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
aa2003ceda41e21d752a9bb68872014e1246eeb0
2,997
h
C
System/Library/PrivateFrameworks/SMBSearch.framework/rowVariant.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/SMBSearch.framework/rowVariant.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/SMBSearch.framework/rowVariant.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:22:52 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/SMBSearch.framework/SMBSearch * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <SMBSearch/SMBSearch-Structs.h> @class NSString, NSMutableArray; @interface rowVariant : NSObject { unsigned char _reserved1; short _vType; unsigned _reserved2; unsigned _uint4Val; int _int4Val; unsigned long long _uint64Val; NSString* _strValue; NSMutableArray* _vector; unsigned long long _vectorCount; timespec _timeSpec; } @property (assign) short vType; //@synthesize vType=_vType - In the implementation block @property (assign) unsigned char reserved1; //@synthesize reserved1=_reserved1 - In the implementation block @property (assign) unsigned reserved2; //@synthesize reserved2=_reserved2 - In the implementation block @property (assign) unsigned long long uint64Val; //@synthesize uint64Val=_uint64Val - In the implementation block @property (assign) timespec timeSpec; //@synthesize timeSpec=_timeSpec - In the implementation block @property (assign) unsigned uint4Val; //@synthesize uint4Val=_uint4Val - In the implementation block @property (assign) int int4Val; //@synthesize int4Val=_int4Val - In the implementation block @property (retain) NSString * strValue; //@synthesize strValue=_strValue - In the implementation block @property (retain) NSMutableArray * vector; //@synthesize vector=_vector - In the implementation block @property (assign) unsigned long long vectorCount; //@synthesize vectorCount=_vectorCount - In the implementation block -(id)init; -(unsigned)reserved2; -(unsigned long long)vectorCount; -(NSMutableArray *)vector; -(void)setTimeSpec:(timespec)arg1 ; -(timespec)timeSpec; -(short)vType; -(void)setReserved2:(unsigned)arg1 ; -(int)decodeBuffer:(id)arg1 BaseOffset:(unsigned)arg2 RowStart:(unsigned)arg3 ValueOffset:(unsigned)arg4 ValueLen:(unsigned)arg5 Use64bit:(BOOL)arg6 ; -(void)setVType:(short)arg1 ; -(int)utf16StrLen:(id)arg1 Offset:(unsigned long long)arg2 Result:(unsigned*)arg3 ; -(unsigned char)reserved1; -(void)setReserved1:(unsigned char)arg1 ; -(unsigned long long)uint64Val; -(void)setUint64Val:(unsigned long long)arg1 ; -(unsigned)uint4Val; -(void)setUint4Val:(unsigned)arg1 ; -(int)int4Val; -(void)setInt4Val:(int)arg1 ; -(NSString *)strValue; -(void)setStrValue:(NSString *)arg1 ; -(void)setVector:(NSMutableArray *)arg1 ; -(void)setVectorCount:(unsigned long long)arg1 ; @end
47.571429
150
0.681682
[ "vector" ]
aa232c28f0d2c9fa1bdd65cbe2d60f33b3b8238e
12,791
h
C
sourceCode/fairport/branch/nikkul/pstsdk/ltp/nameid.h
enrondata/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
6
2019-07-11T23:24:55.000Z
2021-08-03T16:31:12.000Z
sourceCode/fairport/trunk/pstsdk/ltp/nameid.h
Lingchar/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
null
null
null
sourceCode/fairport/trunk/pstsdk/ltp/nameid.h
Lingchar/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
4
2019-04-17T07:08:30.000Z
2020-10-12T22:35:19.000Z
//! \file //! \brief Named Property Lookup Map implementation //! \author Terry Mahaffey //! \ingroup ltp #ifndef PSTSDK_LTP_NAMEID_H #define PSTSDK_LTP_NAMEID_H #include <string> #include <algorithm> #include "pstsdk/util/primitives.h" #include "pstsdk/ndb/database_iface.h" #include "pstsdk/ltp/propbag.h" namespace pstsdk { //! \defgroup ltp_namedproprelated Named Properties //! \ingroup ltp //! \brief A named property //! //! The equivalent of a MAPI named property. This is one half of the named //! property/prop id mapping. This is used as both a key and value type, //! depending on which way in the named property mapping you're going. //! \ingroup ltp_namedproprelated class named_prop { public: //! \brief Construct a named prop from a guid and an id //! \param[in] g The GUID which this named prop is a member //! \param[in] id The numerical id for this property named_prop(const guid& g, long id) : m_guid(g), m_is_string(false), m_id(id) { } //! \brief Construct a named prop from a guid and a string //! \param[in] g The GUID which this named prop is a member //! \param[in] name The string name for this property named_prop(const guid& g, const std::wstring& name) : m_guid(g), m_is_string(true), m_name(name) { } //! \brief Get the namespace GUID of which this named prop is a member //! \returns The GUID for the namespace this named property is in const guid& get_guid() const { return m_guid; } //! \brief Return true if this is a string named prop //! \returns true if this is a string named prop bool is_string() const { return m_is_string; } //! \brief Get the numerical id of this property //! \pre is_string() == false //! \returns The numerical id of this named prop long get_id() const { return m_id; } //! \brief Get the name of this property //! \pre is_string() == true //! \returns The name of this property const std::wstring& get_name() const { return m_name; } private: guid m_guid; //!< The namespace GUID this property is a member of bool m_is_string; //!< True if this is a string named prop long m_id; //!< The id of this property std::wstring m_name; //!< The name of this property }; //! \brief A named property map abstraction //! //! This class abstractions away the logic of doing named property lookups //! in a message store. //! //! To use this class, one just constructs it with a store pointer //! and calls the various lookup overloads as needed. //! \sa [MS-PST] 2.4.7 //! \ingroup ltp_namedproprelated class name_id_map : private boost::noncopyable { public: //! \brief Construct a name_id_map for the given store //! //! This will open the name_id_map node for the store //! \param db The store to get the named property mapping for name_id_map(const shared_db_ptr& db) : m_bag(db->lookup_node(nid_name_id_map)), m_buckets(m_bag.read_prop<slong>(0x1)), m_entry_stream(m_bag.open_prop_stream(0x3)), m_guid_stream(m_bag.open_prop_stream(0x2)), m_string_stream(m_bag.open_prop_stream(0x4)) { } //! \brief Query if a given named prop exists //! \param[in] g The namespace guid for the named prop //! \param[in] name The name of the named prop //! \returns true If the named property has a prop_id mapped bool name_exists(const guid& g, const std::wstring& name) const { return named_prop_exists(named_prop(g, name)); } //! \brief Query if a given named prop exists //! \param[in] g The namespace guid for the named prop //! \param[in] id The name of the named prop //! \returns true If the named property has a prop_id mapped bool id_exists(const guid& g, long id) const { return named_prop_exists(named_prop(g, id)); } //! \brief Query if a given named prop exists //! \param[in] p A constructed named_prop object //! \returns true If the named property has a prop_id mapped bool named_prop_exists(const named_prop& p) const; //! \brief Query if a given prop_id has a named_prop mapped to it //! \param[in] id The prop_id to check //! \returns true If the prop_id has a named_prop mapped bool prop_id_exists(prop_id id) const; //! \brief Get the total count of named property mappings in this store //! \returns The count of named property mappings in this store size_t get_prop_count() const; //! \brief Get all of the prop_ids which have a named_prop mapping in this store //! \returns a vector of prop_ids std::vector<prop_id> get_prop_list() const; //! \brief Get the associated prop_id of the named property //! \throws key_not_found<named_prop> If the named prop doesn't have a prop_id mapping //! \param[in] g The namespace guid for the named prop //! \param[in] name The name of the named prop //! \returns The mapped prop_id of this named property prop_id lookup(const guid& g, const std::wstring& name) const { return lookup(named_prop(g, name)); } //! \brief Get the associated prop_id of the named property //! \throws key_not_found<named_prop> If the named prop doesn't have a prop_id mapping //! \param[in] g The namespace guid for the named prop //! \param[in] id The name of the named prop //! \returns The mapped prop_id of this named property prop_id lookup(const guid& g, long id) const { return lookup(named_prop(g, id)); } //! \brief Get the associated prop_id of the named property //! \throws key_not_found<named_prop> If the named prop doesn't have a prop_id mapping //! \param[in] p A constructed named_prop object //! \returns The mapped prop_id of this named property prop_id lookup(const named_prop& p) const; //! \brief Get the associated named_prop of this prop_id //! \throws key_not_found<prop_id> If the prop_id doesn't have a named_prop mapping //! \param[in] id The prop id to lookup //! \returns The associated named_prop object named_prop lookup(prop_id id) const; private: // helper functions named_prop construct(const disk::nameid& entry) const; named_prop construct(ulong index) const; //! \brief Given a guid index into the GUID stream, return the namespace GUID //! \sa [MS-PST] 2.4.7.1/wGuid //! \param[in] guid_index The index into the guid stream //! \returns The namespace GUID guid read_guid(ushort guid_index) const; ushort get_guid_index(const guid& g) const; std::wstring read_wstring(ulong string_offset) const; ulong compute_hash_base(const named_prop& n) const; ulong compute_hash_value(ushort guid_index, const named_prop& n) const { return (n.is_string() ? ((guid_index << 1) | 1) : (guid_index << 1)) ^ compute_hash_base(n); } prop_id get_bucket_prop(ulong hash_value) const { return static_cast<prop_id>((hash_value % m_buckets) + 0x1000); } property_bag m_bag; //!< The property bag backing the named prop map ulong m_buckets; //!< The number of buckets in the property bag, [NS-PST] 2.4.7.5 mutable prop_stream m_entry_stream; //!< The entry stream, [MS-PST] 2.4.7.3 mutable prop_stream m_guid_stream; //!< The guid stream, [MS-PST] 2.4.7.2 mutable prop_stream m_string_stream; //!< The string stream, [MS-PST] 2.4.7.4 }; inline pstsdk::named_prop pstsdk::name_id_map::construct(const disk::nameid& entry) const { if(nameid_is_string(entry)) return named_prop(read_guid(disk::nameid_get_guid_index(entry)), read_wstring(entry.string_offset)); else return named_prop(read_guid(disk::nameid_get_guid_index(entry)), entry.id); } inline pstsdk::named_prop pstsdk::name_id_map::construct(ulong index) const { disk::nameid entry; m_entry_stream.seekg(index * sizeof(disk::nameid), std::ios_base::beg); m_entry_stream.read((char*)&entry, sizeof(entry)); return construct(entry); } inline pstsdk::guid pstsdk::name_id_map::read_guid(ushort guid_index) const { if(guid_index == 0) return ps_none; if(guid_index == 1) return ps_mapi; if(guid_index == 2) return ps_public_strings; guid g; m_guid_stream.seekg((guid_index-3) * sizeof(guid), std::ios_base::beg); m_guid_stream.read((char*)&g, sizeof(g)); return g; } inline pstsdk::ushort pstsdk::name_id_map::get_guid_index(const guid& g) const { if(memcmp(&g, &ps_none, sizeof(g)) == 0) return 0; if(memcmp(&g, &ps_mapi, sizeof(g)) == 0) return 1; if(memcmp(&g, &ps_public_strings, sizeof(g)) == 0) return 2; guid g_disk; ushort num = 0; m_guid_stream.seekg(0, std::ios_base::beg); while(m_guid_stream.read((char*)&g_disk, sizeof(g_disk))) { if(memcmp(&g, &g_disk, sizeof(g)) == 0) return num + 3; ++num; } // didn't find it m_guid_stream.clear(); throw key_not_found<guid>(g); } inline std::wstring pstsdk::name_id_map::read_wstring(ulong string_offset) const { m_string_stream.seekg(string_offset, std::ios_base::beg); ulong size; m_string_stream.read((char*)&size, sizeof(size)); std::vector<byte> buffer(size); m_string_stream.read(reinterpret_cast<char *>(&buffer[0]), size); return bytes_to_wstring(buffer); } inline pstsdk::ulong pstsdk::name_id_map::compute_hash_base(const named_prop& n) const { if(n.is_string()) { std::vector<byte> bytes(wstring_to_bytes(n.get_name())); return disk::compute_crc(&bytes[0], bytes.size()); } else { return n.get_id(); } } inline bool pstsdk::name_id_map::named_prop_exists(const named_prop& p) const { try { lookup(p); return true; } catch(std::exception&) { return false; } } inline bool pstsdk::name_id_map::prop_id_exists(prop_id id) const { if(id >= 0x8000) return static_cast<size_t>((id - 0x8000)) < get_prop_count(); // id < 0x8000 is a ps_mapi prop return true; } inline std::vector<prop_id> pstsdk::name_id_map::get_prop_list() const { disk::nameid entry; std::vector<prop_id> props; m_entry_stream.seekg(0, std::ios_base::beg); while(m_entry_stream.read((char*)&entry, sizeof(entry)) != 0) props.push_back(nameid_get_prop_index(entry) + 0x8000); m_entry_stream.clear(); return props; } inline size_t pstsdk::name_id_map::get_prop_count() const { m_entry_stream.seekg(0, std::ios_base::end); return static_cast<size_t>(m_entry_stream.tellg()) / sizeof(disk::nameid); } inline pstsdk::prop_id pstsdk::name_id_map::lookup(const named_prop& p) const { ushort guid_index; try { guid_index = get_guid_index(p.get_guid()); } catch(key_not_found<guid>&) { throw key_not_found<named_prop>(p); } // special handling of ps_mapi if(guid_index == 1) { if(p.is_string()) throw key_not_found<named_prop>(p); if(p.get_id() >= 0x8000) throw key_not_found<named_prop>(p); return static_cast<prop_id>(p.get_id()); } ulong hash_value = compute_hash_value(guid_index, p); ulong hash_base = compute_hash_base(p); if(!m_bag.prop_exists(get_bucket_prop(hash_value))) throw key_not_found<named_prop>(p); prop_stream bucket(const_cast<name_id_map*>(this)->m_bag.open_prop_stream(get_bucket_prop(hash_value))); disk::nameid_hash_entry entry; while(bucket.read((char*)&entry, sizeof(entry)) != 0) { if( (entry.hash_base == hash_base) && (disk::nameid_is_string(entry) == p.is_string()) && (disk::nameid_get_guid_index(entry) == guid_index) ) { // just double check the string.. if(p.is_string()) { if(construct(disk::nameid_get_prop_index(entry)).get_name() != p.get_name()) continue; } // found it! return disk::nameid_get_prop_index(entry) + 0x8000; } } throw key_not_found<named_prop>(p); } inline pstsdk::named_prop pstsdk::name_id_map::lookup(prop_id id) const { if(id < 0x8000) return named_prop(ps_mapi, id); ulong index = id - 0x8000; if(index > get_prop_count()) throw key_not_found<prop_id>(id); return construct(index); } } // end namespace pstsdk #endif
36.235127
229
0.647408
[ "object", "vector" ]
aa359ad1196f2a9b69f87ecf9ffcdf9f3f6b33bc
6,751
h
C
arm_compute/core/utils/helpers/tensor_transform.h
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
18
2019-09-05T01:25:16.000Z
2021-10-12T06:37:57.000Z
arm_compute/core/utils/helpers/tensor_transform.h
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
10
2019-11-25T11:09:08.000Z
2021-12-20T12:56:32.000Z
arm_compute/core/utils/helpers/tensor_transform.h
tklebanoff/ComputeLibrary
d6c1eade8c36154ebfd2b61141f045fbc5112ea2
[ "MIT" ]
9
2019-09-05T04:46:59.000Z
2021-10-12T06:33:08.000Z
/* * Copyright (c) 2018 ARM Limited. * * SPDX-License-Identifier: MIT * * 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 __ARM_COMPUTE_UTILS_HELPERS_TENSOR_TRANSFORM_H__ #define __ARM_COMPUTE_UTILS_HELPERS_TENSOR_TRANSFORM_H__ #include "arm_compute/core/Types.h" namespace arm_compute { namespace helpers { namespace tensor_transform { /** Computes stride of a given index * * @param[in] index Index of tensor to calculate absolute start position * @param[in] strides Slice strides * * @return Stride at a given index */ int calculate_stride_on_index(int index, Coordinates strides); /** Computes absolute start position of a given index for a strided slice operation * * @param[in] input_shape Input tensor shape * @param[in] index Index of tensor to calculate absolute start position * @param[in] starts Start coordinates * @param[in] strides Slice strides * @param[in] begin_mask (Optional) If the ith bit of begin_mask is set, starts[i] is ignored and * the fullest possible range in that dimension is used instead. * * @return Absolute start position of a given index */ int calculate_start_on_index(TensorShape input_shape, int index, Coordinates starts, Coordinates strides, int32_t begin_mask); /** Returns the absolute end position of a given index for a strided slice operation * * @param[in] input_shape Input tensor shape * @param[in] index Index of tensor to calculate absolute start position * @param[in] start_on_index Absolute start coordinate for given index * @param[in] ends End coordinates * @param[in] strides Slice strides * @param[in] end_mask (Optional) If the ith bit of end_mask is set, end[i] is ignored and * the fullest possible range in that dimension is used instead. * @param[in] shrink_axis_mask (Optional) If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks the dimensionality by 1. * A slice of size 1 starting from starts[i] in the dimension must be preserved. * * @return Absolute end position of a given index */ int calculate_end_on_index(TensorShape input_shape, int index, int start_on_index, Coordinates ends, Coordinates strides, int32_t end_mask = 0, int32_t shrink_axis_mask = 0); /** Calculate start, end and stride coordinates for a strided slice * * @param[in] input_shape Input tensor shape * @param[in] starts Start coordinates * @param[in] ends End coordinates * @param[in] strides Slice strides * @param[in] begin_mask (Optional) If the ith bit of begin_mask is set, starts[i] is ignored and * the fullest possible range in that dimension is used instead. * @param[in] end_mask (Optional) If the ith bit of end_mask is set, end[i] is ignored and * the fullest possible range in that dimension is used instead. * @param[in] shrink_axis_mask (Optional) If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks the dimensionality by 1. * A slice of size 1 starting from starts[i] in the dimension must be preserved. * * @return A tuple with <Start,End,Strides> */ std::tuple<Coordinates, Coordinates, Coordinates> calculate_strided_slice_coords(TensorShape input_shape, Coordinates starts, Coordinates ends, Coordinates strides, int32_t begin_mask = 0, int32_t end_mask = 0, int32_t shrink_axis_mask = 0); /** Computes output shape of strided slice * * @warning Starts and ends must be non-negative * @warning Starts, ends and final strides should have the same dimensions as the input shape * * @param[in] input_shape Input tensor shape * @param[in] starts Absolute start coordinates * @param[in] ends Absolute end coordinates * @param[in] strides Slice strides * @param[in] begin_mask (Optional) If the ith bit of begin_mask is set, starts[i] is ignored and * the fullest possible range in that dimension is used instead. * @param[in] end_mask (Optional) If the ith bit of end_mask is set, end[i] is ignored and * the fullest possible range in that dimension is used instead. * @param[in] shrink_axis_mask (Optional) If the ith bit of shrink_axis_mask is set, it implies that the ith specification shrinks the dimensionality by 1. * A slice of size 1 starting from starts[i] in the dimension must be preserved. * @param[in] return_unshrinked (Optional) Returns un-shrinked shape * * @return The output tensor shape */ TensorShape compute_strided_slice_output_shape(TensorShape input_shape, Coordinates starts, Coordinates ends, Coordinates strides, int32_t begin_mask = 0, int32_t end_mask = 0, int32_t shrink_axis_mask = 0, bool return_unshrinked = false); /** Constructs end mask in case we want to perform a slice operation using the strided slice interface * * @note Ends are inclusive in slice operations that is why construction an end mask is needed * * @param[in] ends End coordinates * * @return End mask */ int32_t construct_slice_end_mask(Coordinates ends); } // namespace tensor_tranform } // namespace helpers } // namespace arm_compute #endif /* __ARM_COMPUTE_UTILS_HELPERS_TENSOR_TRANSFORM_H__ */
52.333333
157
0.688935
[ "shape" ]
aa362b4f5f7f6a821fedbcfb3069a1604885ee51
3,311
h
C
engine/Dalbaragi/runtime/p_scene.h
SausageTaste/Little-Ruler
f6fb2f28948519981e063a33e978b2f8310d8181
[ "MIT" ]
24
2019-05-25T07:43:09.000Z
2022-03-16T17:37:32.000Z
engine/Dalbaragi/runtime/p_scene.h
SausageTaste/Little-Ruler
f6fb2f28948519981e063a33e978b2f8310d8181
[ "MIT" ]
5
2019-10-14T08:57:55.000Z
2020-07-28T14:52:12.000Z
engine/Dalbaragi/runtime/p_scene.h
SausageTaste/Little-Ruler
f6fb2f28948519981e063a33e978b2f8310d8181
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <list> #include <entt/entity/registry.hpp> #include <d_phyworld.h> #include "p_uniloc.h" #include "u_loadinfo.h" #include "p_resource.h" #include "p_light.h" namespace dal { class IEntityController { public: virtual ~IEntityController(void) = default; virtual void apply(const entt::entity entity, entt::registry& reg) = 0; }; namespace cpnt { struct EntityCtrl { std::shared_ptr<IEntityController> m_ctrler; }; } } namespace dal { class LevelData { public: struct ChunkData { std::string m_name; AABB m_aabb; glm::vec3 m_offsetPos{ 0 }; bool m_active = false; }; private: std::vector<ChunkData> m_chunks; std::string m_respath; public: ChunkData& at(const size_t index) { return this->m_chunks.at(index); } ChunkData& newChunk(void); void clear(void); size_t size(void) const; void reserve(const size_t s); const std::string& respath(void) const { return this->m_respath; } void setRespath(const std::string& respath); }; class SceneGraph { public: struct CameraProp { float m_horizontal = 0, m_vertical = 0; }; private: struct MapChunkPack { MapChunk2 m_map; const LevelData::ChunkData* m_info = nullptr; }; //////// Attribs //////// private: ResourceMaster& m_resMas; PhysicsWorld& m_phyworld; public: LevelData m_activeLevel; std::list<MapChunkPack> m_mapChunks; std::vector<DirectionalLight> m_dlights; entt::registry m_entities; // For player entt::entity m_player; FocusCamera m_playerCam; CameraProp m_playerCamInfo; dal::Transform m_playerLastTrans; //////// Methods //////// public: SceneGraph(ResourceMaster& resMas, PhysicsWorld& phyworld, const unsigned int winWidth, const unsigned int winHeight); void update(const float deltaTime); entt::entity addObj_static(const char* const resid); void render_static(const UniRender_Static& uniloc); void render_animated(const UniRender_Animated& uniloc); void render_staticDepth(const UniRender_StaticDepth& uniloc); void render_animatedDepth(const UniRender_AnimatedDepth& uniloc); void render_staticOnWater(const UniRender_StaticOnWater& uniloc); void render_animatedOnWater(const UniRender_AnimatedOnWater& uniloc); void render_staticOnEnvmap(const UniRender_Static& uniloc); void sendDlightUniform(const UniInterf_Lighting& uniloc); std::optional<RayCastingResult> doRayCasting(const Segment& ray); auto findClosestEnv(const glm::vec3& pos) const -> const dal::EnvMap*; auto findClosestMapChunk(const glm::vec3& pos) const -> const dal::MapChunk2*; void onResize(const unsigned int width, const unsigned int height); private: void openLevel(const char* const respath); void openChunk(const char* const respath, const LevelData::ChunkData& info); }; }
23.992754
126
0.628209
[ "vector", "transform" ]
aa37051681458c76729cdfb5b2d0e24d199fd6c2
23,252
h
C
include/bpf/libbpf.h
dahavey/ebpf-for-windows
865e503a400b796c172a567d12f1eeafa0f3a26b
[ "MIT" ]
null
null
null
include/bpf/libbpf.h
dahavey/ebpf-for-windows
865e503a400b796c172a567d12f1eeafa0f3a26b
[ "MIT" ]
1
2022-03-26T16:17:41.000Z
2022-03-26T16:17:41.000Z
include/bpf/libbpf.h
dahavey/ebpf-for-windows
865e503a400b796c172a567d12f1eeafa0f3a26b
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation // SPDX-License-Identifier: MIT #ifdef __doxygen /** * @name Link-related functions * @{ */ /** @brief Clean up a link. * * @details Unless bpf_link__disconnect was called first, * this API detaches the link. Either way, it then closes * the link fd and frees the memory for the link. * * @param[in] link Link to destroy. * * @sa bpf_link_detach * @sa ebpf_link_close */ int bpf_link__destroy(struct bpf_link* link); /** @brief Release ownership of a link so that it is * not detached when destroyed. * * @param[in] link Link to disconnect. * * @sa bpf_link__destroy */ void bpf_link__disconnect(struct bpf_link* link); /** * @brief Get a file descriptor that refers to a link. * * @param[in] link Link to get a file descriptor for. * * @returns File descriptor that refers to the link. */ int bpf_link__fd(const struct bpf_link* link); /** * @brief Pin a link to a specified path. * * @param[in] link Link to pin. * @param[in] path Path to pin the link to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY A pin path was previously specified. * @exception EEXIST Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_link__unpin */ int bpf_link__pin(struct bpf_link* link, const char* path); /** * @brief Unpin a link. * * @param[in] link Link to unpin. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * @exception ENOENT The link was not pinned. * * @sa bpf_link__pin */ int bpf_link__unpin(struct bpf_link* link); /** @} */ /** * @name Map-related functions * @{ */ /** * @brief Get a file descriptor that refers to a map. * * @param[in] map Map to get a file descriptor for. * * @returns File descriptor that refers to the map. */ int bpf_map__fd(const struct bpf_map* map); /** * @brief Determine whether a map is pinned. * * @param[in] map Map to check. * * @retval true The map is pinned. * @retval false The map is not pinned. * * @sa bpf_map__pin * @sa bpf_object__pin * @sa bpf_object__pin_maps */ bool bpf_map__is_pinned(const struct bpf_map* map); /** * @brief Get the size of keys in a given map. * * @param[in] map Map to check. * * @returns The size in bytes of keys in the map. */ __u32 bpf_map__key_size(const struct bpf_map* map); /** * @brief Get the maximum number of entries allowed in a given map. * * @param[in] map Map to check. * * @returns The maximum number of entries allowed. */ __u32 bpf_map__max_entries(const struct bpf_map* map); /** * @brief Get the name of an eBPF map. * * @param[in] map The map to check. * * @returns The name of the map, or NULL if none. */ const char* bpf_map__name(const struct bpf_map* map); /** * @brief Get the next map for a given eBPF object. * * @param[in] map Previous map. * @param[in] obj Object with maps. * * @returns Next map, or NULL if none. * * @sa bpf_map__prev */ struct bpf_map* bpf_map__next(const struct bpf_map* map, const struct bpf_object* obj); /** * @brief Pin a map to a specified path. * * @param[in] map Map to pin. * @param[in] path Path to pin the map to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY A pin path was previously specified. * @exception EEXIST Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_map_unpin * @sa bpf_object__pin_maps */ int bpf_map__pin(struct bpf_map* map, const char* path); /** * @brief Get the previous map for a given eBPF object. * * @param[in] map Next map. * @param[in] obj Object with maps. * * @returns Previous map, or NULL if none. * * @sa bpf_map__next */ struct bpf_map* bpf_map__prev(const struct bpf_map* map, const struct bpf_object* obj); /** * @brief Get the type of a map. * * @param[in] map Map to check. * * @returns The map type. */ enum bpf_map_type bpf_map__type(const struct bpf_map* map); /** * @brief Unpin a map. * * @param[in] map Map to unpin. * @param[in] path Path from which to unpin the map. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * @exception ENOENT The map was not pinned. * * @sa bpf_map_pin * @sa bpf_object__unpin_maps */ int bpf_map__unpin(struct bpf_map* map, const char* path); /** * @brief Get the size of values in a given map. * * @param[in] map Map to check. * * @returns The size in bytes of values in the map. */ __u32 bpf_map__value_size(const struct bpf_map* map); /** @} */ /** * @name Object-related functions * @{ */ /** * @brief Close an eBPF object. * * @param[in] object The object to close. * * @sa bpf_prog_load */ void bpf_object__close(struct bpf_object* object); /** * @brief Find a map with a given name among maps associated with an eBPF object. * * @param[in] obj The object to check. * @param[in] name The name to look for. * * @returns The map found, or NULL if none. */ struct bpf_map* bpf_object__find_map_by_name(const struct bpf_object* obj, const char* name); /** * @brief Find a map with a given name among maps associated with an eBPF object. * * @param[in] obj The object to check. * @param[in] name The name to look for. * * @returns A file descriptor referring to the map found, or a negative value if none. * * @sa bpf_map__fd */ int bpf_object__find_map_fd_by_name(const struct bpf_object* obj, const char* name); /** * @brief Find a program with a given name among programs associated with an eBPF object. * * @param[in] obj The object to check. * @param[in] name The name to look for. * * @returns A file descriptor referring to the program found, or a negative value if none. * * @sa bpf_program__name */ struct bpf_program* bpf_object__find_program_by_name(const struct bpf_object* obj, const char* name); /** * @brief Load all the programs in a given object. * * @param[in] obj Object from which to load programs. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_object__load_xattr * @sa bpf_object__open * @sa bpf_object__unload * @sa bpf_prog_load */ int bpf_object__load(struct bpf_object* obj); /** * @brief Load all the programs in a given object. * * @param[in] attr Structure with load attributes. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_object__open * @sa bpf_object__load_xattr * @sa bpf_prog_load */ int bpf_object__load_xattr(struct bpf_object_load_attr* attr); /** * @brief Get the name of an eBPF object. * * @param[in] obj The object to check. * * @returns The name of the object, or NULL if none. */ const char* bpf_object__name(const struct bpf_object* obj); /** * @brief Get the next eBPF object opened by the calling process. * * @param[in] prev Previous object, or NULL to get the first object. * * @returns Next object, or NULL if none. */ struct bpf_object* bpf_object__next(struct bpf_object* prev); /** * @brief Open a file without loading the programs. * * @param[in] path File name to open. * @param[opts] opts Options to use when opening the object. * * @returns Pointer to an eBPF object, or NULL on failure. */ struct bpf_object* bpf_object__open_file(const char* path, const struct bpf_object_open_opts* opts); /** * @brief Pin an eBPF object to a specified path. * * @param[in] object Object to pin. * @param[in] path Path to pin the object to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_object__pin_maps * @sa bpf_object__pin_programs * @sa bpf_object__unpin_maps * @sa bpf_object__unpin_programs */ int bpf_object__pin(struct bpf_object* object, const char* path); /** * @brief Pin all maps associated with an eBPF object to a specified path. * * @param[in] obj Object to pin maps of. * @param[in] path Path to pin the maps to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_map__pin * @sa bpf_object__pin * @sa bpf_object__unpin_maps */ int bpf_object__pin_maps(struct bpf_object* obj, const char* path); /** * @brief Pin all programs associated with an eBPF object to a specified path. * * @param[in] obj Object to pin programs of. * @param[in] path Path to pin the programs to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_program__pin * @sa bpf_object__pin * @sa bpf_object__unpin_programs */ int bpf_object__pin_programs(struct bpf_object* obj, const char* path); /** * @brief Unload all the programs in a given object. * * @param[in] obj Object with programs to be unloaded. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @sa bpf_object__load * @sa bpf_object__load_xattr * @sa bpf_prog_load */ int bpf_object__unload(struct bpf_object* obj); /** * @brief Unpin all maps associated with an eBPF object from a specified path. * * @param[in] obj Object to unpin maps of. * @param[in] path Path from which to unpin the maps. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * * @sa bpf_map__upnin * @sa bpf_object__pin_maps * @sa bpf_object__unpin */ int bpf_object__unpin_maps(struct bpf_object* obj, const char* path); /** * @brief Unpin all programs associated with an eBPF object from a specified path. * * @param[in] obj Object to unpin programs of. * @param[in] path Path from which to unpin the programs. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * * @sa bpf_program__unpin * @sa bpf_object__pin_mprograms * @sa bpf_object__unpin */ int bpf_object__unpin_programs(struct bpf_object* obj, const char* path); /** @} */ /** * @name Program-related functions * @{ */ /* * @brief Load (but do not attach) an eBPF program from eBPF instructions * supplied by the caller. * * @param[in] type Program type to use. * @param[in] insns Array of eBPF instructions. * @param[in] insns_cnt Number of eBPF instructions in the array. * @param[in] license License. * @param[in] kern_version Kernel version. * @param[out] log_buf Buffer in which to write any log messages. * @param[in] log_buf_size Size in bytes of the log buffer. * * @returns File descriptor that refers to the program, or <0 on error. * The caller should call _close() on the fd to close this when done. * * @exception EACCES The program failed verification. * @exception EINVAL One or more parameters are incorrect. * @exception ENOMEM Out of memory. * * @sa bpf_prog_load * @sa bpf_load_program_xattr */ int bpf_load_program( enum bpf_prog_type type, const struct bpf_insn* insns, size_t insns_cnt, const char* license, __u32 kern_version, char* log_buf, size_t log_buf_sz); /* * @brief Load (but do not attach) an eBPF program from eBPF instructions * supplied by the caller. * * @param[in] load_attr Parameters to use to load the eBPF program. * @param[out] log_buf Buffer in which to write any log messages. * @param[in] log_buf_size Size in bytes of the log buffer. * * @returns File descriptor that refers to the program, or <0 on error. * The caller should call _close() on the fd to close this when done. * * @exception EACCES The program failed verification. * @exception EINVAL One or more parameters are incorrect. * @exception ENOMEM Out of memory. * * @sa bpf_prog_load * @sa bpf_load_program */ int bpf_load_program_xattr(const struct bpf_load_program_attr* load_attr, char* log_buf, size_t log_buf_sz); /** * @brief Load (but do not attach) eBPF maps and programs from an ELF file. * * @param[in] file Path name to an ELF file. * @param[in] type Program type to use for loading eBPF programs. If BPF_PROG_TYPE_UNKNOWN, * the program type is derived from the section prefix in the ELF file. * @param[out] pobj Pointer to where to store the eBPF object loaded. The caller * is expected to call bpf_object__close() to free the object. * @param[out] prog_fd Returns a file descriptor for the first program. * The caller should not call _close() on the fd, but should instead use * bpf_object__close() on the object returned. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EACCES The program failed verification. * @exception EINVAL One or more parameters are incorrect. * @exception ENOMEM Out of memory. * * @sa bpf_load_program * @sa bpf_load_program_xattr * @sa bpf_object__close * @sa bpf_program__attach */ int bpf_prog_load(const char* file, enum bpf_prog_type type, struct bpf_object** pobj, int* prog_fd); /** * @brief Attach an eBPF program to a hook associated with the program's expected attach type. * * @param[in] prog The program to attach. * * @returns The link created. On error, returns NULL and sets errno. * * @sa bpf_link__destroy * @sa bpf_program__get_expected_attach_type * @sa bpf_program__set_expected_attach_type * @sa ebpf_link_close */ struct bpf_link* bpf_program__attach(const struct bpf_program* prog); /** * @brief Attach an eBPF program to an XDP hook. * * @param[in] prog The program to attach. * @param[in] ifindex The interface index to attach to. * * @returns The link created. On error, returns NULL and sets errno. * * @sa bpf_link__destroy * @sa bpf_program__attach * @sa ebpf_link_close */ struct bpf_link* bpf_program__attach_xdp(struct bpf_program* prog, int ifindex); /** * @brief Attach an eBPF program to an XDP hook. * * @param[in] prog_fd File descriptor of the program to attach. * @param[in] attachable_fd File descriptor corresponding to the attach point. * @param[in] type Attach type. * @param[in] flags Flags (currently 0). * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * */ int bpf_prog_attach(int prog_fd, int attachable_fd, enum bpf_attach_type type, unsigned int flags); /** * @brief Get a file descriptor that refers to a program. * * @param[in] prog Program to get a file descriptor for. * * @returns File descriptor that refers to the program. */ int bpf_program__fd(const struct bpf_program* prog); /** * @brief Get the expected attach type for an eBPF program. * * @param[in] prog Program to check. * * @returns Expected attach type. * * @sa bpf_program__attach * @sa bpf_program__set_expected_attach_type */ enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program* prog); /** * @brief Get the program type for an eBPF program. * * @param[in] prog Program to check. * * @returns Program type. * * @sa bpf_program__get_expected_attach_type */ enum bpf_prog_type bpf_program__get_type(const struct bpf_program* prog); /** * @brief Get the function name of an eBPF program. * * @param[in] prog Program to check. * * @returns The name of the program, which is the name of the main * function called when invoked. * * @sa bpf_object__find_program_by_name */ const char* bpf_program__name(const struct bpf_program* prog); /** * @brief Get the next program for a given eBPF object. * * @param[in] prog Previous program, or NULL to get the first program. * @param[in] obj Object with programs. * * @returns Next program, or NULL if none. * * @sa bpf_program__prev */ struct bpf_program* bpf_program__next(struct bpf_program* prog, const struct bpf_object* obj); /** * @brief Pin a program to a specified path. * * @param[in] prog Program to pin. * @param[in] path Path to pin the program to. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EBUSY A pin path was previously specified. * @exception EEXIST Something is already pinned to the specified path. * @exception EINVAL An invalid argument was provided. * @exception ENOMEM Out of memory. * * @sa bpf_object__pin * @sa bpf_object__pin_programs * @sa bpf_program__unpin */ int bpf_program__pin(struct bpf_program* prog, const char* path); /** * @brief Get the previous eBPF program for a given eBPF object. * * @param[in] prog Next program. * @param[in] obj Object with programs. * * @returns Previous eBPF program, or NULL if none. * * @sa bpf_program__next */ struct bpf_program* bpf_program__prev(struct bpf_program* prog, const struct bpf_object* obj); /** * @brief Gets the ELF section name of an eBPF program, if any. * * @param[in] prog An eBPF program. * * @returns The ELF section name of an eBPF program, or NULL if none. */ const char* bpf_program__section_name(const struct bpf_program* prog); /** * @brief Set the expected attach type for an eBPF program. * * @param[in] prog Program to update. * @param[in] type Attach type to set. * * @sa bpf_program__attach * @sa bpf_program__get_expected_attach_type */ void bpf_program__set_expected_attach_type(struct bpf_program* prog, enum bpf_attach_type type); /** * @brief Set the program type for an eBPF program. * * @param[in] prog Program to update. * @param[in] type Program type to set. * * @sa bpf_program__set_expected_attach_type */ void bpf_program__set_type(struct bpf_program* prog, enum bpf_prog_type type); /** * @brief Unload a program. * * @param[in] prog Program to unload. * * @sa bpf_object__unload * @sa bpf_prog_load */ void bpf_program__unload(struct bpf_program* prog); /** * @brief Unpin a program. * * @param[in] prog Program to unpin. * @param[in] path Path from which to unpin the program. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @exception EINVAL An invalid argument was provided. * @exception ENOENT The program was not pinned. * * @sa bpf_object__unpin_programs * @sa bpf_program__pin */ int bpf_program__unpin(struct bpf_program* prog, const char* path); /** * @brief Attach an XDP program to a given interface. * * @param[in] ifindex The interface index to attach to, or -1 to detach. * @param[in] fd File descriptor of program to attach. * @param[in] flags Flags. Use XDP_FLAGS_REPLACE to replace any program previously attached to * the specified interface index. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @deprecated Use bpf_xdp_attach() instead. * * @sa bpf_program__attach_xdp * @sa bpf_xdp_attach * @sa bpf_xdp_detach */ int bpf_set_link_xdp_fd(int ifindex, int fd, __u32 flags); /** * @brief Attach an XDP program to a given interface. * * @param[in] ifindex The interface index to attach to, or -1 to detach. * @param[in] prog_fd File descriptor of program to attach. * @param[in] flags Flags. Use XDP_FLAGS_REPLACE to replace any program previously attached to * the specified interface index. * @param[in] opts Options (currently unused). * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @sa bpf_program__attach_xdp * @sa bpf_xdp_detach */ int bpf_xdp_attach(int ifindex, int prog_fd, __u32 flags, const struct bpf_xdp_attach_opts* opts); /** * @brief Detach an XDP program from a given interface. * * @param[in] ifindex The interface index to detach from. * @param[in] prog_fd File descriptor of program to detach. * @param[in] flags Flags. Use XDP_FLAGS_REPLACE to detach any program previously attached to * the specified interface index. * @param[in] opts Options (currently unused). * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @sa bpf_link_detach * @sa bpf_program__attach_xdp * @sa bpf_xdp_attach */ int bpf_xdp_detach(int ifindex, __u32 flags, const struct bpf_xdp_attach_opts* opts); /** * @brief Get the XDP program id attached to a given interface index. * * @param[in] ifindex The interface index to query. * @param[in] flags Flags (currently 0). * @param[out] prog_id The ID of the program attached. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. * * @sa bpf_xdp_attach */ int bpf_xdp_query_id(int ifindex, int flags, __u32* prog_id); /** * @brief Get a program type and expected attach type by name. * * @param[in] name Name, as if it were a section name in an ELF file. * @param[out] prog_type Program type. * @param[out] expected_attach_type Expected attach type. * * @retval 0 The operation was successful. * @retval <0 An error occured, and errno was set. */ int libbpf_prog_type_by_name(const char* name, enum bpf_prog_type* prog_type, enum bpf_attach_type* expected_attach_type); /** @} */ /** * @name System-related functions * @{ */ /** * @brief Get a negative error code based on errno and a possibly null pointer. * * @param[in] ptr Pointer that may be NULL. * * @returns Negative error code. */ long libbpf_get_error(const void* ptr); /** * @brief Get the number of processors on the current system. * * @returns Number of processors. */ int libbpf_num_possible_cpus(void); /* Ring buffer APIs */ /** * @brief Creates a new ring buffer manager. * * @param[in] map_fd File descriptor to ring buffer map. * @param[in] sample_cb Pointer to ring buffer notification callback function. * @param[in] ctx Pointer to sample_cb callback function. * @param[in] opts Ring buffer options. * * @returns Pointer to ring buffer manager. */ struct ring_buffer* ring_buffer__new(int map_fd, ring_buffer_sample_fn sample_cb, void* ctx, const struct ring_buffer_opts* opts); /** * @brief Frees a new ring buffer manager. * * @param[in] rb Pointer to ring buffer to be freed. * */ void ring_buffer__free(struct ring_buffer* rb); /** @} */ #else #pragma warning(push) #pragma warning(disable : 4200) // Zero-sized array in struct/union #pragma warning(disable : 4201) // Zero-sized array in struct/union #include "../external/bpftool/libbpf/src/libbpf.h" #pragma warning(pop) #endif
26.096521
118
0.712713
[ "object" ]
aa372436de5795039f07f4dc28afdb7e2b097f81
1,414
h
C
interface/src/ui/overlays/Grid3DOverlay.h
JamesLinus/hifi
7275674d697486a1c0c3eefe5ba702bbd5e2b963
[ "Apache-2.0" ]
1
2019-04-22T09:08:58.000Z
2019-04-22T09:08:58.000Z
interface/src/ui/overlays/Grid3DOverlay.h
JamesLinus/hifi
7275674d697486a1c0c3eefe5ba702bbd5e2b963
[ "Apache-2.0" ]
null
null
null
interface/src/ui/overlays/Grid3DOverlay.h
JamesLinus/hifi
7275674d697486a1c0c3eefe5ba702bbd5e2b963
[ "Apache-2.0" ]
null
null
null
// // Grid3DOverlay.h // interface/src/ui/overlays // // Created by Ryan Huffman on 11/06/14. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_Grid3DOverlay_h #define hifi_Grid3DOverlay_h #include "Planar3DOverlay.h" class Grid3DOverlay : public Planar3DOverlay { Q_OBJECT public: static QString const TYPE; virtual QString getType() const { return TYPE; } Grid3DOverlay(); Grid3DOverlay(const Grid3DOverlay* grid3DOverlay); virtual AABox getBounds() const; virtual void render(RenderArgs* args); virtual const render::ShapeKey getShapeKey() override; void setProperties(const QVariantMap& properties) override; QVariant getProperty(const QString& property) override; virtual Grid3DOverlay* createClone() const; // Grids are UI tools, and may not be intersected (pickable) virtual bool findRayIntersection(const glm::vec3&, const glm::vec3&, float&, BoxFace&, glm::vec3&) { return false; } private: void updateGrid(); bool _followCamera { true }; int _majorGridEvery { 5 }; float _majorGridRowDivisions; float _majorGridColDivisions; float _minorGridEvery { 1.0f }; float _minorGridRowDivisions; float _minorGridColDivisions; }; #endif // hifi_Grid3DOverlay_h
26.185185
120
0.725601
[ "render" ]
aa38a5a64c9c9e2657c7321302a966f74afb54d3
1,560
h
C
include/metaquest/flow-generic.h
jyujin/metaquest
8682e1d7f65abdc2c1a63c406e4e51489581f85e
[ "MIT" ]
null
null
null
include/metaquest/flow-generic.h
jyujin/metaquest
8682e1d7f65abdc2c1a63c406e4e51489581f85e
[ "MIT" ]
null
null
null
include/metaquest/flow-generic.h
jyujin/metaquest
8682e1d7f65abdc2c1a63c406e4e51489581f85e
[ "MIT" ]
null
null
null
/**\file * \brief Generic game flow * * Contains a generic game flow object. * * \copyright * This file is part of the Metaquest project, which is released as open source * under the terms of an MIT/X11-style licence, described in the COPYING file. * * \see Documentation: https://ef.gy/documentation/metaquest * \see Source Code: https://github.com/jyujin/metaquest * \see Licence Terms: https://github.com/jyujin/metaquest/COPYING */ #if !defined(METAQUEST_FLOW_GENERIC_H) #define METAQUEST_FLOW_GENERIC_H namespace metaquest { namespace flow { template <typename interaction, typename logic> class generic { public: generic(void) : interact(), game(interact) {} bool run(void) { while (true) { interact.drawUI(game); switch (game.state()) { case logic::menu: interact.log(game.doMenu()); break; case logic::combat: interact.log(game.doCombat()); break; case logic::victory: interact.log(game.doVictory()); break; case logic::defeat: interact.log(game.doDefeat()); return true; case logic::exit: return true; default: return false; } } return true; } bool load(efgy::json::json json) { game.load(json("game")); interact.load(json("interaction")); return true; } efgy::json::json json(void) const { efgy::json::json rv; rv("game") = game.json(); rv("interaction") = interact.json(); return rv; } interaction interact; logic game; }; } } #endif
21.369863
79
0.630128
[ "object" ]
aa3beaad18654f861bba9ce8d4903e3244da19e9
17,548
c
C
src/dpdk/drivers/raw/skeleton/skeleton_rawdev.c
ajitkhaparde/trex-core
1834ebd49112af0731a819056612dde832f7a94e
[ "Apache-2.0" ]
956
2015-06-24T15:04:55.000Z
2022-03-30T06:25:04.000Z
src/dpdk/drivers/raw/skeleton/skeleton_rawdev.c
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
782
2015-09-20T15:19:00.000Z
2022-03-31T23:52:05.000Z
src/dpdk/drivers/raw/skeleton/skeleton_rawdev.c
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
429
2015-06-27T19:34:21.000Z
2022-03-23T11:02:51.000Z
/* SPDX-License-Identifier: BSD-3-Clause * Copyright 2017 NXP */ #include <assert.h> #include <stdio.h> #include <stdbool.h> #include <errno.h> #include <stdint.h> #include <inttypes.h> #include <string.h> #include <rte_byteorder.h> #include <rte_common.h> #include <rte_debug.h> #include <rte_dev.h> #include <rte_eal.h> #include <rte_kvargs.h> #include <rte_log.h> #include <rte_malloc.h> #include <rte_memory.h> #include <rte_memcpy.h> #include <rte_lcore.h> #include <rte_bus_vdev.h> #include <rte_rawdev.h> #include <rte_rawdev_pmd.h> #include "skeleton_rawdev.h" /* Count of instances */ static uint16_t skeldev_init_once; /**< Rawdev Skeleton dummy driver name */ #define SKELETON_PMD_RAWDEV_NAME rawdev_skeleton struct queue_buffers { void *bufs[SKELETON_QUEUE_MAX_DEPTH]; }; static struct queue_buffers queue_buf[SKELETON_MAX_QUEUES] = {}; static void clear_queue_bufs(int queue_id); static int skeleton_rawdev_info_get(struct rte_rawdev *dev, rte_rawdev_obj_t dev_info, size_t dev_info_size) { struct skeleton_rawdev *skeldev; struct skeleton_rawdev_conf *skeldev_conf; SKELETON_PMD_FUNC_TRACE(); if (!dev_info || dev_info_size != sizeof(*skeldev_conf)) { SKELETON_PMD_ERR("Invalid request"); return -EINVAL; } skeldev = skeleton_rawdev_get_priv(dev); skeldev_conf = dev_info; skeldev_conf->num_queues = skeldev->num_queues; skeldev_conf->capabilities = skeldev->capabilities; skeldev_conf->device_state = skeldev->device_state; skeldev_conf->firmware_state = skeldev->fw.firmware_state; return 0; } static int skeleton_rawdev_configure(const struct rte_rawdev *dev, rte_rawdev_obj_t config, size_t config_size) { struct skeleton_rawdev *skeldev; struct skeleton_rawdev_conf *skeldev_conf; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); if (config == NULL || config_size != sizeof(*skeldev_conf)) { SKELETON_PMD_ERR("Invalid configuration"); return -EINVAL; } skeldev_conf = config; skeldev = skeleton_rawdev_get_priv(dev); if (skeldev_conf->num_queues <= SKELETON_MAX_QUEUES) skeldev->num_queues = skeldev_conf->num_queues; else return -EINVAL; skeldev->capabilities = skeldev_conf->capabilities; skeldev->num_queues = skeldev_conf->num_queues; return 0; } static int skeleton_rawdev_start(struct rte_rawdev *dev) { int ret = 0; struct skeleton_rawdev *skeldev; enum skeleton_firmware_state fw_state; enum skeleton_device_state device_state; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); skeldev = skeleton_rawdev_get_priv(dev); fw_state = skeldev->fw.firmware_state; device_state = skeldev->device_state; if (fw_state == SKELETON_FW_LOADED && device_state == SKELETON_DEV_STOPPED) { skeldev->device_state = SKELETON_DEV_RUNNING; } else { SKELETON_PMD_ERR("Device not ready for starting"); ret = -EINVAL; } return ret; } static void skeleton_rawdev_stop(struct rte_rawdev *dev) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); if (dev) { skeldev = skeleton_rawdev_get_priv(dev); skeldev->device_state = SKELETON_DEV_STOPPED; } } static void reset_queues(struct skeleton_rawdev *skeldev) { int i; for (i = 0; i < SKELETON_MAX_QUEUES; i++) { skeldev->queues[i].depth = SKELETON_QUEUE_DEF_DEPTH; skeldev->queues[i].state = SKELETON_QUEUE_DETACH; } } static void reset_attribute_table(struct skeleton_rawdev *skeldev) { int i; for (i = 0; i < SKELETON_MAX_ATTRIBUTES; i++) { if (skeldev->attr[i].name) { free(skeldev->attr[i].name); skeldev->attr[i].name = NULL; } } } static int skeleton_rawdev_close(struct rte_rawdev *dev) { int ret = 0, i; struct skeleton_rawdev *skeldev; enum skeleton_firmware_state fw_state; enum skeleton_device_state device_state; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); skeldev = skeleton_rawdev_get_priv(dev); fw_state = skeldev->fw.firmware_state; device_state = skeldev->device_state; reset_queues(skeldev); reset_attribute_table(skeldev); switch (fw_state) { case SKELETON_FW_LOADED: if (device_state == SKELETON_DEV_RUNNING) { SKELETON_PMD_ERR("Cannot close running device"); ret = -EINVAL; } else { /* Probably call fw reset here */ skeldev->fw.firmware_state = SKELETON_FW_READY; } break; case SKELETON_FW_READY: SKELETON_PMD_DEBUG("Device already in stopped state"); break; case SKELETON_FW_ERROR: default: SKELETON_PMD_DEBUG("Device in impossible state"); ret = -EINVAL; break; } /* Clear all allocated queues */ for (i = 0; i < SKELETON_MAX_QUEUES; i++) clear_queue_bufs(i); return ret; } static int skeleton_rawdev_reset(struct rte_rawdev *dev) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); skeldev = skeleton_rawdev_get_priv(dev); SKELETON_PMD_DEBUG("Resetting device"); skeldev->fw.firmware_state = SKELETON_FW_READY; return 0; } static int skeleton_rawdev_queue_def_conf(struct rte_rawdev *dev, uint16_t queue_id, rte_rawdev_obj_t queue_conf, size_t conf_size) { struct skeleton_rawdev *skeldev; struct skeleton_rawdev_queue *skelq; SKELETON_PMD_FUNC_TRACE(); if (!dev || !queue_conf || conf_size != sizeof(struct skeleton_rawdev_queue)) return -EINVAL; skeldev = skeleton_rawdev_get_priv(dev); skelq = &skeldev->queues[queue_id]; if (queue_id < SKELETON_MAX_QUEUES) rte_memcpy(queue_conf, skelq, sizeof(struct skeleton_rawdev_queue)); return 0; } static void clear_queue_bufs(int queue_id) { int i; /* Clear buffers for queue_id */ for (i = 0; i < SKELETON_QUEUE_MAX_DEPTH; i++) queue_buf[queue_id].bufs[i] = NULL; } static int skeleton_rawdev_queue_setup(struct rte_rawdev *dev, uint16_t queue_id, rte_rawdev_obj_t queue_conf, size_t conf_size) { int ret = 0; struct skeleton_rawdev *skeldev; struct skeleton_rawdev_queue *q; SKELETON_PMD_FUNC_TRACE(); if (!dev || !queue_conf || conf_size != sizeof(struct skeleton_rawdev_queue)) return -EINVAL; skeldev = skeleton_rawdev_get_priv(dev); q = &skeldev->queues[queue_id]; if (skeldev->num_queues > queue_id && q->depth < SKELETON_QUEUE_MAX_DEPTH) { rte_memcpy(q, queue_conf, sizeof(struct skeleton_rawdev_queue)); clear_queue_bufs(queue_id); } else { SKELETON_PMD_ERR("Invalid queue configuration"); ret = -EINVAL; } return ret; } static int skeleton_rawdev_queue_release(struct rte_rawdev *dev, uint16_t queue_id) { int ret = 0; struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); skeldev = skeleton_rawdev_get_priv(dev); if (skeldev->num_queues > queue_id) { skeldev->queues[queue_id].state = SKELETON_QUEUE_DETACH; skeldev->queues[queue_id].depth = SKELETON_QUEUE_DEF_DEPTH; clear_queue_bufs(queue_id); } else { SKELETON_PMD_ERR("Invalid queue configuration"); ret = -EINVAL; } return ret; } static uint16_t skeleton_rawdev_queue_count(struct rte_rawdev *dev) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); skeldev = skeleton_rawdev_get_priv(dev); return skeldev->num_queues; } static int skeleton_rawdev_get_attr(struct rte_rawdev *dev, const char *attr_name, uint64_t *attr_value) { int i; uint8_t done = 0; struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); if (!dev || !attr_name || !attr_value) { SKELETON_PMD_ERR("Invalid arguments for getting attributes"); return -EINVAL; } skeldev = skeleton_rawdev_get_priv(dev); for (i = 0; i < SKELETON_MAX_ATTRIBUTES; i++) { if (!skeldev->attr[i].name) continue; if (!strncmp(skeldev->attr[i].name, attr_name, SKELETON_ATTRIBUTE_NAME_MAX)) { *attr_value = skeldev->attr[i].value; done = 1; SKELETON_PMD_DEBUG("Attribute (%s) Value (%" PRIu64 ")", attr_name, *attr_value); break; } } if (done) return 0; /* Attribute not found */ return -EINVAL; } static int skeleton_rawdev_set_attr(struct rte_rawdev *dev, const char *attr_name, const uint64_t attr_value) { int i; uint8_t done = 0; struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); if (!dev || !attr_name) { SKELETON_PMD_ERR("Invalid arguments for setting attributes"); return -EINVAL; } skeldev = skeleton_rawdev_get_priv(dev); /* Check if attribute already exists */ for (i = 0; i < SKELETON_MAX_ATTRIBUTES; i++) { if (!skeldev->attr[i].name) break; if (!strncmp(skeldev->attr[i].name, attr_name, SKELETON_ATTRIBUTE_NAME_MAX)) { /* Update value */ skeldev->attr[i].value = attr_value; done = 1; break; } } if (!done) { if (i < (SKELETON_MAX_ATTRIBUTES - 1)) { /* There is still space to insert one more */ skeldev->attr[i].name = strdup(attr_name); if (!skeldev->attr[i].name) return -ENOMEM; skeldev->attr[i].value = attr_value; return 0; } } return -EINVAL; } static int skeleton_rawdev_enqueue_bufs(struct rte_rawdev *dev, struct rte_rawdev_buf **buffers, unsigned int count, rte_rawdev_obj_t context) { unsigned int i; uint16_t q_id; RTE_SET_USED(dev); /* context is essentially the queue_id which is * transferred as opaque object through the library layer. This can * help in complex implementation which require more information than * just an integer - for example, a queue-pair. */ q_id = *((int *)context); for (i = 0; i < count; i++) queue_buf[q_id].bufs[i] = buffers[i]->buf_addr; return i; } static int skeleton_rawdev_dequeue_bufs(struct rte_rawdev *dev, struct rte_rawdev_buf **buffers, unsigned int count, rte_rawdev_obj_t context) { unsigned int i; uint16_t q_id; RTE_SET_USED(dev); /* context is essentially the queue_id which is * transferred as opaque object through the library layer. This can * help in complex implementation which require more information than * just an integer - for example, a queue-pair. */ q_id = *((int *)context); for (i = 0; i < count; i++) buffers[i]->buf_addr = queue_buf[q_id].bufs[i]; return i; } static int skeleton_rawdev_dump(struct rte_rawdev *dev, FILE *f) { RTE_SET_USED(dev); RTE_SET_USED(f); return 0; } static int skeleton_rawdev_firmware_status_get(struct rte_rawdev *dev, rte_rawdev_obj_t status_info) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); skeldev = skeleton_rawdev_get_priv(dev); RTE_FUNC_PTR_OR_ERR_RET(dev, -EINVAL); if (status_info) memcpy(status_info, &skeldev->fw.firmware_state, sizeof(enum skeleton_firmware_state)); return 0; } static int skeleton_rawdev_firmware_version_get( struct rte_rawdev *dev, rte_rawdev_obj_t version_info) { struct skeleton_rawdev *skeldev; struct skeleton_firmware_version_info *vi; SKELETON_PMD_FUNC_TRACE(); skeldev = skeleton_rawdev_get_priv(dev); vi = version_info; vi->major = skeldev->fw.firmware_version.major; vi->minor = skeldev->fw.firmware_version.minor; vi->subrel = skeldev->fw.firmware_version.subrel; return 0; } static int skeleton_rawdev_firmware_load(struct rte_rawdev *dev, rte_rawdev_obj_t firmware_buf) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); skeldev = skeleton_rawdev_get_priv(dev); /* firmware_buf is a mmaped, possibly DMA'able area, buffer. Being * dummy, all this does is check if firmware_buf is not NULL and * sets the state of the firmware. */ if (!firmware_buf) return -EINVAL; skeldev->fw.firmware_state = SKELETON_FW_LOADED; return 0; } static int skeleton_rawdev_firmware_unload(struct rte_rawdev *dev) { struct skeleton_rawdev *skeldev; SKELETON_PMD_FUNC_TRACE(); skeldev = skeleton_rawdev_get_priv(dev); skeldev->fw.firmware_state = SKELETON_FW_READY; return 0; } static const struct rte_rawdev_ops skeleton_rawdev_ops = { .dev_info_get = skeleton_rawdev_info_get, .dev_configure = skeleton_rawdev_configure, .dev_start = skeleton_rawdev_start, .dev_stop = skeleton_rawdev_stop, .dev_close = skeleton_rawdev_close, .dev_reset = skeleton_rawdev_reset, .queue_def_conf = skeleton_rawdev_queue_def_conf, .queue_setup = skeleton_rawdev_queue_setup, .queue_release = skeleton_rawdev_queue_release, .queue_count = skeleton_rawdev_queue_count, .attr_get = skeleton_rawdev_get_attr, .attr_set = skeleton_rawdev_set_attr, .enqueue_bufs = skeleton_rawdev_enqueue_bufs, .dequeue_bufs = skeleton_rawdev_dequeue_bufs, .dump = skeleton_rawdev_dump, .xstats_get = NULL, .xstats_get_names = NULL, .xstats_get_by_name = NULL, .xstats_reset = NULL, .firmware_status_get = skeleton_rawdev_firmware_status_get, .firmware_version_get = skeleton_rawdev_firmware_version_get, .firmware_load = skeleton_rawdev_firmware_load, .firmware_unload = skeleton_rawdev_firmware_unload, .dev_selftest = test_rawdev_skeldev, }; static int skeleton_rawdev_create(const char *name, struct rte_vdev_device *vdev, int socket_id) { int ret = 0, i; struct rte_rawdev *rawdev = NULL; struct skeleton_rawdev *skeldev = NULL; if (!name) { SKELETON_PMD_ERR("Invalid name of the device!"); ret = -EINVAL; goto cleanup; } /* Allocate device structure */ rawdev = rte_rawdev_pmd_allocate(name, sizeof(struct skeleton_rawdev), socket_id); if (rawdev == NULL) { SKELETON_PMD_ERR("Unable to allocate rawdevice"); ret = -EINVAL; goto cleanup; } ret = rawdev->dev_id; /* return the rawdev id of new device */ rawdev->dev_ops = &skeleton_rawdev_ops; rawdev->device = &vdev->device; skeldev = skeleton_rawdev_get_priv(rawdev); skeldev->device_id = SKELETON_DEVICE_ID; skeldev->vendor_id = SKELETON_VENDOR_ID; skeldev->capabilities = SKELETON_DEFAULT_CAPA; memset(&skeldev->fw, 0, sizeof(struct skeleton_firmware)); skeldev->fw.firmware_state = SKELETON_FW_READY; skeldev->fw.firmware_version.major = SKELETON_MAJOR_VER; skeldev->fw.firmware_version.minor = SKELETON_MINOR_VER; skeldev->fw.firmware_version.subrel = SKELETON_SUB_VER; skeldev->device_state = SKELETON_DEV_STOPPED; /* Reset/set to default queue configuration for this device */ for (i = 0; i < SKELETON_MAX_QUEUES; i++) { skeldev->queues[i].state = SKELETON_QUEUE_DETACH; skeldev->queues[i].depth = SKELETON_QUEUE_DEF_DEPTH; } /* Clear all allocated queue buffers */ for (i = 0; i < SKELETON_MAX_QUEUES; i++) clear_queue_bufs(i); return ret; cleanup: if (rawdev) rte_rawdev_pmd_release(rawdev); return ret; } static int skeleton_rawdev_destroy(const char *name) { int ret; struct rte_rawdev *rdev; if (!name) { SKELETON_PMD_ERR("Invalid device name"); return -EINVAL; } rdev = rte_rawdev_pmd_get_named_dev(name); if (!rdev) { SKELETON_PMD_ERR("Invalid device name (%s)", name); return -EINVAL; } /* rte_rawdev_close is called by pmd_release */ ret = rte_rawdev_pmd_release(rdev); if (ret) SKELETON_PMD_DEBUG("Device cleanup failed"); return 0; } static int skeldev_get_selftest(const char *key __rte_unused, const char *value, void *opaque) { int *flag = opaque; *flag = atoi(value); return 0; } static int skeldev_parse_vdev_args(struct rte_vdev_device *vdev) { int selftest = 0; const char *name; const char *params; static const char *const args[] = { SKELETON_SELFTEST_ARG, NULL }; name = rte_vdev_device_name(vdev); params = rte_vdev_device_args(vdev); if (params != NULL && params[0] != '\0') { struct rte_kvargs *kvlist = rte_kvargs_parse(params, args); if (!kvlist) { SKELETON_PMD_INFO( "Ignoring unsupported params supplied '%s'", name); } else { int ret = rte_kvargs_process(kvlist, SKELETON_SELFTEST_ARG, skeldev_get_selftest, &selftest); if (ret != 0 || (selftest < 0 || selftest > 1)) { SKELETON_PMD_ERR("%s: Error in parsing args", name); rte_kvargs_free(kvlist); ret = -1; /* enforce if selftest is invalid */ return ret; } } rte_kvargs_free(kvlist); } return selftest; } static int skeleton_rawdev_probe(struct rte_vdev_device *vdev) { const char *name; int selftest = 0, ret = 0; name = rte_vdev_device_name(vdev); if (name == NULL) return -EINVAL; /* More than one instance is not supported */ if (skeldev_init_once) { SKELETON_PMD_ERR("Multiple instance not supported for %s", name); return -EINVAL; } SKELETON_PMD_INFO("Init %s on NUMA node %d", name, rte_socket_id()); selftest = skeldev_parse_vdev_args(vdev); /* In case of invalid argument, selftest != 1; ignore other values */ ret = skeleton_rawdev_create(name, vdev, rte_socket_id()); if (ret >= 0) { /* In case command line argument for 'selftest' was passed; * if invalid arguments were passed, execution continues but * without selftest. */ if (selftest == 1) test_rawdev_skeldev(ret); } /* Device instance created; Second instance not possible */ skeldev_init_once = 1; return ret < 0 ? ret : 0; } static int skeleton_rawdev_remove(struct rte_vdev_device *vdev) { const char *name; int ret; name = rte_vdev_device_name(vdev); if (name == NULL) return -1; SKELETON_PMD_INFO("Closing %s on NUMA node %d", name, rte_socket_id()); ret = skeleton_rawdev_destroy(name); if (!ret) skeldev_init_once = 0; return ret; } static struct rte_vdev_driver skeleton_pmd_drv = { .probe = skeleton_rawdev_probe, .remove = skeleton_rawdev_remove }; RTE_PMD_REGISTER_VDEV(SKELETON_PMD_RAWDEV_NAME, skeleton_pmd_drv); RTE_LOG_REGISTER(skeleton_pmd_logtype, rawdev.skeleton, INFO);
22.73057
72
0.731308
[ "object" ]
aa3d96c5df39695e50e1d1910f975ef74dc20d61
2,297
h
C
Hildur/src/Hildur/Util/Log.h
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Hildur/src/Hildur/Util/Log.h
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Hildur/src/Hildur/Util/Log.h
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Hildur/Core/Core.h" #include <memory> #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/sinks/base_sink.h> #include <spdlog/fmt/ostr.h> namespace Hildur { struct Message { public: enum class Level : int8_t { Invalid = -1, Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Critical = 5, Off = 6, // Display nothing }; struct Color { float r, g, b, a; }; public: Message(const std::string message = "", Level level = Level::Invalid); inline bool Valid() { return m_Level != Level::Invalid; } void OnImGuiRender(); public: const std::string m_Message; const Level m_Level; static std::unordered_map<Message::Level, Color> s_RenderColors; }; class HILDUR_API Log { public: static void Init(); inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return s_CoreLogger; } inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return s_ClientLogger; } inline static std::vector<spdlog::sink_ptr>& GetSinks() { return s_Sinks; } private: static std::vector<spdlog::sink_ptr> s_Sinks; static std::shared_ptr<spdlog::logger> s_CoreLogger; static std::shared_ptr<spdlog::logger> s_ClientLogger; }; } //Core log macros #define HR_CORE_TRACE(...) ::Hildur::Log::GetCoreLogger()->trace(__VA_ARGS__) #define HR_CORE_INFO(...) ::Hildur::Log::GetCoreLogger()->info(__VA_ARGS__) #define HR_CORE_WARN(...) ::Hildur::Log::GetCoreLogger()->warn(__VA_ARGS__) #define HR_CORE_ERROR(...) ::Hildur::Log::GetCoreLogger()->error(__VA_ARGS__) #define HR_CORE_CRITICAL(...) ::Hildur::Log::GetCoreLogger()->critical(__VA_ARGS__) //App log macros #define HR_TRACE(...) ::Hildur::Log::GetClientLogger()->trace(__VA_ARGS__) #define HR_INFO(...) ::Hildur::Log::GetClientLogger()->info(__VA_ARGS__) #define HR_WARN(...) ::Hildur::Log::GetClientLogger()->warn(__VA_ARGS__) #define HR_ERROR(...) ::Hildur::Log::GetClientLogger()->error(__VA_ARGS__) #define HR_CRITICAL(...) ::Hildur::Log::GetClientLogger()->critical(__VA_ARGS__)
27.674699
93
0.630823
[ "vector" ]
aa3eae889cea75f6df790a49b1c3e7b17f7e168b
18,606
h
C
modules/perception/common/i_lib/geometry/i_rot.h
zhulianhai/apollo
ab47e53dff2a9fe836ac69fdf783a654a0220802
[ "Apache-2.0" ]
7
2017-07-07T07:56:13.000Z
2019-03-06T06:27:00.000Z
modules/perception/common/i_lib/geometry/i_rot.h
zhulianhai/apollo
ab47e53dff2a9fe836ac69fdf783a654a0220802
[ "Apache-2.0" ]
null
null
null
modules/perception/common/i_lib/geometry/i_rot.h
zhulianhai/apollo
ab47e53dff2a9fe836ac69fdf783a654a0220802
[ "Apache-2.0" ]
2
2017-07-07T07:56:15.000Z
2018-08-10T17:13:34.000Z
#pragma once #include "../core/i_rand.h" #include "../core/i_blas.h" #include "../numeric/i_eig.h" #include "../numeric/i_svd.h" namespace idl { /*This routine force a 2x2 orthogonal matrix R in place (i.e., force it to be rotation maxtrix with positive determinant), /*by unitizing the first row, and taking its cross as the second*/ template<typename T> inline void i_force_rot_2x2(T R[4]) { i_unitize2(R); R[2] = -R[1]; R[3] = R[0]; } /*This routine orthogonalizes a 3x3 near Rotation matrix R in place, i.e., force it to be orthogonal.*/ template <typename T> inline void i_rot_orthogonalize(T R[9], int nr_svd_iter = I_DEFAULT_MAX_SVD_ITERATIONS) { /*obtain SVD*/ T Ut[9], w[3], Vt[9]; i_svd_3x3(R, Ut, w, Vt, true, nr_svd_iter); if (i_determinant_3x3(Ut) < (T)0.0) i_neg9(Ut); if (i_determinant_3x3(Vt) < (T)0.0) i_neg9(Vt); i_mult_AtB_3x3_3x3(Ut, Vt, R); } /*Rodrigues' solver for computing the matrix exponential of a 3x3 skew-symmetric matrix*/ template <typename T> inline void i_rot_rodrigues_3x3_solver(T sinc, T mcos, T a0_sqr, T a1_sqr, T a2_sqr, const T a[3], T R[9]) { T tmp1, tmp2; R[0] = (T)1.0 - (a1_sqr + a2_sqr)*mcos; R[4] = (T)1.0 - (a0_sqr + a2_sqr)*mcos; R[8] = (T)1.0 - (a0_sqr + a1_sqr)*mcos; tmp1 = a[0] * a[1] * mcos; tmp2 = a[2] * sinc; R[1] = tmp1 - tmp2; R[3] = tmp1 + tmp2; tmp1 = a[2] * a[0] * mcos; tmp2 = a[1] * sinc; R[2] = tmp1 + tmp2; R[6] = tmp1 - tmp2; tmp1 = a[1] * a[2] * mcos; tmp2 = a[0] * sinc; R[5] = tmp1 - tmp2; R[7] = tmp1 + tmp2; } template <typename T> inline void i_rot_rodrigues_3x3_solver(T sinc, T mcos, T a0_sqr, T a1_sqr, T a2_sqr, const T s_da[3], const T c_da[3], const T a[3], T R[9], T D[9][3]) { T tmp1, tmp2, e_x[9], e_x2[9]; T mcos_x_a0 = mcos * a[0]; T mcos_x_a1 = mcos * a[1]; T mcos_x_a2 = mcos * a[2]; T mtwo_mcos_x_a0 = -(2 * mcos_x_a0); T mtwo_mcos_x_a1 = -(2 * mcos_x_a1); T mtwo_mcos_x_a2 = -(2 * mcos_x_a2); R[0] = (T)1.0 - (a1_sqr + a2_sqr)*mcos; R[4] = (T)1.0 - (a0_sqr + a2_sqr)*mcos; R[8] = (T)1.0 - (a0_sqr + a1_sqr)*mcos; tmp1 = a[0] * mcos_x_a1; tmp2 = a[2] * sinc; R[1] = tmp1 - tmp2; R[3] = tmp1 + tmp2; tmp1 = a[2] * mcos_x_a0; tmp2 = a[1] * sinc; R[2] = tmp1 + tmp2; R[6] = tmp1 - tmp2; tmp1 = a[1] * mcos_x_a2; tmp2 = a[0] * sinc; R[5] = tmp1 - tmp2; R[7] = tmp1 + tmp2; /*derivatives*/ i_axiator(a, e_x); i_sqr_skew_symmetric_3x3(a, e_x2); //i=0 D[0][0] = (T)(/*e_x[0] * s_da[0]*/ /*+ sinc*e_x_da[0][0] +*/ e_x2[0] * c_da[0] /*+ mcos * e_x2_da[0][0]*/); D[0][1] = (T)(/*e_x[0] * s_da[1]*/ /*+ sinc*e_x_da[0][1] +*/ e_x2[0] * c_da[1] + mtwo_mcos_x_a1); D[0][2] = (T)(/*e_x[0] * s_da[2]*/ /*+ sinc*e_x_da[0][2] +*/ e_x2[0] * c_da[2] + mtwo_mcos_x_a2); //i=1 D[1][0] = (T)(e_x[1] * s_da[0] /*+ sinc*e_x_da[1][0]*/ + e_x2[1] * c_da[0] + mcos_x_a1); D[1][1] = (T)(e_x[1] * s_da[1] /*+ sinc*e_x_da[1][1]*/ + e_x2[1] * c_da[1] + mcos_x_a0); D[1][2] = (T)(e_x[1] * s_da[2] - sinc/**e_x_da[1][2]*/ + e_x2[1] * c_da[2] /*+ mcos * e_x2_da[1][2]*/); //i=2 D[2][0] = (T)(e_x[2] * s_da[0] /*+ sinc*e_x_da[2][0]*/ + e_x2[2] * c_da[0] + mcos_x_a2); D[2][1] = (T)(e_x[2] * s_da[1] + sinc/**e_x_da[2][1]*/ + e_x2[2] * c_da[1] /*+ mcos * e_x2_da[2][1]*/); D[2][2] = (T)(e_x[2] * s_da[2] /*+ sinc*e_x_da[2][2]*/ + e_x2[2] * c_da[2] + mcos_x_a0); //i=3 D[3][0] = (T)(e_x[3] * s_da[0] /*+ sinc*e_x_da[3][0]*/ + e_x2[3] * c_da[0] + mcos_x_a1); D[3][1] = (T)(e_x[3] * s_da[1] /*+ sinc*e_x_da[3][1]*/ + e_x2[3] * c_da[1] + mcos_x_a0); D[3][2] = (T)(e_x[3] * s_da[2] + sinc/**e_x_da[3][2]*/ + e_x2[3] * c_da[2] /*+ mcos * e_x2_da[3][2]*/); //i=4 D[4][0] = (T)(/*e_x[4] * s_da[0]*/ /*+ sinc*e_x_da[4][0] +*/ e_x2[4] * c_da[0] + mtwo_mcos_x_a0); D[4][1] = (T)(/*e_x[4] * s_da[1]*/ /*+ sinc*e_x_da[4][1] +*/ e_x2[4] * c_da[1] /*+ mcos * e_x2_da[4][1]*/); D[4][2] = (T)(/*e_x[4] * s_da[2]*/ /*+ sinc*e_x_da[4][2] +*/ e_x2[4] * c_da[2] + mtwo_mcos_x_a2); //i=5 D[5][0] = (T)(e_x[5] * s_da[0] - sinc/**e_x_da[5][0]*/ + e_x2[5] * c_da[0] /*+ mcos * e_x2_da[5][0]*/); D[5][1] = (T)(e_x[5] * s_da[1] /*+ sinc*e_x_da[5][1]*/ + e_x2[5] * c_da[1] + mcos_x_a2); D[5][2] = (T)(e_x[5] * s_da[2] /*+ sinc*e_x_da[5][2]*/ + e_x2[5] * c_da[2] + mcos_x_a1); //i=6 D[6][0] = (T)(e_x[6] * s_da[0] /*+ sinc*e_x_da[6][0]*/ + e_x2[6] * c_da[0] + mcos_x_a2); D[6][1] = (T)(e_x[6] * s_da[1] - sinc/**e_x_da[6][1]*/ + e_x2[6] * c_da[1] /*+ mcos * e_x2_da[6][1]*/); D[6][2] = (T)(e_x[6] * s_da[2] /*+ sinc*e_x_da[6][2]*/ + e_x2[6] * c_da[2] + mcos_x_a0); //i=7 D[7][0] = (T)(e_x[7] * s_da[0] + sinc/**e_x_da[7][0]*/ + e_x2[7] * c_da[0] /*+ mcos * e_x2_da[7][0]*/); D[7][1] = (T)(e_x[7] * s_da[1] /*+ sinc*e_x_da[7][1]*/ + e_x2[7] * c_da[1] + mcos_x_a2); D[7][2] = (T)(e_x[7] * s_da[2] /*+ sinc*e_x_da[7][2]*/ + e_x2[7] * c_da[2] + mcos_x_a1); //i=8 D[8][0] = (T)(/*e_x[8] * s_da[0]*/ /*+ sinc*e_x_da[8][0] +*/ e_x2[8] * c_da[0] + mtwo_mcos_x_a0); D[8][1] = (T)(/*e_x[8] * s_da[1]*/ /*+ sinc*e_x_da[8][1] +*/ e_x2[8] * c_da[1] + mtwo_mcos_x_a1); D[8][2] = (T)(/*e_x[8] * s_da[2]*/ /*+ sinc*e_x_da[8][2] +*/ e_x2[8] * c_da[2] /*+ mcos * e_x2_da[8][2]*/); } /*Rodrigues' formula for computing the matrix exponential of a 3x3 skew-symmetric matrix The 1st argument is the input (a 3-vector) and the 2nd argument is the output (a 3x3 rotation matrix)*/ template <typename T> inline void i_rot_rodrigues_3x3(const T a[3], T R[9]) { T sinc, mcos, x[3]; i_copy3(a, x); T a0_sqr = i_sqr(x[0]); T a1_sqr = i_sqr(x[1]); T a2_sqr = i_sqr(x[2]); T theta2 = a0_sqr + a1_sqr + a2_sqr; T theta = i_sqrt(theta2); if (theta < Constant<T>::MIN_ABS_SAFE_DIVIDEND() ) { /*theta is too small; use a third-order Taylor approximation for sin(theta) and cos(theta)*/ sinc = (T)1.0 - theta2 / (T)6.0; mcos = (T)0.5 - theta2 / (T)24.0; } else if (theta > Constant<T>::PI()) { /*if ||a||>PI, the it maybe replaced by a(1-2PI/||a||), which represenrs the same rotation*/ theta = (T)(1.0) - Constant<T>::TWO_PI() / theta; i_scale3(x, theta); a0_sqr = i_sqr(x[0]); a1_sqr = i_sqr(x[1]); a2_sqr = i_sqr(x[2]); theta2 = a0_sqr + a1_sqr + a2_sqr; theta = i_sqrt(theta2); if (theta < Constant<T>::MIN_ABS_SAFE_DIVIDEND()) { /*theta is too small; use a third-order Taylor approximation for sin(theta) and cos(theta)*/ sinc = (T)1.0 - theta2 / (T)6.0; mcos = (T)0.5 - theta2 / (T)24.0; } else{ sinc = i_div(i_sin(theta), theta); mcos = i_div((T)1.0 - i_cos(theta), theta2); } } else { sinc = i_div(i_sin(theta), theta); mcos = i_div((T)1.0 - i_cos(theta), theta2); } i_rot_rodrigues_3x3_solver(sinc, mcos, a0_sqr, a1_sqr, a2_sqr, x, R); } /*Rodrigues' formula for computing the matrix exponential of a 3x3 skew-symmetric matrix The 1st argument is the input (a 3-vector), the 2nd argument is the output (a 3x3 rotation matrix), The 3rd argument is the derivative (a 9x3 matrix)*/ template <typename T> inline void i_rot_rodrigues_3x3(const T a[3], T R[9], T D[9][3]) { T sinc, mcos, x[3], s_da[3], c_da[3]; /*derivatives of sinc and mcos wrt to a, respectively*/ i_copy3(a, x); T a0_sqr = i_sqr(x[0]); T a1_sqr = i_sqr(x[1]); T a2_sqr = i_sqr(x[2]); T theta2 = a0_sqr + a1_sqr + a2_sqr; T theta = i_sqrt(theta2); if (theta < Constant<T>::MIN_ABS_SAFE_DIVIDEND()) { /*theta is too small; use a third-order Taylor approximation for sin(theta) and cos(theta)*/ sinc = (T)1.0 - theta2 / (T)6.0; mcos = (T)0.5 - theta2 / (T)24.0; /*derivatives*/ i_scale3(x, s_da, -i_rec((T)3.0)); i_scale3(x, c_da, -i_rec((T)12.0)); } else if (theta > Constant<T>::PI()) { /*if ||a||>PI, the it maybe replaced by a(1-2PI/||a||), which represenrs the same rotation*/ theta = (T)(1.0) - Constant<T>::TWO_PI() / theta; i_scale3(x, theta); a0_sqr = i_sqr(x[0]); a1_sqr = i_sqr(x[1]); a2_sqr = i_sqr(x[2]); theta2 = a0_sqr + a1_sqr + a2_sqr; theta = i_sqrt(theta2); if (theta < Constant<T>::MIN_ABS_SAFE_DIVIDEND()) { /*theta is too small; use a third-order Taylor approximation for sin(theta) and cos(theta)*/ sinc = (T)1.0 - theta2 / (T)6.0; mcos = (T)0.5 - theta2 / (T)24.0; /*derivatives*/ i_scale3(x, s_da, -i_rec((T)3.0)); i_scale3(x, c_da, -i_rec((T)12.0)); } else{ T sin_theta = i_sin(theta); T cos_theta = i_cos(theta); sinc = i_div(sin_theta, theta); mcos = i_div((T)1.0 - cos_theta, theta2); /*derivatives*/ T s_dtheta = (cos_theta - sin_theta / theta) / theta2; T c_dtheta = (sinc - (T)(2.0)*mcos) / theta2; i_scale3(x, s_da, s_dtheta); i_scale3(x, c_da, c_dtheta); } } else { T sin_theta = i_sin(theta); T cos_theta = i_cos(theta); sinc = i_div(sin_theta, theta); mcos = i_div((T)1.0 - cos_theta, theta2); /*derivatives*/ T s_dtheta = (cos_theta - sin_theta / theta) / theta2; T c_dtheta = (sinc - (T)(2.0)*mcos) / theta2; i_scale3(x, s_da, s_dtheta); i_scale3(x, c_da, c_dtheta); } i_rot_rodrigues_3x3_solver(sinc, mcos, a0_sqr, a1_sqr, a2_sqr, s_da, c_da, x, R, D); } /*Rodrigues' formula for computing the matrix exponential of a 3x3 skew-symmetric matrix The 1st argument is the input (a 3-vector), the 2nd argument is the output (a 3x3 rotation matrix), The 3rd argument is the derivative (a 9x3 matrix) Keep this slow implementation as baseline - Liang July/31/2015*/ template <typename T> inline void i_rot_rodrigues_3x3_slow(const T a[3], T R[9], T D[9][3]) { T sinc, mcos, tmp1, tmp2; T a0_sqr = i_sqr(a[0]); T a1_sqr = i_sqr(a[1]); T a2_sqr = i_sqr(a[2]); T theta2 = a0_sqr + a1_sqr + a2_sqr; T theta = i_sqrt(theta2); T s_da[3], c_da[3]; /*derivatives of sinc and mcos wrt to a, respectively*/ if (theta < Constant<T>::MIN_ABS_SAFE_DIVIDEND()) { /*theta is too small; use a third-order Taylor approximation for sin(theta) and cos(theta)*/ sinc = (T)1.0 - theta2 / (T)6.0; mcos = (T)0.5 - theta2 / (T)24.0; /*derivatives*/ i_scale3(a, s_da, -i_rec((T)3.0)); i_scale3(a, c_da, -i_rec((T)12.0)); //s_da[0] = -a[0]/(T)3.0; c_da[0] = -a[0]/12.0; //s_da[1] = -a[1]/(T)3.0; c_da[1] = -a[1]/12.0; //s_da[2] = -a[2]/(T)3.0; c_da[2] = -a[2]/12.0; } else { T sin_theta = i_sin(theta); T cos_theta = i_cos(theta); sinc = i_div(sin_theta, theta); mcos = i_div((T)1.0 - cos_theta, theta2); /*derivatives*/ T s_dtheta = (cos_theta - sin_theta / theta) / theta2; T c_dtheta = (sinc - (T)(2.0)*mcos) / theta2; i_scale3(a, s_da, s_dtheta); i_scale3(a, c_da, c_dtheta); //s_da[0] = s_dtheta*a[0]; c_da[0] = c_dtheta*a[0]; //s_da[1] = s_dtheta*a[1]; c_da[1] = c_dtheta*a[1]; //s_da[2] = s_dtheta*a[2]; c_da[2] = c_dtheta*a[2]; } R[0] = (T)1.0 - (a1_sqr + a2_sqr)*mcos; R[4] = (T)1.0 - (a0_sqr + a2_sqr)*mcos; R[8] = (T)1.0 - (a0_sqr + a1_sqr)*mcos; tmp1 = a[0] * a[1] * mcos; tmp2 = a[2] * sinc; R[1] = tmp1 - tmp2; R[3] = tmp1 + tmp2; tmp1 = a[2] * a[0] * mcos; tmp2 = a[1] * sinc; R[2] = tmp1 + tmp2; R[6] = tmp1 - tmp2; tmp1 = a[1] * a[2] * mcos; tmp2 = a[0] * sinc; R[5] = tmp1 - tmp2; R[7] = tmp1 + tmp2; /*derivatives*/ T e_x[9]; i_axiator(a, e_x); static const T e_x_da[9][3] = { { (T)0, (T)0, (T)0 }, { (T)0, (T)0, -(T)1 }, { (T)0, (T)1, (T)0 }, { (T)0, (T)0, (T)1 }, { (T)0, (T)0, (T)0 }, { -(T)1, (T)0, (T)0 }, { (T)0, -(T)1, (T)0 }, { (T)1, (T)0, (T)0 }, { (T)0, (T)0, (T)0 } }; T e_x2[9]; i_sqr_skew_symmetric_3x3(a, e_x2); //\frac{d {\hat v}^2}{d v} T e_x2_da[9][3]; e_x2_da[0][0] = e_x2_da[1][2] = e_x2_da[2][1] = (T)0.0; e_x2_da[3][2] = e_x2_da[4][1] = e_x2_da[5][0] = (T)0.0; e_x2_da[6][1] = e_x2_da[7][0] = e_x2_da[8][2] = (T)0.0; e_x2_da[1][1] = e_x2_da[3][1] = e_x2_da[2][2] = e_x2_da[6][2] = a[0]; e_x2_da[1][0] = e_x2_da[3][0] = e_x2_da[5][2] = e_x2_da[7][2] = a[1]; e_x2_da[2][0] = e_x2_da[6][0] = e_x2_da[5][1] = e_x2_da[7][1] = a[2]; e_x2_da[4][0] = e_x2_da[8][0] = -(T)2.0 * a[0]; e_x2_da[0][1] = e_x2_da[8][1] = -(T)2.0 * a[1]; e_x2_da[0][2] = e_x2_da[4][2] = -(T)2.0 * a[2]; /*for (int i = 0; i<9; ++i) { D[i][0] = (T)(e_x[i] * s_da[0] + sinc*e_x_da[i][0] + e_x2[i] * c_da[0] + mcos * e_x2_da[i][0]); D[i][1] = (T)(e_x[i] * s_da[1] + sinc*e_x_da[i][1] + e_x2[i] * c_da[1] + mcos * e_x2_da[i][1]); D[i][2] = (T)(e_x[i] * s_da[2] + sinc*e_x_da[i][2] + e_x2[i] * c_da[2] + mcos * e_x2_da[i][2]); }*/ //i=0 D[0][0] = (T)(e_x[0] * s_da[0] + sinc*e_x_da[0][0] + e_x2[0] * c_da[0] + mcos * e_x2_da[0][0]); D[0][1] = (T)(e_x[0] * s_da[1] + sinc*e_x_da[0][1] + e_x2[0] * c_da[1] + mcos * e_x2_da[0][1]); D[0][2] = (T)(e_x[0] * s_da[2] + sinc*e_x_da[0][2] + e_x2[0] * c_da[2] + mcos * e_x2_da[0][2]); //i=1 D[1][0] = (T)(e_x[1] * s_da[0] + sinc*e_x_da[1][0] + e_x2[1] * c_da[0] + mcos * e_x2_da[1][0]); D[1][1] = (T)(e_x[1] * s_da[1] + sinc*e_x_da[1][1] + e_x2[1] * c_da[1] + mcos * e_x2_da[1][1]); D[1][2] = (T)(e_x[1] * s_da[2] + sinc*e_x_da[1][2] + e_x2[1] * c_da[2] + mcos * e_x2_da[1][2]); //i=2 D[2][0] = (T)(e_x[2] * s_da[0] + sinc*e_x_da[2][0] + e_x2[2] * c_da[0] + mcos * e_x2_da[2][0]); D[2][1] = (T)(e_x[2] * s_da[1] + sinc*e_x_da[2][1] + e_x2[2] * c_da[1] + mcos * e_x2_da[2][1]); D[2][2] = (T)(e_x[2] * s_da[2] + sinc*e_x_da[2][2] + e_x2[2] * c_da[2] + mcos * e_x2_da[2][2]); //i=3 D[3][0] = (T)(e_x[3] * s_da[0] + sinc*e_x_da[3][0] + e_x2[3] * c_da[0] + mcos * e_x2_da[3][0]); D[3][1] = (T)(e_x[3] * s_da[1] + sinc*e_x_da[3][1] + e_x2[3] * c_da[1] + mcos * e_x2_da[3][1]); D[3][2] = (T)(e_x[3] * s_da[2] + sinc*e_x_da[3][2] + e_x2[3] * c_da[2] + mcos * e_x2_da[3][2]); //i=4 D[4][0] = (T)(e_x[4] * s_da[0] + sinc*e_x_da[4][0] + e_x2[4] * c_da[0] + mcos * e_x2_da[4][0]); D[4][1] = (T)(e_x[4] * s_da[1] + sinc*e_x_da[4][1] + e_x2[4] * c_da[1] + mcos * e_x2_da[4][1]); D[4][2] = (T)(e_x[4] * s_da[2] + sinc*e_x_da[4][2] + e_x2[4] * c_da[2] + mcos * e_x2_da[4][2]); //i=5 D[5][0] = (T)(e_x[5] * s_da[0] + sinc*e_x_da[5][0] + e_x2[5] * c_da[0] + mcos * e_x2_da[5][0]); D[5][1] = (T)(e_x[5] * s_da[1] + sinc*e_x_da[5][1] + e_x2[5] * c_da[1] + mcos * e_x2_da[5][1]); D[5][2] = (T)(e_x[5] * s_da[2] + sinc*e_x_da[5][2] + e_x2[5] * c_da[2] + mcos * e_x2_da[5][2]); //i=6 D[6][0] = (T)(e_x[6] * s_da[0] + sinc*e_x_da[6][0] + e_x2[6] * c_da[0] + mcos * e_x2_da[6][0]); D[6][1] = (T)(e_x[6] * s_da[1] + sinc*e_x_da[6][1] + e_x2[6] * c_da[1] + mcos * e_x2_da[6][1]); D[6][2] = (T)(e_x[6] * s_da[2] + sinc*e_x_da[6][2] + e_x2[6] * c_da[2] + mcos * e_x2_da[6][2]); //i=7 D[7][0] = (T)(e_x[7] * s_da[0] + sinc*e_x_da[7][0] + e_x2[7] * c_da[0] + mcos * e_x2_da[7][0]); D[7][1] = (T)(e_x[7] * s_da[1] + sinc*e_x_da[7][1] + e_x2[7] * c_da[1] + mcos * e_x2_da[7][1]); D[7][2] = (T)(e_x[7] * s_da[2] + sinc*e_x_da[7][2] + e_x2[7] * c_da[2] + mcos * e_x2_da[7][2]); //i=8 D[8][0] = (T)(e_x[8] * s_da[0] + sinc*e_x_da[8][0] + e_x2[8] * c_da[0] + mcos * e_x2_da[8][0]); D[8][1] = (T)(e_x[8] * s_da[1] + sinc*e_x_da[8][1] + e_x2[8] * c_da[1] + mcos * e_x2_da[8][1]); D[8][2] = (T)(e_x[8] * s_da[2] + sinc*e_x_da[8][2] + e_x2[8] * c_da[2] + mcos * e_x2_da[8][2]); } /*The inverse Rodrigues' formula for computing the logarithm of a 3x3 rotation matrix The 1st argument is the input (a 3x3 rotation matrix) and the 2nd argument is the output (a 3-vector rotation vector)*/ template <typename T> inline void i_rot_invert_rodrigues_3x3(const T R[9], T v[3]/*unnormalized rotation vector*/, T &theta/*rotation angle in radians*/) { T r[3]; T Q[9], Ac[9], h[3], htA[3], ss[3]; int iv[3]; const T *R_ref[3]; T *Q_ref[3], *Ac_ref[3]; i_make_const_reference_3x3(R, R_ref); i_make_reference_3x3(Q, Q_ref); i_make_reference_3x3(Ac, Ac_ref); /*compute the eigenvector of R corresponding to the eigenvalue 1, every rotation matrix must have this eigenvalue*/ i_eigenvector_from_eigenvalue(R_ref, (T)(1.0), Q_ref, h, htA, ss, Ac_ref, 3, iv); i_copy3(Q + 6, v);/*eigen vector of R, unit rotation axis*/ r[0] = R[7] - R[5]; r[1] = R[2] - R[6]; r[2] = R[3] - R[1]; T c = (i_trace_3x3(R) - (T)1.0) * (T)0.5; /*the trace of R is 1 + 2\cos(\theta), equivalent to the sum of its eigenvalues*/ T s = i_dot3(r, v) * (T)0.5; theta = i_atan2(s, c); i_scale3(v, theta); } /*This routine finds a rotation matrix R that rotates unit vector a onto unit vector b. a and b are both assumed to be unit vectors. Corner cases are a and b are parallel*/ template<typename T> inline bool i_rot_3x3(const T a[3], const T b[3], T R[9]) { T v[3], s, theta;// vx[9], vx2[9]; i_eye_3x3(R); /*corner case 1: a == b*/ if (i_equal3(a, b)) { return true; } i_cross(a, b, v); /*L2 norm of v:*/ s = i_l2_norm3(v);/*sine of angle*/ if (s < Constant<T>::MIN_ABS_SAFE_DIVIDEND()) { return false; /*parallel vectors*/ } /*normalize v:*/ i_scale3(v, i_rec(s)); //i_axiator(v, vx); //i_mult_AAt_3x3(vx, vx2); //i_sqr_skew_symmetric_3x3(vx, vx2); //c = i_dot3(a, b); theta = i_acos(i_dot3(a, b)); /*dot product - cos(theta)*/ i_scale3(v, theta); i_rot_rodrigues_3x3(v, R); //s = i_sin(theta); //c = (T)1.0 - c; //i_scale9(vx, s); //i_scale9(vx2, c); ///*rotation matrix using exponential map*/ //i_add9(vx, vx2, R); //R[0] += (T)1.0; //R[4] += (T)1.0; //R[8] += (T)1.0; // //if (i_determinant_3x3(R) < (T)0.0) //{ // i_neg9(R); //} return true; } /*Generate a random 3x3 rotation matrix R, if force_proper is set to 1, then R is forced to be a proper rotation matrix with det(R) = 1*/ template <typename T> inline void i_rand_rot_3x3(T R[9], int &seed, int force_proper = 1) { T Q[9], A[9], h[3], htA[3], ss[3]; T *R_ref[3], *Q_ref[3], *A_ref[3]; int iv[3]; i_make_reference_3x3(R, R_ref); i_make_reference_3x3(Q, Q_ref); i_make_reference_3x3(A, A_ref); i_rand_orthogonal<T>(Q_ref, A_ref, R_ref, h, htA, ss, 3, 3, iv, seed); if (force_proper) { if (i_determinant_3x3(R) < (T)0.0) { i_neg9(R); } } } }/* namespace idl */
41.624161
152
0.542836
[ "vector" ]
aa3ffd898a95db7068cb2bf0d9978f71a26c3267
5,015
h
C
numerics/src/QP/QP_Solvers.h
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
numerics/src/QP/QP_Solvers.h
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
numerics/src/QP/QP_Solvers.h
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * 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 QP_SOLVERS_H #define QP_SOLVERS_H /*!\file QP_Solvers.h Subroutines for the resolution of QP problems.\n \author Franck Perignon */ #ifdef __cplusplus extern "C" { #endif /** solution of quadratic programming problems ql0001 solves the quadratic programming problem minimize .5*x'*C*x + d'*x subject to A(j)*x + b(j) = 0 , j=1,...,me A(j)*x + b(j) >= 0 , j=me+1,...,m xl <= x <= xu Here C must be an n by n symmetric and positive matrix, d an n-dimensional vector, A an m by n matrix and b an m-dimensional vector. The above situation is indicated by iwar(1)=1. Alternatively, i.e. if iwar(1)=0, the objective function matrix can also be provided in factorized form. In this case, C is an upper triangular matrix. The subroutine reorganizes some data so that the problem can be solved by a modification of an algorithm proposed by Powell (1983). usage: call ql0001(m,me,mmax,n,nmax,mnn,c,d,a,b,xl,xu,x,u,iout,ifail, iprint,war,lwar,iwar,liwar) Definition of the parameters: \param m : total number of constraints. \param me : number of equality constraints. \param mmax : row dimension of a. mmax must be at least one and greater than m. \param n : number of variables. \param nmax : row dimension of C. nmax must be greater or equal to n. \param mnn : must be equal to m + n + n. \param c(nmax,nmax): objective function matrix which should be symmetric and positive definite. If iwar(1) = 0, c is supposed to be the choleskey-factor of another matrix, i.e. c is upper triangular. \param d(nmax) : contains the constant vector of the objective function. \param a(mmax,nmax): contains the data matrix of the linear constraints. \param b(mmax) : contains the constant data of the linear constraints. \param xl(n),xu(n): contain the lower and upper bounds for the variables. \param x(n) : on return, x contains the optimal solution vector. \param u(mnn) : on return, u contains the lagrange multipliers. The first m positions are reserved for the multipliers of the m linear constraints and the subsequent ones for the multipliers of the lower and upper bounds. On successful termination, all values of u with respect to inequalities and bounds should be greater or equal to zero. \param iout : integer indicating the desired output unit number, i.e. all write-statements start with 'write(iout,... '. \param ifail : shows the termination reason. ifail = 0 : successful return. ifail = 1 : too many iterations (more than 40*(n+m)). ifail = 2 : accuracy insufficient to satisfy convergence criterion. ifail = 5 : length of a working array is too short. ifail > 10 : the constraints are inconsistent. \param iprint : output control. iprint = 0 : no output of ql0001. iprint > 0 : brief output in error cases. \param war(lwar) : real working array. the length lwar should be grater than 3*nmax*nmax/2 + 10*nmax + 2*mmax. \param iwar(liwar): integer working array. the length liwar should be at least n. if iwar(1)=1 initially, then the cholesky decomposition which is required by the dual algorithm to get the first unconstrained minimum of the objective function, is performed internally. otherwise, i.e. if iwar(1)=0, then it is assumed that the user provides the initial fac- torization by himself and stores it in the upper trian- gular part of the array c. a named common-block /cmache/eps must be provided by the user, where \param eps defines a guess for the underlying machine precision. \author (c): k. schittkowski, mathematisches institut, universitaet bayreuth, 95440 bayreuth, germany, f.r. y version: 1.5 (june, 1991) */ void ql0001_(int *m , int *me , int *mmax , int *n , int *nmax , int *mnn , double *c , double *d , double *a , double *b , double *xl , double *xu , double *x , double *u , int *iout , int *ifail , int *iprint , double *war , int *lwar , int *iwar , int *liwar , double *eps); #ifdef __cplusplus } #endif #endif
39.801587
99
0.674177
[ "vector" ]
aa453efb7f5191e8737f4c433ed5aa082c4373e2
2,248
h
C
camera/hal/mediatek/mtkcam/ipc/client/FDIpcClientAdapter.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/mediatek/mtkcam/ipc/client/FDIpcClientAdapter.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/mediatek/mtkcam/ipc/client/FDIpcClientAdapter.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright (C) 2019 Mediatek Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CAMERA_HAL_MEDIATEK_MTKCAM_IPC_CLIENT_FDIPCCLIENTADAPTER_H_ #define CAMERA_HAL_MEDIATEK_MTKCAM_IPC_CLIENT_FDIPCCLIENTADAPTER_H_ #include <vector> #include "Hal3aIpcCommon.h" #include "Mediatek3AClient.h" #include "IPCFD.h" #include "IPCCommon.h" class VISIBILITY_PUBLIC FDIpcClientAdapter { public: static FDIpcClientAdapter* createInstance(DrvFDObject_e eobject, int openId); void destroyInstance(); ~FDIpcClientAdapter(); MINT32 FDVTInit(MTKFDFTInitInfo* init_data); MINT32 FDVTMain(FdOptions* options, int memFd); MINT32 FDGetCalData(fd_cal_struct* fd_cal_data); // add this two function MINT32 FDSetCalData(fd_cal_struct* fd_cal_data); MINT32 FDVTMainPhase2(); MINT32 FDVTReset(); MINT32 FDVTGetResult(MUINT8* a_FD_ICS_Result, MUINT32 Width, MUINT32 Height, MUINT32 LCM, MUINT32 Sensor, MUINT32 Camera_TYPE, MUINT32 Draw_TYPE); private: explicit FDIpcClientAdapter(int openId); MUINT32 sendRequest(IPC_CMD cmd, ShmMemInfo* memInfo); private: Mtk3aCommon mCommon; bool mInitialized; int mOpenId; ShmMemInfo mMemCreate; ShmMemInfo mMemDestory; ShmMemInfo mMemInitInfo; ShmMemInfo mMemMainParam; ShmMemInfo mMemFdGetCalData; ShmMemInfo mMemFdSetCalData; ShmMemInfo mMemMainPhase2; ShmMemInfo mMemReset; ShmMemInfo mMemFdResultInfo; std::vector<ShmMem> mMems; int32_t mFDBufferHandler; }; #endif // CAMERA_HAL_MEDIATEK_MTKCAM_IPC_CLIENT_FDIPCCLIENTADAPTER_H_
32.57971
80
0.713968
[ "vector" ]
aa467efa101952ed8d1c68a4988154df50c960f7
4,694
h
C
src/main/core/manager.h
mjptree/shadow
00af21d5e2da15fe61acac5b7066844c398f3a86
[ "BSD-3-Clause" ]
1,010
2015-01-09T02:14:40.000Z
2022-03-30T09:04:18.000Z
src/main/core/manager.h
mjptree/shadow
00af21d5e2da15fe61acac5b7066844c398f3a86
[ "BSD-3-Clause" ]
1,485
2015-01-09T23:31:49.000Z
2022-03-24T18:39:41.000Z
src/main/core/manager.h
mjptree/shadow
00af21d5e2da15fe61acac5b7066844c398f3a86
[ "BSD-3-Clause" ]
215
2015-01-24T20:38:20.000Z
2022-02-08T19:35:42.000Z
/* * The Shadow Simulator * * Copyright (c) 2010-2011 Rob Jansen <jansen@cs.umn.edu> * Copyright (c) 2011-2013 * To the extent that a federal employee is an author of a portion * of this software or a derivative work thereof, no copyright is * claimed by the United States Government, as represented by the * Secretary of the Navy ("GOVERNMENT") under Title 17, U.S. Code. * All Other Rights Reserved. * * Permission to use, copy, and modify this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * GOVERNMENT ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION * AND DISCLAIMS ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER * RESULTING FROM THE USE OF THIS SOFTWARE. */ #ifndef SHD_MANAGER_H_ #define SHD_MANAGER_H_ #include <glib.h> #include <netinet/in.h> #include "main/core/controller.h" #include "main/core/support/definitions.h" #include "main/host/host_parameters.h" #include "main/routing/dns.h" typedef struct _Manager Manager; Manager* manager_new(Controller* controller, const ConfigOptions* config, SimulationTime endTime, SimulationTime bootstrapEndTime, guint randomSeed); gint manager_free(Manager* manager); ChildPidWatcher* manager_childpidwatcher(Manager* manager); gboolean manager_isForced(Manager* manager); guint manager_getRawCPUFrequency(Manager* manager); DNS* manager_getDNS(Manager* manager); guint32 manager_getNodeBandwidthUp(Manager* manager, GQuark nodeID, in_addr_t ip); guint32 manager_getNodeBandwidthDown(Manager* manager, GQuark nodeID, in_addr_t ip); void manager_updateMinRunahead(Manager* manager, SimulationTime time); SimulationTime manager_getLatencyForAddresses(Manager* manager, Address* sourceAddress, Address* destinationAddress); SimulationTime manager_getLatency(Manager* manager, GQuark sourceHostID, GQuark destinationHostID); gfloat manager_getReliabilityForAddresses(Manager* manager, Address* sourceAddress, Address* destinationAddress); gfloat manager_getReliability(Manager* manager, GQuark sourceHostID, GQuark destinationHostID); bool manager_isRoutable(Manager* manager, Address* sourceAddress, Address* destinationAddress); void manager_incrementPacketCount(Manager* manager, Address* sourceAddress, Address* destinationAddress); const ConfigOptions* manager_getConfig(Manager* manager); SimulationTime manager_getBootstrapEndTime(Manager* manager); void manager_incrementPluginError(Manager* manager); const gchar* manager_getHostsRootPath(Manager* manager); void manager_run(Manager*); gboolean manager_schedulerIsRunning(Manager* manager); /* info received from controller to set up the simulation */ void manager_addNewProgram(Manager* manager, const gchar* name, const gchar* path, const gchar* startSymbol); int manager_addNewVirtualHost(Manager* manager, HostParameters* params); void manager_addNewVirtualProcess(Manager* manager, const gchar* hostName, gchar* pluginName, SimulationTime startTime, SimulationTime stopTime, gchar** argv, char* environment); // Increment a global counter for the allocation of the object with the given name. // This should be paired with an increment of the dealloc counter with the // same name, otherwise we print a warning that a memory leak was detected. void manager_increment_object_alloc_counter_global(const char* object_name); // Increment a global ounter for the deallocation of the object with the given name. // This should be paired with an increment of the alloc counter with the // same name, otherwise we print a warning that a memory leak was detected. void manager_increment_object_dealloc_counter_global(const char* object_name); // Add the given allocated-object counts into a global manager counter. void manager_add_alloc_object_counts(Manager* manager, Counter* alloc_obj_counts); // Add the given deallocated-object counts into a global manager counter. void manager_add_dealloc_object_counts(Manager* manager, Counter* dealloc_obj_counts); // Add the given syscall counts into a global manager counter. void manager_add_syscall_counts(Manager* manager, Counter* syscall_counts); // Add the given syscall counts, used when the worker is no longer alive. void manager_add_syscall_counts_global(Counter* syscall_counts); #endif /* SHD_MANAGER_H_ */
49.410526
99
0.770345
[ "object" ]
aa4b3a9a8052c9e96653eddd728625ef80146931
779
h
C
NEAT/utils.h
MrMarkSub2/RDMNest
271de0acb163fe6a0f1231864b97b901663d1544
[ "MIT" ]
null
null
null
NEAT/utils.h
MrMarkSub2/RDMNest
271de0acb163fe6a0f1231864b97b901663d1544
[ "MIT" ]
11
2018-01-14T03:29:25.000Z
2018-04-29T05:09:34.000Z
NEAT/utils.h
MrMarkSub2/RDMNest
271de0acb163fe6a0f1231864b97b901663d1544
[ "MIT" ]
null
null
null
#pragma once #ifdef NEAT_EXPORTS #define NEAT_API __declspec(dllexport) #else #define NEAT_API __declspec(dllimport) #endif #include <vector> namespace NEAT { bool NEAT_API IsEssentiallyEqual(double a, double b); // gaussian distribution, mean = 0.0, stdev = 1.0 double NEAT_API getNormalizedRand(double mean = 0.0, double stdev = 1.0); double NEAT_API randDouble(double min = 0.0, double max = 1.0); int NEAT_API randInt(int min = 0, int max = 100); // https://en.wikipedia.org/wiki/Rectifier_(neural_networks) double NEAT_API ReLU(double x); // NEAT paper recommended sigmoidal(x) = 1 / (1+e^(?4.9*x)) instead of ReLU, but other sources implied ReLU is really good... maybe experiment // consider templatizing void NEAT_API softmax(std::vector<double>& v); }
27.821429
143
0.732991
[ "vector" ]
aa4febf5e2702c16a900e3040ffb2fff4ed45bae
42,188
c
C
fortran/nf_v2compat.c
earfw/netcdf
a94ae914c5aed5765fcc00d611a1ae58d07f7254
[ "NetCDF" ]
null
null
null
fortran/nf_v2compat.c
earfw/netcdf
a94ae914c5aed5765fcc00d611a1ae58d07f7254
[ "NetCDF" ]
null
null
null
fortran/nf_v2compat.c
earfw/netcdf
a94ae914c5aed5765fcc00d611a1ae58d07f7254
[ "NetCDF" ]
null
null
null
/* * Copyright 1996, University Corporation for Atmospheric Research * See netcdf/COPYRIGHT file for copying and redistribution conditions. */ /* $Id: fort-v2compat.c,v 1.33 2009/01/27 19:48:34 ed Exp $ */ /* * Source for netCDF2 FORTRAN jacket library. */ /* Modified version of fort-v2compat.c used to provide required * C functions used in v2 compatability interface. This clone * was created to keep existing C code fort-v2compat.c pristine * and to make compiling easier. Note all cfortran.h stuff has * been removed to make compiling easier and the functions * have been made external instead of static so that FORTRAN can * see them */ /* April, 2009 * Modified by: Richard Weed, Ph.D * Center for Advanced Vehicular Systems * Mississippi State University * rweed@cavs.msstate.edu * * C routines required for Fortran V2 compatability */ /* * OVERVIEW * * This file contains jacket routines written in C for interfacing * Fortran netCDF-2 function calls to the actual C-binding netCDF * function call -- using either the netCDF-2 or netCDF-3 C API. * In general, these functions handle character-string parameter * conventions, convert between column-major-order arrays and * row-major-order arrays, and map between array indices beginning * at one and array indices beginning at zero. They also adapt the * differing error handling mechanisms between version 2 and version 3. */ #ifndef NO_NETCDF_2 /* LINTLIBRARY */ #include <ctype.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include "netcdf.h" #ifndef USE_NETCDF4 #define NC_CLASSIC_MODEL 0 #else /* There is a dependency error here; NC_CLASSIC_MODEL will not be defined if ../libsrc4/netcdf.h does not exist yet (which it won't after a maintainer-clean). So, define it here if not already defined. */ #ifndef NC_CLASSIC_MODEL #define NC_CLASSIC_MODEL 0x0100 #endif #endif /* New function added by RW to support FORTRAN 2003 interfaces. Function to return C data type sizes to FORTRAN 2003 code for v2 imap conversion. Duplicates some code in f2c_vimap below */ extern size_t v2data_size(nc_type datatype) { size_t size; size = 0; switch (datatype) { case NC_CHAR: size = sizeof(char); break; case NC_BYTE: #if NF_INT1_IS_C_SIGNED_CHAR size = sizeof(signed char); #elif NF_INT1_IS_C_SHORT size = sizeof(short); #elif NF_INT1_IS_C_INT size = sizeof(int); #elif NF_INT1_IS_C_LONG size = sizeof(long); #endif break; case NC_SHORT: #if NF_INT2_IS_C_SHORT size = sizeof(short); #elif NF_INT2_IS_C_INT size = sizeof(int); #elif NF_INT2_IS_C_LONG size = sizeof(long); #endif break; case NC_INT: #if NF_INT_IS_C_INT size = sizeof(int); #elif NF_INT_IS_C_LONG size = sizeof(long); #endif break; case NC_FLOAT: #if NF_REAL_IS_C_FLOAT size = sizeof(float); #elif NF_REAL_IS_C_DOUBLE size = sizeof(double); #endif break; case NC_DOUBLE: #if NF_DOUBLEPRECISION_IS_C_FLOAT size = sizeof(float); #elif NF_DOUBLEPRECISION_IS_C_DOUBLE size = sizeof(double); #endif break; default: size = -1; } return size; } /** * Convert a Version 2 Fortran IMAP vector into a Version 3 C imap vector. */ extern ptrdiff_t* f2c_v2imap(int ncid, int varid, const int* fimap, ptrdiff_t* cimap) { int rank; nc_type datatype; if (nc_inq_vartype(ncid, varid, &datatype) || nc_inq_varndims(ncid, varid, &rank) || rank <= 0) { return NULL; } /* else */ if (fimap[0] == 0) { /* * Special Fortran version 2 semantics: use external netCDF variable * structure. */ int dimids[NC_MAX_VAR_DIMS]; int idim; size_t total; if (nc_inq_vardimid(ncid, varid, dimids) != NC_NOERR) return NULL; for (total = 1, idim = rank - 1; idim >= 0; --idim) { size_t length; cimap[idim] = total; if (nc_inq_dimlen(ncid, dimids[idim], &length) != NC_NOERR) return NULL; total *= length; } } else { /* * Regular Fortran version 2 semantics: convert byte counts to * element counts. */ int idim; size_t size; switch (datatype) { case NC_CHAR: size = sizeof(char); break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR size = sizeof(signed char); # elif NF_INT1_IS_C_SHORT size = sizeof(short); # elif NF_INT1_IS_C_INT size = sizeof(int); # elif NF_INT1_IS_C_LONG size = sizeof(long); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT size = sizeof(short); # elif NF_INT2_IS_C_INT size = sizeof(int); # elif NF_INT2_IS_C_LONG size = sizeof(long); # endif break; case NC_INT: # if NF_INT_IS_C_INT size = sizeof(int); # elif NF_INT_IS_C_LONG size = sizeof(long); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT size = sizeof(float); # elif NF_REAL_IS_C_DOUBLE size = sizeof(double); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT size = sizeof(float); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE size = sizeof(double); # endif break; default: return NULL; } for (idim = 0; idim < rank; ++idim) cimap[idim] = fimap[rank - 1 - idim] / size; } return cimap; } /* * Compute the product of dimensional counts. */ static size_t dimprod(const size_t* count, int rank) { int i; size_t prod = 1; for (i = 0; i < rank; ++i) prod *= count[i]; return prod; } /* * Set the C global variable ncopts. */ extern void c_ncpopt( int val /* NC_FATAL, NC_VERBOSE, or NC_FATAL|NC_VERBOSE */ ) { ncopts = val; } /* * Get the C global variable ncopts from FORTRAN. */ extern void c_ncgopt( int *val /* NC_FATAL, NC_VERBOSE, or NC_FATAL|NC_VERBOSE */ ) { *val = ncopts; } /* * Create a new netCDF file, returning a netCDF ID. New netCDF * file is placed in define mode. */ extern int c_nccre( const char *pathname, /* file name of new netCDF file */ int clobmode, /* either NCCLOB or NCNOCLOB */ int *rcode /* returned error code */ ) { int ncid = -1; if (pathname == NULL) *rcode = NC_EINVAL; else { *rcode = ((ncid = nccreate (pathname, clobmode)) == -1) ? ncerr : 0; } if (*rcode != 0) { nc_advise("NCCRE", *rcode, ""); *rcode = ncerr; } return ncid; } /* * Open an existing netCDF file for access. */ extern int c_ncopn( const char *pathname, /* file name for netCDF to be opened */ int rwmode, /* either NCWRITE or NCNOWRIT */ int *rcode /* returned error code */ ) { int ncid = -1; /* Include NC_LOCK in check, in case NC_LOCK is ever implemented */ if (rwmode < 0 || rwmode > NC_WRITE + NC_SHARE + NC_CLASSIC_MODEL + NC_LOCK) { *rcode = NC_EINVAL; nc_advise("NCOPN", *rcode, "bad flag, did you forget to include netcdf.inc?"); } else { if (pathname == NULL) { *rcode = NC_EINVAL; } else { *rcode = ((ncid = ncopen (pathname, rwmode)) == -1) ? ncerr : 0; } if (*rcode != 0) { nc_advise("NCOPN", *rcode, ""); *rcode = ncerr; } } return ncid; } /* * Add a new dimension to an open netCDF file in define mode. */ extern int c_ncddef ( int ncid, /* netCDF ID */ const char *dimname,/* dimension name */ int dimlen, /* size of dimension */ int *rcode /* returned error code */ ) { int dimid; if ((dimid = ncdimdef (ncid, dimname, (long)dimlen)) == -1) *rcode = ncerr; else { dimid++; *rcode = 0; } return dimid; } /* * Return the ID of a netCDF dimension, given the name of the dimension. */ extern int c_ncdid ( int ncid, /* netCDF ID */ const char *dimname,/* dimension name */ int *rcode /* returned error code */ ) { int dimid; if ((dimid = ncdimid (ncid, dimname)) == -1) *rcode = ncerr; else { dimid++; *rcode = 0; } return dimid; } /* * Add a new variable to an open netCDF file in define mode. */ extern int c_ncvdef ( int ncid, /* netCDF ID */ const char *varname,/* name of variable */ nc_type datatype, /* netCDF datatype of variable */ int ndims, /* number of dimensions of variable */ int *dimids, /* array of ndims dimensions IDs */ int *rcode /* returned error code */ ) { int varid, status; if ((status = nc_def_var(ncid, varname, datatype, ndims, dimids, &varid))) { nc_advise("NCVDEF", status, ""); *rcode = ncerr; varid = -1; } else { varid++; *rcode = 0; } return varid; } /* * Return the ID of a netCDF variable given its name. */ extern int c_ncvid ( int ncid, /* netCDF ID */ const char *varname,/* variable name */ int *rcode /* returned error code */ ) { int varid; if ((varid = ncvarid (ncid, varname)) == -1) *rcode = ncerr; else { varid++; *rcode = 0; } return varid; } /* * Return number of bytes per netCDF data type. */ extern int c_nctlen ( nc_type datatype, /* netCDF datatype */ int* rcode /* returned error code */ ) { int itype; *rcode = ((itype = (int) nctypelen (datatype)) == -1) ? ncerr : 0; return itype; } /* * Close an open netCDF file. */ extern void c_ncclos ( int ncid, /* netCDF ID */ int* rcode /* returned error code */ ) { *rcode = ncclose(ncid) == -1 ? ncerr : 0; } /* * Put an open netCDF into define mode. */ extern void c_ncredf ( int ncid, /* netCDF ID */ int *rcode /* returned error code */ ) { *rcode = ncredef(ncid) == -1 ? ncerr : 0; } /* * Take an open netCDF out of define mode. */ extern void c_ncendf ( int ncid, /* netCDF ID */ int *rcode /* returned error code */ ) { *rcode = ncendef (ncid) == -1 ? ncerr : 0; } /* * Return information about an open netCDF file given its netCDF ID. */ extern void c_ncinq ( int ncid, /* netCDF ID */ int* indims, /* returned number of dimensions */ int* invars, /* returned number of variables */ int* inatts, /* returned number of attributes */ int* irecdim, /* returned ID of the unlimited dimension */ int* rcode /* returned error code */ ) { *rcode = ncinquire(ncid, indims, invars, inatts, irecdim) == -1 ? ncerr : 0; } /* * Make sure that the disk copy of a netCDF file open for writing * is current. */ extern void c_ncsnc( int ncid, /* netCDF ID */ int* rcode /* returned error code */ ) { *rcode = ncsync (ncid) == -1 ? ncerr : 0; } /* * Restore the netCDF to a known consistent state in case anything * goes wrong during the definition of new dimensions, variables * or attributes. */ extern void c_ncabor ( int ncid, /* netCDF ID */ int* rcode /* returned error code */ ) { *rcode = ncabort(ncid) == -1 ? ncerr : 0; } /* * Return the name and size of a dimension, given its ID. */ extern void c_ncdinq ( int ncid, /* netCDF ID */ int dimid, /* dimension ID */ char* dimname, /* returned dimension name */ int* size, /* returned dimension size */ int* rcode /* returned error code */ ) { long siz; if (ncdiminq (ncid, dimid, dimname, &siz) == -1) *rcode = ncerr; else { *size = siz; *rcode = 0; } } /* * Rename an existing dimension in a netCDF open for writing. */ extern void c_ncdren ( int ncid, /* netCDF ID */ int dimid, /* dimension ID */ const char* dimname, /* new name of dimension */ int* rcode /* returned error code */ ) { *rcode = ncdimrename(ncid, dimid, dimname) == -1 ? ncerr : 0; } /* * Return information about a netCDF variable, given its ID. */ extern void c_ncvinq ( int ncid, /* netCDF ID */ int varid, /* variable ID */ char* varname, /* returned variable name */ nc_type* datatype, /* returned variable type */ int* indims, /* returned number of dimensions */ int* dimarray, /* returned array of ndims dimension IDs */ int* inatts, /* returned number of attributes */ int* rcode /* returned error code */ ) { *rcode = ncvarinq(ncid, varid, varname, datatype, indims, dimarray, inatts) == -1 ? ncerr : 0; } /* * Put a single numeric data value into a variable of an open netCDF. */ extern void c_ncvpt1 ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* indices,/* multidim index of data to be written */ const void* value, /* pointer to data value to be written */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_put_var1_schar(ncid, varid, indices, (const signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_put_var1_short(ncid, varid, indices, (const short*)value); # elif NF_INT1_IS_C_INT status = nc_put_var1_int(ncid, varid, indices, (const int*)value); # elif NF_INT1_IS_C_LONG status = nc_put_var1_long(ncid, varid, indices, (const long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_put_var1_short(ncid, varid, indices, (const short*)value); # elif NF_INT2_IS_C_INT status = nc_put_var1_int(ncid, varid, indices, (const int*)value); # elif NF_INT2_IS_C_LONG status = nc_put_var1_long(ncid, varid, indices, (const long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_put_var1_int(ncid, varid, indices, (const int*)value); # elif NF_INT_IS_C_LONG status = nc_put_var1_long(ncid, varid, indices, (const long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_put_var1_float(ncid, varid, indices, (const float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_put_var1_double(ncid, varid, indices, (const double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_put_var1_float(ncid, varid, indices, (const float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_put_var1_double(ncid, varid, indices, (const double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVPT1", status, ""); *rcode = ncerr; } } /* * Put a single character into an open netCDF file. */ extern void c_ncvp1c( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* indices,/* multidim index of data to be written */ const char* value, /* pointer to data value to be written */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { status = datatype != NC_CHAR ? NC_ECHAR : nc_put_var1_text(ncid, varid, indices, value); } if (status == 0) *rcode = 0; else { nc_advise("NCVP1C", status, ""); *rcode = ncerr; } } /* * Write a hypercube of numeric values into a netCDF variable of an open * netCDF file. */ extern void c_ncvpt ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const void* value, /* block of data values to be written */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_put_vara_schar(ncid, varid, start, count, (const signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_put_vara_short(ncid, varid, start, count, (const short*)value); # elif NF_INT1_IS_C_INT status = nc_put_vara_int(ncid, varid, start, count, (const int*)value); # elif NF_INT1_IS_C_LONG status = nc_put_vara_long(ncid, varid, start, count, (const long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_put_vara_short(ncid, varid, start, count, (const short*)value); # elif NF_INT2_IS_C_INT status = nc_put_vara_int(ncid, varid, start, count, (const int*)value); # elif NF_INT2_IS_C_LONG status = nc_put_vara_long(ncid, varid, start, count, (const long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_put_vara_int(ncid, varid, start, count, (const int*)value); # elif NF_INT_IS_C_LONG status = nc_put_vara_long(ncid, varid, start, count, (const long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_put_vara_float(ncid, varid, start, count, (const float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_put_vara_double(ncid, varid, start, count, (const double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_put_vara_float(ncid, varid, start, count, (const float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_put_vara_double(ncid, varid, start, count, (const double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVPT", status, ""); *rcode = ncerr; } } /* * Write a hypercube of character values into an open netCDF file. */ extern void c_ncvptc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const char* value, /* block of data values to be written */ int lenstr, /* declared length of the data argument */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { if (datatype != NC_CHAR) status = NC_ECHAR; else { int rank; status = nc_inq_varndims(ncid, varid, &rank); if (status == 0) { if (dimprod(count, rank) > (size_t)lenstr) status = NC_ESTS; else status = nc_put_vara_text(ncid, varid, start, count, value); } } } if (status == 0) *rcode = 0; else { nc_advise("NCVPTC", status, ""); *rcode = ncerr; } } /* * Write a generalized hypercube of numeric values into a netCDF variable of * an open netCDF file. */ extern void c_ncvptg ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const ptrdiff_t* strides,/* netCDF variable access strides */ const ptrdiff_t* imap, /* memory values access mapping vector */ const void* value, /* block of data values to be written */ int* rcode /* returned error code */ ) { int status; int rank; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0 && (status = nc_inq_varndims(ncid, varid, &rank)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_put_varm_schar(ncid, varid, start, count, strides, imap, (const signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_put_varm_short(ncid, varid, start, count, strides, imap, (const short*)value); # elif NF_INT1_IS_C_INT status = nc_put_varm_int(ncid, varid, start, count, strides, imap, (const int*)value); # elif NF_INT1_IS_C_LONG status = nc_put_varm_long(ncid, varid, start, count, strides, imap, (const long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_put_varm_short(ncid, varid, start, count, strides, imap, (const short*)value); # elif NF_INT2_IS_C_INT status = nc_put_varm_int(ncid, varid, start, count, strides, imap, (const int*)value); # elif NF_INT2_IS_C_LONG status = nc_put_varm_long(ncid, varid, start, count, strides, imap, (const long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_put_varm_int(ncid, varid, start, count, strides, imap, (const int*)value); # elif NF_INT_IS_C_LONG status = nc_put_varm_long(ncid, varid, start, count, strides, imap, (const long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_put_varm_float(ncid, varid, start, count, strides, imap, (const float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_put_varm_double(ncid, varid, start, count, strides, imap, (const double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_put_varm_float(ncid, varid, start, count, strides, imap, (const float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_put_varm_double(ncid, varid, start, count, strides, imap, (const double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVPTG", status, ""); *rcode = ncerr; } } /* * Write a generalized hypercube of character values into a netCDF variable of * an open netCDF file. */ extern void c_ncvpgc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const ptrdiff_t* strides,/* netCDF variable access strides */ const ptrdiff_t* imap, /* memory values access mapping vector */ const char* value, /* block of data values to be written */ int* rcode /* returned error code */ ) { int status; int rank; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0 && (status = nc_inq_varndims(ncid, varid, &rank)) == 0) { switch (datatype) { case NC_CHAR: status = nc_put_varm_text(ncid, varid, start, count, strides, imap, value); break; default: status = NC_ECHAR; break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVPGC", status, ""); *rcode = ncerr; } } /* * Get a single numeric value from a variable of an open netCDF file. */ extern void c_ncvgt1 ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* indices,/* multidim index of data to be read */ void* value, /* pointer to data value to be read */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_get_var1_schar(ncid, varid, indices, (signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_get_var1_short(ncid, varid, indices, (short*)value); # elif NF_INT1_IS_C_INT status = nc_get_var1_int(ncid, varid, indices, (int*)value); # elif NF_INT1_IS_C_LONG status = nc_get_var1_long(ncid, varid, indices, (long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_get_var1_short(ncid, varid, indices, (short*)value); # elif NF_INT2_IS_C_INT status = nc_get_var1_int(ncid, varid, indices, (int*)value); # elif NF_INT2_IS_C_LONG status = nc_get_var1_long(ncid, varid, indices, (long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_get_var1_int(ncid, varid, indices, (int*)value); # elif NF_INT_IS_C_LONG status = nc_get_var1_long(ncid, varid, indices, (long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_get_var1_float(ncid, varid, indices, (float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_get_var1_double(ncid, varid, indices, (double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_get_var1_float(ncid, varid, indices, (float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_get_var1_double(ncid, varid, indices, (double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVGT1", status, ""); *rcode = ncerr; } } /* * Get a single character data value from a variable of an open * netCDF file. */ extern void c_ncvg1c( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* indices,/* multidim index of data to be read */ char* value, /* pointer to data value to be read */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = nc_get_var1_text(ncid, varid, indices, value); break; default: status = NC_ECHAR; break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVG1C", status, ""); *rcode = ncerr; } } /* * Read a hypercube of numeric values from a netCDF variable of an open * netCDF file. */ extern void c_ncvgt( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ void* value, /* block of data values to be read */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_get_vara_schar(ncid, varid, start, count, (signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_get_vara_short(ncid, varid, start, count, (short*)value); # elif NF_INT1_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT1_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_get_vara_short(ncid, varid, start, count, (short*)value); # elif NF_INT2_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT2_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_get_vara_float(ncid, varid, start, count, (float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_get_vara_double(ncid, varid, start, count, (double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_get_vara_float(ncid, varid, start, count, (float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_get_vara_double(ncid, varid, start, count, (double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVGT", status, ""); *rcode = ncerr; } } /* * Read a hypercube of character values from a netCDF variable. */ extern void c_ncvgtc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ char* value, /* block of data values to be read */ int lenstr, /* declared length of the data argument */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { if (datatype != NC_CHAR) status = NC_ECHAR; else if ((status = nc_get_vara_text(ncid, varid, start, count, value)) == 0) { int rank; if ((status = nc_inq_varndims(ncid, varid, &rank)) == 0) { size_t total = dimprod(count, rank); (void) memset(value+total, ' ', lenstr - total); } } } if (status == 0) *rcode = 0; else { nc_advise("NCVGTC", status, ""); *rcode = ncerr; } } /* * Read a generalized hypercube of numeric values from a netCDF variable of an * open netCDF file. */ extern void c_ncvgtg ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const ptrdiff_t* strides,/* netCDF variable access strides */ const ptrdiff_t* imap, /* memory values access basis vector */ void* value, /* block of data values to be read */ int* rcode /* returned error code */ ) { int status; int rank; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0 && (status = nc_inq_varndims(ncid, varid, &rank)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_get_varm_schar(ncid, varid, start, count, strides, imap, (signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_get_varm_short(ncid, varid, start, count, strides, imap, (short*)value); # elif NF_INT1_IS_C_INT status = nc_get_varm_int(ncid, varid, start, count, strides, imap, (int*)value); # elif NF_INT1_IS_C_LONG status = nc_get_varm_long(ncid, varid, start, count, strides, imap, (long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_get_varm_short(ncid, varid, start, count, strides, imap, (short*)value); # elif NF_INT2_IS_C_INT status = nc_get_varm_int(ncid, varid, start, count, strides, imap, (int*)value); # elif NF_INT2_IS_C_LONG status = nc_get_varm_long(ncid, varid, start, count, strides, imap, (long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_get_varm_int(ncid, varid, start, count, strides, imap, (int*)value); # elif NF_INT_IS_C_LONG status = nc_get_varm_long(ncid, varid, start, count, strides, imap, (long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_get_varm_float(ncid, varid, start, count, strides, imap, (float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_get_varm_double(ncid, varid, start, count, strides, imap, (double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_get_varm_float(ncid, varid, start, count, strides, imap, (float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_get_varm_double(ncid, varid, start, count, strides, imap, (double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVGTG", status, ""); *rcode = ncerr; } } /* * Read a generalized hypercube of character values from a netCDF variable * of an open netCDF file. */ extern void c_ncvggc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ const ptrdiff_t* strides,/* netCDF variable access strides */ const ptrdiff_t* imap, /* memory values access basis vector */ char* value, /* block of data values to be written */ int* rcode /* returned error code */ ) { int status; int rank; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0 && (status = nc_inq_varndims(ncid, varid, &rank)) == 0) { switch (datatype) { case NC_CHAR: status = nc_get_varm_text(ncid, varid, start, count, strides, imap, value); break; default: status = NC_ECHAR; break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVGGC", status, ""); *rcode = ncerr; } } /* * Change the name of a netCDF variable in an open netCDF file. */ extern void c_ncvren ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* varname,/* new name for variable */ int* rcode /* returned error code */ ) { *rcode = ncvarrename (ncid, varid, varname) == -1 ? ncerr : 0; } /* * Add or changes a numeric variable or global attribute of an open * netCDF file. */ extern void c_ncapt ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname, /* attribute name */ nc_type datatype, /* attribute datatype */ size_t attlen, /* attribute length */ const void* value, /* pointer to data values */ int* rcode /* returned error code */ ) { int status; switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_put_att_schar(ncid, varid, attname, datatype, attlen, (const signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_put_att_short(ncid, varid, attname, datatype, attlen, (const short*)value); # elif NF_INT1_IS_C_INT status = nc_put_att_int(ncid, varid, attname, datatype, attlen, (const int*)value); # elif NF_INT1_IS_C_LONG status = nc_put_att_long(ncid, varid, attname, datatype, attlen, (const long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_put_att_short(ncid, varid, attname, datatype, attlen, (const short*)value); # elif NF_INT2_IS_C_INT status = nc_put_att_int(ncid, varid, attname, datatype, attlen, (const int*)value); # elif NF_INT2_IS_C_LONG status = nc_put_att_long(ncid, varid, attname, datatype, attlen, (const long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_put_att_int(ncid, varid, attname, datatype, attlen, (const int*)value); # elif NF_INT_IS_C_LONG status = nc_put_att_long(ncid, varid, attname, datatype, attlen, (const long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_put_att_float(ncid, varid, attname, datatype, attlen, (const float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_put_att_double(ncid, varid, attname, datatype, attlen, (const double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_put_att_float(ncid, varid, attname, datatype, attlen, (const float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_put_att_double(ncid, varid, attname, datatype, attlen, (const double*)value); # endif break; } if (status == 0) *rcode = 0; else { nc_advise("NCAPT", status, ""); *rcode = ncerr; } } /* * Add or change a character attribute of an open netCDF file. */ extern void c_ncaptc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname, /* attribute name */ nc_type datatype, /* attribute datatype */ size_t attlen, /* attribute length */ const char* value, /* pointer to data values */ int* rcode /* returned error code */ ) { int status; if (datatype != NC_CHAR) status = NC_ECHAR; else status = nc_put_att_text(ncid, varid, attname, attlen, value); if (status == 0) *rcode = 0; else { nc_advise("NCAPTC", status, ""); *rcode = ncerr; } } /* * Return information about a netCDF attribute given its variable * ID and name. */ extern void c_ncainq ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname, /* attribute name */ nc_type* datatype, /* returned attribute datatype */ int* attlen, /* returned attribute length */ int* rcode /* returned error code */ ) { *rcode = ncattinq(ncid, varid, attname, datatype, attlen) == -1 ? ncerr : 0; } /* * Get the value of a netCDF attribute given its variable ID and name. */ extern void c_ncagt( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname, /* attribute name */ void* value, /* pointer to data values */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_atttype(ncid, varid, attname, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_get_att_schar(ncid, varid, attname, (signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_get_att_short(ncid, varid, attname, (short*)value); # elif NF_INT1_IS_C_INT status = nc_get_att_int(ncid, varid, attname, (int*)value); # elif NF_INT1_IS_C_LONG status = nc_get_att_long(ncid, varid, attname, (long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_get_att_short(ncid, varid, attname, (short*)value); # elif NF_INT2_IS_C_INT status = nc_get_att_int(ncid, varid, attname, (int*)value); # elif NF_INT2_IS_C_LONG status = nc_get_att_long(ncid, varid, attname, (long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_get_att_int(ncid, varid, attname, (int*)value); # elif NF_INT_IS_C_LONG status = nc_get_att_long(ncid, varid, attname, (long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_get_att_float(ncid, varid, attname, (float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_get_att_double(ncid, varid, attname, (double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_get_att_float(ncid, varid, attname, (float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_get_att_double(ncid, varid, attname, (double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCAGT", status, ""); *rcode = ncerr; } } /* * Get the value of a netCDF character attribute given its variable * ID and name. */ extern void c_ncagtc( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname, /* attribute name */ char* value, /* pointer to data values */ int attlen, /* length of string argument */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_atttype(ncid, varid, attname, &datatype)) == 0) { if (datatype != NC_CHAR) status = NC_ECHAR; else { size_t len; status = nc_inq_attlen(ncid, varid, attname, &len); if (status == 0) { if (attlen < len) status = NC_ESTS; else { status = nc_get_att_text(ncid, varid, attname, value); if (status == 0) (void) memset(value+len, ' ', attlen - len); } } } } if (status == 0) *rcode = 0; else { nc_advise("NCAGTC", status, ""); *rcode = ncerr; } } /* * Copy an attribute from one open netCDF file to another. */ extern void c_ncacpy ( int inncid, /* input netCDF ID */ int invarid, /* variable ID of input netCDF or NC_GLOBAL */ const char* attname,/* name of attribute in input netCDF to be copied */ int outncid, /* ID of output netCDF file for attribute */ int outvarid, /* ID of associated netCDF variable or NC_GLOBAL */ int* rcode /* returned error code */ ) { *rcode = ncattcopy(inncid, invarid, attname, outncid, outvarid) == -1 ? ncerr : 0; } /* * Get the name of an attribute given its variable ID and number * as an attribute of that variable. */ extern void c_ncanam ( int ncid, /* netCDF ID */ int varid, /* variable ID */ int attnum, /* attribute number */ char* attname, /* returned attribute name */ int* rcode /* returned error code */ ) { *rcode = ncattname(ncid, varid, attnum, attname) == -1 ? ncerr : 0; } /* * Rename an attribute in an open netCDF file. */ extern void c_ncaren ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname,/* attribute name */ const char* newname,/* new name */ int* rcode /* returned error code */ ) { *rcode = ncattrename(ncid, varid, attname, newname) == -1 ? ncerr : 0; } /* * Delete an attribute from an open netCDF file given the attribute name. */ extern void c_ncadel ( int ncid, /* netCDF ID */ int varid, /* variable ID */ const char* attname,/* attribute name */ int* rcode /* returned error code */ ) { *rcode = ncattdel(ncid, varid, attname) == -1 ? ncerr : 0; } /* * Set the fill mode of a netCDF file open for writing. */ extern int c_ncsfil ( int ncid, /* netCDF ID */ int fillmode, /* fill mode, NCNOFILL or NCFILL */ int* rcode /* returned error code */ ) { int retval; *rcode = ((retval = ncsetfill(ncid, fillmode)) == -1) ? ncerr : 0; return retval; } #endif /*!NO_NETCDF_2*/
22.95321
79
0.62295
[ "vector" ]
aa50737b14e0dced24d071579b64ef17c484c9c0
1,106
h
C
Netcode/Graphics/DX12/DX12Heap.h
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
Netcode/Graphics/DX12/DX12Heap.h
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
Netcode/Graphics/DX12/DX12Heap.h
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
#pragma once #include <Netcode/HandleDecl.h> #include "DX12Decl.h" #include <memory> #include <vector> #include <wrl.h> namespace Netcode::Graphics::DX12 { class Resource; class Heap : public std::enable_shared_from_this<Heap> { uint64_t sizeInBytes; uint64_t offsetInBytes; uint64_t freedSizeInBytes; D3D12_HEAP_TYPE type; D3D12_HEAP_FLAGS flags; com_ptr<ID3D12Device> device; com_ptr<ID3D12Heap> heap; std::vector<Unique<Resource>> freedResources; void ReturnResource(Resource * rawPtr); public: Heap(com_ptr<ID3D12Device> dev, uint64_t sizeInBytes, D3D12_HEAP_TYPE type, D3D12_HEAP_FLAGS flags); bool IsCompatible(D3D12_HEAP_TYPE requiredHeap, D3D12_HEAP_FLAGS requiredFlags) const; bool HasEnoughSpace(uint64_t bytesToStore) const; bool IsEmpty() const; uint64_t GetUnallocatedSize() const; void Defragment(); Ref<Resource> CreateResource( const ResourceDesc & resourceDesc, const D3D12_RESOURCE_DESC & desc, D3D12_RESOURCE_STATES initState, const D3D12_CLEAR_VALUE * clearValue, const D3D12_RESOURCE_ALLOCATION_INFO & allocation); }; }
23.531915
102
0.772152
[ "vector" ]
aa5c4bdd76eec3bda3e7df853e0fb5d4fb7aad81
3,629
h
C
src/carl/formula/model/ran/RealAlgebraicPoint.h
glatteis/carl
fcadbc6bfa9a8d8786d9f7a2e5f6d511772429bd
[ "MIT" ]
null
null
null
src/carl/formula/model/ran/RealAlgebraicPoint.h
glatteis/carl
fcadbc6bfa9a8d8786d9f7a2e5f6d511772429bd
[ "MIT" ]
null
null
null
src/carl/formula/model/ran/RealAlgebraicPoint.h
glatteis/carl
fcadbc6bfa9a8d8786d9f7a2e5f6d511772429bd
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace carl { template<typename Number> class RealAlgebraicPoint; } #include "RealAlgebraicNumber.h" namespace carl { /** * Represent a multidimensional point whose components are algebraic reals. * This class is just a thin wrapper around vector to have a clearer semantic * meaning. */ template<typename Number> class [[deprecated]] RealAlgebraicPoint { private: /** * Numbers of this RealAlgebraicPoint. */ std::vector<RealAlgebraicNumber<Number>> mNumbers; public: /** * Create an empty point of dimension 0. */ RealAlgebraicPoint() noexcept = default; /** * Convert from a vector using its numbers in the same order as components. */ explicit RealAlgebraicPoint(const std::vector<RealAlgebraicNumber<Number>>& v): mNumbers(v) {} /** * Convert from a vector using its numbers in the same order as components. */ explicit RealAlgebraicPoint(std::vector<RealAlgebraicNumber<Number>>&& v): mNumbers(std::move(v)) {} /** * Convert from a list using its numbers in the same order as components. */ explicit RealAlgebraicPoint(const std::list<RealAlgebraicNumber<Number>>& v): mNumbers(v.begin(), v.end()) {} /** * Convert from a initializer_list using its numbers in the same order as components. */ RealAlgebraicPoint(const std::initializer_list<RealAlgebraicNumber<Number>>& v): mNumbers(v.begin(), v.end()) {} /** * Give the dimension/number of components of this point. */ std::size_t dim() const { return mNumbers.size(); } /** * Make a (lower dimensional) copy that contains only the first * 'componentCount'-many components. */ RealAlgebraicPoint prefixPoint(size_t componentCount) const { assert(componentCount <= mNumbers.size()); std::vector<RealAlgebraicNumber<Number>> copy( mNumbers.begin(), std::next(mNumbers.begin(), componentCount)); return RealAlgebraicPoint(std::move(copy)); } /** * Make a (lower dimensional) copy that contains only the first * 'componentCount'-many components. */ [[deprecated("Use prefixPoint instead")]] RealAlgebraicPoint subpoint(size_t componentCount) const { return prefixPoint(componentCount); } /** * Create a new point with another given component added at the end of this * point, thereby increasing its dimension by 1. The original point remains * untouched. */ RealAlgebraicPoint conjoin(const RealAlgebraicNumber<Number>& r) { RealAlgebraicPoint res = RealAlgebraicPoint(*this); res.mNumbers.push_back(r); return res; } /** * Retrieve the component of this point at the given index. */ const RealAlgebraicNumber<Number>& operator[](std::size_t index) const { assert(index < mNumbers.size()); return mNumbers[index]; } /** * Retrieve the component of this point at the given index. */ RealAlgebraicNumber<Number>& operator[](std::size_t index) { assert(index < mNumbers.size()); return mNumbers[index]; } }; /** * Check if two RealAlgebraicPoints are equal. */ template<typename Number> bool operator==(RealAlgebraicPoint<Number>& lhs, RealAlgebraicPoint<Number>& rhs) { if (lhs.dim() != rhs.dim()) return false; std::not_equal_to<Number> neq; for (std::size_t i = 0; i < lhs.dim(); ++i) { if (neq(lhs[i], rhs[i])) return false; } return true; } /** * Streaming operator for a RealAlgebraicPoint. */ template<typename Number> std::ostream& operator<<(std::ostream& os, const RealAlgebraicPoint<Number>& r) { os << "("; for (std::size_t i = 0; i < r.dim(); ++i) { if (i > 0) os << ", "; os << r[i]; } os << ")"; return os; } }
25.377622
87
0.689722
[ "vector" ]
aa601d093699ed1e5e601f598b86001b1a36f57e
2,245
h
C
DSFilter/include/Anime4KCPPDS.h
AaronFeng753/Anime4KCPP
a900a62abcf70ab9b26a4da44bac38c572ad2bbc
[ "MIT" ]
1
2021-08-25T15:10:19.000Z
2021-08-25T15:10:19.000Z
DSFilter/include/Anime4KCPPDS.h
AaronFeng753/Anime4KCPP
a900a62abcf70ab9b26a4da44bac38c572ad2bbc
[ "MIT" ]
null
null
null
DSFilter/include/Anime4KCPPDS.h
AaronFeng753/Anime4KCPP
a900a62abcf70ab9b26a4da44bac38c572ad2bbc
[ "MIT" ]
null
null
null
#pragma once #include<streams.h> #include<Dvdmedia.h> #include"ACuids.h" #include"ACProp.h" #include"Anime4KCPP.hpp" enum class ColorFormat { YV12, IYUV, NV12, RGB24, RGB32, P016 }; enum GPGPU { CPU, OpenCL, CUDA }; class Anime4KCPPDS : public CTransformFilter, ISpecifyPropertyPages, IAC { public: DECLARE_IUNKNOWN; static CUnknown* WINAPI CreateInstance(LPUNKNOWN punk, HRESULT* phr); STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv); virtual HRESULT CheckInputType(const CMediaType* mtIn); virtual HRESULT CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut); virtual HRESULT DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties); virtual HRESULT GetMediaType(int iPosition, CMediaType* pMediaType); virtual HRESULT Transform(IMediaSample* pIn, IMediaSample* pOut); STDMETHODIMP GetParameters( bool* HDN, int* HDNLevel, bool* CNN, unsigned int* pID, unsigned int* dID, double* zoomFactor, int *H, int* W, int* GPGPUModel, int* OpenCLQueueNum, bool* OpenCLParallelIO); STDMETHODIMP SetParameters( bool HDN, int HDNLevel, bool CNN, unsigned int pID, unsigned int dID, double zoomFactor, int H, int W, int GPGPUModel, int OpenCLQueueNum, bool OpenCLParallelIO); STDMETHODIMP GetGPUInfo(std::string& info); STDMETHODIMP GetPages(CAUUID* pPages); private: Anime4KCPPDS(TCHAR* tszName, LPUNKNOWN punk, HRESULT* phr); BOOL IsRGB24(const CMediaType* pMediaType) const; BOOL IsRGB32(const CMediaType* pMediaType) const; BOOL IsIYUV(const CMediaType* pMediaType) const; BOOL IsYV12(const CMediaType* pMediaType) const; BOOL IsNV12(const CMediaType* pMediaType) const; BOOL IsP016(const CMediaType* pMediaType) const; BOOL CheckGPUSupport(); private: Anime4KCPP::ACCreator acCreator; Anime4KCPP::Parameters parameters; unsigned int pID, dID; double zf; bool CNN; int H, W; GPGPU GPGPUModel; int GPUCheckResult; int OpenCLQueueNum; bool OpenCLParallelIO; size_t srcH, srcW, dstH, dstW; LONG dstDataLength; ColorFormat colorFormat; TCHAR lpPath[MAX_PATH]; CCritSec lock; };
29.933333
95
0.717149
[ "transform" ]
aa635e7bd6c02218fb8fa183fa4152dbef957cf7
211,612
c
C
base/ntos/mm/pagfault.c
987432340/wrk-v1.2
423d4c22b892bcc97778385bc0a646ed7a3cfbde
[ "Intel" ]
1
2022-03-12T13:57:18.000Z
2022-03-12T13:57:18.000Z
base/ntos/mm/pagfault.c
987432340/wrk-v1.2
423d4c22b892bcc97778385bc0a646ed7a3cfbde
[ "Intel" ]
null
null
null
base/ntos/mm/pagfault.c
987432340/wrk-v1.2
423d4c22b892bcc97778385bc0a646ed7a3cfbde
[ "Intel" ]
1
2021-11-25T08:18:04.000Z
2021-11-25T08:18:04.000Z
/*++ Copyright (c) Microsoft Corporation. All rights reserved. You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt). If you do not agree to the terms, do not use the code. Module Name: pagfault.c Abstract: This module contains the pager for memory management. --*/ #include "mi.h" #define STATUS_PTE_CHANGED 0x87303000 #define STATUS_REFAULT 0xC7303001 ULONG MmInPageSupportMinimum = 4; ULONG MiInPageSinglePages; extern PMMPTE MmSharedUserDataPte; extern PVOID MmSpecialPoolStart; extern PVOID MmSpecialPoolEnd; ULONG MiFaultRetries; ULONG MiUserFaultRetries; ULONG MmClusterPageFileReads; #define MI_PROTOTYPE_WSINDEX ((ULONG)-1) NTSTATUS MiResolvePageFileFault ( IN PVOID FaultingAddress, IN PMMPTE PointerPte, OUT PMMPTE CapturedPteContents, IN PMMINPAGE_SUPPORT *ReadBlock, IN PEPROCESS Process, IN KIRQL OldIrql ); NTSTATUS MiResolveProtoPteFault ( IN ULONG_PTR StoreInstruction, IN PVOID VirtualAddress, IN PMMPTE PointerPte, IN PMMPTE PointerProtoPte, IN OUT PMMPFN *LockedProtoPfn, IN PMMINPAGE_SUPPORT *ReadBlock, OUT PMMPTE CapturedPteContents, IN PEPROCESS Process, IN KIRQL OldIrql, IN PVOID TrapInformation ); VOID MiHandleBankedSection ( IN PVOID VirtualAddress, IN PMMVAD Vad ); NTSTATUS MiResolveMappedFileFault ( IN PMMPTE PointerPte, IN PMMINPAGE_SUPPORT *ReadBlock, IN PEPROCESS Process, IN KIRQL OldIrql ); NTSTATUS MiResolveTransitionFault ( IN PVOID FaultingAddress, IN PMMPTE PointerPte, IN PEPROCESS Process, IN KIRQL OldIrql, OUT PMMINPAGE_SUPPORT *InPageBlock ); NTSTATUS MiCompleteProtoPteFault ( IN ULONG_PTR StoreInstruction, IN PVOID FaultingAddress, IN PMMPTE PointerPte, IN PMMPTE PointerProtoPte, IN KIRQL OldIrql, IN OUT PMMPFN *LockedProtoPfn ); ULONG MmMaxTransitionCluster = 8; NTSTATUS MiDispatchFault ( IN ULONG_PTR FaultStatus, IN PVOID VirtualAddress, IN PMMPTE PointerPte, IN PMMPTE PointerProtoPte, IN LOGICAL RecheckAccess, IN PEPROCESS Process, IN PVOID TrapInformation, IN PMMVAD Vad ) /*++ Routine Description: This routine dispatches a page fault to the appropriate routine to complete the fault. Arguments: FaultStatus - Supplies fault status information bits. VirtualAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. PointerProtoPte - Supplies a pointer to the prototype PTE to fault in, NULL if no prototype PTE exists. RecheckAccess - Supplies TRUE if the prototype PTE needs to be checked for access permissions - this is only an issue for forked prototype PTEs that are no-access. Process - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. If this parameter is HYDRA_PROCESS, then the fault is for session space and the process's working set lock is not held - rather the session space's working set lock is held. Vad - Supplies the VAD used for sections. May optionally be NULL even for section-based faults, so use purely as an opportunistic hint. TrapInformation - Supplies the trap information. Return Value: NTSTATUS. Environment: Kernel mode, working set mutex held. --*/ { #if DBG KIRQL EntryIrql; MMWSLE ProtoProtect2; #endif #define VARIOUS_FLAGS_DIRTY_PTE 0x01 #define VARIOUS_FLAGS_PFN_HELD 0x02 #define VARIOUS_FLAGS_ACCESS_CHECK_NEEDED 0x04 #define VARIOUS_FLAGS_LOG_HARD_FAULT 0x08 #define VARIOUS_FLAGS_ENTERED_CRITICAL_REGION 0x10 // // Miscellaneous unrelated flags kept here in one ULONG to save stack space. // ULONG VariousFlags; MMPTE OriginalPte; MMPTE TempPte; MMPTE RealPteContents; MMPTE NewPteContents; MM_PROTECTION_MASK Protection; ULONG FreeBit; MMWSLE ProtoProtect; PFILE_OBJECT FileObject; LONGLONG FileOffset; PSUBSECTION Subsection; ULONG Flags; PVOID UsedPageTableHandle; ULONG_PTR i; ULONG_PTR NumberOfProtos; ULONG_PTR MaxProtos; ULONG_PTR ProtosProcessed; NTSTATUS status; PMMINPAGE_SUPPORT ReadBlock; PMMINPAGE_SUPPORT CapturedEvent; KIRQL OldIrql; PPFN_NUMBER Page; PFN_NUMBER PageFrameIndex; LONG NumberOfBytes; PMMPTE CheckPte; PMMPTE ReadPte; PMMPFN PfnClusterPage; PMMPFN Pfn1; PMMSUPPORT SessionWs; PETHREAD WsThread; PERFINFO_HARDPAGEFAULT_INFORMATION HardFaultEvent; LARGE_INTEGER IoStartTime; ULONG_PTR StoreInstruction; PMMPFN LockedProtoPfn; WSLE_NUMBER WorkingSetIndex; PMMPFN Pfn2; PMMPTE ContainingPageTablePointer; MI_PFN_CACHE_ATTRIBUTE CacheAttribute; PCONTROL_AREA ControlArea; PMMCLONE_DESCRIPTOR CloneDescriptor; #if DBG EntryIrql = KeGetCurrentIrql (); ASSERT (EntryIrql <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); SATISFY_OVERZEALOUS_COMPILER (OriginalPte.u.Long = (ULONG_PTR)-1); #endif VariousFlags = 0; LockedProtoPfn = NULL; SessionWs = NULL; StoreInstruction = MI_FAULT_STATUS_INDICATES_WRITE (FaultStatus); WsThread = PsGetCurrentThread (); // // Initializing ReadBlock & ReadPte is not needed for correctness, but // without it the compiler cannot compile this code W4 to check for use of // uninitialized variables. // OldIrql = MM_NOIRQL; ReadPte = NULL; ReadBlock = NULL; ProtoProtect.u1.Long = 0; if (PointerProtoPte != NULL) { ASSERT (!MI_IS_PHYSICAL_ADDRESS(PointerProtoPte)); CheckPte = MiGetPteAddress (PointerProtoPte); if (VirtualAddress < MmSystemRangeStart) { NumberOfProtos = 1; SATISFY_OVERZEALOUS_COMPILER (UsedPageTableHandle = NULL); SATISFY_OVERZEALOUS_COMPILER (Pfn2 = NULL); SATISFY_OVERZEALOUS_COMPILER (Protection = 0); SATISFY_OVERZEALOUS_COMPILER (RealPteContents.u.Long = 0); if ((PointerPte->u.Soft.PageFileHigh != MI_PTE_LOOKUP_NEEDED) && (PointerPte->u.Proto.ReadOnly == 0)) { // // Kernel mode access must be verified, go the long way below. // VariousFlags |= VARIOUS_FLAGS_ACCESS_CHECK_NEEDED; } else { // // Opportunistically cluster the transition faults as needed. // When the Vad is non-NULL, the proper access checks have // already been applied across the range (as long as the // PTEs are zero). // if ((Vad != NULL) && (Vad->u.VadFlags.VadType != VadImageMap) && (Vad->u2.VadFlags2.ExtendableFile == 0) && (MmAvailablePages > MM_ENORMOUS_LIMIT) && ((Process->Vm.Flags.MaximumWorkingSetHard == 0) || (Process->Vm.WorkingSetSize + MmMaxTransitionCluster <= Process->Vm.MaximumWorkingSetSize)) && (RecheckAccess == FALSE)) { NumberOfProtos = MmMaxTransitionCluster; // // Ensure the cluster doesn't cross the VAD contiguous PTE // limits. // MaxProtos = Vad->LastContiguousPte - PointerProtoPte + 1; if (NumberOfProtos > MaxProtos) { NumberOfProtos = MaxProtos; } // // Ensure the cluster doesn't cross the page containing // the real page table page as we only locked down the // single page. // MaxProtos = (PAGE_SIZE - BYTE_OFFSET (PointerPte)) / sizeof (MMPTE); if (NumberOfProtos > MaxProtos) { NumberOfProtos = MaxProtos; } // // Ensure the cluster doesn't cross the page containing // the prototype PTEs as we only locked down the single // page. // MaxProtos = (PAGE_SIZE - BYTE_OFFSET (PointerProtoPte)) / sizeof (MMPTE); if (NumberOfProtos > MaxProtos) { NumberOfProtos = MaxProtos; } // // Ensure the cluster doesn't cross the VAD limits. // MaxProtos = Vad->EndingVpn - MI_VA_TO_VPN (VirtualAddress) + 1; if (NumberOfProtos > MaxProtos) { NumberOfProtos = MaxProtos; } // // Ensure enough WSLEs are available so we cannot fail to // insert the cluster later. // MaxProtos = 1; WorkingSetIndex = MmWorkingSetList->FirstFree; if ((NumberOfProtos > 1) && (WorkingSetIndex != WSLE_NULL_INDEX)) { do { if (MmWsle[WorkingSetIndex].u1.Long == (WSLE_NULL_INDEX << MM_FREE_WSLE_SHIFT)) { break; } MaxProtos += 1; WorkingSetIndex = (WSLE_NUMBER) (MmWsle[WorkingSetIndex].u1.Long >> MM_FREE_WSLE_SHIFT); } while (MaxProtos < NumberOfProtos); } if (NumberOfProtos > MaxProtos) { NumberOfProtos = MaxProtos; } // // We have computed the maximum cluster size. Fill the PTEs // and increment the use counts on the page table page for // each PTE we fill (regardless of whether the prototype // cluster pages are already in transition). // ASSERT (VirtualAddress <= MM_HIGHEST_USER_ADDRESS); for (i = 1; i < NumberOfProtos; i += 1) { if ((PointerPte + i)->u.Long != MM_ZERO_PTE) { break; } MI_WRITE_INVALID_PTE (PointerPte + i, *PointerPte); } NumberOfProtos = i; if (NumberOfProtos > 1) { UsedPageTableHandle = MI_GET_USED_PTES_HANDLE (VirtualAddress); MI_INCREMENT_USED_PTES_BY_HANDLE_CLUSTER (UsedPageTableHandle, NumberOfProtos - 1); // // The protection code for the real PTE comes from // the real PTE as it was placed there earlier during // the handling of this fault. // ProtoProtect.u1.e1.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE (PointerPte); // // Build up a valid PTE so that when the PFN lock is // held, the only additional update to it is for the // actual PFN. // MI_MAKE_VALID_USER_PTE (RealPteContents, 0, ProtoProtect.u1.e1.Protection, PointerPte); if ((StoreInstruction != 0) && ((ProtoProtect.u1.e1.Protection & MM_COPY_ON_WRITE_MASK) != MM_COPY_ON_WRITE_MASK)) { MI_SET_PTE_DIRTY (RealPteContents); VariousFlags |= VARIOUS_FLAGS_DIRTY_PTE; } ContainingPageTablePointer = MiGetPteAddress (PointerPte); Pfn2 = MI_PFN_ELEMENT (ContainingPageTablePointer->u.Hard.PageFrameNumber); } } } ProtosProcessed = 0; // // Acquire the PFN lock to synchronize access to prototype PTEs. // This is required as the working set mutex does not prevent // multiple processes from operating on the same prototype PTE. // VariousFlags |= VARIOUS_FLAGS_PFN_HELD; LOCK_PFN (OldIrql); if (CheckPte->u.Hard.Valid == 0) { // // The working set pushlock must be released here because this // process' working set may be large, but the number of // available pages may be low. In this case, this thread // could end up needing a page to read the prototype PTE // into and would thus wait in MiEnsureAvailablePageOrWait, // but since this would be as part of handling the a "new" // fault, it would not release the process working set. // // Increment the number of mapped views so the control area // (and the prototype PTEs) cannot be immediately deleted since // the working set pushlock is going to be released and // reacquired. // CloneDescriptor = NULL; ControlArea = NULL; if ((Vad == NULL) && ((PAGE_ALIGN (VirtualAddress) != (PVOID) MM_SHARED_USER_DATA_VA))) { Vad = MiLocateAddress (VirtualAddress); ASSERT (Vad != NULL); } if (Vad != NULL) { if (Vad->u.VadFlags.PrivateMemory == 0) { ControlArea = Vad->ControlArea; ASSERT (ControlArea->NumberOfMappedViews >= 1); ControlArea->NumberOfMappedViews += 1; } else { // // Forked private VADs are prototype PTE-backed but // have no control areas. Reference their clone // descriptor instead. // ASSERT (Process->CloneRoot != NULL); CloneDescriptor = MiLocateCloneAddress (Process, PointerProtoPte); ASSERT (CloneDescriptor != NULL); ASSERT (CloneDescriptor->NumberOfReferences >= 1); CloneDescriptor->NumberOfReferences += 1; CloneDescriptor->FinalNumberOfReferences += 1; } } UNLOCK_PFN (OldIrql); UNLOCK_WS (WsThread, Process); MmAccessFault (FALSE, PointerProtoPte, KernelMode, NULL); // // Note that the VAD may no longer exist at this point ! // if (ControlArea != NULL) { LOCK_PFN (OldIrql); ASSERT (ControlArea->NumberOfMappedViews >= 1); ControlArea->NumberOfMappedViews -= 1; // // See if the control area should be deleted - this // returns with the PFN lock released. // MiCheckControlArea (ControlArea, OldIrql); } else if (CloneDescriptor != NULL) { LOCK_WS (WsThread, Process); LOCK_PFN (OldIrql); MiDecrementCloneBlockReference (CloneDescriptor, NULL, Process, NULL, OldIrql); UNLOCK_PFN (OldIrql); ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (KeAreAllApcsDisabled () == TRUE); return STATUS_SUCCESS; } LOCK_WS (WsThread, Process); ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (KeAreAllApcsDisabled () == TRUE); // // Reissue the faulting instruction since while the working set // pushlock was released, the address space may have changed. // return STATUS_SUCCESS; } TempPte = *PointerProtoPte; if (RecheckAccess == TRUE) { // // This is a forked process so shared prototype PTEs // may actually be fork clone prototypes. These have // the protection within the fork clone yet the // hardware PTEs always share it. This must be // checked here for the case where the NO_ACCESS // permission has been put into the fork clone because // it would not necessarily be in the hardware PTEs like // it is for normal prototypes. // // First make sure the proto is in transition or paged // out as only these states can be no access. // if ((TempPte.u.Hard.Valid == 0) && (TempPte.u.Soft.Prototype == 0)) { ProtoProtect.u1.e1.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE (&TempPte); if (ProtoProtect.u1.e1.Protection == MM_NOACCESS) { ASSERT (MiLocateCloneAddress (Process, PointerProtoPte) != NULL); UNLOCK_PFN (OldIrql); return STATUS_ACCESS_VIOLATION; } } } // // If the fault can be handled inline (prototype transition or // valid for example), then process it here (eliminating // locked page charges, etc) to reduce PFN hold times. // if ((VariousFlags & VARIOUS_FLAGS_ACCESS_CHECK_NEEDED) == 0) { while (TRUE) { if (TempPte.u.Hard.Valid == 1) { // // Prototype PTE is valid. // PageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (&TempPte); Pfn1 = MI_PFN_ELEMENT(PageFrameIndex); Pfn1->u2.ShareCount += 1; } else if ((TempPte.u.Soft.Prototype == 0) && (TempPte.u.Soft.Transition == 1)) { // // This is a fault on a PTE which ultimately // decodes to a prototype PTE referencing a // page already in the cache. // // Optimize this path as every cycle counts. // PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&TempPte); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); ASSERT (Pfn1->u3.e1.PageLocation != ActiveAndValid); if ((Pfn1->u3.e1.ReadInProgress == 1) || (Pfn1->u4.InPageError == 1) || (MmAvailablePages < MM_HIGH_LIMIT)) { break; } MiUnlinkPageFromList (Pfn1); // // Update the PFN database - the reference count // must be incremented as the share count is // going to go from zero to 1. // ASSERT (Pfn1->u2.ShareCount == 0); // // The PFN reference count will be 1 already // here if the modified writer has begun a write // of this page. Otherwise it's ordinarily 0. // // Note there is no need to apply locked page // charges for this page as we know that the share // count is zero (and the reference count is // unknown). But since we are incrementing both // the share and reference counts by one, the // page will retain its current locked charge // regardless of whether or not it is currently // set. // InterlockedIncrementPfn ((PSHORT)&Pfn1->u3.e2.ReferenceCount); // // Update the transition PTE. // Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; MI_MAKE_TRANSITION_PROTOPTE_VALID (TempPte, PointerProtoPte); // // If the modified field is set in the PFN database // and this page is not copy on write, then set // the dirty bit. This can be done as the modified // page will not be written to the paging file // until this PTE is made invalid. // if ((Pfn1->u3.e1.Modified) && (TempPte.u.Hard.Write) && (TempPte.u.Hard.CopyOnWrite == 0)) { MI_SET_PTE_DIRTY (TempPte); } else { MI_SET_PTE_CLEAN (TempPte); } MI_WRITE_VALID_PTE (PointerProtoPte, TempPte); ASSERT (PointerPte->u.Hard.Valid == 0); } else { break; } ProtosProcessed += 1; if (ProtosProcessed == NumberOfProtos) { // // This is the last (or only) PFN so use // MiCompleteProtoPteFault so the PFN lock is released // as quickly as possible. // MiCompleteProtoPteFault (StoreInstruction, VirtualAddress, PointerPte, PointerProtoPte, OldIrql, &LockedProtoPfn); VariousFlags &= ~VARIOUS_FLAGS_PFN_HELD; break; } // // Just finish the PFN work here but not the working // set or prefetcher actions as the PFN lock is held // and we want to minimize PFN hold time. // ASSERT (PointerProtoPte->u.Hard.Valid == 1); Pfn1->u3.e1.PrototypePte = 1; // // Prototype PTE is now valid, make the PTE valid. // // A PTE just went from not present, not transition to // present. The share count and valid count must be // updated in the page table page which contains this PTE. // Pfn2->u2.ShareCount += 1; // // Ensure the user's attributes do not conflict with // the PFN attributes. // NewPteContents.u.Long = RealPteContents.u.Long; ASSERT (NewPteContents.u.Long != 0); if (Pfn1->u3.e1.CacheAttribute == MiCached) { NOTHING; } else if (Pfn1->u3.e1.CacheAttribute == MiNonCached) { Protection = (MM_PROTECTION_MASK) ProtoProtect.u1.e1.Protection; Protection &= ~(MM_NOCACHE | MM_WRITECOMBINE); Protection |= MM_NOCACHE; NewPteContents.u.Long = 0; } else if (Pfn1->u3.e1.CacheAttribute == MiWriteCombined) { Protection = (MM_PROTECTION_MASK) ProtoProtect.u1.e1.Protection; Protection &= ~(MM_NOCACHE | MM_WRITECOMBINE); Protection |= MM_WRITECOMBINE; NewPteContents.u.Long = 0; } if (NewPteContents.u.Long == 0) { MI_MAKE_VALID_USER_PTE (NewPteContents, 0, Protection, PointerPte); if ((StoreInstruction != 0) && ((Protection & MM_COPY_ON_WRITE_MASK) != MM_COPY_ON_WRITE_MASK)) { MI_SET_PTE_DIRTY (NewPteContents); } } NewPteContents.u.Hard.PageFrameNumber = PageFrameIndex; #if DBG // // The protection code for the real PTE comes from // the real PTE as it was placed there above. // ProtoProtect2.u1.Long = 0; ASSERT (PointerPte->u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED); ProtoProtect2.u1.e1.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE(PointerPte); MI_MAKE_VALID_PTE (OriginalPte, PageFrameIndex, ProtoProtect2.u1.e1.Protection, PointerPte); if ((StoreInstruction != 0) && ((ProtoProtect2.u1.e1.Protection & MM_COPY_ON_WRITE_MASK) != MM_COPY_ON_WRITE_MASK)) { MI_SET_PTE_DIRTY (OriginalPte); } { MMPTE RealPte2; RealPte2.u.Long = RealPteContents.u.Long; RealPte2.u.Hard.PageFrameNumber = PageFrameIndex; ASSERT (OriginalPte.u.Long == RealPte2.u.Long); } #endif MI_SNAP_DATA (Pfn1, PointerProtoPte, 6); // // If this is a store instruction and the page is not // copy on write, then set the modified bit in the PFN // database and the dirty bit in the PTE. The PTE is // not set dirty even if the modified bit is set so // writes to the page can be tracked for FlushVirtualMemory. // if (VariousFlags & VARIOUS_FLAGS_DIRTY_PTE) { OriginalPte = Pfn1->OriginalPte; #if DBG if (OriginalPte.u.Soft.Prototype == 1) { PCONTROL_AREA ControlArea; Subsection = MiGetSubsectionAddress (&OriginalPte); ControlArea = Subsection->ControlArea; if (ControlArea->DereferenceList.Flink != NULL) { DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MM: page fault completing to dereferenced CA %p %p %p\n", ControlArea, Pfn1, PointerPte); DbgBreakPoint (); } } #endif MI_SET_MODIFIED (Pfn1, 1, 0xA); if ((OriginalPte.u.Soft.Prototype == 0) && (Pfn1->u3.e1.WriteInProgress == 0)) { FreeBit = GET_PAGING_FILE_OFFSET (OriginalPte); if ((FreeBit != 0) && (FreeBit != MI_PTE_LOOKUP_NEEDED)) { MiReleaseConfirmedPageFileSpace (OriginalPte); } Pfn1->OriginalPte.u.Soft.PageFileHigh = 0; } } ASSERT (PointerPte == MiGetPteAddress (VirtualAddress)); MI_WRITE_VALID_PTE (PointerPte, NewPteContents); PointerProtoPte += 1; TempPte = *PointerProtoPte; PointerPte += 1; VirtualAddress = (PVOID)((ULONG_PTR)VirtualAddress + PAGE_SIZE); } } if (ProtosProcessed != 0) { // // At least the first VA was handled and that was the one // that caused the fault so just return now as any other // VAs were purely optional. // if (VariousFlags & VARIOUS_FLAGS_PFN_HELD) { // // The last speculative VA was not made valid and the PFN // lock is still held. Release the PFN lock now. // UNLOCK_PFN (OldIrql); InterlockedExchangeAdd (&KeGetCurrentPrcb ()->MmTransitionCount, (LONG) ProtosProcessed); } else { // // The last speculative VA was made valid and was also // inserted into the working set list. Subtract one from // the count of protos that need working set insertions // below. // InterlockedExchangeAdd (&KeGetCurrentPrcb ()->MmTransitionCount, (LONG) ProtosProcessed); ProtosProcessed -= 1; } // // Back the locals up to the last "made-valid" VA where // the working set insertions need to begin. // // Add working set entries for the cluster of addresses. // // Note because we checked the WSLE list above prior // to clustering (and the working set mutex has never been // released), we are guaranteed that the working set list // insertions below cannot fail. // Subsection = NULL; SATISFY_OVERZEALOUS_COMPILER (FileObject = NULL); SATISFY_OVERZEALOUS_COMPILER (FileOffset = 0); SATISFY_OVERZEALOUS_COMPILER (Flags = 0); while (ProtosProcessed != 0) { PointerProtoPte -= 1; PointerPte -= 1; VirtualAddress = (PVOID)((ULONG_PTR)VirtualAddress - PAGE_SIZE); ProtosProcessed -= 1; PageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (PointerPte); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); ASSERT (ProtoProtect.u1.e1.Protection != MM_ZERO_ACCESS); ASSERT (MI_IS_PAGE_TABLE_ADDRESS(PointerPte)); ASSERT (PointerPte->u.Hard.Valid == 1); WorkingSetIndex = MiAllocateWsle (&Process->Vm, PointerPte, Pfn1, ProtoProtect.u1.Long); ASSERT (WorkingSetIndex != 0); // // Log prefetch fault information. // // Note that the process' working set mutex is still // held so any other faults or operations on user // addresses by other threads in this process // will block for the duration of this call. // if ((Subsection == NULL) && (CCPF_IS_PREFETCHER_ACTIVE()) && (Pfn1->OriginalPte.u.Soft.Prototype == 1)) { Subsection = MiGetSubsectionAddress (&Pfn1->OriginalPte); FileObject = Subsection->ControlArea->FilePointer; FileOffset = MiStartingOffset (Subsection, PointerProtoPte); Flags = 0; // // Image pages are not speculatively transition // clustered so this must be a data page we are telling // the prefetcher about. // ASSERT (Subsection->ControlArea->u.Flags.Image == 0); if (Subsection->ControlArea->u.Flags.Rom) { Flags |= CCPF_TYPE_ROM; } } if (Subsection != NULL) { CcPfLogPageFault (FileObject, FileOffset, Flags); } } ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (EntryIrql <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); return STATUS_PAGE_FAULT_TRANSITION; } ASSERT (VariousFlags & VARIOUS_FLAGS_PFN_HELD); LockedProtoPfn = MI_PFN_ELEMENT (CheckPte->u.Hard.PageFrameNumber); MI_ADD_LOCKED_PAGE_CHARGE (LockedProtoPfn); ASSERT (LockedProtoPfn->u3.e2.ReferenceCount > 1); ASSERT (PointerPte->u.Hard.Valid == 0); } else { LOCK_PFN (OldIrql); if (CheckPte->u.Hard.Valid == 0) { // // Make sure the prototype PTEs are in memory. If not, since // this is a system address, just convert the fault as though // it happened on the prototype PTE instead. // ASSERT ((Process == NULL) || (Process == HYDRA_PROCESS)); UNLOCK_PFN (OldIrql); VirtualAddress = PointerProtoPte; PointerPte = CheckPte; PointerProtoPte = NULL; // // The page that contains the prototype PTE is not in memory. // if (Process == HYDRA_PROCESS) { // // We were called while holding this session space's // working set lock. But we need to fault in a // prototype PTE which is in system paged pool. This // must be done under the system working set lock. // // So we release the session space WSL lock and get // the system working set lock. When done // we return STATUS_MORE_PROCESSING_REQUIRED // so our caller will call us again to handle the // actual prototype PTE fault. // ASSERT (MI_IS_SESSION_ADDRESS (VirtualAddress) == FALSE); SessionWs = &MmSessionSpace->GlobalVirtualAddress->Vm; UNLOCK_WORKING_SET (WsThread, SessionWs); // // Clear Process as the system working set is now held. // Process = NULL; LOCK_SYSTEM_WS (WsThread); if (PointerPte->u.Hard.Valid != 0) { // // The prototype PTE was made valid by some other // thread while we waited for the system working // set pushlock, so just return and reprocess the fault. // UNLOCK_SYSTEM_WS (WsThread); LOCK_WORKING_SET (WsThread, SessionWs); ASSERT (LockedProtoPfn == NULL); ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (KeAreAllApcsDisabled () == TRUE); return STATUS_SUCCESS; } } goto NonProtoFault; } else if (PointerPte->u.Hard.Valid == 1) { // // PTE was already made valid by the cache manager support // routines. // UNLOCK_PFN (OldIrql); return STATUS_SUCCESS; } } status = MiResolveProtoPteFault (StoreInstruction, VirtualAddress, PointerPte, PointerProtoPte, &LockedProtoPfn, &ReadBlock, &OriginalPte, Process, OldIrql, TrapInformation); // // Returns with PFN lock released. // ReadPte = PointerProtoPte; ASSERT (KeGetCurrentIrql() <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); } else { NonProtoFault: TempPte = *PointerPte; ASSERT (TempPte.u.Hard.Valid == 0); ASSERT (TempPte.u.Soft.Prototype == 0); ASSERT (TempPte.u.Long != 0); if (TempPte.u.Soft.Transition != 0) { // // This is a transition page. // CapturedEvent = NULL; status = MiResolveTransitionFault (VirtualAddress, PointerPte, Process, MM_NOIRQL, &CapturedEvent); if (CapturedEvent != NULL) { MiFreeInPageSupportBlock (CapturedEvent); } } else if (TempPte.u.Soft.PageFileHigh == 0) { // // Demand zero fault. // status = MiResolveDemandZeroFault (VirtualAddress, PointerPte, Process, MM_NOIRQL); } else { // // Page resides in paging file. // ReadPte = PointerPte; LOCK_PFN (OldIrql); TempPte = *PointerPte; ASSERT (TempPte.u.Long != 0); if ((TempPte.u.Hard.Valid == 0) && (TempPte.u.Soft.Prototype == 0) && (TempPte.u.Soft.Transition == 0)) { status = MiResolvePageFileFault (VirtualAddress, PointerPte, &OriginalPte, &ReadBlock, Process, OldIrql); } else { UNLOCK_PFN (OldIrql); status = STATUS_REFAULT; } } } // // Issue the I/O and/or finish completing the soft fault. // ASSERT (KeAreAllApcsDisabled () == TRUE); if (NT_SUCCESS(status)) { if (LockedProtoPfn != NULL) { // // Unlock page containing prototype PTEs. // ASSERT (PointerProtoPte != NULL); LOCK_PFN (OldIrql); // // The reference count on the prototype PTE page will // always be greater than 1 if it is a genuine prototype // PTE pool allocation. However, if it is a fork // prototype PTE allocation, it is possible the pool has // already been deallocated and in this case, the LockedProtoPfn // frame below will be in transition limbo with a share // count of 0 and a reference count of 1 awaiting our // final dereference below which will put it on the free list. // ASSERT (LockedProtoPfn->u3.e2.ReferenceCount >= 1); MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (LockedProtoPfn); UNLOCK_PFN (OldIrql); } if (SessionWs != NULL) { UNLOCK_SYSTEM_WS (WsThread); LOCK_WORKING_SET (WsThread, SessionWs); } ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (KeGetCurrentIrql() <= APC_LEVEL); return status; } if (status == STATUS_ISSUE_PAGING_IO) { ASSERT (ReadPte != NULL); ASSERT (ReadBlock != NULL); if (PointerProtoPte == NULL) { OriginalPte = *ReadPte; } else { // // Since we may be holding a process or session working set // pushlock, we cannot reference the prototype PTE here as it // may have been trimmed already (this is possible when the PFN // lock was released) - so our callees have already captured // it for us. // ASSERT (OriginalPte.u.Hard.Valid == 0); ASSERT (OriginalPte.u.Soft.Prototype == 0); ASSERT (OriginalPte.u.Soft.Transition == 1); } CapturedEvent = (PMMINPAGE_SUPPORT)ReadBlock->Pfn->u1.Event; WsThread->ActiveFaultCount += 1; if (Process == HYDRA_PROCESS) { UNLOCK_WORKING_SET (WsThread, &MmSessionSpace->GlobalVirtualAddress->Vm); ASSERT (KeGetCurrentIrql () <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); } else if (Process != NULL) { // // APCs must be explicitly disabled to prevent suspend APCs from // interrupting this thread before the I/O has been issued. // Otherwise a shared page I/O can stop any other thread that // references it indefinitely until the suspend is released. // KeEnterCriticalRegionThread (&WsThread->Tcb); UNLOCK_WS (WsThread, Process); VariousFlags |= VARIOUS_FLAGS_ENTERED_CRITICAL_REGION; } else { UNLOCK_SYSTEM_WS (WsThread); ASSERT (KeGetCurrentIrql () <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); } if (PERFINFO_IS_GROUP_ON (PERF_FILE_IO)) { VariousFlags |= VARIOUS_FLAGS_LOG_HARD_FAULT; PerfTimeStamp (IoStartTime); } else { SATISFY_OVERZEALOUS_COMPILER (IoStartTime.QuadPart = 0); } // // Assert no reads issued here are marked as prefetched. // ASSERT (ReadBlock->u1.e1.PrefetchMdlHighBits == 0); // // Issue the read request. // status = IoPageRead (ReadBlock->FilePointer, &ReadBlock->Mdl, &ReadBlock->ReadOffset, &ReadBlock->Event, &ReadBlock->IoStatus); if (!NT_SUCCESS(status)) { // // Set the event as the I/O system doesn't set it on errors. // ReadBlock->IoStatus.Status = status; ReadBlock->IoStatus.Information = 0; KeSetEvent (&ReadBlock->Event, 0, FALSE); } // // Initializing PageFrameIndex is not needed for correctness, but // without it the compiler cannot compile this code W4 to check // for use of uninitialized variables. // PageFrameIndex = (PFN_NUMBER)-1; // // Wait for the I/O operation. // status = MiWaitForInPageComplete (ReadBlock->Pfn, ReadPte, VirtualAddress, &OriginalPte, CapturedEvent, Process); WsThread->ActiveFaultCount -= 1; if (VariousFlags & VARIOUS_FLAGS_ENTERED_CRITICAL_REGION) { KeLeaveCriticalRegionThread (&WsThread->Tcb); } if (VariousFlags & VARIOUS_FLAGS_LOG_HARD_FAULT) { PerfTimeStamp (HardFaultEvent.IoTime); HardFaultEvent.IoTime.QuadPart -= IoStartTime.QuadPart; } // // MiWaitForInPageComplete RETURNS WITH THE WORKING SET LOCK // AND PFN LOCK HELD!!! // // // This is the thread which owns the event, clear the event field // in the PFN database. // Pfn1 = ReadBlock->Pfn; Page = &ReadBlock->Page[0]; NumberOfBytes = (LONG)ReadBlock->Mdl.ByteCount; CheckPte = ReadBlock->BasePte; while (NumberOfBytes > 0) { // // Don't remove the page we just brought in to // satisfy this page fault. // if (CheckPte != ReadPte) { PfnClusterPage = MI_PFN_ELEMENT (*Page); MI_SNAP_DATA (PfnClusterPage, PfnClusterPage->PteAddress, 0xB); ASSERT (PfnClusterPage->u4.PteFrame == Pfn1->u4.PteFrame); #if DBG if (PfnClusterPage->u4.InPageError) { ASSERT (status != STATUS_SUCCESS); } #endif if (PfnClusterPage->u3.e1.ReadInProgress != 0) { ASSERT (PfnClusterPage->u4.PteFrame != MI_MAGIC_AWE_PTEFRAME); PfnClusterPage->u3.e1.ReadInProgress = 0; if (PfnClusterPage->u4.InPageError == 0) { PfnClusterPage->u1.Event = NULL; } } MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (PfnClusterPage); } else { PageFrameIndex = *Page; MI_SNAP_DATA (MI_PFN_ELEMENT (PageFrameIndex), MI_PFN_ELEMENT (PageFrameIndex)->PteAddress, 0xC); } CheckPte += 1; Page += 1; NumberOfBytes -= PAGE_SIZE; } if (status != STATUS_SUCCESS) { MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (MI_PFN_ELEMENT(PageFrameIndex)); if (status != STATUS_PTE_CHANGED) { // // An I/O error occurred during the page read // operation. All the pages which were just // put into transition should be put onto the // free list if InPageError is set, and their // PTEs restored to the proper contents. // Page = &ReadBlock->Page[0]; NumberOfBytes = ReadBlock->Mdl.ByteCount; while (NumberOfBytes > 0) { PfnClusterPage = MI_PFN_ELEMENT (*Page); if ((PfnClusterPage->u4.InPageError == 1) && (PfnClusterPage->u3.e2.ReferenceCount == 0)) { PfnClusterPage->u4.InPageError = 0; // // Only restore the transition PTE if the address // space still exists. Another thread may have // deleted the VAD while this thread waited for the // fault to complete - in this case, the frame // will be marked as free already. // if (PfnClusterPage->u3.e1.PageLocation != FreePageList) { ASSERT (PfnClusterPage->u3.e1.PageLocation == StandbyPageList); MiUnlinkPageFromList (PfnClusterPage); ASSERT (PfnClusterPage->u3.e2.ReferenceCount == 0); MiRestoreTransitionPte (PfnClusterPage); MiInsertPageInFreeList (*Page); } } Page += 1; NumberOfBytes -= PAGE_SIZE; } } if (LockedProtoPfn != NULL) { // // Unlock page containing prototype PTEs. // ASSERT (PointerProtoPte != NULL); // // The reference count on the prototype PTE page will // always be greater than 1 if it is a genuine prototype // PTE pool allocation. However, if it is a fork // prototype PTE allocation, it is possible the pool has // already been deallocated and in this case, the LockedProtoPfn // frame below will be in transition limbo with a share // count of 0 and a reference count of 1 awaiting our // final dereference below which will put it on the free list. // ASSERT (LockedProtoPfn->u3.e2.ReferenceCount >= 1); MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (LockedProtoPfn); } UNLOCK_PFN (OldIrql); if (SessionWs != NULL) { UNLOCK_SYSTEM_WS (WsThread); LOCK_WORKING_SET (WsThread, SessionWs); } MiFreeInPageSupportBlock (CapturedEvent); if (status == STATUS_PTE_CHANGED) { // // State of PTE changed during I/O operation, just // return success and refault. // status = STATUS_SUCCESS; } else if (status == STATUS_REFAULT) { // // The I/O operation to bring in a system page failed // due to insufficient resources. Set the status to one // of the MmIsRetryIoStatus codes so our caller will // delay and retry. // status = STATUS_NO_MEMORY; } ASSERT (EntryIrql == KeGetCurrentIrql ()); return status; } // // PTE is still in transition state, same protection, etc. // ASSERT (Pfn1->u4.InPageError == 0); if (Pfn1->u2.ShareCount == 0) { MI_REMOVE_LOCKED_PAGE_CHARGE (Pfn1); } Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; // // Ensure the proper cache attribute is used both in the PTE and // recorded in the PFN. // CacheAttribute = MiCached; Protection = (MM_PROTECTION_MASK) ReadPte->u.Soft.Protection; if (MI_IS_WRITECOMBINE (Protection)) { CacheAttribute = MI_TRANSLATE_CACHETYPE (MiWriteCombined, 0); } else if (MI_IS_NOCACHE (Protection)) { CacheAttribute = MI_TRANSLATE_CACHETYPE (MiNonCached, 0); } if (Pfn1->u3.e1.CacheAttribute != CacheAttribute) { MI_FLUSH_TB_FOR_INDIVIDUAL_ATTRIBUTE_CHANGE (PageFrameIndex, CacheAttribute); Pfn1->u3.e1.CacheAttribute = CacheAttribute; } // // Fill the PTE. // MI_MAKE_TRANSITION_PTE_VALID (TempPte, ReadPte); if (StoreInstruction && TempPte.u.Hard.Write) { MI_SET_PTE_DIRTY (TempPte); } MI_WRITE_VALID_PTE (ReadPte, TempPte); if (PointerProtoPte != NULL) { // // The prototype PTE has been made valid, now make the // original PTE valid. The original PTE must still be invalid // otherwise MiWaitForInPageComplete would have returned // a collision status. // ASSERT (PointerPte->u.Hard.Valid == 0); // // PTE is not valid, continue with operation. // status = MiCompleteProtoPteFault (StoreInstruction, VirtualAddress, PointerPte, PointerProtoPte, OldIrql, &LockedProtoPfn); // // Returns with PFN lock released! // ASSERT (KeAreAllApcsDisabled () == TRUE); } else { ASSERT (LockedProtoPfn == NULL); ASSERT (Pfn1->u3.e1.PrototypePte == 0); UNLOCK_PFN (OldIrql); WorkingSetIndex = MiAddValidPageToWorkingSet (VirtualAddress, ReadPte, Pfn1, 0); if (WorkingSetIndex == 0) { // // Trim the page since we couldn't add it to the working // set list at this time. // MiTrimPte (VirtualAddress, ReadPte, Pfn1, Process, ZeroPte); status = STATUS_NO_MEMORY; } ASSERT (KeAreAllApcsDisabled () == TRUE); } if (VariousFlags & VARIOUS_FLAGS_LOG_HARD_FAULT) { HardFaultEvent.ReadOffset = ReadBlock->ReadOffset; HardFaultEvent.VirtualAddress = VirtualAddress; HardFaultEvent.FileObject = ReadBlock->FilePointer; HardFaultEvent.ThreadId = HandleToUlong (WsThread->Cid.UniqueThread); HardFaultEvent.ByteCount = ReadBlock->Mdl.ByteCount; PerfInfoLogBytes (PERFINFO_LOG_TYPE_HARDFAULT, &HardFaultEvent, sizeof(HardFaultEvent)); } MiFreeInPageSupportBlock (CapturedEvent); if (status == STATUS_SUCCESS) { status = STATUS_PAGE_FAULT_PAGING_FILE; } } if ((status == STATUS_REFAULT) || (status == STATUS_PTE_CHANGED)) { status = STATUS_SUCCESS; } ASSERT (KeAreAllApcsDisabled () == TRUE); if (SessionWs != NULL) { UNLOCK_SYSTEM_WS (WsThread); ASSERT (KeAreAllApcsDisabled () == TRUE); LOCK_WORKING_SET (WsThread, SessionWs); } if (LockedProtoPfn != NULL) { // // Unlock page containing prototype PTEs. // ASSERT (PointerProtoPte != NULL); LOCK_PFN (OldIrql); // // The reference count on the prototype PTE page will // always be greater than 1 if it is a genuine prototype // PTE pool allocation. However, if it is a fork // prototype PTE allocation, it is possible the pool has // already been deallocated and in this case, the LockedProtoPfn // frame below will be in transition limbo with a share // count of 0 and a reference count of 1 awaiting our // final dereference below which will put it on the free list. // ASSERT (LockedProtoPfn->u3.e2.ReferenceCount >= 1); MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (LockedProtoPfn); UNLOCK_PFN (OldIrql); } ASSERT (EntryIrql == KeGetCurrentIrql ()); ASSERT (KeAreAllApcsDisabled () == TRUE); return status; } NTSTATUS MiResolveDemandZeroFault ( IN PVOID VirtualAddress, IN PMMPTE PointerPte, IN PEPROCESS Process, IN KIRQL OldIrql ) /*++ Routine Description: This routine resolves a demand zero page fault. Arguments: VirtualAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. Process - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. OldIrql - Supplies the IRQL the caller acquired the PFN lock at (MM_NOIRQL if the caller does not hold the PFN lock). If the caller holds the PFN lock, the lock cannot be dropped, and the page should not be added to the working set at this time. Return Value: NTSTATUS. Environment: Kernel mode, PFN lock held conditionally. --*/ { PMMPFN Pfn1; PFN_NUMBER PageFrameIndex; MMPTE TempPte; ULONG PageColor; LOGICAL NeedToZero; LOGICAL BarrierNeeded; ULONG BarrierStamp; WSLE_NUMBER WorkingSetIndex; LOGICAL ZeroPageNeeded; LOGICAL CallerHeldPfn; NeedToZero = FALSE; BarrierNeeded = FALSE; CallerHeldPfn = TRUE; // // Initializing BarrierStamp is not needed for // correctness but without it the compiler cannot compile this code // W4 to check for use of uninitialized variables. // BarrierStamp = 0; // // Initialize variables assuming the operation will succeed. // If it fails (lack of pages or whatever), it's ok that the // process' NextPageColor got bumped anyway. The goal is to do // as much as possible without holding the PFN lock. // if ((Process > HYDRA_PROCESS) && (OldIrql == MM_NOIRQL)) { ASSERT (MI_IS_PAGE_TABLE_ADDRESS (PointerPte)); // // If a fork operation is in progress and the faulting thread // is not the thread performing the fork operation, block until // the fork is completed. // if (Process->ForkInProgress != NULL) { if (MiWaitForForkToComplete (Process) == TRUE) { return STATUS_REFAULT; } } PageColor = MI_PAGE_COLOR_VA_PROCESS (VirtualAddress, &Process->NextPageColor); ASSERT (PageColor != 0xFFFFFFFF); ZeroPageNeeded = TRUE; } else { if (OldIrql != MM_NOIRQL) { ZeroPageNeeded = TRUE; } else { ZeroPageNeeded = FALSE; // // For session space, the BSS of an image is typically mapped // directly as an image, but in the case of images that have // outstanding user references at the time of section creation, // the image is copied to a pagefile backed section and then // mapped in session view space (the destination is mapped in // system view space). See MiSessionWideReserveImageAddress. // if ((Process == HYDRA_PROCESS) && ((MI_IS_SESSION_IMAGE_ADDRESS (VirtualAddress)) || ((VirtualAddress >= (PVOID) MiSessionViewStart) && (VirtualAddress < (PVOID) MiSessionSpaceWs)))) { ZeroPageNeeded = TRUE; } } PageColor = 0xFFFFFFFF; } if (OldIrql == MM_NOIRQL) { CallerHeldPfn = FALSE; LOCK_PFN (OldIrql); } MM_PFN_LOCK_ASSERT(); ASSERT (PointerPte->u.Hard.Valid == 0); // // Check to see if a page is available, if a wait is // returned, do not continue, just return success. // if ((MmAvailablePages >= MM_HIGH_LIMIT) || (!MiEnsureAvailablePageOrWait (Process, OldIrql))) { if (PageColor != 0xFFFFFFFF) { // // This page is for a user process and so must be zeroed. // PageFrameIndex = MiRemoveZeroPageIfAny (PageColor); if (PageFrameIndex) { // // This barrier check is needed after zeroing the page // and before setting the PTE valid. Note since the PFN // database entry is used to hold the sequence timestamp, // it must be captured now. Check it at the last possible // moment. // Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); BarrierStamp = (ULONG)Pfn1->u4.PteFrame; } else { PageFrameIndex = MiRemoveAnyPage (PageColor); NeedToZero = TRUE; } } else { // // As this is a system page, there is no need to // remove a page of zeroes, it must be initialized by // the system before being used. // PageColor = MI_GET_PAGE_COLOR_FROM_VA (VirtualAddress); if (ZeroPageNeeded) { PageFrameIndex = MiRemoveZeroPage (PageColor); } else { PageFrameIndex = MiRemoveAnyPage (PageColor); } } MiInitializePfn (PageFrameIndex, PointerPte, 1); if (CallerHeldPfn == FALSE) { UNLOCK_PFN (OldIrql); if (Process > HYDRA_PROCESS) { Process->NumberOfPrivatePages += 1; BarrierNeeded = TRUE; } } InterlockedIncrement (&KeGetCurrentPrcb ()->MmDemandZeroCount); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); if (NeedToZero) { PMMPTE ZeroPte; PVOID ZeroAddress; ASSERT (CallerHeldPfn == FALSE); ZeroPte = MiReserveSystemPtes (1, SystemPteSpace); if (ZeroPte != NULL) { TempPte = ValidKernelPte; TempPte.u.Hard.PageFrameNumber = PageFrameIndex; if (Pfn1->u3.e1.CacheAttribute == MiWriteCombined) { MI_SET_PTE_WRITE_COMBINE (TempPte); } else if (Pfn1->u3.e1.CacheAttribute == MiNonCached) { MI_DISABLE_CACHING (TempPte); } MI_WRITE_VALID_PTE (ZeroPte, TempPte); ZeroAddress = MiGetVirtualAddressMappedByPte (ZeroPte); KeZeroSinglePage (ZeroAddress); MiReleaseSystemPtes (ZeroPte, 1, SystemPteSpace); } else { MiZeroPhysicalPage (PageFrameIndex); } // // Note the stamping must occur after the page is zeroed. // MI_BARRIER_STAMP_ZEROED_PAGE (&BarrierStamp); } // // As this page is demand zero, set the modified bit in the // PFN database element and set the dirty bit in the PTE. // MI_SNAP_DATA (Pfn1, PointerPte, 5); if (PointerPte <= MiHighestUserPte) { MI_MAKE_VALID_USER_PTE (TempPte, PageFrameIndex, PointerPte->u.Soft.Protection, PointerPte); } else { // // Might be system or session or user page directories, // so go the long way to find out. // MI_MAKE_VALID_PTE (TempPte, PageFrameIndex, PointerPte->u.Soft.Protection, PointerPte); } if (TempPte.u.Hard.Write != 0) { MI_SET_PTE_DIRTY (TempPte); } if (BarrierNeeded) { MI_BARRIER_SYNCHRONIZE (BarrierStamp); } MI_WRITE_VALID_PTE (PointerPte, TempPte); if (CallerHeldPfn == FALSE) { ASSERT (Pfn1->u1.Event == 0); ASSERT (Pfn1->u3.e1.PrototypePte == 0); WorkingSetIndex = MiAddValidPageToWorkingSet (VirtualAddress, PointerPte, Pfn1, 0); if (WorkingSetIndex == 0) { // // Trim the page since we couldn't add it to the working // set list at this time. // MiTrimPte (VirtualAddress, PointerPte, Pfn1, Process, ZeroPte); return STATUS_NO_MEMORY; } } return STATUS_PAGE_FAULT_DEMAND_ZERO; } if (CallerHeldPfn == FALSE) { UNLOCK_PFN (OldIrql); } return STATUS_REFAULT; } NTSTATUS MiResolveTransitionFault ( IN PVOID FaultingAddress, IN PMMPTE PointerPte, IN PEPROCESS CurrentProcess, IN KIRQL OldIrql, OUT PMMINPAGE_SUPPORT *InPageBlock ) /*++ Routine Description: This routine resolves a transition page fault. Arguments: FaultingAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. CurrentProcess - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. OldIrql - Supplies the IRQL the caller acquired the PFN lock at. InPageBlock - Supplies a pointer to an inpage block pointer. The caller must initialize this to NULL on entry. This routine sets this to a non-NULL value to signify an inpage block the caller must free when the caller releases the PFN lock. Return Value: status, either STATUS_SUCCESS, STATUS_REFAULT or an I/O status code. Environment: Kernel mode, PFN lock may optionally be held. --*/ { MM_PROTECTION_MASK Protection; MMPFNENTRY PfnFlags; PFN_NUMBER PageFrameIndex; PMMPFN Pfn1; PMMPFN Pfn2; MMPTE TempPte; MMPTE TempPte2; NTSTATUS status; NTSTATUS PfnStatus; PMMINPAGE_SUPPORT CapturedEvent; PETHREAD CurrentThread; PMMPTE PointerToPteForProtoPage; WSLE_NUMBER WorkingSetIndex; ULONG PfnLockHeld; LOGICAL EnteredCritical; // // *********************************************************** // Transition PTE. // *********************************************************** // // // A transition PTE is either on the free or modified list, // on neither list because of its ReferenceCount // or currently being read in from the disk (read in progress). // If the page is read in progress, this is a collided page // and must be handled accordingly. // ASSERT (*InPageBlock == NULL); if (OldIrql == MM_NOIRQL) { PfnLockHeld = FALSE; // // Read the PTE now without the PFN lock so that the PFN entry // calculations, etc can be done in advance. If it turns out the PTE // changed after the lock is acquired (should be rare), then // recalculate. // TempPte2 = *PointerPte; PageFrameIndex = (PFN_NUMBER) TempPte2.u.Hard.PageFrameNumber; Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); ASSERT (OldIrql == MM_NOIRQL); LOCK_PFN (OldIrql); TempPte = *PointerPte; if ((TempPte.u.Soft.Valid == 0) && (TempPte.u.Soft.Prototype == 0) && (TempPte.u.Soft.Transition == 1)) { if (TempPte2.u.Long != TempPte.u.Long) { PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&TempPte); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); } NOTHING; } else { UNLOCK_PFN (OldIrql); return STATUS_REFAULT; } } else { PfnLockHeld = TRUE; ASSERT (OldIrql != MM_NOIRQL); TempPte = *PointerPte; ASSERT ((TempPte.u.Soft.Valid == 0) && (TempPte.u.Soft.Prototype == 0) && (TempPte.u.Soft.Transition == 1)); PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&TempPte); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); } // // Still in transition format. // InterlockedIncrement (&KeGetCurrentPrcb ()->MmTransitionCount); if (Pfn1->u4.InPageError) { // // There was an in-page read error and there are other // threads colliding for this page, delay to let the // other threads complete and return. Snap relevant PFN fields // before releasing the lock as the page may immediately get // reused. // PfnFlags = Pfn1->u3.e1; status = Pfn1->u1.ReadStatus; if (!PfnLockHeld) { UNLOCK_PFN (OldIrql); } if (PfnFlags.ReadInProgress) { // // This only occurs when the page is being reclaimed by the // compression reaper. In this case, the page is still on the // transition list (so the ReadStatus is really a flink) so // substitute a retry status which will induce a delay so the // compression reaper can finish taking the page (and PTE). // return STATUS_NO_MEMORY; } ASSERT (!NT_SUCCESS(status)); return status; } if (Pfn1->u3.e1.ReadInProgress) { // // Collided page fault. // CapturedEvent = (PMMINPAGE_SUPPORT)Pfn1->u1.Event; CurrentThread = PsGetCurrentThread (); if (CapturedEvent->Thread == CurrentThread) { // // This detects when the Io APC completion routine accesses // the same user page (ie: during an overlapped I/O) that // the user thread has already faulted on. // // This can result in a fatal deadlock and so must // be detected here. Return a unique status code so the // (legitimate) callers know this has happened so it can be // handled properly, ie: Io must request a callback from // the Mm once the first fault has completed. // // Note that non-legitimate callers must get back a failure // status so the thread can be terminated. // #if DBG #if defined (_AMD64_) { // // Do not assert if there are stack walks in progress since // this can be ok. The stack walking code will deal with // the in page error raised due to this situation. // extern LONG RtlpStackWalksInProgress; if (RtlpStackWalksInProgress == 0) { ASSERT (CurrentThread->ActiveFaultCount >= 1); } } #else ASSERT (CurrentThread->ActiveFaultCount >= 1); #endif #endif CurrentThread->ApcNeeded = 1; if (!PfnLockHeld) { UNLOCK_PFN (OldIrql); } return STATUS_MULTIPLE_FAULT_VIOLATION; } // // Increment the reference count for the page so it won't be // reused until all collisions have been completed. // ASSERT (Pfn1->u2.ShareCount == 0); ASSERT (Pfn1->u3.e2.ReferenceCount != 0); InterlockedIncrementPfn ((PSHORT)&Pfn1->u3.e2.ReferenceCount); // // Careful synchronization is applied to the WaitCount field so // that freeing of the inpage block can occur lock-free. Note // that the ReadInProgress bit on each PFN is set and cleared while // holding the PFN lock. Inpage blocks are always (and must be) // freed _AFTER_ the ReadInProgress bit is cleared. // InterlockedIncrement (&CapturedEvent->WaitCount); UNLOCK_PFN (OldIrql); CurrentThread->ActiveFaultCount += 1; EnteredCritical = FALSE; if (CurrentProcess == HYDRA_PROCESS) { UNLOCK_WORKING_SET (CurrentThread, &MmSessionSpace->GlobalVirtualAddress->Vm); } else if (CurrentProcess != NULL) { // // APCs must be explicitly disabled to prevent suspend APCs from // interrupting this thread before the wait has been issued. // Otherwise the APC can result in this page being locked // indefinitely until the suspend is released. // KeEnterCriticalRegionThread (&CurrentThread->Tcb); UNLOCK_WS (CurrentThread, CurrentProcess); EnteredCritical = TRUE; } else { UNLOCK_SYSTEM_WS (CurrentThread); } // // Set the inpage block address as the waitcount was incremented // above and therefore the free must be done by our caller. // *InPageBlock = CapturedEvent; status = MiWaitForInPageComplete (Pfn1, PointerPte, FaultingAddress, &TempPte, CapturedEvent, CurrentProcess); // // MiWaitForInPageComplete RETURNS WITH THE WORKING SET LOCK // AND PFN LOCK HELD!!! // CurrentThread->ActiveFaultCount -= 1; if (EnteredCritical == TRUE) { KeLeaveCriticalRegionThread (&CurrentThread->Tcb); } ASSERT (Pfn1->u3.e1.ReadInProgress == 0); if (status != STATUS_SUCCESS) { PfnStatus = Pfn1->u1.ReadStatus; MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (Pfn1); // // Check to see if an I/O error occurred on this page. // If so, try to free the physical page, wait a // half second and return a status of PTE_CHANGED. // This will result in success being returned to // the user and the fault will occur again and should // not be a transition fault this time. // if (Pfn1->u4.InPageError == 1) { ASSERT (!NT_SUCCESS(PfnStatus)); status = PfnStatus; if (Pfn1->u3.e2.ReferenceCount == 0) { Pfn1->u4.InPageError = 0; // // Only restore the transition PTE if the address // space still exists. Another thread may have // deleted the VAD while this thread waited for the // fault to complete - in this case, the frame // will be marked as free already. // if (Pfn1->u3.e1.PageLocation != FreePageList) { ASSERT (Pfn1->u3.e1.PageLocation == StandbyPageList); MiUnlinkPageFromList (Pfn1); ASSERT (Pfn1->u3.e2.ReferenceCount == 0); MiRestoreTransitionPte (Pfn1); MiInsertPageInFreeList (PageFrameIndex); } } } if (!PfnLockHeld) { UNLOCK_PFN (OldIrql); } // // Instead of returning status, always return STATUS_REFAULT. // This is to support filesystems that save state in the // ETHREAD of the thread that serviced the fault ! Since // collided threads never enter the filesystem, their ETHREADs // haven't been hacked up. Since this only matters when // errors occur (specifically STATUS_VERIFY_REQUIRED today), // retry any failed I/O in the context of each collider // to give the filesystems ample opportunity. // return STATUS_REFAULT; } } else { // // PTE refers to a normal transition PTE. // ASSERT ((SPFN_NUMBER)MmAvailablePages >= 0); // // Check available pages so that a machine which is low on memory // can stop this thread from gobbling up the pages from every modified // write that completes because that would starve waiting threads. // // Another scenario is if the system is utilizing a hardware // compression cache. Checking ensures that only a safe amount // of the compressed virtual cache is directly mapped so that // if the hardware gets into trouble, we can bail it out. // if ((MmAvailablePages < MM_HIGH_LIMIT) && ((MmAvailablePages == 0) || (PsGetCurrentThread()->MemoryMaker == 0) && (MiEnsureAvailablePageOrWait (CurrentProcess, OldIrql)))) { // // A wait operation was performed which dropped the locks, // repeat this fault. // if (!PfnLockHeld) { UNLOCK_PFN (OldIrql); } // // Note our caller will delay execution after releasing the // working set mutex in order to make pages available. // return STATUS_NO_MEMORY; } ASSERT (Pfn1->u4.InPageError == 0); if (Pfn1->u3.e1.PageLocation == ActiveAndValid) { // // This page must contain an MmSt allocation of prototype PTEs. // Because these types of pages reside in paged pool (or special // pool) and are part of the system working set, they can be // trimmed at any time regardless of the share count. However, // if the share count is nonzero, then the page state will // remain active and the page will remain in memory - but the // PTE will be set to the transition state. Make the page // valid without incrementing the reference count, but // increment the share count. // ASSERT (((Pfn1->PteAddress >= MiGetPteAddress(MmPagedPoolStart)) && (Pfn1->PteAddress <= MiGetPteAddress(MmPagedPoolEnd))) || ((Pfn1->PteAddress >= MiGetPteAddress(MmSpecialPoolStart)) && (Pfn1->PteAddress <= MiGetPteAddress(MmSpecialPoolEnd)))); // // Don't increment the valid PTE count for the // page table page. // ASSERT (Pfn1->u2.ShareCount != 0); ASSERT (Pfn1->u3.e2.ReferenceCount != 0); } else { MiUnlinkPageFromList (Pfn1); // // Update the PFN database - the reference count must be // incremented as the share count is going to go from zero to 1. // ASSERT (Pfn1->u2.ShareCount == 0); // // The PFN reference count will be 1 already here if the // modified writer has begun a write of this page. Otherwise // it's ordinarily 0. // MI_ADD_LOCKED_PAGE_CHARGE_FOR_MODIFIED_PAGE (Pfn1); } } // // Join with collided page fault code to handle updating // the transition PTE. // ASSERT (Pfn1->u4.InPageError == 0); if (Pfn1->u2.ShareCount == 0) { MI_REMOVE_LOCKED_PAGE_CHARGE (Pfn1); } Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; // // Paged pool is trimmed without regard to sharecounts. // This means a paged pool PTE can be in transition while // the page is still marked active. // // Note this check only needs to be done for system space addresses // as user space address faults lock down the page containing the // prototype PTE entries before processing the fault. // // One example is a system cache fault - the FaultingAddress is a // system cache virtual address, the PointerPte points at the pool // allocation containing the relevant prototype PTEs. This page // may have been trimmed because it isn't locked down during // processing of system space virtual address faults. // if (FaultingAddress >= MmSystemRangeStart) { PointerToPteForProtoPage = MiGetPteAddress (PointerPte); TempPte = *PointerToPteForProtoPage; if ((TempPte.u.Hard.Valid == 0) && (TempPte.u.Soft.Transition == 1)) { PageFrameIndex = MI_GET_PAGE_FRAME_FROM_TRANSITION_PTE (&TempPte); Pfn2 = MI_PFN_ELEMENT (PageFrameIndex); ASSERT ((Pfn2->u3.e1.ReadInProgress == 0) && (Pfn2->u4.InPageError)); ASSERT (Pfn2->u3.e1.PageLocation == ActiveAndValid); ASSERT (((Pfn2->PteAddress >= MiGetPteAddress(MmPagedPoolStart)) && (Pfn2->PteAddress <= MiGetPteAddress(MmPagedPoolEnd))) || ((Pfn2->PteAddress >= MiGetPteAddress(MmSpecialPoolStart)) && (Pfn2->PteAddress <= MiGetPteAddress(MmSpecialPoolEnd)))); // // Don't increment the valid PTE count for the // paged pool page. // ASSERT (Pfn2->u2.ShareCount != 0); ASSERT (Pfn2->u3.e2.ReferenceCount != 0); ASSERT (Pfn2->u3.e1.CacheAttribute == MiCached); // // Ensure the PTE mapping does not conflict with the PFN attributes. // Protection = (MM_PROTECTION_MASK) Pfn2->OriginalPte.u.Soft.Protection; Protection &= ~(MM_NOCACHE | MM_WRITECOMBINE); if (Pfn2->u3.e1.CacheAttribute == MiCached) { NOTHING; } else if (Pfn2->u3.e1.CacheAttribute == MiNonCached) { Protection |= MM_NOCACHE; } else if (Pfn2->u3.e1.CacheAttribute == MiWriteCombined) { Protection |= MM_WRITECOMBINE; } MI_MAKE_VALID_PTE (TempPte, PageFrameIndex, Protection, PointerToPteForProtoPage); MI_WRITE_VALID_PTE (PointerToPteForProtoPage, TempPte); } } MI_MAKE_TRANSITION_PTE_VALID (TempPte, PointerPte); // // If the modified field is set in the PFN database and this // page is not copy on modify, then set the dirty bit. // This can be done as the modified page will not be // written to the paging file until this PTE is made invalid. // if ((Pfn1->u3.e1.Modified && TempPte.u.Hard.Write) && (TempPte.u.Hard.CopyOnWrite == 0)) { MI_SET_PTE_DIRTY (TempPte); } else { MI_SET_PTE_CLEAN (TempPte); } MI_WRITE_VALID_PTE (PointerPte, TempPte); if (!PfnLockHeld) { ASSERT (Pfn1->u3.e1.PrototypePte == 0); UNLOCK_PFN (OldIrql); WorkingSetIndex = MiAddValidPageToWorkingSet (FaultingAddress, PointerPte, Pfn1, 0); if (WorkingSetIndex == 0) { // // Trim the page since we couldn't add it to the working // set list at this time. // MiTrimPte (FaultingAddress, PointerPte, Pfn1, CurrentProcess, ZeroPte); return STATUS_NO_MEMORY; } } return STATUS_PAGE_FAULT_TRANSITION; } NTSTATUS MiResolvePageFileFault ( IN PVOID FaultingAddress, IN PMMPTE PointerPte, OUT PMMPTE CapturedPteContents, OUT PMMINPAGE_SUPPORT *ReadBlock, IN PEPROCESS Process, IN KIRQL OldIrql ) /*++ Routine Description: This routine builds the MDL and other structures to allow a read operation on a page file for a page fault. Arguments: FaultingAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. CapturedPteContents - The contents of the prototype PTE on exit are captured here. This is because the caller needs to compare it later to ensure things haven't changed, but the caller is unable to capture it on return because the caller may be holding the pushlock of a process or session working set (not system) and thus cannot access the prototype PTE since it can be paged as soon as the PFN lock is released by us. Note this only has meaning if the caller is actually going to issue the I/O. ReadBlock - Supplies a pointer to put the address of the read block which needs to be completed before an I/O can be issued. Process - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. OldIrql - Supplies the IRQL the caller acquired the PFN lock at. Return Value: status. A status value of STATUS_ISSUE_PAGING_IO is returned if this function completes successfully. Environment: Kernel mode, PFN lock held. --*/ { PMDL Mdl; ULONG i; PMMPTE BasePte; PMMPTE FaultingPte; PMMPTE CheckPte; PMMPTE FirstPte; PMMPTE LastPte; PSUBSECTION Subsection; ULONG ReadSize; LARGE_INTEGER StartingOffset; PFN_NUMBER PageFrameIndex; PPFN_NUMBER MdlPage; ULONG PageFileNumber; ULONG ClusterSize; ULONG BackwardPageCount; ULONG ForwardPageCount; ULONG MaxForwardPageCount; ULONG MaxBackwardPageCount; WSLE_NUMBER WorkingSetIndex; ULONG PageColor; MMPTE TempPte; MMPTE ComparePte; PMMINPAGE_SUPPORT ReadBlockLocal; PETHREAD CurrentThread; PMMVAD Vad; NTSTATUS Status; PKPRCB Prcb; // ************************************************** // Page File Read // ************************************************** // // Calculate the VBN for the in-page operation. // TempPte = *PointerPte; ASSERT (TempPte.u.Hard.Valid == 0); ASSERT (TempPte.u.Soft.Prototype == 0); ASSERT (TempPte.u.Soft.Transition == 0); MM_PFN_LOCK_ASSERT(); if ((MmAvailablePages < MM_HIGH_LIMIT) && (MiEnsureAvailablePageOrWait (Process, OldIrql))) { // // A wait operation was performed which dropped the locks, // repeat this fault. // UNLOCK_PFN (OldIrql); return STATUS_REFAULT; } ReadBlockLocal = MiGetInPageSupportBlock (OldIrql, &Status); if (ReadBlockLocal == NULL) { UNLOCK_PFN (OldIrql); ASSERT (!NT_SUCCESS (Status)); return Status; } // // Transition collisions rely on the entire PFN (including the event field) // being initialized, the ReadBlockLocal's event being not-signaled, // and the ReadBlockLocal's thread and waitcount being initialized. // // All of this has been done by MiGetInPageSupportBlock already except // the PFN settings. The PFN lock can be safely released once // this is done. // ReadSize = 1; BasePte = NULL; FaultingPte = PointerPte; if (MI_IS_PAGE_TABLE_ADDRESS (PointerPte)) { WorkingSetIndex = 1; } else { WorkingSetIndex = MI_PROTOTYPE_WSINDEX; } // // Capture the desired cluster size. // ClusterSize = MmClusterPageFileReads; ASSERT (ClusterSize <= MM_MAXIMUM_READ_CLUSTER_SIZE); if (MiInPageSinglePages != 0) { MiInPageSinglePages -= 1; } else if ((ClusterSize > 1) && (MmAvailablePages > MM_PLENTY_FREE_LIMIT)) { // // Maybe this condition should be only on free+zeroed pages (ie: don't // include standby). Maybe it should look at the recycle rate of // the standby list, etc, etc. // ASSERT (ClusterSize <= MmAvailablePages); // // Attempt to cluster ahead and behind. // MaxForwardPageCount = PTE_PER_PAGE - (BYTE_OFFSET (PointerPte) / sizeof (MMPTE)); ASSERT (MaxForwardPageCount != 0); MaxBackwardPageCount = PTE_PER_PAGE - MaxForwardPageCount; MaxForwardPageCount -= 1; if (WorkingSetIndex == MI_PROTOTYPE_WSINDEX) { // // This is a pagefile read for a shared memory (prototype PTE) // backed section. Stay within the prototype PTE pool allocation. // // The prototype PTE pool start and end must be carefully // calculated (remember the user's view may be smaller or larger // than this). Don't bother walking the entire VAD tree if it is // very large as this can take a significant amount of time. // if ((FaultingAddress <= MM_HIGHEST_USER_ADDRESS) && (Process->VadRoot.NumberGenericTableElements < 128)) { Vad = MiLocateAddress (FaultingAddress); if (Vad != NULL) { Subsection = MiLocateSubsection (Vad, MI_VA_TO_VPN(FaultingAddress)); if (Subsection != NULL) { FirstPte = &Subsection->SubsectionBase[0]; LastPte = &Subsection->SubsectionBase[Subsection->PtesInSubsection]; if ((ULONG)(LastPte - PointerPte - 1) < MaxForwardPageCount) { MaxForwardPageCount = (ULONG)(LastPte - PointerPte - 1); } if ((ULONG)(PointerPte - FirstPte) < MaxBackwardPageCount) { MaxBackwardPageCount = (ULONG)(PointerPte - FirstPte); } } else { ClusterSize = 0; } } else { ClusterSize = 0; } } else { ClusterSize = 0; } } CurrentThread = PsGetCurrentThread(); if (CurrentThread->ForwardClusterOnly) { MaxBackwardPageCount = 0; if (MaxForwardPageCount == 0) { // // This PTE is the last one in the page table page and // no backwards clustering is enabled for this thread so // no clustering can be done. // ClusterSize = 0; } } if (ClusterSize != 0) { if (MaxForwardPageCount > ClusterSize) { MaxForwardPageCount = ClusterSize; } ComparePte = TempPte; CheckPte = PointerPte + 1; ForwardPageCount = MaxForwardPageCount; // // Try to cluster forward within the page of PTEs. // while (ForwardPageCount != 0) { ASSERT (MiIsPteOnPdeBoundary (CheckPte) == 0); ComparePte.u.Soft.PageFileHigh += 1; if (CheckPte->u.Long != ComparePte.u.Long) { break; } ForwardPageCount -= 1; CheckPte += 1; } ReadSize += (MaxForwardPageCount - ForwardPageCount); // // Try to cluster backward within the page of PTEs. Donate // any unused forward cluster space to the backwards gathering // but keep the entire transfer within the MDL. // ClusterSize -= (MaxForwardPageCount - ForwardPageCount); if (MaxBackwardPageCount > ClusterSize) { MaxBackwardPageCount = ClusterSize; } ComparePte = TempPte; BasePte = PointerPte; CheckPte = PointerPte; BackwardPageCount = MaxBackwardPageCount; while (BackwardPageCount != 0) { ASSERT (MiIsPteOnPdeBoundary(CheckPte) == 0); CheckPte -= 1; ComparePte.u.Soft.PageFileHigh -= 1; if (CheckPte->u.Long != ComparePte.u.Long) { break; } BackwardPageCount -= 1; } ReadSize += (MaxBackwardPageCount - BackwardPageCount); BasePte -= (MaxBackwardPageCount - BackwardPageCount); } } if (ReadSize == 1) { // // Get a page and put the PTE into the transition state with the // read-in-progress flag set. // if (Process == HYDRA_PROCESS) { PageColor = MI_GET_PAGE_COLOR_FROM_SESSION (MmSessionSpace); } else if (Process == NULL) { PageColor = MI_GET_PAGE_COLOR_FROM_VA(FaultingAddress); } else { PageColor = MI_PAGE_COLOR_VA_PROCESS (FaultingAddress, &Process->NextPageColor); } PageFrameIndex = MiRemoveAnyPage (PageColor); MiInitializeReadInProgressSinglePfn (PageFrameIndex, PointerPte, &ReadBlockLocal->Event, WorkingSetIndex); MI_RETRIEVE_USED_PAGETABLE_ENTRIES_FROM_PTE (ReadBlockLocal, &TempPte); } else { Mdl = &ReadBlockLocal->Mdl; MdlPage = &ReadBlockLocal->Page[0]; ASSERT (ReadSize <= MmAvailablePages); for (i = 0; i < ReadSize; i += 1) { // // Get a page and put the PTE into the transition state with the // read-in-progress flag set. // if (Process == HYDRA_PROCESS) { PageColor = MI_GET_PAGE_COLOR_FROM_SESSION (MmSessionSpace); } else if (Process == NULL) { PageColor = MI_GET_PAGE_COLOR_FROM_VA(FaultingAddress); } else { PageColor = MI_PAGE_COLOR_VA_PROCESS (FaultingAddress, &Process->NextPageColor); } *MdlPage = MiRemoveAnyPage (PageColor); MdlPage += 1; } ReadSize *= PAGE_SIZE; // // Note PageFrameIndex is the actual frame that was requested by // this caller. All the other frames will be put in transition // when the inpage completes (provided there are no colliding threads). // MdlPage = &ReadBlockLocal->Page[0]; PageFrameIndex = *(MdlPage + (PointerPte - BasePte)); // // Initialize the MDL for this request. // MmInitializeMdl (Mdl, MiGetVirtualAddressMappedByPte (BasePte), ReadSize); Mdl->MdlFlags |= (MDL_PAGES_LOCKED | MDL_IO_PAGE_READ); // // Set PointerPte and TempPte to the base of the cluster so the // correct starting offset can be calculated below. Note this must // be done before MiInitializeReadInProgressPfn overwrites the PTEs. // PointerPte = BasePte; TempPte = *PointerPte; ASSERT (TempPte.u.Soft.Prototype == 0); ASSERT (TempPte.u.Soft.Transition == 0); // // Put the PTEs into the transition state with the // read-in-progress flag set. // MiInitializeReadInProgressPfn (Mdl, BasePte, &ReadBlockLocal->Event, WorkingSetIndex); MI_ZERO_USED_PAGETABLE_ENTRIES_IN_INPAGE_SUPPORT(ReadBlockLocal); } // // Capture the faulting PTE's contents (it will be in transition now) // prior to releasing the PFN lock. The contents of this prototype PTE // are used by the caller to compare it later to ensure things haven't // changed, but the caller is unable to capture it on return because // the caller may be holding the pushlock of a process or session working // set (not system) and thus cannot access the prototype PTE since it can be // paged as soon as the PFN lock is released here. // // Note this only has meaning if the caller is actually going to issue // the I/O, ie: we must return STATUS_ISSUE_PAGING_IO here. // *CapturedPteContents = *FaultingPte; ASSERT (CapturedPteContents->u.Hard.Valid == 0); ASSERT (CapturedPteContents->u.Soft.Prototype == 0); ASSERT (CapturedPteContents->u.Soft.Transition == 1); UNLOCK_PFN (OldIrql); Prcb = KeGetCurrentPrcb (); InterlockedExchangeAdd (&Prcb->MmPageReadCount, (LONG) (ReadSize >> PAGE_SHIFT)); InterlockedIncrement (&Prcb->MmPageReadIoCount); *ReadBlock = ReadBlockLocal; PageFileNumber = GET_PAGING_FILE_NUMBER (TempPte); StartingOffset.LowPart = GET_PAGING_FILE_OFFSET (TempPte); ASSERT (StartingOffset.LowPart <= MmPagingFile[PageFileNumber]->Size); StartingOffset.HighPart = 0; StartingOffset.QuadPart = StartingOffset.QuadPart << PAGE_SHIFT; ReadBlockLocal->FilePointer = MmPagingFile[PageFileNumber]->File; #if DBG if (((StartingOffset.QuadPart >> PAGE_SHIFT) < 8192) && (PageFileNumber == 0)) { if ((MmPagingFileDebug[StartingOffset.QuadPart >> PAGE_SHIFT] & ~0x1f) != ((ULONG_PTR)PointerPte << 3)) { if ((MmPagingFileDebug[StartingOffset.QuadPart >> PAGE_SHIFT] & ~0x1f) != ((ULONG_PTR)(MiGetPteAddress(FaultingAddress)) << 3)) { DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MMINPAGE: Mismatch PointerPte %p Offset %I64X info %p\n", PointerPte, StartingOffset.QuadPart >> PAGE_SHIFT, MmPagingFileDebug[StartingOffset.QuadPart >> PAGE_SHIFT]); DbgBreakPoint (); } } } #endif //DBG ReadBlockLocal->ReadOffset = StartingOffset; ReadBlockLocal->BasePte = PointerPte; // // Build a single page MDL for the request unless it was a cluster - // clustered MDLs have already been constructed. // if (ReadSize == 1) { MmInitializeMdl (&ReadBlockLocal->Mdl, PAGE_ALIGN(FaultingAddress), PAGE_SIZE); ReadBlockLocal->Mdl.MdlFlags |= (MDL_PAGES_LOCKED | MDL_IO_PAGE_READ); ReadBlockLocal->Page[0] = PageFrameIndex; } ReadBlockLocal->Pfn = MI_PFN_ELEMENT (PageFrameIndex); return STATUS_ISSUE_PAGING_IO; } NTSTATUS MiResolveProtoPteFault ( IN ULONG_PTR StoreInstruction, IN PVOID FaultingAddress, IN PMMPTE PointerPte, IN PMMPTE PointerProtoPte, IN OUT PMMPFN *LockedProtoPfn, OUT PMMINPAGE_SUPPORT *ReadBlock, OUT PMMPTE CapturedPteContents, IN PEPROCESS Process, IN KIRQL OldIrql, IN PVOID TrapInformation ) /*++ Routine Description: This routine resolves a prototype PTE fault. Arguments: StoreInstruction - Supplies nonzero if the instruction is trying to modify the faulting address (i.e. write access required). FaultingAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. PointerProtoPte - Supplies a pointer to the prototype PTE to fault in. LockedProtoPfn - Supplies a non-NULL pointer to the prototype PTE's PFN that was locked down by the caller, or NULL if the caller did not lock down any PFN. This routine may unlock the PFN - if so, it must also clear this pointer. ReadBlock - Supplies a pointer to put the address of the read block which needs to be completed before an I/O can be issued. CapturedPteContents - The contents of the prototype PTE on exit are captured here. This is because the caller needs to compare it later to ensure things haven't changed, but the caller is unable to capture it on return because the caller may be holding the pushlock of a process or session working set (not system) and thus cannot access the prototype PTE since it can be paged as soon as the PFN lock is released by us. Note this only has meaning if the caller is actually going to issue the I/O (ie, this routine must be returning STATUS_ISSUE_PAGING_IO). Process - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. OldIrql - Supplies the IRQL the caller acquired the PFN lock at. TrapInformation - Supplies the trap information. Return Value: NTSTATUS: STATUS_SUCCESS, STATUS_REFAULT, or an I/O status code. Environment: Kernel mode, PFN lock held. --*/ { MMPTE TempPte; MMPTE RealPte; MMPTE NewPte; PFN_NUMBER PageFrameIndex; PMMPFN Pfn1; NTSTATUS status; ULONG CopyOnWrite; LOGICAL PfnHeld; PMMINPAGE_SUPPORT CapturedEvent; // // Note the PFN lock must be held as the routine to locate a working // set entry decrements the share count of PFN elements. // MM_PFN_LOCK_ASSERT (); ASSERT (PointerPte->u.Hard.Valid == 0); ASSERT (PointerPte->u.Soft.Prototype == 1); TempPte = *PointerProtoPte; // // The page containing the prototype PTE is resident, // handle the fault referring to the prototype PTE. // If the prototype PTE is already valid, make this // PTE valid and up the share count etc. // if (TempPte.u.Hard.Valid) { // // Prototype PTE is valid, count this as a transition fault. // PageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (&TempPte); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->u2.ShareCount += 1; InterlockedIncrement (&KeGetCurrentPrcb ()->MmTransitionCount); return MiCompleteProtoPteFault (StoreInstruction, FaultingAddress, PointerPte, PointerProtoPte, OldIrql, LockedProtoPfn); } // // Check to make sure the prototype PTE is committed. // if (TempPte.u.Long == 0) { MI_BREAK_ON_AV (FaultingAddress, 0xA); UNLOCK_PFN (OldIrql); return STATUS_ACCESS_VIOLATION; } CapturedEvent = NULL; // // If the PTE indicates that the protection field to be // checked is in the prototype PTE, check it now. // CopyOnWrite = FALSE; RealPte = *PointerPte; if (RealPte.u.Soft.PageFileHigh != MI_PTE_LOOKUP_NEEDED) { if (RealPte.u.Proto.ReadOnly == 0) { // // Check for kernel mode access, we have already verified // that the user has access to the virtual address. // status = MiAccessCheck (PointerProtoPte, StoreInstruction, KernelMode, MI_GET_PROTECTION_FROM_SOFT_PTE (&TempPte), TrapInformation, TRUE); if (status != STATUS_SUCCESS) { if ((StoreInstruction) && (MI_IS_SESSION_ADDRESS (FaultingAddress)) && (MmSessionSpace->ImageLoadingCount != 0)) { PLIST_ENTRY NextEntry; PIMAGE_ENTRY_IN_SESSION Image; NextEntry = MmSessionSpace->ImageList.Flink; while (NextEntry != &MmSessionSpace->ImageList) { Image = CONTAINING_RECORD (NextEntry, IMAGE_ENTRY_IN_SESSION, Link); if ((FaultingAddress >= Image->Address) && (FaultingAddress <= Image->LastAddress)) { if (Image->ImageLoading) { // // Temporarily allow the write so that // relocations and import snaps can be // completed. // // Even though the page's current backing // is the image file, the modified writer // will convert it to pagefile backing // when it notices the change later. // goto done; } break; } NextEntry = NextEntry->Flink; } } MI_BREAK_ON_AV (FaultingAddress, 9); UNLOCK_PFN (OldIrql); return status; } if ((TempPte.u.Soft.Protection & MM_COPY_ON_WRITE_MASK) == MM_COPY_ON_WRITE_MASK) { CopyOnWrite = TRUE; } } } else { if ((RealPte.u.Soft.Protection & MM_COPY_ON_WRITE_MASK) == MM_COPY_ON_WRITE_MASK) { CopyOnWrite = TRUE; } } // // If the fault is in user space and this is a cloned process then // don't take the optimized demand zero copy on write path as we // want to go the long way so the clone block can be properly // decremented in MiCopyOnWrite. // if ((PointerPte <= MiHighestUserPte) && (Process > PREFETCH_PROCESS) && (Process->CloneRoot != NULL)) { CopyOnWrite = FALSE; } done: if ((!IS_PTE_NOT_DEMAND_ZERO (TempPte)) && (CopyOnWrite)) { // // The prototype PTE is demand zero and copy on // write. Make this PTE a private demand zero PTE. // ASSERT (Process != NULL); UNLOCK_PFN (OldIrql); NewPte.u.Long = MM_DEMAND_ZERO_WRITE_PTE; ASSERT (RealPte.u.Hard.Valid == 0); if (RealPte.u.Soft.PageFileHigh != MI_PTE_LOOKUP_NEEDED) { // // Get the protection from the prototype PTE. // if (TempPte.u.Soft.Protection & MM_EXECUTE) { NewPte.u.Long = (MM_EXECUTE_READWRITE << MM_PROTECT_FIELD_SHIFT); } } else { // // The prototype PTE protection has been overridden by the // protection in the real PTE. // if (RealPte.u.Soft.Protection & MM_EXECUTE) { NewPte.u.Long = (MM_EXECUTE_READWRITE << MM_PROTECT_FIELD_SHIFT); } } MI_WRITE_INVALID_PTE (PointerPte, NewPte); status = MiResolveDemandZeroFault (FaultingAddress, PointerPte, Process, MM_NOIRQL); return status; } // // Make the prototype PTE valid, the prototype PTE is in // one of these 4 states: // // demand zero // transition // paging file // mapped file // if (TempPte.u.Soft.Prototype == 1) { // // Mapped File. // status = MiResolveMappedFileFault (PointerProtoPte, ReadBlock, Process, OldIrql); if (status == STATUS_ISSUE_PAGING_IO) { *CapturedPteContents = *PointerProtoPte; ASSERT (CapturedPteContents->u.Hard.Valid == 0); ASSERT (CapturedPteContents->u.Soft.Prototype == 0); ASSERT (CapturedPteContents->u.Soft.Transition == 1); } // // Returns with PFN lock held. // PfnHeld = TRUE; } else if (TempPte.u.Soft.Transition == 1) { // // Transition. // ASSERT (OldIrql != MM_NOIRQL); status = MiResolveTransitionFault (FaultingAddress, PointerProtoPte, Process, OldIrql, &CapturedEvent); // // Returns with PFN lock held. // PfnHeld = TRUE; } else if (TempPte.u.Soft.PageFileHigh == 0) { // // Demand Zero. // ASSERT (OldIrql != MM_NOIRQL); status = MiResolveDemandZeroFault (FaultingAddress, PointerProtoPte, Process, OldIrql); // // Returns with PFN lock held. // PfnHeld = TRUE; } else { // // Paging file. // status = MiResolvePageFileFault (FaultingAddress, PointerProtoPte, CapturedPteContents, ReadBlock, Process, OldIrql); #if DBG if (status == STATUS_ISSUE_PAGING_IO) { ASSERT (CapturedPteContents->u.Hard.Valid == 0); ASSERT (CapturedPteContents->u.Soft.Prototype == 0); ASSERT (CapturedPteContents->u.Soft.Transition == 1); } #endif // // Returns with PFN lock released. // ASSERT (KeAreAllApcsDisabled () == TRUE); PfnHeld = FALSE; } if (NT_SUCCESS (status)) { ASSERT (PointerPte->u.Hard.Valid == 0); status = MiCompleteProtoPteFault (StoreInstruction, FaultingAddress, PointerPte, PointerProtoPte, OldIrql, LockedProtoPfn); if (CapturedEvent != NULL) { MiFreeInPageSupportBlock (CapturedEvent); } } else { if (PfnHeld == TRUE) { UNLOCK_PFN (OldIrql); } ASSERT (KeAreAllApcsDisabled () == TRUE); if (CapturedEvent != NULL) { MiFreeInPageSupportBlock (CapturedEvent); } } return status; } NTSTATUS MiCompleteProtoPteFault ( IN ULONG_PTR StoreInstruction, IN PVOID FaultingAddress, IN PMMPTE PointerPte, IN PMMPTE PointerProtoPte, IN KIRQL OldIrql, IN OUT PMMPFN *LockedProtoPfn ) /*++ Routine Description: This routine completes a prototype PTE fault. It is invoked after a read operation has completed bringing the data into memory. Arguments: StoreInstruction - Supplies nonzero if the instruction is trying to modify the faulting address (i.e. write access required). FaultingAddress - Supplies the faulting address. PointerPte - Supplies the PTE for the faulting address. PointerProtoPte - Supplies a pointer to the prototype PTE to fault in, NULL if no prototype PTE exists. OldIrql - Supplies the IRQL the caller acquired the PFN lock at. LockedProtoPfn - Supplies a pointer to a non-NULL prototype PTE's PFN pointer that was locked down by the caller, or a pointer to NULL if the caller did not lock down any PFN. This routine may unlock the PFN - if so, it must also clear this pointer. Return Value: NTSTATUS. Environment: Kernel mode, PFN lock held. --*/ { NTSTATUS Status; ULONG FreeBit; MMPTE TempPte; MMPTE ProtoPteContents; MMPTE OriginalPte; MMWSLE ProtoProtect; LOGICAL SameProtectAsProto; ULONG MarkPageDirty; PFN_NUMBER PageFrameIndex; PMMPFN Pfn1; PMMPFN Pfn2; PMMPTE ContainingPageTablePointer; PFILE_OBJECT FileObject; LONGLONG FileOffset; PSUBSECTION Subsection; MMSECTION_FLAGS ControlAreaFlags; ULONG Flags; WSLE_NUMBER WorkingSetIndex; PEPROCESS CurrentProcess; MM_PROTECTION_MASK Protection; MM_PFN_LOCK_ASSERT(); ASSERT (PointerProtoPte->u.Hard.Valid == 1); ProtoPteContents.u.Long = PointerProtoPte->u.Long; PageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (&ProtoPteContents); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->u3.e1.PrototypePte = 1; // // Capture prefetch fault information. // OriginalPte = Pfn1->OriginalPte; // // Prototype PTE is now valid, make the PTE valid. // // A PTE just went from not present, not transition to // present. The share count and valid count must be // updated in the page table page which contains this PTE. // ContainingPageTablePointer = MiGetPteAddress (PointerPte); Pfn2 = MI_PFN_ELEMENT (ContainingPageTablePointer->u.Hard.PageFrameNumber); Pfn2->u2.ShareCount += 1; ProtoProtect.u1.Long = 0; if (PointerPte->u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED) { // // The protection code for the real PTE comes from the real PTE as // it was placed there earlier during the handling of this fault. // ProtoProtect.u1.e1.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE (PointerPte); SameProtectAsProto = FALSE; } else { // // Use the protection in the prototype PTE to initialize the real PTE. // ProtoProtect.u1.e1.Protection = MI_GET_PROTECTION_FROM_SOFT_PTE (&OriginalPte); SameProtectAsProto = TRUE; MI_ASSERT_NOT_SESSION_DATA (PointerPte); if ((StoreInstruction != 0) && ((ProtoProtect.u1.e1.Protection & MM_PROTECTION_WRITE_MASK) == 0)) { // // This is the errant case where the user is trying to write // to a readonly subsection in the image. Since we're more than // halfway through the fault, take the easy way to clean this up - // treat the access as a read for the rest of this trip through // the fault. We'll then immediately refault when the instruction // is rerun (because it's really a write), and then we'll notice // that the user's PTE is not copy-on-write (or even writable!) // and return a clean access violation. // StoreInstruction = 0; } } MI_SNAP_DATA (Pfn1, PointerProtoPte, 0xD); MarkPageDirty = 0; // // If this is a store instruction and the page is not copy on // write, then set the modified bit in the PFN database and // the dirty bit in the PTE. The PTE is not set dirty even // if the modified bit is set so writes to the page can be // tracked for FlushVirtualMemory. // if ((StoreInstruction != 0) && ((ProtoProtect.u1.e1.Protection & MM_COPY_ON_WRITE_MASK) != MM_COPY_ON_WRITE_MASK)) { MarkPageDirty = 1; #if DBG if (OriginalPte.u.Soft.Prototype == 1) { PCONTROL_AREA ControlArea; Subsection = MiGetSubsectionAddress (&OriginalPte); ControlArea = Subsection->ControlArea; if (ControlArea->DereferenceList.Flink != NULL) { DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MM: page fault completing to dereferenced CA %p %p %p\n", ControlArea, Pfn1, PointerPte); DbgBreakPoint (); } } #endif MI_SET_MODIFIED (Pfn1, 1, 0xA); if ((OriginalPte.u.Soft.Prototype == 0) && (Pfn1->u3.e1.WriteInProgress == 0)) { FreeBit = GET_PAGING_FILE_OFFSET (OriginalPte); if ((FreeBit != 0) && (FreeBit != MI_PTE_LOOKUP_NEEDED)) { MiReleaseConfirmedPageFileSpace (OriginalPte); } Pfn1->OriginalPte.u.Soft.PageFileHigh = 0; } } if (*LockedProtoPfn != NULL) { // // Unlock page containing prototype PTEs. // // The reference count on the prototype PTE page will // always be greater than 1 if it is a genuine prototype // PTE pool allocation. However, if it is a fork // prototype PTE allocation, it is possible the pool has // already been deallocated and in this case, the LockedProtoPfn // frame below will be in transition limbo with a share // count of 0 and a reference count of 1 awaiting our // final dereference below which will put it on the free list. // ASSERT ((*LockedProtoPfn)->u3.e2.ReferenceCount >= 1); MI_REMOVE_LOCKED_PAGE_CHARGE_AND_DECREF (*LockedProtoPfn); // // Tell our caller we've unlocked it for him. // *LockedProtoPfn = NULL; } UNLOCK_PFN (OldIrql); // // Ensure the user's attributes do not conflict with the PFN attributes. // Protection = (MM_PROTECTION_MASK) ProtoProtect.u1.e1.Protection; Protection &= ~(MM_NOCACHE | MM_WRITECOMBINE); if (Pfn1->u3.e1.CacheAttribute == MiCached) { NOTHING; } else if (Pfn1->u3.e1.CacheAttribute == MiNonCached) { Protection |= MM_NOCACHE; } else if (Pfn1->u3.e1.CacheAttribute == MiWriteCombined) { Protection |= MM_WRITECOMBINE; } if (FaultingAddress < MmSystemRangeStart) { MI_MAKE_VALID_USER_PTE (TempPte, PageFrameIndex, Protection, PointerPte); } else { // // Might be system or session, so go the long way to find out. // MI_MAKE_VALID_PTE (TempPte, PageFrameIndex, Protection, PointerPte); } if (MarkPageDirty != 0) { MI_SET_PTE_DIRTY (TempPte); } MI_WRITE_VALID_PTE (PointerPte, TempPte); if (SameProtectAsProto == TRUE) { ProtoProtect.u1.e1.Protection = MM_ZERO_ACCESS; } WorkingSetIndex = MiAddValidPageToWorkingSet (FaultingAddress, PointerPte, Pfn1, (ULONG) ProtoProtect.u1.Long); if (WorkingSetIndex == 0) { if (SameProtectAsProto == FALSE) { // // The protection for the prototype PTE is in the WSLE. // ASSERT (ProtoProtect.u1.e1.Protection != MM_ZERO_ACCESS); TempPte.u.Long = 0; TempPte.u.Soft.Protection = MI_GET_PROTECTION_FROM_WSLE (&ProtoProtect); TempPte.u.Soft.PageFileHigh = MI_PTE_LOOKUP_NEEDED; } else { // // The protection is in the prototype PTE. // TempPte.u.Long = MiProtoAddressForPte (Pfn1->PteAddress); } TempPte.u.Proto.Prototype = 1; // // Trim the page since we couldn't add it to the working // set list at this time. // if (FaultingAddress < MmSystemRangeStart) { CurrentProcess = PsGetCurrentProcess (); } else if ((MI_IS_SESSION_ADDRESS (FaultingAddress)) || (MI_IS_SESSION_PTE (FaultingAddress))) { CurrentProcess = HYDRA_PROCESS; } else { CurrentProcess = NULL; } MiTrimPte (FaultingAddress, PointerPte, Pfn1, CurrentProcess, TempPte); Status = STATUS_NO_MEMORY; } else { Status = STATUS_SUCCESS; } // // Log prefetch fault information now that the PFN lock has been released // and the PTE has been made valid. This minimizes PFN lock contention, // allows CcPfLogPageFault to allocate (and fault on) pool, and allows other // threads in this process to execute without faulting on this address. // // Note that the process' working set mutex is still held so any other // faults or operations on user addresses by other threads in this process // will block for the duration of this call. // if ((CCPF_IS_PREFETCHER_ACTIVE()) && (OriginalPte.u.Soft.Prototype == 1)) { Subsection = MiGetSubsectionAddress (&OriginalPte); FileObject = Subsection->ControlArea->FilePointer; FileOffset = MiStartingOffset (Subsection, PointerProtoPte); ControlAreaFlags = Subsection->ControlArea->u.Flags; Flags = 0; if (ControlAreaFlags.Image) { Flags |= CCPF_TYPE_IMAGE; } if (ControlAreaFlags.Rom) { Flags |= CCPF_TYPE_ROM; } CcPfLogPageFault (FileObject, FileOffset, Flags); } ASSERT (PointerPte == MiGetPteAddress (FaultingAddress)); return Status; } NTSTATUS MiResolveMappedFileFault ( IN PMMPTE PointerPte, OUT PMMINPAGE_SUPPORT *ReadBlock, IN PEPROCESS Process, IN KIRQL OldIrql ) /*++ Routine Description: This routine builds the MDL and other structures to allow a read operation on a mapped file for a page fault. Arguments: PointerPte - Supplies the PTE for the faulting address. ReadBlock - Supplies a pointer to put the address of the read block which needs to be completed before an I/O can be issued. Process - Supplies a pointer to the process object. If this parameter is NULL, then the fault is for system space and the process's working set lock is not held. OldIrql - Supplies the IRQL the caller acquired the PFN lock at. Return Value: status. A status value of STATUS_ISSUE_PAGING_IO is returned if this function completes successfully. Environment: Kernel mode, PFN lock held. --*/ { PFN_NUMBER PageFrameIndex; PMMPFN Pfn1; PSUBSECTION Subsection; PCONTROL_AREA ControlArea; PMDL Mdl; ULONG ReadSize; PETHREAD CurrentThread; PPFN_NUMBER Page; PPFN_NUMBER EndPage; PMMPTE BasePte; PMMPTE CheckPte; LARGE_INTEGER StartingOffset; LARGE_INTEGER TempOffset; PPFN_NUMBER FirstMdlPage; PMMINPAGE_SUPPORT ReadBlockLocal; ULONG PageColor; ULONG ClusterSize; PFN_NUMBER AvailablePages; NTSTATUS Status; PKPRCB Prcb; ClusterSize = 0; ASSERT (PointerPte->u.Soft.Prototype == 1); // ********************************************* // Mapped File (subsection format) // ********************************************* if ((MmAvailablePages < MM_HIGH_LIMIT) && (MiEnsureAvailablePageOrWait (Process, OldIrql))) { // // A wait operation was performed which dropped the locks, // repeat this fault. // return STATUS_REFAULT; } // // Calculate address of subsection for this prototype PTE. // Subsection = MiGetSubsectionAddress (PointerPte); ControlArea = Subsection->ControlArea; if (ControlArea->u.Flags.FailAllIo) { return STATUS_IN_PAGE_ERROR; } if (PointerPte >= &Subsection->SubsectionBase[Subsection->PtesInSubsection]) { // // Attempt to read past the end of this subsection. // return STATUS_ACCESS_VIOLATION; } ASSERT (ControlArea->u.Flags.Rom != 1); CurrentThread = PsGetCurrentThread (); ReadBlockLocal = MiGetInPageSupportBlock (OldIrql, &Status); if (ReadBlockLocal == NULL) { ASSERT (!NT_SUCCESS (Status)); return Status; } *ReadBlock = ReadBlockLocal; // // Build an MDL for the request. // Mdl = &ReadBlockLocal->Mdl; FirstMdlPage = &ReadBlockLocal->Page[0]; Page = FirstMdlPage; #if DBG RtlFillMemoryUlong (Page, (MM_MAXIMUM_READ_CLUSTER_SIZE+1) * sizeof(PFN_NUMBER), 0xf1f1f1f1); #endif //DBG ReadSize = PAGE_SIZE; BasePte = PointerPte; // // Should we attempt to perform page fault clustering? // AvailablePages = MmAvailablePages; if (MiInPageSinglePages != 0) { AvailablePages = 0; MiInPageSinglePages -= 1; } if ((!CurrentThread->DisablePageFaultClustering) && (ControlArea->u.Flags.NoModifiedWriting == 0)) { if ((AvailablePages > (MmFreeGoal * 2)) || (((ControlArea->u.Flags.Image != 0) || (CurrentThread->ForwardClusterOnly)) && (AvailablePages > MM_HIGH_LIMIT))) { // // Cluster up to n pages. This one + n-1. // ASSERT (MM_HIGH_LIMIT > MM_MAXIMUM_READ_CLUSTER_SIZE + 16); ASSERT (AvailablePages > MM_MAXIMUM_READ_CLUSTER_SIZE + 16); if (ControlArea->u.Flags.Image == 0) { ASSERT (CurrentThread->ReadClusterSize <= MM_MAXIMUM_READ_CLUSTER_SIZE); ClusterSize = CurrentThread->ReadClusterSize; } else { ClusterSize = MmDataClusterSize; if (Subsection->u.SubsectionFlags.Protection & MM_PROTECTION_EXECUTE_MASK ) { ClusterSize = MmCodeClusterSize; } } EndPage = Page + ClusterSize; CheckPte = PointerPte + 1; // // Try to cluster within the page of PTEs. // while ((MiIsPteOnPdeBoundary(CheckPte) == 0) && (Page < EndPage) && (CheckPte < &Subsection->SubsectionBase[Subsection->PtesInSubsection]) && (CheckPte->u.Long == BasePte->u.Long)) { ControlArea->NumberOfPfnReferences += 1; ReadSize += PAGE_SIZE; Page += 1; CheckPte += 1; } if ((Page < EndPage) && (!CurrentThread->ForwardClusterOnly)) { // // Attempt to cluster going backwards from the PTE. // CheckPte = PointerPte - 1; while ((((ULONG_PTR)CheckPte & (PAGE_SIZE - 1)) != (PAGE_SIZE - sizeof(MMPTE))) && (Page < EndPage) && (CheckPte >= Subsection->SubsectionBase) && (CheckPte->u.Long == BasePte->u.Long)) { ControlArea->NumberOfPfnReferences += 1; ReadSize += PAGE_SIZE; Page += 1; CheckPte -= 1; } BasePte = CheckPte + 1; } } } // // // Calculate the offset to read into the file. // offset = base + ((thispte - basepte) << PAGE_SHIFT) // StartingOffset.QuadPart = MiStartingOffset (Subsection, BasePte); TempOffset = MiEndingOffset (Subsection); ASSERT (StartingOffset.QuadPart < TempOffset.QuadPart); // // Remove pages to fill in the MDL. This is done here as the // base PTE has been determined and can be used for virtual // aliasing checks. // EndPage = FirstMdlPage; CheckPte = BasePte; while (EndPage < Page) { if (Process == HYDRA_PROCESS) { PageColor = MI_GET_PAGE_COLOR_FROM_SESSION (MmSessionSpace); } else if (Process == NULL) { PageColor = MI_GET_PAGE_COLOR_FROM_PTE (CheckPte); } else { PageColor = MI_PAGE_COLOR_PTE_PROCESS (CheckPte, &Process->NextPageColor); } *EndPage = MiRemoveAnyPage (PageColor); EndPage += 1; CheckPte += 1; } if (Process == HYDRA_PROCESS) { PageColor = MI_GET_PAGE_COLOR_FROM_SESSION (MmSessionSpace); } else if (Process == NULL) { PageColor = MI_GET_PAGE_COLOR_FROM_PTE (CheckPte); } else { PageColor = MI_PAGE_COLOR_PTE_PROCESS (CheckPte, &Process->NextPageColor); } // // Check to see if the read will go past the end of the file, // If so, correct the read size and get a zeroed page. // Prcb = KeGetCurrentPrcb (); InterlockedIncrement (&Prcb->MmPageReadIoCount); InterlockedExchangeAdd (&Prcb->MmPageReadCount, (LONG) (ReadSize >> PAGE_SHIFT)); if ((ControlArea->u.Flags.Image) && (((UINT64)StartingOffset.QuadPart + ReadSize) > (UINT64)TempOffset.QuadPart)) { ASSERT ((ULONG)(TempOffset.QuadPart - StartingOffset.QuadPart) > (ReadSize - PAGE_SIZE)); ReadSize = (ULONG)(TempOffset.QuadPart - StartingOffset.QuadPart); // // Round the offset to a 512-byte offset as this will help filesystems // optimize the transfer. Note that filesystems will always zero fill // the remainder between VDL and the next 512-byte multiple and we have // already zeroed the whole page. // ReadSize = ((ReadSize + MMSECTOR_MASK) & ~MMSECTOR_MASK); PageFrameIndex = MiRemoveZeroPage (PageColor); } else { // // We are reading a complete page, no need to get a zeroed page. // PageFrameIndex = MiRemoveAnyPage (PageColor); } // // Increment the PFN reference count in the control area for // the subsection (the PFN lock is required to modify this field). // ControlArea->NumberOfPfnReferences += 1; *Page = PageFrameIndex; PageFrameIndex = *(FirstMdlPage + (PointerPte - BasePte)); // // Get a page and put the PTE into the transition state with the // read-in-progress flag set. // Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); // // Initialize MDL for request. // MmInitializeMdl (Mdl, MiGetVirtualAddressMappedByPte (BasePte), ReadSize); Mdl->MdlFlags |= (MDL_PAGES_LOCKED | MDL_IO_PAGE_READ); #if DBG if (ReadSize > ((ClusterSize + 1) << PAGE_SHIFT)) { KeBugCheckEx (MEMORY_MANAGEMENT, 0x777,(ULONG_PTR)Mdl, (ULONG_PTR)Subsection, (ULONG)TempOffset.LowPart); } #endif //DBG MiInitializeReadInProgressPfn (Mdl, BasePte, &ReadBlockLocal->Event, MI_PROTOTYPE_WSINDEX); MI_ZERO_USED_PAGETABLE_ENTRIES_IN_INPAGE_SUPPORT(ReadBlockLocal); ReadBlockLocal->ReadOffset = StartingOffset; ReadBlockLocal->FilePointer = ControlArea->FilePointer; ReadBlockLocal->BasePte = BasePte; ReadBlockLocal->Pfn = Pfn1; return STATUS_ISSUE_PAGING_IO; } NTSTATUS MiWaitForInPageComplete ( IN PMMPFN Pfn2, IN PMMPTE PointerPte, IN PVOID FaultingAddress, IN PMMPTE PointerPteContents, IN PMMINPAGE_SUPPORT InPageSupport, IN PEPROCESS CurrentProcess ) /*++ Routine Description: Waits for a page read to complete. Arguments: Pfn - Supplies a pointer to the PFN element for the page being read. PointerPte - Supplies a pointer to the PTE that is in the transition state. This can be a prototype PTE address. FaultingAddress - Supplies the faulting address. PointerPteContents - Supplies the contents of the PTE before the working set lock was released. InPageSupport - Supplies a pointer to the inpage support structure for this read operation. Return Value: Returns the status of the inpage operation. Note that the working set mutex and PFN lock are held upon return !!! Environment: Kernel mode, APCs disabled. Neither the working set lock nor the PFN lock may be held. --*/ { PMMVAD ProtoVad; PMMPTE NewPointerPte; PMMPTE ProtoPte; PMMPFN Pfn1; PMMPFN Pfn; PULONG Va; PPFN_NUMBER Page; PPFN_NUMBER LastPage; ULONG Offset; ULONG Protection; PMDL Mdl; KIRQL OldIrql; NTSTATUS status; NTSTATUS status2; PEPROCESS Process; PETHREAD Thread; Thread = PsGetCurrentThread (); // // Wait for the I/O to complete. Note that we can't wait for all // the objects simultaneously as other threads/processes could be // waiting for the same event. The first thread which completes // the wait and gets the PFN lock may reuse the event for another // fault before this thread completes its wait. // KeWaitForSingleObject( &InPageSupport->Event, WrPageIn, KernelMode, FALSE, NULL); if (CurrentProcess == HYDRA_PROCESS) { LOCK_WORKING_SET (Thread, &MmSessionSpace->GlobalVirtualAddress->Vm); } else if (CurrentProcess == PREFETCH_PROCESS) { NOTHING; } else if (CurrentProcess != NULL) { LOCK_WS (Thread, CurrentProcess); } else { LOCK_SYSTEM_WS (Thread); } LOCK_PFN (OldIrql); ASSERT (Pfn2->u3.e2.ReferenceCount != 0); // // Check to see if this is the first thread to complete the in-page // operation. // Pfn = InPageSupport->Pfn; if (Pfn2 != Pfn) { ASSERT (Pfn2->u4.PteFrame != MI_MAGIC_AWE_PTEFRAME); Pfn2->u3.e1.ReadInProgress = 0; } // // Another thread has already serviced the read, check the // io-error flag in the PFN database to ensure the in-page // was successful. // if (Pfn2->u4.InPageError == 1) { ASSERT (!NT_SUCCESS(Pfn2->u1.ReadStatus)); if (MmIsRetryIoStatus(Pfn2->u1.ReadStatus)) { return STATUS_REFAULT; } return Pfn2->u1.ReadStatus; } if (InPageSupport->u1.e1.Completed == 0) { // // The ReadInProgress bit for the dummy page is constantly cleared // below as there are generally multiple inpage blocks pointing to // the same dummy page. // ASSERT ((Pfn->u3.e1.ReadInProgress == 1) || (Pfn->PteAddress == MI_PF_DUMMY_PAGE_PTE)); InPageSupport->u1.e1.Completed = 1; Mdl = &InPageSupport->Mdl; if (InPageSupport->u1.e1.PrefetchMdlHighBits != 0) { // // This is a prefetcher-issued read. // Mdl = MI_EXTRACT_PREFETCH_MDL (InPageSupport); } if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) { MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl); } ASSERT (Pfn->u4.PteFrame != MI_MAGIC_AWE_PTEFRAME); Pfn->u3.e1.ReadInProgress = 0; Pfn->u1.Event = NULL; #if defined (_WIN64) // // Page directory and page table pages are never clustered, // ensure this is never violated as only one UsedPageTableEntries // is kept in the inpage support block. // if (InPageSupport->UsedPageTableEntries) { Page = (PPFN_NUMBER)(Mdl + 1); LastPage = Page + ((Mdl->ByteCount - 1) >> PAGE_SHIFT); ASSERT (Page == LastPage); } #endif MI_INSERT_USED_PAGETABLE_ENTRIES_IN_PFN(Pfn, InPageSupport); // // Check the IO_STATUS_BLOCK to ensure the in-page completed successfully. // if (!NT_SUCCESS(InPageSupport->IoStatus.Status)) { if (InPageSupport->IoStatus.Status == STATUS_END_OF_FILE) { // // An attempt was made to read past the end of file // zero all the remaining bytes in the read. // if (Pfn->OriginalPte.u.Soft.Prototype == 0) { // // Something is very wrong for this to happen on a pagefile // read. // KeBugCheckEx (KERNEL_DATA_INPAGE_ERROR, 3, (ULONG_PTR) FaultingAddress, (ULONG_PTR) InPageSupport, 0); } Page = (PPFN_NUMBER)(Mdl + 1); LastPage = Page + ((Mdl->ByteCount - 1) >> PAGE_SHIFT); while (Page <= LastPage) { MiZeroPhysicalPage (*Page); MI_ZERO_USED_PAGETABLE_ENTRIES_IN_PFN(MI_PFN_ELEMENT(*Page)); Page += 1; } } else { // // In page io error occurred. // status = InPageSupport->IoStatus.Status; status2 = InPageSupport->IoStatus.Status; if (status != STATUS_VERIFY_REQUIRED) { LOGICAL Retry; Retry = FALSE; #if DBG DbgPrintEx (DPFLTR_MM_ID, DPFLTR_INFO_LEVEL, "MM: inpage I/O error %X\n", InPageSupport->IoStatus.Status); #endif // // If this page is for paged pool or for paged // kernel code or page table pages, bugcheck. // if ((FaultingAddress > MM_HIGHEST_USER_ADDRESS) && (!MI_IS_SYSTEM_CACHE_ADDRESS(FaultingAddress))) { if (MmIsRetryIoStatus(status)) { if (MiInPageSinglePages == 0) { MiInPageSinglePages = 30; } MiFaultRetries -= 1; if (MiFaultRetries & MiFaultRetryMask) { Retry = TRUE; } } if (Retry == FALSE) { ULONG_PTR PteContents; // // The prototype PTE resides in paged pool which may // not be resident at this point. Check first. // if (MiIsAddressValid (PointerPte, FALSE) == TRUE) { PteContents = *(PULONG_PTR)PointerPte; } else { PteContents = (ULONG_PTR)-1; } KeBugCheckEx (KERNEL_DATA_INPAGE_ERROR, (ULONG_PTR)PointerPte, status, (ULONG_PTR)FaultingAddress, PteContents); } status2 = STATUS_REFAULT; } else { if (MmIsRetryIoStatus(status)) { if (MiInPageSinglePages == 0) { MiInPageSinglePages = 30; } MiUserFaultRetries -= 1; if (MiUserFaultRetries & MiUserFaultRetryMask) { Retry = TRUE; } } if (Retry == TRUE) { status2 = STATUS_REFAULT; } } } Page = (PPFN_NUMBER)(Mdl + 1); LastPage = Page + ((Mdl->ByteCount - 1) >> PAGE_SHIFT); #if DBG Process = PsGetCurrentProcess (); #endif while (Page <= LastPage) { Pfn1 = MI_PFN_ELEMENT (*Page); ASSERT (Pfn1->u3.e2.ReferenceCount != 0); Pfn1->u4.InPageError = 1; Pfn1->u1.ReadStatus = status; #if DBG Va = (PULONG)MiMapPageInHyperSpaceAtDpc (Process, *Page); RtlFillMemoryUlong (Va, PAGE_SIZE, 0x50444142); MiUnmapPageInHyperSpaceFromDpc (Process, Va); #endif Page += 1; } return status2; } } else { MiFaultRetries = 0; MiUserFaultRetries = 0; if (InPageSupport->IoStatus.Information != Mdl->ByteCount) { ASSERT (InPageSupport->IoStatus.Information != 0); // // Less than a full page was read - zero the remainder // of the page if the page is filesystem backed (this can // be legitimate as we are reading whole pages and the // end of file may not be page aligned. // // However, if the page is pagefile backed, then this // underreading is a fatal driver error - and it would // would be a mistake to zero trailing portions of pages // to hide that. // if (Pfn->OriginalPte.u.Soft.Prototype == 0) { KeBugCheckEx (KERNEL_DATA_INPAGE_ERROR, 4, (ULONG_PTR) FaultingAddress, (ULONG_PTR) InPageSupport, 0); } Page = (PPFN_NUMBER)(Mdl + 1); LastPage = Page + ((Mdl->ByteCount - 1) >> PAGE_SHIFT); Page += ((InPageSupport->IoStatus.Information - 1) >> PAGE_SHIFT); Offset = BYTE_OFFSET (InPageSupport->IoStatus.Information); if (Offset != 0) { Process = PsGetCurrentProcess (); Va = (PULONG)((PCHAR)MiMapPageInHyperSpaceAtDpc (Process, *Page) + Offset); RtlZeroMemory (Va, PAGE_SIZE - Offset); MiUnmapPageInHyperSpaceFromDpc (Process, Va); } // // Zero any remaining pages within the MDL. // Page += 1; while (Page <= LastPage) { MiZeroPhysicalPage (*Page); Page += 1; } } // // If any filesystem return non-zeroed data for any slop // after the VDL but before the next 512-byte offset then this // non-zeroed data will overwrite our zeroed page. This would // need to be checked for and cleaned up here. Note that the only // reason Mm even rounds the MDL request up to a 512-byte offset // is so filesystems receive a transfer they can handle optimally, // but any transfer size has always worked (although non-512 byte // multiples end up getting posted by the filesystem). // } } // // Prefetcher-issued reads only put prototype PTEs into transition and // never fill actual hardware PTEs so these can be returned now. // if (CurrentProcess == PREFETCH_PROCESS) { return STATUS_SUCCESS; } // // Check to see if the faulting PTE has changed. // NewPointerPte = MiFindActualFaultingPte (FaultingAddress); // // If this PTE is in prototype PTE format, make the pointer to the // PTE point to the prototype PTE. // if (NewPointerPte == NULL) { return STATUS_PTE_CHANGED; } if (NewPointerPte != PointerPte) { // // Check to make sure the NewPointerPte is not a prototype PTE // which refers to the page being made valid. // if (NewPointerPte->u.Soft.Prototype == 1) { if (NewPointerPte->u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED) { ProtoPte = MiCheckVirtualAddress (FaultingAddress, &Protection, &ProtoVad); } else { ProtoPte = MiPteToProto (NewPointerPte); } // // Make sure the prototype PTE refers to the PTE made valid. // if (ProtoPte != PointerPte) { return STATUS_PTE_CHANGED; } // // If the only difference is the owner mask, everything is okay. // if (ProtoPte->u.Long != PointerPteContents->u.Long) { return STATUS_PTE_CHANGED; } } else { return STATUS_PTE_CHANGED; } } else { if (NewPointerPte->u.Long != PointerPteContents->u.Long) { return STATUS_PTE_CHANGED; } } return STATUS_SUCCESS; } PMMPTE MiFindActualFaultingPte ( IN PVOID FaultingAddress ) /*++ Routine Description: This routine locates the actual PTE which must be made resident in order to complete this fault. Note that for certain cases multiple faults are required to make the final page resident. Arguments: FaultingAddress - Supplies the virtual address which caused the fault. Return Value: The PTE to be made valid to finish the fault, NULL if the fault should be retried. Environment: Kernel mode, APCs disabled, working set mutex held. --*/ { PMMVAD ProtoVad; PMMPTE ProtoPteAddress; PMMPTE PointerPte; PMMPTE PointerFaultingPte; ULONG Protection; if (MI_IS_PHYSICAL_ADDRESS (FaultingAddress)) { return NULL; } #if (_MI_PAGING_LEVELS >= 4) PointerPte = MiGetPxeAddress (FaultingAddress); if (PointerPte->u.Hard.Valid == 0) { // // Page directory parent page is not valid. // return PointerPte; } #endif #if (_MI_PAGING_LEVELS >= 3) PointerPte = MiGetPpeAddress (FaultingAddress); if (PointerPte->u.Hard.Valid == 0) { // // Page directory page is not valid. // return PointerPte; } #endif PointerPte = MiGetPdeAddress (FaultingAddress); if (PointerPte->u.Hard.Valid == 0) { // // Page table page is not valid. // return PointerPte; } PointerPte = MiGetPteAddress (FaultingAddress); if (PointerPte->u.Hard.Valid == 1) { // // Page is already valid, no need to fault it in. // return NULL; } if (PointerPte->u.Soft.Prototype == 0) { // // Page is not a prototype PTE, make this PTE valid. // return PointerPte; } // // Check to see if the PTE which maps the prototype PTE is valid. // if (PointerPte->u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED) { // // Protection is here, PTE must be located in VAD. // ProtoPteAddress = MiCheckVirtualAddress (FaultingAddress, &Protection, &ProtoVad); if (ProtoPteAddress == NULL) { // // No prototype PTE means another thread has deleted the VAD while // this thread waited for the inpage to complete. Certainly NULL // must be returned so a stale PTE is not modified - the instruction // will then be reexecuted and an access violation delivered. // return NULL; } } else { // // Protection is in ProtoPte. // ProtoPteAddress = MiPteToProto (PointerPte); } PointerFaultingPte = MiFindActualFaultingPte (ProtoPteAddress); if (PointerFaultingPte == NULL) { return PointerPte; } return PointerFaultingPte; } PMMPTE MiCheckVirtualAddress ( IN PVOID VirtualAddress, OUT PULONG ProtectCode, OUT PMMVAD *VadOut ) /*++ Routine Description: This function examines the virtual address descriptors to see if the specified virtual address is contained within any of the descriptors. If a virtual address descriptor is found which contains the specified virtual address, a PTE is built from information within the virtual address descriptor and returned to the caller. Arguments: VirtualAddress - Supplies the virtual address to locate within a virtual address descriptor. ProtectCode - Supplies a pointer to a variable that will receive the protection to insert the actual PTE. Vad - Supplies a pointer to a variable that will receive the pointer to the VAD that was used for validation (or NULL if no VAD was used). Return Value: Returns the PTE which corresponds to the supplied virtual address. If no virtual address descriptor is found, a zero PTE is returned. Environment: Kernel mode, APCs disabled, working set mutex held. --*/ { PMMVAD Vad; PMMPTE PointerPte; PLIST_ENTRY NextEntry; PIMAGE_ENTRY_IN_SESSION Image; *VadOut = NULL; if (VirtualAddress <= MM_HIGHEST_USER_ADDRESS) { if (PAGE_ALIGN(VirtualAddress) == (PVOID) MM_SHARED_USER_DATA_VA) { // // This is the page that is double mapped between // user mode and kernel mode. Map it as read only. // *ProtectCode = MM_READONLY; return MmSharedUserDataPte; } Vad = MiLocateAddress (VirtualAddress); if (Vad == NULL) { *ProtectCode = MM_NOACCESS; return NULL; } // // A virtual address descriptor which contains the virtual address // has been located. Build the PTE from the information within // the virtual address descriptor. // if (Vad->u.VadFlags.VadType == VadDevicePhysicalMemory) { // // This is definitely a banked section. // MiHandleBankedSection (VirtualAddress, Vad); *ProtectCode = MM_NOACCESS; return NULL; } if (Vad->u.VadFlags.PrivateMemory == 1) { // // This is a private region of memory. Check to make // sure the virtual address has been committed. Note that // addresses are dense from the bottom up. // if (Vad->u.VadFlags.VadType == VadAwe) { // // These mappings only fault if the access is bad. // *ProtectCode = MM_NOACCESS; return NULL; } if (Vad->u.VadFlags.MemCommit == 1) { *ProtectCode = MI_GET_PROTECTION_FROM_VAD(Vad); return NULL; } // // The address is reserved but not committed. // *ProtectCode = MM_NOACCESS; return NULL; } else { // // This virtual address descriptor refers to a // section, calculate the address of the prototype PTE // and construct a pointer to the PTE. // //******************************************************* //******************************************************* // well here's an interesting problem, how do we know // how to set the attributes on the PTE we are creating // when we can't look at the prototype PTE without // potentially incurring a page fault. In this case // PteTemplate would be zero. //******************************************************* //******************************************************* // if (Vad->u.VadFlags.VadType == VadImageMap) { // // PTE and proto PTEs have the same protection for images. // *ProtectCode = MM_UNKNOWN_PROTECTION; } else { *ProtectCode = MI_GET_PROTECTION_FROM_VAD(Vad); // // Opportunistic clustering can use the identical protections // so give our caller the green light. // if (Vad->u2.VadFlags2.ExtendableFile == 0) { *VadOut = Vad; } } PointerPte = (PMMPTE)MiGetProtoPteAddress(Vad, MI_VA_TO_VPN (VirtualAddress)); if (PointerPte == NULL) { *ProtectCode = MM_NOACCESS; } if (Vad->u2.VadFlags2.ExtendableFile) { // // Make sure the data has been committed. // if ((MI_VA_TO_VPN (VirtualAddress) - Vad->StartingVpn) > (ULONG_PTR)((((PMMVAD_LONG)Vad)->u4.ExtendedInfo->CommittedSize - 1) >> PAGE_SHIFT)) { *ProtectCode = MM_NOACCESS; } } return PointerPte; } } else if (MI_IS_PAGE_TABLE_ADDRESS(VirtualAddress)) { // // The virtual address is within the space occupied by PDEs, // make the PDE valid. // if (((PMMPTE)VirtualAddress >= MiGetPteAddress (MM_PAGED_POOL_START)) && ((PMMPTE)VirtualAddress <= MmPagedPoolInfo.LastPteForPagedPool)) { *ProtectCode = MM_NOACCESS; return NULL; } *ProtectCode = MM_READWRITE; return NULL; } else if (MI_IS_SESSION_ADDRESS (VirtualAddress) == TRUE) { // // See if the session space address is copy on write. // MM_SESSION_SPACE_WS_LOCK_ASSERT (); PointerPte = NULL; *ProtectCode = MM_NOACCESS; NextEntry = MmSessionSpace->ImageList.Flink; while (NextEntry != &MmSessionSpace->ImageList) { Image = CONTAINING_RECORD(NextEntry, IMAGE_ENTRY_IN_SESSION, Link); if ((VirtualAddress >= Image->Address) && (VirtualAddress <= Image->LastAddress)) { PointerPte = Image->PrototypePtes + (((PCHAR)VirtualAddress - (PCHAR)Image->Address) >> PAGE_SHIFT); *ProtectCode = MM_EXECUTE_WRITECOPY; break; } NextEntry = NextEntry->Flink; } return PointerPte; } // // Address is in system space. // *ProtectCode = MM_NOACCESS; return NULL; } #if (_MI_PAGING_LEVELS < 3) NTSTATUS FASTCALL MiCheckPdeForPagedPool ( IN PVOID VirtualAddress ) /*++ Routine Description: This function copies the Page Table Entry for the corresponding virtual address from the system process's page directory. This allows page table pages to be lazily evaluated for things like paged pool and per-session mappings. Arguments: VirtualAddress - Supplies the virtual address in question. Return Value: Either success or access violation. Environment: Kernel mode, DISPATCH level or below. --*/ { PMMPTE PointerPde; NTSTATUS status; if (MI_IS_SESSION_ADDRESS (VirtualAddress) == TRUE) { // // Virtual address in the session space range. // return MiCheckPdeForSessionSpace (VirtualAddress); } if (MI_IS_SESSION_PTE (VirtualAddress) == TRUE) { // // PTE for the session space range. // return MiCheckPdeForSessionSpace (VirtualAddress); } status = STATUS_SUCCESS; if (MI_IS_KERNEL_PAGE_TABLE_ADDRESS(VirtualAddress)) { // // PTE for paged pool. // PointerPde = MiGetPteAddress (VirtualAddress); status = STATUS_WAIT_1; } else if (VirtualAddress < MmSystemRangeStart) { return STATUS_ACCESS_VIOLATION; } else { // // Virtual address in paged pool range. // PointerPde = MiGetPdeAddress (VirtualAddress); } // // Locate the PDE for this page and make it valid. // if (PointerPde->u.Hard.Valid == 0) { // // The MI_WRITE_VALID_PTE macro cannot be used here because // its ASSERTs could mistakenly fire as multiple processors // may execute the instruction below without synchronization. // InterlockedExchangePte (PointerPde, MmSystemPagePtes [((ULONG_PTR)PointerPde & (PD_PER_SYSTEM * (sizeof(MMPTE) * PDE_PER_PAGE) - 1)) / sizeof(MMPTE)].u.Long); } return status; } NTSTATUS FASTCALL MiCheckPdeForSessionSpace ( IN PVOID VirtualAddress ) /*++ Routine Description: This function copies the Page Table Entry for the corresponding session virtual address from the current session's data structures. This allows page table pages to be lazily evaluated for session mappings. The caller must check for the current process having a session space. Arguments: VirtualAddress - Supplies the virtual address in question. Return Value: STATUS_WAIT_1 - The mapping has been made valid, retry the fault. STATUS_SUCCESS - Did not handle the fault, continue further processing. !STATUS_SUCCESS - An access violation has occurred - raise an exception. Environment: Kernel mode, DISPATCH level or below. --*/ { MMPTE TempPde; PMMPTE PointerPde; PVOID SessionVirtualAddress; ULONG Index; // // First check whether the reference was to a page table page which maps // session space. If so, the PDE is retrieved from the session space // data structure and made valid. // if (MI_IS_SESSION_PTE (VirtualAddress) == TRUE) { // // Verify that the current process has a session space. // PointerPde = MiGetPdeAddress (MmSessionSpace); if (PointerPde->u.Hard.Valid == 0) { #if DBG DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MiCheckPdeForSessionSpace: No current session for PTE %p\n", VirtualAddress); DbgBreakPoint (); #endif return STATUS_ACCESS_VIOLATION; } SessionVirtualAddress = MiGetVirtualAddressMappedByPte ((PMMPTE) VirtualAddress); PointerPde = MiGetPteAddress (VirtualAddress); if (PointerPde->u.Hard.Valid == 1) { // // The PDE is already valid - another thread must have // won the race. Just return. // return STATUS_WAIT_1; } // // Calculate the session space PDE index and load the // PDE from the session space table for this session. // Index = MiGetPdeSessionIndex (SessionVirtualAddress); TempPde.u.Long = MmSessionSpace->PageTables[Index].u.Long; if (TempPde.u.Hard.Valid == 1) { // // The MI_WRITE_VALID_PTE macro cannot be used here because // its ASSERTs could mistakenly fire as multiple processors // may execute the instruction below without synchronization. // InterlockedExchangePte (PointerPde, TempPde.u.Long); return STATUS_WAIT_1; } #if DBG DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MiCheckPdeForSessionSpace: No Session PDE for PTE %p, %p\n", PointerPde->u.Long, SessionVirtualAddress); DbgBreakPoint (); #endif return STATUS_ACCESS_VIOLATION; } if (MI_IS_SESSION_ADDRESS (VirtualAddress) == FALSE) { // // Not a session space fault - tell the caller to try other handlers. // return STATUS_SUCCESS; } // // Handle PDE faults for references in the session space. // Verify that the current process has a session space. // PointerPde = MiGetPdeAddress (MmSessionSpace); if (PointerPde->u.Hard.Valid == 0) { #if DBG DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MiCheckPdeForSessionSpace: No current session for VA %p\n", VirtualAddress); DbgBreakPoint (); #endif return STATUS_ACCESS_VIOLATION; } PointerPde = MiGetPdeAddress (VirtualAddress); if (PointerPde->u.Hard.Valid == 0) { // // Calculate the session space PDE index and load the // PDE from the session space table for this session. // Index = MiGetPdeSessionIndex (VirtualAddress); PointerPde->u.Long = MmSessionSpace->PageTables[Index].u.Long; if (PointerPde->u.Hard.Valid == 1) { return STATUS_WAIT_1; } #if DBG DbgPrintEx (DPFLTR_MM_ID, DPFLTR_ERROR_LEVEL, "MiCheckPdeForSessionSpace: No Session PDE for VA %p, %p\n", PointerPde->u.Long, VirtualAddress); DbgBreakPoint (); #endif return STATUS_ACCESS_VIOLATION; } // // Tell the caller to continue with other fault handlers. // return STATUS_SUCCESS; } #endif VOID MiInitializePfn ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE PointerPte, IN ULONG ModifiedState ) /*++ Routine Description: This function initializes the specified PFN element to the active and valid state. Arguments: PageFrameIndex - Supplies the page frame number to initialize. PointerPte - Supplies the pointer to the PTE which caused the page fault. ModifiedState - Supplies the state to set the modified field in the PFN element for this page, either 0 or 1. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPFN Pfn2; PMMPTE PteFramePointer; PFN_NUMBER PteFramePage; MM_PROTECTION_MASK Protection; MI_PFN_CACHE_ATTRIBUTE NewCacheAttribute; MM_PFN_LOCK_ASSERT(); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->PteAddress = PointerPte; NewCacheAttribute = MiCached; // // If the PTE is currently valid, an address space is being built, // just make the original PTE demand zero. // if (PointerPte->u.Hard.Valid == 1) { // // The only time this should happen is for the initial process pages // created (and initialized) out of context. They must be in order // to attach and then initialize the process, and // MmCreateProcessAddressSpace assumes responsibility for detecting // and preventing TB attribute conflicts for this case, so we don't // need to here. // ASSERT (PsGetCurrentProcess()->Vm.WorkingSetSize == 0); ASSERT (!MI_IS_WRITE_COMBINE_ENABLED (PointerPte)); ASSERT (!MI_IS_CACHING_DISABLED (PointerPte)); ASSERT (Pfn1->u3.e1.CacheAttribute == MiCached); Pfn1->OriginalPte.u.Long = MM_DEMAND_ZERO_WRITE_PTE; #if defined (_AMD64_) if (PointerPte->u.Hard.NoExecute == 0) { Pfn1->OriginalPte.u.Soft.Protection = MM_EXECUTE_READWRITE; } #endif #if defined(_X86PAE_) if (MmPaeMask != 0) { if ((PointerPte->u.Long & MmPaeMask) == 0) { Pfn1->OriginalPte.u.Soft.Protection = MM_EXECUTE_READWRITE; } } #endif } else { Pfn1->OriginalPte = *PointerPte; ASSERT (!((Pfn1->OriginalPte.u.Soft.Prototype == 0) && (Pfn1->OriginalPte.u.Soft.Transition == 1))); Protection = (MM_PROTECTION_MASK) PointerPte->u.Soft.Protection; if (MI_IS_WRITECOMBINE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiWriteCombined, 0); } else if (MI_IS_NOCACHE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiNonCached, 0); } if (Pfn1->u3.e1.CacheAttribute != NewCacheAttribute) { MI_FLUSH_TB_FOR_INDIVIDUAL_ATTRIBUTE_CHANGE (PageFrameIndex, NewCacheAttribute); Pfn1->u3.e1.CacheAttribute = NewCacheAttribute; } } ASSERT (Pfn1->u3.e2.ReferenceCount == 0); Pfn1->u3.e2.ReferenceCount += 1; Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; if (ModifiedState == 1) { MI_SET_MODIFIED (Pfn1, 1, 0xB); } else { MI_SET_MODIFIED (Pfn1, 0, 0x26); } #if defined (_WIN64) Pfn1->UsedPageTableEntries = 0; #endif // // Determine the page frame number of the page table page which // contains this PTE. // PteFramePointer = MiGetPteAddress (PointerPte); if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (PointerPte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)PointerPte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(PointerPte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); ASSERT (PteFramePage != 0); Pfn1->u4.PteFrame = PteFramePage; // // Increment the share count for the page table page containing // this PTE. // Pfn2 = MI_PFN_ELEMENT (PteFramePage); Pfn2->u2.ShareCount += 1; return; } VOID MiInitializePfnAndMakePteValid ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE PointerPte, IN MMPTE NewPteContents ) /*++ Routine Description: This function initializes the specified PFN element to the active and valid state. After initializing the PFN, the PTE is then immediately made valid. Note the order is important because the TB may need to be flushed to avoid a prior stale system PTE mapping (these are lazy-flushed) from causing a TB attribute conflict. Arguments: PageFrameIndex - Supplies the page frame number to initialize. PointerPte - Supplies the pointer to the PTE which caused the page fault. NewPteContents - Supplies the contents to insert in the PTE. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPFN Pfn2; PMMPTE PteFramePointer; PFN_NUMBER PteFramePage; MI_PFN_CACHE_ATTRIBUTE NewCacheAttribute; MM_PFN_LOCK_ASSERT(); ASSERT (PointerPte->u.Hard.Valid == 0); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->PteAddress = PointerPte; // // An address space is being built, just make the original PTE demand zero. // Pfn1->OriginalPte.u.Long = MM_DEMAND_ZERO_WRITE_PTE; #if defined (_AMD64_) if (NewPteContents.u.Hard.NoExecute == 0) { Pfn1->OriginalPte.u.Soft.Protection = MM_EXECUTE_READWRITE; } #endif #if defined(_X86PAE_) if (MmPaeMask != 0) { if ((NewPteContents.u.Long & MmPaeMask) == 0) { Pfn1->OriginalPte.u.Soft.Protection = MM_EXECUTE_READWRITE; } } #endif NewCacheAttribute = MiCached; if (MI_IS_WRITE_COMBINE_ENABLED (&NewPteContents)) { Pfn1->OriginalPte.u.Soft.Protection |= MM_WRITECOMBINE; NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiWriteCombined, 0); } else if (MI_IS_CACHING_DISABLED (&NewPteContents)) { Pfn1->OriginalPte.u.Soft.Protection |= MM_NOCACHE; NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiNonCached, 0); } // // Flush the TB if the attribute for this PFN is changing. // if (Pfn1->u3.e1.CacheAttribute != NewCacheAttribute) { MI_FLUSH_TB_FOR_INDIVIDUAL_ATTRIBUTE_CHANGE (PageFrameIndex, NewCacheAttribute); Pfn1->u3.e1.CacheAttribute = NewCacheAttribute; } ASSERT (Pfn1->u3.e2.ReferenceCount == 0); Pfn1->u3.e2.ReferenceCount += 1; Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; MI_SET_MODIFIED (Pfn1, 1, 0xB); #if defined (_WIN64) Pfn1->UsedPageTableEntries = 0; #endif // // Determine the page frame number of the page table page which // contains this PTE. // PteFramePointer = MiGetPteAddress (PointerPte); if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (PointerPte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)PointerPte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(PointerPte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); ASSERT (PteFramePage != 0); Pfn1->u4.PteFrame = PteFramePage; // // Increment the share count for the page table page containing // this PTE. // Pfn2 = MI_PFN_ELEMENT (PteFramePage); Pfn2->u2.ShareCount += 1; MI_WRITE_VALID_PTE (PointerPte, NewPteContents); return; } VOID MiInitializeReadInProgressSinglePfn ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE BasePte, IN PKEVENT Event, IN WSLE_NUMBER WorkingSetIndex ) /*++ Routine Description: This function initializes the specified PFN element to the transition / read-in-progress state for an in-page operation. Arguments: PageFrameIndex - Supplies the page frame to initialize. BasePte - Supplies the pointer to the PTE for the page frame. Event - Supplies the event which is to be set when the I/O operation completes. WorkingSetIndex - Supplies the working set index flag, a value of -1 indicates no WSLE is required because this is a prototype PTE. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPTE PteFramePointer; PFN_NUMBER PteFramePage; MMPTE TempPte; MM_PROTECTION_MASK Protection; MI_PFN_CACHE_ATTRIBUTE NewCacheAttribute; MM_PFN_LOCK_ASSERT(); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->u1.Event = Event; Pfn1->PteAddress = BasePte; Pfn1->OriginalPte = *BasePte; if (WorkingSetIndex == MI_PROTOTYPE_WSINDEX) { Pfn1->u3.e1.PrototypePte = 1; } ASSERT (Pfn1->u3.e2.ReferenceCount == 0); MI_ADD_LOCKED_PAGE_CHARGE_FOR_MODIFIED_PAGE (Pfn1); Pfn1->u2.ShareCount = 0; Pfn1->u3.e1.ReadInProgress = 1; Protection = (MM_PROTECTION_MASK) BasePte->u.Soft.Protection; NewCacheAttribute = MiCached; if (MI_IS_WRITECOMBINE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiWriteCombined, 0); } else if (MI_IS_NOCACHE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiNonCached, 0); } if (Pfn1->u3.e1.CacheAttribute != NewCacheAttribute) { MI_FLUSH_TB_FOR_INDIVIDUAL_ATTRIBUTE_CHANGE (PageFrameIndex, NewCacheAttribute); Pfn1->u3.e1.CacheAttribute = NewCacheAttribute; } Pfn1->u4.InPageError = 0; // // Determine the page frame number of the page table page which // contains this PTE. // PteFramePointer = MiGetPteAddress (BasePte); if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (BasePte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)BasePte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(BasePte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); Pfn1->u4.PteFrame = PteFramePage; // // Put the PTE into the transition state, no cache flush needed as // PTE is still not valid. // MI_MAKE_TRANSITION_PTE (TempPte, PageFrameIndex, BasePte->u.Soft.Protection, BasePte); MI_WRITE_INVALID_PTE (BasePte, TempPte); // // Increment the share count for the page table page containing // this PTE as the PTE just went into the transition state. // ASSERT (PteFramePage != 0); Pfn1 = MI_PFN_ELEMENT (PteFramePage); Pfn1->u2.ShareCount += 1; return; } VOID MiInitializeReadInProgressPfn ( IN PMDL Mdl, IN PMMPTE BasePte, IN PKEVENT Event, IN WSLE_NUMBER WorkingSetIndex ) /*++ Routine Description: This function initializes the specified PFN element to the transition / read-in-progress state for an in-page operation. Arguments: Mdl - Supplies a pointer to the MDL. BasePte - Supplies the pointer to the PTE which the first page in the MDL maps. Event - Supplies the event which is to be set when the I/O operation completes. WorkingSetIndex - Supplies the working set index flag, a value of -1 indicates no WSLE is required because this is a prototype PTE. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPFN Pfn2; PMMPTE PteFramePointer; PFN_NUMBER PteFramePage; MMPTE TempPte; LONG NumberOfBytes; PPFN_NUMBER Page; MM_PROTECTION_MASK Protection; MI_PFN_CACHE_ATTRIBUTE NewCacheAttribute; LOGICAL TbFlushNeeded; TbFlushNeeded = FALSE; PteFramePage = 0; PteFramePointer = 0; SATISFY_OVERZEALOUS_COMPILER (NewCacheAttribute = MiCached); MM_PFN_LOCK_ASSERT(); Page = (PPFN_NUMBER)(Mdl + 1); NumberOfBytes = Mdl->ByteCount; while (NumberOfBytes > 0) { Pfn1 = MI_PFN_ELEMENT (*Page); Pfn1->u1.Event = Event; Pfn1->PteAddress = BasePte; Pfn1->OriginalPte = *BasePte; if (WorkingSetIndex == MI_PROTOTYPE_WSINDEX) { Pfn1->u3.e1.PrototypePte = 1; } ASSERT (Pfn1->u3.e2.ReferenceCount == 0); MI_ADD_LOCKED_PAGE_CHARGE_FOR_MODIFIED_PAGE (Pfn1); Pfn1->u2.ShareCount = 0; Pfn1->u3.e1.ReadInProgress = 1; Protection = (MM_PROTECTION_MASK) BasePte->u.Soft.Protection; NewCacheAttribute = MiCached; if (MI_IS_WRITECOMBINE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiWriteCombined, 0); } else if (MI_IS_NOCACHE (Protection)) { NewCacheAttribute = MI_TRANSLATE_CACHETYPE (MiNonCached, 0); } if (Pfn1->u3.e1.CacheAttribute != NewCacheAttribute) { TbFlushNeeded = TRUE; Pfn1->u3.e1.CacheAttribute = NewCacheAttribute; } Pfn1->u4.InPageError = 0; if ((PteFramePage == 0) || (MiIsPteOnPdeBoundary (BasePte))) { // // Determine the page frame number of the page table page which // contains this PTE. // if (PteFramePage == 0) { PteFramePointer = MiGetPteAddress (BasePte); } else { PteFramePointer += 1; ASSERT (PteFramePointer == MiGetPteAddress (BasePte)); } if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (BasePte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)BasePte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(BasePte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); ASSERT (PteFramePage != 0); } Pfn1->u4.PteFrame = PteFramePage; // // Put the PTE into the transition state, no TB flush needed as the // existing PTE is not valid. // MI_MAKE_TRANSITION_PTE (TempPte, *Page, BasePte->u.Soft.Protection, BasePte); MI_WRITE_INVALID_PTE (BasePte, TempPte); // // Increment the share count for the page table page containing // this PTE as the PTE just went into the transition state. // ASSERT (PteFramePage != 0); Pfn2 = MI_PFN_ELEMENT (PteFramePage); Pfn2->u2.ShareCount += 1; NumberOfBytes -= PAGE_SIZE; Page += 1; BasePte += 1; } if (TbFlushNeeded == TRUE) { MI_FLUSH_ENTIRE_TB_FOR_ATTRIBUTE_CHANGE (NewCacheAttribute); } return; } VOID MiInitializeTransitionPfn ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE PointerPte ) /*++ Routine Description: This function initializes the specified PFN element to the transition state. Main use is by MapImageFile to make the page which contains the image header transition in the prototype PTEs. Arguments: PageFrameIndex - Supplies the page frame index to be initialized. PointerPte - Supplies an invalid, non-transition PTE to initialize. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPFN Pfn2; PMMPTE PteFramePointer; PFN_NUMBER PteFramePage; MMPTE TempPte; MM_PFN_LOCK_ASSERT(); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->u1.Event = NULL; Pfn1->PteAddress = PointerPte; Pfn1->OriginalPte = *PointerPte; ASSERT (!((Pfn1->OriginalPte.u.Soft.Prototype == 0) && (Pfn1->OriginalPte.u.Soft.Transition == 1))); // // Don't change the reference count (it should already be 1). // Pfn1->u2.ShareCount = 0; // // No WSLE is required because this is a prototype PTE. // Pfn1->u3.e1.PrototypePte = 1; Pfn1->u3.e1.PageLocation = TransitionPage; // // Determine the page frame number of the page table page which // contains this PTE. // PteFramePointer = MiGetPteAddress (PointerPte); if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (PointerPte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)PointerPte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(PointerPte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); Pfn1->u4.PteFrame = PteFramePage; // // Put the PTE into the transition state, no cache flush needed as // PTE is still not valid. // MI_MAKE_TRANSITION_PTE (TempPte, PageFrameIndex, PointerPte->u.Soft.Protection, PointerPte); MI_WRITE_INVALID_PTE (PointerPte, TempPte); // // Increment the share count for the page table page containing // this PTE as the PTE just went into the transition state. // Pfn2 = MI_PFN_ELEMENT (PteFramePage); ASSERT (PteFramePage != 0); Pfn2->u2.ShareCount += 1; return; } VOID MiInitializeCopyOnWritePfn ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE PointerPte, IN WSLE_NUMBER WorkingSetIndex, IN PMMWSL WorkingSetList ) /*++ Routine Description: This function initializes the specified PFN element to the active and valid state for a copy on write operation. In this case the page table page which contains the PTE has the proper ShareCount. Arguments: PageFrameIndex - Supplies the page frame number to initialize. PointerPte - Supplies the pointer to the PTE which caused the page fault. WorkingSetIndex - Supplies the working set index for the corresponding virtual address. WorkingSetList - Supplies the relevant working set list. Return Value: None. Environment: Kernel mode, APCs disabled, working set pushlock AND PFN lock held. --*/ { PMMPFN Pfn1; PMMWSLE Wsle; PMMPTE PteFramePointer; PFN_NUMBER OldPageFrameIndex; PMMPFN OldPfn; PFN_NUMBER PteFramePage; PVOID VirtualAddress; MM_PROTECTION_MASK ProtectionMask; ASSERT (PointerPte->u.Hard.Valid == 1); OldPageFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (PointerPte); OldPfn = MI_PFN_ELEMENT (OldPageFrameIndex); Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->PteAddress = PointerPte; // // Get the protection for the page. // VirtualAddress = MiGetVirtualAddressMappedByPte (PointerPte); Pfn1->OriginalPte.u.Long = 0; Wsle = &WorkingSetList->Wsle[WorkingSetIndex]; ProtectionMask = (MM_PROTECTION_MASK) Wsle->u1.e1.Protection; if (ProtectionMask == MM_ZERO_ACCESS) { ProtectionMask = MI_GET_PROTECTION_FROM_SOFT_PTE (&OldPfn->OriginalPte); } Pfn1->OriginalPte.u.Soft.Protection = MI_MAKE_PROTECT_NOT_WRITE_COPY (ProtectionMask); Wsle->u1.e1.Protection = (MM_PROTECTION_MASK) Pfn1->OriginalPte.u.Soft.Protection; // // Now initialize the rest of the new PFN entry. // ASSERT (Pfn1->u3.e2.ReferenceCount == 0); Pfn1->u3.e2.ReferenceCount += 1; Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; if (Pfn1->u3.e1.CacheAttribute != OldPfn->u3.e1.CacheAttribute) { MI_FLUSH_TB_FOR_INDIVIDUAL_ATTRIBUTE_CHANGE (PageFrameIndex, OldPfn->u3.e1.CacheAttribute); Pfn1->u3.e1.CacheAttribute = OldPfn->u3.e1.CacheAttribute; } Pfn1->u1.WsIndex = WorkingSetIndex; // // Determine the page frame number of the page table page which // contains this PTE. // PteFramePointer = MiGetPteAddress (PointerPte); if (PteFramePointer->u.Hard.Valid == 0) { #if (_MI_PAGING_LEVELS < 3) if (!NT_SUCCESS(MiCheckPdeForPagedPool (PointerPte))) { #endif KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR)PointerPte, (ULONG_PTR)PteFramePointer->u.Long, (ULONG_PTR)MiGetVirtualAddressMappedByPte(PointerPte)); #if (_MI_PAGING_LEVELS < 3) } #endif } PteFramePage = MI_GET_PAGE_FRAME_FROM_PTE (PteFramePointer); ASSERT (PteFramePage != 0); Pfn1->u4.PteFrame = PteFramePage; // // Set the modified flag in the PFN database as we are writing // into this page and the dirty bit is already set in the PTE. // MI_SET_MODIFIED (Pfn1, 1, 0xC); return; } BOOLEAN MiIsAddressValid ( IN PVOID VirtualAddress, IN LOGICAL UseForceIfPossible ) /*++ Routine Description: For a given virtual address this function returns TRUE if no page fault will occur for a read operation on the address, FALSE otherwise. Note that after this routine was called, if appropriate locks are not held, a non-faulting address could fault. Arguments: VirtualAddress - Supplies the virtual address to check. UseForceIfPossible - Supplies TRUE if the address should be forced valid if possible. Return Value: TRUE if no page fault would be generated reading the virtual address, FALSE otherwise. Environment: Kernel mode. --*/ { PMMPTE PointerPte; UNREFERENCED_PARAMETER (UseForceIfPossible); #if defined (_AMD64_) // // If this is within the physical addressing range, just return TRUE. // if (MI_IS_PHYSICAL_ADDRESS(VirtualAddress)) { PFN_NUMBER PageFrameIndex; // // Only bound with MmHighestPhysicalPage once Mm has initialized. // if (MmHighestPhysicalPage != 0) { PageFrameIndex = MI_CONVERT_PHYSICAL_TO_PFN(VirtualAddress); if (PageFrameIndex > MmHighestPhysicalPage) { return FALSE; } } return TRUE; } #endif // // If the address is not canonical then return FALSE as the caller (which // may be the kernel debugger) is not expecting to get an unimplemented // address bit fault. // if (MI_RESERVED_BITS_CANONICAL(VirtualAddress) == FALSE) { return FALSE; } #if (_MI_PAGING_LEVELS >= 4) PointerPte = MiGetPxeAddress (VirtualAddress); if (PointerPte->u.Hard.Valid == 0) { return FALSE; } #endif #if (_MI_PAGING_LEVELS >= 3) PointerPte = MiGetPpeAddress (VirtualAddress); if (PointerPte->u.Hard.Valid == 0) { return FALSE; } #endif PointerPte = MiGetPdeAddress (VirtualAddress); if (PointerPte->u.Hard.Valid == 0) { return FALSE; } if (MI_PDE_MAPS_LARGE_PAGE (PointerPte)) { return TRUE; } PointerPte = MiGetPteAddress (VirtualAddress); if (PointerPte->u.Hard.Valid == 0) { return FALSE; } // // Make sure we're not treating a page directory as a page table here for // the case where the page directory is mapping a large page. This is // because the large page bit is valid in PDE formats, but reserved in // PTE formats and will cause a trap. A virtual address like c0200000 (on // x86) triggers this case. // if (MI_PDE_MAPS_LARGE_PAGE (PointerPte)) { return FALSE; } return TRUE; } BOOLEAN MmIsAddressValid ( __in PVOID VirtualAddress ) /*++ Routine Description: For a given virtual address this function returns TRUE if no page fault will occur for a read operation on the address, FALSE otherwise. Note that after this routine was called, if appropriate locks are not held, a non-faulting address could fault. Arguments: VirtualAddress - Supplies the virtual address to check. Return Value: TRUE if no page fault would be generated reading the virtual address, FALSE otherwise. Environment: Kernel mode. --*/ { return MiIsAddressValid (VirtualAddress, FALSE); } VOID MiInitializePfnForOtherProcess ( IN PFN_NUMBER PageFrameIndex, IN PMMPTE PointerPte, IN PFN_NUMBER ContainingPageFrame ) /*++ Routine Description: This function initializes the specified PFN element to the active and valid state with the dirty bit on in the PTE and the PFN database marked as modified. As this PTE is not visible from the current process, the containing page frame must be supplied at the PTE contents field for the PFN database element are set to demand zero. Arguments: PageFrameIndex - Supplies the page frame number of which to initialize. PointerPte - Supplies the pointer to the PTE which caused the page fault. ContainingPageFrame - Supplies the page frame number of the page table page which contains this PTE. If the ContainingPageFrame is 0, then the ShareCount for the containing page is not incremented. Return Value: None. Environment: Kernel mode, APCs disabled, PFN lock held. --*/ { PMMPFN Pfn1; PMMPFN Pfn2; Pfn1 = MI_PFN_ELEMENT (PageFrameIndex); Pfn1->PteAddress = PointerPte; // // Note that pages allocated this way are for the kernel and thus // never have split permissions in the PTE or the PFN. // Pfn1->OriginalPte.u.Long = MM_DEMAND_ZERO_WRITE_PTE; ASSERT (Pfn1->u3.e2.ReferenceCount == 0); Pfn1->u3.e2.ReferenceCount = 1; Pfn1->u2.ShareCount += 1; Pfn1->u3.e1.PageLocation = ActiveAndValid; // // Set the page attribute to cached even though it isn't really mapped // into a TB entry yet - it will be when the I/O completes and in the // future, may get paged in and out multiple times and will be marked // as cached in those transactions also. If in fact the driver stack // wants to map it some other way for the transfer, the correct mapping // will get used regardless. // if (Pfn1->u3.e1.CacheAttribute != MiCached) { MI_FLUSH_TB_FOR_CACHED_ATTRIBUTE (); Pfn1->u3.e1.CacheAttribute = MiCached; } MI_SET_MODIFIED (Pfn1, 1, 0xD); Pfn1->u4.InPageError = 0; // // Increment the share count for the page table page containing // this PTE. // if (ContainingPageFrame != 0) { Pfn1->u4.PteFrame = ContainingPageFrame; Pfn2 = MI_PFN_ELEMENT (ContainingPageFrame); Pfn2->u2.ShareCount += 1; } return; } WSLE_NUMBER MiAddValidPageToWorkingSet ( IN PVOID VirtualAddress, IN PMMPTE PointerPte, IN PMMPFN Pfn1, IN ULONG WsleMask ) /*++ Routine Description: This routine adds the specified virtual address into the appropriate working set list. Arguments: VirtualAddress - Supplies the address to add to the working set list. PointerPte - Supplies a pointer to the PTE that is now valid. Pfn1 - Supplies the PFN database element for the physical page mapped by the virtual address. WsleMask - Supplies a mask (protection and flags) to OR into the working set list entry. Return Value: Non-zero on success, 0 on failure. Environment: Kernel mode, APCs disabled, working set lock. PFN lock NOT held. --*/ { WSLE_NUMBER WorkingSetIndex; PEPROCESS Process; PMMSUPPORT WsInfo; #if !DBG UNREFERENCED_PARAMETER (PointerPte); #endif ASSERT (MI_IS_PAGE_TABLE_ADDRESS(PointerPte)); ASSERT (PointerPte->u.Hard.Valid == 1); if (MI_IS_SESSION_ADDRESS (VirtualAddress) || MI_IS_SESSION_PTE (VirtualAddress)) { // // Current process's session space working set. // WsInfo = &MmSessionSpace->Vm; } else if (MI_IS_PROCESS_SPACE_ADDRESS(VirtualAddress)) { // // Per process working set. // Process = PsGetCurrentProcess(); WsInfo = &Process->Vm; } else { // // System cache working set. // WsInfo = &MmSystemCacheWs; } WorkingSetIndex = MiAllocateWsle (WsInfo, PointerPte, Pfn1, WsleMask); return WorkingSetIndex; } VOID MiTrimPte ( IN PVOID VirtualAddress, IN PMMPTE PointerPte, IN PMMPFN Pfn1, IN PEPROCESS CurrentProcess, IN MMPTE NewPteContents ) /*++ Routine Description: This routine removes the specified virtual address from a page table page. Note there is no working set list entry for this address. Arguments: VirtualAddress - Supplies the address to remove. PointerPte - Supplies a pointer to the PTE that is now valid. Pfn1 - Supplies the PFN database element for the physical page mapped by the virtual address. CurrentProcess - Supplies NULL (ie: system cache), HYDRA_PROCESS (ie: a session) or anything else (ie: process). NewPteContents - Supplies the new PTE contents to place in the PTE. This is only used for prototype PTEs - private PTEs are always encoded with the Pfn's OriginalPte information. Return Value: None. Environment: Kernel mode, APCs disabled, working set lock. PFN lock NOT held. --*/ { KIRQL OldIrql; MMPTE TempPte; MMPTE PreviousPte; PMMPTE ContainingPageTablePage; PMMPFN Pfn2; PFN_NUMBER PageFrameIndex; PFN_NUMBER PageTableFrameIndex; PETHREAD CurrentThread; CurrentThread = PsGetCurrentThread (); PageFrameIndex = MI_PFN_ELEMENT_TO_INDEX (Pfn1); // Working set mutex must be held. ASSERT (KeGetCurrentIrql () <= APC_LEVEL); ASSERT (KeAreAllApcsDisabled () == TRUE); if (Pfn1->u3.e1.PrototypePte) { ASSERT (MI_IS_PFN_DELETED (Pfn1) == 0); // // This is a prototype PTE. The PFN database does not contain // the contents of this PTE it contains the contents of the // prototype PTE. This PTE must be reconstructed to contain // a pointer to the prototype PTE. // // The working set list entry contains information about // how to reconstruct the PTE. // TempPte = NewPteContents; ASSERT (NewPteContents.u.Proto.Prototype == 1); // // Decrement the share count of the containing page table // page as the PTE for the removed page is no longer valid // or in transition. // ContainingPageTablePage = MiGetPteAddress (PointerPte); #if (_MI_PAGING_LEVELS >= 3) ASSERT (ContainingPageTablePage->u.Hard.Valid == 1); #else if (ContainingPageTablePage->u.Hard.Valid == 0) { if (!NT_SUCCESS(MiCheckPdeForPagedPool (PointerPte))) { KeBugCheckEx (MEMORY_MANAGEMENT, 0x61940, (ULONG_PTR) PointerPte, (ULONG_PTR) ContainingPageTablePage->u.Long, (ULONG_PTR) VirtualAddress); } } #endif PageTableFrameIndex = MI_GET_PAGE_FRAME_FROM_PTE (ContainingPageTablePage); Pfn2 = MI_PFN_ELEMENT (PageTableFrameIndex); LOCK_PFN (OldIrql); MiDecrementShareCountInline (Pfn2, PageTableFrameIndex); } else { // // This is a private page, make it transition. // // Assert that the share count is 1 for all user mode pages. // ASSERT ((Pfn1->u2.ShareCount == 1) || (VirtualAddress > (PVOID)MM_HIGHEST_USER_ADDRESS)); if (MI_IS_PFN_DELETED (Pfn1)) { TempPte.u.Long = 0; Pfn2 = MI_PFN_ELEMENT (Pfn1->u4.PteFrame); LOCK_PFN (OldIrql); MiDecrementShareCountInline (Pfn2, Pfn1->u4.PteFrame); } else { TempPte = *PointerPte; MI_MAKE_VALID_PTE_TRANSITION (TempPte, Pfn1->OriginalPte.u.Soft.Protection); LOCK_PFN (OldIrql); } } PreviousPte = *PointerPte; ASSERT (PreviousPte.u.Hard.Valid == 1); MI_WRITE_INVALID_PTE (PointerPte, TempPte); MI_CAPTURE_DIRTY_BIT_TO_PFN (&PreviousPte, Pfn1); if ((CurrentProcess == NULL) || (CurrentProcess == HYDRA_PROCESS)) { MI_FLUSH_SINGLE_TB (VirtualAddress, TRUE); } else { MI_FLUSH_SINGLE_TB (VirtualAddress, FALSE); if ((Pfn1->u3.e1.PrototypePte == 0) && (MI_IS_PTE_DIRTY(PreviousPte)) && (CurrentProcess->Flags & PS_PROCESS_FLAGS_USING_WRITE_WATCH)) { // // This process has (or had) write watch VADs. // Search now for a write watch region encapsulating // the PTE being invalidated. // MiCaptureWriteWatchDirtyBit (CurrentProcess, VirtualAddress); } } MiDecrementShareCountInline (Pfn1, PageFrameIndex); UNLOCK_PFN (OldIrql); } PMMINPAGE_SUPPORT MiGetInPageSupportBlock ( IN KIRQL OldIrql, OUT PNTSTATUS Status ) /*++ Routine Description: This routine acquires an inpage support block. If none are available, the PFN lock will be released and reacquired to add an entry to the list. NULL will then be returned. Arguments: OldIrql - Supplies the IRQL the caller acquired the PFN lock at (or MM_NOIRQL if the caller did not acquire the PFN at all). Status - Supplies a pointer to a status to return (valid only if the PFN lock had to be released, ie: NULL was returned). Return Value: A non-null pointer to an inpage block if one is already available. The PFN lock is not released in this path. NULL is returned if no inpage blocks were available. In this path, the PFN lock is released and an entry is added - but NULL is still returned so the caller is aware that the state has changed due to the lock release and reacquisition. Environment: Kernel mode, PFN lock may optionally be held. --*/ { PMMINPAGE_SUPPORT Support; PSLIST_ENTRY SingleListEntry; #if DBG if (OldIrql != MM_NOIRQL) { MM_PFN_LOCK_ASSERT(); } else { ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL); } #endif if (ExQueryDepthSList (&MmInPageSupportSListHead) != 0) { SingleListEntry = InterlockedPopEntrySList (&MmInPageSupportSListHead); if (SingleListEntry != NULL) { Support = CONTAINING_RECORD (SingleListEntry, MMINPAGE_SUPPORT, ListEntry); returnok: ASSERT (Support->WaitCount == 1); ASSERT (Support->u1.e1.PrefetchMdlHighBits == 0); ASSERT (Support->u1.LongFlags == 0); ASSERT (KeReadStateEvent (&Support->Event) == 0); ASSERT64 (Support->UsedPageTableEntries == 0); Support->Thread = PsGetCurrentThread(); #if DBG Support->ListEntry.Next = NULL; #endif return Support; } } if (OldIrql != MM_NOIRQL) { UNLOCK_PFN (OldIrql); } Support = ExAllocatePoolWithTag (NonPagedPool, sizeof(MMINPAGE_SUPPORT), 'nImM'); if (Support != NULL) { KeInitializeEvent (&Support->Event, NotificationEvent, FALSE); Support->WaitCount = 1; Support->u1.LongFlags = 0; ASSERT (Support->u1.PrefetchMdl == NULL); ASSERT (KeReadStateEvent (&Support->Event) == 0); #if defined (_WIN64) Support->UsedPageTableEntries = 0; #endif #if DBG Support->Thread = NULL; #endif if (OldIrql == MM_NOIRQL) { goto returnok; } InterlockedPushEntrySList (&MmInPageSupportSListHead, (PSLIST_ENTRY)&Support->ListEntry); // // Pool had to be allocated for this inpage block hence the PFN // lock had to be released. No need to delay, but the fault must // be retried due to the PFN lock release. Return a status such // that this will occur quickly. // *Status = STATUS_REFAULT; } else { // // No pool is available - don't let a high priority thread consume // the machine in a continuous refault stream. A delay allows // other system threads to run which will try to free up more pool. // Return a status that will introduce a delay above us in an effort // to make pool available. The advantage of our caller executing the // delay is because he'll do this after releasing the relevant // working set mutex (if any) so the current process can be trimmed // for pages also. // *Status = STATUS_INSUFFICIENT_RESOURCES; } if (OldIrql != MM_NOIRQL) { LOCK_PFN (OldIrql); } return NULL; } VOID MiFreeInPageSupportBlock ( IN PMMINPAGE_SUPPORT Support ) /*++ Routine Description: This routine returns the inpage support block to a list of freed blocks. Arguments: Support - Supplies the inpage support block to put on the free list. Return Value: None. Environment: Kernel mode, APC_LEVEL or below. --*/ { ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL); ASSERT (Support->Thread != NULL); ASSERT (Support->WaitCount != 0); ASSERT ((Support->ListEntry.Next == NULL) || (Support->u1.e1.PrefetchMdlHighBits != 0)); // // An interlock is needed for the WaitCount decrement as an inpage support // block can be simultaneously freed by any number of threads. // // Careful synchronization is applied to the WaitCount field so // that freeing of the inpage block can occur lock-free. Note // that the ReadInProgress bit on each PFN is set and cleared while // holding the PFN lock. Inpage blocks are always (and must be) // freed _AFTER_ the ReadInProgress bit is cleared. // if (InterlockedDecrement (&Support->WaitCount) == 0) { if (Support->u1.e1.PrefetchMdlHighBits != 0) { PMDL Mdl; Mdl = MI_EXTRACT_PREFETCH_MDL (Support); if (Mdl != &Support->Mdl) { ExFreePool (Mdl); } } if (ExQueryDepthSList (&MmInPageSupportSListHead) < MmInPageSupportMinimum) { Support->WaitCount = 1; Support->u1.LongFlags = 0; KeClearEvent (&Support->Event); #if defined (_WIN64) Support->UsedPageTableEntries = 0; #endif #if DBG Support->Thread = NULL; #endif InterlockedPushEntrySList (&MmInPageSupportSListHead, (PSLIST_ENTRY)&Support->ListEntry); return; } ExFreePool (Support); } return; } VOID MiHandleBankedSection ( IN PVOID VirtualAddress, IN PMMVAD Vad ) /*++ Routine Description: This routine invalidates a bank of video memory, calls out to the video driver and then enables the next bank of video memory. Arguments: VirtualAddress - Supplies the address of the faulting page. Vad - Supplies the VAD which maps the range. Return Value: None. Environment: Kernel mode, APCs disabled, working set mutex held. --*/ { PMMBANKED_SECTION Bank; PMMPTE PointerPte; ULONG BankNumber; ULONG size; Bank = ((PMMVAD_LONG) Vad)->u4.Banked; size = Bank->BankSize; MiZeroMemoryPte (Bank->CurrentMappedPte, size >> PAGE_SHIFT); // // Flush the TB as we have invalidated all the PTEs in this range. // MI_FLUSH_PROCESS_TB (FALSE); // // Calculate new bank address and bank number. // PointerPte = MiGetPteAddress ( (PVOID)((ULONG_PTR)VirtualAddress & ~((LONG)size - 1))); Bank->CurrentMappedPte = PointerPte; BankNumber = (ULONG)(((PCHAR)PointerPte - (PCHAR)Bank->BasedPte) >> Bank->BankShift); (Bank->BankedRoutine) (BankNumber, BankNumber, Bank->Context); // // Set the new range valid. // RtlCopyMemory (PointerPte, &Bank->BankTemplate[0], size >> (PAGE_SHIFT - PTE_SHIFT)); return; }
31.078279
133
0.52842
[ "object" ]
aa64e69566ef5a0ca5525e3cc0c05ef1d5b066e7
4,752
h
C
modules/perception/base/image_8u.h
ghdawn/apollo
002eba4a1635d6af7f1ebd2118464bca6f86b106
[ "Apache-2.0" ]
2
2019-02-01T12:35:33.000Z
2019-02-01T12:35:36.000Z
modules/perception/base/image_8u.h
thomasgui76/apollo
808f1d20a08efea23b718b4e423d6619c9d4b412
[ "Apache-2.0" ]
null
null
null
modules/perception/base/image_8u.h
thomasgui76/apollo
808f1d20a08efea23b718b4e423d6619c9d4b412
[ "Apache-2.0" ]
1
2019-02-24T06:20:29.000Z
2019-02-24T06:20:29.000Z
/****************************************************************************** * Copyright 2018 The Apollo 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 <algorithm> #include <atomic> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include "modules/perception/base/blob.h" #include "modules/perception/base/box.h" namespace apollo { namespace perception { namespace base { enum class Color { NONE = 0x00, GRAY = 0x01, RGB = 0x02, BGR = 0x03, }; const std::map<Color, int> kChannelsMap{ {Color::GRAY, 1}, {Color::RGB, 3}, {Color::BGR, 3}}; /** * @brief A wrapper around Blob holders serving as the basic * computational unit for images. * * TODO(dox): more thorough description. */ class Image8U { public: Image8U() : rows_(0), cols_(0), type_(Color::NONE), channels_(0), width_step_(0), blob_(nullptr), offset_(0) {} Image8U(int rows, int cols, Color type, std::shared_ptr<Blob<uint8_t>> blob, int offset = 0) : rows_(rows), cols_(cols), type_(type), blob_(blob), offset_(offset) { channels_ = kChannelsMap.at(type); CHECK_EQ(blob_->num_axes(), 3); CHECK_EQ(blob_->shape(2), channels_); CHECK_LE(offset_ + blob_->offset({rows - 1, cols - 1, channels_ - 1}), blob_->count()); width_step_ = blob_->offset({1, 0, 0}) * static_cast<int>(sizeof(uint8_t)); } Image8U(int rows, int cols, Color type) : rows_(rows), cols_(cols), type_(type), offset_(0) { channels_ = kChannelsMap.at(type); blob_.reset(new Blob<uint8_t>({rows_, cols_, channels_})); width_step_ = blob_->offset({1, 0, 0}) * static_cast<int>(sizeof(uint8_t)); } Image8U(const Image8U &src) : rows_(src.rows_), cols_(src.cols_), type_(src.type_), channels_(src.channels_), width_step_(src.width_step_), blob_(src.blob_), offset_(src.offset_) {} Image8U &operator=(const Image8U &src) { this->rows_ = src.rows_; this->cols_ = src.cols_; this->type_ = src.type_; this->channels_ = src.channels_; this->width_step_ = src.width_step_; this->blob_ = src.blob_; this->offset_ = src.offset_; return *this; } ~Image8U() {} uint8_t *mutable_cpu_data() { return mutable_cpu_ptr(0); } uint8_t *mutable_gpu_data() { return mutable_gpu_ptr(0); } const uint8_t *cpu_data() const { return cpu_ptr(0); } const uint8_t *gpu_data() const { return gpu_ptr(0); } const uint8_t *cpu_ptr(int row = 0) const { return blob_->cpu_data() + blob_->offset({row, 0, 0}) + offset_; } const uint8_t *gpu_ptr(int row = 0) const { return blob_->gpu_data() + blob_->offset({row, 0, 0}) + offset_; } uint8_t *mutable_cpu_ptr(int row = 0) { return blob_->mutable_cpu_data() + blob_->offset({row, 0, 0}) + offset_; } uint8_t *mutable_gpu_ptr(int row = 0) { return blob_->mutable_gpu_data() + blob_->offset({row, 0, 0}) + offset_; } Color type() const { return type_; } int rows() const { return rows_; } int cols() const { return cols_; } int channels() const { return channels_; } int width_step() const { return width_step_; } // @brief: returns the total number of pixels. int total() const { return rows_ * cols_ * channels_; } Image8U operator()(const Rect<int> &roi) { int offset = offset_ + blob_->offset({roi.y, roi.x, 0}); // return Image8U(roi.height, roi.width, type_, blob_, offset); return Image8U(roi.height, roi.width, type_, blob_, offset); } std::shared_ptr<Blob<uint8_t>> blob() { return blob_; } // DONOT return `std::shared_ptr<const Blob<uint8_t>> &` or `const std::... &` std::shared_ptr<const Blob<uint8_t>> blob() const { return blob_; } protected: int rows_; int cols_; Color type_; int channels_; int width_step_; std::shared_ptr<Blob<uint8_t>> blob_; int offset_; }; // class Image8U typedef std::shared_ptr<Image8U> Image8UPtr; typedef std::shared_ptr<const Image8U> Image8UConstPtr; } // namespace base } // namespace perception } // namespace apollo
29.886792
80
0.633628
[ "shape", "vector" ]
aa64ffe3a5c1a63bf6645615fd4e1e696da5ef30
21,705
c
C
gpac-0.7.1/src/terminal/media_control.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
null
null
null
gpac-0.7.1/src/terminal/media_control.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
null
null
null
gpac-0.7.1/src/terminal/media_control.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
1
2021-04-15T18:27:37.000Z
2021-04-15T18:27:37.000Z
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Media terminal sub-project * * GPAC 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, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "media_control.h" #include <gpac/constants.h> #include <gpac/internal/compositor_dev.h> void mediacontrol_restart(GF_ObjectManager *odm) { GF_List *to_restart; GF_ObjectManager *ctrl_od; GF_Clock *ck, *scene_ck; u32 i; u32 current_seg; #ifndef GPAC_DISABLE_VRML MediaControlStack *ctrl; #endif if (!odm || (odm->flags & GF_ODM_NO_TIME_CTRL) ) return; #ifndef GPAC_DISABLE_VRML ctrl = gf_odm_get_mediacontrol(odm); if (ctrl) { /*we have a control - filter calls to only handle objects owning media control*/ ctrl_od = ctrl->stream->odm; /*if media control owns the scene this OD refers to the scene is always restarted - TODO make that an option*/ if (!ctrl_od->subscene) { if (ctrl->stream->odm != odm) return; } odm = ctrl->stream->odm; /*this is inline restart - only possible through media control*/ if (odm->subscene && odm->subscene->root_od==ctrl->stream->odm) { gf_inline_restart(odm->subscene); return; } } #endif /*if clock is main scene clock do nothing*/ scene_ck = gf_odm_get_media_clock(odm->parentscene->root_od); if (gf_odm_shares_clock(odm, scene_ck)) { if (odm->parentscene->is_dynamic_scene) gf_scene_restart_dynamic(odm->parentscene, 0, 0, 0); return; } /*otherwise locate all objects sharing the clock*/ ck = gf_odm_get_media_clock(odm); if (!ck) return; current_seg = 0; #ifndef GPAC_DISABLE_VRML /*store current segment idx*/ if (ctrl) { current_seg = ctrl->current_seg; /*if last segment is passed restart*/ if (gf_list_count(ctrl->seg) == current_seg) current_seg = 0; } #endif to_restart = gf_list_new(); /*do stop/start in 2 pass, it's much cleaner for servers*/ i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(odm->parentscene->resources, &i))) { if (!gf_odm_shares_clock(ctrl_od, ck)) continue; /*if running, stop and collect for restart*/ if (ctrl_od->state) { gf_odm_stop(ctrl_od, 1); gf_list_add(to_restart, ctrl_od); } } /*force clock reset since we don't know how OD ordering is done*/ gf_clock_reset(ck); #ifndef GPAC_DISABLE_VRML if (ctrl) ctrl->current_seg = current_seg; #endif /*play on all ODs collected for restart*/ i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(to_restart, &i))) { //we want to make sure restart is clled right away with the current media control settings gf_odm_start(ctrl_od, 2); } gf_list_del(to_restart); } Bool MC_URLChanged(MFURL *old_url, MFURL *new_url) { u32 i; if (gf_mo_get_od_id(old_url) != gf_mo_get_od_id(new_url)) return 1; if ((new_url->count==1) && new_url->vals[0].url && !strlen(new_url->vals[0].url) ) new_url->count = 0; if (old_url->count != new_url->count) return 1; for (i=0; i<old_url->count; i++) { if (old_url->vals[i].url || new_url->vals[i].url) { if (!old_url->vals[i].url || !new_url->vals[i].url) return 1; if (strcmp(old_url->vals[i].url, new_url->vals[i].url)) return 1; } } return 0; } /*resume all objects*/ void mediacontrol_resume(GF_ObjectManager *odm, Bool resume_to_live) { u32 i; GF_ObjectManager *ctrl_od; GF_Scene *in_scene; GF_Clock *ck; if (odm->flags & GF_ODM_NO_TIME_CTRL) return; /*otherwise locate all objects sharing the clock*/ ck = gf_odm_get_media_clock(odm); if (!ck) return; in_scene = odm->parentscene; if (odm->subscene) { assert(odm->subscene->root_od==odm); assert(odm->subscene->is_dynamic_scene || gf_odm_shares_clock(odm, ck) ); /*resume root*/ gf_odm_resume(odm); in_scene = odm->subscene; } i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(in_scene->resources, &i))) { if (!odm->subscene && !gf_odm_shares_clock(ctrl_od, ck)) continue; if (ctrl_od->addon && (ctrl_od->addon->addon_type==GF_ADDON_TYPE_MAIN)) { gf_clock_resume(ck); if (resume_to_live) gf_scene_select_main_addon(in_scene, ctrl_od, GF_FALSE, 0); } if (ctrl_od->subscene) { mediacontrol_resume(ctrl_od, resume_to_live); } else { gf_odm_resume(ctrl_od); } } } /*pause all objects*/ void mediacontrol_pause(GF_ObjectManager *odm) { u32 i; GF_ObjectManager *ctrl_od; GF_Scene *in_scene; GF_Clock *ck; if (odm->flags & GF_ODM_NO_TIME_CTRL) return; /*otherwise locate all objects sharing the clock*/ ck = gf_odm_get_media_clock(odm); if (!ck) { odm->flags |= GF_ODM_PAUSE_QUEUED; return; } in_scene = odm->parentscene; if (odm->subscene) { assert(odm->subscene->root_od==odm); assert(odm->subscene->is_dynamic_scene || gf_odm_shares_clock(odm, ck) ); /*pause root*/ gf_odm_pause(odm); in_scene = odm->subscene; } i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(in_scene->resources, &i))) { if (!odm->subscene && !gf_odm_shares_clock(ctrl_od, ck)) continue; if (ctrl_od->addon && (ctrl_od->addon->addon_type==GF_ADDON_TYPE_MAIN)) { gf_clock_pause(ck); gf_scene_select_main_addon(in_scene, ctrl_od, GF_TRUE, gf_clock_time(ck) ); } if (ctrl_od->subscene) { mediacontrol_pause(ctrl_od); } else { gf_odm_pause(ctrl_od); } } } /*pause all objects*/ void mediacontrol_set_speed(GF_ObjectManager *odm, Fixed speed) { u32 i; GF_ObjectManager *ctrl_od; GF_Scene *in_scene; GF_Clock *ck; if (odm->flags & GF_ODM_NO_TIME_CTRL) return; /*locate all objects sharing the clock*/ ck = gf_odm_get_media_clock(odm); if (!ck) return; in_scene = odm->parentscene; if (odm->subscene) { assert(odm->subscene->root_od==odm); in_scene = odm->subscene; //dynamic scene with speed direction, we need to re-start everything to issue new PLAY requests if (in_scene->is_dynamic_scene && (gf_mulfix(ck->speed, speed) < 0)) { u32 time = gf_clock_time(ck); gf_clock_set_speed(ck, speed); //enable main addon if (speed<0) { i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(in_scene->resources, &i))) { if (ctrl_od->addon && (ctrl_od->addon->addon_type==GF_ADDON_TYPE_MAIN)) { gf_scene_select_main_addon(in_scene, ctrl_od, GF_TRUE, gf_clock_time(ck) ); break; } } } gf_scene_restart_dynamic(in_scene, time, 0, 1); return; } gf_clock_set_speed(ck, speed); gf_odm_set_speed(odm, speed, GF_TRUE); } i=0; while ((ctrl_od = (GF_ObjectManager*)gf_list_enum(in_scene->resources, &i))) { if (!gf_odm_shares_clock(ctrl_od, ck)) continue; if (ctrl_od->subscene) { mediacontrol_set_speed(ctrl_od, speed); } else { gf_odm_set_speed(ctrl_od, speed, GF_TRUE); } } } #ifndef GPAC_DISABLE_VRML void MC_GetRange(MediaControlStack *ctrl, Double *start_range, Double *end_range) { u32 i; Double duration; GF_Segment *last_seg, *prev_seg; if (gf_list_count(ctrl->seg)) { GF_Segment *desc = (GF_Segment *)gf_list_get(ctrl->seg, ctrl->current_seg); if (!desc) { *start_range = 0; *end_range = 0; return; } /*get last segment in consecutive range so that we never issue stop/play between consecutive segments*/ prev_seg = desc; last_seg = NULL; duration = desc->Duration; i=1+ctrl->current_seg; while ((last_seg = (GF_Segment *)gf_list_enum(ctrl->seg, &i))) { if (prev_seg->startTime + prev_seg->Duration != last_seg->startTime) { last_seg = NULL; break; } prev_seg = last_seg; duration += last_seg->Duration; } // if (!last_seg) last_seg = desc; *start_range = desc->startTime; if (ctrl->control->mediaStartTime>=0) *start_range += ctrl->control->mediaStartTime; *end_range = desc->startTime; if ((ctrl->control->mediaStopTime>=0) && ctrl->control->mediaStopTime<duration) { *end_range += ctrl->control->mediaStopTime; } else { *end_range += duration; } } else { if (ctrl->control->mediaStartTime>=0) *start_range = ctrl->control->mediaStartTime; if (ctrl->control->mediaStopTime>=0) *end_range = ctrl->control->mediaStopTime; } } void RenderMediaControl(GF_Node *node, void *rs, Bool is_destroy) { Bool shall_restart, need_restart; GF_MediaObject *prev; GF_ObjectManager *odm; GF_TraverseState *tr_state = (GF_TraverseState *)rs; MediaControlStack *stack =(MediaControlStack *) gf_node_get_private(node); if (is_destroy) { GF_ObjectManager *odm; MediaControlStack *stack = (MediaControlStack *) gf_node_get_private(node); /*reset ODM using this control*/ if (stack->stream) { if (stack->stream->odm) { odm = stack->stream->odm; gf_odm_remove_mediacontrol(odm, stack); } /*also removes the association ck<->MC if the object has been destroyed before the node*/ if (stack->ck) stack->ck->mc = NULL; } gf_list_del(stack->seg); gf_sg_vrml_mf_reset(&stack->url, GF_SG_VRML_MFURL); gf_free(stack); return; } //we need to disable culling otherwise we may never be called back again ... tr_state->disable_cull = 1; /*not changed nothing to do - note we need to register with stream yet for control switching...*/ if (stack->stream && (!stack->changed || !stack->control->enabled)) return; need_restart = (stack->changed==2) ? 1 : 0; shall_restart = (stack->control->mediaStartTime>=0) ? 1 : 0; /*check url target*/ if (stack->stream) { if (MC_URLChanged(&stack->url, &stack->control->url)) { gf_sg_vrml_mf_reset(&stack->url, GF_SG_VRML_MFURL); prev = stack->stream; if (gf_list_find(stack->parent->scene_objects, prev)<0) prev = NULL; stack->stream = gf_scene_get_media_object(stack->parent, &stack->control->url, GF_MEDIA_OBJECT_UNDEF, 0); if (stack->stream) { if (!stack->stream->odm) return; /*MediaControl on inline: if dynamic scene, make sure it is connected before attaching...*/ if (stack->stream->odm->subscene) { if (stack->stream->odm->subscene->is_dynamic_scene && !stack->stream->odm->subscene->dyn_ck) return; } gf_sg_vrml_field_copy(&stack->url, &stack->control->url, GF_SG_VRML_MFURL); /*remove from prev*/ if (prev && prev->odm && (prev != stack->stream)) gf_odm_remove_mediacontrol(prev->odm, stack); /*register with new*/ /*if we assigned the media control to an exiting object - force the state of the object*/ gf_odm_set_mediacontrol((GF_ObjectManager *) stack->stream->odm, stack); while (gf_list_count(stack->seg)) gf_list_rem(stack->seg, 0); gf_odm_init_segments((GF_ObjectManager *) stack->stream->odm, stack->seg, &stack->control->url); stack->current_seg = 0; //do not restart if no mediaStartTime and speed is 1 if ((stack->control->mediaStartTime>0) || gf_list_count(stack->seg) || (stack->control->mediaSpeed != FIX_ONE) ) { shall_restart = need_restart = 1; } else { shall_restart = need_restart = 0; //URL changed, we are by default in PLAY mode. stack->media_speed = 1; } stack->ck = gf_odm_get_media_clock(stack->stream->odm); } /*control has been removed and we were paused, resume*/ else if (stack->paused) { if (prev) mediacontrol_resume((GF_ObjectManager *) prev->odm, 0); stack->paused = 0; } /*MediaControl has been detached*/ else { if (prev) gf_odm_remove_mediacontrol(prev->odm, stack); return; } } } else { stack->stream = gf_scene_get_media_object(stack->parent, &stack->control->url, GF_MEDIA_OBJECT_UNDEF, 0); if (!stack->stream || !stack->stream->odm) { if (stack->control->url.count) gf_term_invalidate_compositor(stack->parent->root_od->term); stack->stream = NULL; stack->changed = 0; return; } stack->ck = gf_odm_get_media_clock(stack->stream->odm); /*OD not ready yet*/ if (!stack->ck) { stack->stream = NULL; if (stack->control->url.count) { stack->is_init = 0; gf_term_invalidate_compositor(stack->parent->root_od->term); } return; } gf_sg_vrml_field_copy(&stack->url, &stack->control->url, GF_SG_VRML_MFURL); gf_odm_set_mediacontrol((GF_ObjectManager *) stack->stream->odm, stack); while (gf_list_count(stack->seg)) gf_list_rem(stack->seg, 0); gf_odm_init_segments((GF_ObjectManager *) stack->stream->odm, stack->seg, &stack->control->url); stack->current_seg = 0; /*we shouldn't have to restart unless start/stop times have been changed, which is tested below*/ need_restart = 0; } if ((stack->is_init && !stack->changed) || !stack->control->enabled || !stack->stream) return; /*if not previously enabled and now enabled, switch all other controls off and reactivate*/ if (!stack->enabled) { stack->enabled = 1; need_restart = gf_odm_switch_mediacontrol(stack->stream->odm, stack); } stack->changed = 0; if (!stack->control->mediaSpeed) shall_restart = 0; odm = (GF_ObjectManager *)stack->stream->odm; /*check for changes*/ if (!stack->is_init) { need_restart = 0; /*not linked yet*/ if (!odm) return; stack->media_speed = stack->control->mediaSpeed; stack->enabled = stack->control->enabled; stack->media_start = stack->control->mediaStartTime; if (stack->media_stop != stack->control->mediaStopTime) { if (stack->control->mediaStopTime < 1000000000) need_restart = 1; stack->media_stop = stack->control->mediaStopTime; } stack->is_init = 1; stack->paused = 0; /*the object has already been started, and media start time is not 0, restart*/ if (stack->stream->num_open) { if (need_restart || (stack->media_start > 0) || (gf_list_count(stack->seg)>0 ) || (stack->media_speed!=FIX_ONE ) ) { mediacontrol_restart(odm); } else if (stack->media_speed == 0) { mediacontrol_pause(odm); stack->paused = 1; } } return; } if (stack->media_speed != stack->control->mediaSpeed) { /*if no speed pause*/ if (!stack->control->mediaSpeed && !stack->paused) { mediacontrol_pause(odm); stack->paused = 1; } /*else resume if paused*/ else if (stack->control->mediaSpeed && stack->paused) { mediacontrol_resume(odm, 0); stack->paused = 0; need_restart += shall_restart; } /*else set speed*/ else if (stack->media_speed && stack->control->mediaSpeed) { /*don't set speed if we have to restart the media ...*/ if (!shall_restart) mediacontrol_set_speed(odm, stack->control->mediaSpeed); need_restart += shall_restart; } /*init state was paused*/ else if (!stack->media_speed) { need_restart ++; } stack->media_speed = stack->control->mediaSpeed; } /*check start/stop changes*/ if (stack->media_start != stack->control->mediaStartTime) { stack->media_start = stack->control->mediaStartTime; need_restart += shall_restart; } /*stop change triggers restart no matter what (new range) if playing*/ if (stack->media_stop != stack->control->mediaStopTime) { stack->media_stop = stack->control->mediaStopTime; if (stack->control->mediaSpeed) need_restart = 1; } if (need_restart) { mediacontrol_restart(odm); } /*handle preroll*/ } void InitMediaControl(GF_Scene *scene, GF_Node *node) { MediaControlStack *stack; GF_SAFEALLOC(stack, MediaControlStack); if (!stack) { GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[Terminal] Failed to allocate media control stack\n")); return; } stack->changed = 1; stack->parent = scene; stack->control = (M_MediaControl *)node; stack->seg = gf_list_new(); /*default values are stored on first render*/ gf_node_set_callback_function(node, RenderMediaControl); gf_node_set_private(node, stack); } void MC_Modified(GF_Node *node) { MediaControlStack *stack =(MediaControlStack *) gf_node_get_private(node); if (!stack) return; if (stack->changed!=2) { /*check URL*/ if (MC_URLChanged(&stack->url, &stack->control->url)) stack->changed = 2; /*check speed (play/pause)*/ else if (stack->media_speed != stack->control->mediaSpeed) stack->changed = 1; /*check mediaStartTime (seek)*/ else if (stack->media_start != stack->control->mediaStartTime) { /*do not reevaluate if mediaStartTime is reset to -1 (current time)*/ if (stack->control->mediaStartTime!=-1.0) stack->changed = 2; /*check mediaStopTime <0 (timeshift buffer control)*/ } else if (stack->media_stop != stack->control->mediaStopTime) { if (stack->control->mediaStopTime<=0) stack->changed = 2; } // else stack->changed = 1; } gf_node_dirty_set( gf_sg_get_root_node(gf_node_get_graph(node)), 0, 1); /*invalidate scene, we recompute MC state in render*/ gf_term_invalidate_compositor(stack->parent->root_od->term); } void gf_odm_set_mediacontrol(GF_ObjectManager *odm, MediaControlStack *ctrl) { u32 i; GF_Channel *ch; /*keep track of it*/ if (ctrl && (gf_list_find(odm->mc_stack, ctrl) < 0)) gf_list_add(odm->mc_stack, ctrl); if (ctrl && !ctrl->control->enabled) return; if (odm->subscene && odm->subscene->is_dynamic_scene) { if (odm->subscene->dyn_ck) { /*deactivate current control*/ if (ctrl && odm->subscene->dyn_ck->mc) { odm->subscene->dyn_ck->mc->control->enabled = 0; gf_node_event_out((GF_Node *)odm->subscene->dyn_ck->mc->control, 7/*"enabled"*/); } odm->subscene->dyn_ck->mc = ctrl; } } else { /*for each clock in the controled OD*/ i=0; while ((ch = (GF_Channel*)gf_list_enum(odm->channels, &i))) { if (ch->clock->mc != ctrl) { /*deactivate current control*/ if (ctrl && ch->clock->mc) { ch->clock->mc->control->enabled = 0; gf_node_event_out((GF_Node *)ch->clock->mc->control, 7/*"enabled"*/); } /*and attach this control to the clock*/ ch->clock->mc = ctrl; } } } /*store active control on media*/ odm->media_ctrl = gf_odm_get_mediacontrol(odm); } MediaControlStack *gf_odm_get_mediacontrol(GF_ObjectManager *odm) { GF_Clock *ck; ck = gf_odm_get_media_clock(odm); if (!ck) return NULL; return ck->mc; } void gf_odm_remove_mediacontrol(GF_ObjectManager *odm, MediaControlStack *ctrl) { gf_list_del_item(odm->mc_stack, ctrl); /*removed. Note the spec doesn't say what to do in this case...*/ if (odm->media_ctrl == ctrl) { /*we're about to release the media control from this object - if paused, force a resume (as if no MC was set)*/ if (ctrl->paused) mediacontrol_resume(odm, 0); gf_odm_set_mediacontrol(odm, NULL); } } Bool gf_odm_switch_mediacontrol(GF_ObjectManager *odm, MediaControlStack *ctrl) { u32 i; MediaControlStack *st2; if (!ctrl->control->enabled) return 0; /*for all media controls other than this one force enable to false*/ i=0; while ((st2 = (MediaControlStack *)gf_list_enum(odm->mc_stack, &i))) { if (st2 == ctrl) continue; if (st2->control->enabled) { st2->control->enabled = 0; gf_node_event_out((GF_Node *) st2->control, 7/*"enabled"*/); } st2->enabled = 0; } if (ctrl == odm->media_ctrl) return 0; gf_odm_set_mediacontrol(odm, ctrl); return 1; } Bool gf_odm_check_segment_switch(GF_ObjectManager *odm) { u32 count, i; GF_Segment *cur, *next; MediaControlStack *ctrl = gf_odm_get_mediacontrol(odm); /*if no control or control not on this object ignore segment switch*/ if (!ctrl || (ctrl->stream->odm != odm)) return 0; count = gf_list_count(ctrl->seg); /*reached end of controled stream (no more segments)*/ if (ctrl->current_seg>=count) return 0; /*synth media, trigger if end of segment run-time*/ if (!odm->codec || ((odm->codec->type!=GF_STREAM_VISUAL) && (odm->codec->type!=GF_STREAM_AUDIO))) { GF_Clock *ck = gf_odm_get_media_clock(odm); u32 now = gf_clock_time(ck); u64 dur = odm->subscene ? odm->subscene->duration : odm->duration; cur = (GF_Segment *)gf_list_get(ctrl->seg, ctrl->current_seg); if (odm->subscene && odm->subscene->needs_restart) return 0; if (cur) dur = (u32) ((cur->Duration+cur->startTime)*1000); //if next frame is after current segment trigger switch now if (now + odm->term->compositor->frame_duration < dur) return 0; } else { /*FIXME - for natural media with scalability, we should only process when all streams of the object are done*/ } /*get current segment and move to next one*/ cur = (GF_Segment *)gf_list_get(ctrl->seg, ctrl->current_seg); ctrl->current_seg ++; /*resync in case we have been issuing a play range over several segments*/ for (i=ctrl->current_seg; i<count; i++) { next = (GF_Segment *)gf_list_get(ctrl->seg, i); if ( /*if next seg start is after cur seg start*/ (cur->startTime < next->startTime) /*if next seg start is before cur seg end*/ && (cur->startTime + cur->Duration > next->startTime) /*if next seg start is already passed*/ && (1000*next->startTime < odm->media_current_time) /*then next segment was taken into account when requesting play*/ ) { cur = next; ctrl->current_seg ++; } } /*if last segment in ctrl is done, end of stream*/ if (ctrl->current_seg >= count) return 0; next = (GF_Segment *)gf_list_get(ctrl->seg, ctrl->current_seg); /*if next seg start is not in current seg, media needs restart*/ if ((next->startTime < cur->startTime) || (cur->startTime + cur->Duration < next->startTime)) mediacontrol_restart(odm); return 1; } #endif /*GPAC_DISABLE_VRML*/
30.356643
121
0.689519
[ "render", "object" ]
aa6bdb082be1e95a190cdb7acc1b2a3a1b2847a5
4,962
h
C
cvs/objects/investment/include/output_growth_calculator.h
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
null
null
null
cvs/objects/investment/include/output_growth_calculator.h
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
null
null
null
cvs/objects/investment/include/output_growth_calculator.h
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
2
2021-07-26T05:56:09.000Z
2022-02-24T10:29:30.000Z
#ifndef _OUTPUT_GROWTH_CALCULATOR_H_ #define _OUTPUT_GROWTH_CALCULATOR_H_ #if defined(_MSC_VER) #pragma once #endif /* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file output_growth_calculator.h * \ingroup Objects * \brief The OutputGrowthCalculator class header file. * \author Josh Lurz */ #include <string> #include <vector> #include "investment/include/igrowth_calculator.h" class Tabs; class Demographic; class IInvestable; class NationalAccount; /*! * \ingroup Objects * \brief This object contains the standard methodology and variables to * calculate the growth of investment based on an output growth rate. * \details This class is used to determine a scalar which when applied to the * previous period's investment will grow a sector through investment to * reach a proscribed level of output. This growth rate is read-in to * the model and may vary by period. Note that since the trial capital * required to grow output is only calculated once per period, the * equilibrium level of output for this sector will not exactly equal * the previous period's output times the growth rate. * \note This object encapsulates the DEMK functionality of Legacy-SGM. * \author Josh Lurz */ class OutputGrowthCalculator: public IGrowthCalculator { public: OutputGrowthCalculator(); static const std::string& getXMLNameStatic(); void XMLParse( const xercesc::DOMNode* aCurr ); void toDebugXML( const int period, std::ostream& aOut, Tabs* aTabs ) const; void toInputXML( std::ostream& aOut, Tabs* aTabs ) const; double calcInvestmentDependencyScalar( const std::vector<IInvestable*>& aInvestables, const Demographic* aDemographic, const NationalAccount& aNationalAccount, const std::string& aGoodName, const std::string& aRegionName, const double aPrevInvestment, const double aInvestmentLogitExp, const int aPeriod ); protected: //! The read-in per period output growth rate. std::vector<double> mOutputGrowthRate; //! The cached level of trial capital per period so that it is not //! recalculated in each iteration. mutable std::vector<double> mTrialCapital; //! Fraction of total regional investment to use for new technologies. double mAggregateInvestmentFraction; double calcTrialCapital( const std::vector<IInvestable*>& aInvestables, const NationalAccount& aNationalAccount, const std::string& aGoodName, const std::string& aRegionName, const double aInvestmentLogitExp, const int aPeriod ); double calcOutputGap( const std::vector<IInvestable*>& aInvestables, const NationalAccount& aNationalAccount, const std::string& aGoodName, const std::string& aRegionName, const double aInvestmentLogitExp, const int aPeriod ) const; }; #endif // _OUTPUT_GROWTH_CALCULATOR_H_
44.303571
89
0.676945
[ "object", "vector", "model" ]
aa70fed5f86c9eb51fc3be3804ecc76917666593
1,547
h
C
Day1/build/iOS/Preview/include/Outracks.Simulator.Reflection.Native.CppProperty.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/include/Outracks.Simulator.Reflection.Native.CppProperty.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
Day1/build/iOS/Preview/include/Outracks.Simulator.Reflection.Native.CppProperty.h
sauvikatinnofied/ExploringFuse
cc272d55c7221d88ba773494f571b6528e5279f8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '/usr/local/share/uno/Packages/Outracks.Simulator.Reflection.Uno/0.0.0/Native/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Outracks.Simulator.Reflection.Native.IProperty.h> #include <Uno.Object.h> namespace g{namespace Outracks{namespace Simulator{namespace Reflection{namespace Native{struct CppProperty;}}}}} namespace g{ namespace Outracks{ namespace Simulator{ namespace Reflection{ namespace Native{ // internal sealed extern class CppProperty :439 // { struct CppProperty_type : uType { ::g::Outracks::Simulator::Reflection::Native::IProperty interface0; }; CppProperty_type* CppProperty_typeof(); void CppProperty__ctor__fn(CppProperty* __this, uType* declaringType, uType* type, uString* name); void CppProperty__get_DeclaringType_fn(CppProperty* __this, uType** __retval); void CppProperty__get_GetMethod_fn(CppProperty* __this, uObject** __retval); void CppProperty__New1_fn(uType* declaringType, uType* type, uString* name, CppProperty** __retval); void CppProperty__get_SetMethod_fn(CppProperty* __this, uObject** __retval); struct CppProperty : uObject { uStrong<uType*> _declaringType; uStrong<uString*> _name; uStrong<uType*> _type; void ctor_(uType* declaringType, uType* type, uString* name); uType* DeclaringType(); uObject* GetMethod(); uObject* SetMethod(); static CppProperty* New1(uType* declaringType, uType* type, uString* name); }; // } }}}}} // ::g::Outracks::Simulator::Reflection::Native
35.159091
121
0.764059
[ "object" ]
aa80bebd858f95de5a8d2807b50e3fcd16ec3b34
2,518
h
C
lib/Cinder/include/cinder/app/AppImplCocoaTouchRendererGl.h
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
1
2018-07-20T03:56:15.000Z
2018-07-20T03:56:15.000Z
lib/Cinder/include/cinder/app/AppImplCocoaTouchRendererGl.h
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
lib/Cinder/include/cinder/app/AppImplCocoaTouchRendererGl.h
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
/* Copyright (c) 2010, The Barbarian Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <UIKit/UIKit.h> #import "cinder/app/App.h" #import "cinder/app/Renderer.h" @interface AppImplCocoaTouchRendererGl : NSObject { cinder::app::RendererGl *mRenderer; // equivalent of a weak_ptr; 'renderer' owns this // TODO: remove, this is unused cinder::app::App *mApp; UIView *mCinderView; EAGLContext *mContext; // The pixel dimensions of the CAEAGLLayer GLint mBackingWidth, mBackingHeight; // The dimensions of the CAEAGLLayer in points GLint mPointsWidth, mPointsHeight; // The OpenGL names for the framebuffer and renderbuffer used to render to this view GLuint mViewFramebuffer, mViewRenderBuffer, mDepthRenderBuffer; GLuint mMsaaFramebuffer, mMsaaRenderBuffer; BOOL mUsingMsaa; int mMsaaSamples; } - (id)initWithFrame:(CGRect)frame cinderView:(UIView*)aCinderView app:(cinder::app::App*)aApp renderer:(cinder::app::RendererGl*)aRenderer sharedRenderer:(cinder::app::RendererGlRef)sharedRenderer; - (EAGLContext*)getEaglContext; - (void)makeCurrentContext; - (void)flushBuffer; - (void)setFrameSize:(CGSize)newSize; - (void)defaultResize; - (BOOL)needsDrawRect; @end
42.677966
198
0.75973
[ "render" ]
aa89fea0ac2ac07c5fa648b69d2eb1c9ebf8c598
2,734
h
C
lib/EMP/emp-tool/circuits/integer.h
zpleefly/libscapi
27d7d964d645ed111c2cc9870087971cf13e24f4
[ "MIT" ]
null
null
null
lib/EMP/emp-tool/circuits/integer.h
zpleefly/libscapi
27d7d964d645ed111c2cc9870087971cf13e24f4
[ "MIT" ]
2
2021-03-20T05:38:48.000Z
2021-03-31T20:14:11.000Z
lib/EMP/emp-tool/circuits/integer.h
zpleefly/libscapi
27d7d964d645ed111c2cc9870087971cf13e24f4
[ "MIT" ]
null
null
null
#ifndef INTEGER_H__ #define INTEGER_H__ #include "bit.h" #include "number.h" #include "comparable.h" #include "swappable.h" #include <vector> #include <algorithm> #include <math.h> using std::vector; using std::min; class Integer : public Swappable<Integer>, public Comparable<Integer> { public: int length = 0; Bit* bits = nullptr; Integer(Integer&& in) : length(in.length) { bits = in.bits; in.bits = nullptr; } Integer(const Integer& in): length(in.length) { bits = new Bit[length]; memcpy(bits, in.bits, sizeof(Bit)*length); } Integer& operator= (Integer rhs){ length = rhs.length; std::swap(bits, rhs.bits); return *this; } Integer(int len, const void * b) : length(len) { bits = new Bit[len]; memcpy(bits, b, sizeof(Bit)*len); } ~Integer() { if (bits!=nullptr) delete[] bits; } Integer(int length, const string& str, int party = PUBLIC); Integer(int length, long long input, int party = PUBLIC); Integer() :length(0),bits(nullptr){ } //Comparable Bit geq(const Integer & rhs) const; Bit equal(const Integer & rhs) const; //Swappable Integer select(const Bit & sel, const Integer & rhs) const; Integer operator^(const Integer& rhs) const; int size() const; template<typename O> O reveal(int party=PUBLIC) const; Integer abs() const; Integer& resize(int length, bool signed_extend = true); Integer modExp(Integer p, Integer q); Integer leading_zeros() const; Integer hamming_weight() const; Integer operator<<(int shamt)const; Integer operator>>(int shamt)const; Integer operator<<(const Integer& shamt)const; Integer operator>>(const Integer& shamt)const; Integer operator+(const Integer& rhs)const; Integer operator-(const Integer& rhs)const; Integer operator-()const; Integer operator*(const Integer& rhs)const; Integer operator/(const Integer& rhs)const; Integer operator%(const Integer& rhs)const; Integer operator&(const Integer& rhs)const; Integer operator|(const Integer& rhs)const; Bit& operator[](int index); const Bit & operator[](int index) const; //batcher template<typename... Args> static size_t bool_size(size_t size, Args... args) { return size; } static void bool_data(bool* data, size_t len, long long num) { bool_data(data, len, std::to_string(num)); } static void bool_data(bool* data, size_t len, string str) { string bin = dec_to_bin(str); std::reverse(bin.begin(), bin.end()); // cout << "convert " <<str<<" "<<bin<<endl; int l = (bin.size() > (size_t)len ? len : bin.size()); for(int i = 0; i < l; ++i) data[i] = (bin[i] == '1'); for (size_t i = l; i < len; ++i) data[i] = data[l-1]; } }; void init(Bit * bits, const bool* b, int length, int party = PUBLIC); #include "integer.hpp" #endif// INTEGER_H__
27.34
79
0.685077
[ "vector" ]
aa900aa59209345ce7b4b71ca1137750c1dcd490
18,329
h
C
Examples/iOS/APKit.framework/Headers/APKit-Swift.h
joy0304/Swift-AI
0d1c659027766faae8f886f0d2fc76c3e8d9dcc0
[ "MIT" ]
null
null
null
Examples/iOS/APKit.framework/Headers/APKit-Swift.h
joy0304/Swift-AI
0d1c659027766faae8f886f0d2fc76c3e8d9dcc0
[ "MIT" ]
null
null
null
Examples/iOS/APKit.framework/Headers/APKit-Swift.h
joy0304/Swift-AI
0d1c659027766faae8f886f0d2fc76c3e8d9dcc0
[ "MIT" ]
1
2019-12-05T09:39:16.000Z
2019-12-05T09:39:16.000Z
// Generated by Apple Swift version 2.1 (swiftlang-700.1.101.6 clang-700.1.76) #pragma clang diagnostic push #if defined(__has_include) && __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <objc/NSObject.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if defined(__has_include) && __has_include(<uchar.h>) # include <uchar.h> #elif !defined(__cplusplus) || __cplusplus < 201103L typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; #endif typedef struct _NSZone NSZone; #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if defined(__has_attribute) && __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if defined(__has_attribute) && __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if defined(__has_attribute) && __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type #endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); #if defined(__has_feature) && __has_feature(modules) @import UIKit; @import CoreGraphics; @import Foundation; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" @class NSCoder; /// A subclass of UIView that provides the ability to add two optional borders. One to the top, one to the bottom, or both. /// /// :param: border The position of the border(s) /// :param: color The color of the border(s) SWIFT_CLASS("_TtC5APKit12APBorderView") @interface APBorderView : UIView - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)updateConstraints; - (void)hideBorders; - (void)showBorders; @end SWIFT_CLASS("_TtC5APKit12APConstraint") @interface APConstraint : NSLayoutConstraint - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end SWIFT_CLASS("_TtC5APKit11APEmptyView") @interface APEmptyView : UIView - (nonnull instancetype)init; - (nonnull instancetype)initWithFrame:(CGRect)frame OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end @class APStackView; SWIFT_CLASS("_TtC5APKit10APGridView") @interface APGridView : UIView /// The top-level master stackView containing each of the horizontalStackViews. @property (nonatomic, strong) APStackView * __nonnull verticalStackView; /// The horizontal-axis stackViews containing each of the views in the grid. @property (nonatomic, copy) NSArray<APStackView *> * __nonnull horizontalStackViews; @property (nonatomic, readonly, copy) NSArray<UIView *> * __nonnull arrangedSubviews; /// The spacing between each view in the grid. @property (nonatomic) CGFloat spacing; /// The edge insets for the grid view (default zero). Specify positive values for insets; negative values may be used to acheive 'outsets.' @property (nonatomic) UIEdgeInsets edgeInsets; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)updateConstraints; - (void)reloadData; - (void)removeCellAtPositionWithRow:(NSInteger)row column:(NSInteger)column; - (void)hideCellAtPositionWithRow:(NSInteger)row column:(NSInteger)column; - (void)removeRow:(NSInteger)row; - (void)hideRow:(NSInteger)row; - (void)unhideRow:(NSInteger)row; - (void)insertRowAtIndex:(NSInteger)index; @end SWIFT_CLASS("_TtC5APKit17APLabelWithInsets") @interface APLabelWithInsets : UILabel - (nonnull instancetype)initWithInsets:(UIEdgeInsets)insets; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)drawTextInRect:(CGRect)rect; @end @class APMultiSegmentedControlSegment; @class UIColor; SWIFT_CLASS("_TtC5APKit23APMultiSegmentedControl") @interface APMultiSegmentedControl : UIView @property (nonatomic, copy) NSArray<APMultiSegmentedControlSegment *> * __nonnull segments; @property (nonatomic, readonly, strong) UIView * __nonnull segmentContainerView; - (nonnull instancetype)initWithSegementTitles:(NSArray<NSString *> * __nonnull)segmentTitles normalBackgroundColor:(UIColor * __nonnull)normal selectedBackgroundColor:(UIColor * __nonnull)selected highlightedBackgroundColor:(UIColor * __nonnull)highlighted; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)updateConstraints; - (void)selectSegmentsAtIndexes:(NSArray<NSNumber *> * __nonnull)indexes; - (void)deselectAllSegments; - (NSArray<NSNumber *> * __nonnull)selectedSegments; @end SWIFT_CLASS("_TtC5APKit30APMultiSegmentedControlSegment") @interface APMultiSegmentedControlSegment : UIButton - (nonnull instancetype)initWithTitle:(NSString * __nonnull)title normalBackgroundColor:(UIColor * __nonnull)normalBackgroundColor selectedBackgroundColor:(UIColor * __nonnull)selectedBackgroundColor highlightedBackgroundColor:(UIColor * __nonnull)highlightedBackgroundColor first:(BOOL)first last:(BOOL)last; - (void)layoutSubviews; - (void)segmentTapped; - (void)overrideTouchDown; - (nonnull instancetype)initWithFrame:(CGRect)frame OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end /// A subclass of UILabel that automatically wraps text to width of its own frame. May be used with AutoLayout without providing a preferredMaxLayoutWidth. IMPORTANT: Do not assign a height constraint to APMultiLineLabels SWIFT_CLASS("_TtC5APKit16APMultilineLabel") @interface APMultilineLabel : UILabel - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)layoutSubviews; @end @class UITouch; @class UIEvent; /// A UIButton subclass that renders a springy animation when tapped. If the damping parameters are set to 1.0, this class may be used to provide subtle feedback to buttons with no elsasticity. /// /// \param minimumScale The minimum scale that the button may reach while pressed. Default 0.95 /// /// \param pressSpringDamping The damping parameter for the spring animation used when the button is pressed. Default 0.4 /// /// \param releaseSpringDamping The damping parameter for the spring animation used when the button is released. Default 0.35 /// /// \param pressSpringDuration The duration of the spring animation used when the button is pressed. Default 0.4 /// /// \param releaseSpringDuration The duration of the spring animation used when the button is reloeased. Default 0.5 SWIFT_CLASS("_TtC5APKit14APSpringButton") @interface APSpringButton : UIButton @property (nonatomic) CGFloat minimumScale; @property (nonatomic) CGFloat pressSpringDamping; @property (nonatomic) CGFloat releaseSpringDamping; @property (nonatomic) double pressSpringDuration; @property (nonatomic) double releaseSpringDuration; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)touchesBegan:(NSSet<UITouch *> * __nonnull)touches withEvent:(UIEvent * __nullable)event; - (void)touchesEnded:(NSSet<UITouch *> * __nonnull)touches withEvent:(UIEvent * __nullable)event; - (void)touchesMoved:(NSSet<UITouch *> * __nonnull)touches withEvent:(UIEvent * __nullable)event; - (void)touchesCancelled:(NSSet<UITouch *> * __nullable)touches withEvent:(UIEvent * __nullable)event; @end @protocol APStackViewReorderDelegate; @class UIGestureRecognizer; /// This class is a drop-in replacement for UIStackView (introduced with iOS 9), providing support for earlier operating systems. When the client's device is running iOS 9+, Apple's native UIStackView implementation will be used. Otherwise, an instance of TZStackView (courtesy of Tom van Zummeren) will be used. All class members and methods are identical to the native UIStackView. SWIFT_CLASS("_TtC5APKit11APStackView") @interface APStackView : UIView <UIGestureRecognizerDelegate> @property (nonatomic) BOOL isNative; @property (nonatomic) UILayoutConstraintAxis axis; @property (nonatomic) CGFloat spacing; @property (nonatomic) BOOL layoutMarginsRelativeArrangement; @property (nonatomic, readonly, copy) NSArray<UIView *> * __nonnull arrangedSubviews; - (nonnull instancetype)initWithArrangedSubviews:(NSArray<UIView *> * __nonnull)arrangedSubviews OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (void)addArrangedSubview:(UIView * __nonnull)view; - (void)addArrangedSubviews:(NSArray<UIView *> * __nonnull)views; - (void)insertArrangedSubview:(UIView * __nonnull)view atIndex:(NSInteger)stackIndex; - (void)removeArrangedSubview:(UIView * __nonnull)view; - (void)removeArrangedSubviewAtIndex:(NSInteger)index; - (void)willRemoveSubview:(UIView * __nonnull)subview; - (void)updateConstraints; - (void)observeValueForKeyPath:(NSString * __nullable)keyPath ofObject:(id __nullable)object change:(NSDictionary<NSString *, id> * __nullable)change context:(void * __null_unspecified)context; /// Setting reorderdingEnabled to true enables a drag to reorder behavior like UITableView @property (nonatomic) BOOL reorderingEnabled; @property (nonatomic, strong) id <APStackViewReorderDelegate> __nullable reorderDelegate; /// The gap created once the long press drag is triggered @property (nonatomic) BOOL clipsToBoundsWhileReordering; @property (nonatomic) CGFloat cornerRadii; @property (nonatomic) CGFloat temporaryViewScale; @property (nonatomic) CGFloat otherViewsScale; @property (nonatomic) CGFloat temporaryViewAlpha; @property (nonatomic) CGFloat dragHintSpacing; @property (nonatomic) double longPressMinimumPressDuration; - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer * __nonnull)gestureRecognizer; @end SWIFT_PROTOCOL("_TtP5APKit26APStackViewReorderDelegate_") @protocol APStackViewReorderDelegate @optional /// didBeginReordering - called when reordering begins - (void)didBeginReordering; /// Whenever a user drags a subview for a reordering, the delegate is told whether the direction was up or down, as well as what the max and min Y values are of the subview - (void)didDragToReorderInUpDirection:(BOOL)up maxY:(CGFloat)maxY minY:(CGFloat)minY; /// didReorder - called whenever a subview was reordered (returns the new index) didEndReordering = called when reordering ends - (void)didEndReordering; @end SWIFT_CLASS("_TtC5APKit24APTextFieldWithLeftInset") @interface APTextFieldWithLeftInset : UITextField - (nonnull instancetype)initWithInset:(NSInteger)inset OBJC_DESIGNATED_INITIALIZER; - (nonnull instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; - (CGRect)textRectForBounds:(CGRect)bounds; - (CGRect)editingRectForBounds:(CGRect)bounds; @end @interface NSData (SWIFT_EXTENSION(APKit)) /// Returns the hexadecimal string representation of the receiver's bytes - (NSString * __nonnull)toHex; @end SWIFT_CLASS("_TtC5APKit12TZSpacerView") @interface TZSpacerView : UIView - (nonnull instancetype)initWithFrame:(CGRect)frame OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end enum TZStackViewDistribution : NSInteger; enum TZStackViewAlignment : NSInteger; SWIFT_CLASS("_TtC5APKit11TZStackView") @interface TZStackView : UIView @property (nonatomic) enum TZStackViewDistribution distribution; @property (nonatomic) UILayoutConstraintAxis axis; @property (nonatomic) enum TZStackViewAlignment alignment; @property (nonatomic) CGFloat spacing; @property (nonatomic) BOOL layoutMarginsRelativeArrangement; @property (nonatomic, readonly, copy) NSArray<UIView *> * __nonnull arrangedSubviews; - (nonnull instancetype)initWithArrangedSubviews:(NSArray<UIView *> * __nonnull)arrangedSubviews OBJC_DESIGNATED_INITIALIZER; - (void)observeValueForKeyPath:(NSString * __nullable)keyPath ofObject:(id __nullable)object change:(NSDictionary<NSString *, id> * __nullable)change context:(void * __null_unspecified)context; - (void)addArrangedSubview:(UIView * __nonnull)view; - (void)removeArrangedSubview:(UIView * __nonnull)view; - (void)insertArrangedSubview:(UIView * __nonnull)view atIndex:(NSInteger)stackIndex; - (void)willRemoveSubview:(UIView * __nonnull)subview; - (void)updateConstraints; - (nonnull instancetype)initWithCoder:(NSCoder * __nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end typedef SWIFT_ENUM(NSInteger, TZStackViewAlignment) { TZStackViewAlignmentFill = 0, TZStackViewAlignmentCenter = 1, TZStackViewAlignmentLeading = 2, TZStackViewAlignmentTop = 3, TZStackViewAlignmentTrailing = 4, TZStackViewAlignmentBottom = 5, TZStackViewAlignmentFirstBaseline = 6, }; typedef SWIFT_ENUM(NSInteger, TZStackViewDistribution) { TZStackViewDistributionFill = 0, TZStackViewDistributionFillEqually = 1, TZStackViewDistributionFillProportionally = 2, TZStackViewDistributionEqualSpacing = 3, TZStackViewDistributionEqualCentering = 4, }; @interface UIButton (SWIFT_EXTENSION(APKit)) /// Remember to give the button a height constraint - (void)setBackgroundColor:(UIColor * __nonnull)color forUIControlState:(UIControlState)state; @end @interface UIColor (SWIFT_EXTENSION(APKit)) + (UIColor * __nonnull)black; + (UIColor * __nonnull)blue; + (UIColor * __nonnull)clear; + (UIColor * __nonnull)darkGray; + (UIColor * __nonnull)darkText; + (UIColor * __nonnull)green; + (UIColor * __nonnull)lightGray; + (UIColor * __nonnull)magenta; + (UIColor * __nonnull)orange; + (UIColor * __nonnull)purple; + (UIColor * __nonnull)red; + (UIColor * __nonnull)white; + (UIColor * __nonnull)yellow; @end @interface UIDevice (SWIFT_EXTENSION(APKit)) @end @interface UILabel (SWIFT_EXTENSION(APKit)) - (CGSize)labelSizeWithWidthOfContainingView:(CGFloat)widthOfContainingView; @end @interface UIView (SWIFT_EXTENSION(APKit)) /// Adds multiple subviews to the receiver, in the order specified in the array - (void)addSubviews:(NSArray<UIView *> * __nonnull)subviews; - (void)fillSuperview; - (void)centerInSuperview; - (void)removeAllConstraints; - (void)spaceHorizontalWithInsetWithViews:(NSArray<UIView *> * __nonnull)views inset:(UIEdgeInsets)inset; @end @class UIDynamicAnimator; @interface UIView (SWIFT_EXTENSION(APKit)) /// Available to the receiver in order to maintain a reference to a UIDynamicAnimator @property (nonatomic, strong) UIDynamicAnimator * __nullable dynamicAnimator; /// A quick horizontal shake, similar to the OS X failed login animation - (void)shake; - (void)bounce; /// Adds perspective zoom to the receiver, similar to the iOS 7+ home screen. /// /// \param relativeDistance The maximum distance the view may translate in any direction. /// /// \param withShadow Flag indicating whether the receiver's shadow should also be animated. If TRUE and the receiver has not already been given a shadow, a default black shadow (radius 3, opacity 0.4) is assigned. - (void)addPerspectiveWithRelativeDistance:(CGFloat)relativeDistance withShadow:(BOOL)withShadow; /// Adds perspective zoom to the receiver, with a 3D rotation effect. /// /// \param rotationAmount CGFloat between 0 and 1. Maximum amount of rotation allowed. /// /// \param withShadow Flag indicating whether the receiver's shadow should also be animated. If TRUE and the receiver has not already been given a shadow, a default black shadow (radius 3, opacity 0.4) is assigned. - (void)addPerspectiveWithRotationAmount:(CGFloat)rotationAmount withShadow:(BOOL)withShadow; /// Calculates the transformation needed to transition the receiver from its current frame to the given bounds, and assigns it to the receiver.\Important /// /// This method does not work if applied to a view to which a non-identity transform has already been applied. /// It currently works for transitioning between the identity transform, a new calculated transform, and back. /// /// \param toRect The ending bounds for the transformation. - (void)transformToRect:(CGRect)toRect; - (void)transformToRect:(CGRect)toRect affectsSubviews:(BOOL)affectsSubviews; @end #pragma clang diagnostic pop
43.433649
383
0.806973
[ "object", "transform", "3d" ]
aa93db02a39a567d257e201564b725fb72b9896d
42,697
h
C
include/sqlite/sqlite_modern_cpp.h
GuramDuka/spacenet
d63a6bbe606aad3d9ae400d92371f8be36be359f
[ "MIT" ]
null
null
null
include/sqlite/sqlite_modern_cpp.h
GuramDuka/spacenet
d63a6bbe606aad3d9ae400d92371f8be36be359f
[ "MIT" ]
null
null
null
include/sqlite/sqlite_modern_cpp.h
GuramDuka/spacenet
d63a6bbe606aad3d9ae400d92371f8be36be359f
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cctype> #include <string> #include <functional> #include <stdexcept> #include <ctime> #include <tuple> #include <memory> #include <vector> #include <locale> #include <codecvt> #ifdef __has_include #if __cplusplus > 201402 && __has_include(<optional>) #define MODERN_SQLITE_STD_OPTIONAL_SUPPORT #endif #endif #ifdef __has_include #if __cplusplus > 201402 && __has_include(<variant>) #define MODERN_SQLITE_STD_VARIANT_SUPPORT #endif #endif #ifdef MODERN_SQLITE_STD_OPTIONAL_SUPPORT #include <optional> #endif #ifdef _MODERN_SQLITE_BOOST_OPTIONAL_SUPPORT #include <boost/optional.hpp> #endif #include "sqlite/sqlite3.h" #include "sqlite_modern_cpp/utility/function_traits.h" #include "sqlite_modern_cpp/utility/uncaught_exceptions.h" namespace sqlite { class sqlite_exception: public std::runtime_error { public: sqlite_exception(const char* msg, std::string sql, int code = -1): runtime_error(msg), code(code), sql(sql) {} sqlite_exception(int code, std::string sql): runtime_error(sqlite3_errstr(code)), code(code), sql(sql) {} int get_code() {return code;} std::string get_sql() {return sql;} private: int code; std::string sql; }; namespace exceptions { //One more or less trivial derived error class for each SQLITE error. //Note the following are not errors so have no classes: //SQLITE_OK, SQLITE_NOTICE, SQLITE_WARNING, SQLITE_ROW, SQLITE_DONE // //Note these names are exact matches to the names of the SQLITE error codes. class error: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class internal: public sqlite_exception{ using sqlite_exception::sqlite_exception; }; class perm: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class abort: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class busy: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class locked: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class nomem: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class readonly: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class interrupt: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class ioerr: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class corrupt: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class notfound: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class full: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class cantopen: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class protocol: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class empty: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class schema: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class toobig: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class constraint: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class mismatch: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class misuse: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class nolfs: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class auth: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class format: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class range: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class notadb: public sqlite_exception { using sqlite_exception::sqlite_exception; }; //Some additional errors are here for the C++ interface class more_rows: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class no_rows: public sqlite_exception { using sqlite_exception::sqlite_exception; }; class reexecution: public sqlite_exception { using sqlite_exception::sqlite_exception; }; // Prepared statements need to be reset before calling them again class more_statements: public sqlite_exception { using sqlite_exception::sqlite_exception; }; // Prepared statements can only contain one statement static void throw_sqlite_error(const int& error_code, const std::string &sql = "") { if(error_code == SQLITE_ERROR) throw exceptions::error(error_code, sql); else if(error_code == SQLITE_INTERNAL) throw exceptions::internal(error_code, sql); else if(error_code == SQLITE_PERM) throw exceptions::perm(error_code, sql); else if(error_code == SQLITE_ABORT) throw exceptions::abort(error_code, sql); else if(error_code == SQLITE_BUSY) throw exceptions::busy(error_code, sql); else if(error_code == SQLITE_LOCKED) throw exceptions::locked(error_code, sql); else if(error_code == SQLITE_NOMEM) throw exceptions::nomem(error_code, sql); else if(error_code == SQLITE_READONLY) throw exceptions::readonly(error_code, sql); else if(error_code == SQLITE_INTERRUPT) throw exceptions::interrupt(error_code, sql); else if(error_code == SQLITE_IOERR) throw exceptions::ioerr(error_code, sql); else if(error_code == SQLITE_CORRUPT) throw exceptions::corrupt(error_code, sql); else if(error_code == SQLITE_NOTFOUND) throw exceptions::notfound(error_code, sql); else if(error_code == SQLITE_FULL) throw exceptions::full(error_code, sql); else if(error_code == SQLITE_CANTOPEN) throw exceptions::cantopen(error_code, sql); else if(error_code == SQLITE_PROTOCOL) throw exceptions::protocol(error_code, sql); else if(error_code == SQLITE_EMPTY) throw exceptions::empty(error_code, sql); else if(error_code == SQLITE_SCHEMA) throw exceptions::schema(error_code, sql); else if(error_code == SQLITE_TOOBIG) throw exceptions::toobig(error_code, sql); else if(error_code == SQLITE_CONSTRAINT) throw exceptions::constraint(error_code, sql); else if(error_code == SQLITE_MISMATCH) throw exceptions::mismatch(error_code, sql); else if(error_code == SQLITE_MISUSE) throw exceptions::misuse(error_code, sql); else if(error_code == SQLITE_NOLFS) throw exceptions::nolfs(error_code, sql); else if(error_code == SQLITE_AUTH) throw exceptions::auth(error_code, sql); else if(error_code == SQLITE_FORMAT) throw exceptions::format(error_code, sql); else if(error_code == SQLITE_RANGE) throw exceptions::range(error_code, sql); else if(error_code == SQLITE_NOTADB) throw exceptions::notadb(error_code, sql); else throw sqlite_exception(error_code, sql); } } } #ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT #include "sqlite_modern_cpp/utility/variant.h" #endif namespace sqlite { class database; class database_binder; template<std::size_t> class binder; typedef std::shared_ptr<sqlite3> connection_type; template<typename Tuple, int Element = 0, bool Last = (std::tuple_size<Tuple>::value == Element)> struct tuple_iterate { static void iterate(Tuple& t, database_binder& db) { get_col_from_db(db, Element, std::get<Element>(t)); tuple_iterate<Tuple, Element + 1>::iterate(t, db); } }; template<typename Tuple, int Element> struct tuple_iterate<Tuple, Element, true> { static void iterate(Tuple&, database_binder&) {} }; class database_binder { public: // database_binder is not copyable database_binder() = delete; database_binder(const database_binder& other) = delete; database_binder& operator=(const database_binder&) = delete; database_binder(database_binder&& other) : _db(std::move(other._db)), _stmt(std::move(other._stmt)), _inx(other._inx), execution_started(other.execution_started) { } void reset() { sqlite3_reset(_stmt.get()); sqlite3_clear_bindings(_stmt.get()); _inx = 1; used(false); } void execute() { int hresult; used(true); /* prevent from executing again when goes out of scope */ while((hresult = sqlite3_step(_stmt.get())) == SQLITE_ROW) {} if(hresult != SQLITE_DONE) { exceptions::throw_sqlite_error(hresult, sql()); } } std::string sql() { #if SQLITE_VERSION_NUMBER >= 3014000 auto sqlite_deleter = [](void *ptr) {sqlite3_free(ptr);}; std::unique_ptr<char, decltype(sqlite_deleter)> str(sqlite3_expanded_sql(_stmt.get()), sqlite_deleter); return str ? str.get() : original_sql(); #else return original_sql(); #endif } std::string original_sql() { return sqlite3_sql(_stmt.get()); } void used(bool state) { if(execution_started == true && state == true) { throw exceptions::reexecution("Already used statement executed again! Please reset() first!",sql()); } execution_started = state; } bool used() const { return execution_started; } private: std::shared_ptr<sqlite3> _db; std::unique_ptr<sqlite3_stmt, decltype(&sqlite3_finalize)> _stmt; utility::UncaughtExceptionDetector _has_uncaught_exception; int _inx; bool execution_started = false; void _extract(std::function<void(void)> call_back) { int hresult; used(true); while((hresult = sqlite3_step(_stmt.get())) == SQLITE_ROW) { call_back(); } if(hresult != SQLITE_DONE) { exceptions::throw_sqlite_error(hresult, sql()); } } void _extract_single_value(std::function<void(void)> call_back) { int hresult; used(true); if((hresult = sqlite3_step(_stmt.get())) == SQLITE_ROW) { call_back(); } else if(hresult == SQLITE_DONE) { throw exceptions::no_rows("no rows to extract: exactly 1 row expected", sql(), SQLITE_DONE); } if((hresult = sqlite3_step(_stmt.get())) == SQLITE_ROW) { throw exceptions::more_rows("not all rows extracted", sql(), SQLITE_ROW); } if(hresult != SQLITE_DONE) { exceptions::throw_sqlite_error(hresult, sql()); } } #ifdef _MSC_VER sqlite3_stmt* _prepare(const std::u16string& sql) { return _prepare(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(reinterpret_cast<const wchar_t*>(sql.c_str()))); } #else sqlite3_stmt* _prepare(const std::u16string& sql) { return _prepare(std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>().to_bytes(sql)); } #endif sqlite3_stmt* _prepare(const std::string& sql) { int hresult; sqlite3_stmt* tmp = nullptr; const char *remaining; hresult = sqlite3_prepare_v2(_db.get(), sql.data(), -1, &tmp, &remaining); if(hresult != SQLITE_OK) exceptions::throw_sqlite_error(hresult, sql); if(!std::all_of(remaining, sql.data() + sql.size(), [](char ch) {return std::isblank(ch);})) throw exceptions::more_statements("Multiple semicolon separated statements are unsupported", sql); return tmp; } template <typename Type> struct is_sqlite_value : public std::integral_constant< bool, std::is_floating_point<Type>::value || std::is_integral<Type>::value || std::is_same<std::string, Type>::value || std::is_same<std::u16string, Type>::value || std::is_same<sqlite_int64, Type>::value > { }; template <typename Type, typename Allocator> struct is_sqlite_value< std::vector<Type, Allocator> > : public std::integral_constant< bool, std::is_floating_point<Type>::value || std::is_integral<Type>::value || std::is_same<sqlite_int64, Type>::value > { }; #ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT template <typename ...Args> struct is_sqlite_value< std::variant<Args...> > : public std::integral_constant< bool, true > { }; #endif template<typename T> friend database_binder& operator <<(database_binder& db, const T& val); template<typename T> friend void get_col_from_db(database_binder& db, int inx, T& val); /* for vector<T, A> support */ template<typename T, typename A> friend database_binder& operator <<(database_binder& db, const std::vector<T, A>& val); template<typename T, typename A> friend void get_col_from_db(database_binder& db, int inx, std::vector<T, A>& val); /* for nullptr & unique_ptr support */ friend database_binder& operator <<(database_binder& db, std::nullptr_t); template<typename T> friend database_binder& operator <<(database_binder& db, const std::unique_ptr<T>& val); template<typename T> friend void get_col_from_db(database_binder& db, int inx, std::unique_ptr<T>& val); #ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT template<typename ...Args> friend database_binder& operator <<(database_binder& db, const std::variant<Args...>& val); template<typename ...Args> friend void get_col_from_db(database_binder& db, int inx, std::variant<Args...>& val); #endif template<typename T> friend T operator++(database_binder& db, int); // Overload instead of specializing function templates (http://www.gotw.ca/publications/mill17.htm) template <typename T> friend database_binder& operator<<(database_binder& db, const std::pair<const char *, T> & val); friend database_binder& operator<<(database_binder& db, const bool& val); friend void get_col_from_db(database_binder& db, int inx, bool& val); friend database_binder& operator<<(database_binder& db, const int& val); friend void get_col_from_db(database_binder& db, int inx, int& val); friend database_binder& operator<<(database_binder& db, const unsigned& val); friend void get_col_from_db(database_binder& db, int inx, unsigned& val); friend database_binder& operator <<(database_binder& db, const sqlite_int64& val); friend void get_col_from_db(database_binder& db, int inx, sqlite3_int64& i); friend database_binder& operator <<(database_binder& db, const uint64_t& val); friend void get_col_from_db(database_binder& db, int inx, uint64_t& i); friend database_binder& operator <<(database_binder& db, const float& val); friend void get_col_from_db(database_binder& db, int inx, float& f); friend database_binder& operator <<(database_binder& db, const double& val); friend void get_col_from_db(database_binder& db, int inx, double& d); friend void get_col_from_db(database_binder& db, int inx, std::string & s); friend database_binder& operator <<(database_binder& db, const std::string& txt); friend void get_col_from_db(database_binder& db, int inx, std::u16string & w); friend database_binder& operator <<(database_binder& db, const std::u16string& txt); #ifdef MODERN_SQLITE_STD_OPTIONAL_SUPPORT template <typename OptionalT> friend database_binder& operator <<(database_binder& db, const std::optional<OptionalT>& val); template <typename OptionalT> friend void get_col_from_db(database_binder& db, int inx, std::optional<OptionalT>& o); #endif #ifdef _MODERN_SQLITE_BOOST_OPTIONAL_SUPPORT template <typename BoostOptionalT> friend database_binder& operator <<(database_binder& db, const boost::optional<BoostOptionalT>& val); template <typename BoostOptionalT> friend void get_col_from_db(database_binder& db, int inx, boost::optional<BoostOptionalT>& o); #endif public: database_binder(std::shared_ptr<sqlite3> db, std::u16string const & sql): _db(db), _stmt(_prepare(sql), sqlite3_finalize), _inx(1) { } database_binder(std::shared_ptr<sqlite3> db, std::string const & sql): _db(db), _stmt(_prepare(sql), sqlite3_finalize), _inx(1) { } ~database_binder() noexcept(false) { /* Will be executed if no >>op is found, but not if an exception is in mid flight */ if(!used() && !_has_uncaught_exception && _stmt) { execute(); } } template <typename Result> typename std::enable_if<is_sqlite_value<Result>::value, void>::type operator>>( Result& value) { this->_extract_single_value([&value, this] { get_col_from_db(*this, 0, value); }); } template<typename... Types> void operator>>(std::tuple<Types...>&& values) { this->_extract_single_value([&values, this] { tuple_iterate<std::tuple<Types...>>::iterate(values, *this); }); } template <typename Function> typename std::enable_if<!is_sqlite_value<Function>::value, void>::type operator>>( Function&& func) { typedef utility::function_traits<Function> traits; this->_extract([&func, this]() { binder<traits::arity>::run(*this, func); }); } }; namespace sql_function_binder { template< typename ContextType, std::size_t Count, typename Functions > inline void step( sqlite3_context* db, int count, sqlite3_value** vals ); template< std::size_t Count, typename Functions, typename... Values > inline typename std::enable_if<(sizeof...(Values) && sizeof...(Values) < Count), void>::type step( sqlite3_context* db, int count, sqlite3_value** vals, Values&&... values ); template< std::size_t Count, typename Functions, typename... Values > inline typename std::enable_if<(sizeof...(Values) == Count), void>::type step( sqlite3_context* db, int, sqlite3_value**, Values&&... values ); template< typename ContextType, typename Functions > inline void final(sqlite3_context* db); template< std::size_t Count, typename Function, typename... Values > inline typename std::enable_if<(sizeof...(Values) < Count), void>::type scalar( sqlite3_context* db, int count, sqlite3_value** vals, Values&&... values ); template< std::size_t Count, typename Function, typename... Values > inline typename std::enable_if<(sizeof...(Values) == Count), void>::type scalar( sqlite3_context* db, int, sqlite3_value**, Values&&... values ); } enum class OpenFlags { READONLY = SQLITE_OPEN_READONLY, READWRITE = SQLITE_OPEN_READWRITE, CREATE = SQLITE_OPEN_CREATE, NOMUTEX = SQLITE_OPEN_NOMUTEX, FULLMUTEX = SQLITE_OPEN_FULLMUTEX, SHAREDCACHE = SQLITE_OPEN_SHAREDCACHE, PRIVATECACH = SQLITE_OPEN_PRIVATECACHE, URI = SQLITE_OPEN_URI }; inline OpenFlags operator|(const OpenFlags& a, const OpenFlags& b) { return static_cast<OpenFlags>(static_cast<int>(a) | static_cast<int>(b)); }; enum class Encoding { ANY = SQLITE_ANY, UTF8 = SQLITE_UTF8, UTF16 = SQLITE_UTF16 }; struct sqlite_config { OpenFlags flags = OpenFlags::READWRITE | OpenFlags::CREATE; const char *zVfs = nullptr; Encoding encoding = Encoding::ANY; }; class database { protected: std::shared_ptr<sqlite3> _db; public: database(const std::string &db_name, const sqlite_config &config = {}): _db(nullptr) { sqlite3* tmp = nullptr; auto ret = sqlite3_open_v2(db_name.data(), &tmp, static_cast<int>(config.flags), config.zVfs); _db = std::shared_ptr<sqlite3>(tmp, [=](sqlite3* ptr) { sqlite3_close_v2(ptr); }); // this will close the connection eventually when no longer needed. if(ret != SQLITE_OK) exceptions::throw_sqlite_error(ret); if(config.encoding == Encoding::UTF16) *this << R"(PRAGMA encoding = "UTF-16";)"; } database(const std::u16string &db_name, const sqlite_config &config = {}): _db(nullptr) { #ifdef _MSC_VER auto db_name_utf8 = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(reinterpret_cast<const wchar_t*>(db_name.c_str())); #else auto db_name_utf8 = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>().to_bytes(db_name); #endif sqlite3* tmp = nullptr; auto ret = sqlite3_open_v2(db_name_utf8.data(), &tmp, static_cast<int>(config.flags), config.zVfs); _db = std::shared_ptr<sqlite3>(tmp, [=](sqlite3* ptr) { sqlite3_close_v2(ptr); }); // this will close the connection eventually when no longer needed. if(ret != SQLITE_OK) exceptions::throw_sqlite_error(ret); if(config.encoding != Encoding::UTF8) *this << R"(PRAGMA encoding = "UTF-16";)"; } database(std::shared_ptr<sqlite3> db): _db(db) {} database_binder operator<<(const std::string& sql) { return database_binder(_db, sql); } database_binder operator<<(const char* sql) { return *this << std::string(sql); } database_binder operator<<(const std::u16string& sql) { return database_binder(_db, sql); } database_binder operator<<(const char16_t* sql) { return *this << std::u16string(sql); } connection_type connection() const { return _db; } sqlite3_int64 last_insert_rowid() const { return sqlite3_last_insert_rowid(_db.get()); } template <typename Function> void define(const std::string &name, Function&& func) { typedef utility::function_traits<Function> traits; auto funcPtr = new auto(std::forward<Function>(func)); if(int result = sqlite3_create_function_v2( _db.get(), name.c_str(), traits::arity, SQLITE_UTF8, funcPtr, sql_function_binder::scalar<traits::arity, typename std::remove_reference<Function>::type>, nullptr, nullptr, [](void* ptr){ delete static_cast<decltype(funcPtr)>(ptr); })) exceptions::throw_sqlite_error(result); } template <typename StepFunction, typename FinalFunction> void define(const std::string &name, StepFunction&& step, FinalFunction&& final) { typedef utility::function_traits<StepFunction> traits; using ContextType = typename std::remove_reference<typename traits::template argument<0>>::type; auto funcPtr = new auto(std::make_pair(std::forward<StepFunction>(step), std::forward<FinalFunction>(final))); if(int result = sqlite3_create_function_v2( _db.get(), name.c_str(), traits::arity - 1, SQLITE_UTF8, funcPtr, nullptr, sql_function_binder::step<ContextType, traits::arity, typename std::remove_reference<decltype(*funcPtr)>::type>, sql_function_binder::final<ContextType, typename std::remove_reference<decltype(*funcPtr)>::type>, [](void* ptr){ delete static_cast<decltype(funcPtr)>(ptr); })) exceptions::throw_sqlite_error(result); } }; template<std::size_t Count> class binder { private: template < typename Function, std::size_t Index > using nth_argument_type = typename utility::function_traits< Function >::template argument<Index>; public: // `Boundary` needs to be defaulted to `Count` so that the `run` function // template is not implicitly instantiated on class template instantiation. // Look up section 14.7.1 _Implicit instantiation_ of the ISO C++14 Standard // and the [dicussion](https://github.com/aminroosta/sqlite_modern_cpp/issues/8) // on Github. template< typename Function, typename... Values, std::size_t Boundary = Count > static typename std::enable_if<(sizeof...(Values) < Boundary), void>::type run( database_binder& db, Function&& function, Values&&... values ) { typename std::remove_cv<typename std::remove_reference<nth_argument_type<Function, sizeof...(Values)>>::type>::type value{}; get_col_from_db(db, sizeof...(Values), value); run<Function>(db, function, std::forward<Values>(values)..., std::move(value)); } template< typename Function, typename... Values, std::size_t Boundary = Count > static typename std::enable_if<(sizeof...(Values) == Boundary), void>::type run( database_binder&, Function&& function, Values&&... values ) { function(std::move(values)...); } }; template <class P, class T, typename = std::enable_if_t<std::is_base_of<std::string, P>::value> > database_binder& operator<<(database_binder& db, const std::pair<P, T> & val) { return db << std::make_pair(val.first.c_str(), val.second); } template <typename T> database_binder& operator<<(database_binder& db, const std::pair<const char *, T> & val) { int i = sqlite3_bind_parameter_index(db._stmt.get(), val.first); if( !i ) exceptions::throw_sqlite_error(SQLITE_NOTFOUND); auto safe = db._inx; db._inx = i; db << val.second; db._inx = safe; return db; } // bool inline database_binder& operator<<(database_binder& db, const bool& val) { int hresult; if((hresult = sqlite3_bind_int(db._stmt.get(), db._inx, val ? 1 : 0)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const bool& val) { sqlite3_result_int(db, val ? 1 : 0); } inline void get_col_from_db(database_binder& db, int inx, bool& val) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { val = false; } else { val = sqlite3_column_int(db._stmt.get(), inx) != 0; } } inline void get_val_from_db(sqlite3_value *value, bool& val) { if(sqlite3_value_type(value) == SQLITE_NULL) { val = false; } else { val = sqlite3_value_int(value) != 0; } } // int inline database_binder& operator<<(database_binder& db, const int& val) { int hresult; if((hresult = sqlite3_bind_int(db._stmt.get(), db._inx, val)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const int& val) { sqlite3_result_int(db, val); } inline void get_col_from_db(database_binder& db, int inx, int& val) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { val = 0; } else { val = sqlite3_column_int(db._stmt.get(), inx); } } inline void get_val_from_db(sqlite3_value *value, int& val) { if(sqlite3_value_type(value) == SQLITE_NULL) { val = 0; } else { val = sqlite3_value_int(value); } } // unsigned inline database_binder& operator<<(database_binder& db, const unsigned& val) { int hresult; if((hresult = sqlite3_bind_int(db._stmt.get(), db._inx, val)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const unsigned& val) { sqlite3_result_int(db, val); } inline void get_col_from_db(database_binder& db, int inx, unsigned& val) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { val = 0; } else { val = sqlite3_column_int(db._stmt.get(), inx); } } inline void get_val_from_db(sqlite3_value *value, unsigned& val) { if(sqlite3_value_type(value) == SQLITE_NULL) { val = 0; } else { val = sqlite3_value_int(value); } } // sqlite_int64 inline database_binder& operator <<(database_binder& db, const sqlite_int64& val) { int hresult; if((hresult = sqlite3_bind_int64(db._stmt.get(), db._inx, val)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const sqlite_int64& val) { sqlite3_result_int64(db, val); } inline void get_col_from_db(database_binder& db, int inx, sqlite3_int64& i) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { i = 0; } else { i = sqlite3_column_int64(db._stmt.get(), inx); } } inline void get_val_from_db(sqlite3_value *value, sqlite3_int64& i) { if(sqlite3_value_type(value) == SQLITE_NULL) { i = 0; } else { i = sqlite3_value_int64(value); } } // uint64 inline database_binder& operator <<(database_binder& db, const uint64_t& val) { int hresult; if((hresult = sqlite3_bind_int64(db._stmt.get(), db._inx, val)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const uint64_t& val) { sqlite3_result_int64(db, val); } inline void get_col_from_db(database_binder& db, int inx, uint64_t& i) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { i = 0; } else { i = sqlite3_column_int64(db._stmt.get(), inx); } } inline void get_val_from_db(sqlite3_value *value, uint64_t& i) { if(sqlite3_value_type(value) == SQLITE_NULL) { i = 0; } else { i = sqlite3_value_int64(value); } } // float inline database_binder& operator <<(database_binder& db, const float& val) { int hresult; if((hresult = sqlite3_bind_double(db._stmt.get(), db._inx, double(val))) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const float& val) { sqlite3_result_double(db, val); } inline void get_col_from_db(database_binder& db, int inx, float& f) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { f = 0; } else { f = float(sqlite3_column_double(db._stmt.get(), inx)); } } inline void get_val_from_db(sqlite3_value *value, float& f) { if(sqlite3_value_type(value) == SQLITE_NULL) { f = 0; } else { f = float(sqlite3_value_double(value)); } } // double inline database_binder& operator <<(database_binder& db, const double& val) { int hresult; if((hresult = sqlite3_bind_double(db._stmt.get(), db._inx, val)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const double& val) { sqlite3_result_double(db, val); } inline void get_col_from_db(database_binder& db, int inx, double& d) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { d = 0; } else { d = sqlite3_column_double(db._stmt.get(), inx); } } inline void get_val_from_db(sqlite3_value *value, double& d) { if(sqlite3_value_type(value) == SQLITE_NULL) { d = 0; } else { d = sqlite3_value_double(value); } } // vector<T, A> template<typename T, typename A> inline database_binder& operator<<(database_binder& db, const std::vector<T, A>& vec) { void const* buf = reinterpret_cast<void const *>(vec.data()); int bytes = vec.size() * sizeof(T); int hresult; if((hresult = sqlite3_bind_blob64(db._stmt.get(), db._inx, buf, bytes, SQLITE_TRANSIENT)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } template<typename T, typename A> inline void store_result_in_db(sqlite3_context* db, const std::vector<T, A>& vec) { void const* buf = reinterpret_cast<void const *>(vec.data()); int bytes = vec.size() * sizeof(T); sqlite3_result_blob(db, buf, bytes, SQLITE_TRANSIENT); } template<typename T, typename A> inline void get_col_from_db(database_binder& db, int inx, std::vector<T, A>& vec) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { vec.clear(); } else { int bytes = sqlite3_column_bytes(db._stmt.get(), inx); T const* buf = reinterpret_cast<T const *>(sqlite3_column_blob(db._stmt.get(), inx)); vec = std::vector<T, A>(buf, buf + bytes/sizeof(T)); } } template<typename T, typename A> inline void get_val_from_db(sqlite3_value *value, std::vector<T, A>& vec) { if(sqlite3_value_type(value) == SQLITE_NULL) { vec.clear(); } else { int bytes = sqlite3_value_bytes(value); T const* buf = reinterpret_cast<T const *>(sqlite3_value_blob(value)); vec = std::vector<T, A>(buf, buf + bytes/sizeof(T)); } } /* for nullptr support */ inline database_binder& operator <<(database_binder& db, std::nullptr_t) { int hresult; if((hresult = sqlite3_bind_null(db._stmt.get(), db._inx)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, std::nullptr_t) { sqlite3_result_null(db); } /* for nullptr support */ template<typename T> inline database_binder& operator <<(database_binder& db, const std::unique_ptr<T>& val) { if(val) db << *val; else db << nullptr; return db; } /* for unique_ptr<T> support */ template<typename T> inline void get_col_from_db(database_binder& db, int inx, std::unique_ptr<T>& _ptr_) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { _ptr_ = nullptr; } else { auto underling_ptr = new T(); get_col_from_db(db, inx, *underling_ptr); _ptr_.reset(underling_ptr); } } template<typename T> inline void get_val_from_db(sqlite3_value *value, std::unique_ptr<T>& _ptr_) { if(sqlite3_value_type(value) == SQLITE_NULL) { _ptr_ = nullptr; } else { auto underling_ptr = new T(); get_val_from_db(value, *underling_ptr); _ptr_.reset(underling_ptr); } } // std::string inline void get_col_from_db(database_binder& db, int inx, std::string & s) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { s = std::string(); } else { sqlite3_column_bytes(db._stmt.get(), inx); s = std::string(reinterpret_cast<char const *>(sqlite3_column_text(db._stmt.get(), inx))); } } inline void get_val_from_db(sqlite3_value *value, std::string & s) { if(sqlite3_value_type(value) == SQLITE_NULL) { s = std::string(); } else { sqlite3_value_bytes(value); s = std::string(reinterpret_cast<char const *>(sqlite3_value_text(value))); } } // Convert char* to string to trigger op<<(..., const std::string ) template<std::size_t N> inline database_binder& operator <<(database_binder& db, const char(&STR)[N]) { return db << std::string(STR); } template<std::size_t N> inline database_binder& operator <<(database_binder& db, const char16_t(&STR)[N]) { return db << std::u16string(STR); } inline database_binder& operator <<(database_binder& db, const std::string& txt) { int hresult; if((hresult = sqlite3_bind_text(db._stmt.get(), db._inx, txt.data(), -1, SQLITE_TRANSIENT)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const std::string& val) { sqlite3_result_text(db, val.data(), -1, SQLITE_TRANSIENT); } // std::u16string inline void get_col_from_db(database_binder& db, int inx, std::u16string & w) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { w = std::u16string(); } else { sqlite3_column_bytes16(db._stmt.get(), inx); w = std::u16string(reinterpret_cast<char16_t const *>(sqlite3_column_text16(db._stmt.get(), inx))); } } inline void get_val_from_db(sqlite3_value *value, std::u16string & w) { if(sqlite3_value_type(value) == SQLITE_NULL) { w = std::u16string(); } else { sqlite3_value_bytes16(value); w = std::u16string(reinterpret_cast<char16_t const *>(sqlite3_value_text16(value))); } } inline database_binder& operator <<(database_binder& db, const std::u16string& txt) { int hresult; if((hresult = sqlite3_bind_text16(db._stmt.get(), db._inx, txt.data(), -1, SQLITE_TRANSIENT)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } inline void store_result_in_db(sqlite3_context* db, const std::u16string& val) { sqlite3_result_text16(db, val.data(), -1, SQLITE_TRANSIENT); } // std::optional support for NULL values #ifdef MODERN_SQLITE_STD_OPTIONAL_SUPPORT template <typename OptionalT> inline database_binder& operator <<(database_binder& db, const std::optional<OptionalT>& val) { if(val) { return operator << (std::move(db), std::move(*val)); } int hresult; if((hresult = sqlite3_bind_null(db._stmt.get(), db._inx)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } template <typename OptionalT> inline void store_result_in_db(sqlite3_context* db, const std::optional<OptionalT>& val) { if(val) { store_result_in_db(db, *val); } sqlite3_result_null(db); } template <typename OptionalT> inline void get_col_from_db(database_binder& db, int inx, std::optional<OptionalT>& o) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { o.reset(); } else { OptionalT v; get_col_from_db(db, inx, v); o = std::move(v); } } template <typename OptionalT> inline void get_val_from_db(sqlite3_value *value, std::optional<OptionalT>& o) { if(sqlite3_value_type(value) == SQLITE_NULL) { o.reset(); } else { OptionalT v; get_val_from_db(value, v); o = std::move(v); } } #endif // boost::optional support for NULL values #ifdef _MODERN_SQLITE_BOOST_OPTIONAL_SUPPORT template <typename BoostOptionalT> inline database_binder& operator <<(database_binder& db, const boost::optional<BoostOptionalT>& val) { if(val) { return operator << (std::move(db), std::move(*val)); } int hresult; if((hresult = sqlite3_bind_null(db._stmt.get(), db._inx)) != SQLITE_OK) { exceptions::throw_sqlite_error(hresult, db.sql()); } ++db._inx; return db; } template <typename BoostOptionalT> inline void store_result_in_db(sqlite3_context* db, const boost::optional<BoostOptionalT>& val) { if(val) { store_result_in_db(db, *val); } sqlite3_result_null(db); } template <typename BoostOptionalT> inline void get_col_from_db(database_binder& db, int inx, boost::optional<BoostOptionalT>& o) { if(sqlite3_column_type(db._stmt.get(), inx) == SQLITE_NULL) { o.reset(); } else { BoostOptionalT v; get_col_from_db(db, inx, v); o = std::move(v); } } template <typename BoostOptionalT> inline void get_val_from_db(sqlite3_value *value, boost::optional<BoostOptionalT>& o) { if(sqlite3_value_type(value) == SQLITE_NULL) { o.reset(); } else { BoostOptionalT v; get_val_from_db(value, v); o = std::move(v); } } #endif #ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT template <typename ...Args> inline database_binder& operator <<(database_binder& db, const std::variant<Args...>& val) { std::visit([&](auto &&opt) {db << std::forward<decltype(opt)>(opt);}, val); return db; } template <typename ...Args> inline void store_result_in_db(sqlite3_context* db, const std::variant<Args...>& val) { std::visit([&](auto &&opt) {store_result_in_db(db, std::forward<decltype(opt)>(opt));}, val); } template <typename ...Args> inline void get_col_from_db(database_binder& db, int inx, std::variant<Args...>& val) { utility::variant_select<Args...>(sqlite3_column_type(db._stmt.get(), inx))([&](auto v) { get_col_from_db(db, inx, v); val = std::move(v); }); } template <typename ...Args> inline void get_val_from_db(sqlite3_value *value, std::variant<Args...>& val) { utility::variant_select<Args...>(sqlite3_value_type(value))([&](auto v) { get_val_from_db(value, v); val = std::move(v); }); } #endif // Some ppl are lazy so we have a operator for proper prep. statemant handling. void inline operator++(database_binder& db, int) { db.execute(); db.reset(); } // Convert the rValue binder to a reference and call first op<<, its needed for the call that creates the binder (be carefull of recursion here!) template<typename T> database_binder& operator << (database_binder&& db, const T& val) { return db << val; } namespace sql_function_binder { template<class T> struct AggregateCtxt { T obj; bool constructed = true; }; template< typename ContextType, std::size_t Count, typename Functions > inline void step( sqlite3_context* db, int count, sqlite3_value** vals ) { auto ctxt = static_cast<AggregateCtxt<ContextType>*>(sqlite3_aggregate_context(db, sizeof(AggregateCtxt<ContextType>))); if(!ctxt) return; try { if(!ctxt->constructed) new(ctxt) AggregateCtxt<ContextType>(); step<Count, Functions>(db, count, vals, ctxt->obj); return; } catch(sqlite_exception &e) { sqlite3_result_error_code(db, e.get_code()); sqlite3_result_error(db, e.what(), -1); } catch(std::exception &e) { sqlite3_result_error(db, e.what(), -1); } catch(...) { sqlite3_result_error(db, "Unknown error", -1); } if(ctxt && ctxt->constructed) ctxt->~AggregateCtxt(); } template< std::size_t Count, typename Functions, typename... Values > inline typename std::enable_if<(sizeof...(Values) && sizeof...(Values) < Count), void>::type step( sqlite3_context* db, int count, sqlite3_value** vals, Values&&... values ) { typename std::remove_cv< typename std::remove_reference< typename utility::function_traits< typename Functions::first_type >::template argument<sizeof...(Values)> >::type >::type value{}; get_val_from_db(vals[sizeof...(Values) - 1], value); step<Count, Functions>(db, count, vals, std::forward<Values>(values)..., std::move(value)); } template< std::size_t Count, typename Functions, typename... Values > inline typename std::enable_if<(sizeof...(Values) == Count), void>::type step( sqlite3_context* db, int, sqlite3_value**, Values&&... values ) { static_cast<Functions*>(sqlite3_user_data(db))->first(std::forward<Values>(values)...); }; template< typename ContextType, typename Functions > inline void final(sqlite3_context* db) { auto ctxt = static_cast<AggregateCtxt<ContextType>*>(sqlite3_aggregate_context(db, sizeof(AggregateCtxt<ContextType>))); try { if(!ctxt) return; if(!ctxt->constructed) new(ctxt) AggregateCtxt<ContextType>(); store_result_in_db(db, static_cast<Functions*>(sqlite3_user_data(db))->second(ctxt->obj)); } catch(sqlite_exception &e) { sqlite3_result_error_code(db, e.get_code()); sqlite3_result_error(db, e.what(), -1); } catch(std::exception &e) { sqlite3_result_error(db, e.what(), -1); } catch(...) { sqlite3_result_error(db, "Unknown error", -1); } if(ctxt && ctxt->constructed) ctxt->~AggregateCtxt(); } template< std::size_t Count, typename Function, typename... Values > inline typename std::enable_if<(sizeof...(Values) < Count), void>::type scalar( sqlite3_context* db, int count, sqlite3_value** vals, Values&&... values ) { typename std::remove_cv< typename std::remove_reference< typename utility::function_traits<Function>::template argument<sizeof...(Values)> >::type >::type value{}; get_val_from_db(vals[sizeof...(Values)], value); scalar<Count, Function>(db, count, vals, std::forward<Values>(values)..., std::move(value)); } template< std::size_t Count, typename Function, typename... Values > inline typename std::enable_if<(sizeof...(Values) == Count), void>::type scalar( sqlite3_context* db, int, sqlite3_value**, Values&&... values ) { try { store_result_in_db(db, (*static_cast<Function*>(sqlite3_user_data(db)))(std::forward<Values>(values)...)); } catch(sqlite_exception &e) { sqlite3_result_error_code(db, e.get_code()); sqlite3_result_error(db, e.what(), -1); } catch(std::exception &e) { sqlite3_result_error(db, e.what(), -1); } catch(...) { sqlite3_result_error(db, "Unknown error", -1); } } } }
35.286777
158
0.697473
[ "vector" ]
aa944795e6d05de8c36368e5c655dd679c66dd57
9,329
h
C
xcode/POSD/utParser.h
howlie190/xcode
5dd0fac3cff0c4dd62fba45c74fcc2876ee10bdd
[ "BSD-3-Clause" ]
null
null
null
xcode/POSD/utParser.h
howlie190/xcode
5dd0fac3cff0c4dd62fba45c74fcc2876ee10bdd
[ "BSD-3-Clause" ]
null
null
null
xcode/POSD/utParser.h
howlie190/xcode
5dd0fac3cff0c4dd62fba45c74fcc2876ee10bdd
[ "BSD-3-Clause" ]
null
null
null
#ifndef UTPARSER_H #define UTPARSER_H #include "parser.h" #include "scanner.h" #include "struct.h" #include "list.h" #include "variable.h" #include "atom.h" #include "number.h" #include "term.h" Scanner scanner; class ParserTest : public :: testing :: Test { protected: void SetUp() { scanner.getSymtable()->clear(); } }; TEST_F(ParserTest, createTerm_Var){ scanner.setInput("X"); Parser parser(scanner); ASSERT_EQ("X", parser.createTerm()->symbol()); } TEST_F(ParserTest, createTerm_Num){ scanner.setInput("123"); Parser parser(scanner); ASSERT_EQ("123", parser.createTerm()->symbol()); } TEST_F(ParserTest, createTerm_Atom) { scanner.setInput("tom"); Parser parser(scanner); ASSERT_EQ("tom", parser.createTerm()->symbol()); } TEST_F(ParserTest, createArgs) { scanner.setInput("1, X, tom"); Parser parser(scanner); vector<Term*> terms = parser.getArgs(); ASSERT_EQ("1", terms[0]->symbol()); ASSERT_EQ("X", terms[1]->symbol()); ASSERT_EQ("tom", terms[2]->symbol()); } TEST_F(ParserTest, createTerms) { scanner.setInput("s(1, X, tom)"); Parser parser(scanner); ASSERT_EQ("s(1, X, tom)", parser.createTerm()->symbol()); } // Given there is string: " 12345, tom" in scanner. // When parser parses all terms via scanner. // Then it should return two terms, one is "12345", another is "tom". TEST_F(ParserTest, listOfTermsTwo) { scanner.setInput(" 12345, tom"); Parser parser(scanner); vector<Term *>terms = parser.getArgs(); ASSERT_EQ("12345", terms[0]->symbol()); ASSERT_EQ("tom", terms[1]->symbol()); } // Given there is string: "point(1, X, z(1,2,3))" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "point(1, X, z(1,2,3))". TEST_F(ParserTest, parseStructOfStruct) { scanner.setInput("point(1, X, z(1, 2, 3))"); Parser parser(scanner); ASSERT_EQ("point(1, X, z(1, 2, 3))", parser.createTerm()->symbol()); } // Given there is string: " 12345, 67" in scanner. // When parser parses all terms via scanner. // Then it should return two terms, one is "12345", another is "67". TEST_F(ParserTest, listOfTermsTwoNumbers) { scanner.setInput(" 12345, 67"); Parser parser(scanner); vector<Term *>terms = parser.getArgs(); ASSERT_EQ("12345", terms[0]->symbol()); ASSERT_EQ("67", terms[1]->symbol()); } // Given there is string: "point(1, X, z)" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "point(1, X, z)". TEST_F(ParserTest, parseStructThreeArgs) { scanner.setInput("point(1, X, z)"); Parser parser(scanner); ASSERT_EQ("point(1, X, z)", parser.createTerm()->symbol()); } // Given there is string: " [ ]" in scanner. // When parser parses all terms via scanner. // Then it should return a List. // And #symbol() of List should return "[]". TEST_F(ParserTest, parseListEmpty) { scanner.setInput(" [ ]"); Parser parser(scanner); ASSERT_EQ("[]", parser.createTerm()->symbol()); } // Given there is string: "_date" in scanner. // When parser parses all terms via scanner. // Then it should return a Variable. // And #symbol() of Variable should return "_date". TEST_F(ParserTest, parseVar) { scanner.setInput("_date"); Parser parser(scanner); ASSERT_EQ("_date", parser.createTerm()->symbol()); } // Given there is not string in scanner. // When parser parses all terms via scanner. // Then it should return nothing. TEST_F(ParserTest, listOfTermsEmpty) { scanner.setInput(""); Parser parser(scanner); ASSERT_EQ(nullptr, parser.createTerm()); } // Given there is string: "s(s(s(s(1))))" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "s(s(s(s(1))))". TEST_F(ParserTest, parseStructOfStructAllTheWay) { scanner.setInput("s(s(s(s(1))))"); Parser parser(scanner); ASSERT_EQ("s(s(s(s(1))))", parser.createTerm()->symbol()); } // Given there is string: " [ [1], [] ]" in scanner. // When parser parses all terms via scanner. // Then it should return a List. // And #symbol() of List should return "[[1], []]". TEST_F(ParserTest, parseListOfLists) { scanner.setInput(" [ [1], [] ]"); Parser parser(scanner); ASSERT_EQ("[[1], []]", parser.createTerm()->symbol()); } // Given there is string: " [ [1], [], s(s(1)) ] " in scanner. // When parser parses all terms via scanner. // Then it should return a List. // And #symbol() of List should return "[[1], [], s(s(1))]". TEST_F(ParserTest, parseListOfListsAndStruct) { scanner.setInput("[[1], [], s(s(1))]"); Parser parser(scanner); ASSERT_EQ("[[1], [], s(s(1))]", parser.createTerm()->symbol()); } // Given there is string: " [1, 2]" in scanner. // When parser parses all terms via scanner. // Then it should return a List. // And #symbol() of List should return "[1, 2]". TEST_F(ParserTest, parseList) { scanner.setInput(" [1, 2]"); Parser parser(scanner); ASSERT_EQ("[1, 2]", parser.createTerm()->symbol()); } // Given there is string: "[1,2)" in scanner. // When parser parses all terms via scanner. // Then it should return a string: "unexpected token" as exception. TEST_F(ParserTest, illegal1) { scanner.setInput("[1,2)"); Parser parser(scanner); try { parser.createTerm(); } catch(string err) { ASSERT_EQ("unexpected token", err); } } // Given there is string: ".(1,[])" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct which contains two terms. // And #arity() of the Struct should be 2. // And #symbol() of Struct should return ".(1, [])". // And the first term should be number: "1", the second term should be another Strcut: "[]". TEST_F(ParserTest, ListAsStruct) { scanner.setInput(".(1,[])"); Parser parser(scanner); Struct *ps = parser.createTerm()->getStruct(); ASSERT_EQ(2, ps->arity()); ASSERT_EQ(".(1, [])", ps->symbol()); ASSERT_EQ("1", ps->args(0)->symbol()); ASSERT_EQ("[]", ps->args(1)->symbol()); } // Given there is string: ".(2,.(1,[]))" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct which contains two terms. // And #arity() of the Struct should be 2. // And #symbol() of Struct should return ".(2, .(1, []))" // And the first term should be number: "2", the second term should be another Strcut: ".(1, [])". TEST_F(ParserTest, ListAsStruct2) { scanner.setInput( ".(2,.(1,[]))"); Parser parser(scanner); Struct *ps = parser.createTerm()->getStruct(); ASSERT_EQ(2, ps->arity()); ASSERT_EQ(".(2, .(1, []))", ps->symbol()); ASSERT_EQ("2", ps->args(0)->symbol()); ASSERT_EQ(".(1, [])", ps->args(1)->symbol()); } // Given there is string: "s(s(s(s(1)))), b(1,2,3)" in scanner. // When parser parses all terms via scanner. // Then it should return two Struct. // And #symbol() of the first Strcut should return "s(s(s(s(1))))". // And #symbol() of the second Strcut should return "b(1, 2, 3)". TEST_F(ParserTest, parseStructOfStructAllTheWay2) { scanner.setInput("s(s(s(s(1)))), b(1,2,3)"); Parser parser(scanner); vector<Term *>terms = parser.getArgs(); ASSERT_EQ("s(s(s(s(1))))", terms[0]->symbol()); ASSERT_EQ("b(1, 2, 3)", terms[1]->symbol()); } // Given there is string: "point()" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "point()". TEST_F(ParserTest, parseStructNoArg) { scanner.setInput("point()"); Parser parser(scanner); ASSERT_EQ("point()", parser.createTerm()->symbol()); } // Given there is string: " 12345, tom, Date" in scanner. // When parser parses all terms via scanner. // Then it should return three terms: "12345", "tom" and "Date". TEST_F(ParserTest, listOfTermsThree) { scanner.setInput(" 12345, tom, Date"); Parser parser(scanner); vector<Term *>terms = parser.getArgs(); ASSERT_EQ("12345", terms[0]->symbol()); ASSERT_EQ("tom", terms[1]->symbol()); ASSERT_EQ("Date", terms[2]->symbol()); } // Given there is string: "point(11,12)" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "point(11, 12)". TEST_F(ParserTest, parseStructTwoArgs) { scanner.setInput("point(11,12)"); Parser parser(scanner); ASSERT_EQ("point(11, 12)", parser.createTerm()->symbol()); } // Given there is string: "...(11,12)" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "...(11, 12)". TEST_F(ParserTest, parseStructDOTSTwoArgs) { scanner.setInput("...(11,12)"); Parser parser(scanner); ASSERT_EQ("...(11, 12)", parser.createTerm()->symbol()); } // Given there is string: "point(11)" in scanner. // When parser parses all terms via scanner. // Then it should return a Struct. // And #symbol() of Strcut should return "point(11)". TEST_F(ParserTest, parseStructOneArg) { scanner.setInput("point(11)"); Parser parser(scanner); ASSERT_EQ("point(11)", parser.createTerm()->symbol()); } #endif
32.168966
98
0.644871
[ "vector" ]
aa94866823a660fc623fe805ff9f483c4e0dcdac
25,856
h
C
x86Emit.h
andkrau/nuance
32b9d6b9257c6c51944727456fce2e7caf074182
[ "W3C" ]
null
null
null
x86Emit.h
andkrau/nuance
32b9d6b9257c6c51944727456fce2e7caf074182
[ "W3C" ]
null
null
null
x86Emit.h
andkrau/nuance
32b9d6b9257c6c51944727456fce2e7caf074182
[ "W3C" ]
null
null
null
#ifndef X86EMIT_H #define X86EMIT_H #define X86_CC_O (0x0) #define X86_CC_NO (0x1) #define X86_CC_B (0x2) #define X86_CC_NB (0x3) #define X86_CC_Z (0x4) #define X86_CC_NZ (0x5) #define X86_CC_BE (0x6) #define X86_CC_NBE (0x7) #define X86_CC_S (0x8) #define X86_CC_NS (0x9) #define X86_CC_P (0xA) #define X86_CC_NP (0xB) #define X86_CC_L (0xC) #define X86_CC_NL (0xD) #define X86_CC_LE (0xE) #define X86_CC_NLE (0xF) #define X86_CC_E X86_CC_Z #define X86_CC_NE X86_CC_NZ enum x86Reg { x86Reg_al = 0, x86Reg_cl, x86Reg_dl, x86Reg_bl, x86Reg_ah, x86Reg_ch, x86Reg_dh, x86Reg_bh, x86Reg_ax, x86Reg_cx, x86Reg_dx, x86Reg_bx, x86Reg_sp, x86Reg_bp, x86Reg_si, x86Reg_di, x86Reg_eax, x86Reg_ecx, x86Reg_edx, x86Reg_ebx, x86Reg_esp, x86Reg_ebp, x86Reg_esi, x86Reg_edi, x86Reg_es, x86Reg_cs, x86Reg_ss, x86Reg_ds, x86Reg_fs, x86Reg_gs, x86Reg_invalid1, x86Reg_invalid2, x86Reg_mm0, x86Reg_mm1, x86Reg_mm2, x86Reg_mm3, x86Reg_mm4, x86Reg_mm5, x86Reg_mm6, x86Reg_mm7, x86Reg_xmm0, x86Reg_xmm1, x86Reg_xmm2, x86Reg_xmm3, x86Reg_xmm4, x86Reg_xmm5, x86Reg_xmm6, x86Reg_xmm7, x86Reg_cr0, x86Reg_cr1, x86Reg_cr2, x86Reg_cr3, x86Reg_cr4, x86Reg_cr5, x86Reg_cr6, x86Reg_cr7, x86Reg_dr0, x86Reg_dr1, x86Reg_dr2, x86Reg_dr3, x86Reg_dr4, x86Reg_dr5, x86Reg_dr6, x86Reg_dr7, }; enum x86ModReg { x86ModReg_eax = 0, x86ModReg_ecx, x86ModReg_edx, x86ModReg_ebx, x86ModReg_esp, x86ModReg_ebp, x86ModReg_esi, x86ModReg_edi, }; enum x86ModType { x86ModType_mem = 0, x86ModType_mem_disp8 = 1, x86ModType_mem_disp32 = 2, x86ModType_reg = 3, }; enum x86MemPtr { x86MemPtr_byte = 0, x86MemPtr_word = 1, x86MemPtr_dword = 2, x86MemPtr_qword = 3, }; #define x86ModReg_al x86ModReg_eax #define x86ModReg_cl x86ModReg_ecx #define x86ModReg_dl x86ModReg_edx #define x86ModReg_bl x86ModReg_ebx #define x86ModReg_ah x86ModReg_esp #define x86ModReg_ch x86ModReg_ebp #define x86ModReg_dh x86ModReg_esi #define x86ModReg_bh x86ModReg_edi #define x86ModReg_ax x86ModReg_eax #define x86ModReg_cx x86ModReg_ecx #define x86ModReg_dx x86ModReg_edx #define x86ModReg_bx x86ModReg_ebx #define x86ModReg_sp x86ModReg_esp #define x86ModReg_bp x86ModReg_ebp #define x86ModReg_si x86ModReg_esi #define x86ModReg_di x86ModReg_edi #define x86ModReg_mm0 x86ModReg_eax #define x86ModReg_mm1 x86ModReg_ecx #define x86ModReg_mm2 x86ModReg_edx #define x86ModReg_mm3 x86ModReg_ebx #define x86ModReg_mm4 x86ModReg_esp #define x86ModReg_mm5 x86ModReg_ebp #define x86ModReg_mm6 x86ModReg_esi #define x86ModReg_mm7 x86ModReg_edi #define x86ModReg_xmm0 x86ModReg_eax #define x86ModReg_xmm1 x86ModReg_ecx #define x86ModReg_xmm2 x86ModReg_edx #define x86ModReg_xmm3 x86ModReg_ebx #define x86ModReg_xmm4 x86ModReg_esp #define x86ModReg_xmm5 x86ModReg_ebp #define x86ModReg_xmm6 x86ModReg_esi #define x86ModReg_xmm7 x86ModReg_edi enum x86BaseReg { x86BaseReg_eax = 0, x86BaseReg_ecx, x86BaseReg_edx, x86BaseReg_ebx, x86BaseReg_esp, x86BaseReg_ebp, x86BaseReg_esi, x86BaseReg_edi, }; #define x86BaseReg_sib x86BaseReg_esp #define x86BaseReg_sdword x86BaseReg_ebp enum x86IndexReg { x86IndexReg_eax = 0, x86IndexReg_ecx, x86IndexReg_edx, x86IndexReg_ebx, x86IndexReg_none, x86IndexReg_ebp, x86IndexReg_esi, x86IndexReg_edi, }; enum x86ScaleVal { x86Scale_1 = 0, x86Scale_2, x86Scale_4, x86Scale_8, }; void X86Emit_ModRegRM(x86ModType, x86ModReg modReg, uint32 baseReg, x86IndexReg = x86IndexReg_none, x86ScaleVal = x86Scale_1, int32 disp = 0); uint8 *GetEmitPointer(); void SetEmitPointer(uint8 *ptr); void AlignEmitPointer(uint8 boundary); void X86Emit_ADDRR(x86Reg regDest, x86Reg regSrc); void X86Emit_ADDRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ADDMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ADDIR(int32 imm, x86Reg regDest); void X86Emit_ADDIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHES(); void X86Emit_POPES(); void X86Emit_ORRR(x86Reg regDest, x86Reg regSrc); void X86Emit_ORRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ORMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ORIR(int32 imm, x86Reg regDest); void X86Emit_ORIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHCS(); void X86Emit_ADCRR(x86Reg regDest, x86Reg regSrc); void X86Emit_ADCRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ADCMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ADCIR(int32 imm, x86Reg regDest); void X86Emit_ADCIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHSS(); void X86Emit_POPSS(); void X86Emit_SBBRR(x86Reg regDest, x86Reg regSrc); void X86Emit_SBBRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SBBMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SBBIR(int32 imm, x86Reg regDest); void X86Emit_SBBIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHDS(); void X86Emit_POPDS(); void X86Emit_ANDRR(x86Reg regDest, x86Reg regSrc); void X86Emit_ANDRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ANDMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ANDIR(int32 imm, x86Reg regDest); void X86Emit_ANDIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ES(); void X86Emit_DAA(); void X86Emit_SUBRR(x86Reg regDest, x86Reg regSrc); void X86Emit_SUBRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SUBMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SUBIR(int32 imm, x86Reg regDest); void X86Emit_SUBIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CS(); void X86Emit_DAS(); void X86Emit_XORRR(x86Reg regDest, x86Reg regSrc); void X86Emit_XORRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_XORMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_XORIR(int32 imm, x86Reg regDest); void X86Emit_XORIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SS(); void X86Emit_AAA(); void X86Emit_CMPRR(x86Reg regDest, x86Reg regSrc); void X86Emit_CMPRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMPMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMPIR(int32 imm, x86Reg regDest); void X86Emit_CMPIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_DS(); void X86Emit_AAS(); void X86Emit_INCR(x86Reg reg); void X86Emit_DECR(x86Reg reg); void X86Emit_PUSHR(x86Reg reg); void X86Emit_POPR(x86Reg reg); void X86Emit_PUSHAW(); void X86Emit_PUSHAD(); #define X86Emit_PUSHA X86Emit_PUSHAD void X86Emit_POPAW(); void X86Emit_POPAD(); #define X86Emit_POPA X86Emit_POPAD void X86Emit_FS(); void X86Emit_GS(); void X86Emit_OPSIZE(); void X86Emit_ADSIZE(); void X86Emit_PUSHID(int32 imm); void X86Emit_PUSHIW(int16 imm); void X86Emit_IMULIRR(x86Reg regDest, int32 imm, x86Reg regSrc); void X87Emit_IMULIMR(x86Reg regDest, int32 imm, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_IMULRR(x86Reg regSrc); void X86Emit_IMULMR(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_IMULRRR(x86Reg regDest, x86Reg regSrc); void X86Emit_IMULMRR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHIB(int8 imm); void X86Emit_INSB(); void X86Emit_INSW(); void X86Emit_INSD(); void X86Emit_OUTSB(); void X86Emit_OUTSW(); void X86Emit_OUTSD(); void X86Emit_JCC(uint8 *pTarget, int8 conditionCode); void X86Emit_JCC_Label(int8 conditionCode, uint32 labelIndex); void X86Emit_JO(uint8 *pTarget); void X86Emit_JNO(uint8 *pTarget); void X86Emit_JB(uint8 *pTarget); void X86Emit_JNB(uint8 *pTarget); void X86Emit_JZ(uint8 *pTarget); void X86Emit_JNZ(uint8 *pTarget); void X86Emit_JBE(uint8 *pTarget); void X86Emit_JNBE(uint8 *pTarget); void X86Emit_JS(uint8 *pTarget); void X86Emit_JNS(uint8 *pTarget); void X86Emit_JP(uint8 *pTarget); void X86Emit_JNP(uint8 *pTarget); void X86Emit_JL(uint8 *pTarget); void X86Emit_JNL(uint8 *pTarget); void X86Emit_JLE(uint8 *pTarget); void X86Emit_JNLE(uint8 *pTarget); void X86Emit_TESTRR(x86Reg regDest, x86Reg regSrc); void X86Emit_TESTRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_TESTIR(uint32 imm, x86Reg regSrc); void X86Emit_TESTIM(uint32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_XCHGRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVRR(x86Reg regDest, x86Reg regSrc); void X86Emit_LEA(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_POPM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_NOP(); void X86Emit_XCHGRR(x86Reg reg1, x86Reg reg2); void X86Emit_CBW(); void X86Emit_CWDE(); void X86Emit_CWD(); void X86Emit_CDQ(); void X86Emit_CALLI(uint32 offset, uint16 seg); void X86Emit_JMPI(uint8 *target, uint16 seg); void X86Emit_JMPI_Label(uint32 labelIndex); void X86Emit_WAIT(); void X86Emit_PUSHFW(); void X86Emit_PUSHFD(); #define X86Emit_PUSHF X86Emit_PUSHFD void X86Emit_POPFW(); void X86Emit_POPFD(); #define X86Emit_POPF X86Emit_POPFD void X86Emit_SAHF(); void X86Emit_LAHF(); void X86Emit_MOVMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVIR(int32 imm, x86Reg regDest); void X86Emit_MOVSB(); void X86Emit_MOVSW(); void X86Emit_MOVSD(); void X86Emit_CMPSB(); void X86Emit_CMPSW(); void X86Emit_CMPSD(); void X86Emit_STOSB(); void X86Emit_STOSW(); void X86Emit_STOSD(); void X86Emit_LODSB(); void X86Emit_LODSW(); void X86Emit_LODSD(); void X86Emit_SCASB(); void X86Emit_SCASW(); void X86Emit_SCASD(); void X86Emit_ROLIR(x86Reg regDest, uint8 shiftCount); void X86Emit_RORIR(x86Reg regDest, uint8 shiftCount); void X86Emit_RCLIR(x86Reg regDest, uint8 shiftCount); void X86Emit_RCRIR(x86Reg regDest, uint8 shiftCount); void X86Emit_SHLIR(x86Reg regDest, uint8 shiftCount); void X86Emit_SHLDIRR(x86Reg regDest, x86Reg regSrc, uint8 shiftCount); void X86Emit_SHLDRRR(x86Reg regDest, x86Reg regSrc); void X86Emit_SHLDIRM(x86Reg regSrc, x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHLDRRM(x86Reg regSrc, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHRDIRR(x86Reg regDest, x86Reg regSrc, uint8 shiftCount); void X86Emit_SHRDRRR(x86Reg regDest, x86Reg regSrc); void X86Emit_SHRDIRM(x86Reg regSrc, x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHRDRRM(x86Reg regSrc, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHRIR(x86Reg regDest, uint8 shiftCount); void X86Emit_SALIR(x86Reg regDest, uint8 shiftCount); void X86Emit_SARIR(x86Reg regDest, uint8 shiftCount); void X86Emit_ROLIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RORIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RCLIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RCRIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHLIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHRIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SALIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SARIM(x86MemPtr ptrType, uint8 shiftCount, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_ROLRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RORRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RCLRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RCRRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHLRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SHRRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SALRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SARRM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_RETN(uint16 iw); #define X86Emit_RET X86Emit_RETN void X86Emit_MOVIM(int32 imm, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_LEAVE(); void X86Emit_RETF(uint16 iw); void X86Emit_INT3(); void X86Emit_INT(int8 vector); void X86Emit_INTO(); void X86Emit_IRET(); void X86Emit_ROLRR(x86Reg regDest); void X86Emit_RORRR(x86Reg regDest); void X86Emit_RCLRR(x86Reg regDest); void X86Emit_RCRRR(x86Reg regDest); void X86Emit_SHLRR(x86Reg regDest); void X86Emit_SHRRR(x86Reg regDest); void X86Emit_SALRR(x86Reg regDest); void X86Emit_SARRR(x86Reg regDest); void X86Emit_AAM(uint8 divisor); void X86Emit_AAD(uint8 divisor); void X86Emit_XLAT(); void X86Emit_ESC0(); void X86Emit_ESC1(); void X86Emit_ESC2(); void X86Emit_ESC3(); void X86Emit_ESC4(); void X86Emit_ESC5(); void X86Emit_ESC6(); void X86Emit_ESC7(); void X86Emit_LOOPNE(uint8 *pTarget); void X86Emit_LOOPNE_Label(uint32 labelIndex); #define X86Emit_LOOPNZ X86Emit_LOOPNE #define X86Emit_LOOPNZ_Label X86Emit_LOOPNE_Label void X86Emit_LOOPE(uint8 *pTarget); void X86Emit_LOOPE_Label(uint32 labelIndex); #define X86Emit_LOOPZ X86Emit_LOOPE #define X86Emit_LOOPZ_Label X86Emit_LOOPZ_Label void X86Emit_LOOP(uint8 *pTarget); void X86Emit_LOOP_Label(uint32 labelIndex); void X86Emit_JCXZ(uint8 *pTarget); void X86Emit_JCXZ_Label(uint32 labelIndex); void X86Emit_JECXZ(uint8 *pTarget); void X86Emit_JECXZ_Label(uint32 labelIndex); void X86Emit_INI(x86Reg regDest, uint8 port); void X86Emit_OUTI(x86Reg regDest, uint8 data); void X86Emit_INR(x86Reg regDest); void X86Emit_OUTR(x86Reg regDest); void X86Emit_LOCK(); void X86Emit_INT1(); void X86Emit_REPNE(); void X86Emit_REPE(); #define X86Emit_REP X86Emit_REPE void X86Emit_HLT(); void X86Emit_CMC(); void X86Emit_NOTR(x86Reg regDest); void X86Emit_NOTM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_NEGR(x86Reg regDest); void X86Emit_NEGM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CLC(); void X86Emit_STC(); void X86Emit_CLI(); void X86Emit_STI(); void X86Emit_CLD(); void X86Emit_STD(); void X86Emit_INCM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_DECM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CALLNM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); #define X86Emit_CALLM X86Emit_CALLNM void X86Emit_CALLR(x86Reg regSrc); void X86Emit_CALLFM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_JMPR(x86Reg regSrc); void X86Emit_JMPNM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); #define X86Emit_JMPM X86Emit_JMPNM void X86Emit_JMPFM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_PUSHM(x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_INVD(x86Reg reg); void X86Emit_WBINVD(x86Reg reg); void X86Emit_UD1(x86Reg reg); void X86Emit_BSWAP(x86Reg reg); void X86Emit_SETOR(x86Reg reg); void X86Emit_SETOM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNOR(x86Reg reg); void X86Emit_SETNOM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETBR(x86Reg reg); void X86Emit_SETBM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNBR(x86Reg reg); void X86Emit_SETNBM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETZR(x86Reg reg); void X86Emit_SETZM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNZR(x86Reg reg); void X86Emit_SETNZM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETBER(x86Reg reg); void X86Emit_SETBEM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNBER(x86Reg reg); void X86Emit_SETNBEM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETSR(x86Reg reg); void X86Emit_SETSM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNSR(x86Reg reg); void X86Emit_SETNSM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETPR(x86Reg reg); void X86Emit_SETPM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNPR(x86Reg reg); void X86Emit_SETNPM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETLR(x86Reg reg); void X86Emit_SETLM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNLR(x86Reg reg); void X86Emit_SETNLM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETLER(x86Reg reg); void X86Emit_SETLEM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_SETNLER(x86Reg reg); void X86Emit_SETNLEM(uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVORR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVOMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNORR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNOMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVBRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVBMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNBRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNBMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVZRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVZMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNZRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNZMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVBERR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVBEMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNBERR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNBEMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVSRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVSMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNSRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNSMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVPRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVPMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNPRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNPMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVLRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVLMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNLRR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNLMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVLERR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVLEMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_CMOVNLERR(x86Reg regDest, uint32 regSrc); void X86Emit_CMOVNLEMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVSXRR(x86Reg regDest, uint32 regSrc); void X86Emit_MOVZXRR(x86Reg regDest, uint32 regSrc); void X86Emit_MOVSXMR(x86Reg regDest, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVZXMR(x86Reg regDest, x86MemPtr ptrType, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVQRR(x86Reg regDest, x86Reg regSrc); void X86Emit_MOVQRM(x86Reg regSrc, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); void X86Emit_MOVQMR(x86Reg regDest, uint32 base, x86IndexReg index = x86IndexReg_none, x86ScaleVal scale = x86Scale_1, int32 disp = 0); #endif
48.148976
173
0.785775
[ "vector" ]
aa999f5ba9a39cbf72dcab44471a9ab00e43a402
8,808
h
C
lib/NeoPixelBus/src/internal/RgbColor.h
DAbramau/baseboard_leds_fw
cb533becb16d351b54aa1340e2c8dfaa72e736cd
[ "MIT" ]
4
2019-11-10T04:35:24.000Z
2020-07-23T16:04:34.000Z
lib/NeoPixelBus/src/internal/RgbColor.h
DAbramau/baseboard_leds_fw
cb533becb16d351b54aa1340e2c8dfaa72e736cd
[ "MIT" ]
null
null
null
lib/NeoPixelBus/src/internal/RgbColor.h
DAbramau/baseboard_leds_fw
cb533becb16d351b54aa1340e2c8dfaa72e736cd
[ "MIT" ]
2
2020-04-27T10:18:15.000Z
2020-06-09T03:01:44.000Z
/*------------------------------------------------------------------------- RgbColor provides a color object that can be directly consumed by NeoPixelBus Written by Michael C. Miller. I invest time and resources providing this open source code, please support me by dontating (see https://github.com/Makuna/NeoPixelBus) ------------------------------------------------------------------------- This file is part of the Makuna/NeoPixelBus library. NeoPixelBus is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NeoPixelBus 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 NeoPixel. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------*/ #pragma once #include <Arduino.h> #include "NeoSettings.h" #include "RgbColorBase.h" struct RgbwColor; // ------------------------------------------------------------------------ // RgbColor represents a color object that is represented by Red, Green, Blue // component values. It contains helpful color routines to manipulate the // color. // ------------------------------------------------------------------------ struct RgbColor : RgbColorBase { typedef NeoRgbCurrentSettings SettingsObject; // ------------------------------------------------------------------------ // Construct a RgbColor using R, G, B values (0-255) // ------------------------------------------------------------------------ RgbColor(uint8_t r, uint8_t g, uint8_t b) : R(r), G(g), B(b) { }; // ------------------------------------------------------------------------ // Construct a RgbColor using a single brightness value (0-255) // This works well for creating gray tone colors // (0) = black, (255) = white, (128) = gray // ------------------------------------------------------------------------ RgbColor(uint8_t brightness) : R(brightness), G(brightness), B(brightness) { }; // ------------------------------------------------------------------------ // explicitly Construct a RgbColor using RgbwColor // ------------------------------------------------------------------------ explicit RgbColor(const RgbwColor& color); // ------------------------------------------------------------------------ // Construct a RgbColor using Rgb16Color // ------------------------------------------------------------------------ RgbColor(const Rgb16Color& color); // ------------------------------------------------------------------------ // Construct a RgbColor using HtmlColor // ------------------------------------------------------------------------ RgbColor(const HtmlColor& color); // ------------------------------------------------------------------------ // Construct a RgbColor using HslColor // ------------------------------------------------------------------------ RgbColor(const HslColor& color); // ------------------------------------------------------------------------ // Construct a RgbColor using HsbColor // ------------------------------------------------------------------------ RgbColor(const HsbColor& color); // ------------------------------------------------------------------------ // Construct a RgbColor that will have its values set in latter operations // CAUTION: The R,G,B members are not initialized and may not be consistent // ------------------------------------------------------------------------ RgbColor() { }; // ------------------------------------------------------------------------ // Comparison operators // ------------------------------------------------------------------------ bool operator==(const RgbColor& other) const { return (R == other.R && G == other.G && B == other.B); }; bool operator!=(const RgbColor& other) const { return !(*this == other); }; // ------------------------------------------------------------------------ // CalculateBrightness will calculate the overall brightness // NOTE: This is a simple linear brightness // ------------------------------------------------------------------------ uint8_t CalculateBrightness() const; // ------------------------------------------------------------------------ // Dim will return a new color that is blended to black with the given ratio // ratio - (0-255) where 255 will return the original color and 0 will return black // // NOTE: This is a simple linear blend // ------------------------------------------------------------------------ RgbColor Dim(uint8_t ratio) const; // ------------------------------------------------------------------------ // Brighten will return a new color that is blended to white with the given ratio // ratio - (0-255) where 255 will return the original color and 0 will return white // // NOTE: This is a simple linear blend // ------------------------------------------------------------------------ RgbColor Brighten(uint8_t ratio) const; // ------------------------------------------------------------------------ // Darken will adjust the color by the given delta toward black // NOTE: This is a simple linear change // delta - (0-255) the amount to dim the color // ------------------------------------------------------------------------ void Darken(uint8_t delta); // ------------------------------------------------------------------------ // Lighten will adjust the color by the given delta toward white // NOTE: This is a simple linear change // delta - (0-255) the amount to lighten the color // ------------------------------------------------------------------------ void Lighten(uint8_t delta); // ------------------------------------------------------------------------ // LinearBlend between two colors by the amount defined by progress variable // left - the color to start the blend at // right - the color to end the blend at // progress - (0.0 - 1.0) value where 0 will return left and 1.0 will return right // and a value between will blend the color weighted linearly between them // ------------------------------------------------------------------------ static RgbColor LinearBlend(const RgbColor& left, const RgbColor& right, float progress); // ------------------------------------------------------------------------ // BilinearBlend between four colors by the amount defined by 2d variable // c00 - upper left quadrant color // c01 - upper right quadrant color // c10 - lower left quadrant color // c11 - lower right quadrant color // x - unit value (0.0 - 1.0) that defines the blend progress in horizontal space // y - unit value (0.0 - 1.0) that defines the blend progress in vertical space // ------------------------------------------------------------------------ static RgbColor BilinearBlend(const RgbColor& c00, const RgbColor& c01, const RgbColor& c10, const RgbColor& c11, float x, float y); uint32_t CalcTotalTenthMilliAmpere(const SettingsObject& settings) { auto total = 0; total += R * settings.RedTenthMilliAmpere / Max; total += G * settings.GreenTenthMilliAmpere / Max; total += B * settings.BlueTenthMilliAmpere / Max; return total; } // ------------------------------------------------------------------------ // Red, Green, Blue color members (0-255) where // (0,0,0) is black and (255,255,255) is white // ------------------------------------------------------------------------ uint8_t R; uint8_t G; uint8_t B; const static uint8_t Max = 255; private: inline static uint8_t _elementDim(uint8_t value, uint8_t ratio) { return (static_cast<uint16_t>(value) * (static_cast<uint16_t>(ratio) + 1)) >> 8; } inline static uint8_t _elementBrighten(uint8_t value, uint8_t ratio) { uint16_t element = ((static_cast<uint16_t>(value) + 1) << 8) / (static_cast<uint16_t>(ratio) + 1); if (element > Max) { element = Max; } else { element -= 1; } return element; } };
41.54717
106
0.437557
[ "object" ]
aaaa6cd00b75016b6e810fead9c658ebd5a43133
1,723
c
C
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_eigen/mult_ldu1.c
mcopik/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
2
2020-10-20T09:27:07.000Z
2021-03-22T05:10:24.000Z
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_eigen/mult_ldu1.c
spcl/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
11
2021-06-03T08:55:28.000Z
2022-01-20T19:38:29.000Z
benchmarks/milc/milc_qcd-7.8.1/arb_dirac_eigen/mult_ldu1.c
mcopik/perf-taint
16613b83f504c114a77f7a22d587c29ce52d7a4b
[ "BSD-3-Clause" ]
1
2020-12-05T09:53:50.000Z
2020-12-05T09:53:50.000Z
/******************* mult_ldu1.c ***************************************/ /* MIMD version 6 */ /* MIMD version 4 */ /* version of 12/29/94 by UMH */ /* Multiply a Wilson vector (spin,color) with a block-diagonal hermition matrix stored as a complex lower triangular matrix (without diagonal) and a real diagonal. The blocks are spin indices 0,1 and 2,3. */ #include "arb_dirac_eig_includes.h" /* To simplify the code with the above block structure, introduce the somewhat dirty structure, equivalent to a wilson_vector: */ typedef struct { complex b[2][6]; } wilson_block_vector; void mult_ldu1_site(field_offset src,field_offset dest, field_offset triang,field_offset diag, int parity) { register int i; register site *s; register int b,j,k,jk,kj; complex ctmp; FORSOMEPARITY(i,s,parity){ for(b=0;b<2;b++)for(j=0;j<6;j++){ /* diagonal part */ CMULREAL(((wilson_block_vector *)F_PT(s,src))->b[b][j], ((diagonal *)F_PT(s,diag))->di[b][j], ((wilson_block_vector *)F_PT(s,dest))->b[b][j]); /* lower triangular part */ jk=j*(j-1)/2; for(k=0;k<j;k++){ CMUL(((triangular *)F_PT(s,triang))->tr[b][jk], ((wilson_block_vector *)F_PT(s,src))->b[b][k],ctmp); CADD(ctmp,((wilson_block_vector *)F_PT(s,dest))->b[b][j], ((wilson_block_vector *)F_PT(s,dest))->b[b][j]); jk++; } } for(b=0;b<2;b++)for(k=0;k<6;k++){ /* upper triangular part */ kj=k*(k-1)/2; for(j=0;j<k;j++){ CMULJ_(((triangular *)F_PT(s,triang))->tr[b][kj], ((wilson_block_vector *)F_PT(s,src))->b[b][k],ctmp); CADD(ctmp,((wilson_block_vector *)F_PT(s,dest))->b[b][j], ((wilson_block_vector *)F_PT(s,dest))->b[b][j]); kj++; } } } } /* mult_ldu1 */
28.716667
73
0.603598
[ "vector" ]
ece6fa055e43fae7ca8208ed86a605213ba31579
1,667
h
C
src/balObject.h
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
1
2020-02-02T22:30:37.000Z
2020-02-02T22:30:37.000Z
src/balObject.h
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
src/balObject.h
danielelinaro/BAL
d735048d9962a0c424c29db93f774494c67b12a9
[ "MIT" ]
null
null
null
/*========================================================================= * * Program: Bifurcation Analysis Library * Module: balObject.h * * Copyright (C) 2009,2010 Daniele Linaro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *=========================================================================*/ /** * \file balObject.h * \brief Definition of the class balObject */ #ifndef _BALOBJECT_ #define _BALOBJECT_ #include <string> namespace bal { /** * \class balObject * \brief Base class for all BAL objects. * * Object is the base class for all objects in the Bifurcation Analysis * Library. Every object in the library should be a subclass of balObject. */ class Object { public: /** Constructor of the class. */ Object(); /** Destructor of the class. */ virtual ~Object(); /** Method for cloning an object. */ virtual Object* Clone() const = 0; /** Builds a string that represents the object. */ virtual std::string ToString() const = 0; }; } // namespace bal #endif
28.254237
77
0.623875
[ "object" ]
ece7bfc480da7fc5d833d481282900cd72cf1444
9,429
c
C
src/refine_local_extrema.c
cmimprota/ASL-SIFT
e6e489e9cc06746e2ab8cd11193fc9fc0112e5df
[ "Zlib" ]
1
2021-12-30T14:59:43.000Z
2021-12-30T14:59:43.000Z
src/refine_local_extrema.c
cmimprota/ASL-SIFT
e6e489e9cc06746e2ab8cd11193fc9fc0112e5df
[ "Zlib" ]
null
null
null
src/refine_local_extrema.c
cmimprota/ASL-SIFT
e6e489e9cc06746e2ab8cd11193fc9fc0112e5df
[ "Zlib" ]
1
2021-04-12T11:13:32.000Z
2021-04-12T11:13:32.000Z
#include "internal.h" /// <summary> /// Refine the location of the keypoints to be sub-pixel accurate. /// </summary> /// <param name="differences"> IN: DOG pyramid. </param> /// <param name="octave_count"> IN: Number of Octaves. </param> /// <param name="gaussian_count"> IN: Number of layers. </param> /// <param name="keypoints"> OUT: Array of detected keypoints. </param> /// <returns> 1 IF computation was successful, ELSE 0. </returns> /// <remarks> 477 + 2POWs FLOPs </remarks> int ethsift_refine_local_extrema(struct ethsift_image differences[], uint32_t octave_count, uint32_t gaussian_count, struct ethsift_keypoint *keypoint){ // Settings int intvls = ETHSIFT_INTVLS; float inverse_intvls = ETHSIFT_INVERSE_INTVLS; int max_interp_steps = ETHSIFT_MAX_INTERP_STEPS; float kpt_subpixel_thr = ETHSIFT_KEYPOINT_SUBPiXEL_THR; float contr_thr = ETHSIFT_CONTR_THR; float curv_thr = ETHSIFT_CURV_THR; float response = ETHSIFT_RESPONSE; float sigma = ETHSIFT_SIGMA; // Fields: int w = 0; int h = 0; int layer_ind = 0; int nDoGLayers = ((int) gaussian_count) - 1; int octave = (int) keypoint->octave; int layer = (int) keypoint->layer; inc_read(2, int32_t); int r = keypoint->layer_pos.y; int c = keypoint->layer_pos.x; inc_read(2, int32_t); int xr_i = 0, xc_i = 0; float dx = 0.0f, dy = 0.0f, ds = 0.0f; float dxx = 0.0f, dyy = 0.0f, dss = 0.0f, dxs = 0.0f, dys = 0.0f, dxy = 0.0f; // Current, low and high index in DoG pyramid float *curData = 0; float *lowData = 0; float *highData = 0; // Interpolation (x,y,sigma) 3D space to find sub-pixel accurate // location of keypoints. // 5 * 91 = 455 FLOPs int i = 0; layer_ind = octave * nDoGLayers + layer; w = differences[layer_ind].width; h = differences[layer_ind].height; inc_read(2, int32_t); float temp[4] = {c, r, layer, 0.0}; float xD[4]; float Hinvert[12]; curData = differences[layer_ind].pixels; highData = differences[layer_ind + 1].pixels; lowData = differences[layer_ind - 1].pixels; for (; i < max_interp_steps; i++) { c += xc_i; r += xr_i; int c_right = internal_min(internal_max(c + 1, 0), w - 1); int c_center = internal_min(internal_max(c, 0), w - 1); int c_left = internal_min(internal_max(c - 1, 0), w - 1); int r_top_w = internal_min(internal_max(r + 1, 0), h - 1)*w; int r_center_w = internal_min(internal_max(r, 0), h - 1) * w; int r_bottom_w = internal_min(internal_max(r - 1, 0), h - 1)*w; int rbw_cl= r_bottom_w + c_left; int rbw_cc = r_bottom_w + c_center; int rbw_cr = r_bottom_w + c_right; int rcw_cl = r_center_w + c_left; int rcw_cc = r_center_w + c_center; int rcw_cr = r_center_w + c_right; int rtw_cl = r_top_w + c_left; int rtw_cc = r_top_w + c_center; int rtw_cr = r_top_w + c_right; float cur_rb_cl = curData[rbw_cl]; // [r - 1, c - 1] float cur_rb_cc = curData[rbw_cc]; // [r - 1, c] float cur_rb_cr = curData[rbw_cr]; // [r - 1, c + 1] float cur_rc_cl = curData[rcw_cl]; // [r, c - 1] float cur_rc_cc = curData[rcw_cc]; // [r, c] float cur_rc_cr = curData[rcw_cr]; // [r, c + 1] float cur_rt_cl = curData[rtw_cl]; // [r + 1, c - 1] float cur_rt_cc = curData[rtw_cc]; // [r + 1, c] float cur_rt_cr = curData[rtw_cr]; // [r + 1, c + 1] inc_read(1+3*3, float); float v2 = 2.0f * cur_rc_cc; //1 MUL inc_mults(1); dx = 0.5f * (cur_rc_cr - cur_rc_cl); //1 MUL + 1 SUB dxx = cur_rc_cr + cur_rc_cl - v2; //1 ADD + 1 SUB inc_mults(1); inc_adds(3); dy = 0.5f * (cur_rt_cc - cur_rb_cc); //1 MUL + 1 SUB dyy = cur_rt_cc + cur_rb_cc - v2; //1 ADD + 1 SUB inc_mults(1); inc_adds(3); dxy = 0.25f * (cur_rt_cr - cur_rt_cl - cur_rb_cr + cur_rb_cl); // 1MUL + 2SUBs + 1ADD 17 inc_mults(1); inc_adds(3); float high_rc_cl = highData[rcw_cl]; // [r, c - 1] float high_rc_cc = highData[rcw_cc]; // [r, c] float high_rc_cr = highData[rcw_cr]; // [r, c + 1] inc_read(1+3, float); float low_rc_cl = lowData[rcw_cl]; // [r, c - 1] float low_rc_cc = lowData[rcw_cc]; // [r, c] float low_rc_cr = lowData[rcw_cr]; // [r, c + 1] float high_rt_cc = highData[rtw_cc]; // [r + 1, c] float high_rb_cc = highData[rbw_cc]; // [r - 1, c] float low_rt_cc = lowData[rtw_cc]; // [r + 1, c] float low_rb_cc = lowData[rbw_cc]; // [r - 1, c] inc_read(1+3+2+2, float); ds = 0.5f * (high_rc_cc - low_rc_cc); //1 MUL + 1 SUB inc_mults(1); inc_adds(1); dss = high_rc_cc + low_rc_cc - v2; //1 ADD + 1 SUB inc_adds(2); dxs = 0.25f * (high_rc_cr - high_rc_cl - low_rc_cr + low_rc_cl); // 1MUL + 2SUBs + 1ADD inc_mults(1); inc_adds(3); dys = 0.25f * (high_rt_cc - high_rb_cc - low_rt_cc + low_rb_cc); // 1MUL + 2SUBs + 1ADD inc_mults(1); inc_adds(3); // The scale in two sides of the equation should cancel each other. float H[9] = {dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss}; inc_write(9, float); float det; // SARRUS Hinvert[0] = (H[4] * H[8] - H[5] * H[7]); Hinvert[1] = (H[5] * H[6] - H[3] * H[8]); Hinvert[2] = (H[3] * H[7] - H[4] * H[6]); inc_mults(6); inc_adds(3); inc_read(3*4, float); inc_write(3, float); det = H[0] * Hinvert[0]; // 3 MUL + 1 SUB det += H[1] * Hinvert[1]; // 3 MUL + 2 SUB det += H[2] * Hinvert[2]; // 3 MUL + 1 SUB + 1 ADD inc_adds(2); inc_mults(3); inc_read(3*2, float); if (fabsf(det) < FLT_MIN) break; Hinvert[4] = (H[2] * H[7] - H[1] * H[8]); Hinvert[5] = (H[0] * H[8] - H[2] * H[6]); Hinvert[6] = (H[1] * H[6] - H[0] * H[7]); Hinvert[8] = (H[1] * H[5] - H[2] * H[4]); Hinvert[9] = (H[2] * H[3] - H[0] * H[5]); Hinvert[10] = (H[0] * H[4] - H[1] * H[3]); inc_adds(6); inc_mults(12); inc_read(2*3*4, float); inc_write(2*3, float); float s = -1.0f / det; // 1 DIV inc_div(1); float t1 = dx * s; float t2 = dy * s; float t3 = ds * s; inc_mults(3); // MAT_DOT_VEC_3X3 __m128 xc_xr_xs, col1, col2, vec_t1, vec_t2, vec_t3, temp_add; vec_t1 = _mm_set1_ps(t1); vec_t2 = _mm_set1_ps(t2); vec_t3 = _mm_set1_ps(t3); xc_xr_xs = _mm_load_ps(Hinvert); col1 = _mm_load_ps(Hinvert+4); col2 = _mm_load_ps(Hinvert+8); inc_read(3+3*8, float); xc_xr_xs = _mm_mul_ps(xc_xr_xs, vec_t1); xc_xr_xs = _mm_fmadd_ps(col1, vec_t2, xc_xr_xs); xc_xr_xs = _mm_fmadd_ps(col2, vec_t3, xc_xr_xs); inc_adds(8); inc_mults(12); _mm_store_ps(xD, xc_xr_xs); inc_write(1, float); temp_add = _mm_set_ps(0.0, layer, r, c); inc_write(4, float); temp_add = _mm_add_ps(xc_xr_xs, temp_add); inc_adds(4); _mm_store_ps(temp, temp_add); inc_write(1, float); // Make sure there is room to move for next iteration. xc_i = ((xD[0] >= kpt_subpixel_thr && c < w - 2) ? 1 : 0) + ((xD[0] <= -kpt_subpixel_thr && c > 1) ? -1 : 0); inc_read(2, float); xr_i = ((xD[1] >= kpt_subpixel_thr && r < h - 2) ? 1 : 0) + ((xD[1] <= -kpt_subpixel_thr && r > 1) ? -1 : 0); inc_read(2, float); if (xc_i == 0 && xr_i == 0) // xs_i is never modifed, so I remove it from the checks break; } // We MIGHT be able to remove the following two checking conditions. // Condition 1 if (i == max_interp_steps) return 0; // Condition 2. if (fabsf(xD[0]) >= 1.5 || fabsf(xD[1]) >= 1.5 || fabsf(xD[2]) >= 1.5) return 0; inc_read(3, float); // If (r, c, layer) is out of range, return false. if (temp[2] < 0 || temp[2] > (((int) gaussian_count) - 1) || temp[1] < 0 || temp[1] > h - 1 || temp[0] < 0 || temp[0] > w - 1) return 0; inc_read(6, float); int c_center = internal_min(internal_max(c, 0), w - 1); int r_center = internal_min(internal_max(r, 0), h - 1); float cur_rc_cc = curData[r_center * w + c_center]; // [r, c] inc_read(1, float); float value = cur_rc_cc + 0.5f * (dx * xD[0] + dy * xD[1] + ds * xD[2]); // 4MUL + 3 ADD inc_adds(3); inc_mults(4); inc_read(3, float); if (fabsf(value) < contr_thr) // 1 MASK return 0; float trH = dxx + dyy; // 1 ADD float detH = dxx * dyy - dxy * dxy; // 2 MUL // 2 ADDs + 1 MUL + 1 DIV inc_adds(2); inc_mults(2); inc_div(1); if (detH > 0) { inc_div(1); inc_mults(1); } if (detH <= 0 || (trH * trH / detH) >= response) // 1 MUL + 1 DIV return 0; keypoint->layer_pos.y = temp[1]; keypoint->layer_pos.x = temp[0]; keypoint->layer_pos.scale = sigma * powf(2.0f, temp[2] * inverse_intvls); // 2 MUL + 1 POW inc_mults(2); inc_read(3, float); inc_write(3, float); float norm = (float)(1 << octave); // 1 POW // Coordinates in the normalized format (compared to the original image). keypoint->global_pos.y = temp[1] * norm; // 1 MUL keypoint->global_pos.x = temp[0] * norm; // 1 MUL keypoint->global_pos.scale = keypoint->layer_pos.scale * norm; // 1 MUL inc_mults(3); inc_read(2, float); inc_write(3, float); //22 FLOPS + 2 POWs return 1; }
27.489796
152
0.57005
[ "3d" ]
eced005b91c6791cdc0adb70680bdbc8b9e302cb
7,851
h
C
hw5/base.h
brkn45/OOP-Courses-HW
35ed393047d4446e0d7cbc35d2ac96fb30874c88
[ "MIT" ]
null
null
null
hw5/base.h
brkn45/OOP-Courses-HW
35ed393047d4446e0d7cbc35d2ac96fb30874c88
[ "MIT" ]
null
null
null
hw5/base.h
brkn45/OOP-Courses-HW
35ed393047d4446e0d7cbc35d2ac96fb30874c88
[ "MIT" ]
null
null
null
#ifndef BASE_H #define BASE_H #include <iostream> #include <cstdlib> #include <vector> #include <fstream> #include <string> #include <deque> using std::cout; using std::endl; using std::cin; using std::cerr; using std::ofstream; using std::ifstream; using std::vector; using std::deque; using std::string; namespace HexGame{ enum shape{O,X,DOT}; enum direction{RIGHT=1,LEFT=2}; class Cell{ // Board cells public: Cell():row(0),colum(0),shape(2){}; Cell(const Cell& tmp); void operator=(const Cell &temp); void set_row(int x){row = x;} int get_row() const { return row;} void set_colum(int y){colum=y;} int get_colum() const { return colum;} void set_shape(int temp){shape =temp;} // set shape int get_shape() const{ return shape;} // get shape private: int row; int colum; int shape; }; class AbstractHex{ // Base Class other for drived class public: virtual void setSize(int & tSize)=0; virtual void reset()=0; virtual void print()=0; virtual void readFromFile(char *filename)=0; virtual void writeToFile(char *filename)=0; virtual Cell play()=0; virtual void play(Cell & temp ) =0; virtual int operator()(int,int)=0; virtual int getSize() =0; virtual bool isEnd(int ,int ,int)=0; bool operator==(AbstractHex &); // no pure becuse drived class compera two obje virtual Cell lastMove(AbstractHex &); //no pure becuse drived class compera two obje virtual Cell getLastCell()=0; virtual void setLastCell(Cell & tmp)=0; virtual int numberOfMoves() =0; private: }; class HexVector : public AbstractHex { public: std::vector <std::vector <Cell>> vecCell; // board cell HexVector(int size,Cell tmp):size(size),last(tmp){}; HexVector():size(5),last(){}; //HexVector(HexVector& ); //~HexVector(); void setSize(int & tSize){size=tSize;} int getSize(){return size;} void reset(); // redraw boardd void print(); void playGame(); // start game void userUser(); // Play User vs User void userPc(); // Play user ve Pc Cell play(); // computer movement void movement(Cell & temp,int &move_x,int& move_y,int type); void play(Cell & temp); // movement int input_fun(); // input commmit bool isEnd(int move_x,int move_y,int type); // game is end return true int convert_let_to_num(const char &letter); // convert letter to num bool recuv_check_O(int x,int y ,int counter,int turn);// game end controll bool recuv_check_X(int x,int y ,int counter,int turn); // game end controll bool check_board(int tips); // game and controll bool check_board_near(); // if computer movement contoll void writeToFile(char *filename); // write file void readFromFile(char *filename); // read file int operator()(int ,int ); // return cell content const char alphabet[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'V','W', 'X', 'Y', 'Z'}; int numberOfMoves(); Cell getLastCell(){return last;} // helper function void setLastCell(Cell & tmp){last=tmp;} // set take last move private: int size; char name[20]; Cell last; // take last move content }; // same functions Hexvector class class HexArray1D : public AbstractHex { public: HexArray1D():size(5),last(){}; HexArray1D(int size,Cell tmp): size(size),last(tmp){}; HexArray1D(HexArray1D & ); void operator=(HexArray1D &); ~HexArray1D(); Cell * arrCell=nullptr; void setSize(int & tSize){size=tSize;} int getSize(){return size;} void reset(); void print(); void playGame(); void userUser(); void userPc(); int input_fun(); void movement(Cell & temp,int &move_x,int& move_y,int type); void play(Cell & temp); int convert_let_to_num(const char & letter); int operator()(int ,int ); bool check_board(int tips); bool recuv_check_O(int x,int y,int counter,int turn); bool recuv_check_X(int x,int y,int counter,int turn); Cell play(); void writeToFile(char *filename); void readFromFile(char *filename) ; bool isEnd(int move_x,int move_y,int type); int numberOfMoves(); const char alphabet[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'V','W', 'X', 'Y', 'Z'}; Cell getLastCell(){return last;} void setLastCell(Cell & tmp){last=tmp;} private: int size; char name[10]; Cell last; }; // same function HexVector Class template<typename T> class HexAdapter : public AbstractHex{ public: HexAdapter() :size(5), last() {}; HexAdapter(int size,Cell last): size(size),last(last){}; T adapCell; void setSize(int & tSize){size=tSize;} int getSize(){return size;} void reset(); void print(); void playGame(); void userUser(); void userPc(); Cell play(); void movement(Cell & temp,int &move_x,int& move_y,int type); void play(Cell & temp); int input_fun(); int convert_let_to_num(const char &letter); bool recuv_check_O(int x,int y ,int counter,int turn); bool recuv_check_X(int x,int y ,int counter,int turn); bool check_board(int tips); bool check_board_near(); void writeToFile(char *filename); void readFromFile(char *filename); int operator()(int ,int ); bool isEnd(int,int ,int ); int numberOfMoves(); const char alphabet[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'V','W', 'X', 'Y', 'Z'}; Cell getLastCell(){return last;} void setLastCell(Cell & tmp){last=tmp;} private: int size; char name[20]; Cell last; }; class OpenFile{ // control reading and writing file public: OpenFile(); OpenFile(string theMessage): message(theMessage) {} string getMessage() {return message;} private : string message; }; class LastMoveError{ // control last move public: LastMoveError(); LastMoveError(string theMessage): message(theMessage) {} string getMessage() {return message;} private : string message; }; class FalseGame{ // global function control game public: FalseGame(); FalseGame(string theMessage): message(theMessage) {} string getMessage() {return message;} private : string message; }; } #endif
36.859155
162
0.512928
[ "shape", "vector" ]
ecfaed08fd0168e336bc1ae1ca2d4c8569428a1a
43,953
c
C
srclib/apr/tables/apr_tables.c
ydnzol/apache
04ca7c32fd043b1b1496b8a45fdcd34b907d46c8
[ "Beerware" ]
null
null
null
srclib/apr/tables/apr_tables.c
ydnzol/apache
04ca7c32fd043b1b1496b8a45fdcd34b907d46c8
[ "Beerware" ]
null
null
null
srclib/apr/tables/apr_tables.c
ydnzol/apache
04ca7c32fd043b1b1496b8a45fdcd34b907d46c8
[ "Beerware" ]
2
2020-11-04T06:20:32.000Z
2020-11-06T11:02:17.000Z
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * Resource allocation code... the code here is responsible for making * sure that nothing leaks. * * rst --- 4/95 --- 6/95 */ #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_tables.h" #include "apr_strings.h" #include "apr_lib.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_STRINGS_H #include <strings.h> #endif /***************************************************************** * This file contains array and apr_table_t functions only. */ /***************************************************************** * * The 'array' functions... */ static void make_array_core(apr_array_header_t *res, apr_pool_t *p, int nelts, int elt_size, int clear) { /* * Assure sanity if someone asks for * array of zero elts. */ if (nelts < 1) { nelts = 1; } if (clear) { res->elts = apr_pcalloc(p, nelts * elt_size); } else { res->elts = apr_palloc(p, nelts * elt_size); } res->pool = p; res->elt_size = elt_size; res->nelts = 0; /* No active elements yet... */ res->nalloc = nelts; /* ...but this many allocated */ } APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a) { return ((a == NULL) || (a->nelts == 0)); } APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, int nelts, int elt_size) { apr_array_header_t *res; res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); make_array_core(res, p, nelts, elt_size, 1); return res; } APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr) { if (apr_is_empty_array(arr)) { return NULL; } return arr->elts + (arr->elt_size * (--arr->nelts)); } APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr) { if (arr->nelts == arr->nalloc) { int new_size = (arr->nalloc <= 0) ? 1 : arr->nalloc * 2; char *new_data; new_data = apr_palloc(arr->pool, arr->elt_size * new_size); memcpy(new_data, arr->elts, arr->nalloc * arr->elt_size); memset(new_data + arr->nalloc * arr->elt_size, 0, arr->elt_size * (new_size - arr->nalloc)); arr->elts = new_data; arr->nalloc = new_size; } ++arr->nelts; return arr->elts + (arr->elt_size * (arr->nelts - 1)); } static void *apr_array_push_noclear(apr_array_header_t *arr) { if (arr->nelts == arr->nalloc) { int new_size = (arr->nalloc <= 0) ? 1 : arr->nalloc * 2; char *new_data; new_data = apr_palloc(arr->pool, arr->elt_size * new_size); memcpy(new_data, arr->elts, arr->nalloc * arr->elt_size); arr->elts = new_data; arr->nalloc = new_size; } ++arr->nelts; return arr->elts + (arr->elt_size * (arr->nelts - 1)); } APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, const apr_array_header_t *src) { int elt_size = dst->elt_size; if (dst->nelts + src->nelts > dst->nalloc) { int new_size = (dst->nalloc <= 0) ? 1 : dst->nalloc * 2; char *new_data; while (dst->nelts + src->nelts > new_size) { new_size *= 2; } new_data = apr_pcalloc(dst->pool, elt_size * new_size); memcpy(new_data, dst->elts, dst->nalloc * elt_size); dst->elts = new_data; dst->nalloc = new_size; } memcpy(dst->elts + dst->nelts * elt_size, src->elts, elt_size * src->nelts); dst->nelts += src->nelts; } APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, const apr_array_header_t *arr) { apr_array_header_t *res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); make_array_core(res, p, arr->nalloc, arr->elt_size, 0); memcpy(res->elts, arr->elts, arr->elt_size * arr->nelts); res->nelts = arr->nelts; memset(res->elts + res->elt_size * res->nelts, 0, res->elt_size * (res->nalloc - res->nelts)); return res; } /* This cute function copies the array header *only*, but arranges * for the data section to be copied on the first push or arraycat. * It's useful when the elements of the array being copied are * read only, but new stuff *might* get added on the end; we have the * overhead of the full copy only where it is really needed. */ static APR_INLINE void copy_array_hdr_core(apr_array_header_t *res, const apr_array_header_t *arr) { res->elts = arr->elts; res->elt_size = arr->elt_size; res->nelts = arr->nelts; res->nalloc = arr->nelts; /* Force overflow on push */ } APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, const apr_array_header_t *arr) { apr_array_header_t *res; res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); res->pool = p; copy_array_hdr_core(res, arr); return res; } /* The above is used here to avoid consing multiple new array bodies... */ APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, const apr_array_header_t *first, const apr_array_header_t *second) { apr_array_header_t *res = apr_array_copy_hdr(p, first); apr_array_cat(res, second); return res; } /* apr_array_pstrcat generates a new string from the apr_pool_t containing * the concatenated sequence of substrings referenced as elements within * the array. The string will be empty if all substrings are empty or null, * or if there are no elements in the array. * If sep is non-NUL, it will be inserted between elements as a separator. */ APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, const apr_array_header_t *arr, const char sep) { char *cp, *res, **strpp; apr_size_t len; int i; if (arr->nelts <= 0 || arr->elts == NULL) { /* Empty table? */ return (char *) apr_pcalloc(p, 1); } /* Pass one --- find length of required string */ len = 0; for (i = 0, strpp = (char **) arr->elts; ; ++strpp) { if (strpp && *strpp != NULL) { len += strlen(*strpp); } if (++i >= arr->nelts) { break; } if (sep) { ++len; } } /* Allocate the required string */ res = (char *) apr_palloc(p, len + 1); cp = res; /* Pass two --- copy the argument strings into the result space */ for (i = 0, strpp = (char **) arr->elts; ; ++strpp) { if (strpp && *strpp != NULL) { len = strlen(*strpp); memcpy(cp, *strpp, len); cp += len; } if (++i >= arr->nelts) { break; } if (sep) { *cp++ = sep; } } *cp = '\0'; /* Return the result string */ return res; } /***************************************************************** * * The "table" functions. */ #if APR_CHARSET_EBCDIC #define CASE_MASK 0xbfbfbfbf #else #define CASE_MASK 0xdfdfdfdf #endif #define TABLE_HASH_SIZE 32 #define TABLE_INDEX_MASK 0x1f #define TABLE_HASH(key) (TABLE_INDEX_MASK & *(unsigned char *)(key)) #define TABLE_INDEX_IS_INITIALIZED(t, i) ((t)->index_initialized & (1 << (i))) #define TABLE_SET_INDEX_INITIALIZED(t, i) ((t)->index_initialized |= (1 << (i))) /* Compute the "checksum" for a key, consisting of the first * 4 bytes, normalized for case-insensitivity and packed into * an int...this checksum allows us to do a single integer * comparison as a fast check to determine whether we can * skip a strcasecmp */ #define COMPUTE_KEY_CHECKSUM(key, checksum) \ { \ const char *k = (key); \ apr_uint32_t c = (apr_uint32_t)*k; \ (checksum) = c; \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ checksum &= CASE_MASK; \ } /** The opaque string-content table type */ struct apr_table_t { /* This has to be first to promote backwards compatibility with * older modules which cast a apr_table_t * to an apr_array_header_t *... * they should use the table_elts() function for most of the * cases they do this for. */ /** The underlying array for the table */ apr_array_header_t a; #ifdef MAKE_TABLE_PROFILE /** Who created the array. */ void *creator; #endif /* An index to speed up table lookups. The way this works is: * - Take the requested key and compute its checksum * - Hash the checksum into the index: * - index_first[TABLE_HASH(checksum)] is the offset within * the table of the first entry with that key checksum * - index_last[TABLE_HASH(checksum)] is the offset within * the table of the first entry with that key checksum * - If (and only if) there is no entry in the table whose * checksum hashes to index element i, then the i'th bit * of index_initialized will be zero. (Check this before * trying to use index_first[i] or index_last[i]!) */ apr_uint32_t index_initialized; int index_first[TABLE_HASH_SIZE]; int index_last[TABLE_HASH_SIZE]; }; /* * XXX: if you tweak this you should look at is_empty_table() and table_elts() * in alloc.h */ #ifdef MAKE_TABLE_PROFILE static apr_table_entry_t *table_push(apr_table_t *t) { if (t->a.nelts == t->a.nalloc) { return NULL; } return (apr_table_entry_t *) apr_array_push_noclear(&t->a); } #else /* MAKE_TABLE_PROFILE */ #define table_push(t) ((apr_table_entry_t *) apr_array_push_noclear(&(t)->a)) #endif /* MAKE_TABLE_PROFILE */ APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t) { return (const apr_array_header_t *)t; } APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t) { return ((t == NULL) || (t->a.nelts == 0)); } APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts) { apr_table_t *t = apr_palloc(p, sizeof(apr_table_t)); make_array_core(&t->a, p, nelts, sizeof(apr_table_entry_t), 0); #ifdef MAKE_TABLE_PROFILE t->creator = __builtin_return_address(0); #endif t->index_initialized = 0; return t; } APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, const apr_table_t *t) { apr_table_t *new = apr_palloc(p, sizeof(apr_table_t)); #ifdef POOL_DEBUG /* we don't copy keys and values, so it's necessary that t->a.pool * have a life span at least as long as p */ if (!apr_pool_is_ancestor(t->a.pool, p)) { fprintf(stderr, "copy_table: t's pool is not an ancestor of p\n"); abort(); } #endif make_array_core(&new->a, p, t->a.nalloc, sizeof(apr_table_entry_t), 0); memcpy(new->a.elts, t->a.elts, t->a.nelts * sizeof(apr_table_entry_t)); new->a.nelts = t->a.nelts; memcpy(new->index_first, t->index_first, sizeof(int) * TABLE_HASH_SIZE); memcpy(new->index_last, t->index_last, sizeof(int) * TABLE_HASH_SIZE); new->index_initialized = t->index_initialized; return new; } static void table_reindex(apr_table_t *t) { int i; int hash; apr_table_entry_t *next_elt = (apr_table_entry_t *) t->a.elts; t->index_initialized = 0; for (i = 0; i < t->a.nelts; i++, next_elt++) { hash = TABLE_HASH(next_elt->key); t->index_last[hash] = i; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = i; TABLE_SET_INDEX_INITIALIZED(t, hash); } } } APR_DECLARE(void) apr_table_clear(apr_table_t *t) { t->a.nelts = 0; t->index_initialized = 0; } APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; if (key == NULL) { return NULL; } hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { return NULL; } COMPUTE_KEY_CHECKSUM(key, checksum); next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { return next_elt->val; } } return NULL; } APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *table_end; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; table_end =((apr_table_entry_t *) t->a.elts) + t->a.nelts; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so overwrite it */ int must_reindex = 0; apr_table_entry_t *dst_elt = NULL; next_elt->val = apr_pstrdup(t->a.pool, val); /* Remove any other instances of this key */ for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; if (!dst_elt) { dst_elt = next_elt; } } else if (dst_elt) { *dst_elt++ = *next_elt; must_reindex = 1; } } /* If we've removed anything, shift over the remainder * of the table (note that the previous loop didn't * run to the end of the table, just to the last match * for the index) */ if (dst_elt) { for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; } if (must_reindex) { table_reindex(t); } return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = apr_pstrdup(t->a.pool, key); next_elt->val = apr_pstrdup(t->a.pool, val); next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *table_end; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; table_end =((apr_table_entry_t *) t->a.elts) + t->a.nelts; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so overwrite it */ int must_reindex = 0; apr_table_entry_t *dst_elt = NULL; next_elt->val = (char *)val; /* Remove any other instances of this key */ for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; if (!dst_elt) { dst_elt = next_elt; } } else if (dst_elt) { *dst_elt++ = *next_elt; must_reindex = 1; } } /* If we've removed anything, shift over the remainder * of the table (note that the previous loop didn't * run to the end of the table, just to the last match * for the index) */ if (dst_elt) { for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; } if (must_reindex) { table_reindex(t); } return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = (char *)key; next_elt->val = (char *)val; next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *dst_elt; apr_uint32_t checksum; int hash; int must_reindex; hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { return; } COMPUTE_KEY_CHECKSUM(key, checksum); next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash]; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; must_reindex = 0; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found a match: remove this entry, plus any additional * matches for the same key that might follow */ apr_table_entry_t *table_end = ((apr_table_entry_t *) t->a.elts) + t->a.nelts; t->a.nelts--; dst_elt = next_elt; for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; } else { *dst_elt++ = *next_elt; } } /* Shift over the remainder of the table (note that * the previous loop didn't run to the end of the table, * just to the last match for the index) */ for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; break; } } if (must_reindex) { table_reindex(t); } } APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash]; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so merge with it */ next_elt->val = apr_pstrcat(t->a.pool, next_elt->val, ", ", val, NULL); return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = apr_pstrdup(t->a.pool, key); next_elt->val = apr_pstrdup(t->a.pool, val); next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; #ifdef POOL_DEBUG { if (!apr_pool_is_ancestor(apr_pool_find(key), t->a.pool)) { fprintf(stderr, "table_set: key not in ancestor pool of t\n"); abort(); } if (!apr_pool_is_ancestor(apr_pool_find(val), t->a.pool)) { fprintf(stderr, "table_set: key not in ancestor pool of t\n"); abort(); } } #endif COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so merge with it */ next_elt->val = apr_pstrcat(t->a.pool, next_elt->val, ", ", val, NULL); return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = (char *)key; next_elt->val = (char *)val; next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *elts; apr_uint32_t checksum; int hash; hash = TABLE_HASH(key); t->index_last[hash] = t->a.nelts; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); } COMPUTE_KEY_CHECKSUM(key, checksum); elts = (apr_table_entry_t *) table_push(t); elts->key = apr_pstrdup(t->a.pool, key); elts->val = apr_pstrdup(t->a.pool, val); elts->key_checksum = checksum; } APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *elts; apr_uint32_t checksum; int hash; #ifdef POOL_DEBUG { if (!apr_pool_is_ancestor(apr_pool_find(key), t->a.pool)) { fprintf(stderr, "table_set: key not in ancestor pool of t\n"); abort(); } if (!apr_pool_is_ancestor(apr_pool_find(val), t->a.pool)) { fprintf(stderr, "table_set: key not in ancestor pool of t\n"); abort(); } } #endif hash = TABLE_HASH(key); t->index_last[hash] = t->a.nelts; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); } COMPUTE_KEY_CHECKSUM(key, checksum); elts = (apr_table_entry_t *) table_push(t); elts->key = (char *)key; elts->val = (char *)val; elts->key_checksum = checksum; } APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, const apr_table_t *overlay, const apr_table_t *base) { apr_table_t *res; #ifdef POOL_DEBUG /* we don't copy keys and values, so it's necessary that * overlay->a.pool and base->a.pool have a life span at least * as long as p */ if (!apr_pool_is_ancestor(overlay->a.pool, p)) { fprintf(stderr, "overlay_tables: overlay's pool is not an ancestor of p\n"); abort(); } if (!apr_pool_is_ancestor(base->a.pool, p)) { fprintf(stderr, "overlay_tables: base's pool is not an ancestor of p\n"); abort(); } #endif res = apr_palloc(p, sizeof(apr_table_t)); /* behave like append_arrays */ res->a.pool = p; copy_array_hdr_core(&res->a, &overlay->a); apr_array_cat(&res->a, &base->a); table_reindex(res); return res; } /* And now for something completely abstract ... * For each key value given as a vararg: * run the function pointed to as * int comp(void *r, char *key, char *value); * on each valid key-value pair in the apr_table_t t that matches the vararg key, * or once for every valid key-value pair if the vararg list is empty, * until the function returns false (0) or we finish the table. * * Note that we restart the traversal for each vararg, which means that * duplicate varargs will result in multiple executions of the function * for each matching key. Note also that if the vararg list is empty, * only one traversal will be made and will cut short if comp returns 0. * * Note that the table_get and table_merge functions assume that each key in * the apr_table_t is unique (i.e., no multiple entries with the same key). This * function does not make that assumption, since it (unfortunately) isn't * true for some of Apache's tables. * * Note that rec is simply passed-on to the comp function, so that the * caller can pass additional info for the task. * * ADDENDUM for apr_table_vdo(): * * The caching api will allow a user to walk the header values: * * apr_status_t apr_cache_el_header_walk(apr_cache_el *el, * int (*comp)(void *, const char *, const char *), void *rec, ...); * * So it can be ..., however from there I use a callback that use a va_list: * * apr_status_t (*cache_el_header_walk)(apr_cache_el *el, * int (*comp)(void *, const char *, const char *), void *rec, va_list); * * To pass those ...'s on down to the actual module that will handle walking * their headers, in the file case this is actually just an apr_table - and * rather than reimplementing apr_table_do (which IMHO would be bad) I just * called it with the va_list. For mod_shmem_cache I don't need it since I * can't use apr_table's, but mod_file_cache should (though a good hash would * be better, but that's a different issue :). * * So to make mod_file_cache easier to maintain, it's a good thing */ APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, ...) { int rv; va_list vp; va_start(vp, t); rv = apr_table_vdo(comp, rec, t, vp); va_end(vp); return rv; } /* XXX: do the semantics of this routine make any sense? Right now, * if the caller passed in a non-empty va_list of keys to search for, * the "early termination" facility only terminates on *that* key; other * keys will continue to process. Note that this only has any effect * at all if there are multiple entries in the table with the same key, * otherwise the called function can never effectively early-terminate * this function, as the zero return value is effectively ignored. * * Note also that this behavior is at odds with the behavior seen if an * empty va_list is passed in -- in that case, a zero return value terminates * the entire apr_table_vdo (which is what I think should happen in * both cases). * * If nobody objects soon, I'm going to change the order of the nested * loops in this function so that any zero return value from the (*comp) * function will cause a full termination of apr_table_vdo. I'm hesitant * at the moment because these (funky) semantics have been around for a * very long time, and although Apache doesn't seem to use them at all, * some third-party vendor might. I can only think of one possible reason * the existing semantics would make any sense, and it's very Apache-centric, * which is this: if (*comp) is looking for matches of a particular * substring in request headers (let's say it's looking for a particular * cookie name in the Set-Cookie headers), then maybe it wants to be * able to stop searching early as soon as it finds that one and move * on to the next key. That's only an optimization of course, but changing * the behavior of this function would mean that any code that tried * to do that would stop working right. * * Sigh. --JCW, 06/28/02 */ APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, va_list vp) { char *argp; apr_table_entry_t *elts = (apr_table_entry_t *) t->a.elts; int vdorv = 1; argp = va_arg(vp, char *); do { int rv = 1, i; if (argp) { /* Scan for entries that match the next key */ int hash = TABLE_HASH(argp); if (TABLE_INDEX_IS_INITIALIZED(t, hash)) { apr_uint32_t checksum; COMPUTE_KEY_CHECKSUM(argp, checksum); for (i = t->index_first[hash]; rv && (i <= t->index_last[hash]); ++i) { if (elts[i].key && (checksum == elts[i].key_checksum) && !strcasecmp(elts[i].key, argp)) { rv = (*comp) (rec, elts[i].key, elts[i].val); } } } } else { /* Scan the entire table */ for (i = 0; rv && (i < t->a.nelts); ++i) { if (elts[i].key) { rv = (*comp) (rec, elts[i].key, elts[i].val); } } } if (rv == 0) { vdorv = 0; } } while (argp && ((argp = va_arg(vp, char *)) != NULL)); return vdorv; } /* During apr_table_overlap(), we build an overlap key for * each element in the two tables. */ #define RED 0 #define BLACK 1 typedef struct overlap_key { /* The table element */ apr_table_entry_t *elt; /* 0 if from table 'a', 1 if from table 'b' */ int level; /* Whether to omit this element when building the result table */ int skip; /* overlap_keys can be assembled into a red-black tree */ int black; struct overlap_key *tree_parent; struct overlap_key *tree_left; struct overlap_key *tree_right; int color; /* List of multiple values for this key */ struct overlap_key *merge_next; struct overlap_key *merge_last; } overlap_key; /* Rotate a subtree of a red-black tree */ static void rotate_counterclockwise(overlap_key **root, overlap_key *rotate_node) { overlap_key *child = rotate_node->tree_right; rotate_node->tree_right = child->tree_left; if (rotate_node->tree_right) { rotate_node->tree_right->tree_parent = rotate_node; } child->tree_parent = rotate_node->tree_parent; if (child->tree_parent == NULL) { *root = child; } else { if (rotate_node == rotate_node->tree_parent->tree_left) { rotate_node->tree_parent->tree_left = child; } else { rotate_node->tree_parent->tree_right = child; } } child->tree_left = rotate_node; rotate_node->tree_parent = child; } static void rotate_clockwise(overlap_key **root, overlap_key *rotate_node) { overlap_key *child = rotate_node->tree_left; rotate_node->tree_left = child->tree_right; if (rotate_node->tree_left) { rotate_node->tree_left->tree_parent = rotate_node; } child->tree_parent = rotate_node->tree_parent; if (child->tree_parent == NULL) { *root = child; } else { if (rotate_node == rotate_node->tree_parent->tree_left) { rotate_node->tree_parent->tree_left = child; } else { rotate_node->tree_parent->tree_right = child; } } child->tree_right = rotate_node; rotate_node->tree_parent = child; } static void overlap_hash(overlap_key *elt, overlap_key **hash_table, int nhash, unsigned flags) { /* Each bucket in the hash table holds a red-black tree * containing the overlap_keys that hash into that bucket */ overlap_key **child = &(hash_table[elt->elt->key_checksum & (nhash - 1)]); overlap_key **root = child; overlap_key *parent = NULL; overlap_key *next; /* Look for the element in the tree */ while ((next = *child) != NULL) { int direction = strcasecmp(elt->elt->key, next->elt->key); if (direction < 0) { parent = next; child = &(next->tree_left); } else if (direction > 0) { parent = next; child = &(next->tree_right); } else { /* This is the key we're looking for */ if (flags == APR_OVERLAP_TABLES_MERGE) { /* Just link this node at the end of the list * of values for the key. It doesn't need to * be linked into the tree, because the node at * the head of this key's value list is in the * tree already. */ elt->skip = 1; elt->merge_next = NULL; if (next->merge_last) { next->merge_last->merge_next = elt; } else { next->merge_next = elt; } next->merge_last = elt; } else { /* In the "set" case, don't bother storing * this value in the tree if it's already * there, except if the previous value was * from table 'a' (level==0) and this value * is from table 'b' (level==1) */ if (elt->level > next->level) { elt->tree_left = next->tree_left; if (next->tree_left) { next->tree_left->tree_parent = elt; } elt->tree_right = next->tree_right; if (next->tree_right) { next->tree_right->tree_parent = elt; } elt->tree_parent = next->tree_parent; elt->color = next->color; (*child) = elt; elt->merge_next = NULL; elt->merge_last = NULL; elt->skip = 0; next->skip = 1; } else { elt->skip = 1; } } return; } } /* The element wasn't in the tree, so add it */ elt->tree_left = NULL; elt->tree_right = NULL; elt->tree_parent = parent; (*child) = elt; elt->merge_next = NULL; elt->merge_last = NULL; elt->skip = 0; elt->color = RED; /* Shuffle the nodes to maintain the red-black tree's balanced * shape property. (This is what guarantees O(n*log(n)) worst-case * performance for apr_table_overlap().) */ next = elt; while ((next->tree_parent) && (next->tree_parent->color == RED)) { /* Note: Root is always black, and red and black nodes * alternate on any path down the tree. So if we're inside * this block, the grandparent node is non-NULL. */ overlap_key *grandparent = next->tree_parent->tree_parent; if (next->tree_parent == grandparent->tree_left) { overlap_key *parent_sibling = grandparent->tree_right; if (parent_sibling && (parent_sibling->color == RED)) { next->tree_parent->color = BLACK; parent_sibling->color = BLACK; grandparent->color = RED; next = grandparent; } else { if (next == next->tree_parent->tree_right) { next = next->tree_parent; rotate_counterclockwise(root, next); } next->tree_parent->color = BLACK; next->tree_parent->tree_parent->color = RED; rotate_clockwise(root, next->tree_parent->tree_parent); } } else { overlap_key *parent_sibling = grandparent->tree_left; if (parent_sibling && (parent_sibling->color == RED)) { next->tree_parent->color = BLACK; parent_sibling->color = BLACK; grandparent->color = RED; next = grandparent; } else { if (next == next->tree_parent->tree_left) { next = next->tree_parent; rotate_clockwise(root, next); } next->tree_parent->color = BLACK; next->tree_parent->tree_parent->color = RED; rotate_counterclockwise(root, next->tree_parent->tree_parent); } } } (*root)->color = BLACK; } /* Must be a power of 2 */ #define DEFAULT_HASH_SIZE 16 APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, unsigned flags) { int max_keys; int nkeys; overlap_key *cat_keys; /* concatenation of the keys of a and b */ overlap_key **hash_table; int nhash; int i; apr_table_entry_t *elts; apr_table_entry_t *dst_elt; max_keys = a->a.nelts + b->a.nelts; if (!max_keys) { /* The following logic won't do anything harmful if we keep * going in this situation, but * * 1) certain memory debuggers don't like an alloc size of 0 * so we'd like to avoid that... * 2) this isn't all that rare a call anyway, so it is useful * to skip the storage allocation and other checks in the * following logic */ return; } cat_keys = apr_palloc(b->a.pool, sizeof(overlap_key) * max_keys); nhash = DEFAULT_HASH_SIZE; while (nhash < max_keys) { nhash <<= 1; } hash_table = (overlap_key **)apr_pcalloc(b->a.pool, sizeof(overlap_key *) * nhash); /* The cat_keys array contains an element for each entry in a, * followed by one for each in b. While populating this array, * we also use it as: * 1) a hash table, to detect matching keys, and * 2) a linked list of multiple values for a given key (in the * APR_OVERLAP_TABLES_MERGE case) */ /* First, the elements of a */ nkeys = 0; elts = (apr_table_entry_t *)a->a.elts; for (i = 0; i < a->a.nelts; i++, nkeys++) { cat_keys[nkeys].elt = &(elts[i]); cat_keys[nkeys].level = 0; overlap_hash(&(cat_keys[nkeys]), hash_table, nhash, flags); } /* Then the elements of b */ elts = (apr_table_entry_t *)b->a.elts; for (i = 0; i < b->a.nelts; i++, nkeys++) { cat_keys[nkeys].elt = &(elts[i]); cat_keys[nkeys].level = 1; overlap_hash(&(cat_keys[nkeys]), hash_table, nhash, flags); } /* Copy concatenated list of elements into table a to * form the new table contents, but: * 1) omit the ones marked "skip," and * 2) merge values for the same key if needed */ make_array_core(&a->a, b->a.pool, max_keys, sizeof(apr_table_entry_t), 0); nkeys = 0; dst_elt = (apr_table_entry_t *)a->a.elts; for (i = 0; i < max_keys; i++) { if (cat_keys[i].skip) { continue; } if (cat_keys[i].merge_next) { char *new_val; char *val_next; overlap_key *next = cat_keys[i].merge_next; int len = (cat_keys[i].elt->val ? strlen(cat_keys[i].elt->val) : 0); do { len += 2; if (next->elt->val) { len += strlen(next->elt->val); } next = next->merge_next; } while (next); len++; new_val = (char *)apr_palloc(b->a.pool, len); val_next = new_val; if (cat_keys[i].elt->val) { strcpy(val_next, cat_keys[i].elt->val); val_next += strlen(cat_keys[i].elt->val); } next = cat_keys[i].merge_next; do { *val_next++ = ','; *val_next++ = ' '; if (next->elt->val) { strcpy(val_next, next->elt->val); val_next += strlen(next->elt->val); } next = next->merge_next; } while (next); *val_next = 0; dst_elt->key = cat_keys[i].elt->key; dst_elt->val = new_val; dst_elt->key_checksum = cat_keys[i].elt->key_checksum; dst_elt++; } else { dst_elt->key = cat_keys[i].elt->key; dst_elt->val = cat_keys[i].elt->val; dst_elt->key_checksum = cat_keys[i].elt->key_checksum; dst_elt++; } } a->a.nelts = dst_elt - (apr_table_entry_t *)a->a.elts; table_reindex(a); }
33.047368
83
0.578618
[ "shape" ]
ecfbcb23c1d77f5dc198241bda99a1fddd5d57ea
6,694
h
C
CaptureTheFlag/Public/CaptureTheFlagCharacter.h
DennisSSDev/NetworkedCaptureTheFlagBase
ea4d5cfcac500d109c510af20d426f42a2649111
[ "MIT" ]
1
2019-04-18T12:13:26.000Z
2019-04-18T12:13:26.000Z
CaptureTheFlag/Public/CaptureTheFlagCharacter.h
DennisSSDev/NetworkedCaptureTheFlagBase
ea4d5cfcac500d109c510af20d426f42a2649111
[ "MIT" ]
null
null
null
CaptureTheFlag/Public/CaptureTheFlagCharacter.h
DennisSSDev/NetworkedCaptureTheFlagBase
ea4d5cfcac500d109c510af20d426f42a2649111
[ "MIT" ]
null
null
null
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "CaptureTheFlagController.h" #include "TimerManager.h" #include "CaptureTheFlagCharacter.generated.h" class UCharacterMovementComponent; class UHealthComponent; UCLASS(config=Game) class ACaptureTheFlagCharacter : public ACharacter { GENERATED_BODY() /** Pawn mesh: 1st person view (arms; seen only by self) */ UPROPERTY(VisibleDefaultsOnly, Category=Mesh) class USkeletalMeshComponent* Mesh1P; /** Gun mesh: 1st person view (seen only by self) */ UPROPERTY(VisibleDefaultsOnly, Category = Mesh) class USkeletalMeshComponent* FP_Gun; /** Location on gun mesh where projectiles should spawn. */ UPROPERTY(VisibleDefaultsOnly, Category = Mesh) class USceneComponent* FP_MuzzleLocation; /** First person camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FirstPersonCameraComponent; UPROPERTY() class UCharacterMovementComponent* CharacterMovementComponent; UPROPERTY(VisibleAnywhere) class UHealthComponent* HealthComponent; /* Temporary pointer to a nearby flag */ UPROPERTY() class AFlag* NearbyFlag; /* A flag that the actor currently has picked up */ UPROPERTY() class AFlag* StoredFlag; /* A pointer to a vehicle the actor is in right now */ UPROPERTY() class AHoverVehicle* StoredVehicle; public: ACaptureTheFlagCharacter(); /** Fires a projectile. */ UFUNCTION() void OnFire(); /** Handles moving forward/backward */ UFUNCTION() void MoveForward(float Val); /** Handles stafing movement, left and right */ UFUNCTION() void MoveRight(float Val); /** Handle jump animation */ void Jump() override; /** Reverse the jump state */ UFUNCTION() void StopJump(); /** Used mainly for flag interaction or vehicle hop in */ UFUNCTION() void Interact(); /* Stop interacting with the flag*/ UFUNCTION() void StopInteract(); /* Manually drop a flag with a timer */ UFUNCTION() void DropFlag(); /* Instant drop flag. Used internally */ UFUNCTION() void InstantDropFlag(); /* Cancel Flag Drop */ UFUNCTION() void StopDropFlag(); protected: virtual void BeginPlay() override; virtual void Destroyed() override; private: /* Play a jump animation on all machines */ UFUNCTION(NetMulticast, Reliable) void Server_JumpMontage(const bool bStop); UFUNCTION(Server, Reliable, WithValidation) void RPC_JumpMontage(const bool bStop); /* Handle hit target with weapon */ UFUNCTION(Server, Reliable, WithValidation) void RPC_RequestHit(const APawn* Target); /* Call when you're near a flag to initate a flag pick up process (timed) */ UFUNCTION(NetMulticast, Reliable) void Server_PickUpFlag(AFlag* Target); UFUNCTION(Server, Reliable, WithValidation) void RPC_RequestPickUpFlag(AFlag* Target); /* Call to initiate a drop flag progress (timed) */ UFUNCTION(NetMulticast, Reliable) void Server_DropFlag(); UFUNCTION(Server, Reliable, WithValidation) void RPC_RequestDropFlag(); /* Cancels the flag capture process immediately */ UFUNCTION(NetMulticast, Reliable) void Server_StopFlagCapture(); /* Return a dropped flag to a random Base immediately */ UFUNCTION(Server, Reliable, WithValidation) void RPC_ReturnFlagToBase(AFlag* Target); /* Draw the bullet path when shooting your weapon */ UFUNCTION(Server, UnReliable, WithValidation) void RPC_DrawShot(FVector Start, FVector End); UFUNCTION(NetMulticast, UnReliable) void Server_DrawShot(FVector Start, FVector End); UFUNCTION() void OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); UFUNCTION() void OnEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex); /* Local function that will initiate a Server flag PICKUP request */ UFUNCTION() void AttemptPickUp(); /* Local function that will initiate a Server flag DROP request */ UFUNCTION() void AttemptDropFlag(); /* Local function that will attempt to bring the flag back to a base via server request */ UFUNCTION() void AttemptRetrieveFlag(); /* Locally invalidate the actor's ownership of the flag. Mainly used for UMG updates */ UFUNCTION() void InvalidateFlagOwnership() { bHasFlag = false; } public: /** Sound to play each time we fire */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay) class USoundBase* FireSound; /** AnimMontage to play each time we fire */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) class UAnimMontage* FireAnimation; /** AnimMontage to play each time we fire */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) class UAnimMontage* JumpAnimation; /** Gun muzzle's offset from the characters location */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) FVector GunOffset; /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) float BaseLookUpRate; private: UPROPERTY() FTimerHandle PickUpTimer; UPROPERTY() FTimerHandle DropTimer; UPROPERTY() float DropTime = 1.f; UPROPERTY() float InteractTime = 0.f; UPROPERTY() uint8 SpawnPointCount = 3; UPROPERTY() bool bInitPickUp = false; UPROPERTY() bool bInitDrop = false; UPROPERTY() bool bHasFlag = false; public: /** Getters */ FORCEINLINE UFUNCTION() class USkeletalMeshComponent* GetMesh1P() const { return Mesh1P; } FORCEINLINE UFUNCTION() class UCameraComponent* GetFirstPersonCameraComponent() const { return FirstPersonCameraComponent; } FORCEINLINE UFUNCTION() class AFlag* GetStoredFlag() const { return StoredFlag; } FORCEINLINE UFUNCTION() class AHoverVehicle* GetStoredVehicle() const { return StoredVehicle; } /* CAN ACCESS IN BP */ UFUNCTION(BlueprintPure, Category = "Capture the Flag Data") const FORCEINLINE bool& IsPickUpStarted() const { return bInitPickUp; } UFUNCTION(BlueprintPure, Category = "Capture the Flag Data") const FORCEINLINE bool& IsDropStarted() const { return bInitDrop; } UFUNCTION(BlueprintPure, Category = "Capture the Flag Data") const FORCEINLINE float& GetInteractTime() const { return InteractTime; } UFUNCTION(BlueprintPure, Category = "Capture the Flag Data") const FORCEINLINE bool& IsOwningFlag() const { return bHasFlag; } };
28.485106
180
0.759635
[ "mesh" ]
ecfd286c143e9459374b20809ebac0d7c260df83
851
h
C
api/ObjectFranchisereferalincomeAPI.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
api/ObjectFranchisereferalincomeAPI.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
api/ObjectFranchisereferalincomeAPI.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "../include/apiClient.h" #include "../include/list.h" #include "../external/cJSON.h" #include "../include/keyValuePair.h" #include "../include/binary.h" #include "../model/franchisereferalincome_create_object_v1_request.h" #include "../model/franchisereferalincome_create_object_v1_response.h" // Create a new Franchisereferalincome // // The endpoint allows to create one or many elements at once. The array can contain simple (Just the object) or compound (The object and its child) objects. Creating compound elements allows to reduce the multiple requests to create all child objects. // franchisereferalincome_create_object_v1_response_t* ObjectFranchisereferalincomeAPI_franchisereferalincomeCreateObjectV1(apiClient_t *apiClient, list_t * franchisereferalincome_create_object_v1_request );
42.55
254
0.804935
[ "object", "model" ]
a601ad9b11965d52aed1d94165fbb5ac3d5fc627
5,742
h
C
tensorflow/stream_executor/cuda/cuda_driver.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/stream_executor/cuda/cuda_driver.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/stream_executor/cuda/cuda_driver.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2015 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. ==============================================================================*/ // CUDA userspace driver library wrapper functionality. #ifndef TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ #define TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ #include "absl/container/node_hash_map.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "tensorflow/stream_executor/gpu/gpu_driver.h" namespace stream_executor { namespace gpu { // Formats CUresult to output prettified values into a log stream. static std::string ToString(CUresult result) { const char* error_name; if (cuGetErrorName(result, &error_name)) { return absl::StrCat("UNKNOWN ERROR (", static_cast<int>(result), ")"); } const char* error_string; if (cuGetErrorString(result, &error_string)) { return error_name; } return absl::StrCat(error_name, ": ", error_string); } // CUDAContext wraps a cuda CUcontext handle, and includes a unique id. The // unique id is positive, and ids are not repeated within the process. class GpuContext { public: GpuContext(CUcontext context, int64_t id) : context_(context), id_(id) {} CUcontext context() const { return context_; } int64_t id() const { return id_; } // Disallow copying and moving. GpuContext(GpuContext&&) = delete; GpuContext(const GpuContext&) = delete; GpuContext& operator=(GpuContext&&) = delete; GpuContext& operator=(const GpuContext&) = delete; private: CUcontext const context_; const int64_t id_; }; // Manages the singleton map of contexts that we've created, mapping // from the CUcontext to the GpuContext* that we pass around internally. // This also manages assignment of unique ids to GpuContexts, to allow // for fast comparison of a context against the current context. // // CUDA-runtime-created contexts are avoided, if triple angle // brace launches are required, by using the scoped activations in // gpu/gpu_activation.h. class CreatedContexts { public: // Returns whether context is a member of the live set. static bool Has(CUcontext context) { absl::ReaderMutexLock lock(&mu_); return Live()->find(context) != Live()->end(); } // Adds context to the live set, or returns it if it's already present. static GpuContext* Add(CUcontext context, int device_ordinal) { CHECK(context != nullptr); absl::MutexLock lock(&mu_); auto insert_result = Live()->insert(std::make_pair(context, nullptr)); auto it = insert_result.first; if (insert_result.second) { // context was not present in the map. Add it. it->second = absl::make_unique<GpuContext>(context, next_id_++); (*LiveOrdinal())[device_ordinal].push_back(context); } return it->second.get(); } // Removes context from the live set. static void Remove(CUcontext context) { CHECK(context != nullptr); absl::MutexLock lock(&mu_); auto it = Live()->find(context); CHECK(it != Live()->end()) << context; Live()->erase(it); for (auto p : (*LiveOrdinal())) { auto it2 = std::find(p.second.begin(), p.second.end(), context); if (it2 != p.second.end()) { p.second.erase(it2, it2++); if (p.second.empty()) { LiveOrdinal()->erase(p.first); } break; } } } // Return the context associated to that ptr. static CUcontext GetAnyContext(void* ptr) { absl::ReaderMutexLock lock(&mu_); int device_ordinal; CUresult result = cuPointerGetAttribute(static_cast<void*>(&device_ordinal), CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, reinterpret_cast<CUdeviceptr>(ptr)); if (result != CUDA_SUCCESS) { LOG(FATAL) << "Not able to get the device_ordinal for ptr: " << ptr << ". Error: " << ToString(result); } CHECK_EQ(LiveOrdinal()->count(device_ordinal), 1); CHECK(!LiveOrdinal()->at(device_ordinal).empty()) << "Need at least one context."; return LiveOrdinal()->at(device_ordinal)[0]; } private: // Returns the live map singleton. static absl::node_hash_map<CUcontext, std::unique_ptr<GpuContext>>* Live() { static auto singleton = new absl::node_hash_map<CUcontext, std::unique_ptr<GpuContext>>; return singleton; } static absl::node_hash_map<int, std::vector<CUcontext>>* LiveOrdinal() { static auto singleton = new absl::node_hash_map<int, std::vector<CUcontext>>; return singleton; } // Lock that guards access-to/mutation-of the live set. static absl::Mutex mu_; static int64_t next_id_; }; } // namespace gpu namespace cuda { using MemorySpace = gpu::MemorySpace; using CUDADriver = gpu::GpuDriver; using ScopedActivateContext = gpu::ScopedActivateContext; using CudaContext = gpu::GpuContext; // Returns the current context set in CUDA. This is done by calling the cuda // driver (e.g., this value is not our cached view of the current context). CUcontext CurrentContextOrDie(); } // namespace cuda } // namespace stream_executor #endif // TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_
34.590361
80
0.68861
[ "vector" ]
a6036ef73921c836413a8a895a1987bf26c59224
4,200
h
C
libarea-read-only/dxf.h
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
17
2018-07-30T17:38:02.000Z
2022-02-03T10:35:38.000Z
libarea-read-only/dxf.h
play113/swer
78764c67885dfacb1fa24e494a20681265f5254c
[ "MIT" ]
2
2020-06-11T10:29:06.000Z
2020-06-11T15:42:00.000Z
Geom/dxf.h
danheeks/PyCAD
711543aaa88c88a82d909f329b6ee36a9b96ae79
[ "BSD-3-Clause" ]
5
2017-02-09T23:27:16.000Z
2020-03-17T14:57:03.000Z
// dxf.h // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #pragma once #include <algorithm> #include <list> #include <vector> #include <map> #include <set> #include <fstream> #include <sstream> #include <iostream> #include <stdio.h> #include <string.h> #include <math.h> //Following is required to be defined on Ubuntu with OCC 6.3.1 #ifndef HAVE_IOSTREAM #define HAVE_IOSTREAM #endif typedef int Aci_t; // AutoCAD color index typedef enum { eUnspecified = 0, // Unspecified (No units) eInches, eFeet, eMiles, eMillimeters, eCentimeters, eMeters, eKilometers, eMicroinches, eMils, eYards, eAngstroms, eNanometers, eMicrons, eDecimeters, eDekameters, eHectometers, eGigameters, eAstronomicalUnits, eLightYears, eParsecs } eDxfUnits_t; struct SplineData { double norm[3]; int degree; int knots; int control_points; int fit_points; int flag; std::list<double> starttanx; std::list<double> starttany; std::list<double> starttanz; std::list<double> endtanx; std::list<double> endtany; std::list<double> endtanz; std::list<double> knot; std::list<double> weight; std::list<double> controlx; std::list<double> controly; std::list<double> controlz; std::list<double> fitx; std::list<double> fity; std::list<double> fitz; }; class CDxfWrite{ private: std::ofstream* m_ofs; bool m_fail; public: CDxfWrite(const char* filepath); ~CDxfWrite(); bool Failed(){return m_fail;} void WriteLine(const double* s, const double* e, const char* layer_name ); void WritePoint(const double*, const char*); void WriteArc(const double* s, const double* e, const double* c, bool dir, const char* layer_name ); void WriteEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir, const char* layer_name ); void WriteCircle(const double* c, double radius, const char* layer_name ); }; // derive a class from this and implement it's virtual functions class CDxfRead{ private: std::ifstream* m_ifs; bool m_fail; char m_str[1024]; char m_unused_line[1024]; eDxfUnits_t m_eUnits; char m_layer_name[1024]; char m_section_name[1024]; char m_block_name[1024]; bool m_ignore_errors; typedef std::map< std::string,Aci_t > LayerAciMap_t; LayerAciMap_t m_layer_aci; // layer names -> layer color aci map bool ReadUnits(); bool ReadLayer(); bool ReadLine(); bool ReadText(); bool ReadArc(); bool ReadCircle(); bool ReadEllipse(); bool ReadPoint(); bool ReadSpline(); bool ReadLwPolyLine(); bool ReadPolyLine(); bool ReadVertex(double *pVertex, bool *bulge_found, double *bulge); void OnReadArc(double start_angle, double end_angle, double radius, const double* c); void OnReadCircle(const double* c, double radius); void OnReadEllipse(const double* c, const double* m, double ratio, double start_angle, double end_angle); void get_line(); void put_line(const char *value); void DerefACI(); protected: Aci_t m_aci; // manifest color name or 256 for layer color public: CDxfRead(const char* filepath); // this opens the file ~CDxfRead(); // this closes the file bool Failed(){return m_fail;} void DoRead(const bool ignore_errors = false); // this reads the file and calls the following functions double mm( const double & value ) const; bool IgnoreErrors() const { return(m_ignore_errors); } virtual void OnReadLine(const double* s, const double* e){} virtual void OnReadPoint(const double* s){} virtual void OnReadText(const double* point, const double height, const char* text){} virtual void OnReadArc(const double* s, const double* e, const double* c, bool dir){} virtual void OnReadCircle(const double* s, const double* c, bool dir){} virtual void OnReadEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir){} virtual void OnReadSpline(struct SplineData& sd){} virtual void AddGraphics() const { } std::string LayerName() const; };
26.751592
172
0.71119
[ "vector" ]
a60982deb2f2d87d9d332d3b8f1f31f645f129a2
7,677
h
C
sdk/inc/maths3D.h
VirtualPythonLLC/VPGP-SGDK
826d49e31a17f35599c7c13a29abe1a5c7a8e2a2
[ "MIT" ]
null
null
null
sdk/inc/maths3D.h
VirtualPythonLLC/VPGP-SGDK
826d49e31a17f35599c7c13a29abe1a5c7a8e2a2
[ "MIT" ]
null
null
null
sdk/inc/maths3D.h
VirtualPythonLLC/VPGP-SGDK
826d49e31a17f35599c7c13a29abe1a5c7a8e2a2
[ "MIT" ]
null
null
null
/** * \file maths3D.h * \brief 3D math engine. * \author Stephane Dallongeville * \date 08/2011 * * This unit provides 3D transformation methods :<br> * - translation X, Y, Z<br> * - rotation X, Y, Z<br> * - one directionnal light<br> * - 2D projection<br> *<br> * Can transform (including 2D projection) about ~10000 vertices / seconde. */ #ifndef _MATHS3D_H_ #define _MATHS3D_H_ /** * \brief * Structure hosting settings / context for the 3D transform engine. */ typedef struct { Vect2D_u16 viewport; fix16 camDist; Vect3D_f16 light; u16 lightEnabled; } Context3D; /** * \brief * 3D translation informations object - f16 (fix16) type. */ typedef Vect3D_f16 Translation3D; /** * \brief * 3D rotation informations object - f16 (fix16) type. */ typedef Vect3D_f16 Rotation3D; /** * \brief * 3D transformation object - f16 (fix16) type.<br> * This object define the global 3D transformation informations and associated cached data.<br> * If rotation information is modified the rebuildMat flag should be set to 1.<br> * Rotation and translation objects are reference so don't forget to set them. */ typedef struct { u16 rebuildMat; Translation3D *translation; Rotation3D *rotation; Mat3D_f16 mat; Mat3D_f16 matInv; Vect3D_f16 cameraInv; Vect3D_f16 lightInv; } Transformation3D; /** * \brief * Reset math 3D engine (reset matrices and transformation parameters mainly). */ void M3D_reset(); /** * \brief * Enable or disable light transformation calculation. */ void M3D_setLightEnabled(u16 enabled); /** * \brief * Get light transformation calculation enabled flag. */ u16 M3D_getLightEnabled(); /** * \brief * Set viewport dimension. * * \param w * Viewport width (use BMP_WIDTH if you use 3D with software bitmap engine) * \param h * Viewport height (use BMP_HEIGHT if you use 3D with software bitmap engine) */ void M3D_setViewport(u16 w, u16 h); /** * \brief * Set camera scene distance. * * \param value * Distance between the camera and the scene. */ void M3D_setCamDistance(fix16 value); /** * \brief * Set light direction vector. */ void M3D_setLightXYZ(fix16 x, fix16 y, fix16 z); /** * \brief * Set light direction vector. */ void M3D_setLight(Vect3D_f16 *value); /** * \brief * Reset the specified Transformation3D object. */ void M3D_resetTransform(Transformation3D *t); /** * \brief * Set translation and rotation objects to the specified transformation object. */ void M3D_setTransform(Transformation3D *tr, Translation3D *t, Rotation3D *r); /** * \brief * Set translation parameters to the specified transformation object. */ void M3D_setTranslation(Transformation3D *t, fix16 x, fix16 y, fix16 z); /** * \brief * Set rotation parameters to the specified #Transformation3D object.<br> * Be careful, x, y, z angle values are not given in radiant:<br> * [-8..+8] range correspond to radian [-PI..+PI] range. */ void M3D_setRotation(Transformation3D *t, fix16 x, fix16 y, fix16 z); /** * \brief * Combine the specified right and left #Transformation3D objects and store result in <code>result</code>. * result cannot be the same transformation object as left or right. * * \param left * Left #Transformation3D object. * \param right * Right #Transformation3D object. * \param result * Result #Transformation3D object. */ void M3D_combineTransform(Transformation3D *left, Transformation3D *right, Transformation3D *result); /** * \brief * Combine the specified left #Translation3D and right #Transformation3D and store result in <code>result</code>.<br> * right and result transformation object can be the same. * * \param left * Left #Transformation3D object. * \param right * Right #Transformation3D object. * \param result * Result #Transformation3D object. */ void M3D_combineTranslationLeft(Translation3D *left, Transformation3D *right, Transformation3D *result); /** * \brief * Combine the specified left #Transformation3D with right #Translation3D and store result in <code>result</code>.<br> * left and result transformation object can be the same. * * \param left * Left #Transformation3D object. * \param right * Right #Translation3D object. * \param result * Result #Transformation3D object. */ void M3D_combineTranslationRight(Transformation3D *left, Translation3D *right, Transformation3D *result); /** * \brief * Build the transformation matrix of the specified #Transformation3D object.<br> * This also rebuild cached informations as inverse transformation matrix, inverse camera view... * * \param t * #Transformation3D object. */ void M3D_buildMat3D(Transformation3D *t); /** * \brief * Build the transformation matrix of the specified transformation object. * Only rebuild the transformation matrix (faster), cached infos as inverse matrix are not rebuild. * * \param t * Transformation object. */ void M3D_buildMat3DOnly(Transformation3D *t); /** * \brief * Only rebuild the cached infos as inverse matrix, inverse camera view... * * \param t * Transformation object. */ void M3D_buildMat3DExtras(Transformation3D *t); /** * \brief * Process 3D translation only to specified 3D vertices buffer. * * \param t * Transformation object containing translation parameter. * \param vertices * 3D vertices buffer to translate. * \param numv * Number of vertices to translate. */ void M3D_translate(Transformation3D *t, Vect3D_f16 *vertices, u16 numv); /** * \brief * Process 3D rotation only to specified 3D vertices buffer. * * \param t * Transformation object containing rotation parameter. * \param src * Source 3D vertices buffer. * \param dest * Destination 3D vertices buffer. * \param numv * Number of vertices to rotate. */ void M3D_rotate(Transformation3D *t, const Vect3D_f16 *src, Vect3D_f16 *dest, u16 numv); /** * \brief * Process 3D inverse rotation only to specified 3D vertex. * * \param t * Transformation object containing rotation parameter. * \param src * Source 3D vertex. * \param dest * Destination 3D vertex. */ void M3D_rotateInv(Transformation3D *t, const Vect3D_f16 *src, Vect3D_f16 *dest); /** * \brief * Process 3D transform (rotation and translation) to specified 3D vertices buffer. * * \param t * Transformation object containing rotation and translation parameters. * \param src * Source 3D vertices buffer. * \param dest * Destination 3D vertices buffer. * \param numv * Number of vertices to transform. */ void M3D_transform(Transformation3D *t, const Vect3D_f16 *src, Vect3D_f16 *dest, u16 numv); /** * \brief * Process 2D projection to specified 3D vertices buffer (fix16 version). * * \param src * Source 3D vertices buffer. * \param dest * Destination 2D vertices buffer - fix16 format * \param numv * Number of vertices to project. */ void M3D_project_f16(const Vect3D_f16 *src, Vect2D_f16 *dest, u16 numv); /** * \brief * Process 2D projection to specified 3D vertices buffer (s16 version). * * \param src * Source 3D vertices buffer. * \param dest * Destination 2D vertices buffer - s16 format * \param numv * Number of vertices to project. */ void M3D_project_s16(const Vect3D_f16 *src, Vect2D_s16 *dest, u16 numv); #endif // _MATHS3D_H_
27.417857
123
0.68321
[ "object", "vector", "transform", "3d" ]
a6099ad749da2be5542dba9d1f92971fe854e0f3
5,264
h
C
chrome/browser/ui/views/location_bar/page_action_image_view.h
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/ui/views/location_bar/page_action_image_view.h
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/ui/views/location_bar/page_action_image_view.h
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_ #include <map> #include <string> #include "base/memory/scoped_ptr.h" #include "chrome/browser/extensions/image_loading_tracker.h" #include "chrome/browser/ui/views/extensions/extension_popup.h" #include "chrome/common/extensions/extension_action.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/image_view.h" #include "ui/views/widget/widget_observer.h" class Browser; class LocationBarView; namespace content { class WebContents; } namespace views { class MenuRunner; } // PageActionImageView is used by the LocationBarView to display the icon for a // given PageAction and notify the extension when the icon is clicked. class PageActionImageView : public views::ImageView, public ImageLoadingTracker::Observer, public views::WidgetObserver, public views::ContextMenuController, public content::NotificationObserver, public ExtensionAction::IconAnimation::Observer { public: PageActionImageView(LocationBarView* owner, ExtensionAction* page_action, Browser* browser); virtual ~PageActionImageView(); ExtensionAction* page_action() { return page_action_; } int current_tab_id() { return current_tab_id_; } void set_preview_enabled(bool preview_enabled) { preview_enabled_ = preview_enabled; } // Overridden from views::View: virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE; virtual bool OnMousePressed(const views::MouseEvent& event) OVERRIDE; virtual void OnMouseReleased(const views::MouseEvent& event) OVERRIDE; virtual bool OnKeyPressed(const views::KeyEvent& event) OVERRIDE; // Overridden from ImageLoadingTracker: virtual void OnImageLoaded(const gfx::Image& image, const std::string& extension_id, int index) OVERRIDE; // Overridden from views::WidgetObserver: virtual void OnWidgetClosing(views::Widget* widget) OVERRIDE; // Overridden from views::ContextMenuController. virtual void ShowContextMenuForView(View* source, const gfx::Point& point) OVERRIDE; // Overridden from content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Overridden from ui::AcceleratorTarget: virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) OVERRIDE; virtual bool CanHandleAccelerators() const OVERRIDE; // Called to notify the PageAction that it should determine whether to be // visible or hidden. |contents| is the WebContents that is active, |url| is // the current page URL. void UpdateVisibility(content::WebContents* contents, const GURL& url); // Either notify listeners or show a popup depending on the page action. void ExecuteAction(int button); private: // Overridden from ExtensionAction::IconAnimation::Observer: virtual void OnIconChanged( const ExtensionAction::IconAnimation& animation) OVERRIDE; // Shows the popup, with the given URL. void ShowPopupWithURL(const GURL& popup_url); // Hides the active popup, if there is one. void HidePopup(); // The location bar view that owns us. LocationBarView* owner_; // The PageAction that this view represents. The PageAction is not owned by // us, it resides in the extension of this particular profile. ExtensionAction* page_action_; // The corresponding browser. Browser* browser_; // The object that is waiting for the image loading to complete // asynchronously. ImageLoadingTracker tracker_; // The tab id we are currently showing the icon for. int current_tab_id_; // The URL we are currently showing the icon for. GURL current_url_; // The string to show for a tooltip; std::string tooltip_; // This is used for post-install visual feedback. The page_action icon is // briefly shown even if it hasn't been enabled by its extension. bool preview_enabled_; // The current popup and the button it came from. NULL if no popup. ExtensionPopup* popup_; content::NotificationRegistrar registrar_; // The extension command accelerator this page action is listening for (to // show the popup). scoped_ptr<ui::Accelerator> page_action_keybinding_; // The extension command accelerator this script badge is listening for (to // show the popup). scoped_ptr<ui::Accelerator> script_badge_keybinding_; scoped_ptr<views::MenuRunner> menu_runner_; // Fade-in animation for the icon with observer scoped to this. ExtensionAction::IconAnimation::ScopedObserver scoped_icon_animation_observer_; DISALLOW_IMPLICIT_CONSTRUCTORS(PageActionImageView); }; #endif // CHROME_BROWSER_UI_VIEWS_LOCATION_BAR_PAGE_ACTION_IMAGE_VIEW_H_
35.809524
79
0.731003
[ "object" ]
a617cd6477e92904cbae6e04c17c864acf3ee18e
1,581
h
C
client.h
ami-GS/MQTTcc
0ab77727ae3bbabbbae40d38a6dac2aa5d3e3258
[ "MIT" ]
null
null
null
client.h
ami-GS/MQTTcc
0ab77727ae3bbabbbae40d38a6dac2aa5d3e3258
[ "MIT" ]
null
null
null
client.h
ami-GS/MQTTcc
0ab77727ae3bbabbbae40d38a6dac2aa5d3e3258
[ "MIT" ]
null
null
null
#ifndef MQTT_CLIENT_H_ #define MQTT_CLIENT_H_ #include <stdint.h> #include <map> #include <sys/time.h> #include "frame.h" #include "transport.h" #include "terminal.h" #include "string" class Client : public Terminal { public: struct timeval timeOfPing; uint32_t pingDulation; Client(const std::string id, const User* user, uint16_t keepAlive, const Will* will); ~Client(); MQTT_ERROR ping(); MQTT_ERROR connect(const std::string addr, int port, bool cleanSession); MQTT_ERROR publish(const std::string topic, const std::string data, uint8_t qos, bool retain); MQTT_ERROR subscribe(std::vector<SubscribeTopic*> topics); MQTT_ERROR unsubscribe(std::vector<std::string> topics); MQTT_ERROR disconnectProcessing(); MQTT_ERROR disconnect(); MQTT_ERROR recvConnectMessage(ConnectMessage* m); MQTT_ERROR recvConnackMessage(ConnackMessage* m); MQTT_ERROR recvPublishMessage(PublishMessage* m); MQTT_ERROR recvPubackMessage(PubackMessage* m); MQTT_ERROR recvPubrecMessage(PubrecMessage* m); MQTT_ERROR recvPubrelMessage(PubrelMessage* m); MQTT_ERROR recvPubcompMessage(PubcompMessage* m); MQTT_ERROR recvSubscribeMessage(SubscribeMessage* m); MQTT_ERROR recvSubackMessage(SubackMessage* m); MQTT_ERROR recvUnsubscribeMessage(UnsubscribeMessage* m); MQTT_ERROR recvUnsubackMessage(UnsubackMessage* m); MQTT_ERROR recvPingreqMessage(PingreqMessage* m); MQTT_ERROR recvPingrespMessage(PingrespMessage* m); MQTT_ERROR recvDisconnectMessage(DisconnectMessage* m); }; #endif //MQTT_CLIENT_H_
36.767442
98
0.763441
[ "vector" ]
a62467f1bfffa3f91936014e94a8f48cf367ae5a
15,186
h
C
content/browser/browser_plugin/browser_plugin_guest.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
content/browser/browser_plugin/browser_plugin_guest.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/browser_plugin/browser_plugin_guest.h
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.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. // A BrowserPluginGuest is the browser side of a browser <--> embedder // renderer channel. A BrowserPlugin (a WebPlugin) is on the embedder // renderer side of browser <--> embedder renderer communication. // // BrowserPluginGuest lives on the UI thread of the browser process. It has a // helper, BrowserPluginGuestHelper, which is a RenderViewHostObserver. The // helper object intercepts messages (ViewHostMsg_*) directed at the browser // process and redirects them to this class. Any messages about the guest render // process that the embedder might be interested in receiving should be listened // for here. // // BrowserPluginGuest is a WebContentsDelegate and WebContentsObserver for the // guest WebContents. BrowserPluginGuest operates under the assumption that the // guest will be accessible through only one RenderViewHost for the lifetime of // the guest WebContents. Thus, cross-process navigation is not supported. #ifndef CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_ #define CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_ #include <map> #include "base/compiler_specific.h" #include "base/id_map.h" #include "base/shared_memory.h" #include "base/time.h" #include "content/common/browser_plugin_message_enums.h" #include "content/port/common/input_event_ack_state.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDragStatus.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" #include "ui/gfx/rect.h" #include "ui/surface/transport_dib.h" struct BrowserPluginHostMsg_AutoSize_Params; struct BrowserPluginHostMsg_CreateGuest_Params; struct BrowserPluginHostMsg_ResizeGuest_Params; struct ViewHostMsg_CreateWindow_Params; #if defined(OS_MACOSX) struct ViewHostMsg_ShowPopup_Params; #endif struct ViewHostMsg_UpdateRect_Params; class WebCursor; struct WebDropData; namespace WebKit { class WebInputEvent; } namespace content { class BrowserPluginHostFactory; class BrowserPluginEmbedder; class RenderProcessHost; class RenderWidgetHostView; struct MediaStreamRequest; // A browser plugin guest provides functionality for WebContents to operate in // the guest role and implements guest specific overrides for ViewHostMsg_* // messages. // // BrowserPluginEmbedder is responsible for creating and destroying a guest. class CONTENT_EXPORT BrowserPluginGuest : public NotificationObserver, public WebContentsDelegate, public WebContentsObserver { public: virtual ~BrowserPluginGuest(); static BrowserPluginGuest* Create( int instance_id, WebContentsImpl* embedder_web_contents, WebContentsImpl* web_contents, const BrowserPluginHostMsg_CreateGuest_Params& params); // Overrides factory for testing. Default (NULL) value indicates regular // (non-test) environment. static void set_factory_for_testing(BrowserPluginHostFactory* factory) { content::BrowserPluginGuest::factory_ = factory; } bool OnMessageReceivedFromEmbedder(const IPC::Message& message); void Initialize(const BrowserPluginHostMsg_CreateGuest_Params& params); void set_guest_hang_timeout_for_testing(const base::TimeDelta& timeout) { guest_hang_timeout_ = timeout; } void set_embedder_web_contents(WebContentsImpl* web_contents) { embedder_web_contents_ = web_contents; } WebContentsImpl* embedder_web_contents() const { return embedder_web_contents_; } RenderWidgetHostView* GetEmbedderRenderWidgetHostView(); bool focused() const { return focused_; } bool visible() const { return guest_visible_; } void clear_damage_buffer() { damage_buffer_.reset(); } void UpdateVisibility(); // NotificationObserver implementation. virtual void Observe(int type, const NotificationSource& source, const NotificationDetails& details) OVERRIDE; // WebContentsObserver implementation. virtual void DidStartProvisionalLoadForFrame( int64 frame_id, int64 parent_frame_id, bool is_main_frame, const GURL& validated_url, bool is_error_page, bool is_iframe_srcdoc, RenderViewHost* render_view_host) OVERRIDE; virtual void DidFailProvisionalLoad( int64 frame_id, bool is_main_frame, const GURL& validated_url, int error_code, const string16& error_description, RenderViewHost* render_view_host) OVERRIDE; virtual void DidCommitProvisionalLoadForFrame( int64 frame_id, bool is_main_frame, const GURL& url, PageTransition transition_type, RenderViewHost* render_view_host) OVERRIDE; virtual void DidStopLoading(RenderViewHost* render_view_host) OVERRIDE; virtual void RenderViewReady() OVERRIDE; virtual void RenderViewGone(base::TerminationStatus status) OVERRIDE; virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; // WebContentsDelegate implementation. virtual bool CanDownload(RenderViewHost* render_view_host, int request_id, const std::string& request_method) OVERRIDE; virtual bool HandleContextMenu(const ContextMenuParams& params) OVERRIDE; virtual void RendererUnresponsive(WebContents* source) OVERRIDE; virtual void RendererResponsive(WebContents* source) OVERRIDE; virtual void RunFileChooser(WebContents* web_contents, const FileChooserParams& params) OVERRIDE; virtual bool ShouldFocusPageAfterCrash() OVERRIDE; virtual void RequestMediaAccessPermission( WebContents* web_contents, const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) OVERRIDE; // Exposes the protected web_contents() from WebContentsObserver. WebContents* GetWebContents(); // Kill the guest process. void Terminate(); // Overridden in tests. virtual void SetDamageBuffer( const BrowserPluginHostMsg_ResizeGuest_Params& params); gfx::Point GetScreenCoordinates(const gfx::Point& relative_position) const; // Helper to send messages to embedder. This methods fills the message with // the correct routing id. // Overridden in test implementation since we want to intercept certain // messages for testing. virtual void SendMessageToEmbedder(IPC::Message* msg); // Returns the identifier that uniquely identifies a browser plugin guest // within an embedder. int instance_id() const { return instance_id_; } // Allow the embedder to call this for unhandled messages when // BrowserPluginGuest is already destroyed. static void AcknowledgeBufferPresent(int route_id, int gpu_host_id, const std::string& mailbox_name, uint32 sync_point); private: typedef std::pair<content::MediaStreamRequest, content::MediaResponseCallback> MediaStreamRequestAndCallbackPair; typedef std::map<int, MediaStreamRequestAndCallbackPair> MediaStreamRequestsMap; friend class TestBrowserPluginGuest; BrowserPluginGuest(int instance_id, WebContentsImpl* embedder_web_contents, WebContentsImpl* web_contents, const BrowserPluginHostMsg_CreateGuest_Params& params); // Returns the embedder's routing ID. int embedder_routing_id() const; // Schedules this BrowserPluginGuest for deletion if it hasn't already been // scheduled. void Destroy(); base::SharedMemory* damage_buffer() const { return damage_buffer_.get(); } const gfx::Size& damage_view_size() const { return damage_view_size_; } float damage_buffer_scale_factor() const { return damage_buffer_scale_factor_; } // Returns the damage buffer corresponding to the handle in resize |params|. base::SharedMemory* GetDamageBufferFromEmbedder( const BrowserPluginHostMsg_ResizeGuest_Params& params); // Called when a redirect notification occurs. void LoadRedirect(const GURL& old_url, const GURL& new_url, bool is_top_level); bool InAutoSizeBounds(const gfx::Size& size) const; // Message handlers for messsages from embedder. // Allows or denies a permission request access, after the embedder has had a // chance to decide. void OnRespondPermission(int instance_id, BrowserPluginPermissionType permission_type, int request_id, bool should_allow); // Handles drag events from the embedder. // When dragging, the drag events go to the embedder first, and if the drag // happens on the browser plugin, then the plugin sends a corresponding // drag-message to the guest. This routes the drag-message to the guest // renderer. void OnDragStatusUpdate(int instance_id, WebKit::WebDragStatus drag_status, const WebDropData& drop_data, WebKit::WebDragOperationsMask drag_mask, const gfx::Point& location); // If possible, navigate the guest to |relative_index| entries away from the // current navigation entry. virtual void OnGo(int instance_id, int relative_index); // Overriden in tests. virtual void OnHandleInputEvent(int instance_id, const gfx::Rect& guest_window_rect, const WebKit::WebInputEvent* event); void OnLockMouse(bool user_gesture, bool last_unlocked_by_target, bool privileged); void OnLockMouseAck(int instance_id, bool succeeded); void OnNavigateGuest(int instance_id, const std::string& src); void OnPluginDestroyed(int instance_id); // Reload the guest. Overriden in tests. virtual void OnReload(int instance_id); // Grab the new damage buffer from the embedder, and resize the guest's // web contents. void OnResizeGuest(int instance_id, const BrowserPluginHostMsg_ResizeGuest_Params& params); // Overriden in tests. virtual void OnSetFocus(int instance_id, bool focused); // Sets the name of the guest so that other guests in the same partition can // access it. void OnSetName(int instance_id, const std::string& name); // Updates the size state of the guest. void OnSetSize( int instance_id, const BrowserPluginHostMsg_AutoSize_Params& auto_size_params, const BrowserPluginHostMsg_ResizeGuest_Params& resize_guest_params); // The guest WebContents is visible if both its embedder is visible and // the browser plugin element is visible. If either one is not then the // WebContents is marked as hidden. A hidden WebContents will consume // fewer GPU and CPU resources. // // When every WebContents in a RenderProcessHost is hidden, it will lower // the priority of the process (see RenderProcessHostImpl::WidgetHidden). // // It will also send a message to the guest renderer process to cleanup // resources such as dropping back buffers and adjusting memory limits (if in // compositing mode, see CCLayerTreeHost::setVisible). // // Additionally, it will slow down Javascript execution and garbage // collection. See RenderThreadImpl::IdleHandler (executed when hidden) and // RenderThreadImpl::IdleHandlerInForegroundTab (executed when visible). void OnSetVisibility(int instance_id, bool visible); // Stop loading the guest. Overriden in tests. virtual void OnStop(int instance_id); // Message from embedder acknowledging last HW buffer. void OnSwapBuffersACK(int instance_id, int route_id, int gpu_host_id, const std::string& mailbox_name, uint32 sync_point); void OnTerminateGuest(int instance_id); void OnUnlockMouse(); void OnUnlockMouseAck(int instance_id); void OnUpdateRectACK( int instance_id, const BrowserPluginHostMsg_AutoSize_Params& auto_size_params, const BrowserPluginHostMsg_ResizeGuest_Params& resize_guest_params); // Message handlers for messages from guest. void OnCreateWindow(const ViewHostMsg_CreateWindow_Params& params, int* route_id, int* surface_id, int64* cloned_session_storage_namespace_id); void OnHandleInputEventAck( WebKit::WebInputEvent::Type event_type, InputEventAckState ack_result); void OnHasTouchEventHandlers(bool accept); void OnSetCursor(const WebCursor& cursor); // On MacOSX popups are painted by the browser process. We handle them here // so that they are positioned correctly. #if defined(OS_MACOSX) void OnShowPopup(const ViewHostMsg_ShowPopup_Params& params); #endif void OnShowWidget(int route_id, const gfx::Rect& initial_pos); // Overriden in tests. virtual void OnTakeFocus(bool reverse); void OnUpdateDragCursor(WebKit::WebDragOperation operation); void OnUpdateFrameName(int frame_id, bool is_top_level, const std::string& name); void OnUpdateRect(const ViewHostMsg_UpdateRect_Params& params); // Static factory instance (always NULL for non-test). static content::BrowserPluginHostFactory* factory_; NotificationRegistrar notification_registrar_; WebContentsImpl* embedder_web_contents_; // An identifier that uniquely identifies a browser plugin guest within an // embedder. int instance_id_; scoped_ptr<base::SharedMemory> damage_buffer_; // An identifier that uniquely identifies a damage buffer. uint32 damage_buffer_sequence_id_; size_t damage_buffer_size_; gfx::Size damage_view_size_; float damage_buffer_scale_factor_; gfx::Rect guest_window_rect_; gfx::Rect guest_screen_rect_; base::TimeDelta guest_hang_timeout_; bool focused_; bool mouse_locked_; bool guest_visible_; bool embedder_visible_; std::string name_; bool auto_size_enabled_; gfx::Size max_auto_size_; gfx::Size min_auto_size_; bool destroy_called_; // A counter to generate unique request id for a media access request. // We only need the ids to be unique for a given BrowserPluginGuest. int current_media_access_request_id_; // A map to store WebContents's media request object and callback. // We need to store these because we need a roundtrip to the embedder to know // if we allow or disallow the request. The key of the map is unique only for // a given BrowserPluginGuest. MediaStreamRequestsMap media_requests_map_; DISALLOW_COPY_AND_ASSIGN(BrowserPluginGuest); }; } // namespace content #endif // CONTENT_BROWSER_BROWSER_PLUGIN_BROWSER_PLUGIN_GUEST_H_
40.713137
80
0.73706
[ "render", "object" ]
a624efdfd62c1379e1d0242e29b69dcd24f258cb
949
h
C
src/tableview_frozen.h
Frodo45127/qt_custom_rpfm
8df9fbc7e220d4d8e859026349b51923e92c7bf6
[ "MIT" ]
null
null
null
src/tableview_frozen.h
Frodo45127/qt_custom_rpfm
8df9fbc7e220d4d8e859026349b51923e92c7bf6
[ "MIT" ]
null
null
null
src/tableview_frozen.h
Frodo45127/qt_custom_rpfm
8df9fbc7e220d4d8e859026349b51923e92c7bf6
[ "MIT" ]
null
null
null
#ifndef TABLEVIEW_FROZEN_H #define TABLEVIEW_FROZEN_H #include "qt_custom_rpfm_global.h" #include <QTableView> extern "C" QTableView* new_tableview_frozen(QAbstractItemModel* model = 0, QTableView* frozen_table = 0); class QTableViewFrozen : public QTableView { Q_OBJECT public: QTableViewFrozen(QAbstractItemModel* model, QTableView* tableview); ~QTableViewFrozen(); protected: void resizeEvent(QResizeEvent *event) override; QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override; void scrollTo (const QModelIndex & index, ScrollHint hint = EnsureVisible) override; private: QTableView *frozenTableView; void init(); void updateFrozenTableGeometry(); private slots: void updateSectionWidth(int logicalIndex, int oldSize, int newSize); void updateSectionHeight(int logicalIndex, int oldSize, int newSize); }; #endif // TABLEVIEW_FROZEN_H
29.65625
105
0.758693
[ "model" ]
a6267fa66455e0411a851d51cf44f5fa1b2866a1
8,764
h
C
Win32.Carberp/all source/BJWJ/include/plugin/nsIJVMAuthTools.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Carberp/all source/BlackJoeWhiteJoe/include/plugin/nsIJVMAuthTools.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Carberp/all source/BlackJoeWhiteJoe/include/plugin/nsIJVMAuthTools.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/modules/plugin/base/public/nsIJVMAuthTools.idl */ #ifndef __gen_nsIJVMAuthTools_h__ #define __gen_nsIJVMAuthTools_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif #define NS_JVMAUTHTOOLS_CID \ { /* d8e716f9-c96e-4e84-ab12-980f5567e2a4 */ \ 0xd8e716f9, \ 0xc96e, \ 0x4e84, \ {0xab, 0x12, 0x98, 0x0f, 0x55, 0x67, 0xe2, 0xa4} \ } /* starting interface: nsIAuthenticationInfo */ #define NS_IAUTHENTICATIONINFO_IID_STR "078a1b99-6be2-4a57-a749-378f4a506097" #define NS_IAUTHENTICATIONINFO_IID \ {0x078a1b99, 0x6be2, 0x4a57, \ { 0xa7, 0x49, 0x37, 0x8f, 0x4a, 0x50, 0x60, 0x97 }} class NS_NO_VTABLE nsIAuthenticationInfo : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IAUTHENTICATIONINFO_IID) /** * AuthenticationInfo (username/password pair) */ /* readonly attribute const_char_ptr username; */ NS_IMETHOD GetUsername(const char * *aUsername) = 0; /* readonly attribute const_char_ptr password; */ NS_IMETHOD GetPassword(const char * *aPassword) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIAuthenticationInfo, NS_IAUTHENTICATIONINFO_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIAUTHENTICATIONINFO \ NS_IMETHOD GetUsername(const char * *aUsername); \ NS_IMETHOD GetPassword(const char * *aPassword); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIAUTHENTICATIONINFO(_to) \ NS_IMETHOD GetUsername(const char * *aUsername) { return _to GetUsername(aUsername); } \ NS_IMETHOD GetPassword(const char * *aPassword) { return _to GetPassword(aPassword); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIAUTHENTICATIONINFO(_to) \ NS_IMETHOD GetUsername(const char * *aUsername) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUsername(aUsername); } \ NS_IMETHOD GetPassword(const char * *aPassword) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPassword(aPassword); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsAuthenticationInfo : public nsIAuthenticationInfo { public: NS_DECL_ISUPPORTS NS_DECL_NSIAUTHENTICATIONINFO nsAuthenticationInfo(); private: ~nsAuthenticationInfo(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsAuthenticationInfo, nsIAuthenticationInfo) nsAuthenticationInfo::nsAuthenticationInfo() { /* member initializers and constructor code */ } nsAuthenticationInfo::~nsAuthenticationInfo() { /* destructor code */ } /* readonly attribute const_char_ptr username; */ NS_IMETHODIMP nsAuthenticationInfo::GetUsername(const char * *aUsername) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute const_char_ptr password; */ NS_IMETHODIMP nsAuthenticationInfo::GetPassword(const char * *aPassword) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIJVMAuthTools */ #define NS_IJVMAUTHTOOLS_IID_STR "82274a32-a196-42ee-8e3b-fcb73e339518" #define NS_IJVMAUTHTOOLS_IID \ {0x82274a32, 0xa196, 0x42ee, \ { 0x8e, 0x3b, 0xfc, 0xb7, 0x3e, 0x33, 0x95, 0x18 }} class NS_NO_VTABLE nsIJVMAuthTools : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IJVMAUTHTOOLS_IID) /** * Export AuthenticationInfo interface to JPI. * * @param protocol the protocol that support (http/https) * @param host host name * @param port port number * @param scheme scheme * @param realm realm * @param nsIAuthenticationInfo the AuthenticationInfo interface * that export * * @return NS_OK if success, other if fail */ /* nsIAuthenticationInfo GetAuthenticationInfo (in string protocol, in string host, in PRInt32 port, in string scheme, in string realm); */ NS_IMETHOD GetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, nsIAuthenticationInfo **_retval NS_OUTPARAM) = 0; /** * Import username/password pair from JPI. * * @param protocol the protocol that support (http/https) * @param host host name * @param port port number * @param scheme scheme * @param realm realm * @param username user name * @param password password * * @return NS_OK if success, other if fail */ /* void SetAuthenticationInfo (in string protocol, in string host, in PRInt32 port, in string scheme, in string realm, in string username, in string password); */ NS_IMETHOD SetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, const char *username, const char *password) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIJVMAuthTools, NS_IJVMAUTHTOOLS_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIJVMAUTHTOOLS \ NS_IMETHOD GetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, nsIAuthenticationInfo **_retval NS_OUTPARAM); \ NS_IMETHOD SetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, const char *username, const char *password); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIJVMAUTHTOOLS(_to) \ NS_IMETHOD GetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, nsIAuthenticationInfo **_retval NS_OUTPARAM) { return _to GetAuthenticationInfo(protocol, host, port, scheme, realm, _retval); } \ NS_IMETHOD SetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, const char *username, const char *password) { return _to SetAuthenticationInfo(protocol, host, port, scheme, realm, username, password); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIJVMAUTHTOOLS(_to) \ NS_IMETHOD GetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, nsIAuthenticationInfo **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAuthenticationInfo(protocol, host, port, scheme, realm, _retval); } \ NS_IMETHOD SetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, const char *username, const char *password) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAuthenticationInfo(protocol, host, port, scheme, realm, username, password); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsJVMAuthTools : public nsIJVMAuthTools { public: NS_DECL_ISUPPORTS NS_DECL_NSIJVMAUTHTOOLS nsJVMAuthTools(); private: ~nsJVMAuthTools(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsJVMAuthTools, nsIJVMAuthTools) nsJVMAuthTools::nsJVMAuthTools() { /* member initializers and constructor code */ } nsJVMAuthTools::~nsJVMAuthTools() { /* destructor code */ } /* nsIAuthenticationInfo GetAuthenticationInfo (in string protocol, in string host, in PRInt32 port, in string scheme, in string realm); */ NS_IMETHODIMP nsJVMAuthTools::GetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, nsIAuthenticationInfo **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* void SetAuthenticationInfo (in string protocol, in string host, in PRInt32 port, in string scheme, in string realm, in string username, in string password); */ NS_IMETHODIMP nsJVMAuthTools::SetAuthenticationInfo(const char *protocol, const char *host, PRInt32 port, const char *scheme, const char *realm, const char *username, const char *password) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIJVMAuthTools_h__ */
38.951111
299
0.729804
[ "object" ]
a62c4f2cad9cbab6e5e5c4e32a768c0c36112873
9,854
c
C
lib/commonmarker/src/main.c
gitter-badger/Browser-1
378a81709de6042604f19072492017ee53a57036
[ "MIT" ]
6
2021-11-13T04:42:32.000Z
2022-03-19T21:13:11.000Z
thirdparty/cmark-gfm/src/main.c
godot-extended-libraries/commonmark
282962c5e013a87f57d16ed8516481bcd04ba5bb
[ "MIT" ]
1
2021-03-16T16:35:26.000Z
2021-03-16T16:35:26.000Z
thirdparty/cmark-gfm/src/main.c
godot-extended-libraries/commonmark
282962c5e013a87f57d16ed8516481bcd04ba5bb
[ "MIT" ]
2
2021-03-16T16:23:22.000Z
2022-01-25T23:08:39.000Z
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "config.h" #include "cmark-gfm.h" #include "node.h" #include "cmark-gfm-extension_api.h" #include "syntax_extension.h" #include "parser.h" #include "registry.h" #include "../extensions/cmark-gfm-core-extensions.h" #if defined(__OpenBSD__) # include <sys/param.h> # if OpenBSD >= 201605 # define USE_PLEDGE # include <unistd.h> # endif #endif #if defined(__OpenBSD__) # include <sys/param.h> # if OpenBSD >= 201605 # define USE_PLEDGE # include <unistd.h> # endif #endif #if defined(_WIN32) && !defined(__CYGWIN__) #include <io.h> #include <fcntl.h> #endif typedef enum { FORMAT_NONE, FORMAT_HTML, FORMAT_XML, FORMAT_MAN, FORMAT_COMMONMARK, FORMAT_PLAINTEXT, FORMAT_LATEX } writer_format; void print_usage() { printf("Usage: cmark-gfm [FILE*]\n"); printf("Options:\n"); printf(" --to, -t FORMAT Specify output format (html, xml, man, " "commonmark, plaintext, latex)\n"); printf(" --width WIDTH Specify wrap width (default 0 = nowrap)\n"); printf(" --sourcepos Include source position attribute\n"); printf(" --hardbreaks Treat newlines as hard line breaks\n"); printf(" --nobreaks Render soft line breaks as spaces\n"); printf(" --unsafe Render raw HTML and dangerous URLs\n"); printf(" --smart Use smart punctuation\n"); printf(" --validate-utf8 Replace UTF-8 invalid sequences with U+FFFD\n"); printf(" --github-pre-lang Use GitHub-style <pre lang> for code blocks\n"); printf(" --extension, -e EXTENSION_NAME Specify an extension name to use\n"); printf(" --list-extensions List available extensions and quit\n"); printf(" --strikethrough-double-tilde Only parse strikethrough (if enabled)\n"); printf(" with two tildes\n"); printf(" --table-prefer-style-attributes Use style attributes to align table cells\n" " instead of align attributes.\n"); printf(" --full-info-string Include remainder of code block info\n" " string in a separate attribute.\n"); printf(" --help, -h Print usage information\n"); printf(" --version Print version\n"); } static bool print_document(cmark_node *document, writer_format writer, int options, int width, cmark_parser *parser) { char *result; cmark_mem *mem = cmark_get_default_mem_allocator(); switch (writer) { case FORMAT_HTML: result = cmark_render_html_with_mem(document, options, parser->syntax_extensions, mem); break; case FORMAT_XML: result = cmark_render_xml_with_mem(document, options, mem); break; case FORMAT_MAN: result = cmark_render_man_with_mem(document, options, width, mem); break; case FORMAT_COMMONMARK: result = cmark_render_commonmark_with_mem(document, options, width, mem); break; case FORMAT_PLAINTEXT: result = cmark_render_plaintext_with_mem(document, options, width, mem); break; case FORMAT_LATEX: result = cmark_render_latex_with_mem(document, options, width, mem); break; default: fprintf(stderr, "Unknown format %d\n", writer); return false; } printf("%s", result); mem->free(result); return true; } static void print_extensions(void) { cmark_llist *syntax_extensions; cmark_llist *tmp; printf ("Available extensions:\nfootnotes\n"); cmark_mem *mem = cmark_get_default_mem_allocator(); syntax_extensions = cmark_list_syntax_extensions(mem); for (tmp = syntax_extensions; tmp; tmp=tmp->next) { cmark_syntax_extension *ext = (cmark_syntax_extension *) tmp->data; printf("%s\n", ext->name); } cmark_llist_free(mem, syntax_extensions); } int main(int argc, char *argv[]) { int i, numfps = 0; int *files; char buffer[4096]; cmark_parser *parser = NULL; size_t bytes; cmark_node *document = NULL; int width = 0; char *unparsed; writer_format writer = FORMAT_HTML; int options = CMARK_OPT_DEFAULT; int res = 1; #ifdef USE_PLEDGE if (pledge("stdio rpath", NULL) != 0) { perror("pledge"); return 1; } #endif cmark_gfm_core_extensions_ensure_registered(); #ifdef USE_PLEDGE if (pledge("stdio rpath", NULL) != 0) { perror("pledge"); return 1; } #endif #if defined(_WIN32) && !defined(__CYGWIN__) _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); #endif files = (int *)calloc(argc, sizeof(*files)); for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--version") == 0) { printf("cmark-gfm %s", CMARK_GFM_VERSION_STRING); printf(" - CommonMark with GitHub Flavored Markdown converter\n(C) 2014-2016 John MacFarlane\n"); goto success; } else if (strcmp(argv[i], "--list-extensions") == 0) { print_extensions(); goto success; } else if (strcmp(argv[i], "--full-info-string") == 0) { options |= CMARK_OPT_FULL_INFO_STRING; } else if (strcmp(argv[i], "--table-prefer-style-attributes") == 0) { options |= CMARK_OPT_TABLE_PREFER_STYLE_ATTRIBUTES; } else if (strcmp(argv[i], "--strikethrough-double-tilde") == 0) { options |= CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE; } else if (strcmp(argv[i], "--sourcepos") == 0) { options |= CMARK_OPT_SOURCEPOS; } else if (strcmp(argv[i], "--hardbreaks") == 0) { options |= CMARK_OPT_HARDBREAKS; } else if (strcmp(argv[i], "--nobreaks") == 0) { options |= CMARK_OPT_NOBREAKS; } else if (strcmp(argv[i], "--smart") == 0) { options |= CMARK_OPT_SMART; } else if (strcmp(argv[i], "--github-pre-lang") == 0) { options |= CMARK_OPT_GITHUB_PRE_LANG; } else if (strcmp(argv[i], "--unsafe") == 0) { options |= CMARK_OPT_UNSAFE; } else if (strcmp(argv[i], "--validate-utf8") == 0) { options |= CMARK_OPT_VALIDATE_UTF8; } else if (strcmp(argv[i], "--liberal-html-tag") == 0) { options |= CMARK_OPT_LIBERAL_HTML_TAG; } else if ((strcmp(argv[i], "--help") == 0) || (strcmp(argv[i], "-h") == 0)) { print_usage(); goto success; } else if (strcmp(argv[i], "--width") == 0) { i += 1; if (i < argc) { width = (int)strtol(argv[i], &unparsed, 10); if (unparsed && strlen(unparsed) > 0) { fprintf(stderr, "failed parsing width '%s' at '%s'\n", argv[i], unparsed); goto failure; } } else { fprintf(stderr, "--width requires an argument\n"); goto failure; } } else if ((strcmp(argv[i], "-t") == 0) || (strcmp(argv[i], "--to") == 0)) { i += 1; if (i < argc) { if (strcmp(argv[i], "man") == 0) { writer = FORMAT_MAN; } else if (strcmp(argv[i], "html") == 0) { writer = FORMAT_HTML; } else if (strcmp(argv[i], "xml") == 0) { writer = FORMAT_XML; } else if (strcmp(argv[i], "commonmark") == 0) { writer = FORMAT_COMMONMARK; } else if (strcmp(argv[i], "plaintext") == 0) { writer = FORMAT_PLAINTEXT; } else if (strcmp(argv[i], "latex") == 0) { writer = FORMAT_LATEX; } else { fprintf(stderr, "Unknown format %s\n", argv[i]); goto failure; } } else { fprintf(stderr, "No argument provided for %s\n", argv[i - 1]); goto failure; } } else if ((strcmp(argv[i], "-e") == 0) || (strcmp(argv[i], "--extension") == 0)) { i += 1; // Simpler to handle extensions in a second pass, as we can directly register // them with the parser. if (i < argc && strcmp(argv[i], "footnotes") == 0) { options |= CMARK_OPT_FOOTNOTES; } } else if (*argv[i] == '-') { print_usage(); goto failure; } else { // treat as file argument files[numfps++] = i; } } #if DEBUG parser = cmark_parser_new(options); #else parser = cmark_parser_new_with_mem(options, cmark_get_arena_mem_allocator()); #endif for (i = 1; i < argc; i++) { if ((strcmp(argv[i], "-e") == 0) || (strcmp(argv[i], "--extension") == 0)) { i += 1; if (i < argc) { if (strcmp(argv[i], "footnotes") == 0) { continue; } cmark_syntax_extension *syntax_extension = cmark_find_syntax_extension(argv[i]); if (!syntax_extension) { fprintf(stderr, "Unknown extension %s\n", argv[i]); goto failure; } cmark_parser_attach_syntax_extension(parser, syntax_extension); } else { fprintf(stderr, "No argument provided for %s\n", argv[i - 1]); goto failure; } } } for (i = 0; i < numfps; i++) { FILE *fp = fopen(argv[files[i]], "rb"); if (fp == NULL) { fprintf(stderr, "Error opening file %s: %s\n", argv[files[i]], strerror(errno)); goto failure; } while ((bytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) { cmark_parser_feed(parser, buffer, bytes); if (bytes < sizeof(buffer)) { break; } } fclose(fp); } if (numfps == 0) { while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) > 0) { cmark_parser_feed(parser, buffer, bytes); if (bytes < sizeof(buffer)) { break; } } } #ifdef USE_PLEDGE if (pledge("stdio", NULL) != 0) { perror("pledge"); return 1; } #endif document = cmark_parser_finish(parser); if (!document || !print_document(document, writer, options, width, parser)) goto failure; success: res = 0; failure: #if DEBUG if (parser) cmark_parser_free(parser); if (document) cmark_node_free(document); #else cmark_arena_reset(); #endif cmark_release_plugins(); free(files); return res; }
29.951368
103
0.599756
[ "render" ]
a62d0b466118448434a2f82e243968113c49f454
2,702
c
C
unit-test/test_ezsigntemplatepackagesigner_response_compound.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
unit-test/test_ezsigntemplatepackagesigner_response_compound.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
unit-test/test_ezsigntemplatepackagesigner_response_compound.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
#ifndef ezsigntemplatepackagesigner_response_compound_TEST #define ezsigntemplatepackagesigner_response_compound_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define ezsigntemplatepackagesigner_response_compound_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/ezsigntemplatepackagesigner_response_compound.h" ezsigntemplatepackagesigner_response_compound_t* instantiate_ezsigntemplatepackagesigner_response_compound(int include_optional); ezsigntemplatepackagesigner_response_compound_t* instantiate_ezsigntemplatepackagesigner_response_compound(int include_optional) { ezsigntemplatepackagesigner_response_compound_t* ezsigntemplatepackagesigner_response_compound = NULL; if (include_optional) { ezsigntemplatepackagesigner_response_compound = ezsigntemplatepackagesigner_response_compound_create( 174, 99, "Customer" ); } else { ezsigntemplatepackagesigner_response_compound = ezsigntemplatepackagesigner_response_compound_create( 174, 99, "Customer" ); } return ezsigntemplatepackagesigner_response_compound; } #ifdef ezsigntemplatepackagesigner_response_compound_MAIN void test_ezsigntemplatepackagesigner_response_compound(int include_optional) { ezsigntemplatepackagesigner_response_compound_t* ezsigntemplatepackagesigner_response_compound_1 = instantiate_ezsigntemplatepackagesigner_response_compound(include_optional); cJSON* jsonezsigntemplatepackagesigner_response_compound_1 = ezsigntemplatepackagesigner_response_compound_convertToJSON(ezsigntemplatepackagesigner_response_compound_1); printf("ezsigntemplatepackagesigner_response_compound :\n%s\n", cJSON_Print(jsonezsigntemplatepackagesigner_response_compound_1)); ezsigntemplatepackagesigner_response_compound_t* ezsigntemplatepackagesigner_response_compound_2 = ezsigntemplatepackagesigner_response_compound_parseFromJSON(jsonezsigntemplatepackagesigner_response_compound_1); cJSON* jsonezsigntemplatepackagesigner_response_compound_2 = ezsigntemplatepackagesigner_response_compound_convertToJSON(ezsigntemplatepackagesigner_response_compound_2); printf("repeating ezsigntemplatepackagesigner_response_compound:\n%s\n", cJSON_Print(jsonezsigntemplatepackagesigner_response_compound_2)); } int main() { test_ezsigntemplatepackagesigner_response_compound(1); test_ezsigntemplatepackagesigner_response_compound(0); printf("Hello world \n"); return 0; } #endif // ezsigntemplatepackagesigner_response_compound_MAIN #endif // ezsigntemplatepackagesigner_response_compound_TEST
42.888889
213
0.866025
[ "model" ]
a62d6547791d1d1244812ecbdc7e0dda09bdac34
6,024
h
C
vstgui/lib/dispatchlist.h
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
608
2015-12-18T10:21:27.000Z
2022-03-29T01:00:52.000Z
vstgui/lib/dispatchlist.h
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
111
2016-01-27T09:07:33.000Z
2022-02-28T06:47:32.000Z
vstgui/lib/dispatchlist.h
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
123
2015-12-18T08:30:36.000Z
2022-03-05T17:26:38.000Z
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #pragma once #include <vector> #include <algorithm> //------------------------------------------------------------------------ namespace VSTGUI { template<typename T> class DispatchList { public: DispatchList () = default; void add (const T& obj); void add (T&& obj); void remove (const T& obj); void remove (T&& obj); bool empty () const; template<typename Procedure> void forEach (Procedure proc); template<typename Procedure, typename Condition> void forEach (Procedure proc, Condition condition); template<typename Procedure> void forEachReverse (Procedure proc); template<typename Procedure, typename Condition> void forEachReverse (Procedure proc, Condition condition); private: using Array = std::vector<std::pair<bool, T>>; using AddArray = std::vector<T>; void postForEach (); Array entries; AddArray toAdd; bool inForEach{false}; }; //------------------------------------------------------------------------ template <typename T, typename ListenerInterface> struct ListenerProvider { //------------------------------------------------------------------------ using List = DispatchList<ListenerInterface*>; void registerListener (ListenerInterface* listener) { listeners.add (listener); } void unregisterListener (ListenerInterface* listener) { listeners.remove (listener); } template<typename Proc> void forEachListener (Proc proc) { listeners.forEach ( [&] (ListenerInterface* listener) { proc (listener); }); } List& getListeners () { return listeners; } const List& getListeners () const { return listeners; } private: List listeners; }; //------------------------------------------------------------------------ template<typename T> inline void DispatchList<T>::add (const T& obj) { if (inForEach) toAdd.emplace_back (obj); else entries.emplace_back (std::make_pair (true, obj)); } //------------------------------------------------------------------------ template<typename T> inline void DispatchList<T>::add (T&& obj) { if (inForEach) toAdd.emplace_back (std::move (obj)); else entries.emplace_back (std::make_pair (true, std::move (obj))); } //------------------------------------------------------------------------ template<typename T> inline void DispatchList<T>::remove (const T& obj) { auto it = std::find_if ( entries.begin (), entries.end (), [&](const typename Array::value_type& element) { return element.second == obj; }); if (it != entries.end ()) { if (inForEach) it->first = false; else entries.erase (it); } } //------------------------------------------------------------------------ template<typename T> inline void DispatchList<T>::remove (T&& obj) { auto it = std::find ( entries.begin (), entries.end (), [&](const typename Array::value_type& element) { return element.second == obj; }); if (it != entries.end ()) { if (inForEach) it->first = false; else entries.erase (it); } } //------------------------------------------------------------------------ template<typename T> inline bool DispatchList<T>::empty () const { return entries.empty (); } //------------------------------------------------------------------------ template<typename T> inline void DispatchList<T>::postForEach () { AddArray toRemove; for (auto& element : entries) { if (element.first) continue; toRemove.emplace_back (std::move (element.second)); } if (!toRemove.empty ()) { entries.erase (std::remove_if (entries.begin (), entries.end (), [] (const typename Array::value_type& element) { return element.first == false; }), entries.end ()); } if (!toAdd.empty ()) { AddArray tmp; toAdd.swap (tmp); for (auto&& it : tmp) add (std::move (it)); } } //------------------------------------------------------------------------ template<typename T> template<typename Procedure> inline void DispatchList<T>::forEach (Procedure proc) { if (entries.empty ()) return; bool wasInForEach = inForEach; inForEach = true; for (auto& it : entries) { if (it.first == false) continue; proc (it.second); } inForEach = wasInForEach; if (!inForEach) postForEach (); } //------------------------------------------------------------------------ template<typename T> template<typename Procedure> inline void DispatchList<T>::forEachReverse (Procedure proc) { if (entries.empty ()) return; bool wasInForEach = inForEach; inForEach = true; for (auto it = entries.rbegin (); it != entries.rend (); ++it) { if ((*it).first == false) continue; proc ((*it).second); } inForEach = wasInForEach; if (!inForEach) postForEach (); } //------------------------------------------------------------------------ template<typename T> template<typename Procedure, typename Condition> inline void DispatchList<T>::forEach (Procedure proc, Condition condition) { if (entries.empty ()) return; bool wasInForEach = inForEach; inForEach = true; for (auto& it : entries) { if (it.first == false) continue; if (condition (proc (it.second))) break; } inForEach = wasInForEach; if (!inForEach) postForEach (); } //------------------------------------------------------------------------ template<typename T> template<typename Procedure, typename Condition> inline void DispatchList<T>::forEachReverse (Procedure proc, Condition condition) { if (entries.empty ()) return; bool wasInForEach = inForEach; inForEach = true; for (auto it = entries.rbegin (); it != entries.rend (); ++it) { if ((*it).first == false) continue; if (condition (proc ((*it).second))) break; } inForEach = wasInForEach; if (!inForEach) postForEach (); } //------------------------------------------------------------------------ } // VSTGUI
24.487805
87
0.555445
[ "vector" ]
a63664fc6f9217a244bc25a4f35c02cfa8668d6d
1,677
h
C
mindspore/core/ops/bn_training_update.h
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/core/ops/bn_training_update.h
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/core/ops/bn_training_update.h
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies 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 MINDSPORE_CORE_OPS_BN_TRAINING_UPDATE_H_ #define MINDSPORE_CORE_OPS_BN_TRAINING_UPDATE_H_ #include <map> #include <memory> #include <vector> #include <string> #include "ops/base_operator.h" #include "mindapi/base/types.h" namespace mindspore { namespace ops { constexpr auto kNameBNTrainingUpdate = "BNTrainingUpdate"; class MIND_API BNTrainingUpdate : public BaseOperator { public: MIND_API_BASE_MEMBER(BNTrainingUpdate); BNTrainingUpdate() : BaseOperator(kNameBNTrainingUpdate) { InitIOName({"x", "sum", "square_sum", "scale", "b", "mean", "variance"}, {"y", "running_mean", "running_variance", "save_mean", "save_inv_variance"}); } }; abstract::AbstractBasePtr BNTrainingUpdateInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive, const std::vector<abstract::AbstractBasePtr> &input_args); using kPrimBNTrainingUpdatePtr = std::shared_ptr<BNTrainingUpdate>; } // namespace ops } // namespace mindspore #endif // MINDSPORE_CORE_OPS_BN_TRAINING_UPDATE_H_
34.9375
115
0.73703
[ "vector" ]
a6391687effcff4ae38342a9bdb5984ab7406a39
78
h
C
import_all.h
fliptrail/stl-cpp
26ef65d338265ff3d1703e9dc23c17bde54ea5c9
[ "MIT" ]
2
2021-06-04T14:13:56.000Z
2021-06-07T06:40:11.000Z
import_all.h
fliptrail/stl-cpp
26ef65d338265ff3d1703e9dc23c17bde54ea5c9
[ "MIT" ]
null
null
null
import_all.h
fliptrail/stl-cpp
26ef65d338265ff3d1703e9dc23c17bde54ea5c9
[ "MIT" ]
1
2021-06-06T16:51:51.000Z
2021-06-06T16:51:51.000Z
#include "pair.h" #include "algorithms.h" #include "vector.h" #include "set.h"
19.5
23
0.705128
[ "vector" ]
a63c29946878b3d9cb2b9fd87b204bf0541f2775
18,931
c
C
source/blender/blenkernel/intern/subdiv_displacement_multires.c
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/blenkernel/intern/subdiv_displacement_multires.c
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/blenkernel/intern/subdiv_displacement_multires.c
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-12-02T20:05:42.000Z
2020-12-02T20:05:42.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2018 by Blender Foundation. * All rights reserved. */ /** \file * \ingroup bke */ #include "BKE_subdiv.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_modifier_types.h" #include "DNA_object_types.h" #include "BLI_math_vector.h" #include "BLI_utildefines.h" #include "BKE_customdata.h" #include "BKE_multires.h" #include "BKE_subdiv_eval.h" #include "MEM_guardedalloc.h" typedef struct PolyCornerIndex { int poly_index; int corner; } PolyCornerIndex; typedef struct MultiresDisplacementData { Subdiv *subdiv; int grid_size; /* Mesh is used to read external displacement. */ Mesh *mesh; const MultiresModifierData *mmd; const MPoly *mpoly; const MDisps *mdisps; /* Indexed by ptex face index, contains polygon/corner which corresponds * to it. * * NOTE: For quad polygon this is an index of first corner only, since * there we only have one ptex. */ PolyCornerIndex *ptex_poly_corner; /* Indexed by coarse face index, returns first ptex face index corresponding * to that coarse face. */ int *face_ptex_offset; /* Sanity check, is used in debug builds. * Controls that initialize() was called prior to eval_displacement(). */ bool is_initialized; } MultiresDisplacementData; /* Denotes which grid to use to average value of the displacement read from the * grid which corresponds to the ptex face. */ typedef enum eAverageWith { AVERAGE_WITH_NONE, AVERAGE_WITH_ALL, AVERAGE_WITH_PREV, AVERAGE_WITH_NEXT, } eAverageWith; static int displacement_get_grid_and_coord(SubdivDisplacement *displacement, const int ptex_face_index, const float u, const float v, const MDisps **r_displacement_grid, float *grid_u, float *grid_v) { MultiresDisplacementData *data = displacement->user_data; const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; const int start_grid_index = poly->loopstart + poly_corner->corner; int corner = 0; if (poly->totloop == 4) { float corner_u, corner_v; corner = BKE_subdiv_rotate_quad_to_corner(u, v, &corner_u, &corner_v); *r_displacement_grid = &data->mdisps[start_grid_index + corner]; BKE_subdiv_ptex_face_uv_to_grid_uv(corner_u, corner_v, grid_u, grid_v); } else { *r_displacement_grid = &data->mdisps[start_grid_index]; BKE_subdiv_ptex_face_uv_to_grid_uv(u, v, grid_u, grid_v); } return corner; } static const MDisps *displacement_get_other_grid(SubdivDisplacement *displacement, const int ptex_face_index, const int corner, const int corner_delta) { MultiresDisplacementData *data = displacement->user_data; const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; const int effective_corner = (poly->totloop == 4) ? corner : poly_corner->corner; const int next_corner = (effective_corner + corner_delta + poly->totloop) % poly->totloop; return &data->mdisps[poly->loopstart + next_corner]; } BLI_INLINE eAverageWith read_displacement_grid(const MDisps *displacement_grid, const int grid_size, const float grid_u, const float grid_v, float r_tangent_D[3]) { if (displacement_grid->disps == NULL) { zero_v3(r_tangent_D); return AVERAGE_WITH_NONE; } const int x = (grid_u * (grid_size - 1) + 0.5f); const int y = (grid_v * (grid_size - 1) + 0.5f); copy_v3_v3(r_tangent_D, displacement_grid->disps[y * grid_size + x]); if (x == 0 && y == 0) { return AVERAGE_WITH_ALL; } if (x == 0) { return AVERAGE_WITH_PREV; } if (y == 0) { return AVERAGE_WITH_NEXT; } return AVERAGE_WITH_NONE; } static void average_convert_grid_coord_to_ptex(const MPoly *poly, const int corner, const float grid_u, const float grid_v, float *r_ptex_face_u, float *r_ptex_face_v) { if (poly->totloop == 4) { BKE_subdiv_rotate_grid_to_quad(corner, grid_u, grid_v, r_ptex_face_u, r_ptex_face_v); } else { BKE_subdiv_grid_uv_to_ptex_face_uv(grid_u, grid_v, r_ptex_face_u, r_ptex_face_v); } } static void average_construct_tangent_matrix(Subdiv *subdiv, const MPoly *poly, const int ptex_face_index, const int corner, const float u, const float v, float r_tangent_matrix[3][3]) { const bool is_quad = (poly->totloop == 4); const int quad_corner = is_quad ? corner : 0; float dummy_P[3], dPdu[3], dPdv[3]; BKE_subdiv_eval_limit_point_and_derivatives(subdiv, ptex_face_index, u, v, dummy_P, dPdu, dPdv); BKE_multires_construct_tangent_matrix(r_tangent_matrix, dPdu, dPdv, quad_corner); } static void average_read_displacement_tangent(MultiresDisplacementData *data, const MDisps *other_displacement_grid, const float grid_u, const float grid_v, float r_tangent_D[3]) { read_displacement_grid(other_displacement_grid, data->grid_size, grid_u, grid_v, r_tangent_D); } static void average_read_displacement_object(MultiresDisplacementData *data, const MDisps *displacement_grid, const float grid_u, const float grid_v, const int ptex_face_index, const int corner_index, float r_D[3]) { const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; /* Get (u, v) coordinate within the other ptex face which corresponds to * the grid coordinates. */ float u, v; average_convert_grid_coord_to_ptex(poly, corner_index, grid_u, grid_v, &u, &v); /* Construct tangent matrix which corresponds to partial derivatives * calculated for the other ptex face. */ float tangent_matrix[3][3]; average_construct_tangent_matrix( data->subdiv, poly, ptex_face_index, corner_index, u, v, tangent_matrix); /* Read displacement from other grid in a tangent space. */ float tangent_D[3]; average_read_displacement_tangent(data, displacement_grid, grid_u, grid_v, tangent_D); /* Convert displacement to object space. */ mul_v3_m3v3(r_D, tangent_matrix, tangent_D); } static void average_get_other_ptex_and_corner(MultiresDisplacementData *data, const int ptex_face_index, const int corner, const int corner_delta, int *r_other_ptex_face_index, int *r_other_corner_index) { const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; const int num_corners = poly->totloop; const bool is_quad = (num_corners == 4); const int poly_index = poly - data->mpoly; const int start_ptex_face_index = data->face_ptex_offset[poly_index]; *r_other_corner_index = (corner + corner_delta + num_corners) % num_corners; *r_other_ptex_face_index = is_quad ? start_ptex_face_index : start_ptex_face_index + *r_other_corner_index; } /* NOTE: Grid coordinates are relatiev to the other grid already. */ static void average_with_other(SubdivDisplacement *displacement, const int ptex_face_index, const int corner, const float grid_u, const float grid_v, const int corner_delta, float r_D[3]) { MultiresDisplacementData *data = displacement->user_data; const MDisps *other_displacement_grid = displacement_get_other_grid( displacement, ptex_face_index, corner, corner_delta); int other_ptex_face_index, other_corner_index; average_get_other_ptex_and_corner( data, ptex_face_index, corner, corner_delta, &other_ptex_face_index, &other_corner_index); /* Get displacement in object space. */ float other_D[3]; average_read_displacement_object(data, other_displacement_grid, grid_u, grid_v, other_ptex_face_index, other_corner_index, other_D); /* Average result with the other displacement vector. */ add_v3_v3(r_D, other_D); mul_v3_fl(r_D, 0.5f); } static void average_with_all(SubdivDisplacement *displacement, const int ptex_face_index, const int corner, const float UNUSED(grid_u), const float UNUSED(grid_v), float r_D[3]) { MultiresDisplacementData *data = displacement->user_data; const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; const int num_corners = poly->totloop; for (int corner_delta = 1; corner_delta < num_corners; corner_delta++) { average_with_other(displacement, ptex_face_index, corner, 0.0f, 0.0f, corner_delta, r_D); } } static void average_with_next(SubdivDisplacement *displacement, const int ptex_face_index, const int corner, const float grid_u, const float UNUSED(grid_v), float r_D[3]) { average_with_other(displacement, ptex_face_index, corner, 0.0f, grid_u, 1, r_D); } static void average_with_prev(SubdivDisplacement *displacement, const int ptex_face_index, const int corner, const float UNUSED(grid_u), const float grid_v, float r_D[3]) { average_with_other(displacement, ptex_face_index, corner, grid_v, 0.0f, -1, r_D); } static void average_displacement(SubdivDisplacement *displacement, eAverageWith average_with, const int ptex_face_index, const int corner, const float grid_u, const float grid_v, float r_D[3]) { switch (average_with) { case AVERAGE_WITH_ALL: average_with_all(displacement, ptex_face_index, corner, grid_u, grid_v, r_D); break; case AVERAGE_WITH_PREV: average_with_prev(displacement, ptex_face_index, corner, grid_u, grid_v, r_D); break; case AVERAGE_WITH_NEXT: average_with_next(displacement, ptex_face_index, corner, grid_u, grid_v, r_D); break; case AVERAGE_WITH_NONE: break; } } static int displacement_get_face_corner(MultiresDisplacementData *data, const int ptex_face_index, const float u, const float v) { const PolyCornerIndex *poly_corner = &data->ptex_poly_corner[ptex_face_index]; const MPoly *poly = &data->mpoly[poly_corner->poly_index]; const int num_corners = poly->totloop; const bool is_quad = (num_corners == 4); if (is_quad) { float dummy_corner_u, dummy_corner_v; return BKE_subdiv_rotate_quad_to_corner(u, v, &dummy_corner_u, &dummy_corner_v); } return poly_corner->corner; } static void initialize(SubdivDisplacement *displacement) { MultiresDisplacementData *data = displacement->user_data; multiresModifier_ensure_external_read(data->mesh, data->mmd); data->is_initialized = true; } static void eval_displacement(SubdivDisplacement *displacement, const int ptex_face_index, const float u, const float v, const float dPdu[3], const float dPdv[3], float r_D[3]) { MultiresDisplacementData *data = displacement->user_data; BLI_assert(data->is_initialized); const int grid_size = data->grid_size; /* Get displacement in tangent space. */ const MDisps *displacement_grid; float grid_u, grid_v; const int corner_of_quad = displacement_get_grid_and_coord( displacement, ptex_face_index, u, v, &displacement_grid, &grid_u, &grid_v); /* Read displacement from the current displacement grid and see if any * averaging is needed. */ float tangent_D[3]; eAverageWith average_with = read_displacement_grid( displacement_grid, grid_size, grid_u, grid_v, tangent_D); /* Convert it to the object space. */ float tangent_matrix[3][3]; BKE_multires_construct_tangent_matrix(tangent_matrix, dPdu, dPdv, corner_of_quad); mul_v3_m3v3(r_D, tangent_matrix, tangent_D); /* For the boundary points of grid average two (or all) neighbor grids. */ const int corner = displacement_get_face_corner(data, ptex_face_index, u, v); average_displacement(displacement, average_with, ptex_face_index, corner, grid_u, grid_v, r_D); } static void free_displacement(SubdivDisplacement *displacement) { MultiresDisplacementData *data = displacement->user_data; MEM_freeN(data->ptex_poly_corner); MEM_freeN(data); } /* TODO(sergey): This seems to be generally used information, which almost * worth adding to a subdiv itself, with possible cache of the value. */ static int count_num_ptex_faces(const Mesh *mesh) { int num_ptex_faces = 0; const MPoly *mpoly = mesh->mpoly; for (int poly_index = 0; poly_index < mesh->totpoly; poly_index++) { const MPoly *poly = &mpoly[poly_index]; num_ptex_faces += (poly->totloop == 4) ? 1 : poly->totloop; } return num_ptex_faces; } static void displacement_data_init_mapping(SubdivDisplacement *displacement, const Mesh *mesh) { MultiresDisplacementData *data = displacement->user_data; const MPoly *mpoly = mesh->mpoly; const int num_ptex_faces = count_num_ptex_faces(mesh); /* Allocate memory. */ data->ptex_poly_corner = MEM_malloc_arrayN( num_ptex_faces, sizeof(*data->ptex_poly_corner), "ptex poly corner"); /* Fill in offsets. */ int ptex_face_index = 0; PolyCornerIndex *ptex_poly_corner = data->ptex_poly_corner; for (int poly_index = 0; poly_index < mesh->totpoly; poly_index++) { const MPoly *poly = &mpoly[poly_index]; if (poly->totloop == 4) { ptex_poly_corner[ptex_face_index].poly_index = poly_index; ptex_poly_corner[ptex_face_index].corner = 0; ptex_face_index++; } else { for (int corner = 0; corner < poly->totloop; corner++) { ptex_poly_corner[ptex_face_index].poly_index = poly_index; ptex_poly_corner[ptex_face_index].corner = corner; ptex_face_index++; } } } } static void displacement_init_data(SubdivDisplacement *displacement, Subdiv *subdiv, Mesh *mesh, const MultiresModifierData *mmd) { MultiresDisplacementData *data = displacement->user_data; data->subdiv = subdiv; data->grid_size = BKE_subdiv_grid_size_from_level(mmd->totlvl); data->mesh = mesh; data->mmd = mmd; data->mpoly = mesh->mpoly; data->mdisps = CustomData_get_layer(&mesh->ldata, CD_MDISPS); data->face_ptex_offset = BKE_subdiv_face_ptex_offset_get(subdiv); data->is_initialized = false; displacement_data_init_mapping(displacement, mesh); } static void displacement_init_functions(SubdivDisplacement *displacement) { displacement->initialize = initialize; displacement->eval_displacement = eval_displacement; displacement->free = free_displacement; } void BKE_subdiv_displacement_attach_from_multires(Subdiv *subdiv, Mesh *mesh, const MultiresModifierData *mmd) { /* Make sure we don't have previously assigned displacement. */ BKE_subdiv_displacement_detach(subdiv); /* It is possible to have mesh without MDISPS layer. Happens when using * dynamic topology. */ if (!CustomData_has_layer(&mesh->ldata, CD_MDISPS)) { return; } /* Allocate all required memory. */ SubdivDisplacement *displacement = MEM_callocN(sizeof(SubdivDisplacement), "multires displacement"); displacement->user_data = MEM_callocN(sizeof(MultiresDisplacementData), "multires displacement data"); displacement_init_data(displacement, subdiv, mesh, mmd); displacement_init_functions(displacement); /* Finish. */ subdiv->displacement_evaluator = displacement; }
41.334061
98
0.619777
[ "mesh", "object", "vector" ]
a63e22d0202ef00c29d4c74803c1692fec756834
1,330
h
C
Engine/Math/KMeansClusteringKDTree.h
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
27
2015-09-03T18:41:03.000Z
2022-01-17T20:38:54.000Z
Engine/Math/KMeansClusteringKDTree.h
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
null
null
null
Engine/Math/KMeansClusteringKDTree.h
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
8
2015-02-23T10:04:30.000Z
2020-09-04T10:56:22.000Z
/* KMeansClusteringKDTree.h Written by Matthew Fisher */ #ifdef USE_ANN #ifdef USE_KDTREE struct KMeansClusterKDTree { public: void Init(UINT dimensionCount, const float *start); void FinishIteration(UINT dimensionCount, const float *fallback); __forceinline void AddEntry(const float *entry) { entries.PushEnd(entry); } VecNf center; Vector<const float*> entries; float assignmentError; }; class KMeansClusteringKDTree { public: void Cluster(const Vector<const float*> &elements, UINT dimensionCount, UINT clusterCount, UINT maxIterations = 0, double maxDelta = 0.0, bool verbose = true); __forceinline const VecNf& ClusterCenter(UINT clusterIndex) { return _clusters[clusterIndex].center; } __forceinline UINT ClusterCount() { return _clusters.Length(); } __forceinline const VecNf& QuantizeToNearestClusterCenter(const float *element) { return _clusters[QuantizeToNearestClusterIndex(element)].center; } UINT QuantizeToNearestClusterIndex(const float *element); private: void UpdateClusterTree(); void Iterate(const Vector<const float*> &elements); UINT _dimensionCount; KDTree _clusterTree; Vector< KMeansClusterKDTree > _clusters; mutable Vector<UINT> _indicesStorage; }; #endif #endif
24.62963
163
0.722556
[ "vector" ]
a643843f0e5dc4b1e7e07e4e2b5e0df4f7dd0d76
5,977
h
C
sfdb/base/db.h
ipr0/sfdb
1d4b96adf41324a399dbee30c804c35d4f1eecdd
[ "Apache-2.0" ]
5
2020-03-21T19:41:00.000Z
2022-03-09T20:24:02.000Z
sfdb/base/db.h
ipr0/sfdb
1d4b96adf41324a399dbee30c804c35d4f1eecdd
[ "Apache-2.0" ]
9
2020-03-24T22:22:44.000Z
2022-02-27T01:31:34.000Z
sfdb/base/db.h
ipr0/sfdb
1d4b96adf41324a399dbee30c804c35d4f1eecdd
[ "Apache-2.0" ]
2
2020-03-25T22:55:48.000Z
2020-04-26T14:35:41.000Z
/* * Copyright (c) 2019 Google LLC. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ #ifndef SFDB_BASE_DB_H_ #define SFDB_BASE_DB_H_ #include <map> #include <memory> #include <string> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "sfdb/base/vars.h" #include "sfdb/proto/pool.h" namespace sfdb { class TableIndex; // A database table. // // Not thread-safe. struct Table { const std::string name; std::unique_ptr<ProtoPool> pool; // A child of the Db's |pool|. const ::google::protobuf::Descriptor *const type; // Owned by |pool| std::vector<std::unique_ptr<::google::protobuf::Message>> rows; // Of type |type| std::map<std::string, TableIndex*> indices; // |pool| must own |type| Table(::absl::string_view name, std::unique_ptr<ProtoPool> &&pool, const ::google::protobuf::Descriptor *type) : name(name), pool(std::move(pool)), type(type) {} ~Table() = default; Table(const Table&) = delete; Table(Table&&) = delete; Table &operator=(const Table&) = delete; Table &operator=(Table&&) = delete; // Appends a row and updates all indices. void Insert(std::unique_ptr<::google::protobuf::Message> &&row); }; // An index over a database table. // // Not thread-safe. class TableIndex { public: // Comparator for sorting rows according to |columns|. // Immutable. struct Comparator { const TableIndex *const index; bool operator()( const std::pair<const ::google::protobuf::Message*, int> &apair, const std::pair<const ::google::protobuf::Message*, int> &bpair) const; }; Table *const t; const std::string name; const std::vector<const ::google::protobuf::FieldDescriptor*> columns; using TableIndexTree = std::set<std::pair<const ::google::protobuf::Message*, int>, Comparator>; TableIndexTree tree; TableIndex(Table *t, ::absl::string_view name, std::vector<const ::google::protobuf::FieldDescriptor*> &&columns) : t(t), name(name), columns(std::move(columns)), tree(Comparator{this}) {} ~TableIndex() = default; TableIndex(const TableIndex&) = delete; TableIndex(TableIndex&&) = delete; TableIndex &operator=(const TableIndex&) = delete; TableIndex &operator=(TableIndex&&) = delete; }; // A SQL database. // Has a name. Contains tables and indices. // // Not thread-safe. Use |mu| to lock the whole Db. struct Db { mutable ::absl::Mutex mu; const std::string name; std::unique_ptr<ProtoPool> pool; // thread-safe on its own std::map<std::string, std::unique_ptr<Table>> tables GUARDED_BY(mu); std::unique_ptr<Vars> vars GUARDED_BY(mu); std::map<std::string, std::unique_ptr<TableIndex>> table_indices GUARDED_BY(mu); Db(::absl::string_view name, Vars *root_vars); ~Db() = default; Db(const Db&) = delete; Db(const Db&&) = delete; Db &operator=(const Db&) = delete; Db &operator=(const Db&&) = delete; // These functions don't touch the |pool|. Deal with it separately. Table *FindTable(::absl::string_view name) const SHARED_LOCKS_REQUIRED(mu); Table *PutTable(::absl::string_view name, std::unique_ptr<ProtoPool> &&pool, const ::google::protobuf::Descriptor *type) EXCLUSIVE_LOCKS_REQUIRED(mu); bool DropTable(::absl::string_view name) EXCLUSIVE_LOCKS_REQUIRED(mu); // Caller owns retult object const Table *GetTableList() const SHARED_LOCKS_REQUIRED(mu); const Table *DescribeTable(::absl::string_view name) const SHARED_LOCKS_REQUIRED(mu); const ::google::protobuf::Descriptor* GetTableListTableType() const; const ::google::protobuf::Descriptor* GetDescribeTableType() const; // Table indices. TableIndex *FindIndex(::absl::string_view index_name) const SHARED_LOCKS_REQUIRED(mu); TableIndex *PutIndex(Table *t, ::absl::string_view index_name, std::vector<const ::google::protobuf::FieldDescriptor*> &&columns) EXCLUSIVE_LOCKS_REQUIRED(mu); bool DropIndex(::absl::string_view index_name) EXCLUSIVE_LOCKS_REQUIRED(mu); private: // TODO: move this functionality to separate class // This functions caches a list of tables into Table instance table_list_. void UpdateTableList() const; // This function creates a table to store the list of tables in this database. void CreateTableListTable() const; // This function creates/updates a table which will contain table structure description. // Should be called by internal functions when table is created or its structure changes. void UpdateTableDescritption(const Table* table); void RemoveTableDescritption(const std::string& table_name); // Variables to hold cached list of tables. mutable bool scheme_changed_; mutable std::unique_ptr<Table> table_list_ GUARDED_BY(mu); // Used to store tables descriptions for DESCRIBE <table> queries. std::map<std::string, std::unique_ptr<Table>> table_descs_ GUARDED_BY(mu); // This descriptor is used to avoid useless memory allocations const ::google::protobuf::Descriptor* const describe_table_descriptor_; }; } // namespace sfdb #endif // SFDB_BASE_DB_H_
36.224242
98
0.714238
[ "object", "vector" ]
a645b7dec680f0d638f89fc5a45efebf1fb15ab2
1,910
h
C
src/payload/payload.h
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
148
2015-01-01T18:32:25.000Z
2022-03-05T12:02:24.000Z
src/payload/payload.h
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
109
2015-02-11T16:33:49.000Z
2021-01-04T16:14:00.000Z
src/payload/payload.h
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
89
2015-02-04T00:39:29.000Z
2021-10-03T00:01:17.000Z
#ifndef __PAYLOAD_H__ #define __PAYLOAD_H__ #include "openxc.pb.h" #include <stdint.h> namespace openxc { namespace payload { /* Public: The available encoding formats for OpenXC payloads. */ typedef enum { JSON, PROTOBUF, } PayloadFormat; /* Public: Deserialize an OpenXC message from the given payload, using the given * format. * * The payload must be in one of the formats defined by the OpenXC message * format: * * https://github.com/openxc/openxc-message-format * * payload - The bytestream payload to parse a message from. * length - The length of the payload. * format - The expected format of the message serialized in the payload. * message - An output parameter, the object to store the deserialized message. * * Returns the number of bytes read for a complete message from the payload, if * any where found. */ size_t deserialize(uint8_t payload[], size_t length, PayloadFormat format, openxc_VehicleMessage* message); /* Public: Serialize an OpenXC message into a payload of bytes using the OpenXC * message format (https://github.com/openxc/openxc-message-format). * * message - The message to serialize. * payload - The buffer to store the payload - must be allocated by the caller. * length - The length of the payload buffer. * format - The serialization format to use in the payload (e.g. JSON, protocol * buffers, etc). * * Returns the number of bytes written to the payload. If the length is 0, an * error occurred while serializing. */ int serialize(openxc_VehicleMessage* message, uint8_t payload[], size_t length, PayloadFormat format); /* Public: Helper functions to wrap values in an openxc_DynamicField */ openxc_DynamicField wrapNumber(float value); openxc_DynamicField wrapString(const char* value); openxc_DynamicField wrapBoolean(bool value); } // namespace payload } // namespace openxc #endif // __PAYLOAD_H__
31.311475
80
0.741885
[ "object" ]
106f7a8a53103f7ecd2cd763274a8ecf8ade4f09
7,562
h
C
Pods/Headers/Public/ShareSDK2/QZoneConnection/ISSQZoneApp.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/ShareSDK2/QZoneConnection/ISSQZoneApp.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/ShareSDK2/QZoneConnection/ISSQZoneApp.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
///#begin zh-cn // // Created by ShareSDK.cn on 13-1-14. // 官网地址:http://www.ShareSDK.cn // 技术支持邮箱:support@sharesdk.cn // 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) // 商务QQ:4006852216 // Copyright (c) 2013年 ShareSDK.cn. All rights reserved. // ///#end ///#begin en // // Created by ShareSDK.cn on 13-1-14. // website:http://www.ShareSDK.cn // Support E-mail:support@sharesdk.cn // WeChat ID:ShareSDK (If publish a new version, we will be push the updates content of version to you. If you have any questions about the ShareSDK, you can get in touch through the WeChat with us, we will respond within 24 hours) // Business QQ:4006852216 // Copyright (c) 2013年 ShareSDK.cn. All rights reserved. // ///#end #import <Foundation/Foundation.h> #import <ShareSDKCoreService/ShareSDKCoreService.h> #import "SSQZoneUser.h" #import "SSQZoneErrorInfo.h" #import "SSQZoneShareInfo.h" #import <ShareSDK/ShareSDKPlugin.h> ///#begin zh-cn /** * @brief QQ空间应用 */ ///#end ///#begin en /** * @brief QZone App. */ ///#end @protocol ISSQZoneApp <ISSPlatformApp> ///#begin zh-cn /** * @brief 获取应用Key * * @return 应用Key */ ///#end ///#begin en /** * @brief Get app key. * * @return App key. */ ///#end - (NSString *) appKey; ///#begin zh-cn /** * @brief 获取应用ID * * @return 应用ID */ ///#end ///#begin en /** * @brief Get app id. * * @return App id. */ ///#end - (NSString *) appId; ///#begin zh-cn /** * @brief 获取SSO回调地址 * * @return SSO回调地址 */ ///#end ///#begin en /** * @brief Get SSO callback URL address. * * @return SSO callback url address. */ ///#end - (NSString *) ssoCallbackUrl; /** * 分享链接类型到QQ空间(包括普通链接,音频链接,视频链接) * * @param title 标题 * @param description 描述 * @param image 预览图 * @param result 回调 * * @since 2.12.2 */ - (void) shareWebPageToQzoneWithTitle:(NSString *)title description:(NSString *)description url:(NSString *)url image:(id<ISSCAttachment>)image result:(SSShareResultEvent)result; ///#begin zh-cn /** * * @brief 上传照片 * * @param pic 照片 * @param desc 描述 * @param title 标题 * @param albumid 相册ID,为nil则表示默认相册 */ ///#end ///#begin en /** * @brief Upload picture. * * @param pic Picture attachment object. * @param desc Description. * @param title Title string. * @param albumid Album ID,The default is nil indicates album */ ///#end - (void) uploadPic:(id<ISSCAttachment>)pic desc:(NSString *)desc title:(NSString *)title albumid:(NSString *)albumid result:(void(^)(BOOL result, id image, CMErrorInfo *error))result; #pragma - mark 弃用接口 - DEPRECATED_API ///#begin zh-cn /** * * @deprecated since 2.12.1 QQ空间授权如果在无安装的时候会直接进行web授权 * * @brief 设置是否打开网页授权,默认值为NO。旧时申请QQ空间应用是可以进行网页授权的,新申请的应用目前不允许网页授权 * * @return YES为打开网页授权开关,NO为关闭 */ ///#end ///#begin en /** * * @deprecated since 2.12.1 if QQ is not installed, it will excute web authorize directly * * @brief whether to allow QZone to authorize through Web(the default value is NO),the new QZone App is allow SSO only. * * @return YES means allow to authorize through Web,NO means no allow */ ///#end - (void) setIsAllowWebAuthorize:(BOOL)isAllowWebAuthorize; ///#begin zh-cn /** * * @deprecated since 2.12.1 QQ空间授权如果在无安装的时候会直接进行web授权 * * @brief 获取是否打开网页授权开关的值 * * @return YES为打开网页授权开关,NO为关闭 */ ///#end ///#begin en /** * * @deprecated since 2.12.1 if QQ is not installed, it will excute web authorize directly * * @brief Get the value of isAllowWebAuthorize * * @return YES means allow to authorize through Web,NO means no allow */ ///#end - (BOOL) isAllowWebAuthorize; ///#begin zh-cn /** * * @deprecated since 2.12.1 QQ空间分享链接类型请调用[shareWebPageToQzoneWithTitle:description:url:image:result:] * * @brief 定向分享 * * @param title 标题 * @param description 分享的内容描述 * @param shareUrl 分享连接 * @param pics 分享图片 * @param summary 分享的摘要内容 * @param url 分享的来源网站对应的网站地址url * @param act 默认为“进入应用” * @param result 返回回调 */ ///#end ///#begin en /** * * @deprecated since 2.12.1 QZone share webPage please use [shareWebPageToQzoneWithTitle:description:url:image:result:] instead * * @brief Send story. * * @param title Title string. * @param description Description. * @param shareUrl Share url. * @param pics a image list. * @param summary Summary string. * @param url URL string. * @param act Default is “进入应用” * @param result Result handler. */ ///#end - (void) sendStoryWithTitle:(NSString *)title description:(NSString *)description shareUrl:(NSString *)shareUrl pics:(NSArray *)pics summary:(NSString *)summary url:(NSString *)url act:(NSString *)act result:(SSShareResultEvent)result; ///#begin zh-cn /** * * @deprecated since 2.12.1 QQ空间分享链接类型请调用[shareWebPageToQzoneWithTitle:description:url:image:result:] * * @brief 添加分享 * * @param title 标题,最长36个中文字,超出部分会被截断。 * @param url 分享所在网页资源的链接,点击后跳转至第三方网页 * @param site 分享的来源网站名称,请填写网站申请接入时注册的网站名称 * @param fromUrl 分享的来源网站对应的网站地址url * @param comment 用户评论内容,最长40个中文字,超出部分会被截断。 * @param summary 所分享的网页资源的摘要内容,或者是网页的概要描述,最长80个中文字,超出部分会被截断。 * @param images 所分享的网页资源的代表性图片链接 * @param type 分享内容的类型。4表示网页;5表示视频(type=5时,必须传入playurl)。 * @param playUrl 长度限制为256字节。仅在type=5的时候有效,表示视频的swf播放地址。 * @param nswb 值为1时,表示分享不默认同步到微博,其他值或者不传此参数表示默认同步到微博。 * @param result 返回回调 */ ///#end ///#begin en /** * * @deprecated since 2.12.1 QZone share webPage please use [shareWebPageToQzoneWithTitle:description:url:image:result:] instead * * @brief Add share information. * * @param title Title, the longest 36 characters, the excess will be truncated. * @param url Sharing website where links to resources, click after the jump to a third party website * @param site Site name when sharing the source site, please fill out the application access to registration site name. * @param fromUrl Shared source site corresponding website address url * @param comment User Content, the longest 40 characters, the excess will be truncated. * @param summary Summary of content sharing web resources, or a summary description of the page, the longest 80 characters, the excess will be truncated. * @param images Representative image links shared web resources. * @param type Share types of content. 4 indicate that the page; 5 shows a video (type = 5, you must pass playurl). * @param playUrl Length is limited to 256 bytes. Type = 5 only when effective, which means that the video playback swf address. * @param nswb A value of 1, which means that the default is not synchronized to Tencent Weibo, other values ​​or do not pass this parameter indicates the default synchronized to Tencent Weibo. * @param result Result handler. */ ///#end - (void) addShareWithTitle:(NSString *)title url:(NSString *)url site:(NSString *)site fromUrl:(NSString *)fromUrl comment:(NSString *)comment summary:(NSString *)summary images:(NSArray *)images type:(NSNumber *)type playUrl:(NSString *)playUrl nswb:(NSNumber *)nswb result:(SSShareResultEvent)result; @end
27.007143
234
0.649696
[ "object" ]
1072494efe9144b51716fa05e5f87fc77bf66ea6
9,974
h
C
apps/eop1/timing/MA_v1.0_src/include/Utils.h
gaps-closure/top-level
11ccdbf753d4093bed1f6537b3fe675e3251076c
[ "BSD-3-Clause" ]
null
null
null
apps/eop1/timing/MA_v1.0_src/include/Utils.h
gaps-closure/top-level
11ccdbf753d4093bed1f6537b3fe675e3251076c
[ "BSD-3-Clause" ]
null
null
null
apps/eop1/timing/MA_v1.0_src/include/Utils.h
gaps-closure/top-level
11ccdbf753d4093bed1f6537b3fe675e3251076c
[ "BSD-3-Clause" ]
2
2020-03-30T05:47:37.000Z
2020-04-02T23:10:14.000Z
#pragma once #define earthRadiusKm 6371.0 #define _USE_MATH_DEFINES #include <math.h> #include <cmath> #include <fstream> #include <missions/MissionPlan.h> #include <nlohmann/json.hpp> #include <thread> #include <chrono> #include <missions/Detect.h> #ifndef UTILS_H #define UTILS_H using namespace uas; using json = nlohmann::json; using namespace std; using namespace std::chrono; // start all components on the same day! static long TIME_NOWMS = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); static long TIME_BASE = TIME_NOWMS - (TIME_NOWMS % (24 * 60 * 60 * 1000)); /** * @brief – Class responsible for providing useful functions that can be used by all systems. * * @author – Original Author - Mases Krikorian * @author – Last Edited By - Frederick Santiago * @date – 9/15/2020 * * @details – Utils provides various methods that can be used by all systems. Functions that include * putting a thread to sleep, various unit conversions and other useful mathematical calculations, handling mission plan, * and any other logic that can be useful for more than one system. All functions are provided statically. */ class Utils { public : /** * @brief put the calling thread to sleep forever * * @param VOID * * @return VOID */ static void sleep_forever() { std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::hours((std::numeric_limits<int>::max)())); } /** * @brief puts the calling thread to sleep for a given time in milliseconds * * @param milliseconds - duration of sleep in milliseconds * * @return VOID */ static void sleep_for(long milliseconds) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } /** * @brief given a storage of detections, add a new detection to the storage * * @param detects - a store of detects * @param j - new detection in json format * * @return VOID */ static void addDetections(Store<Detect *> &detects, json j) { Detect * detect; for (int i = 0; i < j.size(); i++) { string id = j[i]["TGT_ISRM_ID"]; if (detects.contains(id)) { detects.get(id)->setLocation(j[i]["lat"], j[i]["lon"], j[i]["alt"]); if (j[i]["bearing"] >= 0) { detects.get(id)->setBearing(j[i]["bearing"]); } if (! j[i]["classification"].empty()) { detects.get(id)->setClassification(j[i]["classification"]); } if (j[i]["speed"] >= 0) { detects.get(id)->setSpeed(j[i]["speed"]); } if (j[i]["confidence"] >= 0) { detects.get(id)->setConfidence(j[i]["confidence"]); } } else { detect = new Detect(j[i]["lat"], j[i]["lon"], j[i]["alt"], id, j[i]["speed"], j[i]["bearing"]); detects.add(id, detect); } } } /** * @brief Get the Detections Json object from a store of detects * * @param detects storage of detects using an ordered map * * @return json - an array of json object containing TGT_ISRM_ID, lat, lon, alt, bearing, speed * confidence, classification */ static json getDetectionsJson(Store<Detect *> &detects) { json body; json out = json::array(); for (auto key_value : detects.getMap()) { body["TGT_ISRM_ID"] = key_value.second->getId(); body["lat"] = key_value.second->getLat(); body["lon"] = key_value.second->getLon(); body["alt"] = key_value.second->getAlt(); body["bearing"] = key_value.second->getBearing(); body["speed"] = key_value.second->getSpeed(); body["confidence"] = key_value.second->getConfidence(); body["classification"] = key_value.second->getClassification(); out.push_back(body); body.clear(); } return out; } /** * @brief given a json input following a mission plan format, this function will extract the required values * for mission plan, vehicle plan, and sensor plan * * @param input - json object with data vehicle plan (waypoints) and sensor plan (actions at waypoints) * * @return MissionPlan* - a pointer to a new MissionPlan instance that can be added to a store */ static MissionPlan* parsePlan(json const &input) { string mp = "missionPlan"; string wp = "wayPoints"; string vp = "vehiclePlan"; int size = input[mp][vp][wp].size(); MissionPlan *plan = new MissionPlan(input[mp]["missionPlanId"], size); for (int i = 0; i < size; i++) { plan->addSchedule ( input[mp][vp][wp][i]["wayPointId"], input[mp][vp][wp][i]["x"], input[mp][vp][wp][i]["y"], input[mp][vp][wp][i]["z"] ); } plan->getSchedule(size - 1)->setEgressPoint(true); json sp = input[mp]["sensorPlan"]; string actions = "actions"; string wayPointId = "wayPointId"; string actionType = "actionType"; for (int i = 0; i < sp[actions].size(); i++) { string wpid = sp[actions][i][wayPointId]; string aType = sp[actions][i][actionType]; if (plan->getSchedule(wpid) != nullptr) { plan->getSchedule(wpid)->setPhase(aType); } } return plan; } /** * @brief given 2 sets of latitude and longtitude in degrees, calculate the distance between them in kilometers * * @param lat1d - latitdue in degrees of position 1 * @param lon1d - longtitude in degrees of position 1 * @param lat2d - latitude in degrees of position 2 * @param lon2d - longtitude in degrees of position 2 * * @return double - distance betwen the 2 points */ static double distanceEarth(double lat1d, double lon1d, double lat2d, double lon2d) { double lat1r, lon1r, lat2r, lon2r, u, v; lat1r = deg2rad(lat1d); lon1r = deg2rad(lon1d); lat2r = deg2rad(lat2d); lon2r = deg2rad(lon2d); u = sin((lat2r - lat1r) / 2); v = sin((lon2r - lon1r) / 2); return 2.0 * earthRadiusKm * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v)); } /** * @brief convert degrees to radians * * @param deg - value in degrees * * @return double - convert value of degrees to radians */ static double deg2rad(double deg) { return (deg * M_PI / 180); } /** * @brief given 2 sets of latitude and longtitude in degrees, calculate the bearing between them in degrees * * @param lat - latitdue in degrees of position 1 * @param lon - longtitude in degrees of position 1 * @param lat2 - latitdue in degrees of position 2 * @param lon2 - longtitude in degrees of position 2 * * @return double - bearing betweem the two points in degrees */ static double bearing(double lat, double lon, double lat2, double lon2) { double teta1 = deg2rad(lat); double teta2 = deg2rad(lat2); double delta1 = deg2rad(lat2 - lat); double delta2 = deg2rad(lon2 - lon); //==================Heading Formula Calculation================// double y = sin(delta2) * cos(teta2); double x = cos(teta1)*sin(teta2) - sin(teta1)*cos(teta2)*cos(delta2); double brng = atan2(y, x); brng = rad2deg(brng);// radians to degrees brng = (((int)brng + 360) % 360); return brng; } /** * @brief convert radians to degrees * * @param rad - value to be converted to radians * * @return double - value converted to radians */ static double rad2deg(double rad) { return (rad * 180 / M_PI); } /** * @brief given a distance, calculate if the distance is within a certain constant * * @param distance - current distance to another point * @param within - considered near is distance is within this value * * @return true if distance is within the value * */ static bool isNear(const double &distance, const double &within) { if (distance - within <= 0) { return true; } return false; } /** * @brief Override the referrence value of the latitude and longtitude based on current location and speed of unit * * @param lat - current latitude in degrees of unit * @param lon - current longtitude in degrees of unit * @param waypointLat - destination latitude in degrees * @param waypointLon - desttination longtitude in degrees * @param s - speed of unit in km / s */ static void getNextLatLon(double &lat, double &lon, const double &waypointLat, const double &waypointLon, const double &s) { double d = (s); double tc = Utils::deg2rad(Utils::bearing(lat, lon, waypointLat, waypointLon )); double dist = d / 6371; double brng = tc; double lat1 = deg2rad(lat); double lon1 = deg2rad(lon); double lat2 = asin(sin(lat1)*cos(dist) + cos(lat1)*sin(dist)*cos(brng)); double a = atan2(sin(brng)*sin(dist)*cos(lat1), cos(dist) - sin(lat1)*sin(lat2)); double lon2 = lon1 + a; lat = rad2deg(lat2); lon = rad2deg(lon2); } /** * @brief will look for the default json locally * * @param VOID * * @return default json * */ static json loadDefaultConfig() { std::ifstream k("config/defaultConfig.json"); json j; k >> j; k.close(); return j; } /** * @brief will look for the local json that corresponds to a configPlan * * @param configPlan - the configuration plan that is requested to be loaded * * @return the loaded json * */ static json loadConfig(json configPlan) { string config = "config/"; string jsonFile = ".json"; string configFile = configPlan["configPlan"]; string str = config + configFile + jsonFile; std::ifstream k(str); json j; if (!k) return j; k >> j; k.close(); return j; } static long getTimestamp() { return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - TIME_BASE; } static long getElapsedTime(json j) { auto ms_since_epoch = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - TIME_BASE; return ms_since_epoch - j["timestamp"].get<long>(); } static void logElapsedTime(json j, string component, string msg) { static std::map<std::string, ofstream *> streamMap; string fname = component + "-timing.csv"; ofstream *of; map<string, ofstream *>::iterator it = streamMap.find(component); if (it != streamMap.end()) { of = it->second; } else { of = new ofstream(); of->open(fname); streamMap[component] = of; } *of << getTimestamp() << "," << component << ",received," << msg << ",in," << Utils::getElapsedTime(j) << "\n" << std::flush; } }; #endif
29.773134
129
0.664428
[ "object" ]
107642dd4c45adeec09122742d5ccbcc455865a5
1,461
h
C
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/attribute/ResolutionSyntax.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
22
2019-06-13T01:16:44.000Z
2022-03-29T02:42:39.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/attribute/ResolutionSyntax.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
26
2019-09-20T06:46:05.000Z
2022-03-11T08:07:14.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/attribute/ResolutionSyntax.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
14
2019-07-15T06:42:39.000Z
2022-02-15T10:32:28.000Z
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_print_attribute_ResolutionSyntax__ #define __javax_print_attribute_ResolutionSyntax__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> extern "Java" { namespace javax { namespace print { namespace attribute { class ResolutionSyntax; } } } } class javax::print::attribute::ResolutionSyntax : public ::java::lang::Object { public: ResolutionSyntax(jint, jint, jint); virtual jboolean equals(::java::lang::Object *); virtual jint getCrossFeedResolution(jint); public: // actually protected virtual jint getCrossFeedResolutionDphi(); public: virtual jint getFeedResolution(jint); public: // actually protected virtual jint getFeedResolutionDphi(); public: virtual JArray< jint > * getResolution(jint); virtual jint hashCode(); virtual jboolean lessThanOrEquals(::javax::print::attribute::ResolutionSyntax *); virtual ::java::lang::String * toString(); virtual ::java::lang::String * toString(jint, ::java::lang::String *); private: static const jlong serialVersionUID = 2706743076526672017LL; public: static const jint DPCM = 254; static const jint DPI = 100; private: jint __attribute__((aligned(__alignof__( ::java::lang::Object)))) crossFeedResolution; jint feedResolution; public: static ::java::lang::Class class$; }; #endif // __javax_print_attribute_ResolutionSyntax__
25.189655
88
0.727584
[ "object" ]
107c0aa6896ed389594e230592bbadae817d5cec
424
h
C
StdPatch/src/main/Mods.h
2010kohtep/StdPatch
a968726034d235a0a7fedb0a330bf8a81ed6eb0b
[ "MIT" ]
10
2017-02-27T03:26:49.000Z
2022-03-22T17:35:38.000Z
StdPatch/src/main/Mods.h
2010kohtep/StdPatch
a968726034d235a0a7fedb0a330bf8a81ed6eb0b
[ "MIT" ]
5
2018-12-05T20:42:44.000Z
2021-09-04T19:27:17.000Z
StdPatch/src/main/Mods.h
2010kohtep/StdPatch
a968726034d235a0a7fedb0a330bf8a81ed6eb0b
[ "MIT" ]
3
2020-03-08T19:23:09.000Z
2021-02-10T10:51:35.000Z
#pragma once #include <vector> struct IMod; class CModMgr { private: std::vector<IMod *> m_Mods; public: CModMgr() { m_Mods = std::vector<IMod *>(); } void RegisterMod(IMod *mod); void InitMods(); }; extern CModMgr gModMgr; struct IMod { IMod() { gModMgr.RegisterMod(this); } virtual ~IMod() {} virtual const char *GetName() abstract; virtual bool Find() abstract; virtual bool Patch() abstract; };
11.777778
40
0.665094
[ "vector" ]
107ca1570c0b268a481ddc929470f76c44491b84
24,862
c
C
Modules/ThirdParty/HDF5/src/itkhdf5/src/H5Pgcpl.c
dave3d/ITK
c1f266aa75ef95671ed4ca2062c97faad130cde1
[ "Apache-2.0" ]
945
2015-01-09T00:43:52.000Z
2022-03-30T08:23:02.000Z
Modules/ThirdParty/HDF5/src/itkhdf5/src/H5Pgcpl.c
ebrahimebrahim/ITK
3a63e79d17addbc8903270f363fac6c5b89cdf53
[ "Apache-2.0" ]
2,354
2015-02-04T21:54:21.000Z
2022-03-31T20:58:21.000Z
Modules/ThirdParty/HDF5/src/itkhdf5/src/H5Pgcpl.c
ebrahimebrahim/ITK
3a63e79d17addbc8903270f363fac6c5b89cdf53
[ "Apache-2.0" ]
566
2015-01-04T14:26:57.000Z
2022-03-18T20:33:18.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: H5Pgcpl.c * August 29 2006 * Quincey Koziol * * Purpose: Group creation property list class routines * *------------------------------------------------------------------------- */ /****************/ /* Module Setup */ /****************/ #include "H5Pmodule.h" /* This source code file is part of the H5P module */ /***********/ /* Headers */ /***********/ #include "H5private.h" /* Generic Functions */ #include "H5Eprivate.h" /* Error handling */ #include "H5Gprivate.h" /* Groups */ #include "H5Iprivate.h" /* IDs */ #include "H5Oprivate.h" /* Object headers */ #include "H5Ppkg.h" /* Property lists */ /****************/ /* Local Macros */ /****************/ /* ========= Group Creation properties ============ */ #define H5G_CRT_GROUP_INFO_ENC H5P__gcrt_group_info_enc #define H5G_CRT_GROUP_INFO_DEC H5P__gcrt_group_info_dec #define H5G_CRT_LINK_INFO_ENC H5P__gcrt_link_info_enc #define H5G_CRT_LINK_INFO_DEC H5P__gcrt_link_info_dec /******************/ /* Local Typedefs */ /******************/ /********************/ /* Package Typedefs */ /********************/ /********************/ /* Local Prototypes */ /********************/ /* Property class callbacks */ static herr_t H5P__gcrt_reg_prop(H5P_genclass_t *pclass); /* Property callbacks */ static herr_t H5P__gcrt_group_info_enc(const void *value, void **_pp, size_t *size); static herr_t H5P__gcrt_group_info_dec(const void **_pp, void *value); static herr_t H5P__gcrt_link_info_enc(const void *value, void **_pp, size_t *size); static herr_t H5P__gcrt_link_info_dec(const void **_pp, void *value); /*********************/ /* Package Variables */ /*********************/ /* Group creation property list class library initialization object */ const H5P_libclass_t H5P_CLS_GCRT[1] = {{ "group create", /* Class name for debugging */ H5P_TYPE_GROUP_CREATE, /* Class type */ &H5P_CLS_OBJECT_CREATE_g, /* Parent class */ &H5P_CLS_GROUP_CREATE_g, /* Pointer to class */ &H5P_CLS_GROUP_CREATE_ID_g, /* Pointer to class ID */ &H5P_LST_GROUP_CREATE_ID_g, /* Pointer to default property list ID */ H5P__gcrt_reg_prop, /* Default property registration routine */ NULL, /* Class creation callback */ NULL, /* Class creation callback info */ NULL, /* Class copy callback */ NULL, /* Class copy callback info */ NULL, /* Class close callback */ NULL /* Class close callback info */ }}; /*****************************/ /* Library Private Variables */ /*****************************/ /*******************/ /* Local Variables */ /*******************/ /* Property value defaults */ static const H5O_ginfo_t H5G_def_ginfo_g = H5G_CRT_GROUP_INFO_DEF; /* Default group info settings */ static const H5O_linfo_t H5G_def_linfo_g = H5G_CRT_LINK_INFO_DEF; /* Default link info settings */ /*------------------------------------------------------------------------- * Function: H5P__gcrt_reg_prop * * Purpose: Initialize the group creation property list class * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * October 31, 2006 *------------------------------------------------------------------------- */ static herr_t H5P__gcrt_reg_prop(H5P_genclass_t *pclass) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Register group info property */ if(H5P__register_real(pclass, H5G_CRT_GROUP_INFO_NAME, H5G_CRT_GROUP_INFO_SIZE, &H5G_def_ginfo_g, NULL, NULL, NULL, H5G_CRT_GROUP_INFO_ENC, H5G_CRT_GROUP_INFO_DEC, NULL, NULL, NULL, NULL) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTINSERT, FAIL, "can't insert property into class") /* Register link info property */ if(H5P__register_real(pclass, H5G_CRT_LINK_INFO_NAME, H5G_CRT_LINK_INFO_SIZE, &H5G_def_linfo_g, NULL, NULL, NULL, H5G_CRT_LINK_INFO_ENC, H5G_CRT_LINK_INFO_DEC, NULL, NULL, NULL, NULL) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTINSERT, FAIL, "can't insert property into class") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5P__gcrt_reg_prop() */ /*------------------------------------------------------------------------- * Function: H5Pset_local_heap_size_hint * * Purpose: Set the "size hint" for creating local heaps for a group. * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * August 29, 2005 *------------------------------------------------------------------------- */ herr_t H5Pset_local_heap_size_hint(hid_t plist_id, size_t size_hint) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE2("e", "iz", plist_id, size_hint); /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get value */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") /* Update field */ H5_CHECKED_ASSIGN(ginfo.lheap_size_hint, uint32_t, size_hint, size_t); /* Set value */ if(H5P_set(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTSET, FAIL, "can't set group info") done: FUNC_LEAVE_API(ret_value) } /* end H5Pset_local_heap_size_hint() */ /*------------------------------------------------------------------------- * Function: H5Pget_local_heap_size_hint * * Purpose: Returns the local heap size hint, which is used for creating * groups * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * August 29, 2005 *------------------------------------------------------------------------- */ herr_t H5Pget_local_heap_size_hint(hid_t plist_id, size_t *size_hint /*out*/) { herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE2("e", "ix", plist_id, size_hint); if(size_hint) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get value */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") /* Update field */ *size_hint = ginfo.lheap_size_hint; } /* end if */ done: FUNC_LEAVE_API(ret_value) } /* end H5Pget_local_heap_size_hint() */ /*------------------------------------------------------------------------- * Function: H5Pset_link_phase_change * * Purpose: Set the maximum # of links to store "compactly" and the * minimum # of links to store "densely". (These should * overlap). * * Note: Currently both of these must be updated at the same time. * * Note: Come up with better name & description! -QAK * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * August 29, 2005 *------------------------------------------------------------------------- */ herr_t H5Pset_link_phase_change(hid_t plist_id, unsigned max_compact, unsigned min_dense) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE3("e", "iIuIu", plist_id, max_compact, min_dense); /* Range check values */ if(max_compact < min_dense) HGOTO_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "max compact value must be >= min dense value") if(max_compact > 65535) HGOTO_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "max compact value must be < 65536") if(min_dense > 65535) HGOTO_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "min dense value must be < 65536") /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get group info */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") /* Update fields */ if(max_compact != H5G_CRT_GINFO_MAX_COMPACT || min_dense != H5G_CRT_GINFO_MIN_DENSE) ginfo.store_link_phase_change = TRUE; else ginfo.store_link_phase_change = FALSE; ginfo.max_compact = (uint16_t)max_compact; ginfo.min_dense = (uint16_t)min_dense; /* Set group info */ if(H5P_set(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTSET, FAIL, "can't set group info") done: FUNC_LEAVE_API(ret_value) } /* end H5Pset_link_phase_change() */ /*------------------------------------------------------------------------- * Function: H5Pget_link_phase_change * * Purpose: Returns the max. # of compact links & the min. # of dense * links, which are used for storing groups * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * August 29, 2005 *------------------------------------------------------------------------- */ herr_t H5Pget_link_phase_change(hid_t plist_id, unsigned *max_compact /*out*/, unsigned *min_dense /*out*/) { herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE3("e", "ixx", plist_id, max_compact, min_dense); /* Get values */ if(max_compact || min_dense) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get group info */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") if(max_compact) *max_compact = ginfo.max_compact; if(min_dense) *min_dense = ginfo.min_dense; } /* end if */ done: FUNC_LEAVE_API(ret_value) } /* end H5Pget_link_phase_change() */ /*------------------------------------------------------------------------- * Function: H5Pset_est_link_info * * Purpose: Set the estimates for the number of entries and length of each * entry name in a group. * * Note: Currently both of these must be updated at the same time. * * Note: EST_NUM_ENTRIES applies only when the number of entries is less * than the MAX_COMPACT # of entries (from H5Pset_link_phase_change). * * Note: Come up with better name & description? -QAK * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * September 6, 2005 *------------------------------------------------------------------------- */ herr_t H5Pset_est_link_info(hid_t plist_id, unsigned est_num_entries, unsigned est_name_len) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE3("e", "iIuIu", plist_id, est_num_entries, est_name_len); /* Range check values */ if(est_num_entries > 65535) HGOTO_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "est. number of entries must be < 65536") if(est_name_len > 65535) HGOTO_ERROR(H5E_ARGS, H5E_BADRANGE, FAIL, "est. name length must be < 65536") /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get group info */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") /* Update fields */ if(est_num_entries != H5G_CRT_GINFO_EST_NUM_ENTRIES || est_name_len != H5G_CRT_GINFO_EST_NAME_LEN) ginfo.store_est_entry_info = TRUE; else ginfo.store_est_entry_info = FALSE; ginfo.est_num_entries = (uint16_t)est_num_entries; ginfo.est_name_len = (uint16_t)est_name_len; /* Set group info */ if(H5P_set(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTSET, FAIL, "can't set group info") done: FUNC_LEAVE_API(ret_value) } /* end H5Pset_est_link_info() */ /*------------------------------------------------------------------------- * Function: H5Pget_est_link_info * * Purpose: Returns the est. # of links in a group & the est. length of * the name of each link. * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * September 6, 2005 *------------------------------------------------------------------------- */ herr_t H5Pget_est_link_info(hid_t plist_id, unsigned *est_num_entries /*out*/, unsigned *est_name_len /*out*/) { herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE3("e", "ixx", plist_id, est_num_entries, est_name_len); /* Get values */ if(est_num_entries || est_name_len) { H5P_genplist_t *plist; /* Property list pointer */ H5O_ginfo_t ginfo; /* Group information structure */ /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get group info */ if(H5P_get(plist, H5G_CRT_GROUP_INFO_NAME, &ginfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get group info") if(est_num_entries) *est_num_entries = ginfo.est_num_entries; if(est_name_len) *est_name_len = ginfo.est_name_len; } /* end if */ done: FUNC_LEAVE_API(ret_value) } /* end H5Pget_est_link_info() */ /*------------------------------------------------------------------------- * Function: H5Pset_link_creation_order * * Purpose: Set the flags for creation order of links in a group * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * September 12, 2006 *------------------------------------------------------------------------- */ herr_t H5Pset_link_creation_order(hid_t plist_id, unsigned crt_order_flags) { H5P_genplist_t *plist; /* Property list pointer */ H5O_linfo_t linfo; /* Link information structure */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE2("e", "iIu", plist_id, crt_order_flags); /* Check for bad combination of flags */ if(!(crt_order_flags & H5P_CRT_ORDER_TRACKED) && (crt_order_flags & H5P_CRT_ORDER_INDEXED)) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "tracking creation order is required for index") /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get link info */ if(H5P_get(plist, H5G_CRT_LINK_INFO_NAME, &linfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get link info") /* Update fields */ linfo.track_corder = (hbool_t)((crt_order_flags & H5P_CRT_ORDER_TRACKED) ? TRUE : FALSE); linfo.index_corder = (hbool_t)((crt_order_flags & H5P_CRT_ORDER_INDEXED) ? TRUE : FALSE); /* Set link info */ if(H5P_set(plist, H5G_CRT_LINK_INFO_NAME, &linfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTSET, FAIL, "can't set link info") done: FUNC_LEAVE_API(ret_value) } /* end H5Pset_link_creation_order() */ /*------------------------------------------------------------------------- * Function: H5Pget_link_creation_order * * Purpose: Returns the flag indicating that creation order is tracked * for links in a group. * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * September 12, 2006 *------------------------------------------------------------------------- */ herr_t H5Pget_link_creation_order(hid_t plist_id, unsigned *crt_order_flags /*out*/) { herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE2("e", "ix", plist_id, crt_order_flags); /* Get values */ if(crt_order_flags) { H5P_genplist_t *plist; /* Property list pointer */ H5O_linfo_t linfo; /* Link information structure */ /* Reset the value to return */ *crt_order_flags = 0; /* Get the plist structure */ if(NULL == (plist = H5P_object_verify(plist_id, H5P_GROUP_CREATE))) HGOTO_ERROR(H5E_ATOM, H5E_BADATOM, FAIL, "can't find object for ID") /* Get link info */ if(H5P_get(plist, H5G_CRT_LINK_INFO_NAME, &linfo) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get link info") *crt_order_flags |= linfo.track_corder ? H5P_CRT_ORDER_TRACKED : 0; *crt_order_flags |= linfo.index_corder ? H5P_CRT_ORDER_INDEXED : 0; } /* end if */ done: FUNC_LEAVE_API(ret_value) } /* end H5Pget_link_creation_order() */ /*------------------------------------------------------------------------- * Function: H5P__gcrt_group_info_enc * * Purpose: Callback routine which is called whenever the group * property in the dataset access property list is * encoded. * * Return: Success: Non-negative * Failure: Negative * * Programmer: Mohamad Chaarawi * Monday, October 10, 2011 * *------------------------------------------------------------------------- */ static herr_t H5P__gcrt_group_info_enc(const void *value, void **_pp, size_t *size) { const H5O_ginfo_t *ginfo = (const H5O_ginfo_t *)value; /* Create local aliases for values */ uint8_t **pp = (uint8_t **)_pp; FUNC_ENTER_STATIC_NOERR if(NULL != *pp) { UINT32ENCODE(*pp, ginfo->lheap_size_hint) UINT16ENCODE(*pp, ginfo->max_compact) UINT16ENCODE(*pp, ginfo->min_dense) UINT16ENCODE(*pp, ginfo->est_num_entries) UINT16ENCODE(*pp, ginfo->est_name_len) } /* end if */ *size += sizeof(uint16_t) * 4 + sizeof(uint32_t); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5P__gcrt_group_info_enc() */ /*------------------------------------------------------------------------- * Function: H5P__gcrt_group_info_dec * * Purpose: Callback routine which is called whenever the group info * property in the dataset access property list is * decoded. * * Return: Success: Non-negative * Failure: Negative * * Programmer: Mohamad Chaarawi * Monday, October 10, 2011 * *------------------------------------------------------------------------- */ static herr_t H5P__gcrt_group_info_dec(const void **_pp, void *_value) { H5O_ginfo_t *ginfo = (H5O_ginfo_t *)_value; /* Group info settings */ const uint8_t **pp = (const uint8_t **)_pp; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Set property to default value */ HDmemset(ginfo, 0, sizeof(H5O_ginfo_t)); *ginfo = H5G_def_ginfo_g; UINT32DECODE(*pp, ginfo->lheap_size_hint) UINT16DECODE(*pp, ginfo->max_compact) UINT16DECODE(*pp, ginfo->min_dense) UINT16DECODE(*pp, ginfo->est_num_entries) UINT16DECODE(*pp, ginfo->est_name_len) /* Update fields */ if(ginfo->max_compact != H5G_CRT_GINFO_MAX_COMPACT || ginfo->min_dense != H5G_CRT_GINFO_MIN_DENSE) ginfo->store_link_phase_change = TRUE; else ginfo->store_link_phase_change = FALSE; if(ginfo->est_num_entries != H5G_CRT_GINFO_EST_NUM_ENTRIES || ginfo->est_name_len != H5G_CRT_GINFO_EST_NAME_LEN) ginfo->store_est_entry_info = TRUE; else ginfo->store_est_entry_info = FALSE; FUNC_LEAVE_NOAPI(ret_value) } /* end H5P__gcrt_group_info_dec() */ /*------------------------------------------------------------------------- * Function: H5P__gcrt_link_info_enc * * Purpose: Callback routine which is called whenever the link * property in the dataset access property list is * encoded. * * Return: Success: Non-negative * Failure: Negative * * Programmer: Mohamad Chaarawi * Monday, October 10, 2011 * *------------------------------------------------------------------------- */ static herr_t H5P__gcrt_link_info_enc(const void *value, void **_pp, size_t *size) { const H5O_linfo_t *linfo = (const H5O_linfo_t *)value; /* Create local aliases for values */ uint8_t **pp = (uint8_t **)_pp; FUNC_ENTER_STATIC_NOERR if(NULL != *pp) { unsigned crt_order_flags = 0; crt_order_flags |= linfo->track_corder ? H5P_CRT_ORDER_TRACKED : 0; crt_order_flags |= linfo->index_corder ? H5P_CRT_ORDER_INDEXED : 0; /* Encode the size of unsigned*/ *(*pp)++ = (uint8_t)sizeof(unsigned); /* Encode the value */ H5_ENCODE_UNSIGNED(*pp, crt_order_flags) } /* end if */ *size += (1 + sizeof(unsigned)); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5P__gcrt_link_info_enc() */ /*------------------------------------------------------------------------- * Function: H5P__gcrt_link_info_dec * * Purpose: Callback routine which is called whenever the link info * property in the dataset access property list is * decoded. * * Return: Success: Non-negative * Failure: Negative * * Programmer: Mohamad Chaarawi * Monday, October 10, 2011 * *------------------------------------------------------------------------- */ static herr_t H5P__gcrt_link_info_dec(const void **_pp, void *_value) { H5O_linfo_t *linfo = (H5O_linfo_t *)_value; /* Link info settings */ const uint8_t **pp = (const uint8_t **)_pp; unsigned crt_order_flags; unsigned enc_size; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC enc_size = *(*pp)++; if(enc_size != sizeof(unsigned)) HGOTO_ERROR(H5E_PLIST, H5E_BADVALUE, FAIL, "unsigned value can't be decoded") /* Set property to default value */ HDmemset(linfo, 0, sizeof(H5O_linfo_t)); *linfo = H5G_def_linfo_g; H5_DECODE_UNSIGNED(*pp, crt_order_flags) /* Update fields */ linfo->track_corder = (hbool_t)((crt_order_flags & H5P_CRT_ORDER_TRACKED) ? TRUE : FALSE); linfo->index_corder = (hbool_t)((crt_order_flags & H5P_CRT_ORDER_INDEXED) ? TRUE : FALSE); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5P__gcrt_link_info_dec() */
35.165488
104
0.571877
[ "object" ]
107fe2ee6e977aa7abc0f73caaafb781d6b646fd
2,036
h
C
client/interface.h
BigTows/Hospital
3a44141ee2618f77ece4abeb6c99a8ac50678709
[ "BSD-3-Clause" ]
1
2017-06-14T16:19:30.000Z
2017-06-14T16:19:30.000Z
client/interface.h
BigTows/Hospital
3a44141ee2618f77ece4abeb6c99a8ac50678709
[ "BSD-3-Clause" ]
1
2020-12-02T11:14:33.000Z
2020-12-03T08:21:32.000Z
client/interface.h
BigTows/Hospital
3a44141ee2618f77ece4abeb6c99a8ac50678709
[ "BSD-3-Clause" ]
null
null
null
#ifndef INTERFACE_H #define INTERFACE_H #include <QGraphicsScene> #include <QGraphicsView> #include <QtNetwork> #include <QLineEdit> #include <QPushButton> #include <QListWidget> #include <vector> #include <QCalendarWidget> #include <QLabel> #include "user.h" #include <QFrame> #include <QVBoxLayout> #include <windows.h> class Interface: public QGraphicsView { Q_OBJECT public: Interface(QWidget * parent = 0); void auth(); void getRecords(bool from, QDate date); void hide_auth_window(); void fill_list(); void draw_calendar(); void addHistory(); void hideListfucn(); void loadPicture(QString photo); void getUser(); void updateCalendar(); void fillProfile(); void blink(); void getHistory(); private: QGraphicsScene * scene; QLineEdit * editLogin; QLineEdit * editPassword; QListWidget * list; QPushButton * bt; QNetworkAccessManager * net; QCalendarWidget * calendar; QPushButton * showButton; QPushButton * backButton; QLabel * label; QFrame * frame; QTimer * timer; QVBoxLayout * layout; QPushButton * historyButton; std::vector<QString> massive; QString token = ""; QString str_getText = ""; QEventLoop loop; std::vector<MyUser> mas; QList< QLabel*> mas_label; MyUser SelectedUser; QByteArray postData; QNetworkRequest request; private slots: void onAuthResult(QNetworkReply *reply); void ongetRecordsResult(QNetworkReply *reply); void onloadPictureResult(QNetworkReply *reply); void ongetUserResult(QNetworkReply *reply); void ongetHistoryResult(QNetworkReply *reply); void on_EnterButton_Clicked(); void itemDoubleClicked(QListWidgetItem* item); void itemClicked(QListWidgetItem* item); void calendarSelection(); void onbackButtonClick(); void onTimerTimeout(); void onhistoryButtonClick(); void test(); }; #endif // INTERFACE_H
24.238095
52
0.66945
[ "vector" ]
1084677162162d57ec55b85af117e3b9f78d022a
2,495
h
C
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zpoint.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zpoint.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zpoint.h
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/**@file zpoint.h * @brief 3D point class * @author Ting Zhao */ #ifndef ZPOINT_H #define ZPOINT_H #include <iostream> #include <string> #include "zqtheader.h" #include "zdocumentable.h" #include "zstackdrawable.h" class ZPoint : public ZDocumentable, public ZStackDrawable { public: ZPoint(); ZPoint(double x, double y, double z); ZPoint(const double *pt); ZPoint(const ZPoint &pt); virtual const std::string& className() const; public: inline void set(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } inline void set(const ZPoint &pt) { set(pt.x(), pt.y(), pt.z()); } inline double x() const { return m_x; } inline double y() const { return m_y; } inline double z() const { return m_z; } inline double* xRef() { return &m_x; } inline double* yRef() { return &m_y; } inline double* zRef() { return &m_z; } const double& operator[] (int index) const; double& operator[] (int index); ZPoint& operator= (const ZPoint &pt); inline void setX(double x) { m_x = x; } inline void setY(double y) { m_y = y; } inline void setZ(double z) { m_z = z; } double distanceTo(const ZPoint &pt) const; double distanceTo(double x, double y, double z) const; double length() const; ZPoint& operator += (const ZPoint &pt); ZPoint& operator -= (const ZPoint &pt); ZPoint& operator /= (const ZPoint &pt); ZPoint& operator += (double offset); ZPoint& operator -= (double offset); ZPoint& operator *= (double scale); ZPoint& operator /= (double scale); friend ZPoint operator + (const ZPoint &pt1, const ZPoint &pt2); friend ZPoint operator - (const ZPoint &pt1, const ZPoint &pt2); friend ZPoint operator * (const ZPoint &pt1, double scale); void toArray(double *pt) const; void normalize(); double dot(const ZPoint &pt) const; double cosAngle(const ZPoint &pt) const; bool isApproxOrigin() const; bool approxEquals(const ZPoint &pt) const; std::string toString() const; std::string toJsonString() const; inline void translate(double dx, double dy, double dz) { m_x += dx; m_y += dy; m_z += dz; } public: virtual void display(QPainter &painter, int n = 0, Display_Style style = NORMAL) const; virtual void save(const char *filePath); virtual void load(const char *filePath); static inline double minimalDistance() { return m_minimalDistance; } private: double m_x; double m_y; double m_z; const static double m_minimalDistance; }; #endif // ZPOINT_H
24.95
89
0.67014
[ "3d" ]
1084a629afe01a508f4c621ab44faec589b825c0
427
h
C
GU/Renderer/Renderer.h
ImGili/GU
5337781a8921b47cdd2e4eafe3224b87c4bcf35d
[ "MIT" ]
1
2021-12-10T07:34:31.000Z
2021-12-10T07:34:31.000Z
GU/Renderer/Renderer.h
ImGili/GU
5337781a8921b47cdd2e4eafe3224b87c4bcf35d
[ "MIT" ]
null
null
null
GU/Renderer/Renderer.h
ImGili/GU
5337781a8921b47cdd2e4eafe3224b87c4bcf35d
[ "MIT" ]
null
null
null
/* * @Author: ImGili * @Description: */ #pragma once #include"Core/Core.h" #include"Renderer/Shader.h" #include"Renderer/VertexArray.h" #include<glm/glm.hpp> #include<memory> namespace GU { class Renderer { public: static void Submit(const std::shared_ptr<Shader>& shader, const std::shared_ptr<VertexArray>& vertexarray, const glm::mat4& transform = glm::mat4(1)); static void Init(); }; }
21.35
158
0.669789
[ "transform" ]
1093c8f8d9840d4fa57b110e36eaa6f51e0cf502
2,740
h
C
simple-mbed-cloud-client.h
paul-szczepanek-arm/simple-mbed-cloud-client
9f05156e8386f7ef27a0194d12546b8397c0c564
[ "Apache-2.0" ]
null
null
null
simple-mbed-cloud-client.h
paul-szczepanek-arm/simple-mbed-cloud-client
9f05156e8386f7ef27a0194d12546b8397c0c564
[ "Apache-2.0" ]
null
null
null
simple-mbed-cloud-client.h
paul-szczepanek-arm/simple-mbed-cloud-client
9f05156e8386f7ef27a0194d12546b8397c0c564
[ "Apache-2.0" ]
null
null
null
// ---------------------------------------------------------------------------- // Copyright 2016-2018 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 SIMPLEMBEDCLOUDCLIENT_H #define SIMPLEMBEDCLOUDCLIENT_H #include <stdio.h> #include "mbed-cloud-client/MbedCloudClient.h" #include "m2mdevice.h" #include "m2mresource.h" #include "mbed-client/m2minterface.h" #include "mbed-client/m2mvector.h" #include "mbed_cloud_client_resource.h" #include "mbed.h" #include "NetworkInterface.h" class MbedCloudClientResource; class SimpleMbedCloudClient { public: SimpleMbedCloudClient(NetworkInterface *net, BlockDevice *bd, FileSystem *fs); ~SimpleMbedCloudClient(); int init(); bool call_register(); void close(); void register_update(); void client_registered(); void client_unregistered(); void error(int error_code); bool is_client_registered(); bool is_register_called(); bool register_and_connect(); MbedCloudClient& get_cloud_client(); MbedCloudClientResource* create_resource(const char *path, const char *name); void on_registered(Callback<void(const ConnectorClientEndpointInfo*)> cb); void on_unregistered(Callback<void()> cb); private: int reformat_storage(); void reset_storage(); int mount_storage(); M2MObjectList _obj_list; MbedCloudClient _cloud_client; bool _registered; bool _register_called; bool _register_and_connect_called; Vector<MbedCloudClientResource*> _resources; Callback<void(const ConnectorClientEndpointInfo*)> _registered_cb; Callback<void()> _unregistered_cb; NetworkInterface * _net; BlockDevice * _bd; FileSystem * _fs; }; #endif // SIMPLEMBEDCLOUDCLIENT_H
37.027027
85
0.598905
[ "vector" ]
10acb865102747ecd1a3ac7bb03808e9e7842f12
1,489
h
C
Libraries/LibGUI/GModelIndex.h
F0xedb/serenity
5fb40b3ae53d83f0b718e2cc14dfc893d8a04c15
[ "BSD-2-Clause" ]
null
null
null
Libraries/LibGUI/GModelIndex.h
F0xedb/serenity
5fb40b3ae53d83f0b718e2cc14dfc893d8a04c15
[ "BSD-2-Clause" ]
8
2019-08-25T12:52:40.000Z
2019-09-08T14:46:11.000Z
Libraries/LibGUI/GModelIndex.h
F0xedb/serenity
5fb40b3ae53d83f0b718e2cc14dfc893d8a04c15
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <AK/LogStream.h> #include <AK/String.h> class GModel; class GModelIndex { friend class GModel; public: GModelIndex() {} bool is_valid() const { return m_row != -1 && m_column != -1; } int row() const { return m_row; } int column() const { return m_column; } void* internal_data() const { return m_internal_data; } GModelIndex parent() const; bool operator==(const GModelIndex& other) const { return m_model == other.m_model && m_row == other.m_row && m_column == other.m_column && m_internal_data == other.m_internal_data; } bool operator!=(const GModelIndex& other) const { return !(*this == other); } private: GModelIndex(const GModel& model, int row, int column, void* internal_data) : m_model(&model) , m_row(row) , m_column(column) , m_internal_data(internal_data) { } const GModel* m_model { nullptr }; int m_row { -1 }; int m_column { -1 }; void* m_internal_data { nullptr }; }; inline const LogStream& operator<<(const LogStream& stream, const GModelIndex& value) { return stream << String::format("GModelIndex(%d,%d)", value.row(), value.column()); } namespace AK { template<> struct Traits<GModelIndex> : public GenericTraits<GModelIndex> { static unsigned hash(const GModelIndex& index) { return pair_int_hash(index.row(), index.column()); } }; }
21.897059
138
0.617864
[ "model" ]
10acedd19a3b0e250b257623b1cea8d5df9cc827
5,182
h
C
extensions/browser/app_window/app_window_geometry_cache.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
extensions/browser/app_window/app_window_geometry_cache.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
extensions/browser/app_window/app_window_geometry_cache.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_ #define EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_ #include <stddef.h> #include <map> #include <memory> #include <set> #include <string> #include "base/memory/singleton.h" #include "base/observer_list.h" #include "base/scoped_observation.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" namespace extensions { class ExtensionPrefs; // A cache for persisted geometry of app windows, both to not have to wait // for IO when creating a new window, and to not cause IO on every window // geometry change. class AppWindowGeometryCache : public KeyedService, public ExtensionRegistryObserver { public: class Factory : public BrowserContextKeyedServiceFactory { public: static AppWindowGeometryCache* GetForContext( content::BrowserContext* context, bool create); static Factory* GetInstance(); private: friend struct base::DefaultSingletonTraits<Factory>; Factory(); ~Factory() override; // BrowserContextKeyedServiceFactory KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; }; class Observer { public: virtual void OnGeometryCacheChanged(const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds) = 0; protected: virtual ~Observer() {} }; AppWindowGeometryCache(content::BrowserContext* context, ExtensionPrefs* prefs); ~AppWindowGeometryCache() override; // Returns the instance for the given browsing context. static AppWindowGeometryCache* Get(content::BrowserContext* context); // Save the geometry and state associated with |extension_id| and |window_id|. void SaveGeometry(const std::string& extension_id, const std::string& window_id, const gfx::Rect& bounds, const gfx::Rect& screen_bounds, ui::WindowShowState state); // Get any saved geometry and state associated with |extension_id| and // |window_id|. If saved data exists, sets |bounds|, |screen_bounds| and // |state| if not NULL and returns true. bool GetGeometry(const std::string& extension_id, const std::string& window_id, gfx::Rect* bounds, gfx::Rect* screen_bounds, ui::WindowShowState* state); // KeyedService void Shutdown() override; void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); // Maximum number of windows we'll cache the geometry for per app. static const size_t kMaxCachedWindows = 100; protected: friend class AppWindowGeometryCacheTest; // For tests, this modifies the timeout delay for saving changes from calls // to SaveGeometry. (Note that even if this is set to 0, you still need to // run the message loop to see the results of any SyncToStorage call). void SetSyncDelayForTests(int timeout_ms); private: // Data stored for each window. struct WindowData { WindowData(); ~WindowData(); gfx::Rect bounds; gfx::Rect screen_bounds; ui::WindowShowState window_state; base::Time last_change; }; // Data stored for each extension. typedef std::map<std::string, WindowData> ExtensionData; // ExtensionRegistryObserver implementation. void OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) override; void OnExtensionUnloaded(content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) override; void LoadGeometryFromStorage(const std::string& extension_id); void SyncToStorage(); // Preferences storage. ExtensionPrefs* prefs_; // Cached data. std::map<std::string, ExtensionData> cache_; // Data that still needs saving. std::set<std::string> unsynced_extensions_; // The timer used to save the data. base::OneShotTimer sync_timer_; // The timeout value we'll use for |sync_timer_|. base::TimeDelta sync_delay_; // Listen to extension load, unloaded notifications. base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; base::ObserverList<Observer>::Unchecked observers_; }; } // namespace extensions #endif // EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_
32.797468
83
0.706291
[ "geometry" ]
10ae1b0c7dc03914b40079971cccf0198c00e463
1,564
h
C
atom/browser/atom_browser_client.h
cybernetics/atom-shell
66ab12738931b7ea971f9f109264f1b0cbe2eac8
[ "MIT" ]
1
2019-04-22T08:48:46.000Z
2019-04-22T08:48:46.000Z
atom/browser/atom_browser_client.h
FWeinb/atom-shell
f0e297ba7790c297d2a3fcf8bbd883e0e66aa251
[ "MIT" ]
null
null
null
atom/browser/atom_browser_client.h
FWeinb/atom-shell
f0e297ba7790c297d2a3fcf8bbd883e0e66aa251
[ "MIT" ]
null
null
null
// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ATOM_BROWSER_ATOM_BROWSER_CLIENT_H_ #define ATOM_BROWSER_ATOM_BROWSER_CLIENT_H_ #include <string> #include "brightray/browser/browser_client.h" namespace atom { class AtomBrowserClient : public brightray::BrowserClient { public: AtomBrowserClient(); virtual ~AtomBrowserClient(); protected: net::URLRequestContextGetter* CreateRequestContext( content::BrowserContext* browser_context, content::ProtocolHandlerMap* protocol_handlers) OVERRIDE; virtual void OverrideWebkitPrefs(content::RenderViewHost* render_view_host, const GURL& url, WebPreferences* prefs) OVERRIDE; virtual bool ShouldSwapProcessesForNavigation( content::SiteInstance* site_instance, const GURL& current_url, const GURL& new_url) OVERRIDE; virtual std::string GetApplicationLocale() OVERRIDE; virtual void AppendExtraCommandLineSwitches(CommandLine* command_line, int child_process_id) OVERRIDE; private: virtual brightray::BrowserMainParts* OverrideCreateBrowserMainParts( const content::MainFunctionParams&) OVERRIDE; // The render process which would be swapped out soon. content::RenderProcessHost* dying_render_process_; DISALLOW_COPY_AND_ASSIGN(AtomBrowserClient); }; } // namespace atom #endif // ATOM_BROWSER_ATOM_BROWSER_CLIENT_H_
33.276596
77
0.732737
[ "render" ]
10b014c4a817e9421301a70c73225517a510c7d3
693
h
C
sgutils.h
john-mai-2605/graphic-robot
f33a5039144bb4df3ee442ddbee1ee1953df863c
[ "BSD-3-Clause" ]
1
2021-09-15T00:45:07.000Z
2021-09-15T00:45:07.000Z
sgutils.h
john-mai-2605/graphic-robot
f33a5039144bb4df3ee442ddbee1ee1953df863c
[ "BSD-3-Clause" ]
null
null
null
sgutils.h
john-mai-2605/graphic-robot
f33a5039144bb4df3ee442ddbee1ee1953df863c
[ "BSD-3-Clause" ]
null
null
null
#ifndef SGUTILS_H #define SGUTILS_H #include <vector> #include "scenegraph.h" struct RbtNodesScanner : public SgNodeVisitor { typedef std::vector<std::shared_ptr<SgRbtNode> > SgRbtNodes; SgRbtNodes& nodes_; RbtNodesScanner(SgRbtNodes& nodes) : nodes_(nodes) {} virtual bool visit(SgTransformNode& node) { using namespace std; shared_ptr<SgRbtNode> rbtPtr = dynamic_pointer_cast<SgRbtNode>(node.shared_from_this()); if (rbtPtr) nodes_.push_back(rbtPtr); return true; } }; inline void dumpSgRbtNodes(std::shared_ptr<SgNode> root, std::vector<std::shared_ptr<SgRbtNode> >& rbtNodes) { RbtNodesScanner scanner(rbtNodes); root->accept(scanner); } #endif
23.1
110
0.734488
[ "vector" ]
10b08d2c862453bb01ec863c745e1b0bee16cc3f
16,030
h
C
groups/bsl/bsls/bsls_byteorder.h
Nexuscompute/bde
d717c1cb780a46afe9373f522ba0e6ef9bab6220
[ "Apache-2.0" ]
null
null
null
groups/bsl/bsls/bsls_byteorder.h
Nexuscompute/bde
d717c1cb780a46afe9373f522ba0e6ef9bab6220
[ "Apache-2.0" ]
null
null
null
groups/bsl/bsls/bsls_byteorder.h
Nexuscompute/bde
d717c1cb780a46afe9373f522ba0e6ef9bab6220
[ "Apache-2.0" ]
null
null
null
// bsls_byteorder.h -*-C++-*- #ifndef INCLUDED_BSLS_BYTEORDER #define INCLUDED_BSLS_BYTEORDER #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide byte-order manipulation macros. // //@CLASSES: // //@SEE_ALSO: bsls_byteorderutil // //@MACROS: // BSLS_BYTEORDER_HTON(x): Convert value from host to network order // BSLS_BYTEORDER_HTONS(x): Convert 16-bit value from host to network order // BSLS_BYTEORDER_HTONL(x): Convert 32-bit value from host to network order // BSLS_BYTEORDER_HTONLL(x): Convert 64-bit value from host to network order // BSLS_BYTEORDER_NTOH(x): Convert value from network to host order // BSLS_BYTEORDER_NTOHS(x): Convert 16-bit value from network to host order // BSLS_BYTEORDER_NTOHL(x): Convert 32-bit value from network to host order // BSLS_BYTEORDER_NTOHLL(x): Convert 64-bit value from network to host order // // BSLS_BYTEORDER_HTON_CONSTANT(x): static host to network order // BSLS_BYTEORDER_HTONS_CONSTANT(x): static 16-bit network to host order // BSLS_BYTEORDER_HTONL_CONSTANT(x): static 32-bit network to host order // BSLS_BYTEORDER_HTONLL_CONSTANT(x): static 64-bit network to host order // BSLS_BYTEORDER_NTOH_CONSTANT(x): static network to host order // BSLS_BYTEORDER_NTOHS_CONSTANT(x): static 16-bit network to host order // BSLS_BYTEORDER_NTOHL_CONSTANT(x): static 32-bit network to host order // BSLS_BYTEORDER_NTOHLL_CONSTANT(x): static 64-bit network to host order // // BSLS_BYTEORDER_LE_TO_HOST(x): little-endian to host-endian // BSLS_BYTEORDER_LE_U16_TO_HOST(x): 16-bit little-endian to host-endian // BSLS_BYTEORDER_LE_U32_TO_HOST(x): 32-bit little-endian to host-endian // BSLS_BYTEORDER_LE_U64_TO_HOST(x): 64-bit little-endian to host-endian // BSLS_BYTEORDER_BE_TO_HOST(x): big-endian to host-endian // BSLS_BYTEORDER_BE_U16_TO_HOST(x): 16-bit big-endian to host-endian // BSLS_BYTEORDER_BE_U32_TO_HOST(x): 32-bit big-endian to host-endian // BSLS_BYTEORDER_BE_U64_TO_HOST(x): 64-bit big-endian to host-endian // // BSLS_BYTEORDER_HOST_TO_LE(x): host-endian to little-endian // BSLS_BYTEORDER_HOST_U16_TO_LE(x): 16-bit host-endian to little-endian // BSLS_BYTEORDER_HOST_U32_TO_LE(x): 32-bit host-endian to little-endian // BSLS_BYTEORDER_HOST_U64_TO_LE(x): 64-bit host-endian to little-endian // BSLS_BYTEORDER_HOST_TO_BE(x): host-endian to big-endian // BSLS_BYTEORDER_HOST_U16_TO_BE(x): 16-bit host-endian to big-endian // BSLS_BYTEORDER_HOST_U32_TO_BE(x): 32-bit host-endian to big-endian // BSLS_BYTEORDER_HOST_U64_TO_BE(x): 64-bit host-endian to big-endian // //@DESCRIPTION: This component provides a set of byte-order manipulation macros // that replace the standard 'htonl', 'htons', 'ntohl', and 'ntohs' functions, // and which do not require including any system header files: //.. // BSLS_BYTEORDER_HTON(x) // BSLS_BYTEORDER_HTONS(x) // BSLS_BYTEORDER_HTONL(x) // BSLS_BYTEORDER_HTONLL(x) // BSLS_BYTEORDER_NTOH(x) // BSLS_BYTEORDER_NTOHS(x) // BSLS_BYTEORDER_NTOHL(x) // BSLS_BYTEORDER_NTOHLL(x) //.. // The "S", "L", and "LL" suffices in the names of the above macros indicate // their applicability to 16-bit ('short'), 32-bit ('int', *not* 'long'), and // 64-bit ('long long') values, respectively. // // The macros without "S", "L", or "LL" suffices in their names indicate that // they take the word size to be swapped from the word size of 'x', and return // a value of the same type as 'x'. These should only be passed fundamental // integral types, and not 'enum' values, as the sizes of 'enum' values are // implementation defined. // // This set of host-to-network and network-to-host conversion macros are very // efficient, but sacrifices the ability to perform compile-time // initialization. To compensate, the following set of functionally equivalent // "CONSTANT" macros are provided. These macros can be used for compile-time // initialization, but are less efficient than non-"CONSTANT" versions: //.. // BSLS_BYTEORDER_HTONS_CONSTANT(x) // BSLS_BYTEORDER_HTONL_CONSTANT(x) // BSLS_BYTEORDER_HTONLL_CONSTANT(x) // BSLS_BYTEORDER_NTOHS_CONSTANT(x) // BSLS_BYTEORDER_NTOHL_CONSTANT(x) // BSLS_BYTEORDER_NTOHLL_CONSTANT(x) //.. // Another set of macros provides conversion from big-endian or little-endian // byte order to host-endian order. The macros take 16-, 32- or 64-bit values // and perform the indicated byte-order conversion on those values: //.. // BSLS_BYTEORDER_LE_TO_HOST(x) // BSLS_BYTEORDER_LE_U16_TO_HOST(x) // BSLS_BYTEORDER_LE_U32_TO_HOST(x) // BSLS_BYTEORDER_LE_U64_TO_HOST(x) // BSLS_BYTEORDER_BE_TO_HOST(x) // BSLS_BYTEORDER_BE_U16_TO_HOST(x) // BSLS_BYTEORDER_BE_U32_TO_HOST(x) // BSLS_BYTEORDER_BE_U64_TO_HOST(x) //.. // The "LE" and "BE" embedded in the above macro names indicate Little-Endian // and Big-Endian, respectively. // // Finally, a complementary set of macros provides conversion from host-endian // byte order to big-endian or little-endian order: //.. // BSLS_BYTEORDER_HOST_TO_LE(x) // BSLS_BYTEORDER_HOST_U16_TO_LE(x) // BSLS_BYTEORDER_HOST_U32_TO_LE(x) // BSLS_BYTEORDER_HOST_U64_TO_LE(x) // BSLS_BYTEORDER_HOST_TO_BE(x) // BSLS_BYTEORDER_HOST_U16_TO_BE(x) // BSLS_BYTEORDER_HOST_U32_TO_BE(x) // BSLS_BYTEORDER_HOST_U64_TO_BE(x) //.. // ///Usage ///----- // To use these macros, simply pass a 16-, 32-, or 64-bit value to the macros. // To demonstrate the change in byte order effected by the macros, we first // write a function to print, in hex, a character buffer of a specified size: //.. // void printHex(const char *c, int size) // // Print the specified character array 'c', having the specified 'size' // // (in bytes), to 'stdout' in hex. // { // const char *hex = "0123456789abcdef"; // for (int i = 0; i < size; ++i) { // std::cout << hex[(c[i] >> 4) & 0xf] // << hex[ c[i] & 0xf]; // } // } // // template <class T> // void printHex(T x) // // Print the specified object 'x' of parameterized type 'T' in hex. // { // printHex((const char*)&x, sizeof x); // } //.. // For example, to use the little-endian/big-endian to host-endian macros: //.. // short x = static_cast<short>(0xabcd); // int y = 0xabcdef12; // bsls::Types::Int64 z = 0xabcdef1234567890LL; // // // Note the use of macros within the calls to 'printHex'. // // printf("\nLE to Host(x): "); // printHex(BSLS_BYTEORDER_LE_U16_TO_HOST(x)); // // printf("\nLE to Host(y): "); // printHex(BSLS_BYTEORDER_LE_U32_TO_HOST(y)); // // printf("\nLE to Host(z): "); // printHex(BSLS_BYTEORDER_LE_U64_TO_HOST(z)); // // printf("\nBE to Host(x): "); // printHex(BSLS_BYTEORDER_BE_U16_TO_HOST(x)); // // printf("\nBE to Host(y): "); // printHex(BSLS_BYTEORDER_BE_U32_TO_HOST(y)); // // printf("\nBE to Host(z): "); // printHex(BSLS_BYTEORDER_BE_U64_TO_HOST(z)); //.. // On little-endian machines (e.g., x86, IA64), this will print the following // to 'stdout': //.. // LE to Host(x): abcd // LE to Host(y): abcdef12 // LE to Host(z): abcdef1234567890 // BE to Host(x): cdab // BE to Host(y): 12efcdab // BE to Host(z): 9078563412efcdab //.. // On big-endian machines (e.g., sparc, powerpc), the following will be printed // instead: //.. // LE to Host(x): cdab // LE to Host(y): 12efcdab // LE to Host(z): 9078563412efcdab // BE to Host(x): abcd // BE to Host(y): abcdef12 // BE to Host(z): abcdef1234567890 //.. // The other macros can be used in a similar manner. #include <bsls_byteorderutil.h> #include <bsls_platform.h> // ============================================================================ // MACROS // ====== // STANDARD NETWORK AND HOST CONVERSIONS #if defined(BSLS_PLATFORM_IS_BIG_ENDIAN) #define BSLS_BYTEORDER_NTOH(x) (x) #define BSLS_BYTEORDER_NTOHS(x) (x) #define BSLS_BYTEORDER_NTOHL(x) (x) #define BSLS_BYTEORDER_NTOHLL(x) (x) #define BSLS_BYTEORDER_HTON(x) (x) #define BSLS_BYTEORDER_HTONS(x) (x) #define BSLS_BYTEORDER_HTONL(x) (x) #define BSLS_BYTEORDER_HTONLL(x) (x) #define BSLS_BYTEORDER_NTOHS_CONSTANT(x) (x) #define BSLS_BYTEORDER_NTOHL_CONSTANT(x) (x) #define BSLS_BYTEORDER_NTOHLL_CONSTANT(x) (x) #define BSLS_BYTEORDER_HTONS_CONSTANT(x) (x) #define BSLS_BYTEORDER_HTONL_CONSTANT(x) (x) #define BSLS_BYTEORDER_HTONLL_CONSTANT(x) (x) #else // BSLS_PLATFORM_IS_LITTLE_ENDIAN #define BSLS_BYTEORDER_NTOH(x) BloombergLP::bsls::ByteOrderUtil::swapBytes(x) #define BSLS_BYTEORDER_NTOHS(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes16(x) #define BSLS_BYTEORDER_NTOHL(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes32(x) #define BSLS_BYTEORDER_NTOHLL(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes64(x) #define BSLS_BYTEORDER_HTON(x) BSLS_BYTEORDER_NTOH(x) #define BSLS_BYTEORDER_HTONS(x) BSLS_BYTEORDER_NTOHS(x) #define BSLS_BYTEORDER_HTONL(x) BSLS_BYTEORDER_NTOHL(x) #define BSLS_BYTEORDER_HTONLL(x) BSLS_BYTEORDER_NTOHLL(x) #define BSLS_BYTEORDER_NTOHS_CONSTANT(x) \ static_cast<unsigned short>( \ (static_cast<unsigned short>(x) >> 8) | \ (static_cast<unsigned short>(x) << 8)) // The "NO_MSB" versions of the byte-swapping macros always move a 0 bit into // the most significant bit of the result, in order to avoid undefined behavior // caused by left shifting a 1 into the sign bit of a signed positive value. // These versions are invoked by the user versions of the macros, which first // test whether that bit is 1, and if so, perform the operation on the // complement of the value and complement the result. The "NO_MSB" macros are // intended to be private to the implementation. #define BSLS_BYTEORDER_NTOHL_CONSTANT_NO_MSB(x) \ ((((x) >> 24) & 0x000000FF) | (((x) & 0x00FF0000) >> 8) \ /* note 0x7F */ | (((x) & 0x0000FF00) << 8) | (((x) & 0x0000007F) << 24)) #define BSLS_BYTEORDER_NTOHL_CONSTANT(x) \ ((x) & 0x80 ? ~BSLS_BYTEORDER_NTOHL_CONSTANT_NO_MSB(~(x)) \ : BSLS_BYTEORDER_NTOHL_CONSTANT_NO_MSB(x)) #define BSLS_BYTEORDER_NTOHLL_CONSTANT_NO_MSB(x) \ /* note 0x7F */ ((((x) & 0x000000000000007FLL) << 56) \ | (((x) & 0x000000000000FF00LL) << 40) \ | (((x) & 0x0000000000FF0000LL) << 24) \ | (((x) & 0x00000000FF000000LL) << 8) \ | (((x) & 0x000000FF00000000LL) >> 8) \ | (((x) & 0x0000FF0000000000LL) >> 24) \ | (((x) & 0x00FF000000000000LL) >> 40) \ | (((x) >> 56) & 0x00000000000000FFLL)) #define BSLS_BYTEORDER_NTOHLL_CONSTANT(x) \ ((x) & 0x80 ? ~BSLS_BYTEORDER_NTOHLL_CONSTANT_NO_MSB(~(x)) \ : BSLS_BYTEORDER_NTOHLL_CONSTANT_NO_MSB(x)) #define BSLS_BYTEORDER_HTONS_CONSTANT(x) BSLS_BYTEORDER_NTOHS_CONSTANT(x) #define BSLS_BYTEORDER_HTONL_CONSTANT(x) BSLS_BYTEORDER_NTOHL_CONSTANT(x) #define BSLS_BYTEORDER_HTONLL_CONSTANT(x) BSLS_BYTEORDER_NTOHLL_CONSTANT(x) #endif // BSLS_PLATFORM_IS_BIG_ENDIAN // ---------------------------------------------------------------------------- // ENDIAN CONVERSION MACROS #if defined(BSLS_PLATFORM_IS_LITTLE_ENDIAN) #define BSLS_BYTEORDER_LE_U16_TO_HOST(x) (x) #define BSLS_BYTEORDER_LE_U32_TO_HOST(x) (x) #define BSLS_BYTEORDER_LE_U64_TO_HOST(x) (x) #define BSLS_BYTEORDER_HOST_U16_TO_LE(x) (x) #define BSLS_BYTEORDER_HOST_U32_TO_LE(x) (x) #define BSLS_BYTEORDER_HOST_U64_TO_LE(x) (x) #define BSLS_BYTEORDER_BE_U16_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes16(x) #define BSLS_BYTEORDER_BE_U32_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes32(x) #define BSLS_BYTEORDER_BE_U64_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes64(x) #define BSLS_BYTEORDER_HOST_U16_TO_BE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes16(x) #define BSLS_BYTEORDER_HOST_U32_TO_BE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes32(x) #define BSLS_BYTEORDER_HOST_U64_TO_BE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes64(x) #define BSLS_BYTEORDER_LE_TO_HOST(x) (x) #define BSLS_BYTEORDER_HOST_TO_LE(x) (x) #define BSLS_BYTEORDER_BE_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes(x) #define BSLS_BYTEORDER_HOST_TO_BE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes(x) #else // BSLS_PLATFORM_IS_BIG_ENDIAN #define BSLS_BYTEORDER_LE_U16_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes16(x) #define BSLS_BYTEORDER_LE_U32_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes32(x) #define BSLS_BYTEORDER_LE_U64_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes64(x) #define BSLS_BYTEORDER_HOST_U16_TO_LE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes16(x) #define BSLS_BYTEORDER_HOST_U32_TO_LE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes32(x) #define BSLS_BYTEORDER_HOST_U64_TO_LE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes64(x) #define BSLS_BYTEORDER_BE_U16_TO_HOST(x) (x) #define BSLS_BYTEORDER_BE_U32_TO_HOST(x) (x) #define BSLS_BYTEORDER_BE_U64_TO_HOST(x) (x) #define BSLS_BYTEORDER_HOST_U16_TO_BE(x) (x) #define BSLS_BYTEORDER_HOST_U32_TO_BE(x) (x) #define BSLS_BYTEORDER_HOST_U64_TO_BE(x) (x) #define BSLS_BYTEORDER_LE_TO_HOST(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes(x) #define BSLS_BYTEORDER_HOST_TO_LE(x) \ BloombergLP::bsls::ByteOrderUtil::swapBytes(x) #define BSLS_BYTEORDER_BE_TO_HOST(x) (x) #define BSLS_BYTEORDER_HOST_TO_BE(x) (x) #endif // BSLS_PLATFORM_IS_LITTLE_ENDIAN #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
44.15978
79
0.627698
[ "object" ]
10b0b64640f272e23edeabcb7d8d339f413902c3
10,635
c
C
duniverse/lwt/src/unix/unix_c/unix_getcwd_job.c
emillon/opam-monorepo
243f2310ad01722df7a29fc0d497d8834fb71ec1
[ "0BSD" ]
24
2021-03-13T22:22:18.000Z
2021-12-16T21:51:26.000Z
duniverse/lwt/src/unix/unix_c/unix_getcwd_job.c
emillon/opam-monorepo
243f2310ad01722df7a29fc0d497d8834fb71ec1
[ "0BSD" ]
2
2020-09-28T09:42:04.000Z
2020-11-18T23:37:58.000Z
duniverse/lwt/src/unix/unix_c/unix_getcwd_job.c
emillon/opam-monorepo
243f2310ad01722df7a29fc0d497d8834fb71ec1
[ "0BSD" ]
1
2020-10-05T13:41:44.000Z
2020-10-05T13:41:44.000Z
/* This file is part of Lwt, released under the MIT license. See LICENSE.md for details, or visit https://github.com/ocsigen/lwt/blob/master/LICENSE.md. */ #include "lwt_config.h" #if !defined(LWT_ON_WINDOWS) #include <caml/alloc.h> #include <caml/mlvalues.h> #include <caml/unixsupport.h> #include <errno.h> #include <unistd.h> #include "lwt_unix.h" /** Lwt C stubs come in two varieties, depending on whether the underlying C call is blocking or non-blocking. In all cases, the Lwt wrapper around the C call must be made to appear *non*-blocking. 1. The simple case is when the underlying C call is already non-blocking. An example of this is `lwt_unix_read`, which is used by Lwt to perform reads from file descriptors that are in non-blocking mode. This stub is a simple wrapper around `read(2)`. It converts its arguments from OCaml runtime representation to normal C, machine representation, passes them to `read(2)`, converts the result back to OCaml, and returns. 2. In case the underlying C call is blocking, as `getcwd(3)` is, Lwt "converts" it to a non-blocking call by running it inside a worker thread. The rest of this comment is concerned with such blocking calls. For background on writing C stubs in OCaml, see http://caml.inria.fr/pub/docs/manual-ocaml/intfc.html Each Lwt stub for a blocking C call defines a *job* for the Lwt worker thread pool. The actual thread pool is implemented in `lwt_unix_stubs.c` and is beyond the scope of this comment. It is not necessary to understand it to implement Lwt jobs (indeed, the author currently doesn't remember exactly how it works!). The thread pool expects jobs in a fixed format (the `struct` below) and accompanying functions with fixed names. You *MUST* follow this naming conventions. Specifically, for a job "`FOO`", you must define - the struct `struct job_FOO` - the function `lwt_unix_FOO_job` - the function `worker_FOO` - the function `result_FOO` The struct `struct job_FOO`: This is the representation of the job that will be manipulated by the thread pool. It has several purposes: - Store the pointers to `worker_FOO` and `result_FOO`, so the thread pool is able to run them. - Store the C call arguments, or references to them, so they can be accessed by `worker_FOO` when it runs in the worker thread. - Store the C call results, so they can be accessed by `result_FOO` in the main thread. - Be something that can be placed in queues, or manipulated otherwise. The function `lwt_unix_FOO_job` allocates the job's struct. The function `worker_FOO` is later called in a worker thread to actually run the job. The function `result_FOO` is, even later, called in the main thread to return the result of the job to OCaml, and deallocate the job. It is also possible to define additional helper functions and/or types, as needed. Many stubs are defined on Unix-like systems, but not Windows, and vice versa. However, Lwt's OCaml code lacks conditional compilation for this, and expects all the C symbols to be available on all platforms during linking. It just doesn't call the ones that don't have a real implementation. The unimplemented symbols are defined using the `LWT_NOT_AVAILABLEx` macros. The `getcwd` job currently takes one argument, and is not implemented on Windows. For this reason, `lwt_unix_windows.h` has `LWT_NOT_AVAILABLE1(unix_getcwd_job)`. The `lwt_` prefix is left off. In case this macro is forgotten, Lwt's CI builds should detect that when you open a PR against the Lwt repo. Don't worry if this happens – it's a typical oversight for all contributors and maintainers. See inline comments in the implementation of the `getcwd` job below for other details. */ /** The first field of a job `struct` must always be `struct lwt_unix_job job`: - The `struct lwt_unix_job` contains the data the thread pool needs to manage the job: function pointers, the total size of the job `struct`, etc. Placing it at the start of each job `struct` type ensures that the offsets to these fields are the same between all kinds of jobs. - The `struct lwt_unix_job` must be called `job`, because that is what the job helper macros expect. The job `struct` should also contain a field `error_code`. This is a snapshot of `errno` from the worker thread, right after the C call ran. `errno` is a notorious source of pitfalls; see comments in `worker_getcwd` and `result_getcwd`. The rest of the `struct` is free-form, but typically it contains - One field per argument to the C call. - One field for the return value of the C call. */ struct job_getcwd { struct lwt_unix_job job; char buf[4096]; char *result; int error_code; }; /* In the OCaml sources, getcwd's buffer size is set as either - 4096 (in asmrun/spacetime.c, byterun/sys.c) - PATH_MAX, MAXPATHLEN, or 512 (in otherlibs/unix/getcwd.c) */ /* Runs in the worker thread. This function is `static` (not visible outside this C file) because it is called only through the function pointer that is stored inside `job_getcwd::job` when the job is allocated. `static` is why the name is not prefixed with `lwt_unix_`. */ static void worker_getcwd(struct job_getcwd *job) { /* Run the C call. We don't perform any checking in the worker thread, because we typically don't want to take any other action here – we want to take action in the main thread. In more complex calls, pre-checks on the arguments are done in the `lwt_unix_FOO_job` job-allocating function, and post-checks on the results are done in the `result_FOO` function. */ job->result = getcwd(job->buf, sizeof(job->buf)); /* Store the current value of `errno`. Note that if the C call succeeded, it did not reset `errno` to zero. In that case, `errno` still contains the error code from the last C call to fail in this worker thread. This means that `errno`/`job->error_code` *cannot* be used to determine whether the C call succeeded or not. */ job->error_code = errno; } /* Runs in the main thread. This function is `static` for the same reason as `worker_getcwd`. */ static value result_getcwd(struct job_getcwd *job) { /* This macro is defined in `lwt_unix.h`. The arguments are used as follows: - The first argument is the name of the job variable. - If the check in the second argument *succeeds*, the C call, and job, failed (confusing!). Note that this check must *not* be based solely on `job->error_code`; see comment in `worker_getcwd` above. - The last argument is the name of the C call, used in a `Unix.Unix_error` exception raised if the job failed. If the check succeeds/job failed, this macro deallocates the job, raises the exception, and does *not* "return" to the rest of `result_getcwd`. Otherwise, if the job succeeded, the job is *not* deallocated, and execution continues in the rest of `result_getcwd`. `job->error_code` is used internally by the macro in creating the `Unix.Unix_error`. If this is incorrect (i.e., some job does not set `errno` on failure), it is necessary to replace the macro by its expansion, and modify the behavior. */ LWT_UNIX_CHECK_JOB(job, job->result == NULL, "getcwd"); /* Convert the job result to an OCaml value. In this case, create an OCaml string from the temporary buffer into which `getcwd(3)` wrote the current directory. This copies the string. Throughout Lwt, blocking C calls that run in worker threads can't write directly into OCaml strings, because the OCaml garbage collector might move the strings after the pointer has already been passed to the call, but while the call is still blocked. Bigarrays don't have this problem, so pointers into them are passed to blocking C calls, avoiding a copy. In addition to worker threads not being able to write into OCaml strings, they typically cannot *allocate* any OCaml strings (or other values) either, because the worker threads do not try to take OCaml's global runtime lock. This sometimes results in extra data copies. For an example, see the implementation of `readdir_n`. At the time of this writing, that implementation copied each string returned by `readdir` twice. For jobs that return integers or other kinds of values, it is necessary to use the various `Int_val`, `Long_val` macros, etc. See http://caml.inria.fr/pub/docs/manual-ocaml/intfc.html#sec415 */ value result = caml_copy_string(job->result); /* Have to free the job manually! */ lwt_unix_free_job(&job->job); return result; } /* In the case of `Lwt_unix.getcwd`, the argument is `()`, which is represented in C by one argument, which we conventually call `unit`. OCaml always passes the same value for this argument, and we don't use it. */ CAMLprim value lwt_unix_getcwd_job(value unit) { /* Allocate the `job_getcwd` on the OCaml heap. Inside it, store its size, and pointers to `worker_getcwd` and `result_getcwd`. Arguments must be stored manually after the macro is called, but in the case of `getcwd`, there are no arguments to initialize. For an example of a job that has arguments, see `lwt_unix_read_job`. The first argument is the name of the variable to be created to store the pointer to the job `struct`, i.e. struct job_getcwd *job = ... The last argument is the number of bytes of storage to reserve in memory immediately following the `struct`. This is for fields such as `char data[]` at the end of the struct. It is typically zero. For an example where it is not zero, see `lwt_unix_read_job` again. If the additional data is stored inline in the job struct, it is deallocated with `lwt_unix_free_job`. If the additional data is for pointers to additional structure, you must remember to deallocate it yourself. For an example of this, see `readdir_n`.*/ LWT_UNIX_INIT_JOB(job, getcwd, 0); /* Allocate a corresponding object in the OCaml heap. `&job->job` is the same numeric address as `job`, but has type `struct lwt_unix_job`. */ return lwt_unix_alloc_job(&job->job); } #endif
45.255319
81
0.707475
[ "object" ]
10b433c00087d66ec9fed50b19ef854f7e3abe7b
1,093
h
C
include/DocxFactory/DocxCompiler/DocxCompilerChartFieldSeries.h
qjclinux/DocxFactory
91131f28f3324d8fad526c7faa1595203cb9a215
[ "BSD-3-Clause" ]
116
2016-12-22T18:01:41.000Z
2022-03-29T15:55:59.000Z
include/DocxFactory/DocxCompiler/DocxCompilerChartFieldSeries.h
qjclinux/DocxFactory
91131f28f3324d8fad526c7faa1595203cb9a215
[ "BSD-3-Clause" ]
16
2017-01-30T15:56:15.000Z
2021-01-13T06:09:28.000Z
include/DocxFactory/DocxCompiler/DocxCompilerChartFieldSeries.h
qjclinux/DocxFactory
91131f28f3324d8fad526c7faa1595203cb9a215
[ "BSD-3-Clause" ]
49
2017-01-16T07:34:47.000Z
2022-01-25T15:04:12.000Z
#ifndef __DOCXFACTORY_DOCX_COMPILER_CHART_FIELD_SERIES_H__ #define __DOCXFACTORY_DOCX_COMPILER_CHART_FIELD_SERIES_H__ #include "DocxFactory/DocxCompiler/DocxCompilerChartField.h" #include <vector> namespace DocxFactory { using namespace std; class ZipFile; class OpcPart; class DocxCompilerChartFieldSeries : public DocxCompilerChartField { public: DocxCompilerChartFieldSeries( DocxCompilerItem* p_item, const string& p_name, xercesc::DOMElement* p_placeHolderNode, xercesc::DOMElement* p_drawingNode, OpcPart* p_chartPart ); virtual ~DocxCompilerChartFieldSeries(); virtual void serialize( ZipFile* p_zipFile ); protected: private: DocxCompilerChartFieldSeries( const DocxCompilerChartFieldSeries& p_other ); DocxCompilerChartFieldSeries& operator = ( const DocxCompilerChartFieldSeries& p_other ); void loadSeries( xercesc::DOMElement* p_seriesNode, char p_seriesIdx ); list<pair<string, char>> m_chartStrings; vector<list<pair<string, char>>> m_seriesStrings; DocxCompilerField::FieldType m_catType; }; }; #endif
22.306122
91
0.782251
[ "vector" ]
10bafaaaebbfd01040587294ffe63622a786decd
1,510
h
C
include/soci/ref-counted-prepare-info.h
thishome153/soci
179d1c80f4c405f09dedfa75d6352e66e521a432
[ "BSL-1.0" ]
999
2015-01-03T22:22:34.000Z
2022-03-31T16:50:28.000Z
include/soci/ref-counted-prepare-info.h
thishome153/soci
179d1c80f4c405f09dedfa75d6352e66e521a432
[ "BSL-1.0" ]
640
2015-01-04T13:27:32.000Z
2022-03-31T20:09:51.000Z
include/soci/ref-counted-prepare-info.h
thishome153/soci
179d1c80f4c405f09dedfa75d6352e66e521a432
[ "BSL-1.0" ]
443
2015-01-04T08:48:29.000Z
2022-03-31T15:15:55.000Z
// // Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef SOCI_REF_COUNTED_PREPARE_INFO_INCLUDED #define SOCI_REF_COUNTED_PREPARE_INFO_INCLUDED #include "soci/bind-values.h" #include "soci/ref-counted-statement.h" // std #include <string> #include <vector> namespace soci { class session; namespace details { class procedure_impl; class statement_impl; class into_type_base; // this class conveys only the statement text and the bind/define info // it exists only to be passed to statement's constructor class ref_counted_prepare_info : public ref_counted_statement_base { public: ref_counted_prepare_info(session& s) : ref_counted_statement_base(s) {} void exchange(use_type_ptr const& u) { uses_.exchange(u); } template <typename T, typename Indicator> void exchange(use_container<T, Indicator> const &uc) { uses_.exchange(uc); } void exchange(into_type_ptr const& i) { intos_.exchange(i); } template <typename T, typename Indicator> void exchange(into_container<T, Indicator> const &ic) { intos_.exchange(ic); } void final_action() SOCI_OVERRIDE; private: friend class statement_impl; friend class procedure_impl; into_type_vector intos_; use_type_vector uses_; std::string get_query() const; }; } // namespace details } // namespace soci #endif
22.537313
70
0.739073
[ "vector" ]
10c4bb889971fc0dde1ce5c39b1e5f6b81787c8e
7,635
h
C
modules/lua_runtime_private.h
b1v1r/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
148
2015-01-10T01:53:39.000Z
2022-03-20T20:48:12.000Z
modules/lua_runtime_private.h
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
8
2015-03-09T15:50:36.000Z
2020-10-10T19:23:06.000Z
modules/lua_runtime_private.h
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
46
2015-03-08T22:45:42.000Z
2022-01-15T13:47:59.000Z
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS 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. ****************************************************************************/ /** * @file * @brief IronBee --- Lua Runtime * * Things used to manage Lua runtime stacks used throughout `ibmod_lua`. * * A runtime includes a little meta information and a lua_State pointer. * * @author Sam Baskinger <sbaskinger@qualys.com> */ #ifndef __MODULES__LUA_RUNTIME_H #define __MODULES__LUA_RUNTIME_H #include "lua/ironbee.h" #include "lua_common_private.h" #include "lua_private.h" #include <ironbee/mpool_lite.h> #include <ironbee/resource_pool.h> /** * Per-connection module data containing a Lua runtime. * * Created for each connection and stored as the module's connection data. */ struct modlua_runtime_t { lua_State *L; /**< Lua stack */ ssize_t use_count; /**< Number of times this stack is used. */ ib_mpool_lite_t *mp; /**< Memory pool for this runtime. */ ib_resource_t *resource; /**< Bookkeeping for modlua_releasestate(). */ }; typedef struct modlua_runtime_t modlua_runtime_t; /** * The type of reloading that must be done to initialize a new Lua stack. * * Lua requires many stacks to be created and initialized. Each * stack must have rules and modules reloaded into it in a specific way. * This enumeration labels each type of reloading record as a * Lua module reload or a Lua rule reload. */ enum modlua_reload_type_t { MODLUA_RELOAD_RULE, /**< Reload a Lua rule. */ MODLUA_RELOAD_MODULE /**< Reload a Lua module. */ }; typedef enum modlua_reload_type_t modlua_reload_type_t; /** * This represents a Lua item that must be reloaded. * * Reloading happens when a new Lua stack is created for the * resource pool (created by modlua_runtime_resource_pool_create()) * and when a site-specific Lua file must be loaded. * * To maximize performance all Lua scripts should be put in in the main * context and as few as possible should be put in site contexts. */ struct modlua_reload_t { modlua_reload_type_t type; /**< Is this a module or a rule? */ ib_module_t *module; /**< Lua module (not ibmod_lua.so). */ const char *file; /**< File of the rule or module code. */ const char *rule_id; /**< Rule if this is a rule type. */ }; typedef struct modlua_reload_t modlua_reload_t; /** * Set the limit on the number of times a Lua stack may be used. * * When the limit is exceeded the stack is invalided, destroyed, and replaced * in the resource pool. * * @param[in] cfg The configuration object returned to the user by * modlua_runtime_resource_pool_create(). * @param[in] limit The limit. * * @return * - IB_OK On success. * - IB_EINVAL If @a limit is not a positive, non-zero value. */ ib_status_t modlua_runtime_cfg_set_stack_use_limit( modlua_runtime_cfg_t *cfg, ssize_t limit ) NONNULL_ATTRIBUTE(1); /** * Create a resource pool that manages @ref modlua_runtime_t instances. * * @param[out] resource_pool Resource pool to create. * @param[in] ib The IronBee engine made available to the Lua runtime. * @param[in] module The IronBee module structure. * @param[in] mm The memory manager the resource pool will use. * @param[in] cfg Runtime configuration parameters that the user may set * during configuration time. * * @returns * - IB_OK On success * - IB_EALLOC If callback data structure cannot be allocated out of @a mp. * - Failures codes ib_resource_pool_create(). */ ib_status_t modlua_runtime_resource_pool_create( ib_resource_pool_t **resource_pool, ib_engine_t *ib, ib_module_t *module, ib_mm_t mm, modlua_runtime_cfg_t **cfg ); /** * Reload @a ctx and all parent contexts except the main context. * * When a Lua stack is given from the resource pool to a connection, * it is assumed that the stack has all the files referenced in the main * context already loaded. All site-specific scripts must be reloaded. * * @param[in] ib The IronBee engine. * @param[in] module The module object for the Lua module. * @param[in] ctx The configuration context. If this is the main context, * this function does nothing. If this is a context other than * the main context it's parent is recursively passed * to this function until @a ctx is the main context. * @param[in] L The Lua State to reload Lua scripts into. * * @returns * - IB_OK On success or if @a ctx is the main context. * - IB_EALLOC On an allocation error. * - IB_EINVAL If the Lua script fails to load. */ ib_status_t modlua_reload_ctx_except_main( ib_engine_t *ib, ib_module_t *module, ib_context_t *ctx, lua_State *L ); /** * Reload the main context Lua files. * * @param[in] ib IronBee engine. * @param[in] module The Lua module structure. * @param[in] L The Lua state to reload the files into. * * @returns * - IB_OK * - Failures of modlua_reload_ctx(). */ ib_status_t modlua_reload_ctx_main( ib_engine_t *ib, ib_module_t *module, lua_State *L ); /** * Push the file and the type into the reload list. * * This list is used to reload modules and rules into independent lua stacks * per transaction. * * @param[in] ib IronBee engine. * @param[in] cfg Configuration. * @param[in] type The type of the thing to reload. * @param[in] module For MODLUA_RELOAD_MODULE types this is a pointer * to the Lua script's module structure. * @param[in] rule_id The rule id. This is copied. * @param[in] file Where is the Lua file to load. This is copied. */ ib_status_t modlua_record_reload( ib_engine_t *ib, modlua_cfg_t *cfg, modlua_reload_type_t type, ib_module_t *module, const char *rule_id, const char *file ); /** * Return a @ref modlua_runtime_t to the resource pool. * * @param[in] ib IronBee engine. * @param[in] cfg The module configuration. * @param[out] modlua_runtime The runtime that should be returned to the * resource pool. * * @returns * - IB_OK On success. * - Other on failure. */ ib_status_t modlua_releasestate( ib_engine_t *ib, modlua_cfg_t *cfg, modlua_runtime_t *modlua_runtime ); /** * Acquire a @ref modlua_runtime_t from the resource pool. * * @param[in] ib IronBee engine. * @param[in] cfg The module configuration. * @param[out] modlua_runtime The fetched runtime is placed here. * * @returns * - IB_OK On success. * - IB_DECLINED If no resources are available. * - Other on failure. */ ib_status_t modlua_acquirestate( ib_engine_t *ib, modlua_cfg_t *cfg, modlua_runtime_t **modlua_runtime ); #endif /* __MODULES__LUA_RUNTIME_H */
33.195652
78
0.68055
[ "object" ]
10d2fe49b2a76564f6af7bed49440d0a55d92f23
790
h
C
sources/Utils/memory.h
n-paukov/skeletal-animation-demo
390ebba9b50cce10b4ae61b829d2e72a29c44b0c
[ "MIT" ]
3
2020-05-11T21:12:26.000Z
2021-01-01T23:12:30.000Z
sources/Utils/memory.h
n-paukov/skeletal-animation-demo
390ebba9b50cce10b4ae61b829d2e72a29c44b0c
[ "MIT" ]
null
null
null
sources/Utils/memory.h
n-paukov/skeletal-animation-demo
390ebba9b50cce10b4ae61b829d2e72a29c44b0c
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <type_traits> class MemoryUtils { public: template<class SourceType, class TargetType> [[nodiscard]] static std::vector<TargetType> createBinaryCompatibleVector(std::vector<SourceType>& source); }; template<class SourceType, class TargetType> std::vector<TargetType> MemoryUtils::createBinaryCompatibleVector(std::vector<SourceType>& source) { static_assert(std::is_pod_v<SourceType> && std::is_pod_v<TargetType> && sizeof(SourceType) == sizeof(TargetType)); size_t dataSize = sizeof(SourceType); std::vector<TargetType> target; if (source.size() > 0) { target.resize(source.size()); memcpy_s(target.data(), source.size() * dataSize, source.data(), source.size() * dataSize); } return target; }
25.483871
109
0.727848
[ "vector" ]
10d3cd2a8c3e054c31698bc98f110008896585ea
10,150
c
C
third_party/cairo-wasm/src/cairo-shape-mask-compositor.c
tsingdao-Tp/Indigo
b2d73faebb6a450e9b3d34fed553fad4f9d0012f
[ "Apache-2.0" ]
204
2015-11-06T21:34:34.000Z
2022-03-30T16:17:01.000Z
third_party/cairo-wasm/src/cairo-shape-mask-compositor.c
tsingdao-Tp/Indigo
b2d73faebb6a450e9b3d34fed553fad4f9d0012f
[ "Apache-2.0" ]
509
2015-11-05T13:54:43.000Z
2022-03-30T22:15:30.000Z
third_party/cairo-wasm/src/cairo-shape-mask-compositor.c
tsingdao-Tp/Indigo
b2d73faebb6a450e9b3d34fed553fad4f9d0012f
[ "Apache-2.0" ]
89
2015-11-17T08:22:54.000Z
2022-03-17T04:26:28.000Z
/* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */ /* cairo-wasm - a vector graphics library with display and print output * * Copyright © 2012 Intel Corporation * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL") or, at your option, under the terms of the Mozilla * Public License Version 1.1 (the "MPL"). If you do not alter this * notice, a recipient may use your version of this file under either * the MPL or the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA * You should have received a copy of the MPL along with this library * in the file COPYING-MPL-1.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY * OF ANY KIND, either express or implied. See the LGPL or the MPL for * the specific language governing rights and limitations. * * The Original Code is the cairo-wasm graphics library. * * The Initial Developer of the Original Code is University of Southern * California. * * Contributor(s): * Chris Wilson <chris@chris-wilson.co.uk> */ #include "cairoint.h" #include "cairo-compositor-private.h" #include "cairo-clip-private.h" #include "cairo-pattern-private.h" #include "cairo-surface-private.h" #include "cairo-surface-offset-private.h" static cairo_int_status_t _cairo_shape_mask_compositor_stroke (const cairo_compositor_t *_compositor, cairo_composite_rectangles_t *extents, const cairo_path_fixed_t *path, const cairo_stroke_style_t *style, const cairo_matrix_t *ctm, const cairo_matrix_t *ctm_inverse, double tolerance, cairo_antialias_t antialias) { cairo_surface_t *mask; cairo_surface_pattern_t pattern; cairo_int_status_t status; cairo_clip_t *clip; if (! extents->is_bounded) return CAIRO_INT_STATUS_UNSUPPORTED; TRACE ((stderr, "%s\n", __FUNCTION__)); mask = _cairo_surface_create_scratch (extents->surface, CAIRO_CONTENT_ALPHA, extents->bounded.width, extents->bounded.height, NULL); if (unlikely (mask->status)) return mask->status; clip = extents->clip; if (! _cairo_clip_is_region (clip)) clip = _cairo_clip_copy_region (clip); if (! mask->is_clear) { status = _cairo_surface_offset_paint (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_CLEAR, &_cairo_pattern_clear.base, clip); if (unlikely (status)) goto error; } status = _cairo_surface_offset_stroke (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_ADD, &_cairo_pattern_white.base, path, style, ctm, ctm_inverse, tolerance, antialias, clip); if (unlikely (status)) goto error; if (clip != extents->clip) { status = _cairo_clip_combine_with_surface (extents->clip, mask, extents->bounded.x, extents->bounded.y); if (unlikely (status)) goto error; } _cairo_pattern_init_for_surface (&pattern, mask); cairo_matrix_init_translate (&pattern.base.matrix, -extents->bounded.x, -extents->bounded.y); pattern.base.filter = CAIRO_FILTER_NEAREST; pattern.base.extend = CAIRO_EXTEND_NONE; if (extents->op == CAIRO_OPERATOR_SOURCE) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_DEST_OUT, &_cairo_pattern_white.base, &pattern.base, clip); if ((status == CAIRO_INT_STATUS_SUCCESS)) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_ADD, &extents->source_pattern.base, &pattern.base, clip); } } else { status = _cairo_surface_mask (extents->surface, extents->op, &extents->source_pattern.base, &pattern.base, clip); } _cairo_pattern_fini (&pattern.base); error: cairo_surface_destroy (mask); if (clip != extents->clip) _cairo_clip_destroy (clip); return status; } static cairo_int_status_t _cairo_shape_mask_compositor_fill (const cairo_compositor_t *_compositor, cairo_composite_rectangles_t *extents, const cairo_path_fixed_t *path, cairo_fill_rule_t fill_rule, double tolerance, cairo_antialias_t antialias) { cairo_surface_t *mask; cairo_surface_pattern_t pattern; cairo_int_status_t status; cairo_clip_t *clip; TRACE ((stderr, "%s\n", __FUNCTION__)); if (! extents->is_bounded) return CAIRO_INT_STATUS_UNSUPPORTED; mask = _cairo_surface_create_scratch (extents->surface, CAIRO_CONTENT_ALPHA, extents->bounded.width, extents->bounded.height, NULL); if (unlikely (mask->status)) return mask->status; clip = extents->clip; if (! _cairo_clip_is_region (clip)) clip = _cairo_clip_copy_region (clip); if (! mask->is_clear) { status = _cairo_surface_offset_paint (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_CLEAR, &_cairo_pattern_clear.base, clip); if (unlikely (status)) goto error; } status = _cairo_surface_offset_fill (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_ADD, &_cairo_pattern_white.base, path, fill_rule, tolerance, antialias, clip); if (unlikely (status)) goto error; if (clip != extents->clip) { status = _cairo_clip_combine_with_surface (extents->clip, mask, extents->bounded.x, extents->bounded.y); if (unlikely (status)) goto error; } _cairo_pattern_init_for_surface (&pattern, mask); cairo_matrix_init_translate (&pattern.base.matrix, -extents->bounded.x, -extents->bounded.y); pattern.base.filter = CAIRO_FILTER_NEAREST; pattern.base.extend = CAIRO_EXTEND_NONE; if (extents->op == CAIRO_OPERATOR_SOURCE) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_DEST_OUT, &_cairo_pattern_white.base, &pattern.base, clip); if ((status == CAIRO_INT_STATUS_SUCCESS)) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_ADD, &extents->source_pattern.base, &pattern.base, clip); } } else { status = _cairo_surface_mask (extents->surface, extents->op, &extents->source_pattern.base, &pattern.base, clip); } _cairo_pattern_fini (&pattern.base); error: if (clip != extents->clip) _cairo_clip_destroy (clip); cairo_surface_destroy (mask); return status; } static cairo_int_status_t _cairo_shape_mask_compositor_glyphs (const cairo_compositor_t *_compositor, cairo_composite_rectangles_t *extents, cairo_scaled_font_t *scaled_font, cairo_glyph_t *glyphs, int num_glyphs, cairo_bool_t overlap) { cairo_surface_t *mask; cairo_surface_pattern_t pattern; cairo_int_status_t status; cairo_clip_t *clip; if (! extents->is_bounded) return CAIRO_INT_STATUS_UNSUPPORTED; TRACE ((stderr, "%s\n", __FUNCTION__)); mask = _cairo_surface_create_scratch (extents->surface, CAIRO_CONTENT_ALPHA, extents->bounded.width, extents->bounded.height, NULL); if (unlikely (mask->status)) return mask->status; clip = extents->clip; if (! _cairo_clip_is_region (clip)) clip = _cairo_clip_copy_region (clip); if (! mask->is_clear) { status = _cairo_surface_offset_paint (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_CLEAR, &_cairo_pattern_clear.base, clip); if (unlikely (status)) goto error; } status = _cairo_surface_offset_glyphs (mask, extents->bounded.x, extents->bounded.y, CAIRO_OPERATOR_ADD, &_cairo_pattern_white.base, scaled_font, glyphs, num_glyphs, clip); if (unlikely (status)) goto error; if (clip != extents->clip) { status = _cairo_clip_combine_with_surface (extents->clip, mask, extents->bounded.x, extents->bounded.y); if (unlikely (status)) goto error; } _cairo_pattern_init_for_surface (&pattern, mask); cairo_matrix_init_translate (&pattern.base.matrix, -extents->bounded.x, -extents->bounded.y); pattern.base.filter = CAIRO_FILTER_NEAREST; pattern.base.extend = CAIRO_EXTEND_NONE; if (extents->op == CAIRO_OPERATOR_SOURCE) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_DEST_OUT, &_cairo_pattern_white.base, &pattern.base, clip); if ((status == CAIRO_INT_STATUS_SUCCESS)) { status = _cairo_surface_mask (extents->surface, CAIRO_OPERATOR_ADD, &extents->source_pattern.base, &pattern.base, clip); } } else { status = _cairo_surface_mask (extents->surface, extents->op, &extents->source_pattern.base, &pattern.base, clip); } _cairo_pattern_fini (&pattern.base); error: if (clip != extents->clip) _cairo_clip_destroy (clip); cairo_surface_destroy (mask); return status; } void _cairo_shape_mask_compositor_init (cairo_compositor_t *compositor, const cairo_compositor_t *delegate) { compositor->delegate = delegate; compositor->paint = NULL; compositor->mask = NULL; compositor->fill = _cairo_shape_mask_compositor_fill; compositor->stroke = _cairo_shape_mask_compositor_stroke; compositor->glyphs = _cairo_shape_mask_compositor_glyphs; }
29.765396
78
0.670542
[ "vector" ]
10dea57b03b8d512d5d95ba72361992c69290707
34,324
h
C
include/gravity/solver.h
amadavan/Gravity
fdf997b7df8c5ca1feadce593d402fd8de3f0fe6
[ "BSD-3-Clause" ]
null
null
null
include/gravity/solver.h
amadavan/Gravity
fdf997b7df8c5ca1feadce593d402fd8de3f0fe6
[ "BSD-3-Clause" ]
null
null
null
include/gravity/solver.h
amadavan/Gravity
fdf997b7df8c5ca1feadce593d402fd8de3f0fe6
[ "BSD-3-Clause" ]
null
null
null
// // solver.h // Gravity // // Created by Hassan #ifndef __Gravity____Solver__ #define __Gravity____Solver__ #include <stdio.h> #include <gravity/GravityConfig.h> #include <gravity/model.h> #ifdef USE_MPI #include <mpi.h> #endif #ifdef USE_IPOPT #include <gravity/IpoptProgram.h> //#include "IpoptInterfaceCommon.h" #include <coin/IpRegOptions.hpp> #include <coin/IpJournalist.hpp> #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include <future> #include <thread> using Ipopt::IsValid; using Ipopt::RegisteredOption; using Ipopt::EJournalLevel; using Ipopt::Journal; using Ipopt::IpoptApplication; using Ipopt::SmartPtr; using Ipopt::TNLP; using Ipopt::ApplicationReturnStatus; using Ipopt::SolveStatistics; #endif #ifdef USE_GUROBI #include <gravity/GurobiProgram.h> #endif #ifdef USE_BONMIN #include <gravity/BonminProgram.h> #endif #ifdef USE_CPLEX #include <gravity/CplexProgram.h> #endif #ifdef USE_CLP #include <gravity/ClpProgram.h> #endif //#ifdef USE_SDPA //#include "SdpaProgram.h" //#endif #ifdef USE_MOSEK #include "MosekProgram.h" #endif void gurobiNotAvailable(); void cplexNotAvailable(); void bonminNotAvailable(); void ipoptNotAvailable(); void mosekNotAvailable(); void ClpNotAvailable(); namespace gravity { template<typename type = double> class solver { public: gravity::Model<type>* _model = nullptr; shared_ptr<Program<type>> _prog = nullptr; SolverType _stype; type _tol = 1e-6; /*<< Solver tolerance. */ unsigned _nb_iterations = 0; map<string,string> _str_options; map<string,int> _int_options; map<string,double> _double_options; /** Constructor */ //@{ solver(); solver(shared_ptr<gravity::Model<type>> model, SolverType stype){ _stype = stype; _model = (Model<type>*)(&(*model)); _model->_built = true; init(); } solver(const Model<type>& model, SolverType stype){ _stype = stype; _model = (Model<type>*)&model; _model->_built = true; init(); } void set_option(const string& option, const string& val){ _str_options[option] = val; } void set_option(const string& option, const int& val){ _int_options[option] = val; } void set_option(const string& option, const double& val){ _double_options[option] = val; } unsigned get_nb_iterations(){ return _nb_iterations; }; void init(){ if (_stype==ipopt) { #ifdef USE_IPOPT _model->replace_integers(); SmartPtr<IpoptApplication> iapp = IpoptApplicationFactory(); iapp->RethrowNonIpoptException(true); ApplicationReturnStatus status = iapp->Initialize(); if (status != Solve_Succeeded) { throw invalid_argument("*** Error during initialization!\n"); } if(_model->_objt==maximize){ *_model->_obj *= -1; } _prog = make_shared<IpoptProgram<type>>(_model); #else ipoptNotAvailable(); #endif } else if(_stype==gurobi) { #ifdef USE_GUROBI _prog = make_shared<GurobiProgram>(_model); #else gurobiNotAvailable(); #endif } else if(_stype==cplex) { #ifdef USE_CPLEX _prog = make_shared<CplexProgram>(_model); #else cplexNotAvailable(); #endif } else if(_stype == _mosek) { #ifdef USE_MOSEK _prog = make_shared<MosekProgram>(_model); #else mosekNotAvailable(); #endif } else if(_stype==bonmin) { #ifdef USE_BONMIN _model->replace_integers(); if(_model->_objt==maximize){ *_model->_obj *= -1; } _prog = make_shared<BonminProgram>(_model); #else bonminNotAvailable(); #endif } else if (_stype == clp){ #ifdef USE_CLP _model->replace_integers(); _prog = make_shared<ClpProgram>(_model); #else ClpNotAvailable(); #endif } } //@} void set_model(gravity::Model<type>& m); int run(bool relax){ return run(5, 1e-6, 10000, 1e-6, relax, {false,""}, 1e+6); } int run(int output, type tol , const string& lin_solver){ return run(output, tol, 10000, 1e-6, true, {lin_solver!="",lin_solver}, 1e+6); } int run(type tol , double time_limit){ return run(5, tol, 10000, 1e-6, true, {false,""}, time_limit); } //OPF.run(tol,time_limit,"ma97"); int run(type tol , double time_limit, const string& lin_solver){ return run(5, tol, 10000, 1e-6, true, {lin_solver!="",lin_solver}, time_limit); } int run(int output, type tol , const string& lin_solver, int max_iter){ return run(output, tol, max_iter, 1e-6, true, {lin_solver!="",lin_solver}, 1e6); } int run(int output, type tol , double time_limit, const string& lin_solver, int max_iter){ return run(output, tol, max_iter, 1e-6, true, {lin_solver!="",lin_solver}, time_limit); } int run(int output=5, type tol=1e-6 , int max_iter=2000){ return run(output, tol, max_iter, 1e-6, false, {false,""}, 1e+6); } /* run model */ int run(int output, type tol , int max_iter, double mipgap, bool relax, pair<bool,string> lin_solver, double time_limit){ int return_status = -1, dyn_max_iter = 20; bool violated_constraints = true, optimal = true; unsigned nb_it = 0; while(violated_constraints && optimal){ if (_stype==ipopt) { #ifdef USE_IPOPT auto nb_eq = _model->get_nb_eq(); auto nb_vars = _model->get_nb_vars(); if(nb_vars<nb_eq){ auto nb_aux = nb_eq-nb_vars+1; auto aux = var<>("aux_var"); try{ _model->add(aux.in(R(nb_aux))); } catch(invalid_argument){ throw invalid_argument("aux_var is a reserved variable name, please rename your variable"); } } double mu_init = std::exp(5)/std::exp(1); SmartPtr<IpoptApplication> iapp = IpoptApplicationFactory(); iapp->RethrowNonIpoptException(true); ApplicationReturnStatus status = iapp->Initialize(); if (status != Solve_Succeeded) { std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl; return (int) status; } if(lin_solver.first){ iapp->Options()->SetStringValue("linear_solver", lin_solver.second); } // iapp->Options()->SetStringValue("mehrotra_algorithm", mehrotra); iapp->Options()->SetNumericValue("tol", tol); iapp->Options()->SetIntegerValue("print_level", output); //iapp->Options()->SetStringValue("honor_original_bounds", "no"); /** Bonmin options */ // iapp->Options()->SetStringValue("mu_strategy", "adaptive"); // iapp->Options()->SetStringValue("mu_oracle", "probing"); // iapp->Options()->SetNumericValue("gamma_phi", 1e-8); // iapp->Options()->SetNumericValue("gamma_theta", 1e-4); // iapp->Options()->SetNumericValue("bound_push", 1e-12); // iapp->Options()->SetNumericValue("bound_frac", 1e-12); // iapp->Options()->SetIntegerValue("acceptable_iter", 0); // iapp->Options()->SetNumericValue("slack_bound_push", 1e-12); iapp->Options()->SetNumericValue("constr_viol_tol", tol); // iapp->Options()->SetNumericValue("dual_inf_tol", 1); // iapp->Options()->SetNumericValue("compl_inf_tol", 1e-3); // iapp->Options()->SetNumericValue("bound_relax_factor", tol*1e-1); // iapp->Options()->SetNumericValue("bound_relax_factor", 0); // iapp->Options()->SetStringValue("derivative_test", "second-order"); // iapp->Options()->SetNumericValue("mu_init", mu_init); // iapp->Options()->SetNumericValue("obj_scaling_factor", 1e-2); /** Hot start if already solved */ if (!_model->_first_run) { mu_init = std::exp(-1)/std::exp(2); iapp->Options()->SetNumericValue("mu_init", mu_init); iapp->Options()->SetStringValue("warm_start_init_point", "yes"); DebugOn("Using Warm Start\n"); } _model->_first_run = false; iapp->Options()->SetIntegerValue("max_iter", max_iter); // iapp->Options()->SetStringValue("hessian_approximation", "limited-memory"); // iapp->Options()->SetStringValue("hessian_constant", "yes"); // iapp->Options()->SetStringValue("derivative_test", "only-second-order"); // iapp->Options()->SetNumericValue("ma57_pre_alloc", 10); // iapp->Options()->SetIntegerValue("ma57_small_pivot_flag", 1); // iapp->Options()->SetNumericValue("ma27_liw_init_factor", 20); // iapp->Options()->SetNumericValue("ma27_la_init_factor", 20); // iapp->Options()->SetNumericValue("ma27_meminc_factor", 3); // iapp->Options()->SetStringValue("ma57_automatic_scaling", "yes"); // iapp->Options()->SetStringValue("derivative_test", "second-order"); // iapp->Options()->SetNumericValue("derivative_test_perturbation", 1e-6); // iapp->Options()->SetNumericValue("print_level", 10); // iapp->Options()->SetStringValue("derivative_test", "second-order"); // iapp->Options()->SetNumericValue("ma27_liw_init_factor", 50); // iapp->Options()->SetNumericValue("ma27_pivtol", 1e-6); // iapp->Options()->SetNumericValue("ma27_la_init_factor", 100); // iapp->Options()->SetNumericValue("ma27_meminc_factor", 5); // iapp->Options()->SetStringValue("mu_strategy", "adaptive"); iapp->Options()->SetNumericValue("tol", tol); // iapp->Options()->SetNumericValue("dual_inf_tol", 1e-6); // iapp->Options()->SetStringValue("derivative_test", "second-order"); // iapp->Options()->SetNumericValue("bound_relax_factor", 0); // iapp.Options()->SetIntegerValue("print_level", 5); // iapp->Options()->SetStringValue("derivative_test_print_all", "yes"); for(const auto &op: _str_options){ iapp->Options()->SetStringValue(op.first, op.second); } for(const auto &op: _int_options){ iapp->Options()->SetIntegerValue(op.first, op.second); } for(const auto &op: _double_options){ iapp->Options()->SetNumericValue(op.first, op.second); } if(!_model->_built){ /* Constraints have been added */ _model->reindex(); } _model->fill_in_maps(); SmartPtr<TNLP> tmp = new IpoptProgram<type>(_model); status = iapp->OptimizeTNLP(tmp); if (IsValid(iapp->Statistics())) { SmartPtr<SolveStatistics> stats = iapp->Statistics(); _nb_iterations = stats->IterationCount(); } if(_model->_objt==maximize){ *_model->_obj *= -1; _model->_obj->_val->at(0) *= -1; } DebugOn("Return status = " << status << endl); if (status == Solve_Succeeded) { optimal = true; _model->round_solution(); // Retrieve some statistics about the solve // printf("\n\nSolution of the primal variables:\n"); // _model->print_solution(); // return status; // return_status = status; } else if (status == Solved_To_Acceptable_Level) { // return 150; optimal = true; } else { optimal = false; } return_status = optimal ? 0 : -1; #else ipoptNotAvailable(); #endif } else if (_stype == clp){ #ifdef USE_CLP auto clp_prog = (ClpProgram*)(_prog.get()); clp_prog->prepare_model(); optimal = clp_prog->solve(); #else ClpNotAvailable(); #endif } else if(_stype==gurobi) { #ifdef USE_GUROBI try{ auto grb_prog = (GurobiProgram*)(_prog.get()); grb_prog->_output = output; // prog.grb_prog->reset_model(); grb_prog->prepare_model(); optimal = grb_prog->solve(relax,mipgap); return_status = optimal ? 0 : -1; }catch(GRBException e) { cerr << "\nError code = " << e.getErrorCode() << endl; cerr << e.getMessage() << endl; } #else gurobiNotAvailable(); #endif } else if(_stype==cplex) { #ifdef USE_CPLEX try{ auto cplex_prog = (CplexProgram*)(_prog.get()); cplex_prog->_output = output; cplex_prog->prepare_model(); optimal = cplex_prog->solve(relax,mipgap); return_status = optimal ? 0 : -1; } catch(IloException e) { cerr << e.getMessage() << endl; } #else cplexNotAvailable(); #endif } else if(_stype == _mosek) { #ifdef USE_MOSEK try{ auto mosek_prog = (MosekProgram*)(_prog.get()); mosek_prog->_output = output; mosek_prog->prepare_model(); bool ok = mosek_prog->solve(relax); return_status = ok ? 0 : -1; } catch(mosek::fusion::FusionException e) { cerr << e.toString() << endl; } #else mosekNotAvailable(); #endif } else if(_stype==bonmin) { #ifdef USE_BONMIN // using namespace Bonmin; BonminSetup bonmin; bonmin.initializeOptionsAndJournalist(); // bonmin.options()->SetIntegerValue("max_consecutive_infeasible", 100); // bonmin.options()->SetIntegerValue("solution_limit", 1); // bonmin.options()->SetIntegerValue("bb_log_level", 3); // bonmin.options()->SetNumericValue("allowable_gap", -1e5); // bonmin.options()->SetNumericValue("allowable_fraction_gap", -1e5); // bonmin.options()->SetNumericValue("tol", tol); // bonmin.options()->SetIntegerValue("print_level", 5); bonmin.options()->SetStringValue("tree_search_strategy", "top-node"); bonmin.options()->SetStringValue("warm_start", "optimum"); // bonmin.options()->SetStringValue("variable_selection", "random"); // bonmin.options()->SetStringValue("linear_solver", "ma57"); // bonmin.options()->SetIntegerValue("nlp_log_at_root", 5); bonmin.options()->SetNumericValue("cutoff", 0.9); // bonmin.options()->SetNumericValue("resolve_on_small_infeasibility", INFINITY); bonmin.options()->SetStringValue("heuristic_dive_MIP_fractional", "no"); bonmin.options()->SetStringValue("heuristic_dive_MIP_vectorLength", "no"); bonmin.options()->SetStringValue("heuristic_dive_fractional", "no"); bonmin.options()->SetStringValue("heuristic_dive_vectorLength", "no"); bonmin.options()->SetStringValue("heuristic_feasibility_pump", "no"); bonmin.options()->SetStringValue("pump_for_minlp", "no"); // bonmin.options()->SetStringValue("algorithm", "B-iFP"); bonmin.options()->SetStringValue("node_comparison", "best-guess"); // bonmin.options()->SetStringValue("dynamic_def_cutoff_decr", "yes"); bonmin.options()->SetIntegerValue("num_resolve_at_root", 5); _model->fill_in_maps(); SmartPtr<TMINLP> tmp = new BonminProgram(_model); bonmin.initialize(tmp); bool ok = false; // bonmin.initialize(prog.bonmin_prog); try { Bab bb; bb(bonmin); auto status = bb.mipStatus(); switch (bb.mipStatus()) { case Bab::MipStatuses::FeasibleOptimal: case Bab::MipStatuses::Feasible: ok = true; break; default: ok = false; } } catch(TNLPSolver::UnsolvedError *E) { //There has been a failure to solve a problem with Bonmin. std::cerr << "Bonmin has failed to solve a problem" << std::endl; ok = false; } catch(OsiTMINLPInterface::SimpleError &E) { std::cerr << E.className() << "::" << E.methodName() << std::endl << E.message() << std::endl; ok = false; } catch(CoinError &E) { std::cerr << E.className() << "::" << E.methodName() << std::endl << E.message() << std::endl; ok = false; } catch(...) { std::cerr << "Unknown error: Bonmin failed to solve the problem." << std::endl; ok = false; } if(_model->_objt==maximize){ *_model->_obj *= -1; _model->_obj->_val->at(0) *= -1; } return_status = ok ? 0 : -1; #else bonminNotAvailable(); #endif } if (optimal) { violated_constraints = _model->has_violated_constraints(tol); if (violated_constraints) { _model->reindex(); // _model->print(); // _model->print_symbolic(); // Constraint obj_cstr("obj_cstr_"+to_string(nb_it)); // obj_cstr += _model->_obj - _model->_obj_ub; // if (_model->_objt==minimize) { // _model->add(obj_cstr <= 0); // } // else { // _model->add(obj_cstr >= 0); // } // _model->print(); } } // if(violated_constraints && _stype!=ipopt) { // _model->reset(); // _model->print(); // } nb_it++; } if (nb_it>1) { DebugOn(endl << "####################" << endl); DebugOn("Solved in " << nb_it << " constraint generation iterations" << endl); DebugOn("####################" << endl); } _model->_status = return_status; if(_model->_status == 0){ DebugOff("Solved to Optimality/Acceptable "<< endl); } return return_status; } }; template<typename type> int run_models(const std::vector<shared_ptr<Model<type>>>& models, size_t start, size_t end, SolverType stype, type tol, const string& lin_solver="", unsigned max_iter = 1e6){ int return_status = -1; for (auto i = start; i<end; i++) { return_status = solver<type>((models.at(i)),stype).run(0, tol, lin_solver, max_iter); DebugOff("Return status "<<return_status << endl); // models.at(i)->print_solution(24); } return return_status; } // template<typename type> // int run_parallel(const initializer_list<shared_ptr<gravity::Model<type>>>& models, gravity::SolverType stype = ipopt, type tol = 1e-6, unsigned nr_threads=std::thread::hardware_concurrency(), const string& lin_solver="", unsigned max_iter = 1e6){ // return run_parallel(vector<shared_ptr<gravity::Model<type>>>(models), stype, tol, nr_threads, lin_solver, max_iter); // } /* Runs models stored in the vector in parallel, using solver of stype and tolerance tol */ //run_parallel,ref(vec),stype,tol,nr_threads,lin_solver,max_iter); int run_parallel(const vector<shared_ptr<gravity::Model<double>>>& models, gravity::SolverType stype = ipopt, double tol = 1e-6, unsigned nr_threads=std::thread::hardware_concurrency(), const string& lin_solver="", int max_iter=1e6); int run_parallel(const vector<shared_ptr<gravity::Model<double>>>& models, gravity::SolverType stype, double tol, unsigned nr_threads, int max_iter); #ifdef USE_MPI /** Send model status to all workers @models vector of models with stored solutions @limits vector specifying which models are assigned to which workers */ template<typename type> void send_status(const vector<shared_ptr<gravity::Model<type>>>& models, const vector<size_t>& limits){ int worker_id, nb_workers; auto err_rank = MPI_Comm_rank(MPI_COMM_WORLD, &worker_id); auto err_size = MPI_Comm_size(MPI_COMM_WORLD, &nb_workers); auto nb_workers_ = std::min((size_t)nb_workers, models.size()); MPI_Request send_reqs[nb_workers_*models.size()]; if(worker_id+1<limits.size()){ DebugOff("I'm worker ID: " << worker_id << ", I will be sending my model status to all workers " << endl); for (auto i = limits[worker_id]; i < limits[worker_id+1]; i++) { auto model = models[i]; for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } DebugOff("I'm worker ID: " << worker_id << ", I finished loading model status of task " << i << endl); MPI_Isend(&model->_status, 1, MPI_INT, w_id, i, MPI_COMM_WORLD, &send_reqs[(worker_id+1)*i]); DebugOff("I'm worker ID: " << worker_id << ", I finished sending model status of task " << i << "to worker " << w_id << endl); } } } MPI_Barrier(MPI_COMM_WORLD); DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the model status broadcasted by the other workers " << endl); for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } if(w_id+1<limits.size()){ for (auto i = limits[w_id]; i < limits[w_id+1]; i++) { auto model = models[i]; DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the model status of task " << i << " broadcasted by worker " << w_id << endl); MPI_Recv(&model->_status, 1, MPI_INT, w_id, i, MPI_COMM_WORLD, MPI_STATUS_IGNORE); DebugOff("I'm worker ID: " << worker_id <<", I received the model status of task " << i << " broadcasted by worker " << w_id << endl); } } } } /** Send model solutions to all workers @models vector of models with stored solutions @limits vector specifying which models are assigned to which workers */ template<typename type> void send_solution_all(const vector<shared_ptr<gravity::Model<type>>>& models, const vector<size_t>& limits){ int worker_id, nb_workers; auto err_rank = MPI_Comm_rank(MPI_COMM_WORLD, &worker_id); auto err_size = MPI_Comm_size(MPI_COMM_WORLD, &nb_workers); auto nb_workers_ = std::min((size_t)nb_workers, models.size()); MPI_Request send_reqs[nb_workers_*models.size()]; if(worker_id+1<limits.size()){ DebugOff("I'm worker ID: " << worker_id << ", I will be sending my solutions to all workers " << endl); for (auto i = limits[worker_id]; i < limits[worker_id+1]; i++) { auto model = models[i]; if(model->_status==0){ auto nb_vars = model->get_nb_vars(); vector<double> solution; solution.resize(nb_vars); model->get_solution(solution); for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } DebugOff("I'm worker ID: " << worker_id << ", I finished loading solution of task " << i << endl); MPI_Isend(&solution[0], nb_vars, MPI_DOUBLE, w_id, i, MPI_COMM_WORLD, &send_reqs[(worker_id+1)*i]); DebugOff("I'm worker ID: " << worker_id << ", I finished sending solution of task " << i << "to worker " << w_id << endl); } } } } MPI_Barrier(MPI_COMM_WORLD); DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the solutions broadcasted by the other workers " << endl); for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } if(w_id+1<limits.size()){ for (auto i = limits[w_id]; i < limits[w_id+1]; i++) { auto model = models[i]; if(model->_status==0){ auto nb_vars = model->get_nb_vars(); vector<double> solution; solution.resize(nb_vars); DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the solution of task " << i << " broadcasted by worker " << w_id << endl); MPI_Recv(&solution[0], nb_vars, MPI_DOUBLE, w_id, i, MPI_COMM_WORLD, MPI_STATUS_IGNORE); DebugOff("I'm worker ID: " << worker_id <<", I received the solution of task " << i << " broadcasted by worker " << w_id << endl); model->set_solution(solution); } } } } } /** Send model objective value to all workers @models vector of models with stored solutions @limits vector specifying which models are assigned to which workers */ template<typename type> void send_obj_all(const vector<shared_ptr<gravity::Model<type>>>& models, const vector<size_t>& limits){ int worker_id, nb_workers; auto err_rank = MPI_Comm_rank(MPI_COMM_WORLD, &worker_id); auto err_size = MPI_Comm_size(MPI_COMM_WORLD, &nb_workers); auto nb_workers_ = std::min((size_t)nb_workers, models.size()); MPI_Request send_reqs[nb_workers_*models.size()]; if(worker_id+1<limits.size()){ DebugOff("I'm worker ID: " << worker_id << ", I will be sending my objective value to all workers " << endl); for (auto i = limits[worker_id]; i < limits[worker_id+1]; i++) { auto model = models[i]; if(model->_status==0){ for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } DebugOff("I'm worker ID: " << worker_id << ", I finished loading objective value of task " << i << endl); MPI_Isend(&model->_obj->_val->at(0), 1, MPI_DOUBLE, w_id, i, MPI_COMM_WORLD, &send_reqs[(worker_id+1)*i]); DebugOff("I'm worker ID: " << worker_id << ", I finished sending objective value of task " << i << "to worker " << w_id << endl); } } } } MPI_Barrier(MPI_COMM_WORLD); DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the objective value broadcasted by the other workers " << endl); for (auto w_id = 0; w_id<nb_workers; w_id++) { if (worker_id == w_id){ continue; } if(w_id+1<limits.size()){ for (auto i = limits[w_id]; i < limits[w_id+1]; i++) { auto model = models[i]; if(model->_status==0){ DebugOff("I'm worker ID: " << worker_id <<", I'm waiting for the objective value of task " << i << " broadcasted by worker " << w_id << endl); MPI_Recv(&model->_obj->_val->at(0), 1, MPI_DOUBLE, w_id, i, MPI_COMM_WORLD, MPI_STATUS_IGNORE); DebugOff("I'm worker ID: " << worker_id <<", I received the objective value of task " << i << " broadcasted by worker " << w_id << endl); } } } } } /** Runs models stored in the vector in parallel using MPI @models vector of models to run in parallel @stype Solver type @tol numerical tolerance @max_iter max number of iterations per model @max_batch_time max wall clock time of each batch @nb_threads Number of parallel threads per worker @lin_solver linear system solver @share_all propagate model status and solutions to all workers, if false, only worker 0 has updated solutions and status flags for all models @share_all_obj propagate only objective values and model status to all workers */ int run_MPI(const vector<shared_ptr<gravity::Model<double>>>& models, gravity::SolverType stype = ipopt, double tol = 1e-6, unsigned nr_threads=std::thread::hardware_concurrency(), const string& lin_solver="", int max_iter = 1e6, int max_batch_time = 1e6, bool share_all = false, bool share_all_obj = false); void run_MPI(const initializer_list<shared_ptr<gravity::Model<double>>>& models, gravity::SolverType stype = ipopt, double tol = 1e-6, unsigned nr_threads=std::thread::hardware_concurrency(), const string& lin_solver="", int max_iter = 1e6, int max_batch_time = 1e6, bool share_all = false, bool share_all_obj = false); #endif } #endif /* defined(__Gravity____Solver__) */
47.871688
323
0.487298
[ "vector", "model" ]
10e01e8d6466a56268e5af76c4f980bf94dcc098
86,064
h
C
src/outputWriter/VTKWriter/template/vtk-unstructured.h
Dominik-Weinzierl/MolSim
ced15c201b7dca815f8cc178dec16e0ecd51bb37
[ "MIT" ]
1
2022-03-12T15:48:24.000Z
2022-03-12T15:48:24.000Z
src/outputWriter/VTKWriter/template/vtk-unstructured.h
Dominik-Weinzierl/MolSim
ced15c201b7dca815f8cc178dec16e0ecd51bb37
[ "MIT" ]
null
null
null
src/outputWriter/VTKWriter/template/vtk-unstructured.h
Dominik-Weinzierl/MolSim
ced15c201b7dca815f8cc178dec16e0ecd51bb37
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // /** * @file * @brief Generated from vtk-unstructured.xsd. */ #ifndef VTK_UNSTRUCTURED_H #define VTK_UNSTRUCTURED_H #ifndef XSD_CXX11 #define XSD_CXX11 #endif #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char unsigned_byte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short short_; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short unsigned_short; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int int_; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int unsigned_int; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long long_; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long non_positive_integer; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long non_negative_integer; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long positive_integer; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long negative_integer; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float float_; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double double_; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, simple_type > string; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, normalized_string > token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, token > name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, name > ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, ncname > id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone time_zone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, simple_type > date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, simple_type > duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, simple_type > gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, ncname > entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; /** * @brief Content order sequence entry. */ typedef ::xsd::cxx::tree::content_order content_order; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > namespace_info; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > namespace_infomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > list_stream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< double_ > as_double; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< decimal > as_decimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > expected_element; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > error_handler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::unique_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // class DataArrayList_t; class DataArray_t; class PieceUnstructuredGrid_t; class UnstructuredGrid_t; class PolyData_t; class VTKFile_t; class type; class PointData; class CellData; class Points; class Cells; #include <memory> // ::std::unique_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <utility> // std::move #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> /** * @brief List class corresponding to the %DataArrayList_t * schema type. * * This class has an interface of a standard C++ sequence (e.g., * std::vector). */ class DataArrayList_t: public ::xml_schema::simple_type, public ::xsd::cxx::tree::list< ::xml_schema::decimal, char, ::xsd::cxx::tree::schema_type::decimal > { public: /** * @brief Default constructor. * * Creates an empty list. */ DataArrayList_t (); /** * @brief Create a list with copies of the specified element. * * @param n A number of elements to copy. * @param x An element to copy. * * This constructor creates a list with @a n copies of @a x. */ DataArrayList_t (size_type n, const ::xml_schema::decimal& x); /** * @brief Create a list from an iterator range. * * @param begin An iterator pointing to the first element. * @param end An iterator pointing to the one past the last element. * * This constructor creates a list consisting of copies of the * elements in the range [begin,end). */ template < typename I > DataArrayList_t (const I& begin, const I& end) : ::xsd::cxx::tree::list< ::xml_schema::decimal, char, ::xsd::cxx::tree::schema_type::decimal > (begin, end, this) { } /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ DataArrayList_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Create an instance from a DOM attribute. * * @param a A DOM attribute to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ DataArrayList_t (const ::xercesc::DOMAttr& a, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Create an instance from a string fragment. * * @param s A string fragment to extract the data from. * @param e A pointer to DOM element containing the string fragment. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ DataArrayList_t (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ DataArrayList_t (const DataArrayList_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual DataArrayList_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Destructor. */ virtual ~DataArrayList_t (); }; /** * @brief Class corresponding to the %DataArray_t schema type. * * @nosubgrouping */ class DataArray_t: public ::DataArrayList_t { public: /** * @name type * * @brief Accessor and modifier functions for the %type * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::type type_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< type_type, char > type_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const type_type& type () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ type_type& type (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void type (const type_type& x); /** * @brief Set the attribute value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void type (::std::unique_ptr< type_type > p); //@} /** * @name Name * * @brief Accessor and modifier functions for the %Name * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::string Name_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< Name_type, char > Name_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const Name_type& Name () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ Name_type& Name (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void Name (const Name_type& x); /** * @brief Set the attribute value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void Name (::std::unique_ptr< Name_type > p); //@} /** * @name NumberOfComponents * * @brief Accessor and modifier functions for the %NumberOfComponents * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::integer NumberOfComponents_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< NumberOfComponents_type, char > NumberOfComponents_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const NumberOfComponents_type& NumberOfComponents () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ NumberOfComponents_type& NumberOfComponents (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void NumberOfComponents (const NumberOfComponents_type& x); //@} /** * @name format * * @brief Accessor and modifier functions for the %format * optional attribute with a default value. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::string format_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< format_type, char > format_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const format_type& format () const; /** * @brief Return the default value for the attribute. * * @return A read-only (constant) reference to the attribute's * default value. */ static const format_type& format_default_value (); //@} /** * @name offset * * @brief Accessor and modifier functions for the %offset * optional attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::integer offset_type; /** * @brief Attribute optional container type. */ typedef ::xsd::cxx::tree::optional< offset_type > offset_optional; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< offset_type, char > offset_traits; /** * @brief Return a read-only (constant) reference to the attribute * container. * * @return A constant reference to the optional container. */ const offset_optional& offset () const; /** * @brief Return a read-write reference to the attribute container. * * @return A reference to the optional container. */ offset_optional& offset (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void offset (const offset_type& x); /** * @brief Set the attribute value. * * @param x An optional container with the new value to set. * * If the value is present in @a x then this function makes a copy * of this value and sets it as the new value of the attribute. * Otherwise the attribute container is set the 'not present' state. */ void offset (const offset_optional& x); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from initializers for required * elements and attributes. */ DataArray_t (const type_type&, const Name_type&, const NumberOfComponents_type&); /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ DataArray_t (const ::DataArrayList_t&, const type_type&, const Name_type&, const NumberOfComponents_type&); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ DataArray_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ DataArray_t (const DataArray_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual DataArray_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ DataArray_t& operator= (const DataArray_t& x); //@} /** * @brief Destructor. */ virtual ~DataArray_t (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: ::xsd::cxx::tree::one< type_type > type_; ::xsd::cxx::tree::one< Name_type > Name_; ::xsd::cxx::tree::one< NumberOfComponents_type > NumberOfComponents_; ::xsd::cxx::tree::one< format_type > format_; static const format_type format_default_value_; offset_optional offset_; //@endcond }; /** * @brief Class corresponding to the %PieceUnstructuredGrid_t schema type. * * @nosubgrouping */ class PieceUnstructuredGrid_t: public ::xml_schema::type { public: /** * @name PointData * * @brief Accessor and modifier functions for the %PointData * required element. */ //@{ /** * @brief Element type. */ typedef ::PointData PointData_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< PointData_type, char > PointData_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const PointData_type& PointData () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ PointData_type& PointData (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void PointData (const PointData_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void PointData (::std::unique_ptr< PointData_type > p); //@} /** * @name CellData * * @brief Accessor and modifier functions for the %CellData * required element. */ //@{ /** * @brief Element type. */ typedef ::CellData CellData_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< CellData_type, char > CellData_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const CellData_type& CellData () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ CellData_type& CellData (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void CellData (const CellData_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void CellData (::std::unique_ptr< CellData_type > p); //@} /** * @name Points * * @brief Accessor and modifier functions for the %Points * required element. */ //@{ /** * @brief Element type. */ typedef ::Points Points_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< Points_type, char > Points_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const Points_type& Points () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ Points_type& Points (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void Points (const Points_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void Points (::std::unique_ptr< Points_type > p); //@} /** * @name Cells * * @brief Accessor and modifier functions for the %Cells * required element. */ //@{ /** * @brief Element type. */ typedef ::Cells Cells_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< Cells_type, char > Cells_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const Cells_type& Cells () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ Cells_type& Cells (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void Cells (const Cells_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void Cells (::std::unique_ptr< Cells_type > p); //@} /** * @name NumberOfPoints * * @brief Accessor and modifier functions for the %NumberOfPoints * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::integer NumberOfPoints_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< NumberOfPoints_type, char > NumberOfPoints_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const NumberOfPoints_type& NumberOfPoints () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ NumberOfPoints_type& NumberOfPoints (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void NumberOfPoints (const NumberOfPoints_type& x); //@} /** * @name NumberOfCells * * @brief Accessor and modifier functions for the %NumberOfCells * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::integer NumberOfCells_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< NumberOfCells_type, char > NumberOfCells_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const NumberOfCells_type& NumberOfCells () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ NumberOfCells_type& NumberOfCells (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void NumberOfCells (const NumberOfCells_type& x); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ PieceUnstructuredGrid_t (const PointData_type&, const CellData_type&, const Points_type&, const Cells_type&, const NumberOfPoints_type&, const NumberOfCells_type&); /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes * (::std::unique_ptr version). * * This constructor will try to use the passed values directly * instead of making copies. */ PieceUnstructuredGrid_t (::std::unique_ptr< PointData_type >, ::std::unique_ptr< CellData_type >, ::std::unique_ptr< Points_type >, ::std::unique_ptr< Cells_type >, const NumberOfPoints_type&, const NumberOfCells_type&); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ PieceUnstructuredGrid_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ PieceUnstructuredGrid_t (const PieceUnstructuredGrid_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual PieceUnstructuredGrid_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ PieceUnstructuredGrid_t& operator= (const PieceUnstructuredGrid_t& x); //@} /** * @brief Destructor. */ virtual ~PieceUnstructuredGrid_t (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: ::xsd::cxx::tree::one< PointData_type > PointData_; ::xsd::cxx::tree::one< CellData_type > CellData_; ::xsd::cxx::tree::one< Points_type > Points_; ::xsd::cxx::tree::one< Cells_type > Cells_; ::xsd::cxx::tree::one< NumberOfPoints_type > NumberOfPoints_; ::xsd::cxx::tree::one< NumberOfCells_type > NumberOfCells_; //@endcond }; /** * @brief Class corresponding to the %UnstructuredGrid_t schema type. * * @nosubgrouping */ class UnstructuredGrid_t: public ::xml_schema::type { public: /** * @name Piece * * @brief Accessor and modifier functions for the %Piece * required element. */ //@{ /** * @brief Element type. */ typedef ::PieceUnstructuredGrid_t Piece_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< Piece_type, char > Piece_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const Piece_type& Piece () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ Piece_type& Piece (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void Piece (const Piece_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void Piece (::std::unique_ptr< Piece_type > p); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ UnstructuredGrid_t (const Piece_type&); /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes * (::std::unique_ptr version). * * This constructor will try to use the passed values directly * instead of making copies. */ UnstructuredGrid_t (::std::unique_ptr< Piece_type >); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ UnstructuredGrid_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ UnstructuredGrid_t (const UnstructuredGrid_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual UnstructuredGrid_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ UnstructuredGrid_t& operator= (const UnstructuredGrid_t& x); //@} /** * @brief Destructor. */ virtual ~UnstructuredGrid_t (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: ::xsd::cxx::tree::one< Piece_type > Piece_; //@endcond }; /** * @brief Class corresponding to the %PolyData_t schema type. * * @nosubgrouping */ class PolyData_t: public ::xml_schema::type { public: /** * @name greeting * * @brief Accessor and modifier functions for the %greeting * required element. */ //@{ /** * @brief Element type. */ typedef ::xml_schema::string greeting_type; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< greeting_type, char > greeting_traits; /** * @brief Return a read-only (constant) reference to the element. * * @return A constant reference to the element. */ const greeting_type& greeting () const; /** * @brief Return a read-write reference to the element. * * @return A reference to the element. */ greeting_type& greeting (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void greeting (const greeting_type& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void greeting (::std::unique_ptr< greeting_type > p); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ PolyData_t (const greeting_type&); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ PolyData_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ PolyData_t (const PolyData_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual PolyData_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ PolyData_t& operator= (const PolyData_t& x); //@} /** * @brief Destructor. */ virtual ~PolyData_t (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: ::xsd::cxx::tree::one< greeting_type > greeting_; //@endcond }; /** * @brief Class corresponding to the %VTKFile_t schema type. * * The hello_t type consists of a greeting phrase and a * collection of names to which this greeting applies. * * @nosubgrouping */ class VTKFile_t: public ::xml_schema::type { public: /** * @name UnstructuredGrid * * @brief Accessor and modifier functions for the %UnstructuredGrid * optional element. */ //@{ /** * @brief Element type. */ typedef ::UnstructuredGrid_t UnstructuredGrid_type; /** * @brief Element optional container type. */ typedef ::xsd::cxx::tree::optional< UnstructuredGrid_type > UnstructuredGrid_optional; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< UnstructuredGrid_type, char > UnstructuredGrid_traits; /** * @brief Return a read-only (constant) reference to the element * container. * * @return A constant reference to the optional container. */ const UnstructuredGrid_optional& UnstructuredGrid () const; /** * @brief Return a read-write reference to the element container. * * @return A reference to the optional container. */ UnstructuredGrid_optional& UnstructuredGrid (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void UnstructuredGrid (const UnstructuredGrid_type& x); /** * @brief Set the element value. * * @param x An optional container with the new value to set. * * If the value is present in @a x then this function makes a copy * of this value and sets it as the new value of the element. * Otherwise the element container is set the 'not present' state. */ void UnstructuredGrid (const UnstructuredGrid_optional& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly instead * of making a copy. */ void UnstructuredGrid (::std::unique_ptr< UnstructuredGrid_type > p); //@} /** * @name PolyData * * @brief Accessor and modifier functions for the %PolyData * optional element. */ //@{ /** * @brief Element type. */ typedef ::PolyData_t PolyData_type; /** * @brief Element optional container type. */ typedef ::xsd::cxx::tree::optional< PolyData_type > PolyData_optional; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< PolyData_type, char > PolyData_traits; /** * @brief Return a read-only (constant) reference to the element * container. * * @return A constant reference to the optional container. */ const PolyData_optional& PolyData () const; /** * @brief Return a read-write reference to the element container. * * @return A reference to the optional container. */ PolyData_optional& PolyData (); /** * @brief Set the element value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the element. */ void PolyData (const PolyData_type& x); /** * @brief Set the element value. * * @param x An optional container with the new value to set. * * If the value is present in @a x then this function makes a copy * of this value and sets it as the new value of the element. * Otherwise the element container is set the 'not present' state. */ void PolyData (const PolyData_optional& x); /** * @brief Set the element value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly instead * of making a copy. */ void PolyData (::std::unique_ptr< PolyData_type > p); //@} /** * @name type * * @brief Accessor and modifier functions for the %type * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::string type_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< type_type, char > type_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const type_type& type () const; /** * @brief Return a read-write reference to the attribute. * * @return A reference to the attribute. */ type_type& type (); /** * @brief Set the attribute value. * * @param x A new value to set. * * This function makes a copy of its argument and sets it as * the new value of the attribute. */ void type (const type_type& x); /** * @brief Set the attribute value without copying. * * @param p A new value to use. * * This function will try to use the passed value directly * instead of making a copy. */ void type (::std::unique_ptr< type_type > p); //@} /** * @name version * * @brief Accessor and modifier functions for the %version * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::string version_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< version_type, char > version_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const version_type& version () const; /** * @brief Return the default value for the attribute. * * @return A read-only (constant) reference to the attribute's * default value. */ static const version_type& version_default_value (); //@} /** * @name byte_order * * @brief Accessor and modifier functions for the %byte_order * required attribute. */ //@{ /** * @brief Attribute type. */ typedef ::xml_schema::string byte_order_type; /** * @brief Attribute traits type. */ typedef ::xsd::cxx::tree::traits< byte_order_type, char > byte_order_traits; /** * @brief Return a read-only (constant) reference to the attribute. * * @return A constant reference to the attribute. */ const byte_order_type& byte_order () const; /** * @brief Return the default value for the attribute. * * @return A read-only (constant) reference to the attribute's * default value. */ static const byte_order_type& byte_order_default_value (); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ VTKFile_t (const type_type&); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ VTKFile_t (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ VTKFile_t (const VTKFile_t& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual VTKFile_t* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ VTKFile_t& operator= (const VTKFile_t& x); //@} /** * @brief Destructor. */ virtual ~VTKFile_t (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: UnstructuredGrid_optional UnstructuredGrid_; PolyData_optional PolyData_; ::xsd::cxx::tree::one< type_type > type_; ::xsd::cxx::tree::one< version_type > version_; static const version_type version_default_value_; ::xsd::cxx::tree::one< byte_order_type > byte_order_; static const byte_order_type byte_order_default_value_; //@endcond }; /** * @brief Enumeration class corresponding to the %type * schema type. */ class type: public ::xml_schema::string { public: /** * @brief Underlying enum type. */ enum value { Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float32, Float64 }; /** * @brief Create an instance from the underlying enum value. * * @param v A enum value. */ type (value v); /** * @brief Create an instance from a C string. * * @param v A string value. */ type (const char* v); /** * @brief Create an instance from a string. * * @param v A string value. */ type (const ::std::string& v); /** * @brief Create an instance from the base value. * * @param v A base value. */ type (const ::xml_schema::string& v); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ type (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Create an instance from a DOM attribute. * * @param a A DOM attribute to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ type (const ::xercesc::DOMAttr& a, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Create an instance from a string fragment. * * @param s A string fragment to extract the data from. * @param e A pointer to DOM element containing the string fragment. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ type (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ type (const type& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual type* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Assign the underlying enum value. * * @param v A enum value. * @return A refernce to the instance. */ type& operator= (value v); /** * @brief Implicit conversion operator to the underlying * enum value. * * @return A enum value. */ virtual operator value () const { return _xsd_type_convert (); } //@cond protected: value _xsd_type_convert () const; public: static const char* const _xsd_type_literals_[10]; static const value _xsd_type_indexes_[10]; //@endcond }; /** * @brief Class corresponding to the %PointData schema type. * * @nosubgrouping */ class PointData: public ::xml_schema::type { public: /** * @name DataArray * * @brief Accessor and modifier functions for the %DataArray * sequence element. */ //@{ /** * @brief Element type. */ typedef ::DataArray_t DataArray_type; /** * @brief Element sequence container type. */ typedef ::xsd::cxx::tree::sequence< DataArray_type > DataArray_sequence; /** * @brief Element iterator type. */ typedef DataArray_sequence::iterator DataArray_iterator; /** * @brief Element constant iterator type. */ typedef DataArray_sequence::const_iterator DataArray_const_iterator; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< DataArray_type, char > DataArray_traits; /** * @brief Return a read-only (constant) reference to the element * sequence. * * @return A constant reference to the sequence container. */ const DataArray_sequence& DataArray () const; /** * @brief Return a read-write reference to the element sequence. * * @return A reference to the sequence container. */ DataArray_sequence& DataArray (); /** * @brief Copy elements from a given sequence. * * @param s A sequence to copy elements from. * * For each element in @a s this function makes a copy and adds it * to the sequence. Note that this operation completely changes the * sequence and all old elements will be lost. */ void DataArray (const DataArray_sequence& s); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ PointData (); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ PointData (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ PointData (const PointData& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual PointData* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ PointData& operator= (const PointData& x); //@} /** * @brief Destructor. */ virtual ~PointData (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: DataArray_sequence DataArray_; //@endcond }; /** * @brief Class corresponding to the %CellData schema type. * * @nosubgrouping */ class CellData: public ::xml_schema::type { public: /** * @name DataArray * * @brief Accessor and modifier functions for the %DataArray * sequence element. */ //@{ /** * @brief Element type. */ typedef ::DataArray_t DataArray_type; /** * @brief Element sequence container type. */ typedef ::xsd::cxx::tree::sequence< DataArray_type > DataArray_sequence; /** * @brief Element iterator type. */ typedef DataArray_sequence::iterator DataArray_iterator; /** * @brief Element constant iterator type. */ typedef DataArray_sequence::const_iterator DataArray_const_iterator; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< DataArray_type, char > DataArray_traits; /** * @brief Return a read-only (constant) reference to the element * sequence. * * @return A constant reference to the sequence container. */ const DataArray_sequence& DataArray () const; /** * @brief Return a read-write reference to the element sequence. * * @return A reference to the sequence container. */ DataArray_sequence& DataArray (); /** * @brief Copy elements from a given sequence. * * @param s A sequence to copy elements from. * * For each element in @a s this function makes a copy and adds it * to the sequence. Note that this operation completely changes the * sequence and all old elements will be lost. */ void DataArray (const DataArray_sequence& s); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ CellData (); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ CellData (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ CellData (const CellData& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual CellData* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ CellData& operator= (const CellData& x); //@} /** * @brief Destructor. */ virtual ~CellData (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: DataArray_sequence DataArray_; //@endcond }; /** * @brief Class corresponding to the %Points schema type. * * @nosubgrouping */ class Points: public ::xml_schema::type { public: /** * @name DataArray * * @brief Accessor and modifier functions for the %DataArray * sequence element. */ //@{ /** * @brief Element type. */ typedef ::DataArray_t DataArray_type; /** * @brief Element sequence container type. */ typedef ::xsd::cxx::tree::sequence< DataArray_type > DataArray_sequence; /** * @brief Element iterator type. */ typedef DataArray_sequence::iterator DataArray_iterator; /** * @brief Element constant iterator type. */ typedef DataArray_sequence::const_iterator DataArray_const_iterator; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< DataArray_type, char > DataArray_traits; /** * @brief Return a read-only (constant) reference to the element * sequence. * * @return A constant reference to the sequence container. */ const DataArray_sequence& DataArray () const; /** * @brief Return a read-write reference to the element sequence. * * @return A reference to the sequence container. */ DataArray_sequence& DataArray (); /** * @brief Copy elements from a given sequence. * * @param s A sequence to copy elements from. * * For each element in @a s this function makes a copy and adds it * to the sequence. Note that this operation completely changes the * sequence and all old elements will be lost. */ void DataArray (const DataArray_sequence& s); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ Points (); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Points (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ Points (const Points& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual Points* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ Points& operator= (const Points& x); //@} /** * @brief Destructor. */ virtual ~Points (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: DataArray_sequence DataArray_; //@endcond }; /** * @brief Class corresponding to the %Cells schema type. * * @nosubgrouping */ class Cells: public ::xml_schema::type { public: /** * @name DataArray * * @brief Accessor and modifier functions for the %DataArray * sequence element. */ //@{ /** * @brief Element type. */ typedef ::DataArray_t DataArray_type; /** * @brief Element sequence container type. */ typedef ::xsd::cxx::tree::sequence< DataArray_type > DataArray_sequence; /** * @brief Element iterator type. */ typedef DataArray_sequence::iterator DataArray_iterator; /** * @brief Element constant iterator type. */ typedef DataArray_sequence::const_iterator DataArray_const_iterator; /** * @brief Element traits type. */ typedef ::xsd::cxx::tree::traits< DataArray_type, char > DataArray_traits; /** * @brief Return a read-only (constant) reference to the element * sequence. * * @return A constant reference to the sequence container. */ const DataArray_sequence& DataArray () const; /** * @brief Return a read-write reference to the element sequence. * * @return A reference to the sequence container. */ DataArray_sequence& DataArray (); /** * @brief Copy elements from a given sequence. * * @param s A sequence to copy elements from. * * For each element in @a s this function makes a copy and adds it * to the sequence. Note that this operation completely changes the * sequence and all old elements will be lost. */ void DataArray (const DataArray_sequence& s); //@} /** * @name Constructors */ //@{ /** * @brief Create an instance from the ultimate base and * initializers for required elements and attributes. */ Cells (); /** * @brief Create an instance from a DOM element. * * @param e A DOM element to extract the data from. * @param f Flags to create the new instance with. * @param c A pointer to the object that will contain the new * instance. */ Cells (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy constructor. * * @param x An instance to make a copy of. * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * * For polymorphic object models use the @c _clone function instead. */ Cells (const Cells& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); /** * @brief Copy the instance polymorphically. * * @param f Flags to create the copy with. * @param c A pointer to the object that will contain the copy. * @return A pointer to the dynamically allocated copy. * * This function ensures that the dynamic type of the instance is * used for copying and should be used for polymorphic object * models instead of the copy constructor. */ virtual Cells* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; /** * @brief Copy assignment operator. * * @param x An instance to make a copy of. * @return A reference to itself. * * For polymorphic object models use the @c _clone function instead. */ Cells& operator= (const Cells& x); //@} /** * @brief Destructor. */ virtual ~Cells (); // Implementation. // //@cond protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: DataArray_sequence DataArray_; //@endcond }; #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> /** * @name Parsing functions for the %VTKFile document root. * * The hello element is a root of the Hello XML vocabulary. * Every conforming document should start with this element. */ //@{ /** * @brief Parse a URI or a local file. * * @param uri A URI or a local file name. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function uses exceptions to report parsing errors. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (const ::std::string& uri, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a URI or a local file with an error handler. * * @param uri A URI or a local file name. * @param eh An error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (const ::std::string& uri, ::xml_schema::error_handler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a URI or a local file with a Xerces-C++ DOM error * handler. * * @param uri A URI or a local file name. * @param eh A Xerces-C++ DOM error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (const ::std::string& uri, ::xercesc::DOMErrorHandler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream. * * @param is A standrad input stream. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function uses exceptions to report parsing errors. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream with an error handler. * * @param is A standrad input stream. * @param eh An error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, ::xml_schema::error_handler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream with a Xerces-C++ DOM error * handler. * * @param is A standrad input stream. * @param eh A Xerces-C++ DOM error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, ::xercesc::DOMErrorHandler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream with a resource id. * * @param is A standrad input stream. * @param id A resource id. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * The resource id is used to identify the document being parsed in * diagnostics as well as to resolve relative paths. * * This function uses exceptions to report parsing errors. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, const ::std::string& id, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream with a resource id and an * error handler. * * @param is A standrad input stream. * @param id A resource id. * @param eh An error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * The resource id is used to identify the document being parsed in * diagnostics as well as to resolve relative paths. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, const ::std::string& id, ::xml_schema::error_handler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a standard input stream with a resource id and a * Xerces-C++ DOM error handler. * * @param is A standrad input stream. * @param id A resource id. * @param eh A Xerces-C++ DOM error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * The resource id is used to identify the document being parsed in * diagnostics as well as to resolve relative paths. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::std::istream& is, const ::std::string& id, ::xercesc::DOMErrorHandler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a Xerces-C++ input source. * * @param is A Xerces-C++ input source. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function uses exceptions to report parsing errors. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::xercesc::InputSource& is, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a Xerces-C++ input source with an error handler. * * @param is A Xerces-C++ input source. * @param eh An error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::xercesc::InputSource& is, ::xml_schema::error_handler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a Xerces-C++ input source with a Xerces-C++ DOM * error handler. * * @param is A Xerces-C++ input source. * @param eh A Xerces-C++ DOM error handler. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function reports parsing errors by calling the error handler. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::xercesc::InputSource& is, ::xercesc::DOMErrorHandler& eh, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a Xerces-C++ DOM document. * * @param d A Xerces-C++ DOM document. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (const ::xercesc::DOMDocument& d, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); /** * @brief Parse a Xerces-C++ DOM document. * * @param d A pointer to the Xerces-C++ DOM document. * @param f Parsing flags. * @param p Parsing properties. * @return A pointer to the root of the object model. * * This function is normally used together with the keep_dom and * own_dom parsing flags to assign ownership of the DOM document * to the object model. */ ::std::unique_ptr< ::VTKFile_t > VTKFile (::xml_schema::dom::unique_ptr< ::xercesc::DOMDocument > d, ::xml_schema::flags f = 0, const ::xml_schema::properties& p = ::xml_schema::properties ()); //@} #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> void operator<< (::xercesc::DOMElement&, const DataArrayList_t&); void operator<< (::xercesc::DOMAttr&, const DataArrayList_t&); void operator<< (::xml_schema::list_stream&, const DataArrayList_t&); void operator<< (::xercesc::DOMElement&, const DataArray_t&); void operator<< (::xercesc::DOMElement&, const PieceUnstructuredGrid_t&); void operator<< (::xercesc::DOMElement&, const UnstructuredGrid_t&); void operator<< (::xercesc::DOMElement&, const PolyData_t&); void operator<< (::xercesc::DOMElement&, const VTKFile_t&); /** * @name Serialization functions for the %VTKFile document root. * * The hello element is a root of the Hello XML vocabulary. * Every conforming document should start with this element. */ //@{ /** * @brief Serialize to a standard output stream. * * @param os A standrad output stream. * @param x An object model to serialize. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function uses exceptions to report serialization errors. */ void VTKFile (::std::ostream& os, const ::VTKFile_t& x, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to a standard output stream with an error handler. * * @param os A standrad output stream. * @param x An object model to serialize. * @param eh An error handler. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function reports serialization errors by calling the error * handler. */ void VTKFile (::std::ostream& os, const ::VTKFile_t& x, ::xml_schema::error_handler& eh, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to a standard output stream with a Xerces-C++ DOM * error handler. * * @param os A standrad output stream. * @param x An object model to serialize. * @param eh A Xerces-C++ DOM error handler. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function reports serialization errors by calling the error * handler. */ void VTKFile (::std::ostream& os, const ::VTKFile_t& x, ::xercesc::DOMErrorHandler& eh, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to a Xerces-C++ XML format target. * * @param ft A Xerces-C++ XML format target. * @param x An object model to serialize. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function uses exceptions to report serialization errors. */ void VTKFile (::xercesc::XMLFormatTarget& ft, const ::VTKFile_t& x, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to a Xerces-C++ XML format target with an error * handler. * * @param ft A Xerces-C++ XML format target. * @param x An object model to serialize. * @param eh An error handler. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function reports serialization errors by calling the error * handler. */ void VTKFile (::xercesc::XMLFormatTarget& ft, const ::VTKFile_t& x, ::xml_schema::error_handler& eh, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to a Xerces-C++ XML format target with a * Xerces-C++ DOM error handler. * * @param ft A Xerces-C++ XML format target. * @param x An object model to serialize. * @param eh A Xerces-C++ DOM error handler. * @param m A namespace information map. * @param e A character encoding to produce XML in. * @param f Serialization flags. * * This function reports serialization errors by calling the error * handler. */ void VTKFile (::xercesc::XMLFormatTarget& ft, const ::VTKFile_t& x, ::xercesc::DOMErrorHandler& eh, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), const ::std::string& e = "UTF-8", ::xml_schema::flags f = 0); /** * @brief Serialize to an existing Xerces-C++ DOM document. * * @param d A Xerces-C++ DOM document. * @param x An object model to serialize. * @param f Serialization flags. * * Note that it is your responsibility to create the DOM document * with the correct root element as well as set the necessary * namespace mapping attributes. */ void VTKFile (::xercesc::DOMDocument& d, const ::VTKFile_t& x, ::xml_schema::flags f = 0); /** * @brief Serialize to a new Xerces-C++ DOM document. * * @param x An object model to serialize. * @param m A namespace information map. * @param f Serialization flags. * @return A pointer to the new Xerces-C++ DOM document. */ ::xml_schema::dom::unique_ptr< ::xercesc::DOMDocument > VTKFile (const ::VTKFile_t& x, const ::xml_schema::namespace_infomap& m = ::xml_schema::namespace_infomap (), ::xml_schema::flags f = 0); //@} void operator<< (::xercesc::DOMElement&, const type&); void operator<< (::xercesc::DOMAttr&, const type&); void operator<< (::xml_schema::list_stream&, const type&); void operator<< (::xercesc::DOMElement&, const PointData&); void operator<< (::xercesc::DOMElement&, const CellData&); void operator<< (::xercesc::DOMElement&, const Points&); void operator<< (::xercesc::DOMElement&, const Cells&); #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // VTK_UNSTRUCTURED_H
24.216095
116
0.641348
[ "object", "vector", "model" ]
10e21f0c91475b510d8ca1093490a602653d1b40
9,741
h
C
Classes/Views/SGAnnotationView.h
simplegeo/SGAREnvironment
6f9196744ad7e7f19e94f50d41810aae015c389e
[ "BSD-3-Clause" ]
9
2015-01-13T15:09:50.000Z
2019-07-18T02:34:32.000Z
Classes/Views/SGAnnotationView.h
Jason-Cooke/SGAREnvironment
6f9196744ad7e7f19e94f50d41810aae015c389e
[ "BSD-3-Clause" ]
null
null
null
Classes/Views/SGAnnotationView.h
Jason-Cooke/SGAREnvironment
6f9196744ad7e7f19e94f50d41810aae015c389e
[ "BSD-3-Clause" ]
5
2015-08-31T20:27:01.000Z
2019-07-17T22:23:17.000Z
// // SGAnnotationView.h // SGAREnvironment // // Copyright (c) 2009-2010, SimpleGeo // 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 SimpleGeo 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. // // Created by Derek Smith. // #import <MapKit/MapKit.h> #import "SGTexture.h" #import "SGMath.h" @protocol SGAnnotationViewDelegate; /*! * @class SGAnnotationView * @abstract Used to display information about @link //simplegeo/ooc/intf/SGRecordAnnotation/SGAnnotation SGAnnotation @/link in an AR enviornment. * @discussion SGAnnotationViews are the only views that can be rendered in the @link //simplegeo/ooc/cl/SGARView SGARView @/link. * The annotation view has two different modes, when it is being inspected and when it is not being inspected. You can toggle through * inspection modes by calling @link inspectView: inspectView: @/link. When an annotation view is created it calls @link inspectView: inspectView: @/link * on itself with the value NO. When NO is specifed the view enters into target mode. If YES is passed into @link inspectView: inspectView: @/link, the view switches * to inspect mode. * Target mode is intended to be just a target in in the AR enviornment; something that allows the user to inspect further by generating a touch event. When * a touch event occurs on an annotation view, @link shouldInspectAnnotationView: shouldInspectAnntationView: @/link is called. Anytime throughout the life-cycle of * the view, you can call @link inspectView: inspectView: @/link and it will change its subviews properly, independent of its enviornment. * A SGAnnotationView has two display enviornments. The first is within the augmented reality view. The second is as a UIView was intended, using CoreAnimation. When the view is within * the AR enviornment, the orign within the @link frame frame @/link is ignored. The AR enviornment must place the view based on its relative position of the device and * the coordinate obtained from @link annotation annotation @/link. When the annotation view is rendered as a UIView, in most cases, * it will be a subview of @link SGARView SGARView @/link. */ @interface SGAnnotationView : UIView { id<MKAnnotation> annotation; NSString* reuseIdentifier; UIImageView* targetImageView; id<SGAnnotationViewDelegate> delegate; double bearing; double distance; double altitude; // This should probably be a bit-mask. BOOL enableOpenGL; BOOL isCapturable; BOOL isCaptured; BOOL isSelected; UIButton* radarTargetButton; UIImage* containerImage; @private SGPoint3* point; SGTexture* texture; SGTexture* radarPointTexture; BOOL needNewTexture; } /*! * @property * @abstract The source of the view's location in the AR enviornment. */ @property (nonatomic, retain) id<MKAnnotation> annotation; /*! * @property * @abstract Use this identifier to dequeue unused annotation views from @link //simplegeo/ooc/cl/SGARView SGARView @/link. */ @property (nonatomic, readonly) NSString* reuseIdentifier; /*! * @property * @abstract The image that is shown when the @link targetType targetType @/link is set to * @link kSGAnnotationViewTargetType_Glass kSGAnnotationViewTargetType_Glass @/link. */ @property (nonatomic, retain, readonly) UIImageView* targetImageView; /*! * @property * @abstract The delegate that recieves inspection and close notifications. */ @property (nonatomic, assign) id<SGAnnotationViewDelegate> delegate; /*! * @property * @abstract Ignores the UIView components of the view, and calls @link drawAnnotationView drawAnnotationView @/link * when it needs to be rendered in the AR enviornment. */ @property (nonatomic, assign) BOOL enableOpenGL; /*! * @property * @abstract The bearing of the view calculated from the @link //simplegeo/ooc/instn/SGAnnotation annotation @/link * and the device's current location. Bearing is expressed in radians. */ @property (nonatomic, assign) double bearing; /*! * @property * @abstract The distance of the view calculated from the @link //simplegeo/ooc/instn/SGAnnotation annotation @/link * and the device's current location. Distance is expressed in meters. */ @property (nonatomic, assign) double distance; /*! * @property * @abstract The altitude of the view. The default is 0. Altitude is expressed in meters. */ @property (nonatomic, assign) double altitude; /*! * @property * @abstract The UIButton that is displayed in the @link //simplegeo/ooc/cl/SGRadar SGRadar @/link. */ @property (nonatomic, readonly) UIButton* radarTargetButton; /*! * @property * @abstract If YES, the view can be added to the @link //simplegeo/ooc/cl/SGMovableStack SGMovableStack @/link. Otherwise, NO. */ @property (nonatomic, assign) BOOL isCapturable; /*! * @property * @abstract If YES, the view is either added to a @link //simplegeo/ooc/cl/SGMovableStack SGMovableStack @/link or * a @link //simplegeo/ooc/cl/SGAnnotationViewContainer SGAnnotationViewContainer @/link. Otherwise, NO. */ @property (nonatomic, assign) BOOL isCaptured; /*! * @property * @abstract The point at which the @link texture texture @/link is drawn * in the OpenGL environment. * @discussion This property should never be mutated by anything else * besides @link //simplegeo/ooc/cl/SG3DOverlayEnvironment SG3DOverlayEnvironment @/link. The value * is set everytime the view is drawn in OpenGL and is only referenced whenever a touch event occurs * on the @link //simplegeo/ooc/cl/SG3DOverlayView SG3DOverlayView @/link. */ @property (nonatomic, assign) SGPoint3* point; /*! * @property * @abstract The texture that represents this view. */ @property (nonatomic, readonly) SGTexture* texture; /*! * @property * @abstract Determines whether or not a new texture needs to be * generated for this view. */ @property (nonatomic, assign) BOOL needNewTexture; /*! * @property * @abstract The image used to display in a * @link //simplegeo/ooc/cl/SGAnnotationViewContainer SGAnnotationViewContainer @/link when the view * has reached the top of the stack. */ @property (nonatomic, retain) UIImage* containerImage; /*! * @method initWithFrame:reuseIdentifier: * @abstract Initialize a new annotation view. * @param frame The frame of the view. * @param identifier The identifier for the view. * @result A new instance of SGAnnotationView. */ - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString*)identifier; /*! * @method prepareForReuse * @abstract Called when the view is removed from the reuse queue. * @discussion The default implementaiton of this method resets its subviews. You can override it in your custom annotation views * and use it to put the view in a specific state. */ - (void) prepareForReuse; /*! * @method drawAnnotationView * @abstract The current implementation of this method does nothing. If @link enableOpenGL enableOpenGL @/link is set to YES, then * this method will be called everytime the AR enviornment needs to render the view. */ - (void) drawAnnotationView; @end /*! * @protocol SGAnnotationViewDelegate * @abstract Callback methods for @link //simplegeo/ooc/cl/SGAnnotationView SGAnnotationViews @link when * they recieve touch events. * @discussion Every annotation view has two modes: target and inspect. Target is the default mode. When the view is clicked, * @link shouldInspectAnnotationView: shouldInspectAnnotationView: @/link is called. * If the delegate returns a view, the annotation view will move into inspect mode. */ @protocol SGAnnotationViewDelegate <NSObject> @optional /*! * @method shouldInspectAnnotationView: * @abstract Asks the delegate whether the view should be inspected. * @discussion Notice how the return value is a UIView. You do not have to return the annotation * view that is passed in. You can create your own view to display. If you return the same * annotation view that was passed in, the AR view will call @link //simplegeo/ooc/instm/inspectView: inspectView: @/link. * If any view is returned, the view will be added to the AR view as a subview and will no longer be rendered in the AR * enviornment. * * @param view The view that is in question. * @result Any UIView if the view should enter into inspection mode; otherwise NO. */ - (UIView*) shouldInspectAnnotationView:(SGAnnotationView*)view; @end
39.922131
183
0.756904
[ "render" ]
10e33badd08afeb2a3a6b5a30f5f0b79a16c061f
1,184
h
C
connections/clients/ios/Internal/GNCCore.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
69
2021-10-18T00:37:29.000Z
2022-03-20T19:53:38.000Z
connections/clients/ios/Internal/GNCCore.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
14
2021-10-13T19:49:27.000Z
2022-03-31T22:19:13.000Z
connections/clients/ios/Internal/GNCCore.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
22
2021-10-20T12:36:47.000Z
2022-03-31T18:39:46.000Z
// Copyright 2020 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. #import <Foundation/Foundation.h> #include <memory> #include "connections/core.h" #include "connections/implementation/service_controller_router.h" NS_ASSUME_NONNULL_BEGIN /** This class contains the C++ Core object. */ @interface GNCCore : NSObject { @public std::unique_ptr<::location::nearby::connections::Core> _core; std::unique_ptr<::location::nearby::connections::ServiceControllerRouter> _service_controller_router; } @end /** This function returns the Core singleton, wrapped in an Obj-C object for lifetime management. */ GNCCore *GNCGetCore(); NS_ASSUME_NONNULL_END
31.157895
100
0.756757
[ "object" ]
10e4e9c7daf895cd81b20e0663425b5593232a96
5,135
h
C
VST3 SDK/vstgui4/vstgui/uidescription/uiviewswitchcontainer.h
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
2
2019-06-14T10:20:30.000Z
2020-02-19T17:53:42.000Z
VST3 SDK/vstgui4/vstgui/uidescription/uiviewswitchcontainer.h
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
null
null
null
VST3 SDK/vstgui4/vstgui/uidescription/uiviewswitchcontainer.h
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
1
2021-03-16T13:02:17.000Z
2021-03-16T13:02:17.000Z
//----------------------------------------------------------------------------- // VST Plug-Ins SDK // VSTGUI: Graphical User Interface Framework for VST plugins // // Version 4.3 // //----------------------------------------------------------------------------- // VSTGUI LICENSE // (c) 2015, Steinberg Media Technologies, 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 Steinberg Media Technologies nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #ifndef __uiviewswitchcontainer__ #define __uiviewswitchcontainer__ #include "../lib/cviewcontainer.h" #include "../lib/vstguifwd.h" #include "uidescriptionfwd.h" #include <vector> namespace VSTGUI { class IViewSwitchController; //----------------------------------------------------------------------------- class UIViewSwitchContainer : public CViewContainer { public: UIViewSwitchContainer (const CRect& size); ~UIViewSwitchContainer (); IViewSwitchController* getController () const { return controller; } void setController (IViewSwitchController* controller); // owns controller if it is a CBaseObject void setCurrentViewIndex (int32_t viewIndex); int32_t getCurrentViewIndex () const { return currentViewIndex; } void setAnimationTime (uint32_t ms); uint32_t getAnimationTime () const { return animationTime; } enum AnimationStyle { kFadeInOut, kMoveInOut, kPushInOut }; void setAnimationStyle (AnimationStyle style); AnimationStyle getAnimationStyle () const { return animationStyle; } bool attached (CView* parent) VSTGUI_OVERRIDE_VMETHOD; bool removed (CView* parent) VSTGUI_OVERRIDE_VMETHOD; //----------------------------------------------------------------------------- CLASS_METHODS (UIViewSwitchContainer, CViewContainer) protected: IViewSwitchController* controller; int32_t currentViewIndex; uint32_t animationTime; AnimationStyle animationStyle; }; //----------------------------------------------------------------------------- class IViewSwitchController { public: IViewSwitchController (UIViewSwitchContainer* viewSwitch) : viewSwitch (viewSwitch) {} virtual ~IViewSwitchController () {} void init () { viewSwitch->setController (this); } UIViewSwitchContainer* getViewSwitchContainer () const { return viewSwitch; } virtual CView* createViewForIndex (int32_t index) = 0; virtual void switchContainerAttached () = 0; virtual void switchContainerRemoved () = 0; protected: UIViewSwitchContainer* viewSwitch; }; //----------------------------------------------------------------------------- class UIDescriptionViewSwitchController : public CBaseObject, public IViewSwitchController { public: UIDescriptionViewSwitchController (UIViewSwitchContainer* viewSwitch, const IUIDescription* uiDescription, IController* uiController); CView* createViewForIndex (int32_t index) VSTGUI_OVERRIDE_VMETHOD; void switchContainerAttached () VSTGUI_OVERRIDE_VMETHOD; void switchContainerRemoved () VSTGUI_OVERRIDE_VMETHOD; CMessageResult notify (CBaseObject* sender, IdStringPtr message) VSTGUI_OVERRIDE_VMETHOD; void setTemplateNames (UTF8StringPtr templateNames); // comma separated void getTemplateNames (std::string& str); // comma separated void setSwitchControlTag (int32_t tag) { switchControlTag = tag; } int32_t getSwitchControlTag () const { return switchControlTag; } protected: const IUIDescription* uiDescription; IController* uiController; int32_t switchControlTag; int32_t currentIndex; CControl* switchControl; std::vector<std::string> templateNames; }; } // namespace #endif // __uiviewswitchcontainer__
39.806202
135
0.688608
[ "vector" ]
10e90b583c73725c1d6311a960ed11bd55fe07f5
5,803
h
C
NSUnderscore/NSArray+NSUnderscoreAdditions.h
rgerard/NSUnderscore
11c60283964c06722feff27bdf9d908a31e8657a
[ "MIT" ]
2
2016-01-06T23:30:19.000Z
2016-05-20T16:56:55.000Z
NSUnderscore/NSArray+NSUnderscoreAdditions.h
rgerard/NSUnderscore
11c60283964c06722feff27bdf9d908a31e8657a
[ "MIT" ]
null
null
null
NSUnderscore/NSArray+NSUnderscoreAdditions.h
rgerard/NSUnderscore
11c60283964c06722feff27bdf9d908a31e8657a
[ "MIT" ]
null
null
null
// // NSUnderscore.h // NSUnderscore // // Created by Ryan Gerard on 10/18/15. // Copyright © 2015 Ryan Gerard. All rights reserved. // #import <Foundation/Foundation.h> @interface NSArray (NSUnderscoreAdditions) /* * Iterates over a list of elements, yielding each in turn to an action function. * Example: * NSArray *objects = @[@(2), @(4)]; * __block NSInteger total = 0; * [objects each:^(NSNumber *object) { * total += object.integerValue; * }]; * Result: total == 6 */ - (void)each:(void(^)(id))action; /* * Produces a new array of values by mapping each value in list through a transformation function (action). * Example: * NSArray *objects = @[@(2), @(3)]; * NSArray *modifiedObjects = [objects map:(id)^(NSNumber *object) { * return @(object.integerValue * 2); * }]; * Result: modifiedObjects == @[ @(4), @(6) ] */ - (NSArray *)map:(id(^)(id))action; /* * Reduce boils down a list of values into a single value. Each successive step of it should be returned by action. * Example: * NSArray *objects = @[@(2), @(4)]; * NSNumber *reduced = [objects reduce:(id)^(NSNumber *object, NSNumber *previousValue) { * return @(object.integerValue + previousValue.integerValue); * }]; * Result: reduced == @(6) */ - (id)reduce:(id(^)(id, id))action; /* * Looks through each value in the list, returning an array of all the values that pass a truth test * Example: * NSArray *objects = @[@(2), @(4)]; * NSArray *filtered = [objects filter:(id)^(NSNumber *object) { * return object.integerValue == 2; * }]; * Result: filtered == @[ @(2) ] */ - (NSArray *)filter:(bool(^)(id))action; /* * Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter. * Example: * NSArray *objects = @[@(2), @(4)]; * NSArray *filtered = [objects reject:(id)^(NSNumber *object) { * return object.integerValue == 2; * }]; * Result: filtered == @[ @(5) ] */ - (NSArray *)reject:(bool(^)(id))action; /* * Returns true if all of the values in the list pass the predicate truth test. * Example: * NSArray *objects = @[@(2), @(4)]; * BOOL result = [objects every:^BOOL(NSNumber *object) { * return object.integerValue > 0; * }]; * Result: result == YES */ - (BOOL)every:(BOOL(^)(id))action; /* * Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found. * Example: * NSArray *objects = @[@(-2), @(4)]; * BOOL result = [objects some:^BOOL(NSNumber *object) { * return object.integerValue < 0; * }]; * Result: result == YES */ - (BOOL)some:(BOOL(^)(id))action; /* * A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. * Example: * NSArray *objects = @[@{@"id": @(1)}, @{@"id": @(2)}]; * NSArray *plucked = [objects pluck:@"id"]; * Result: plucked == [ @(1), @(2) ] */ - (NSArray *)pluck:(NSString *)propertyName; /* * Returns the maximum value in list. * Example: * NSArray *objects = @[@{@"id": @(10)}, @{@"id": @(20)}]; * NSDictionary *maxValue = [objects max:^NSInteger(NSDictionary *dict) { * NSNumber *dictVal = (NSNumber *)[dict objectForKey:@"id"]; * return dictVal.integerValue; * }]; * Result: maxValue == @{@"id": @(20)} */ - (id)max:(NSInteger(^)(id))action; /* * Returns the minimum value in list. * Example: * NSArray *objects = @[@{@"id": @(10)}, @{@"id": @(20)}]; * NSDictionary *minValue = [objects max:^NSInteger(NSDictionary *dict) { * NSNumber *dictVal = (NSNumber *)[dict objectForKey:@"id"]; * return dictVal.integerValue; * }]; * Result: minValue == @{@"id": @(10)} */ - (id)min:(NSInteger(^)(id))action; /* * Splits a collection into sets, grouped by the result of running each value through action. * Example: * NSArray *objects = @[@{@"token": @"ryan-1"}, @{@"token": @"ryan-2"}, @{@"token": @"test-1"}]; * NSDictionary *groupedObjects = [objects groupBy:^id(NSDictionary *val) { * NSString *token = [val objectForKey:@"token"]; * return [token substringToIndex:4]; * }]; * groupedObjects is: @{ @"ryan": [@{@"token": @"ryan-1"}, @{@"token": @"ryan-2"}], @"test": [@{@"token": @"test-1"}] } */ - (NSDictionary *)groupBy:(id(^)(id))action; /* * Given a list, and an action function that returns a key for each element in the list, returns an object with an index of each item. * Just like groupBy, but for when you know your keys are unique. * Example: * NSArray *objects = @[@{@"token": @"1"}, @{@"token": @"2"}, @{@"token": @"3"}]; * NSDictionary *indexedObjects = [objects indexBy:^id(NSDictionary *val) { * return [val objectForKey:@"token"]; * }]; * indexedObjects is: @{ @"1": @{@"token": @"1"}, @"2": @{@"token": @"ryan-2"}, @"3": @{@"token": @"3"}] } */ - (NSDictionary *)indexBy:(id(^)(id))action; /* * Sorts a list into groups and returns a count for the number of objects in each group. * Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group. * Example: * NSArray *objects = @[@(1), @(2), @(3)]; * NSDictionary *countedObjects = [objects countBy:^id(NSNumber *val) { * return val.integerValue % 2 == 0 ? @"even": @"odd"; * }]; * countedObjects is: @{ @"even": 1, @"odd": 2 } */ - (NSDictionary *)countBy:(id(^)(id))action; /* * Split array into two arrays: one whose elements all satisfy action and one whose elements all do not satisfy action. * Example: * NSArray *objects = @[@(1), @(2), @(3)]; * NSDictionary *partitionedObjects = [objects partition:^BOOL(NSNumber *val) { * return val.integerValue % 2 == 0; * }]; * partitionedObjects is: @[ @[ @(2) ], @[ @(1), @(3) ] ] */ - (NSArray *)partition:(BOOL(^)(id))action; @end
33.738372
152
0.61451
[ "object" ]
10ea483efcb7053eb510b35bf617d6ccc4903b46
1,721
h
C
src/library/f3d_engine.h
mwestphal/f3d
a2bebe2a6b049e54bfe8d0b5d0dcfd61684498c7
[ "BSD-3-Clause" ]
1
2021-11-25T19:30:05.000Z
2021-11-25T19:30:05.000Z
src/library/f3d_engine.h
mwestphal/f3d
a2bebe2a6b049e54bfe8d0b5d0dcfd61684498c7
[ "BSD-3-Clause" ]
null
null
null
src/library/f3d_engine.h
mwestphal/f3d
a2bebe2a6b049e54bfe8d0b5d0dcfd61684498c7
[ "BSD-3-Clause" ]
null
null
null
/** * @class engine * @brief Class used to create instance of other classes * * TODO improve doc */ #ifndef f3d_engine_h #define f3d_engine_h #include "f3d_export.h" #include <stdexcept> #include <string> namespace f3d { class options; class window; class loader; class interactor; class F3D_EXPORT engine { public: class exception : public std::runtime_error { public: exception(const std::string& what = "") : std::runtime_error(what) { } }; //======== Engine Flags ============= // engine::CREATE_WINDOW: Create a window to render into. // engine::CREATE_INTERACTOR: Create an interactor to interact with. // engine::WINDOW_OFFSCREEN: Create an offscreen window to render into, need CREATE_WINDOW. using flags_t = uint32_t; enum Flags : flags_t { FLAGS_NONE = 0, // 0000 CREATE_WINDOW = 1 << 0, // 0001 CREATE_INTERACTOR = 1 << 1, // 0010 WINDOW_OFFSCREEN = 1 << 2 // 0100 }; engine(const flags_t& flags); ~engine(); // Engine provide a default options // use this setter to use other options // copy options into engine void setOptions(const options& opt); // Engine provide a default options // use this setter to use other options // move options into engine void setOptions(options&& opt); options& getOptions(); window& getWindow(); loader& getLoader(); interactor& getInteractor(); // TODO: remove this function static const std::string& getAppTitle(); static void printVersion(); static void printReadersList(); private: class F3DInternals; F3DInternals* Internals; engine(const engine& opt) = delete; engine& operator=(const engine& opt) = delete; }; } #endif
21.246914
93
0.667635
[ "render" ]
10f0408a15b0987132a19351bdf5c743f340a886
1,061
h
C
include/rabbitmq-c/tcp_socket.h
salugoju/rabbitmq-c
08546893c3e63868c34a8786dee22380cee1c3c9
[ "MIT" ]
1,355
2015-01-02T16:01:43.000Z
2022-03-30T07:06:50.000Z
include/rabbitmq-c/tcp_socket.h
salugoju/rabbitmq-c
08546893c3e63868c34a8786dee22380cee1c3c9
[ "MIT" ]
381
2015-01-02T14:29:11.000Z
2022-03-23T09:28:35.000Z
include/rabbitmq-c/tcp_socket.h
salugoju/rabbitmq-c
08546893c3e63868c34a8786dee22380cee1c3c9
[ "MIT" ]
640
2015-01-08T17:08:23.000Z
2022-03-28T14:43:39.000Z
// Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors. // SPDX-License-Identifier: mit /** \file */ /** * A TCP socket connection. */ #ifndef RABBITMQ_C_TCP_SOCKET_H #define RABBITMQ_C_TCP_SOCKET_H #include <rabbitmq-c/amqp.h> #include <rabbitmq-c/export.h> AMQP_BEGIN_DECLS /** * Create a new TCP socket. * * Call amqp_connection_close() to release socket resources. * * \return A new socket object or NULL if an error occurred. * * \since v0.4.0 */ AMQP_EXPORT amqp_socket_t *AMQP_CALL amqp_tcp_socket_new(amqp_connection_state_t state); /** * Assign an open file descriptor to a socket object. * * This function must not be used in conjunction with amqp_socket_open(), i.e. * the socket connection should already be open(2) when this function is * called. * * \param [in,out] self A TCP socket object. * \param [in] sockfd An open socket descriptor. * * \since v0.4.0 */ AMQP_EXPORT void AMQP_CALL amqp_tcp_socket_set_sockfd(amqp_socket_t *self, int sockfd); AMQP_END_DECLS #endif /* RABBITMQ_C_TCP_SOCKET_H */
22.104167
78
0.734213
[ "object" ]
10f47b2c2c8a75eb92bb37937521095e4efb70e9
2,562
h
C
resources/home/dnanexus/root/include/TRootDialog.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/home/dnanexus/root/include/TRootDialog.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/home/dnanexus/root/include/TRootDialog.h
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
1
2020-05-28T23:01:44.000Z
2020-05-28T23:01:44.000Z
// @(#)root/gui:$Id$ // Author: Fons Rademakers 20/02/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TRootDialog #define ROOT_TRootDialog ////////////////////////////////////////////////////////////////////////// // // // TRootDialog // // // // A TRootDialog is used to prompt for the arguments of an object's // // member function. A TRootDialog is created via the context menu's // // when selecting a member function taking arguments. // // // ////////////////////////////////////////////////////////////////////////// #include "TGFrame.h" class TRootContextMenu; class TRootDialog : public TGTransientFrame { private: TRootContextMenu *fMenu; // associated context menu TGLayoutHints *fL1; // label layout TGLayoutHints *fL2; // text entry layout TList *fWidgets; // label and text field widgets created in dialog Bool_t fOk; // if true show OK button Bool_t fCancel; // if true show Cancel button Bool_t fApply; // if true show Apply button Bool_t fHelp; // if true show Online Help button public: TRootDialog(TRootContextMenu *cmenu = 0, const TGWindow *main = 0, const char *title = "ROOT Dialog", Bool_t okB = kTRUE, Bool_t cancelB = kTRUE, Bool_t applyB = kFALSE, Bool_t helpB = kTRUE); virtual ~TRootDialog(); virtual void Add(const char *argname, const char *value, const char *type); //virtual void Add(TGComboBox *optionSel); virtual const char *GetParameters(); virtual void CloseWindow(); virtual void Popup(); virtual Bool_t HandleKey(Event_t *event); void TabPressed(); ClassDef(TRootDialog,0) //Native GUI method argument prompt dialog box }; #endif
38.818182
80
0.460578
[ "object" ]
10f9b4dad8a49a1c5ed6cb1f38879e5832d940de
902
h
C
sail/csrc/core/autograd/ActivationGrad.h
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
1
2021-04-28T16:29:02.000Z
2021-04-28T16:29:02.000Z
sail/csrc/core/autograd/ActivationGrad.h
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
56
2021-04-28T16:39:05.000Z
2021-07-29T01:13:25.000Z
sail/csrc/core/autograd/ActivationGrad.h
sail-ml/sail
e261ef22661aa267bcf32d1552be95d8b7255220
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <iostream> #include <vector> #include "Tensor.h" #include "TensorBody.h" #include "function.h" #include "ops/ops.h" namespace sail { namespace autograd { using TensorVector = std::vector<Tensor>; class Sigmoid : public Function { public: TensorBody::pointer sigmoid_stored; explicit Sigmoid() = default; Tensor forward(TensorVector inputs) override; TensorVector backward(Tensor& grad) override; }; class Softmax : public Function { public: Tensor softmax_stored; int axis; Softmax(int axis = 1) : axis(axis){}; Tensor forward(TensorVector inputs) override; TensorVector backward(Tensor& grad) override; }; class ReLU : public Function { public: explicit ReLU() = default; Tensor forward(TensorVector inputs) override; TensorVector backward(Tensor& grad) override; }; } // namespace autograd } // namespace sail
20.976744
49
0.707317
[ "vector" ]
10ffac2de2d75520a020b0df6b38b2b3fd8e9963
5,747
h
C
ui/gfx/codec/png_codec.h
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
ui/gfx/codec/png_codec.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
ui/gfx/codec/png_codec.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.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 UI_GFX_CODEC_PNG_CODEC_H_ #define UI_GFX_CODEC_PNG_CODEC_H_ #pragma once #include <string> #include <vector> #include "base/basictypes.h" #include "ui/base/ui_export.h" class SkBitmap; namespace gfx { class Size; // Interface for encoding and decoding PNG data. This is a wrapper around // libpng, which has an inconvenient interface for callers. This is currently // designed for use in tests only (where we control the files), so the handling // isn't as robust as would be required for a browser (see Decode() for more). // WebKit has its own more complicated PNG decoder which handles, among other // things, partially downloaded data. class UI_EXPORT PNGCodec { public: enum ColorFormat { // 3 bytes per pixel (packed), in RGB order regardless of endianness. // This is the native JPEG format. FORMAT_RGB, // 4 bytes per pixel, in RGBA order in memory regardless of endianness. FORMAT_RGBA, // 4 bytes per pixel, in BGRA order in memory regardless of endianness. // This is the default Windows DIB order. FORMAT_BGRA, // 4 bytes per pixel, in pre-multiplied kARGB_8888_Config format. For use // with directly writing to a skia bitmap. FORMAT_SkBitmap }; // Represents a comment in the tEXt ancillary chunk of the png. struct UI_EXPORT Comment { Comment(const std::string& k, const std::string& t); ~Comment(); std::string key; std::string text; }; // Calls PNGCodec::EncodeWithCompressionLevel with the default compression // level. static bool Encode(const unsigned char* input, ColorFormat format, const Size& size, int row_byte_width, bool discard_transparency, const std::vector<Comment>& comments, std::vector<unsigned char>* output); // Encodes the given raw 'input' data, with each pixel being represented as // given in 'format'. The encoded PNG data will be written into the supplied // vector and true will be returned on success. On failure (false), the // contents of the output buffer are undefined. // // When writing alpha values, the input colors are assumed to be post // multiplied. // // size: dimensions of the image // row_byte_width: the width in bytes of each row. This may be greater than // w * bytes_per_pixel if there is extra padding at the end of each row // (often, each row is padded to the next machine word). // discard_transparency: when true, and when the input data format includes // alpha values, these alpha values will be discarded and only RGB will be // written to the resulting file. Otherwise, alpha values in the input // will be preserved. // comments: comments to be written in the png's metadata. // compression_level: An integer between -1 and 9, corresponding to zlib's // compression levels. -1 is the default. static bool EncodeWithCompressionLevel(const unsigned char* input, ColorFormat format, const Size& size, int row_byte_width, bool discard_transparency, const std::vector<Comment>& comments, int compression_level, std::vector<unsigned char>* output); // Call PNGCodec::Encode on the supplied SkBitmap |input|, which is assumed // to be BGRA, 32 bits per pixel. The params |discard_transparency| and // |output| are passed directly to Encode; refer to Encode for more // information. During the call, an SkAutoLockPixels lock is held on |input|. static bool EncodeBGRASkBitmap(const SkBitmap& input, bool discard_transparency, std::vector<unsigned char>* output); // Decodes the PNG data contained in input of length input_size. The // decoded data will be placed in *output with the dimensions in *w and *h // on success (returns true). This data will be written in the 'format' // format. On failure, the values of these output variables are undefined. // // This function may not support all PNG types, and it hasn't been tested // with a large number of images, so assume a new format may not work. It's // really designed to be able to read in something written by Encode() above. static bool Decode(const unsigned char* input, size_t input_size, ColorFormat format, std::vector<unsigned char>* output, int* w, int* h); // Decodes the PNG data directly into the passed in SkBitmap. This is // significantly faster than the vector<unsigned char> version of Decode() // above when dealing with PNG files that are >500K, which a lot of theme // images are. (There are a lot of themes that have a NTP image of about ~1 // megabyte, and those require a 7-10 megabyte side buffer.) // // Returns true if data is non-null and can be decoded as a png, false // otherwise. static bool Decode(const unsigned char* input, size_t input_size, SkBitmap* bitmap); // Create a SkBitmap from a decoded BGRA DIB. The caller owns the returned // SkBitmap. static SkBitmap* CreateSkBitmapFromBGRAFormat( std::vector<unsigned char>& bgra, int width, int height); private: DISALLOW_COPY_AND_ASSIGN(PNGCodec); }; } // namespace gfx #endif // UI_GFX_CODEC_PNG_CODEC_H_
42.257353
79
0.663825
[ "vector" ]
80053c13a21bc9df01d02022fec619fd3f61d097
5,450
h
C
geo3d/include/CGAL/Lightweight_vector_3.h
vipuserr/vipuserr-Geological-hazard
2b29c03cdac6f5e1ceac4cd2f15b594040ef909c
[ "MIT" ]
187
2019-01-23T04:07:11.000Z
2022-03-27T03:44:58.000Z
ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Lightweight_vector_3.h
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
8
2019-03-22T13:27:38.000Z
2020-06-18T13:23:23.000Z
ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Lightweight_vector_3.h
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
34
2019-02-13T01:11:12.000Z
2022-02-28T03:29:40.000Z
// Copyright (c) 2007-2008 INRIA (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Laurent Saboret, Pierre Alliez #ifndef CGAL_LIGHTWEIGHT_VECTOR_3_H #define CGAL_LIGHTWEIGHT_VECTOR_3_H #include <CGAL/license/Poisson_surface_reconstruction_3.h> #include <CGAL/Vector_3.h> #include <CGAL/Origin.h> namespace CGAL { /// \internal /// The Lightweight_vector_3 class represents a 3D vector (oriented). /// The purpose of this class is to save memory as the actual vector /// is allocated only when needed. /// /// \cgalModels `Kernel::Vector_3` /// /// @tparam Gt Geometric traits class. template<class Gt> class Lightweight_vector_3 { // Public types public: typedef Gt Geom_traits; ///< Geometric traits class typedef typename Geom_traits::FT FT; typedef typename Geom_traits::RT RT; typedef typename Geom_traits::Vector_3 Vector; ///< Kernel's Vector_3 class. // Public methods public: /// Vector is (0,0,0) by default. Lightweight_vector_3(Null_vector = NULL_VECTOR) { m_pVector = NULL; } Lightweight_vector_3(const Vector& vector) { m_pVector = new Vector(vector); } Lightweight_vector_3(FT x, FT y, FT z) { m_pVector = new Vector(x,y,z); } Lightweight_vector_3(RT hx, RT hy, RT hz, RT hw) { m_pVector = new Vector(hx,hy,hz,hw); } /// Copy constructor Lightweight_vector_3(const Lightweight_vector_3& that) { m_pVector = (that.m_pVector == NULL) ? NULL : new Vector(*that.m_pVector); } template <class K> Lightweight_vector_3(const Lightweight_vector_3<K>& that) { Vector vector = that.get_vector(); m_pVector = (vector == NULL_VECTOR) ? NULL : new Vector(vector); } /// Operator =() Lightweight_vector_3& operator=(const Lightweight_vector_3& that) { if (m_pVector != NULL && that.m_pVector != NULL) { *m_pVector = *that.m_pVector; } else { delete m_pVector; m_pVector = (that.m_pVector == NULL) ? NULL : new Vector(*that.m_pVector); } return *this; } /// Destructor ~Lightweight_vector_3() { delete m_pVector; m_pVector = NULL; } /// Compare vectors bool operator==(const Lightweight_vector_3& that) { return Vector(*this) == Vector(that); } bool operator!=(const Lightweight_vector_3& that) { return ! (*this == that); } /// Gets (a copy of) the actual vector. operator Vector() const { if (m_pVector != NULL) return *m_pVector; else return NULL_VECTOR; } Vector get_vector() const { return *this; } FT x() const { return (m_pVector != NULL) ? m_pVector->x() : 0; } FT y() const { return (m_pVector != NULL) ? m_pVector->y() : 0; } FT z() const { return (m_pVector != NULL) ? m_pVector->z() : 0; } RT hx() const { return (m_pVector != NULL) ? m_pVector->hx() : 0; } RT hy() const { return (m_pVector != NULL) ? m_pVector->hy() : 0; } RT hz() const { return (m_pVector != NULL) ? m_pVector->hz() : 0; } RT hw() const { return (m_pVector != NULL) ? m_pVector->hw() : 1; } FT cartesian(int i) const { if (m_pVector != NULL) return m_pVector->cartesian(i); else return 0; } FT operator[](int i) const { if (m_pVector != NULL) return (*m_pVector)[i]; else if (i != 3) return 0; else return 1; } RT homogeneous(int i) const { if (m_pVector != NULL) return m_pVector->homogeneous(); else if (i != 3) return 0; else return 1; } int dimension() const { return 3; } Vector operator+(const Vector& that) const { return Vector(*this) + Vector(that); } Vector operator-(const Vector& that) const { return Vector(*this) - Vector(that); } FT operator*(const Vector& that) const { return Vector(*this) * Vector(that); } Vector operator-() const { if (m_pVector != NULL) return -(*m_pVector); else return NULL_VECTOR; } Vector operator/(RT c) const { if (m_pVector != NULL) return (*m_pVector) / c; else return NULL_VECTOR; } Vector operator*(FT c) const { if (m_pVector != NULL) return (*m_pVector) * c; else return NULL_VECTOR; } friend Vector operator*(FT c, const Lightweight_vector_3& vector) { return vector * c; } FT squared_length() const { if (m_pVector != NULL) return m_pVector->squared_length(); else return 0; } // Data private: Vector* m_pVector; // Vector (optional to save memory) }; } //namespace CGAL #endif //CGAL_LIGHTWEIGHT_VECTOR_3_H
24.660633
82
0.606422
[ "vector", "3d" ]
8009206f5721bdcbf35a21611bb102cfdb3b289c
10,250
h
C
core/math/face3.h
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
core/math/face3.h
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
core/math/face3.h
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* face3.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #pragma once #include "core/math/aabb.h" #include "core/math/plane.h" #include "core/math/transform.h" #include "core/math/vector3.h" class GODOT_EXPORT Face3 { public: enum Side { SIDE_OVER, SIDE_UNDER, SIDE_SPANNING, SIDE_COPLANAR }; Vector3 vertex[3]; /** * * @param p_plane plane used to split the face * @param p_res array of at least 3 faces, amount used in functio return * @param p_is_point_over array of at least 3 booleans, determining which face is over the plane, amount used in functio return * @param _epsilon constant used for numerical error rounding, to add "thickness" to the plane (so coplanar points can happen) * @return amount of faces generated by the split, either 0 (means no split possible), 2 or 3 */ int split_by_plane(const Plane &p_plane, Face3 *p_res, bool *p_is_point_over) const; Plane get_plane(ClockDirection p_dir = CLOCKWISE) const; Vector3 get_random_point_inside() const; Side get_side_of(const Face3 &p_face, ClockDirection p_clock_dir = CLOCKWISE) const; bool is_degenerate() const; real_t get_area() const; Vector3 get_median_point() const; Vector3 get_closest_point_to(const Vector3 &p_point) const; bool intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = nullptr) const; bool intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = nullptr) const; ClockDirection get_clock_dir() const; ///< todo, test if this is returning the proper clockwisity void get_support(const Vector3 &p_normal, const Transform &p_transform, Vector3 *p_vertices, int *p_count, int p_max) const; void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const; AABB get_aabb() const { AABB aabb(vertex[0], Vector3()); aabb.expand_to(vertex[1]); aabb.expand_to(vertex[2]); return aabb; } bool intersects_aabb(const AABB &p_aabb) const; _FORCE_INLINE_ bool intersects_aabb2(const AABB &p_aabb) const; operator String() const; constexpr Face3() = default; inline Face3(Vector3 p_v1, Vector3 p_v2, Vector3 p_v3) { vertex[0] = p_v1; vertex[1] = p_v2; vertex[2] = p_v3; } }; bool Face3::intersects_aabb2(const AABB &p_aabb) const { Vector3 perp = (vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]); Vector3 half_extents = p_aabb.size * 0.5; Vector3 ofs = p_aabb.position + half_extents; Vector3 sup = Vector3( (perp.x > 0) ? -half_extents.x : half_extents.x, (perp.y > 0) ? -half_extents.y : half_extents.y, (perp.z > 0) ? -half_extents.z : half_extents.z); real_t d = perp.dot(vertex[0]); real_t dist_a = perp.dot(ofs + sup) - d; real_t dist_b = perp.dot(ofs - sup) - d; if (dist_a * dist_b > 0) return false; //does not intersect the plane for(int ax=0; ax<3; ++ax){ real_t aabb_min = p_aabb.position[ax]; real_t aabb_max = p_aabb.position[ax] + p_aabb.size[ax]; real_t tri_min = vertex[0][ax], tri_max = vertex[0][ax]; for (int i = 1; i < 3; i++) { if (vertex[i][ax] > tri_max) tri_max = vertex[i][ax]; if (vertex[i][ax] < tri_min) tri_min = vertex[i][ax]; } if (tri_max < aabb_min || aabb_max < tri_min) return false; } Vector3 edge_norms[3] = { vertex[0] - vertex[1], vertex[1] - vertex[2], vertex[2] - vertex[0], }; for (int i = 0; i < 12; i++) { Vector3 from, to; switch (i) { case 0: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z); to = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z); } break; case 1: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z); } break; case 2: { from = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); } break; case 3: { from = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z); to = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); } break; case 4: { from = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); } break; case 5: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); } break; case 6: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); } break; case 7: { from = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); } break; case 8: { from = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); } break; case 9: { from = Vector3(p_aabb.position.x, p_aabb.position.y, p_aabb.position.z); to = Vector3(p_aabb.position.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); } break; case 10: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z); } break; case 11: { from = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y, p_aabb.position.z + p_aabb.size.z); to = Vector3(p_aabb.position.x + p_aabb.size.x, p_aabb.position.y + p_aabb.size.y, p_aabb.position.z + p_aabb.size.z); } break; } Vector3 e1 = from - to; for (int j = 0; j < 3; j++) { Vector3 e2 = edge_norms[j]; Vector3 axis = vec3_cross(e1, e2); if (axis.length_squared() < 0.0001f) continue; // coplanar //axis.normalize(); Vector3 sup2 = Vector3( (axis.x > 0) ? -half_extents.x : half_extents.x, (axis.y > 0) ? -half_extents.y : half_extents.y, (axis.z > 0) ? -half_extents.z : half_extents.z); real_t maxB = axis.dot(ofs + sup2); real_t minB = axis.dot(ofs - sup2); if (minB > maxB) { SWAP(maxB, minB); } real_t minT = 1e20f, maxT = -1e20f; for (int k = 0; k < 3; k++) { real_t vert_d = axis.dot(vertex[k]); if (vert_d > maxT) maxT = vert_d; if (vert_d < minT) minT = vert_d; } if (maxB < minT || maxT < minB) return false; } } return true; }
41.497976
136
0.549171
[ "transform" ]
80106036387029350f4a85651aabc430ed96f1f9
1,689
h
C
Source/Source/Tools/Dumper/DumpReport/stdafx.h
uvbs/FullSource
07601c5f18d243fb478735b7bdcb8955598b9a90
[ "MIT" ]
2
2018-07-26T07:58:14.000Z
2019-05-31T14:32:18.000Z
Jx3Full/Source/Source/Tools/Dumper/DumpReport/stdafx.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Tools/Dumper/DumpReport/stdafx.h
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #ifndef _STDAFX_H_ #define _STDAFX_H_ #define _CRT_SECURE_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #define _USE_32BIT_TIME_T #define DECLSPEC_DEPRECATED // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows XP or later. #define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. #define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. #endif #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #include <tchar.h> #include "KGPublic.h" #include <string> #include <vector> using namespace std; #if defined(UNICODE) || defined(_UNICODE) typedef std::wstring tstring; #else typedef std::string tstring; #endif #endif //_STDAFX_H_
34.469388
105
0.746596
[ "vector" ]
80190e9eb92d30ca86b8d487647646184350a761
5,693
h
C
tf2_src/public/steamnetworkingsockets/isteamnetworkingutils.h
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/public/steamnetworkingsockets/isteamnetworkingutils.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/public/steamnetworkingsockets/isteamnetworkingutils.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//====== Copyright Valve Corporation, All rights reserved. ==================== // // Purpose: misc networking utilities // //============================================================================= #ifndef ISTEAMNETWORKINGUTILS #define ISTEAMNETWORKINGUTILS #ifdef _WIN32 #pragma once #endif #include "steamnetworkingtypes.h" struct SteamDatagramRelayAuthTicket; //----------------------------------------------------------------------------- /// Misc networking utilities for checking the local networking environment /// and estimating pings. class ISteamNetworkingUtils { public: /// Fetch current timestamp. These values never go backwards, and /// the initial value is low enough that practically speaking it's /// not necessary to worry about the value wrapping around. virtual SteamNetworkingMicroseconds GetLocalTimestamp() = 0; /// Check if the ping data of sufficient recency is available, and if /// it's too old, start refreshing it. /// /// Games that use the ping location information will typically /// want to call this at boot time, to make sure all prerequisites /// are ready. Especially since the first measurement might take /// slightly longer than subsequent measurements. /// /// Returns true if sufficiently recent data is already available. /// /// Returns false if sufficiently recent data is not available. In this /// case, ping measurement is initiated, if it is not already active. /// (You cannot restart a measurement already in progress.) /// /// A FIXME event will be posted when measurement is completed. virtual bool CheckPingDataUpToDate( float flMaxAgeSeconds ) = 0; /// Return location info for the current host. Returns the approximate /// age of the data, in seconds, or -1 if no data is available. /// Note that this might return an age older than the age of your game's /// process, if the data was obtained before you game started. /// /// This always return the most up-to-date information we have available /// right now, even if we are in the middle of re-calculating ping times. virtual float GetLocalPingLocation( SteamNetworkPingLocation_t &result ) = 0; /// Return true if we are taking ping measurements to update our ping /// location or select optimal routing. Ping measurement typically takes /// a few seconds, perhaps up to 10 seconds. virtual bool IsPingMeasurementInProgress() = 0; /// Estimate the round-trip latency between two arbitrary locations, in /// milliseconds. This is a conservative estimate, based on routing through /// the relay network. For most basic connections based on SteamID, /// this ping time will be pretty accurate, since it will be based on the /// route likely to be actually used. /// /// If a direct IP route is used (perhaps via NAT traversal), then the route /// will be different, and the ping time might be better. Or it might actually /// be a bit worse! Standard IP routing is frequently suboptimal! /// /// but even in this case, the estimate obtained using this method is a /// reasonable upper bound on the ping time. (Also it has the advantage /// of returning immediately and not sending any packets.) /// /// In a few cases we might not able to estimate the route. In this case /// a negative value is returned. k_nSteamNetworkingPing_Failed means /// the reason was because of some networking difficulty. (Failure to /// ping, etc) k_nSteamNetworkingPing_Unknown is returned if we cannot /// currently answer the question for some other reason. virtual int EstimatePingTimeBetweenTwoLocations( const SteamNetworkPingLocation_t &location1, const SteamNetworkPingLocation_t &location2 ) = 0; /// Same as EstimatePingTime, but assumes that one location is the local host. /// This is a bit faster, especially if you need to calculate a bunch of /// these in a loop to find the fastest one. /// /// In rare cases this might return a slightly different estimate than combining /// GetLocalPingLocation with EstimatePingTimeBetweenTwoLocations. That's because /// this function uses a slightly more complete description virtual int EstimatePingTimeFromLocalHost( const SteamNetworkPingLocation_t &remoteLocation ) = 0; // FIXME: // // Check current internet connection status // // Low level ticket stuff. I need to get some advice and talk through how this should work // or how best to tuck it away and make it transparent. // virtual bool ReceivedTicket( const void *pvTicket, int cbTicket, SteamDatagramRelayAuthTicket *pOutParsedTicket ) = 0; virtual bool HasTicketForServer( CSteamID steamID ) = 0; virtual uint32 GetIPForServerSteamIDFromTicket( CSteamID steamID ) = 0; // // Low level network config stuff I haven't figure out how best to tuck away. // Dota and CSGO use it because we have gameservers in the datacenter, and // we need this information to do region selection. But most games won't // need it. // /// Fetch directly measured ping time from local host to a particular network PoP. /// Most games will not need to call this. virtual int GetPingToDataCenter( SteamNetworkingPOPID popID, SteamNetworkingPOPID *pViaRelayPoP ) = 0; virtual int GetDirectPingToPOP( SteamNetworkingPOPID popID ) = 0; /// Get number of network PoPs in the config virtual int GetPOPCount() = 0; /// Get list of all POP IDs virtual int GetPOPList( SteamNetworkingPOPID *list, int nListSz ) = 0; }; #define STEAMNETWORKINGUTILS_VERSION "SteamNetworkingUtils001" /// Get ISteamNetworkingUtils object. This will eventually go in Steam_api.h with all the rest of its kin STEAMDATAGRAMLIB_INTERFACE ISteamNetworkingUtils *SteamNetworkingUtils(); #endif // ISTEAMNETWORKINGUTILS
45.18254
145
0.733181
[ "object" ]
8019d13c0f66c9ebac5a74a53a8362758252eedb
13,003
h
C
renderdoc/core/sparse_page_table.h
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
6,181
2015-01-07T11:49:11.000Z
2022-03-31T21:46:55.000Z
renderdoc/core/sparse_page_table.h
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
2,015
2015-01-16T01:45:25.000Z
2022-03-25T12:01:06.000Z
renderdoc/core/sparse_page_table.h
PLohrmannAMD/renderdoc
ea16d31aa340581f5e505e0c734a8468e5d3d47f
[ "MIT" ]
1,088
2015-01-06T08:36:25.000Z
2022-03-30T03:31:21.000Z
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 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 #include "api/replay/data_types.h" #include "api/replay/rdcarray.h" #include "api/replay/rdcpair.h" #include "api/replay/resourceid.h" #include "api/replay/stringise.h" namespace Sparse { class PageTable; }; // namespace Sparse // we pre-declare this function so we can make it a friend inside the PageTable implementation template <class SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::PageTable &el); namespace Sparse { // used for co-ordinates as well as dimensions struct Coord { uint32_t x, y, z; bool operator==(const Coord &o) const { return x == o.x && y == o.y && z == o.z; } }; struct Page { ResourceId memory; uint64_t offset; bool operator==(const Page &o) const { return memory == o.memory && offset == o.offset; } }; struct PageRangeMapping { bool hasSingleMapping() const { return pages.empty(); } // the memory mapping if there's a single mapping. Only valid if pages below is empty Page singleMapping; // since with a single mapping we only store the 'base' page, we need an additional bool to // indicate if it's a single page re-used or if it's all subsequent pages used. bool singlePageReused = false; // the memory mappings per-page if there are different mappings per-page rdcarray<Page> pages; Page getPage(uint32_t idx, uint32_t pageSize) const { if(pages.empty()) { if(singlePageReused) return singleMapping; Page ret = singleMapping; ret.offset += pageSize * idx; return ret; } return pages[idx]; } void createPages(uint32_t numPages, uint32_t pageSize); }; struct MipTail { // the first mip that is in the mip tail uint32_t firstMip = 0; // the offset in bytes for the mip tail. uint64_t byteOffset = 0; // the stride in bytes for the mip tail between each array slice's mip stride. This is set to 0 // if there is only one mip tail uint64_t byteStride = 0; // the size in bytes for the mip tail uint64_t totalPackedByteSize = 0; // the pages for the mip tail (or buffer pages for buffers). If byteStride is 0 this is the // single set of pages for all array slices. If byteStride is non-zero then the first N pages // (with N = byteStride / pageByteSize) are for slice 0, the next N for slice 1, etc. rdcarray<PageRangeMapping> mappings; }; // shadows the page table for a sparse resource - buffer or texture - and handles updates and // retrieval. Currently the system is simple - we first store a page mapping per subresource. This // should hopefully cover most applications and avoids needing to allocate, update, and store/apply // a whole page table. If we detect a partial update we allocate a full page table and store the // mapping for each page. class PageTable { public: // initialise the page table for a buffer. We just need to know its size and the page size void Initialise(uint64_t bufferByteSize, uint32_t pageByteSize); // initialise the page table for a texture. We specify various properties about the texture and // its page shape/size and mip tail. // The mip tail starts at firstTailMip - if this is >= numMips then there is no mip tail. // mipTailOffset is an arbitrary offset which all mip tail bindings are relative to. It does // nothing but rebase the offset provided setMipTailRange. // mipTailStride is the byte stride between mip tails if they are stored separately per slice in // an array texture. Again this is arbitrary to offset the binding resource offset. If the stride // is 0 this means all slices have their mip tails consecutively packed. // mipTailTotalPackedSize is the *total packed size of the mip tails*. This can be calculated with // the size of one array slice's mip tail multiplied by the number of array slices. If the stride // is 0 this is the size of the whole mip tail of the resource. void Initialise(const Coord &overallTexelDim, uint32_t numMips, uint32_t numArraySlices, uint32_t pageByteSize, const Coord &pageTexelDim, uint32_t firstTailMip, uint64_t mipTailOffset, uint64_t mipTailStride, uint64_t mipTailTotalPackedSize); uint64_t GetSerialiseSize() const; inline uint32_t getPageByteSize() const { return m_PageByteSize; } inline Coord getPageTexelSize() const { return m_PageTexelSize; } inline Coord getResourceSize() const { return m_TextureDim; } // useful for D3D where the mip tail is indexed by subresource/array slice even if we treat it all // as one inline uint64_t getMipTailByteOffsetForSubresource(uint32_t subresource) const { const uint32_t arraySlice = (subresource / m_MipCount) % m_ArraySize; return m_MipTail.byteOffset + m_MipTail.byteStride * arraySlice; } inline uint32_t calcSubresource(uint32_t arraySlice, uint32_t mipLevel) const { return arraySlice * m_MipCount + mipLevel; } Coord calcSubresourcePageDim(uint32_t subresource) const; // is this subresource in the mip tail inline bool isSubresourceInMipTail(uint32_t subresource) const { const uint32_t mipLevel = subresource % m_MipCount; return mipLevel >= m_MipTail.firstMip; } // is this byte offset in the resource (according to the mip tail - no other offsets are known) inline bool isByteOffsetInResource(uint64_t byteOffset) const { const uint64_t mipTailSize = m_MipTail.byteStride == 0 ? m_MipTail.totalPackedByteSize : m_MipTail.byteStride * m_ArraySize; return byteOffset >= m_MipTail.byteOffset && byteOffset < m_MipTail.byteOffset + mipTailSize; } // read-only accessors to get current state uint32_t getNumSubresources() const { return (uint32_t)m_Subresources.size(); } uint32_t getArraySize() const { return m_ArraySize; } uint32_t getMipCount() const { return m_MipCount; } const PageRangeMapping &getSubresource(uint32_t subresource) const { return m_Subresources[subresource]; } const MipTail &getMipTail() const { return m_MipTail; } const PageRangeMapping &getMipTailMapping(uint32_t subresource) const { const uint32_t arraySlice = (subresource / m_MipCount) % m_ArraySize; return m_MipTail.mappings[arraySlice]; } uint64_t getMipTailSliceSize() const { return m_MipTail.totalPackedByteSize / m_ArraySize; } uint64_t getSubresourceByteSize(uint32_t subresource) const { const Coord subresourcePageDim = calcSubresourcePageDim(subresource); return subresourcePageDim.x * subresourcePageDim.y * subresourcePageDim.z * m_PageByteSize; } // set a contiguous range of pages, with offsets and sizes applied in bytes. // This is when you are setting XYZ resource pages to point to ABC memory pages. // useSinglePage means only one page of memory will be used for all pages in the resource. Think // of the case of mapping a single 'black' page to large areas of the resource, or NULL'ing out // mappings. // as a convenience it returns the resource offset where it finishes, since D3D allows // mismatched boundaries for tile ranges and memory regions uint64_t setMipTailRange(uint64_t resourceByteOffset, ResourceId memory, uint64_t memoryByteOffset, uint64_t byteSize, bool useSinglePage); inline uint64_t setBufferRange(uint64_t resourceByteOffset, ResourceId memory, uint64_t memoryByteOffset, uint64_t byteSize, bool useSinglePage) { return setMipTailRange(resourceByteOffset, memory, memoryByteOffset, byteSize, useSinglePage); } // set a 3D box of texel pages to a range of memory. // useSinglePage means only one page of memory will be used for all pages in the resource. Think // of the case of mapping a single 'black' page to large areas of the resource, or NULL'ing out // mappings. void setImageBoxRange(uint32_t subresource, const Coord &coord, const Coord &dim, ResourceId memory, uint64_t memoryByteOffset, bool useSinglePage); // set a series of tiles in x, y, z order starting at a given point and wrapping around the // overall image dimensions. In theory you could e.g. map 10 pages starting at page 6, when there // are only 8 pages to a row. It would update pages 6 and 7 in the first row then all pages in the // next row. This also allows wrapping from one subresource to the next // we accept a byte size for consistency with all other calls that work in bytes not pages, even // though this is only expected to be used by D3D which has this wrapping update operation and it // operates in pages - the calling code can mutiply by getPageByteSize(). // useSinglePage means only one page of memory will be used for all pages in the resource. Think // of the case of mapping a single 'black' page to large areas of the resource, or NULL'ing out // mappings // as a convenience it returns the co-ordinate and subresource where it finishes, since D3D allows // mismatched boundaries for tile ranges and memory regions. This interacts with the // updateMappings parameter which can skip applying any bindings and only advances the coord // 'cursor' rdcpair<uint32_t, Coord> setImageWrappedRange(uint32_t dstSubresource, const Coord &coord, uint64_t byteSize, ResourceId memory, uint64_t memoryByteOffset, bool useSinglePage, bool updateMappings = true); // copy pages from another page table, in D3D fashion. These take co-ordinates and dimensions in // tiles because copying between textures with different tile shapes seems possible and if we // expect inputs in texels we have to specify which page table's texel dimensions we're using, // which is probably more error prone than breaking the convention of not accepting parameters in // tiles. void copyImageBoxRange(uint32_t dstSubresource, const Coord &coordInTiles, const Coord &dimInTiles, const PageTable &srcPageTable, uint32_t srcSubresource, const Coord &srcCoordInTiles); void copyImageWrappedRange(uint32_t subresource, const Coord &coordInTiles, uint64_t numTiles, const PageTable &srcPageTable, uint32_t srcSubresource, const Coord &srcCoordInTiles); private: PageRangeMapping &getMipTailMapping(uint32_t subresource) { const uint32_t arraySlice = (subresource / m_MipCount) % m_ArraySize; return m_MipTail.mappings[arraySlice]; } // The image dimensions that we need. We don't care about the format or anything, we just need to // know the size in pages and the subresource setup Coord m_TextureDim = {}; uint32_t m_MipCount = 1; uint32_t m_ArraySize = 1; // the byte size of a page, constant over a resource uint32_t m_PageByteSize = 0; // the size of a page in texels Coord m_PageTexelSize = {}; // the page tables for each subresource, if this is an image. Note for buffers everything goes in // the "mipTail". // For simplicity and robustness of access every subresource has an entry here, even those // corresponding to mips that are in mip tails - the overhead is nominal with each entry being // 5*ptrsize = 40 bytes. rdcarray<PageRangeMapping> m_Subresources; MipTail m_MipTail; template <typename SerialiserType> friend void ::DoSerialise(SerialiserType &ser, PageTable &el); }; }; // namespace Sparse DECLARE_REFLECTION_STRUCT(Sparse::Coord); DECLARE_REFLECTION_STRUCT(Sparse::Page); DECLARE_REFLECTION_STRUCT(Sparse::PageRangeMapping); DECLARE_REFLECTION_STRUCT(Sparse::MipTail); DECLARE_REFLECTION_STRUCT(Sparse::PageTable);
45.624561
100
0.722064
[ "shape", "3d" ]
801ac821d96f4c7d56537d7268e226dfe9e5f7b4
32,011
h
C
core/connections/base_im.h
SammyEnigma/im-desktop
d93c1c335c8290b21b69c578c399edf61cb899e8
[ "Apache-2.0" ]
2
2020-10-23T06:27:27.000Z
2021-11-12T12:06:12.000Z
core/connections/base_im.h
john-preston/im-desktop
271e42db657bdaa8e261f318c627ca5414e0dd87
[ "Apache-2.0" ]
null
null
null
core/connections/base_im.h
john-preston/im-desktop
271e42db657bdaa8e261f318c627ca5414e0dd87
[ "Apache-2.0" ]
1
2022-03-25T16:10:33.000Z
2022-03-25T16:10:33.000Z
#pragma once #include "../../common.shared/patch_version.h" #include "accept_agreement_info.h" #include "wim/privacy_settings.h" #include "archive/history_message.h" #include "smartreply/smartreply_marker.h" #include "../Voip/VoipManager.h" namespace voip_manager { class VoipManager; struct VoipProtoMsg; struct WindowParams; struct VoipProxySettings; enum AvatarThemeType : unsigned short; } namespace core { class login_info; class im_login_id; class phone_info; class search_params; enum class file_sharing_function; enum class message_type; enum class sticker_size; enum class profile_state; enum class typing_status; enum class message_read_mode; class auto_callback; class masks; namespace wim { class im; class wim_packet; struct wim_packet_params; class chat_params; struct auth_parameters; enum class is_ping; enum class is_login; enum class is_updated_messages; } namespace archive { class message_header; class quote; struct shared_contact_data; struct geo_data; struct gallery_entry_id; typedef std::vector<int64_t> msgids_list; typedef std::vector<quote> quotes_vec; typedef std::map<std::string, std::string> mentions_map; using shared_contact = std::optional<shared_contact_data>; using geo = std::optional<geo_data>; using poll = std::optional<poll_data>; struct message_pack { std::string message_; quotes_vec quotes_; mentions_map mentions_; std::string internal_id_; core::message_type type_; uint64_t message_time_ = 0; std::string description_; std::string url_; common::tools::patch_version version_; shared_contact shared_contact_; geo geo_; poll poll_; smartreply::marker_opt smartreply_marker_; bool channel_ = false; }; struct delete_message_info { delete_message_info(int64_t _id, const std::string& _internal_id, bool _for_all) : id_(_id) , internal_id_(_internal_id) , for_all_(_for_all) { } int64_t id_; std::string internal_id_; bool for_all_; }; } namespace stickers { class face; } namespace smartreply { enum class type; } namespace themes { class wallpaper_loader; } namespace memory_stats { class memory_stats_collector; struct request_handle; struct partial_response; using request_id = int64_t; } class base_im { std::shared_ptr<voip_manager::VoipManager> voip_manager_; int32_t id_; // stickers // use it only this from thread std::shared_ptr<stickers::face> stickers_; std::shared_ptr<themes::wallpaper_loader> wp_loader_; protected: std::shared_ptr<core::memory_stats::memory_stats_collector> memory_stats_collector_; std::shared_ptr<masks> masks_; std::wstring get_contactlist_file_name() const; std::wstring get_my_info_file_name() const; std::wstring get_active_dialogs_file_name() const; std::wstring get_pinned_chats_file_name() const; std::wstring get_unimportant_file_name() const; std::wstring get_mailboxes_file_name() const; std::wstring get_im_data_path() const; std::wstring get_avatars_data_path() const; std::wstring get_file_name_by_url(const std::string& _url) const; std::wstring get_masks_path() const; std::wstring get_stickers_path() const; std::wstring get_im_downloads_path(const std::string &alt) const; std::wstring get_content_cache_path() const; std::wstring get_last_suggest_file_name() const; std::wstring get_search_history_path() const; std::wstring get_call_log_file_name() const; virtual std::string _get_protocol_uid() = 0; void set_id(int32_t _id); int32_t get_id() const; void create_masks(std::weak_ptr<wim::im> _im); std::shared_ptr<stickers::face> get_stickers(); std::shared_ptr<themes::wallpaper_loader> get_wallpaper_loader(); std::vector<std::string> get_audio_devices_names(); std::vector<std::string> get_video_devices_names(); public: base_im(const im_login_id& _login, std::shared_ptr<voip_manager::VoipManager> _voip_manager, std::shared_ptr<memory_stats::memory_stats_collector> _memory_stats_collector); virtual ~base_im(); virtual void connect() = 0; virtual std::wstring get_im_path() const = 0; // login functions virtual void login(int64_t _seq, const login_info& _info) = 0; virtual void login_normalize_phone(int64_t _seq, const std::string& _country, const std::string& _raw_phone, const std::string& _locale, bool _is_login) = 0; virtual void login_get_sms_code(int64_t _seq, const phone_info& _info, bool _is_login) = 0; virtual void login_by_phone(int64_t _seq, const phone_info& _info) = 0; virtual void start_attach_phone(int64_t _seq, const phone_info& _info) = 0; virtual std::string get_login() const = 0; virtual void logout(std::function<void()> _on_result) = 0; virtual wim::wim_packet_params make_wim_params() const = 0; virtual wim::wim_packet_params make_wim_params_general(bool _is_current_auth_params) const = 0; virtual void erase_auth_data() = 0; // when logout virtual void start_session(wim::is_ping _is_ping, wim::is_login _is_login) = 0; virtual void handle_net_error(int32_t err) = 0; virtual void phoneinfo(int64_t _seq, const std::string &phone, const std::string &gui_locale) = 0; // messaging functions virtual void send_message_to_contact( const int64_t _seq, const std::string& _contacts, core::archive::message_pack _pack) = 0; virtual void send_message_to_contacts( const int64_t _seq, const std::vector<std::string>& _contact, core::archive::message_pack _pack) = 0; virtual void update_message_to_contact( const int64_t _seq, const int64_t _id, const std::string& _contact, core::archive::message_pack _pack) = 0; virtual void send_message_typing(const int64_t _seq, const std::string& _contact, const core::typing_status& _status, const std::string& _id) = 0; // state virtual void set_state(const int64_t, const core::profile_state) = 0; // group chat virtual void remove_members(int64_t _seq, const std::string& _aimid, const std::string& _m_chat_members) = 0; virtual void add_members(int64_t _seq, const std::string& _aimid, const std::string& _m_chat_members_to_add) = 0; virtual void add_chat(int64_t _seq, const std::string& _m_chat_name, std::vector<std::string> _m_chat_members) = 0; // mrim virtual void get_mrim_key(int64_t _seq, const std::string& _email) = 0; // avatar function virtual void get_contact_avatar(int64_t _seq, const std::string& _contact, int32_t _avatar_size, bool _force) = 0; virtual void show_contact_avatar(int64_t _seq, const std::string& _contact, int32_t _avatar_size) = 0; virtual void remove_contact_avatars(int64_t _seq, const std::string& _contact) = 0; // history functions virtual void get_archive_messages(int64_t _seq_, const std::string& _contact, int64_t _from, int64_t _count_early, int64_t _count_later, bool _need_prefetch, bool _first_request, bool _after_search) = 0; virtual void get_archive_messages_buddies(int64_t _seq_, const std::string& _contact, std::shared_ptr<archive::msgids_list> _ids, wim::is_updated_messages) = 0; virtual void set_last_read(const std::string& _contact, int64_t _message, message_read_mode _mode) = 0; virtual void set_last_read_mention(const std::string& _contact, int64_t _message) = 0; virtual void set_last_read_partial(const std::string& _contact, int64_t _message) = 0; virtual void hide_dlg_state(const std::string& _contact) = 0; virtual void delete_archive_messages(const int64_t _seq, const std::string &_contact_aimid, const std::vector<archive::delete_message_info>& _messages) = 0; virtual void delete_archive_messages_from(const int64_t _seq, const std::string &_contact_aimid, const int64_t _from_id) = 0; virtual void delete_archive_all_messages(const int64_t _seq, std::string_view _contact_aimid) = 0; virtual void get_messages_for_update(const std::string& _contact) = 0; virtual void get_mentions(int64_t _seq, std::string_view _contact) = 0; virtual void get_message_context(int64_t _seq, const std::string& _contact, const int64_t _msgid) = 0; virtual void add_opened_dialog(const std::string& _contact) = 0; virtual void remove_opened_dialog(const std::string& _contact) = 0; virtual void get_stickers_meta(int64_t _seq, const std::string& _size) = 0; virtual void get_sticker(const int64_t _seq, const int32_t _set_id, const int32_t _sticker_id, std::string_view _fs_id, const core::sticker_size _size) = 0; virtual void get_stickers_pack_info(const int64_t _seq, const int32_t _set_id, const std::string& _store_id, const std::string& _file_id) = 0; virtual void add_stickers_pack(const int64_t _seq, const int32_t _set_id, std::string _store_id) = 0; virtual void remove_stickers_pack(const int64_t _seq, const int32_t _set_id, std::string _store_id) = 0; virtual void get_stickers_store(const int64_t _seq) = 0; virtual void search_stickers_store(const int64_t _seq, const std::string& _search_term) = 0; virtual void get_set_icon_big(const int64_t _seq, const int32_t _set_id) = 0; virtual void clean_set_icon_big(const int64_t _seq, const int32_t _set_id) = 0; virtual void set_sticker_order(const int64_t _seq, std::vector<int32_t> _values) = 0; virtual void get_fs_stickers_by_ids(const int64_t _seq, std::vector<std::pair<int32_t, int32_t>> _values) = 0; virtual void get_sticker_suggests(std::string _sn, std::string _text) = 0; virtual void get_smartreplies(std::string _aimid, int64_t _msgid, std::vector<smartreply::type> _types) = 0; virtual void clear_smartreply_suggests(const std::string_view _aimid) = 0; virtual void clear_smartreply_suggests_for_message(const std::string_view _aimid, const int64_t _msgid) = 0; virtual void load_cached_smartreplies(const std::string_view _aimid) const = 0; virtual void get_chat_home(int64_t _seq, const std::string& _tag) = 0; virtual void get_chat_info(int64_t _seq, const std::string& _aimid, const std::string& _stamp, int32_t _limit) = 0; virtual void get_chat_member_info(int64_t _seq, const std::string& _aimid, const std::vector<std::string>& _members) = 0; virtual void get_chat_members_page(int64_t _seq, std::string_view _aimid, std::string_view _role, uint32_t _page_size) = 0; virtual void get_chat_members_next_page(int64_t _seq, std::string_view _aimid, std::string_view _cursor, uint32_t _page_size) = 0; virtual void search_chat_members_page(int64_t _seq, std::string_view _aimid, std::string_view _role, std::string_view _keyword, uint32_t _page_size) = 0; virtual void search_chat_members_next_page(int64_t _seq, std::string_view _aimid, std::string_view _cursor, uint32_t _page_size) = 0; virtual void get_chat_contacts(int64_t _seq, const std::string& _aimid, const std::string& _cursor, uint32_t _page_size) = 0; virtual void check_themes_meta_updates(int64_t _seq) = 0; virtual void get_theme_wallpaper(const std::string_view _wp_id) = 0; virtual void get_theme_wallpaper_preview(const std::string_view _wp_id) = 0; virtual void set_user_wallpaper(const std::string_view _wp_id, tools::binary_stream _image) = 0; virtual void remove_user_wallpaper(const std::string_view _wp_id) = 0; virtual void resolve_pending(int64_t _seq, const std::string& _aimid, const std::vector<std::string>& _contact, bool _approve) = 0; virtual void create_chat(int64_t _seq, const std::string& _aimid, const std::string& _name, std::vector<std::string> _members, core::wim::chat_params _params) = 0; virtual void mod_chat_params(int64_t _seq, const std::string& _aimid, core::wim::chat_params _params) = 0; virtual void mod_chat_name(int64_t _seq, const std::string& _aimid, const std::string& _name) = 0; virtual void mod_chat_about(int64_t _seq, const std::string& _aimid, const std::string& _about) = 0; virtual void mod_chat_rules(int64_t _seq, const std::string& _aimid, const std::string& _rules) = 0; virtual void mod_chat_public(int64_t _seq, const std::string& _aimid, bool _public) = 0; virtual void mod_chat_join(int64_t _seq, const std::string& _aimid, bool _approved) = 0; virtual void mod_chat_link(int64_t _seq, const std::string& _aimid, bool _link) = 0; virtual void mod_chat_ro(int64_t _seq, const std::string& _aimid, bool _ro) = 0; virtual void mod_chat_stamp(int64_t _seq, const std::string& _aimid,const std::string& _stamp) = 0; virtual void set_attention_attribute(int64_t _seq, std::string _aimid, const bool _value, const bool _resume) = 0; virtual void block_chat_member(int64_t _seq, const std::string& _aimid, const std::string& _contact, bool _block, bool _remove_messages) = 0; virtual void set_chat_member_role(int64_t _seq, const std::string& _aimid, const std::string& _contact, const std::string& _role) = 0; virtual void pin_chat_message(int64_t _seq, const std::string& _aimid, int64_t _message, bool _is_unpin) = 0; virtual void get_mentions_suggests(int64_t _seq, const std::string& _aimid, const std::string& _pattern) = 0; // search functions virtual void search_dialogs_local(const std::string& search_patterns, const std::vector<std::string>& _aimids) = 0; virtual void search_contacts_local(const std::vector<std::vector<std::string>>& search_patterns, int64_t _req_id, unsigned fixed_patterns_count, const std::string& pattern) = 0; virtual void setup_search_dialogs_params(int64_t _req_id) = 0; virtual void clear_search_dialogs_params() = 0; virtual void add_search_pattern_to_history(const std::string_view _search_pattern, const std::string_view _contact) = 0; virtual void remove_search_pattern_from_history(const std::string_view _search_pattern, const std::string_view _contact) = 0; // cl virtual std::string get_contact_friendly_name(const std::string& contact_login) = 0; virtual void hide_chat(const std::string& _contact) = 0; virtual void mute_chat(const std::string& _contact, bool _mute) = 0; virtual void add_contact(int64_t _seq, const std::string& _aimid, const std::string& _group, const std::string& _auth_message) = 0; virtual void remove_contact(int64_t _seq, const std::string& _aimid) = 0; virtual void rename_contact(int64_t _seq, const std::string& _aimid, const std::string& _friendly) = 0; virtual void ignore_contact(int64_t _seq, const std::string& _aimid, bool ignore) = 0; virtual void get_ignore_list(int64_t _seq) = 0; virtual void pin_chat(const std::string& _contact) = 0; virtual void unpin_chat(const std::string& _contact) = 0; virtual void mark_unimportant(const std::string& _contact) = 0; virtual void remove_from_unimportant(const std::string& _contact) = 0; virtual void update_outgoing_msg_count(const std::string& _aimid, int _count) = 0; // voip //virtual void on_peer_list_updated(const std::vector<std::string>& peers) = 0; virtual void on_voip_call_request_calls(); //virtual void on_voip_call_set_proxy(const voip_manager::VoipProxySettings& proxySettings); virtual void on_voip_call_start(const std::vector<std::string> &contacts, const voip_manager::CallStartParams &params); virtual void on_voip_add_window(voip_manager::WindowParams& windowParams); virtual void on_voip_remove_window(void* hwnd); virtual void on_voip_call_end(const std::string &call_id, const std::string &contact, bool busy, bool conference); virtual void on_voip_call_accept(const std::string &call_id, bool video); virtual void on_voip_call_stop(); virtual void on_voip_proto_msg(bool allocate, const char* data, unsigned len, std::shared_ptr<auto_callback> _on_complete); virtual void on_voip_proto_ack(const voip_manager::VoipProtoMsg& msg, bool success); virtual void on_voip_update(); virtual void on_voip_reset(); virtual bool on_voip_avatar_actual_for_voip(const std::string& contact, unsigned avatar_size); virtual void on_voip_user_update_avatar(const std::string& contact, const unsigned char* data, unsigned size, unsigned avatar_h, unsigned avatar_w, voip_manager::AvatarThemeType theme); virtual void on_voip_user_update_avatar_no_video(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); //virtual void on_voip_user_update_avatar_camera_off(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); //virtual void on_voip_user_update_avatar_no_camera(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); virtual void on_voip_user_update_avatar_text(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); virtual void on_voip_user_update_avatar_text_header(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); virtual void on_voip_user_update_avatar_background(const std::string& contact, const unsigned char* data, unsigned size, unsigned h, unsigned w, voip_manager::AvatarThemeType theme); virtual void on_voip_window_update_background(void* hwnd, const unsigned char* data, unsigned size, unsigned w, unsigned h); virtual void on_voip_window_set_offsets(void* hwnd, unsigned l, unsigned t, unsigned r, unsigned b); virtual void on_voip_window_set_primary(void* hwnd, const std::string& contact); virtual void on_voip_window_set_conference_layout(void* hwnd, int); virtual void on_voip_window_set_hover(void* hwnd, bool); virtual void on_voip_window_set_large(void* hwnd, bool); virtual void on_voip_device_changed(std::string_view dev_type, const std::string& uid); virtual void on_voip_devices_changed(); virtual void on_voip_switch_media(bool video); virtual void on_voip_volume_change(int vol); virtual void on_voip_mute_switch(); virtual void on_voip_set_mute(bool mute); virtual void on_voip_mute_incoming_call_sounds(bool mute); virtual void on_voip_minimal_bandwidth_switch(); virtual void on_voip_load_mask(const std::string& path); virtual void on_voip_init_mask_engine(); virtual void voip_set_model_path(const std::string& _local_path); virtual bool has_created_call(); virtual void post_voip_msg_to_server(const voip_manager::VoipProtoMsg& msg) = 0; virtual void post_voip_alloc_to_server(const std::string& data) = 0; virtual std::shared_ptr<wim::wim_packet> prepare_voip_msg(const std::string& data) = 0; virtual std::shared_ptr<wim::wim_packet> prepare_voip_pac(const voip_manager::VoipProtoMsg& data) = 0; // files functions virtual void upload_file_sharing( const int64_t _seq, const std::string& _contact, const std::string& _file_name, std::shared_ptr<core::tools::binary_stream> _data, const std::string& _extension, const core::archive::quotes_vec& _quotes, const std::string& _description, const core::archive::mentions_map& _mentions, const std::optional<int64_t>& _duration) = 0; virtual void get_file_sharing_preview_size( const int64_t _seq, const std::string& _file_url, const int32_t _original_size) = 0; virtual void download_file_sharing_metainfo( const int64_t _seq, const std::string& _file_url) = 0; virtual void download_file_sharing( const int64_t _seq, const std::string& _contact, const std::string& _file_url, const bool _force_request_metainfo, const std::string& _filename, const std::string& _download_dir, bool _raise_priority) = 0; virtual void download_image( const int64_t _seq, const std::string& _file_url, const std::string& _destination, const bool _download_preview, const int32_t _preview_width, const int32_t _preview_height, const bool _ext_resource, const bool _raise_priority, const bool _with_data) = 0; virtual void download_link_metainfo( const int64_t _seq, const std::string& _url, const int32_t _preview_width, const int32_t _preview_height, const bool _load_preview, std::string_view _log_str) = 0; virtual void cancel_loader_task(std::string _url, std::optional<int64_t> _seq) = 0; virtual void abort_file_sharing_download(std::string _url, std::optional<int64_t> _seq) = 0; virtual void abort_file_sharing_upload( const int64_t _seq, const std::string & _contact, const std::string &_process_seq) = 0; virtual void raise_download_priority( const int64_t _task_id) = 0; virtual void download_file( priority_t _priority, const std::string& _file_url, const std::string& _destination, std::string_view _normalized_url, bool _is_binary_data, std::function<void(bool)> _on_result) = 0; virtual void get_external_file_path(const int64_t _seq, const std::string& _url) = 0; virtual void contact_switched(const std::string &_contact_aimid) = 0; virtual void speech_to_text(int64_t _seq, const std::string& _url, const std::string& _locale) = 0; // search for contacts virtual void search_contacts_server(int64_t _seq, const std::string_view _keyword, const std::string_view _phone) = 0; virtual void syncronize_address_book(const int64_t _seq, const std::string& _keyword, const std::vector<std::string>& _phone) = 0; virtual void search_dialogs_one(const int64_t _seq, const std::string_view _keyword, const std::string_view _contact) = 0; virtual void search_dialogs_all(const int64_t _seq, const std::string_view _keyword) = 0; virtual void search_dialogs_continue(const int64_t _seq, const std::string_view _cursor, const std::string_view _contact) = 0; virtual void update_profile(int64_t _seq, const std::vector<std::pair<std::string, std::string>>& _field) = 0; // live chats virtual void join_live_chat(int64_t _seq, const std::string& _stamp) = 0; virtual void set_avatar(const int64_t _seq, tools::binary_stream image, const std::string& _aimId, const bool _chat) = 0; // masks virtual void get_mask_id_list(int64_t _seq) = 0; virtual void get_mask_preview(int64_t _seq, const std::string& mask_id) = 0; virtual void get_mask_model(int64_t _seq) = 0; virtual void get_mask(int64_t _seq, const std::string& mask_id) = 0; virtual void get_existent_masks(int64_t _seq) = 0; virtual bool has_valid_login() const = 0; virtual void get_code_by_phone_call(const std::string& _ivr_url) = 0; virtual void get_voip_calls_quality_popup_conf(const int64_t _seq, const std::string& _locale, const std::string& _lang) = 0; virtual void get_logs_path(const int64_t _seq) = 0; virtual void remove_content_cache(const int64_t _seq) = 0; virtual void clear_avatars(const int64_t _seq) = 0; virtual void remove_omicron_stg(const int64_t _seq) = 0; virtual void report_contact(int64_t _seq, const std::string& _aimid, const std::string& _reason, const bool _ignore_and_close) = 0; virtual void report_stickerpack(const int32_t _id, const std::string& _reason) = 0; virtual void report_sticker(const std::string& _id, const std::string& _reason, const std::string& _aimid, const std::string& _chatId) = 0; virtual void report_message(const int64_t _id, const std::string& _text, const std::string& _reason, const std::string& _aimid, const std::string& _chatId) = 0; virtual void user_accept_gdpr(int64_t _seq, const accept_agreement_info& _accept_info) = 0; virtual void send_voip_calls_quality_report(int _score, const std::string& _survey_id, const std::vector<std::string>& _reasons, const std::string& _aimid); virtual void send_stat() = 0; virtual void get_dialog_gallery(const int64_t _seq, const std::string& _aimid, const std::vector<std::string>& _type, const archive::gallery_entry_id _after, const int _page_size, const bool _download_holes) = 0; virtual void get_dialog_gallery_by_msg(const int64_t _seq, const std::string& _aimid, const std::vector<std::string>& _type, int64_t _msg_id) = 0; virtual void request_gallery_state(const std::string& _aimId) = 0; virtual void get_gallery_index(const std::string& _aimId, const std::vector<std::string>& _type, int64_t _msg, int64_t _seq) = 0; virtual void make_gallery_hole(const std::string& _aimid, int64_t _from, int64_t _till) = 0; virtual void stop_gallery_holes_downloading(const std::string& _aimId) = 0; virtual void request_memory_usage(const int64_t _seq) = 0; virtual void report_memory_usage(const int64_t _seq, memory_stats::request_id _req_handle, const memory_stats::partial_response& _partial_response) = 0; virtual void get_ram_usage(const int64_t _seq) = 0; virtual void make_archive_holes(const int64_t _seq, const std::string& _archive) = 0; virtual void invalidate_archive_data(const int64_t _seq, const std::string& _archive, std::vector<int64_t> _ids) = 0; virtual void invalidate_archive_data(const int64_t _seq, const std::string& _archive, int64_t _from, int64_t _before_count, int64_t _after_count) = 0; virtual void on_ui_activity(const int64_t _time) = 0; virtual void close_stranger(const std::string& _contact) = 0; virtual void on_local_pin_set(const std::string& _password) = 0; virtual void on_local_pin_entered(const int64_t _seq, const std::string& _password) = 0; virtual void on_local_pin_disable(const int64_t _seq) = 0; virtual void get_id_info(const int64_t _seq, const std::string_view _id) = 0; virtual void get_user_info(const int64_t _seq, const std::string& _aimid) = 0; virtual void get_user_last_seen(const int64_t _seq, std::vector<std::string> _ids) = 0; virtual void set_privacy_settings(const int64_t _seq, core::wim::privacy_settings _settings) = 0; virtual void get_privacy_settings(const int64_t _seq) = 0; virtual void on_nickname_check(const int64_t _seq, const std::string& _nickname, bool _set_nick) = 0; virtual void on_group_nickname_check(const int64_t _seq, const std::string& _nickname) = 0; virtual void on_get_common_chats(const int64_t _seq, const std::string& _sn) = 0; virtual void get_poll(const int64_t _seq, const std::string& _poll_id) = 0; virtual void vote_in_poll(const int64_t _seq, const std::string& _poll_id, const std::string& _answer_id) = 0; virtual void revoke_vote(const int64_t _seq, const std::string& _poll_id) = 0; virtual void stop_poll(const int64_t _seq, const std::string& _poll_id) = 0; virtual void group_subscribe(const int64_t _seq, const std::string& _stamp) = 0; virtual void cancel_group_subscription(const int64_t _seq, const std::string& _stamp) = 0; virtual void suggest_group_nick(const int64_t _seq, const std::string& _sn, bool _public) = 0; virtual void get_bot_callback_answer(const int64_t& _seq, const std::string_view _chat_id, const std::string_view _callback_data, int64_t _msg_id) = 0; virtual void start_bot(const int64_t _seq, std::string_view _nick, std::string_view _params) = 0; virtual void create_conference(int64_t _seq, std::string_view _name, bool _is_webinar, std::vector<std::string> _participants, bool _call_participants) = 0; virtual void get_sessions() = 0; virtual void reset_session(std::string_view _session_hash) = 0; virtual void cancel_pending_join(std::string _sn) = 0; virtual void get_reactions(const std::string& _chat_id, std::shared_ptr<archive::msgids_list> _msg_ids, bool _first_load) = 0; virtual void add_reaction(const int64_t _seq, int64_t _msg_id, const std::string& _chat_id, const std::string& _reaction, const std::vector<std::string>& _reactions_list) = 0; virtual void remove_reaction(const int64_t _seq, int64_t _msg_id, const std::string& _chat_id) = 0; virtual void list_reactions(const int64_t _seq, int64_t _msg_id, const std::string& _chat_id, const std::string& _reaction, const std::string& _newer_than, const std::string& _older_than, int64_t _limit) = 0; virtual void set_status(std::string_view _status, std::chrono::seconds _duration) = 0; virtual void subscribe_status(const std::vector<std::string>& _contacts) = 0; virtual void unsubscribe_status(const std::vector<std::string>& _contacts) = 0; virtual void subscribe_call_room_info(const std::string& _room_id) = 0; virtual void unsubscribe_call_room_info(const std::string& _room_id) = 0; }; }
55.478336
212
0.676174
[ "vector" ]
801b7864e868c7713fc62d38929327c2712f7a29
1,713
h
C
Rocket/Engine/Geometry/Tetrahedra.h
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/Geometry/Tetrahedra.h
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/Geometry/Tetrahedra.h
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Memory/MemoryDefine.h" #include "Geometry/Sphere.h" #include "Geometry/Triangle.h" #include <Eigen/Eigen> #include <vector> #include <array> #include <atomic> namespace Rocket { namespace Geometry { class Tetrahedra { public: Tetrahedra(); Tetrahedra(const SpherePtr& sphere); Tetrahedra(const VertexPtr& p0, const VertexPtr& p1, const VertexPtr& p2, const VertexPtr& p3); void GenerateFaces(); void UpdateFaces(); void GenerateBasicParameter( const Eigen::Vector3d& p0, const Eigen::Vector3d& p1, const Eigen::Vector3d& p2, const Eigen::Vector3d& p3); void CreateBoundingTetrahedra(const SpherePtr& sphere); void CreateBoundingTetrahedra(const SpherePtr& sphere, const Eigen::Vector3d& x, const Eigen::Vector3d& y, const Eigen::Vector3d& z); Tetrahedra* GetLocateId(VertexPtr& v); TrianglePtr GetAdjacentSurface(Tetrahedra* t); bool IsInSphere(VertexPtr& v); private: static int32_t GenerateId() { static std::atomic<int32_t> id = 0; return id++; } public: // TODO : remove copy when possible int32_t id = 0; std::array<VertexPtr, 4> nodes = {}; std::array<TrianglePtr, 4> faces = {}; VertexPtr scenter; VertexPtr gcenter; double sround; double volume; double aspect; bool is_active = false; }; using TetrahedraPtr = std::shared_ptr<Tetrahedra>; } }
30.589286
145
0.566258
[ "geometry", "vector" ]
801bfcfce9445929a53844ab89a3063224e39fbc
50,824
h
C
Quake3e-2019-11-29/code/renderervk/tr_local.h
Daan4/Defrag-Scripting
3456a4db82171d4bc1b13ecda357e3de8e972ac5
[ "MIT" ]
3
2020-11-02T15:49:41.000Z
2021-06-22T07:38:18.000Z
Quake3e-2019-11-29/code/renderervk/tr_local.h
Daan4/Defrag-Scripting
3456a4db82171d4bc1b13ecda357e3de8e972ac5
[ "MIT" ]
null
null
null
Quake3e-2019-11-29/code/renderervk/tr_local.h
Daan4/Defrag-Scripting
3456a4db82171d4bc1b13ecda357e3de8e972ac5
[ "MIT" ]
1
2020-07-08T16:38:22.000Z
2020-07-08T16:38:22.000Z
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code 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. Quake III Arena source code 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 Quake III Arena source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #ifndef TR_LOCAL_H #define TR_LOCAL_H #define USE_VBO // store static world geometry in VBO #define USE_FOG_ONLY #define USE_FOG_COLLAPSE //#define USE_LEGACY_DLIGHTS // vq3 dynamic lights #define USE_PMLIGHT // promode dynamic lights via \r_dlightMode 1 #define MAX_REAL_DLIGHTS (MAX_DLIGHTS*2) #define MAX_LITSURFS (MAX_DRAWSURFS) #define MAX_FLARES 256 #include "../qcommon/q_shared.h" #include "../qcommon/qfiles.h" #include "../qcommon/qcommon.h" #include "../renderercommon/tr_public.h" #include "tr_common.h" #include "iqm.h" #ifdef USE_VULKAN #include "vk.h" // GL constants substitutions typedef enum { GL_RGBA4, GL_RGBA8, GL_RGBA, GL_RGB4_S3TC, GL_RGB5, GL_RGB8, GL_RGB, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_MODULATE, GL_ADD, GL_DECAL, GL_BACK_LEFT, GL_BACK_RIGHT } glCompat; #define GL_INDEX_TYPE uint32_t #define GLint int #define GLuint unsigned int #define GLboolean VkBool32 #else #include "qgl.h" #define GL_INDEX_TYPE GL_UNSIGNED_INT #endif typedef uint32_t glIndex_t; #define REFENTITYNUM_BITS 12 // as we actually using only 1 bit for dlight mask in opengl1 renderer #define REFENTITYNUM_MASK ((1<<REFENTITYNUM_BITS) - 1) // the last N-bit number (2^REFENTITYNUM_BITS - 1) is reserved for the special world refentity, // and this is reflected by the value of MAX_REFENTITIES (which therefore is not a power-of-2) #define MAX_REFENTITIES ((1<<REFENTITYNUM_BITS) - 1) #define REFENTITYNUM_WORLD ((1<<REFENTITYNUM_BITS) - 1) // 14 bits // can't be increased without changing bit packing for drawsurfs // see QSORT_SHADERNUM_SHIFT #define SHADERNUM_BITS 14 #define MAX_SHADERS (1<<SHADERNUM_BITS) #define SHADERNUM_MASK (MAX_SHADERS-1) typedef struct dlight_s { vec3_t origin; vec3_t origin2; vec3_t dir; // origin2 - origin vec3_t color; // range from 0.0 to 1.0, should be color normalized float radius; vec3_t transformed; // origin in local coordinate system vec3_t transformed2; // origin2 in local coordinate system int additive; // texture detail is lost tho when the lightmap is dark qboolean linear; #ifdef USE_PMLIGHT struct litSurf_s *head; struct litSurf_s *tail; #endif } dlight_t; // a trRefEntity_t has all the information passed in by // the client game, as well as some locally derived info typedef struct { refEntity_t e; float axisLength; // compensate for non-normalized axis #ifdef USE_LEGACY_DLIGHTS qboolean needDlights; // true for bmodels that touch a dlight #endif qboolean lightingCalculated; vec3_t lightDir; // normalized direction towards light vec3_t ambientLight; // color normalized to 0-255 int ambientLightInt; // 32 bit rgba packed vec3_t directedLight; #ifdef USE_PMLIGHT vec3_t shadowLightDir; // normalized direction towards light #endif qboolean intShaderTime; } trRefEntity_t; typedef struct { vec3_t origin; // in world coordinates vec3_t axis[3]; // orientation in world vec3_t viewOrigin; // viewParms->or.origin in local coordinates float modelMatrix[16]; } orientationr_t; //=============================================================================== typedef enum { SS_BAD, SS_PORTAL, // mirrors, portals, viewscreens SS_ENVIRONMENT, // sky box SS_OPAQUE, // opaque SS_DECAL, // scorch marks, etc. SS_SEE_THROUGH, // ladders, grates, grills that may have small blended edges // in addition to alpha test SS_BANNER, SS_FOG, SS_UNDERWATER, // for items that should be drawn in front of the water plane SS_BLEND0, // regular transparency and filters SS_BLEND1, // generally only used for additive type effects SS_BLEND2, SS_BLEND3, SS_BLEND6, SS_STENCIL_SHADOW, SS_ALMOST_NEAREST, // gun smoke puffs SS_NEAREST // blood blobs } shaderSort_t; #define MAX_SHADER_STAGES 8 typedef enum { GF_NONE, GF_SIN, GF_SQUARE, GF_TRIANGLE, GF_SAWTOOTH, GF_INVERSE_SAWTOOTH, GF_NOISE } genFunc_t; typedef enum { DEFORM_NONE, DEFORM_WAVE, DEFORM_NORMALS, DEFORM_BULGE, DEFORM_MOVE, DEFORM_PROJECTION_SHADOW, DEFORM_AUTOSPRITE, DEFORM_AUTOSPRITE2, DEFORM_TEXT0, DEFORM_TEXT1, DEFORM_TEXT2, DEFORM_TEXT3, DEFORM_TEXT4, DEFORM_TEXT5, DEFORM_TEXT6, DEFORM_TEXT7 } deform_t; typedef enum { AGEN_IDENTITY, AGEN_SKIP, AGEN_ENTITY, AGEN_ONE_MINUS_ENTITY, AGEN_VERTEX, AGEN_ONE_MINUS_VERTEX, AGEN_LIGHTING_SPECULAR, AGEN_WAVEFORM, AGEN_PORTAL, AGEN_CONST } alphaGen_t; typedef enum { CGEN_BAD, CGEN_IDENTITY_LIGHTING, // tr.identityLight CGEN_IDENTITY, // always (1,1,1,1) CGEN_ENTITY, // grabbed from entity's modulate field CGEN_ONE_MINUS_ENTITY, // grabbed from 1 - entity.modulate CGEN_EXACT_VERTEX, // tess.vertexColors CGEN_VERTEX, // tess.vertexColors * tr.identityLight CGEN_ONE_MINUS_VERTEX, CGEN_WAVEFORM, // programmatically generated CGEN_LIGHTING_DIFFUSE, CGEN_FOG, // standard fog CGEN_CONST // fixed color } colorGen_t; typedef enum { TCGEN_BAD, TCGEN_IDENTITY, // clear to 0,0 TCGEN_LIGHTMAP, TCGEN_TEXTURE, TCGEN_ENVIRONMENT_MAPPED, TCGEN_ENVIRONMENT_MAPPED_FP, // with correct first-person mapping TCGEN_FOG, TCGEN_VECTOR // S and T from world coordinates } texCoordGen_t; typedef enum { ACFF_NONE, ACFF_MODULATE_RGB, ACFF_MODULATE_RGBA, ACFF_MODULATE_ALPHA } acff_t; typedef struct { float base; float amplitude; float phase; float frequency; genFunc_t func; } waveForm_t; #define TR_MAX_TEXMODS 4 typedef enum { TMOD_NONE, TMOD_TRANSFORM, TMOD_TURBULENT, TMOD_SCROLL, TMOD_SCALE, TMOD_STRETCH, TMOD_ROTATE, TMOD_ENTITY_TRANSLATE } texMod_t; #define MAX_SHADER_DEFORMS 3 typedef struct { deform_t deformation; // vertex coordinate modification type vec3_t moveVector; waveForm_t deformationWave; float deformationSpread; float bulgeWidth; float bulgeHeight; float bulgeSpeed; } deformStage_t; typedef struct { texMod_t type; // used for TMOD_TURBULENT and TMOD_STRETCH waveForm_t wave; // used for TMOD_TRANSFORM float matrix[2][2]; // s' = s * m[0][0] + t * m[1][0] + trans[0] float translate[2]; // t' = s * m[0][1] + t * m[0][1] + trans[1] // used for TMOD_SCALE float scale[2]; // s *= scale[0] // t *= scale[1] // used for TMOD_SCROLL float scroll[2]; // s' = s + scroll[0] * time // t' = t + scroll[1] * time // + = clockwise // - = counterclockwise float rotateSpeed; } texModInfo_t; #define MAX_IMAGE_ANIMATIONS 8 typedef struct { image_t *image[MAX_IMAGE_ANIMATIONS]; int numImageAnimations; double imageAnimationSpeed; // -EC- set to double texCoordGen_t tcGen; vec3_t tcGenVectors[2]; int numTexMods; texModInfo_t *texMods; int videoMapHandle; qboolean isLightmap; qboolean isVideoMap; } textureBundle_t; #define NUM_TEXTURE_BUNDLES 2 typedef struct { qboolean active; textureBundle_t bundle[NUM_TEXTURE_BUNDLES]; waveForm_t rgbWave; colorGen_t rgbGen; waveForm_t alphaWave; alphaGen_t alphaGen; byte constantColor[4]; // for CGEN_CONST and AGEN_CONST unsigned stateBits; // GLS_xxxx mask GLint mtEnv; // 0, GL_MODULATE, GL_ADD, GL_DECAL acff_t adjustColorsForFog; qboolean isDetail; qboolean depthFragment; #ifdef USE_VULKAN uint32_t tessFlags; uint32_t vk_pipeline[2]; // normal,fogged uint32_t vk_portal_pipeline[2]; uint32_t vk_mirror_pipeline[2]; uint32_t vk_pipeline_df; // depthFragment uint32_t vk_portal_pipeline_df; uint32_t vk_mirror_pipeline_df; #endif #ifdef USE_VBO uint32_t color_offset; // within current shader uint32_t tex_offset[2]; // within current shader #endif } shaderStage_t; struct shaderCommands_s; typedef enum { FP_NONE, // surface is translucent and will just be adjusted properly FP_EQUAL, // surface is opaque but possibly alpha tested FP_LE // surface is trnaslucent, but still needs a fog pass (fog surface) } fogPass_t; typedef struct { float cloudHeight; image_t *outerbox[6], *innerbox[6]; } skyParms_t; typedef struct { vec3_t color; float depthForOpaque; } fogParms_t; typedef struct shader_s { char name[MAX_QPATH]; // game path, including extension int lightmapSearchIndex; // for a shader to match, both name and lightmapIndex must match int lightmapIndex; // for rendering int index; // this shader == tr.shaders[index] int sortedIndex; // this shader == tr.sortedShaders[sortedIndex] float sort; // lower numbered shaders draw before higher numbered qboolean defaultShader; // we want to return index 0 if the shader failed to // load for some reason, but R_FindShader should // still keep a name allocated for it, so if // something calls RE_RegisterShader again with // the same name, we don't try looking for it again qboolean explicitlyDefined; // found in a .shader file int surfaceFlags; // if explicitlyDefined, this will have SURF_* flags int contentFlags; qboolean entityMergable; // merge across entites optimizable (smoke, blood) qboolean isSky; skyParms_t sky; fogParms_t fogParms; float portalRange; // distance to fog out at qboolean multitextureEnv; // if shader has multitexture stage(s) cullType_t cullType; // CT_FRONT_SIDED, CT_BACK_SIDED, or CT_TWO_SIDED qboolean polygonOffset; // set for decals and other items that must be offset unsigned noMipMaps:1; // for console fonts, 2D elements, etc. unsigned noPicMip:1; // for images that must always be full resolution unsigned noLightScale:1; unsigned noVLcollapse:1; // ignore vertexlight mode fogPass_t fogPass; // draw a blended pass, possibly with depth test equals qboolean needsNormal; // not all shaders will need all data to be gathered qboolean needsST1; qboolean needsST2; qboolean needsColor; int numDeforms; deformStage_t deforms[MAX_SHADER_DEFORMS]; int numUnfoggedPasses; shaderStage_t *stages[MAX_SHADER_STAGES]; #ifdef USE_PMLIGHT int lightingStage; int lightingBundle; #endif qboolean fogCollapse; int tessFlags; #ifdef USE_VBO // VBO structures qboolean isStaticShader; int svarsSize; int iboOffset; int vboOffset; int normalOffset; int numIndexes; int numVertexes; int curVertexes; int curIndexes; #endif float lightmapOffset[2]; // within merged lightmap void (*optimalStageIteratorFunc)( void ); double clampTime; // time this shader is clamped to - set to double for frameloss fix -EC- double timeOffset; // current time offset for this shader - set to double for frameloss fix -EC- struct shader_s *remappedShader; // current shader this one is remapped too struct shader_s *next; } shader_t; // trRefdef_t holds everything that comes in refdef_t, // as well as the locally generated scene information typedef struct { int x, y, width, height; float fov_x, fov_y; vec3_t vieworg; vec3_t viewaxis[3]; // transformation matrix stereoFrame_t stereoFrame; int time; // time in milliseconds for shader effects and other time dependent rendering issues int rdflags; // RDF_NOWORLDMODEL, etc // 1 bits will prevent the associated area from rendering at all byte areamask[MAX_MAP_AREA_BYTES]; qboolean areamaskModified; // qtrue if areamask changed since last scene double floatTime; // tr.refdef.time / 1000.0 -EC- set to double // text messages for deform text shaders char text[MAX_RENDER_STRINGS][MAX_RENDER_STRING_LENGTH]; int num_entities; trRefEntity_t *entities; unsigned int num_dlights; struct dlight_s *dlights; int numPolys; struct srfPoly_s *polys; int numDrawSurfs; struct drawSurf_s *drawSurfs; #ifdef USE_PMLIGHT int numLitSurfs; struct litSurf_s *litSurfs; #endif } trRefdef_t; //================================================================================= // max surfaces per-skin // This is an arbitry limit. Vanilla Q3 only supported 32 surfaces in skins but failed to // enforce the maximum limit when reading skin files. It was possile to use more than 32 // surfaces which accessed out of bounds memory past end of skin->surfaces hunk block. #define MAX_SKIN_SURFACES 256 // skins allow models to be retextured without modifying the model file typedef struct { char name[MAX_QPATH]; shader_t *shader; } skinSurface_t; typedef struct skin_s { char name[MAX_QPATH]; // game path, including extension int numSurfaces; skinSurface_t *surfaces; // dynamically allocated array of surfaces } skin_t; typedef struct { int originalBrushNumber; vec3_t bounds[2]; unsigned colorInt; // in packed byte format vec4_t color; float tcScale; // texture coordinate vector scales fogParms_t parms; // for clipping distance in fog when outside qboolean hasSurface; float surface[4]; } fog_t; typedef struct { float eyeT; qboolean eyeOutside; vec4_t fogDistanceVector; vec4_t fogDepthVector; const float *fogColor; // vec4_t } fogProgramParms_t; typedef enum { PV_NONE = 0, PV_PORTAL, PV_MIRROR, // portal + inverted face culling PV_COUNT } portalView_t; typedef struct { orientationr_t or; orientationr_t world; vec3_t pvsOrigin; // may be different than or.origin for portals portalView_t portalView; int frameSceneNum; // copied from tr.frameSceneNum int frameCount; // copied from tr.frameCount cplane_t portalPlane; // clip anything behind this if mirroring int viewportX, viewportY, viewportWidth, viewportHeight; int scissorX, scissorY, scissorWidth, scissorHeight; float fovX, fovY; float projectionMatrix[16]; cplane_t frustum[4]; vec3_t visBounds[2]; float zFar; stereoFrame_t stereoFrame; #ifdef USE_PMLIGHT // each view will have its own dlight set unsigned int num_dlights; struct dlight_s *dlights; #endif } viewParms_t; /* ============================================================================== SURFACES ============================================================================== */ // any changes in surfaceType must be mirrored in rb_surfaceTable[] typedef enum { SF_BAD, SF_SKIP, // ignore SF_FACE, SF_GRID, SF_TRIANGLES, SF_POLY, SF_MD3, SF_MDR, SF_IQM, SF_FLARE, SF_ENTITY, // beams, rails, lightning, etc that can be determined by entity SF_NUM_SURFACE_TYPES, SF_MAX = 0x7fffffff // ensures that sizeof( surfaceType_t ) == sizeof( int ) } surfaceType_t; typedef struct drawSurf_s { unsigned int sort; // bit combination for fast compares surfaceType_t *surface; // any of surface*_t } drawSurf_t; #ifdef USE_PMLIGHT typedef struct litSurf_s { unsigned int sort; // bit combination for fast compares surfaceType_t *surface; // any of surface*_t struct litSurf_s *next; } litSurf_t; #endif #define MAX_FACE_POINTS 64 #define MAX_PATCH_SIZE 32 // max dimensions of a patch mesh in map file #define MAX_GRID_SIZE 65 // max dimensions of a grid mesh in memory // when cgame directly specifies a polygon, it becomes a srfPoly_t // as soon as it is called typedef struct srfPoly_s { surfaceType_t surfaceType; qhandle_t hShader; int fogIndex; int numVerts; polyVert_t *verts; } srfPoly_t; typedef struct srfFlare_s { surfaceType_t surfaceType; vec3_t origin; vec3_t normal; vec3_t color; } srfFlare_t; typedef struct srfGridMesh_s { surfaceType_t surfaceType; // dynamic lighting information int dlightBits; // culling information vec3_t meshBounds[2]; vec3_t localOrigin; float meshRadius; // lod information, which may be different // than the culling information to allow for // groups of curves that LOD as a unit vec3_t lodOrigin; float lodRadius; int lodFixed; int lodStitched; #ifdef USE_VBO int vboItemIndex; int vboExpectIndices; int vboExpectVertices; #endif // vertexes int width, height; float *widthLodError; float *heightLodError; drawVert_t verts[1]; // variable sized } srfGridMesh_t; #define VERTEXSIZE 8 typedef struct { surfaceType_t surfaceType; cplane_t plane; // dynamic lighting information #ifdef USE_LEGACY_DLIGHTS int dlightBits; #endif #ifdef USE_VBO int vboItemIndex; #endif float *normals; // triangle definitions (no normals at points) int numPoints; int numIndices; int ofsIndices; float points[1][VERTEXSIZE]; // variable sized // there is a variable length list of indices here also } srfSurfaceFace_t; // misc_models in maps are turned into direct geometry by q3map typedef struct { surfaceType_t surfaceType; // dynamic lighting information #ifdef USE_LEGACY_DLIGHTS int dlightBits; #endif #ifdef USE_VBO int vboItemIndex; #endif // culling information (FIXME: use this!) vec3_t bounds[2]; vec3_t localOrigin; float radius; // triangle definitions int numIndexes; int *indexes; int numVerts; drawVert_t *verts; } srfTriangles_t; typedef struct { vec3_t translate; quat_t rotate; vec3_t scale; } iqmTransform_t; // inter-quake-model typedef struct { int num_vertexes; int num_triangles; int num_frames; int num_surfaces; int num_joints; int num_poses; struct srfIQModel_s *surfaces; int *triangles; // vertex arrays float *positions; float *texcoords; float *normals; float *tangents; byte *colors; int *influences; // [num_vertexes] indexes into influenceBlendVertexes // unique list of vertex blend indexes/weights for faster CPU vertex skinning byte *influenceBlendIndexes; // [num_influences] union { float *f; byte *b; } influenceBlendWeights; // [num_influences] // depending upon the exporter, blend indices and weights might be int/float // as opposed to the recommended byte/byte, for example Noesis exports // int/float whereas the official IQM tool exports byte/byte int blendWeightsType; // IQM_UBYTE or IQM_FLOAT char *jointNames; int *jointParents; float *bindJoints; // [num_joints * 12] float *invBindJoints; // [num_joints * 12] iqmTransform_t *poses; // [num_frames * num_poses] float *bounds; } iqmData_t; // inter-quake-model surface typedef struct srfIQModel_s { surfaceType_t surfaceType; char name[MAX_QPATH]; shader_t *shader; iqmData_t *data; int first_vertex, num_vertexes; int first_triangle, num_triangles; int first_influence, num_influences; } srfIQModel_t; extern void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *); /* ============================================================================== BRUSH MODELS ============================================================================== */ // // in memory representation // #define SIDE_FRONT 0 #define SIDE_BACK 1 #define SIDE_ON 2 typedef struct msurface_s { int viewCount; // if == tr.viewCount, already added struct shader_s *shader; int fogIndex; #ifdef USE_PMLIGHT int vcVisible; // if == tr.viewCount, is actually VISIBLE in this frame, i.e. passed facecull and has been added to the drawsurf list int lightCount; // if == tr.lightCount, already added to the litsurf list for the current light #endif // USE_PMLIGHT surfaceType_t *data; // any of srf*_t } msurface_t; typedef struct mnode_s { // common with leaf and node int contents; // -1 for nodes, to differentiate from leafs int visframe; // node needs to be traversed if current vec3_t mins, maxs; // for bounding box culling struct mnode_s *parent; // node specific cplane_t *plane; struct mnode_s *children[2]; // leaf specific int cluster; int area; msurface_t **firstmarksurface; int nummarksurfaces; } mnode_t; typedef struct { vec3_t bounds[2]; // for culling msurface_t *firstSurface; int numSurfaces; } bmodel_t; typedef struct { char name[MAX_QPATH]; // ie: maps/tim_dm2.bsp char baseName[MAX_QPATH]; // ie: tim_dm2 int dataSize; int numShaders; dshader_t *shaders; bmodel_t *bmodels; int numplanes; cplane_t *planes; int numnodes; // includes leafs int numDecisionNodes; mnode_t *nodes; int numsurfaces; msurface_t *surfaces; int nummarksurfaces; msurface_t **marksurfaces; int numfogs; fog_t *fogs; vec3_t lightGridOrigin; vec3_t lightGridSize; vec3_t lightGridInverseSize; int lightGridBounds[3]; byte *lightGridData; int numClusters; int clusterBytes; const byte *vis; // may be passed in by CM_LoadMap to save space byte *novis; // clusterBytes of 0xff char *entityString; const char *entityParsePoint; } world_t; //====================================================================== typedef enum { MOD_BAD, MOD_BRUSH, MOD_MESH, MOD_MDR, MOD_IQM } modtype_t; typedef struct model_s { char name[MAX_QPATH]; modtype_t type; int index; // model = tr.models[model->index] int dataSize; // just for listing purposes bmodel_t *bmodel; // only if type == MOD_BRUSH md3Header_t *md3[MD3_MAX_LODS]; // only if type == MOD_MESH void *modelData; // only if type == (MOD_MDR | MOD_IQM) int numLods; } model_t; #define MAX_MOD_KNOWN 1024 void R_ModelInit (void); model_t *R_GetModelByHandle( qhandle_t hModel ); int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, float frac, const char *tagName ); void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ); void R_Modellist_f (void); //==================================================== #define MAX_DRAWIMAGES 2048 #define MAX_SKINS 1024 #define MAX_DRAWSURFS 0x20000 #define DRAWSURF_MASK (MAX_DRAWSURFS-1) /* the drawsurf sort data is packed into a single 32 bit value so it can be compared quickly during the qsorting process the bits are allocated as follows: 0 - 1 : dlightmap index //2 : used to be clipped flag REMOVED - 03.21.00 rad 2 - 6 : fog index 11 - 20 : entity index 21 - 31 : sorted shader index TTimo - 1.32 0-1 : dlightmap index 2-6 : fog index 7-16 : entity index 17-30 : sorted shader index */ #define DLIGHT_BITS 1 // qboolean in opengl1 renderer #define DLIGHT_MASK ((1<<DLIGHT_BITS)-1) #define FOGNUM_BITS 5 #define FOGNUM_MASK ((1<<FOGNUM_BITS)-1) #define QSORT_FOGNUM_SHIFT DLIGHT_BITS #define QSORT_REFENTITYNUM_SHIFT (QSORT_FOGNUM_SHIFT + FOGNUM_BITS) #define QSORT_SHADERNUM_SHIFT (QSORT_REFENTITYNUM_SHIFT+REFENTITYNUM_BITS) #if (QSORT_SHADERNUM_SHIFT+SHADERNUM_BITS) > 32 #error "Need to update sorting, too many bits." #endif #define QSORT_REFENTITYNUM_MASK (REFENTITYNUM_MASK << QSORT_REFENTITYNUM_SHIFT) extern int gl_filter_min, gl_filter_max; /* ** performanceCounters_t */ typedef struct { int c_sphere_cull_patch_in, c_sphere_cull_patch_clip, c_sphere_cull_patch_out; int c_box_cull_patch_in, c_box_cull_patch_clip, c_box_cull_patch_out; int c_sphere_cull_md3_in, c_sphere_cull_md3_clip, c_sphere_cull_md3_out; int c_box_cull_md3_in, c_box_cull_md3_clip, c_box_cull_md3_out; int c_leafs; int c_dlightSurfaces; int c_dlightSurfacesCulled; #ifdef USE_PMLIGHT int c_light_cull_out; int c_light_cull_in; int c_lit_leafs; int c_lit_surfs; int c_lit_culls; int c_lit_masks; #endif } frontEndCounters_t; #define FOG_TABLE_SIZE 256 #define FUNCTABLE_SIZE 1024 #define FUNCTABLE_SIZE2 10 #define FUNCTABLE_MASK (FUNCTABLE_SIZE-1) // the renderer front end should never modify glstate_t typedef struct { GLuint currenttextures[ MAX_TEXTURE_UNITS ]; int currenttmu; qboolean finishCalled; GLint texEnv[2]; int faceCulling; unsigned long glStateBits; } glstate_t; typedef struct { int c_surfaces, c_shaders, c_vertexes, c_indexes, c_totalIndexes; float c_overDraw; int c_dlightVertexes; int c_dlightIndexes; int c_flareAdds; int c_flareTests; int c_flareRenders; int msec; // total msec for backend run #ifdef USE_PMLIGHT int c_lit_batches; int c_lit_vertices; int c_lit_indices; int c_lit_indices_latecull_in; int c_lit_indices_latecull_out; int c_lit_vertices_lateculltest; #endif } backEndCounters_t; typedef struct videoFrameCommand_s { int commandId; int width; int height; byte *captureBuffer; byte *encodeBuffer; qboolean motionJpeg; } videoFrameCommand_t; enum { SCREENSHOT_TGA = 1<<0, SCREENSHOT_JPG = 1<<1, SCREENSHOT_BMP = 1<<2, SCREENSHOT_BMP_CLIPBOARD = 1<<3, SCREENSHOT_AVI = 1<<4 // take video frame }; // all state modified by the back end is seperated // from the front end state typedef struct { trRefdef_t refdef; viewParms_t viewParms; orientationr_t or; backEndCounters_t pc; qboolean isHyperspace; const trRefEntity_t *currentEntity; qboolean skyRenderedThisView; // flag for drawing sun qboolean projection2D; // if qtrue, drawstretchpic doesn't need to change modes byte color2D[4]; qboolean doneSurfaces; // done any 3d surfaces already trRefEntity_t entity2D; // currentEntity will point at this when doing 2D rendering int screenshotMask; // tga | jpg | bmp char screenshotTGA[ MAX_OSPATH ]; char screenshotJPG[ MAX_OSPATH ]; char screenshotBMP[ MAX_OSPATH ]; qboolean screenShotTGAsilent; qboolean screenShotJPGsilent; qboolean screenShotBMPsilent; videoFrameCommand_t vcmd; // avi capture qboolean throttle; qboolean drawConsole; } backEndState_t; /* ** trGlobals_t ** ** Most renderer globals are defined here. ** backend functions should never modify any of these fields, ** but may read fields that aren't dynamically modified ** by the frontend. */ typedef struct { qboolean registered; // cleared at shutdown, set at beginRegistration int visCount; // incremented every time a new vis cluster is entered int frameCount; // incremented every frame int sceneCount; // incremented every scene int viewCount; // incremented every view (twice a scene if portaled) // and every R_MarkFragments call #ifdef USE_PMLIGHT int lightCount; // incremented for each dlight in the view #endif int frameSceneNum; // zeroed at RE_BeginFrame qboolean worldMapLoaded; world_t *world; const byte *externalVisData; // from RE_SetWorldVisData, shared with CM_Load image_t *defaultImage; image_t *scratchImage[ MAX_VIDEO_HANDLES ]; image_t *fogImage; image_t *dlightImage; // inverse-quare highlight for projective adding image_t *flareImage; image_t *whiteImage; // full of 0xff image_t *identityLightImage; // full of tr.identityLightByte shader_t *defaultShader; shader_t *cinematicShader; shader_t *shadowShader; shader_t *projectionShadowShader; shader_t *flareShader; shader_t *sunShader; int numLightmaps; image_t **lightmaps; float lightmapScale[2]; trRefEntity_t *currentEntity; trRefEntity_t worldEntity; // point currentEntity at this when rendering world int currentEntityNum; int shiftedEntityNum; // currentEntityNum << QSORT_REFENTITYNUM_SHIFT model_t *currentModel; viewParms_t viewParms; float identityLight; // 1.0 / ( 1 << overbrightBits ) int identityLightByte; // identityLight * 255 int overbrightBits; // r_overbrightBits->integer, but set to 0 if no hw gamma orientationr_t or; // for current entity trRefdef_t refdef; int viewCluster; #ifdef USE_PMLIGHT dlight_t *light; // current light during R_RecursiveLightNode #endif vec3_t sunLight; // from the sky shader for this level vec3_t sunDirection; frontEndCounters_t pc; int frontEndMsec; // not in pc due to clearing issue // // put large tables at the end, so most elements will be // within the +/32K indexed range on risc processors // model_t *models[MAX_MOD_KNOWN]; int numModels; int numImages; image_t *images[MAX_DRAWIMAGES]; // shader indexes from other modules will be looked up in tr.shaders[] // shader indexes from drawsurfs will be looked up in sortedShaders[] // lower indexed sortedShaders must be rendered first (opaque surfaces before translucent) int numShaders; shader_t *shaders[MAX_SHADERS]; shader_t *sortedShaders[MAX_SHADERS]; int numSkins; skin_t *skins[MAX_SKINS]; float sinTable[FUNCTABLE_SIZE]; float squareTable[FUNCTABLE_SIZE]; float triangleTable[FUNCTABLE_SIZE]; float sawToothTable[FUNCTABLE_SIZE]; float inverseSawToothTable[FUNCTABLE_SIZE]; float fogTable[FOG_TABLE_SIZE]; qboolean mapLoading; qboolean needScreenMap; qboolean vertexLightingAllowed; } trGlobals_t; extern backEndState_t backEnd; extern trGlobals_t tr; extern glstate_t glState; // outside of TR since it shouldn't be cleared during ref re-init extern void myGlMultMatrix(const float *a, const float *b, float *out); #ifdef USE_VULKAN extern Vk_Instance vk; // shouldn't be cleared during ref re-init extern Vk_World vk_world; // this data is cleared during ref re-init #endif // // cvars // extern cvar_t *r_flareSize; extern cvar_t *r_flareFade; extern cvar_t *r_flareCoeff; // coefficient for the flare intensity falloff function. extern cvar_t *r_railWidth; extern cvar_t *r_railCoreWidth; extern cvar_t *r_railSegmentLength; extern cvar_t *r_znear; // near Z clip plane extern cvar_t *r_zproj; // z distance of projection plane extern cvar_t *r_stereoSeparation; // separation of cameras for stereo rendering extern cvar_t *r_lodbias; // push/pull LOD transitions extern cvar_t *r_lodscale; extern cvar_t *r_fastsky; // controls whether sky should be cleared or drawn extern cvar_t *r_neatsky; // nomip and nopicmip for skyboxes, cnq3 like look extern cvar_t *r_drawSun; // controls drawing of sun quad extern cvar_t *r_dynamiclight; // dynamic lights enabled/disabled extern cvar_t *r_mergeLightmaps; #ifdef USE_PMLIGHT extern cvar_t *r_dlightMode; // 0 - vq3, 1 - pmlight //extern cvar_t *r_dlightSpecPower; // 1 - 32 //extern cvar_t *r_dlightSpecColor; // -1.0 - 1.0 extern cvar_t *r_dlightScale; // 0.1 - 1.0 extern cvar_t *r_dlightIntensity; // 0.1 - 1.0 #endif #ifdef USE_VULKAN extern cvar_t *r_device; #ifdef USE_VBO extern cvar_t *r_vbo; #endif extern cvar_t *r_fbo; extern cvar_t *r_hdr; extern cvar_t *r_ext_multisample; extern cvar_t *r_ext_alpha_to_coverage; #endif extern cvar_t *r_dlightBacks; // dlight non-facing surfaces for continuity extern cvar_t *r_norefresh; // bypasses the ref rendering extern cvar_t *r_drawentities; // disable/enable entity rendering extern cvar_t *r_drawworld; // disable/enable world rendering extern cvar_t *r_speeds; // various levels of information display extern cvar_t *r_detailTextures; // enables/disables detail texturing stages extern cvar_t *r_novis; // disable/enable usage of PVS extern cvar_t *r_nocull; extern cvar_t *r_facePlaneCull; // enables culling of planar surfaces with back side test extern cvar_t *r_nocurves; extern cvar_t *r_showcluster; extern cvar_t *r_gamma; extern cvar_t *r_nobind; // turns off binding to appropriate textures extern cvar_t *r_singleShader; // make most world faces use default shader extern cvar_t *r_roundImagesDown; extern cvar_t *r_colorMipLevels; // development aid to see texture mip usage extern cvar_t *r_picmip; // controls picmip values extern cvar_t *r_nomip; // apply picmip only on worldspawn textures extern cvar_t *r_finish; extern cvar_t *r_textureMode; extern cvar_t *r_offsetFactor; extern cvar_t *r_offsetUnits; extern cvar_t *r_fullbright; // avoid lightmap pass extern cvar_t *r_lightmap; // render lightmaps only extern cvar_t *r_vertexLight; // vertex lighting mode for better performance extern cvar_t *r_showtris; // enables wireframe rendering of the world extern cvar_t *r_showsky; // forces sky in front of all surfaces extern cvar_t *r_shownormals; // draws wireframe normals extern cvar_t *r_clear; // force screen clear every frame extern cvar_t *r_shadows; // controls shadows: 0 = none, 1 = blur, 2 = stencil, 3 = black planar projection extern cvar_t *r_flares; // light flares extern cvar_t *r_intensity; extern cvar_t *r_lockpvs; extern cvar_t *r_noportals; extern cvar_t *r_portalOnly; extern cvar_t *r_subdivisions; extern cvar_t *r_lodCurveError; extern cvar_t *r_skipBackEnd; extern cvar_t *r_greyscale; extern cvar_t *r_ignoreGLErrors; extern cvar_t *r_overBrightBits; extern cvar_t *r_mapOverBrightBits; extern cvar_t *r_mapGreyScale; extern cvar_t *r_debugSurface; extern cvar_t *r_simpleMipMaps; extern cvar_t *r_showImages; extern cvar_t *r_defaultImage; extern cvar_t *r_debugSort; extern cvar_t *r_printShaders; extern cvar_t *r_marksOnTriangleMeshes; //==================================================================== void R_SwapBuffers( int ); void R_RenderView( const viewParms_t *parms ); void R_AddMD3Surfaces( trRefEntity_t *e ); void R_AddNullModelSurfaces( trRefEntity_t *e ); void R_AddBeamSurfaces( trRefEntity_t *e ); void R_AddRailSurfaces( trRefEntity_t *e, qboolean isUnderwater ); void R_AddLightningBoltSurfaces( trRefEntity_t *e ); void R_AddPolygonSurfaces( void ); void R_DecomposeSort( unsigned sort, int *entityNum, shader_t **shader, int *fogNum, int *dlightMap ); void R_AddDrawSurf( surfaceType_t *surface, shader_t *shader, int fogIndex, int dlightMap ); #ifdef USE_PMLIGHT void R_DecomposeLitSort( unsigned sort, int *entityNum, shader_t **shader, int *fogNum ); void R_AddLitSurf( surfaceType_t *surface, shader_t *shader, int fogIndex ); #endif #define CULL_IN 0 // completely unclipped #define CULL_CLIP 1 // clipped by one or more planes #define CULL_OUT 2 // completely outside the clipping planes void R_LocalNormalToWorld( const vec3_t local, vec3_t world ); void R_LocalPointToWorld( const vec3_t local, vec3_t world ); int R_CullLocalBox( vec3_t bounds[] ); int R_CullPointAndRadius( const vec3_t origin, float radius ); int R_CullLocalPointAndRadius( const vec3_t origin, float radius ); int R_CullDlight( const dlight_t *dl ); void R_SetupProjection( viewParms_t *dest, float zProj, qboolean computeFrustum ); void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *or ); /* ** GL wrapper/helper functions */ void GL_Bind( image_t *image ); void GL_SelectTexture( int unit ); void GL_TextureMode( const char *string ); void GL_CheckErrors( void ); void GL_State( unsigned long stateVector ); #ifndef USE_VULKAN void GL_TexEnv( GLint env ); void GL_Cull( int cullType ); #endif #define GLS_SRCBLEND_ZERO 0x00000001 #define GLS_SRCBLEND_ONE 0x00000002 #define GLS_SRCBLEND_DST_COLOR 0x00000003 #define GLS_SRCBLEND_ONE_MINUS_DST_COLOR 0x00000004 #define GLS_SRCBLEND_SRC_ALPHA 0x00000005 #define GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA 0x00000006 #define GLS_SRCBLEND_DST_ALPHA 0x00000007 #define GLS_SRCBLEND_ONE_MINUS_DST_ALPHA 0x00000008 #define GLS_SRCBLEND_ALPHA_SATURATE 0x00000009 #define GLS_SRCBLEND_BITS 0x0000000f #define GLS_DSTBLEND_ZERO 0x00000010 #define GLS_DSTBLEND_ONE 0x00000020 #define GLS_DSTBLEND_SRC_COLOR 0x00000030 #define GLS_DSTBLEND_ONE_MINUS_SRC_COLOR 0x00000040 #define GLS_DSTBLEND_SRC_ALPHA 0x00000050 #define GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA 0x00000060 #define GLS_DSTBLEND_DST_ALPHA 0x00000070 #define GLS_DSTBLEND_ONE_MINUS_DST_ALPHA 0x00000080 #define GLS_DSTBLEND_BITS 0x000000f0 #define GLS_DEPTHMASK_TRUE 0x00000100 #define GLS_POLYMODE_LINE 0x00001000 #define GLS_DEPTHTEST_DISABLE 0x00010000 #define GLS_DEPTHFUNC_EQUAL 0x00020000 #define GLS_ATEST_GT_0 0x10000000 #define GLS_ATEST_LT_80 0x20000000 #define GLS_ATEST_GE_80 0x30000000 #define GLS_ATEST_BITS 0x30000000 #define GLS_DEFAULT GLS_DEPTHMASK_TRUE void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty); void RE_UploadCinematic (int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty); void RE_BeginFrame( stereoFrame_t stereoFrame ); void RE_BeginRegistration( glconfig_t *glconfig ); void RE_LoadWorldMap( const char *mapname ); void RE_SetWorldVisData( const byte *vis ); qhandle_t RE_RegisterModel( const char *name ); qhandle_t RE_RegisterSkin( const char *name ); qboolean RE_GetEntityToken( char *buffer, int size ); model_t *R_AllocModel( void ); void R_Init( void ); void R_SetColorMappings( void ); void R_GammaCorrect( byte *buffer, int bufSize ); void R_ImageList_f( void ); void R_SkinList_f( void ); void R_InitFogTable( void ); float R_FogFactor( float s, float t ); void R_InitImages( void ); void R_DeleteTextures( void ); int R_SumOfUsedImages( void ); void R_InitSkins( void ); skin_t *R_GetSkinByHandle( qhandle_t hSkin ); int R_ComputeLOD( trRefEntity_t *ent ); const void *RB_TakeVideoFrameCmd( const void *data ); // // tr_shader.c // shader_t *R_FindShader( const char *name, int lightmapIndex, qboolean mipRawImage ); shader_t *R_GetShaderByHandle( qhandle_t hShader ); shader_t *R_GetShaderByState( int index, long *cycleTime ); shader_t *R_FindShaderByName( const char *name ); void R_InitShaders( void ); void R_ShaderList_f( void ); void RE_RemapShader(const char *oldShader, const char *newShader, const char *timeOffset); void FindLightingStages( shader_t *sh ); // // tr_surface.c // void RB_SurfaceGridEstimate( srfGridMesh_t *cv, int *numVertexes, int *numIndexes ); /* ==================================================================== TESSELATOR/SHADER DECLARATIONS ==================================================================== */ typedef byte color4ub_t[4]; typedef struct stageVars { color4ub_t colors[SHADER_MAX_VERTEXES]; vec2_t texcoords[NUM_TEXTURE_BUNDLES][SHADER_MAX_VERTEXES]; } stageVars_t; typedef struct shaderCommands_s { #pragma pack(push,16) glIndex_t indexes[SHADER_MAX_INDEXES] QALIGN(16); vec4_t xyz[SHADER_MAX_VERTEXES] QALIGN(16); vec4_t normal[SHADER_MAX_VERTEXES] QALIGN(16); vec2_t texCoords[SHADER_MAX_VERTEXES][2] QALIGN(16); color4ub_t vertexColors[SHADER_MAX_VERTEXES] QALIGN(16); #ifdef USE_LEGACY_DLIGHTS int vertexDlightBits[SHADER_MAX_VERTEXES] QALIGN(16); #endif stageVars_t svars QALIGN(16); color4ub_t constantColor255[SHADER_MAX_VERTEXES] QALIGN(16); #pragma pack(pop) #ifdef USE_VBO surfaceType_t surfType; int vboIndex; int vboStage; qboolean allowVBO; #endif shader_t *shader; double shaderTime; // -EC- set to double for frameloss fix int fogNum; #ifdef USE_LEGACY_DLIGHTS int dlightBits; // or together of all vertexDlightBits #endif int numIndexes; int numVertexes; #ifdef USE_PMLIGHT const dlight_t* light; qboolean dlightPass; qboolean dlightUpdateParams; #endif #ifdef USE_VULKAN Vk_Depth_Range depthRange; #endif // info extracted from current shader int numPasses; shaderStage_t **xstages; } shaderCommands_t; extern shaderCommands_t tess; void RB_BeginSurface( shader_t *shader, int fogNum ); void RB_EndSurface( void ); void RB_CheckOverflow( int verts, int indexes ); #define RB_CHECKOVERFLOW(v,i) RB_CheckOverflow(v,i) void RB_StageIteratorGeneric( void ); void RB_StageIteratorSky( void ); void RB_AddQuadStamp( const vec3_t origin, const vec3_t left, const vec3_t up, const byte *color ); void RB_AddQuadStampExt( const vec3_t origin, const vec3_t left, const vec3_t up, const byte *color, float s1, float t1, float s2, float t2 ); void RB_ShowImages( void ); /* ============================================================ WORLD MAP ============================================================ */ void R_AddBrushModelSurfaces( trRefEntity_t *e ); void R_AddWorldSurfaces( void ); qboolean R_inPVS( const vec3_t p1, const vec3_t p2 ); /* ============================================================ FLARES ============================================================ */ void R_ClearFlares( void ); void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal ); void RB_AddDlightFlares( void ); void RB_RenderFlares( void ); /* ============================================================ LIGHTS ============================================================ */ void R_DlightBmodel( bmodel_t *bmodel ); void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ); void R_TransformDlights( int count, dlight_t *dl, orientationr_t *or ); int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ); #ifdef USE_PMLIGHT void VK_LightingPass( void ); qboolean R_LightCullBounds( const dlight_t* dl, const vec3_t mins, const vec3_t maxs ); #endif // USE_PMLIGHT void R_BindAnimatedImage( const textureBundle_t *bundle ); void R_DrawElements( int numIndexes, const glIndex_t *indexes ); void R_ComputeColors( const shaderStage_t *pStage ); void R_ComputeTexCoords( int b, const textureBundle_t *bundle ); /* ============================================================ SHADOWS ============================================================ */ void RB_ShadowTessEnd( void ); void RB_ShadowFinish( void ); void RB_ProjectionShadowDeform( void ); /* ============================================================ SKIES ============================================================ */ void R_BuildCloudData( shaderCommands_t *shader ); void R_InitSkyTexCoords( float cloudLayerHeight ); void R_DrawSkyBox( shaderCommands_t *shader ); void RB_DrawSun( float scale, shader_t *shader ); void RB_ClipSkyPolygons( shaderCommands_t *shader ); /* ============================================================ CURVE TESSELATION ============================================================ */ #define PATCH_STITCHING srfGridMesh_t *R_SubdividePatchToGrid( int width, int height, drawVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ); srfGridMesh_t *R_GridInsertColumn( srfGridMesh_t *grid, int column, int row, vec3_t point, float loderror ); srfGridMesh_t *R_GridInsertRow( srfGridMesh_t *grid, int row, int column, vec3_t point, float loderror ); void R_FreeSurfaceGridMesh( srfGridMesh_t *grid ); /* ============================================================ MARKERS, POLYGON PROJECTION ON WORLD POLYGONS ============================================================ */ int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ); /* ============================================================ SCENE GENERATION ============================================================ */ void R_InitNextFrame( void ); void RE_ClearScene( void ); void RE_AddRefEntityToScene( const refEntity_t *ent, qboolean intShaderTime ); void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ); void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ); void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ); void RE_AddLinearLightToScene( const vec3_t start, const vec3_t end, float intensity, float r, float g, float b ); void RE_RenderScene( const refdef_t *fd ); /* ============================================================= UNCOMPRESSING BONES ============================================================= */ #define MC_BITS_X (16) #define MC_BITS_Y (16) #define MC_BITS_Z (16) #define MC_BITS_VECT (16) #define MC_SCALE_X (1.0f/64) #define MC_SCALE_Y (1.0f/64) #define MC_SCALE_Z (1.0f/64) void MC_UnCompress(float mat[3][4],const unsigned char * comp); /* ============================================================= ANIMATED MODELS ============================================================= */ void R_MDRAddAnimSurfaces( trRefEntity_t *ent ); void RB_MDRSurfaceAnim( mdrSurface_t *surface ); qboolean R_LoadIQM (model_t *mod, void *buffer, int filesize, const char *name ); void R_AddIQMSurfaces( trRefEntity_t *ent ); void RB_IQMSurfaceAnim( surfaceType_t *surface ); int R_IQMLerpTag( orientation_t *tag, iqmData_t *data, int startFrame, int endFrame, float frac, const char *tagName ); /* ============================================================= ============================================================= */ void R_TransformModelToClip( const vec3_t src, const float *modelMatrix, const float *projectionMatrix, vec4_t eye, vec4_t dst ); void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ); void RB_DeformTessGeometry( void ); void RB_CalcEnvironmentTexCoords( float *dstTexCoords ); void RB_CalcEnvironmentTexCoordsFP( float *dstTexCoords, qboolean screenMap ); void RB_CalcFogTexCoords( float *dstTexCoords ); const fogProgramParms_t *RB_CalcFogProgramParms( void ); void RB_CalcScrollTexCoords( const float scroll[2], float *dstTexCoords ); void RB_CalcRotateTexCoords( float rotSpeed, float *dstTexCoords ); void RB_CalcScaleTexCoords( const float scale[2], float *dstTexCoords ); void RB_CalcTurbulentTexCoords( const waveForm_t *wf, float *dstTexCoords ); void RB_CalcTransformTexCoords( const texModInfo_t *tmi, float *dstTexCoords ); void RB_CalcModulateColorsByFog( unsigned char *dstColors ); void RB_CalcModulateAlphasByFog( unsigned char *dstColors ); void RB_CalcModulateRGBAsByFog( unsigned char *dstColors ); void RB_CalcWaveAlpha( const waveForm_t *wf, unsigned char *dstColors ); void RB_CalcWaveColor( const waveForm_t *wf, unsigned char *dstColors ); void RB_CalcAlphaFromEntity( unsigned char *dstColors ); void RB_CalcAlphaFromOneMinusEntity( unsigned char *dstColors ); void RB_CalcStretchTexCoords( const waveForm_t *wf, float *texCoords ); void RB_CalcColorFromEntity( unsigned char *dstColors ); void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ); void RB_CalcSpecularAlpha( unsigned char *alphas ); void RB_CalcDiffuseColor( unsigned char *colors ); /* ============================================================= RENDERER BACK END FUNCTIONS ============================================================= */ void RB_ExecuteRenderCommands( const void *data ); /* ============================================================= RENDERER BACK END COMMAND QUEUE ============================================================= */ #define MAX_RENDER_COMMANDS 0x80000 typedef struct { byte cmds[MAX_RENDER_COMMANDS]; int used; } renderCommandList_t; typedef struct { int commandId; float color[4]; } setColorCommand_t; typedef struct { int commandId; int buffer; } drawBufferCommand_t; typedef struct { int commandId; image_t *image; int width; int height; void *data; } subImageCommand_t; typedef struct { int commandId; } swapBuffersCommand_t; typedef struct { int commandId; } finishBloomCommand_t; typedef struct { int commandId; shader_t *shader; float x, y; float w, h; float s1, t1; float s2, t2; } stretchPicCommand_t; typedef struct { int commandId; trRefdef_t refdef; viewParms_t viewParms; drawSurf_t *drawSurfs; int numDrawSurfs; } drawSurfsCommand_t; typedef struct { int commandId; GLboolean rgba[4]; } colorMaskCommand_t; typedef struct { int commandId; } clearDepthCommand_t; typedef struct { int commandId; } clearColorCommand_t; typedef enum { RC_END_OF_LIST, RC_SET_COLOR, RC_STRETCH_PIC, RC_DRAW_SURFS, RC_DRAW_BUFFER, RC_SWAP_BUFFERS, RC_FINISHBLOOM, RC_COLORMASK, RC_CLEARDEPTH, RC_CLEARCOLOR } renderCommand_t; // these are sort of arbitrary limits. // the limits apply to the sum of all scenes in a frame -- // the main view, all the 3D icons, etc #define MAX_POLYS 8192 #define MAX_POLYVERTS 32768 // all of the information needed by the back end must be // contained in a backEndData_t typedef struct { drawSurf_t drawSurfs[MAX_DRAWSURFS]; #ifdef USE_PMLIGHT litSurf_t litSurfs[MAX_LITSURFS]; dlight_t dlights[MAX_REAL_DLIGHTS]; #else dlight_t dlights[MAX_DLIGHTS]; #endif trRefEntity_t entities[MAX_REFENTITIES]; srfPoly_t *polys;//[MAX_POLYS]; polyVert_t *polyVerts;//[MAX_POLYVERTS]; renderCommandList_t commands; } backEndData_t; extern int max_polys; extern int max_polyverts; extern backEndData_t *backEndData; void RB_ExecuteRenderCommands( const void *data ); void RB_TakeScreenshot( int x, int y, int width, int height, const char *fileName ); void RB_TakeScreenshotJPEG( int x, int y, int width, int height, const char *fileName ); void RB_TakeScreenshotBMP( int x, int y, int width, int height, const char *fileName, int clipboard ); void R_IssuePendingRenderCommands( void ); void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ); void RE_SetColor( const float *rgba ); void RE_StretchPic ( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ); void RE_BeginFrame( stereoFrame_t stereoFrame ); void RE_EndFrame( int *frontEndMsec, int *backEndMsec ); void RE_TakeVideoFrame( int width, int height, byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg ); void RE_FinishBloom( void ); void RE_ThrottleBackend( void ); qboolean RE_CanMinimize( void ); const glconfig_t *RE_GetConfig( void ); void RE_VertexLighting( qboolean allowed ); qboolean R_HaveExtension( const char *ext ); #ifndef USE_VULKAN #define GLE( ret, name, ... ) extern ret ( APIENTRY * q##name )( __VA_ARGS__ ); QGL_Core_PROCS; QGL_Ext_PROCS; #undef GLE #endif #ifdef USE_VBO // VBO functions extern void R_BuildWorldVBO( msurface_t *surf, int surfCount ); extern void VBO_PushData( int itemIndex, shaderCommands_t *input ); extern void VBO_UnBind( void ); extern void VBO_Cleanup( void ); extern void VBO_QueueItem( int itemIndex ); extern void VBO_ClearQueue( void ); extern void VBO_Flush( void ); #endif #endif //TR_LOCAL_H
27.106133
142
0.715745
[ "mesh", "geometry", "render", "vector", "model", "3d" ]
801f5866081e2d3d2777eb4b1072ce97d8a8ba39
9,949
h
C
src/core/inc/amd_aql_queue.h
legionella-rs/ROCR-Runtime
c78f0f5e160dded6bfce40c29dd0d16887f75dd0
[ "AMDPLPA" ]
null
null
null
src/core/inc/amd_aql_queue.h
legionella-rs/ROCR-Runtime
c78f0f5e160dded6bfce40c29dd0d16887f75dd0
[ "AMDPLPA" ]
null
null
null
src/core/inc/amd_aql_queue.h
legionella-rs/ROCR-Runtime
c78f0f5e160dded6bfce40c29dd0d16887f75dd0
[ "AMDPLPA" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // The University of Illinois/NCSA // Open Source License (NCSA) // // Copyright (c) 2014-2015, Advanced Micro Devices, Inc. All rights reserved. // // Developed by: // // AMD Research and AMD HSA Software Development // // Advanced Micro Devices, Inc. // // www.amd.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal with 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: // // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimers. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimers in // the documentation and/or other materials provided with the distribution. // - Neither the names of Advanced Micro Devices, Inc, // nor the names of its contributors may be used to endorse or promote // products derived from this Software without specific prior written // permission. // // 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 CONTRIBUTORS 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 WITH THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// #ifndef HSA_RUNTIME_CORE_INC_AMD_HW_AQL_COMMAND_PROCESSOR_H_ #define HSA_RUNTIME_CORE_INC_AMD_HW_AQL_COMMAND_PROCESSOR_H_ #include "core/inc/runtime.h" #include "core/inc/signal.h" #include "core/inc/queue.h" #include "core/inc/amd_gpu_agent.h" #include "core/util/locks.h" namespace amd { /// @brief Encapsulates HW Aql Command Processor functionality. It /// provide the interface for things such as Doorbell register, read, /// write pointers and a buffer. class AqlQueue : public core::Queue, private core::LocalSignal, public core::DoorbellSignal { public: static __forceinline bool IsType(core::Signal* signal) { return signal->IsType(&rtti_id_); } static __forceinline bool IsType(core::Queue* queue) { return queue->IsType(&rtti_id_); } // Acquires/releases queue resources and requests HW schedule/deschedule. AqlQueue(GpuAgent* agent, size_t req_size_pkts, HSAuint32 node_id, ScratchInfo& scratch, core::HsaEventCallback callback, void* err_data, bool is_kv = false); ~AqlQueue(); /// @brief Queue interfaces hsa_status_t Inactivate() override; /// @brief Change the scheduling priority of the queue hsa_status_t SetPriority(HSA_QUEUE_PRIORITY priority) override; /// @brief Atomically reads the Read index of with Acquire semantics /// /// @return uint64_t Value of read index uint64_t LoadReadIndexAcquire() override; /// @brief Atomically reads the Read index of with Relaxed semantics /// /// @return uint64_t Value of read index uint64_t LoadReadIndexRelaxed() override; /// @brief Atomically reads the Write index of with Acquire semantics /// /// @return uint64_t Value of write index uint64_t LoadWriteIndexAcquire() override; /// @brief Atomically reads the Write index of with Relaxed semantics /// /// @return uint64_t Value of write index uint64_t LoadWriteIndexRelaxed() override; /// @brief This operation is illegal void StoreReadIndexRelaxed(uint64_t value) override { assert(false); } /// @brief This operation is illegal void StoreReadIndexRelease(uint64_t value) override { assert(false); } /// @brief Atomically writes the Write index of with Relaxed semantics /// /// @param value New value of write index to update with void StoreWriteIndexRelaxed(uint64_t value) override; /// @brief Atomically writes the Write index of with Release semantics /// /// @param value New value of write index to update with void StoreWriteIndexRelease(uint64_t value) override; /// @brief Compares and swaps Write index using Acquire and Release semantics /// /// @param expected Current value of write index /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t CasWriteIndexAcqRel(uint64_t expected, uint64_t value) override; /// @brief Compares and swaps Write index using Acquire semantics /// /// @param expected Current value of write index /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t CasWriteIndexAcquire(uint64_t expected, uint64_t value) override; /// @brief Compares and swaps Write index using Relaxed semantics /// /// @param expected Current value of write index /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t CasWriteIndexRelaxed(uint64_t expected, uint64_t value) override; /// @brief Compares and swaps Write index using Release semantics /// /// @param expected Current value of write index /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t CasWriteIndexRelease(uint64_t expected, uint64_t value) override; /// @brief Updates the Write index using Acquire and Release semantics /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t AddWriteIndexAcqRel(uint64_t value) override; /// @brief Updates the Write index using Acquire semantics /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t AddWriteIndexAcquire(uint64_t value) override; /// @brief Updates the Write index using Relaxed semantics /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t AddWriteIndexRelaxed(uint64_t value) override; /// @brief Updates the Write index using Release semantics /// /// @param value Value of new write index /// /// @return uint64_t Value of write index before the update uint64_t AddWriteIndexRelease(uint64_t value) override; /// @brief Set CU Masking /// /// @param num_cu_mask_count size of mask bit array /// /// @param cu_mask pointer to cu mask /// /// @return hsa_status_t hsa_status_t SetCUMasking(const uint32_t num_cu_mask_count, const uint32_t* cu_mask) override; // @brief Submits a block of PM4 and waits until it has been executed. void ExecutePM4(uint32_t* cmd_data, size_t cmd_size_b) override; /// @brief Update signal value using Relaxed semantics void StoreRelaxed(hsa_signal_value_t value) override; /// @brief Update signal value using Release semantics void StoreRelease(hsa_signal_value_t value) override; protected: bool _IsA(Queue::rtti_t id) const override { return id == &rtti_id_; } private: uint32_t ComputeRingBufferMinPkts(); uint32_t ComputeRingBufferMaxPkts(); // (De)allocates and (de)registers ring_buf_. void AllocRegisteredRingBuffer(uint32_t queue_size_pkts); void FreeRegisteredRingBuffer(); /// @brief Abstracts the file handle use for double mapping queues. void CloseRingBufferFD(const char* ring_buf_shm_path, int fd) const; int CreateRingBufferFD(const char* ring_buf_shm_path, uint32_t ring_buf_phys_size_bytes) const; /// @brief Define the Scratch Buffer Descriptor and related parameters /// that enable kernel access scratch memory void InitScratchSRD(); /// @brief Halt the queue without destroying it or fencing memory. void Suspend(); /// @brief Handler for hardware queue events. static bool DynamicScratchHandler(hsa_signal_value_t error_code, void* arg); // AQL packet ring buffer void* ring_buf_; // Size of ring_buf_ allocation. // This may be larger than (amd_queue_.hsa_queue.size * sizeof(AqlPacket)). uint32_t ring_buf_alloc_bytes_; // Id of the Queue used in communication with thunk HSA_QUEUEID queue_id_; // Indicates if queue is active std::atomic<bool> active_; // Cached value of HsaNodeProperties.HSA_CAPABILITY.DoorbellType int doorbell_type_; // Handle of agent, which queue is attached to GpuAgent* agent_; uint32_t queue_full_workaround_; // Handle of scratch memory descriptor ScratchInfo queue_scratch_; AMD::callback_t<core::HsaEventCallback> errors_callback_; void* errors_data_; // Is KV device queue bool is_kv_queue_; // GPU-visible indirect buffer holding PM4 commands. void* pm4_ib_buf_; uint32_t pm4_ib_size_b_; KernelMutex pm4_ib_mutex_; // Error handler control variable. std::atomic<uint32_t> dynamicScratchState; enum { ERROR_HANDLER_DONE = 1, ERROR_HANDLER_TERMINATE = 2, ERROR_HANDLER_SCRATCH_RETRY = 4 }; // Queue currently suspended or scheduled bool suspended_; // Thunk dispatch and wavefront scheduling priority HSA_QUEUE_PRIORITY priority_; // Shared event used for queue errors static HsaEvent* queue_event_; // Queue count - used to ref count queue_event_ static std::atomic<uint32_t> queue_count_; // Mutex for queue_event_ manipulation static KernelMutex queue_lock_; static int rtti_id_; // Forbid copying and moving of this object DISALLOW_COPY_AND_ASSIGN(AqlQueue); }; } // namespace amd #endif // header guard
35.03169
97
0.728415
[ "object" ]
802bab6d90f88a9920e40eaf6d8e908a53541c83
4,577
h
C
src/sfm/twoview_info.h
Yzhbuaa/DAGSfM
321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f
[ "BSD-3-Clause" ]
255
2018-12-14T05:59:29.000Z
2020-11-04T12:15:32.000Z
src/sfm/twoview_info.h
Yzhbuaa/DAGSfM
321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f
[ "BSD-3-Clause" ]
35
2018-12-25T03:02:48.000Z
2020-11-19T03:33:25.000Z
src/sfm/twoview_info.h
Yzhbuaa/DAGSfM
321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f
[ "BSD-3-Clause" ]
54
2018-12-14T06:09:21.000Z
2020-11-21T08:29:31.000Z
// Copyright (C) 2014 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) // BSD 3-Clause License // Copyright (c) 2020, Chenyu // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. 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 GRAPHSFM_SFM_TWOVIEW_INFO_H_ #define GRAPHSFM_SFM_TWOVIEW_INFO_H_ #include <ceres/rotation.h> #include <glog/logging.h> #include <stdint.h> #include <Eigen/Core> #include "math/rotation.h" namespace DAGSfM { // A struct to hold match and projection data between two views. It is assumed // that the first view is at the origin with an identity rotation. class TwoViewInfo { public: TwoViewInfo() : position_2(Eigen::Vector3d::Zero()), rotation_2(Eigen::Vector3d::Zero()), visibility_score(1) {} Eigen::Vector3d position_2; Eigen::Vector3d rotation_2; // The visibility score is computed based on the inlier features from 2-view // geometry estimation. This score is similar to the number of verified // matches, but has a spatial weighting to encourage good coverage of the // image by the inliers. The visibility score here is the sum of the // visibility scores for each image. int visibility_score; }; // Inverts the two view info such that the focal lengths are swapped and the // rotation and position are inverted. void SwapCameras(TwoViewInfo* twoview_info); } // namespace DAGSfM #endif // GRAPHSFM_SFM_TWOVIEW_INFO_H_
42.775701
79
0.756172
[ "geometry" ]
802d4b9f9d5f6420ca7fcee9fb45c71a78157aca
315
h
C
src/provider/TypeInfoProvider.h
tacr-iotcloud/server
c46fd292843acf25b3f03d927e6ed32bd9d05732
[ "BSD-3-Clause" ]
1
2020-09-30T06:41:47.000Z
2020-09-30T06:41:47.000Z
src/provider/TypeInfoProvider.h
tacr-iotcloud/server
c46fd292843acf25b3f03d927e6ed32bd9d05732
[ "BSD-3-Clause" ]
null
null
null
src/provider/TypeInfoProvider.h
tacr-iotcloud/server
c46fd292843acf25b3f03d927e6ed32bd9d05732
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <set> #include "model/TypeInfo.h" #include "provider/InfoProvider.h" namespace BeeeOn { class TypeInfoProvider : public XmlInfoProvider<TypeInfo> { public: TypeInfoProvider(); void setTypesFile(const std::string &typesFile); void loadInfo(); private: std::string m_typesFile; }; }
13.695652
59
0.742857
[ "model" ]
802f3b5bc947b5f471d9008020231607206ea9c0
1,329
h
C
ios/Pods/FirebaseFirestore/Firestore/core/include/firebase/firestore/set_options.h
SyntaxError02/Test
57d2802ab6953adec5281ce0c7da088d3ccea7db
[ "MIT" ]
1
2020-03-31T13:26:58.000Z
2020-03-31T13:26:58.000Z
ios/Pods/FirebaseFirestore/Firestore/core/include/firebase/firestore/set_options.h
SyntaxError02/Test
57d2802ab6953adec5281ce0c7da088d3ccea7db
[ "MIT" ]
2
2020-03-31T16:28:13.000Z
2020-09-07T13:51:54.000Z
ios/Pods/FirebaseFirestore/Firestore/core/include/firebase/firestore/set_options.h
SyntaxError02/Test
57d2802ab6953adec5281ce0c7da088d3ccea7db
[ "MIT" ]
3
2020-01-16T13:27:45.000Z
2021-05-22T20:20:16.000Z
/* * Copyright 2018 Google * * 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 FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ #define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_ namespace firebase { namespace firestore { /** * An options object that configures the behavior of Set() calls. By providing * the SetOptions objects returned by Merge(), the Set() methods in * DocumentReference, WriteBatch and Transaction can be configured to perform * granular merges instead of overwriting the target documents in their * entirety. */ // TODO(zxu123): add more methods to complete the class and make it useful. class SetOptions { public: SetOptions(); }; } // namespace firestore } // namespace firebase #endif // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_SET_OPTIONS_H_
33.225
78
0.768247
[ "object" ]
802fbc4828399365cb03d31869f9bfc22d15d4f6
3,966
h
C
validation/embedded_host/src/image_program/intelhex_image.h
ko7m/NXP_Kinetis_Bootloader
664682cc8ff8faca4e1e0532afb4e6c85dfdf18e
[ "BSD-3-Clause" ]
22
2016-10-01T16:22:43.000Z
2021-07-19T19:03:14.000Z
validation/embedded_host/src/image_program/intelhex_image.h
ko7m/NXP_Kinetis_Bootloader
664682cc8ff8faca4e1e0532afb4e6c85dfdf18e
[ "BSD-3-Clause" ]
12
2016-11-20T21:26:48.000Z
2018-04-30T19:06:15.000Z
validation/embedded_host/src/image_program/intelhex_image.h
ko7m/NXP_Kinetis_Bootloader
664682cc8ff8faca4e1e0532afb4e6c85dfdf18e
[ "BSD-3-Clause" ]
11
2016-09-25T22:41:53.000Z
2021-10-05T11:00:41.000Z
/* * Copyright (c) 2013 - 2014, Freescale Semiconductor, 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: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL 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 __intelhex_image_H__ #define __intelhex_image_H__ #include "executable_image.h" /******************************************************************************* * Definitions ******************************************************************************/ enum { /*! The required first character of a Intel Hex */ INTELHEX_START_CHAR = ':', /*! The minimum length of a Hex. This is the start char (1) + datacount (2) + addr (4) + type (2) + check sum (2). */ INTELHEX_MIN_LENGTH = 11, /*! Index of the first character of the address field. */ INTELHEX_ADDRESS_START_CHAR_INDEX = 3, /*! Index of the first character of the record type field. */ INTELHEX_TYPE_START_CHAR_INDEX = 7, /*! Index of the first character of the record type field. */ INTELHEX_DATA_START_CHAR_INDEX = 9 }; /*! Intel Hex Record Type */ enum { /*! Data Record, which contains data and a 16-bit start address for the data. */ INTELHEX_RECORD_DATA = 0x00, /*! End of File Record, which specifies the end of the hex file, and */ /*! must occur exactly once per file in the last line of the file. */ INTELHEX_RECORD_END_OF_FILE = 0x01, /*! Extended Segment Address Record, which is used to specify bits 4- 19 of the Segment Base Address. */ INTELHEX_RECORD_EXTENDED_SEGMENT_ADDRESS = 0x02, /*! Start Segment Address Record, which is used to specify the execution start address for the object file. */ INTELHEX_RECORD_START_SEGMENT_ADDRESS = 0x03, /*! Extended Linear Address Record, which is used to specify bits 16- 31 of the Linear Base Address. */ INTELHEX_RECORD_EXTENDED_LINEAR_ADDRESS = 0x04, /*! Start Linear Address Record, which is used to specify the execution start address for the object file. */ INTELHEX_RECORD_START_LINEAR_ADDRESS = 0x05 }; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus */ /*! @brief parse srecord image */ recordStatus_t intelhex_image_program(uint32_t image_address); #if defined(__cplusplus) } #endif /* __cplusplus */ #endif /* __intelhex_image_H__ */
41.3125
119
0.658346
[ "object" ]
803087f81e5edc08e99417e5c9ac7fa12141a1da
4,787
h
C
src/samplers/SamplerCapCVT/Geex/graphics/geexapp.h
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
44
2018-01-09T19:56:29.000Z
2022-03-03T06:38:54.000Z
src/samplers/SamplerCapCVT/Geex/graphics/geexapp.h
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
16
2018-01-29T18:01:42.000Z
2022-03-31T07:01:09.000Z
src/samplers/SamplerCapCVT/Geex/graphics/geexapp.h
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
12
2018-03-14T00:24:14.000Z
2022-03-03T06:40:07.000Z
/* * _____ _____ ________ _ * / __// __// __/\ \// * | | _| \ | \ \ / * | |_//| /_ | /_ / \ * \____\\____\\____\/__/\\ * * Graphics Environment for EXperimentations. * Copyright (C) 2006 INRIA - Project ALICE * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: * * ALICE Project - INRIA * INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * * Note that the GNU General Public License does not permit incorporating * the Software into proprietary programs. */ #ifndef __GEEX_GRAPHICS_GEEXAPP__ #define __GEEX_GRAPHICS_GEEXAPP__ #include "geexob.h" #include <glut_viewer/glut_viewer_gui.h> class HDRtexture ; namespace Geex { class GEEX_API GeexApp { public: GeexApp(int argc, char** argv) ; virtual ~GeexApp() ; int argc() { return argc_ ; } char** argv() { return argv_ ; } static GeexApp* instance() { return instance_ ; } Geexob* scene() { return scene_ ; } void main_loop() ; // Creates a slider connected to a uniform variable // of the shader (works for both vertex and fragment // shaders) void create_gui_for_uniform( const std::string& caption, // The name displayed in the GUI near the slider const std::string& uniform_name, // The name of the uniform variable in the shader GLfloat initial_value, // Initial value of the variable / position of the slider GLfloat range_min = 0.0f, // The slider is mapped to [range_min...range_man] GLfloat range_max = 1.0f, Geexob* object = nil ) { if(object == nil) { object = scene_ ; } viewer_properties_->add_slider( caption, object->new_uniform(uniform_name, initial_value), range_min, range_max ) ; } void get_arg(std::string arg_name, GLint& arg_val) ; void get_arg(std::string arg_name, GLfloat& arg_val) ; void get_arg(std::string arg_name, GLboolean& arg_val) ; void get_arg(std::string arg_name, std::string& arg_val) ; std::string get_file_arg(std::string extension, int start_index = 1) ; GLuint create_hdr_cubemap(const std::string& filename) ; void set_cubemap(const std::string& filename) ; void inc_frame() ; void dec_frame() ; virtual void init_scene() ; virtual void init_gui() ; static GLhandleARB load_program(const std::string& shader_base_name) ; GLboolean in_main_loop() const { return in_main_loop_ ; } protected: // Member-function versions of the callbacks virtual void initialize() ; virtual void display() ; virtual void overlay() ; virtual GLboolean mouse(float x, float y, int button, enum GlutViewerEvent event) ; // Callbacks static void initialize_CB() ; static void toggle_skybox_CB() ; static void display_CB() ; static void overlay_CB() ; static GLboolean mouse_CB(float x, float y, int button, enum GlutViewerEvent event) ; protected: // GeexApp management. static GeexApp* instance_ ; int argc_ ; char** argv_ ; int width_ ; int height_ ; GLboolean in_main_loop_ ; // SceneGraph Geexob* scene_ ; // Rendering GLboolean hdr_ ; GLuint diffuse_cubemap_ ; GLuint cubemap_ ; GLboolean fp_filtering_ ; // GUI GlutViewerGUI::Container GUI_ ; GlutViewerGUI::ViewerProperties* viewer_properties_ ; // Animation GLfloat frame_ ; GLfloat delay_ ; int frame_delta_ ; GLboolean frame_wrap_ ; GLboolean animate_ ; } ; } #endif
31.913333
113
0.621893
[ "object" ]
80310f2361a3634d2cf1ed3bfed3fa5b67b49955
1,825
h
C
include/vps.h
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
include/vps.h
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
include/vps.h
daemyung/vps
b031151e42fb355446bb4e207b74e65eb0e4b9ac
[ "MIT" ]
null
null
null
// // This file is part of the "vps" project // See "LICENSE" for license information. // #ifndef VPS_VPS_GUARD #define VPS_VPS_GUARD #include <vulkan/vulkan.h> //---------------------------------------------------------------------------------------------------------------------- using VpsContext = void*; //---------------------------------------------------------------------------------------------------------------------- typedef struct VpsContextCreateInfo { VkInstance instance; VkPhysicalDevice physicalDevice; VkDevice device; } VpsContextCreateInfo; //---------------------------------------------------------------------------------------------------------------------- VKAPI_ATTR VkResult VKAPI_CALL vpsCreateContext( const VpsContextCreateInfo* pCreateInfo, VpsContext* pContext); //---------------------------------------------------------------------------------------------------------------------- extern void vpsDestoryContext( VpsContext pContext); //---------------------------------------------------------------------------------------------------------------------- extern void vpsCmdImageThresholdToZero( VpsContext context, VkCommandBuffer commandBuffer, VkImageView srcImageView, VkImageView dstImageView, float threshold, const float* transform); //---------------------------------------------------------------------------------------------------------------------- #endif // VPS_VPS_GUARD
39.673913
120
0.313973
[ "transform" ]