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
c13edd6ce9bcafd0e0bd7a95c89cf5d0128c4c70
2,205
h
C
FlippednseSDK/FlippednseSDK/Model/ModelOrder.h
JaccobLee/FlippednseSDK
853f5e78ccf9f6f2858c4288e117e485d8c00477
[ "MIT" ]
1
2017-08-29T11:23:55.000Z
2017-08-29T11:23:55.000Z
FlippednseSDK/FlippednseSDK/Model/ModelOrder.h
JaccobLee/FlippednseSDK
853f5e78ccf9f6f2858c4288e117e485d8c00477
[ "MIT" ]
null
null
null
FlippednseSDK/FlippednseSDK/Model/ModelOrder.h
JaccobLee/FlippednseSDK
853f5e78ccf9f6f2858c4288e117e485d8c00477
[ "MIT" ]
null
null
null
// // ModelOrder.h // iEnglish // // Created by JacobLi on 4/25/16. // Copyright © 2016 jxb. All rights reserved. // #import <Foundation/Foundation.h> #import "Model.h" #import <CoreGraphics/CoreGraphics.h> @interface ModelOrder : Model @property (nonatomic, strong) NSString *bookName; @property (nonatomic, assign) int bookOrderId; @property (nonatomic, strong) NSString<Optional> *closeTime; @property (nonatomic, strong) NSString *code; @property (nonatomic, strong) NSString *cover; @property (nonatomic, strong) NSArray<Ignore> *coverList; @property (nonatomic, strong) NSString<Optional> *createTime; @property (nonatomic, strong) NSString *editionName; @property (nonatomic, assign) BOOL isActivityOrder; @property (nonatomic, assign) BOOL isPackage; @property (nonatomic, assign) int num; @property (nonatomic, strong) NSString *orderSn; @property (nonatomic, strong) NSString<Optional> *packageName; @property (nonatomic, strong) NSString<Optional> *packageType; @property (nonatomic, strong) NSString<Optional> *payTime; @property (nonatomic, assign) CGFloat price; @property (nonatomic, strong) NSString<Optional> *publishingHouseName; @property (nonatomic, assign) int status; @property (nonatomic, assign) CGFloat totalPrice; @property (nonatomic, assign) int type; @property (nonatomic, assign) int validity; @end @interface ModelOrderHistory : Model @property (nonatomic, strong) NSString *bookName; @property (nonatomic, strong) NSString *code; @property (nonatomic, strong) NSString<Optional> *publishingHouseName; @property (nonatomic, assign) int type; // 1 : 标准版 2 : 互动版 @property (nonatomic, strong) NSString<Optional> *createTime; @property (nonatomic, strong) NSString<Optional> *startDate; @property (nonatomic, strong) NSString<Optional> *endDate; @property (nonatomic, assign) int purchaseType; // 1.在线购买,2.免费申请,3.代理商同步,4.活动免费购买,5.激活码券购买 @end
42.403846
110
0.652154
[ "model" ]
c1449711b5ac92a13afa7af7bade9b0d021845c6
32,758
h
C
dp/third-party/hyperscan/src/util/simd_utils.h
jtravee/neuvector
a88b9363108fc5c412be3007c3d4fb700d18decc
[ "Apache-2.0" ]
327
2022-01-17T02:45:20.000Z
2022-03-31T20:02:31.000Z
dp/third-party/hyperscan/src/util/simd_utils.h
jtravee/neuvector
a88b9363108fc5c412be3007c3d4fb700d18decc
[ "Apache-2.0" ]
45
2022-01-18T13:04:16.000Z
2022-03-31T17:57:10.000Z
dp/third-party/hyperscan/src/util/simd_utils.h
jtravee/neuvector
a88b9363108fc5c412be3007c3d4fb700d18decc
[ "Apache-2.0" ]
66
2022-01-14T18:55:18.000Z
2022-03-31T06:05:35.000Z
/* * Copyright (c) 2015-2017, Intel Corporation * * 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 Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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. */ /** \file * \brief SIMD types and primitive operations. */ #ifndef SIMD_UTILS #define SIMD_UTILS #if !defined(_WIN32) && !defined(__SSSE3__) #error SSSE3 instructions must be enabled #endif #include "config.h" #include "ue2common.h" #include "simd_types.h" #include "unaligned.h" #include "util/arch.h" #include "util/intrinsics.h" #include <string.h> // for memcpy // Define a common assume_aligned using an appropriate compiler built-in, if // it's available. Note that we need to handle C or C++ compilation. #ifdef __cplusplus # ifdef HAVE_CXX_BUILTIN_ASSUME_ALIGNED # define assume_aligned(x, y) __builtin_assume_aligned((x), (y)) # endif #else # ifdef HAVE_CC_BUILTIN_ASSUME_ALIGNED # define assume_aligned(x, y) __builtin_assume_aligned((x), (y)) # endif #endif // Fallback to identity case. #ifndef assume_aligned #define assume_aligned(x, y) (x) #endif #ifdef __cplusplus extern "C" { #endif extern const char vbs_mask_data[]; #ifdef __cplusplus } #endif static really_inline m128 ones128(void) { #if defined(__GNUC__) || defined(__INTEL_COMPILER) /* gcc gets this right */ return _mm_set1_epi8(0xFF); #else /* trick from Intel's optimization guide to generate all-ones. * ICC converts this to the single cmpeq instruction */ return _mm_cmpeq_epi8(_mm_setzero_si128(), _mm_setzero_si128()); #endif } static really_inline m128 zeroes128(void) { return _mm_setzero_si128(); } /** \brief Bitwise not for m128*/ static really_inline m128 not128(m128 a) { return _mm_xor_si128(a, ones128()); } /** \brief Return 1 if a and b are different otherwise 0 */ static really_inline int diff128(m128 a, m128 b) { return (_mm_movemask_epi8(_mm_cmpeq_epi8(a, b)) ^ 0xffff); } static really_inline int isnonzero128(m128 a) { return !!diff128(a, zeroes128()); } /** * "Rich" version of diff128(). Takes two vectors a and b and returns a 4-bit * mask indicating which 32-bit words contain differences. */ static really_inline u32 diffrich128(m128 a, m128 b) { a = _mm_cmpeq_epi32(a, b); return ~(_mm_movemask_ps(_mm_castsi128_ps(a))) & 0xf; } /** * "Rich" version of diff128(), 64-bit variant. Takes two vectors a and b and * returns a 4-bit mask indicating which 64-bit words contain differences. */ static really_inline u32 diffrich64_128(m128 a, m128 b) { #if defined(HAVE_SSE41) a = _mm_cmpeq_epi64(a, b); return ~(_mm_movemask_ps(_mm_castsi128_ps(a))) & 0x5; #else u32 d = diffrich128(a, b); return (d | (d >> 1)) & 0x5; #endif } static really_really_inline m128 lshift64_m128(m128 a, unsigned b) { #if defined(HAVE__BUILTIN_CONSTANT_P) if (__builtin_constant_p(b)) { return _mm_slli_epi64(a, b); } #endif m128 x = _mm_cvtsi32_si128(b); return _mm_sll_epi64(a, x); } #define rshift64_m128(a, b) _mm_srli_epi64((a), (b)) #define eq128(a, b) _mm_cmpeq_epi8((a), (b)) #define movemask128(a) ((u32)_mm_movemask_epi8((a))) static really_inline m128 set16x8(u8 c) { return _mm_set1_epi8(c); } static really_inline m128 set4x32(u32 c) { return _mm_set1_epi32(c); } static really_inline u32 movd(const m128 in) { return _mm_cvtsi128_si32(in); } static really_inline u64a movq(const m128 in) { #if defined(ARCH_X86_64) return _mm_cvtsi128_si64(in); #else // 32-bit - this is horrific u32 lo = movd(in); u32 hi = movd(_mm_srli_epi64(in, 32)); return (u64a)hi << 32 | lo; #endif } /* another form of movq */ static really_inline m128 load_m128_from_u64a(const u64a *p) { return _mm_set_epi64x(0LL, *p); } #define rshiftbyte_m128(a, count_immed) _mm_srli_si128(a, count_immed) #define lshiftbyte_m128(a, count_immed) _mm_slli_si128(a, count_immed) #if defined(HAVE_SSE41) #define extract32from128(a, imm) _mm_extract_epi32(a, imm) #define extract64from128(a, imm) _mm_extract_epi64(a, imm) #else #define extract32from128(a, imm) movd(_mm_srli_si128(a, imm << 2)) #define extract64from128(a, imm) movq(_mm_srli_si128(a, imm << 3)) #endif #if !defined(HAVE_AVX2) // TODO: this entire file needs restructuring - this carveout is awful #define extractlow64from256(a) movq(a.lo) #define extractlow32from256(a) movd(a.lo) #if defined(HAVE_SSE41) #define extract32from256(a, imm) _mm_extract_epi32((imm >> 2) ? a.hi : a.lo, imm % 4) #define extract64from256(a, imm) _mm_extract_epi64((imm >> 1) ? a.hi : a.lo, imm % 2) #else #define extract32from256(a, imm) movd(_mm_srli_si128((imm >> 2) ? a.hi : a.lo, (imm % 4) * 4)) #define extract64from256(a, imm) movq(_mm_srli_si128((imm >> 1) ? a.hi : a.lo, (imm % 2) * 8)) #endif #endif // !AVX2 static really_inline m128 and128(m128 a, m128 b) { return _mm_and_si128(a,b); } static really_inline m128 xor128(m128 a, m128 b) { return _mm_xor_si128(a,b); } static really_inline m128 or128(m128 a, m128 b) { return _mm_or_si128(a,b); } static really_inline m128 andnot128(m128 a, m128 b) { return _mm_andnot_si128(a, b); } // aligned load static really_inline m128 load128(const void *ptr) { assert(ISALIGNED_N(ptr, alignof(m128))); ptr = assume_aligned(ptr, 16); return _mm_load_si128((const m128 *)ptr); } // aligned store static really_inline void store128(void *ptr, m128 a) { assert(ISALIGNED_N(ptr, alignof(m128))); ptr = assume_aligned(ptr, 16); *(m128 *)ptr = a; } // unaligned load static really_inline m128 loadu128(const void *ptr) { return _mm_loadu_si128((const m128 *)ptr); } // unaligned store static really_inline void storeu128(void *ptr, m128 a) { _mm_storeu_si128 ((m128 *)ptr, a); } // packed unaligned store of first N bytes static really_inline void storebytes128(void *ptr, m128 a, unsigned int n) { assert(n <= sizeof(a)); memcpy(ptr, &a, n); } // packed unaligned load of first N bytes, pad with zero static really_inline m128 loadbytes128(const void *ptr, unsigned int n) { m128 a = zeroes128(); assert(n <= sizeof(a)); memcpy(&a, ptr, n); return a; } #ifdef __cplusplus extern "C" { #endif extern const u8 simd_onebit_masks[]; #ifdef __cplusplus } #endif static really_inline m128 mask1bit128(unsigned int n) { assert(n < sizeof(m128) * 8); u32 mask_idx = ((n % 8) * 64) + 95; mask_idx -= n / 8; return loadu128(&simd_onebit_masks[mask_idx]); } // switches on bit N in the given vector. static really_inline void setbit128(m128 *ptr, unsigned int n) { *ptr = or128(mask1bit128(n), *ptr); } // switches off bit N in the given vector. static really_inline void clearbit128(m128 *ptr, unsigned int n) { *ptr = andnot128(mask1bit128(n), *ptr); } // tests bit N in the given vector. static really_inline char testbit128(m128 val, unsigned int n) { const m128 mask = mask1bit128(n); #if defined(HAVE_SSE41) return !_mm_testz_si128(mask, val); #else return isnonzero128(and128(mask, val)); #endif } // offset must be an immediate #define palignr(r, l, offset) _mm_alignr_epi8(r, l, offset) static really_inline m128 pshufb_m128(m128 a, m128 b) { m128 result; result = _mm_shuffle_epi8(a, b); return result; } static really_inline m256 pshufb_m256(m256 a, m256 b) { #if defined(HAVE_AVX2) return _mm256_shuffle_epi8(a, b); #else m256 rv; rv.lo = pshufb_m128(a.lo, b.lo); rv.hi = pshufb_m128(a.hi, b.hi); return rv; #endif } #if defined(HAVE_AVX512) static really_inline m512 pshufb_m512(m512 a, m512 b) { return _mm512_shuffle_epi8(a, b); } static really_inline m512 maskz_pshufb_m512(__mmask64 k, m512 a, m512 b) { return _mm512_maskz_shuffle_epi8(k, a, b); } #endif static really_inline m128 variable_byte_shift_m128(m128 in, s32 amount) { assert(amount >= -16 && amount <= 16); m128 shift_mask = loadu128(vbs_mask_data + 16 - amount); return pshufb_m128(in, shift_mask); } static really_inline m128 max_u8_m128(m128 a, m128 b) { return _mm_max_epu8(a, b); } static really_inline m128 min_u8_m128(m128 a, m128 b) { return _mm_min_epu8(a, b); } static really_inline m128 sadd_u8_m128(m128 a, m128 b) { return _mm_adds_epu8(a, b); } static really_inline m128 sub_u8_m128(m128 a, m128 b) { return _mm_sub_epi8(a, b); } static really_inline m128 set64x2(u64a hi, u64a lo) { return _mm_set_epi64x(hi, lo); } /**** **** 256-bit Primitives ****/ #if defined(HAVE_AVX2) static really_really_inline m256 lshift64_m256(m256 a, unsigned b) { #if defined(HAVE__BUILTIN_CONSTANT_P) if (__builtin_constant_p(b)) { return _mm256_slli_epi64(a, b); } #endif m128 x = _mm_cvtsi32_si128(b); return _mm256_sll_epi64(a, x); } #define rshift64_m256(a, b) _mm256_srli_epi64((a), (b)) static really_inline m256 set32x8(u32 in) { return _mm256_set1_epi8(in); } #define eq256(a, b) _mm256_cmpeq_epi8((a), (b)) #define movemask256(a) ((u32)_mm256_movemask_epi8((a))) static really_inline m256 set2x128(m128 a) { return _mm256_broadcastsi128_si256(a); } #else static really_really_inline m256 lshift64_m256(m256 a, int b) { m256 rv = a; rv.lo = lshift64_m128(rv.lo, b); rv.hi = lshift64_m128(rv.hi, b); return rv; } static really_inline m256 rshift64_m256(m256 a, int b) { m256 rv = a; rv.lo = rshift64_m128(rv.lo, b); rv.hi = rshift64_m128(rv.hi, b); return rv; } static really_inline m256 set32x8(u32 in) { m256 rv; rv.lo = set16x8((u8) in); rv.hi = rv.lo; return rv; } static really_inline m256 eq256(m256 a, m256 b) { m256 rv; rv.lo = eq128(a.lo, b.lo); rv.hi = eq128(a.hi, b.hi); return rv; } static really_inline u32 movemask256(m256 a) { u32 lo_mask = movemask128(a.lo); u32 hi_mask = movemask128(a.hi); return lo_mask | (hi_mask << 16); } static really_inline m256 set2x128(m128 a) { m256 rv = {a, a}; return rv; } #endif static really_inline m256 zeroes256(void) { #if defined(HAVE_AVX2) return _mm256_setzero_si256(); #else m256 rv = {zeroes128(), zeroes128()}; return rv; #endif } static really_inline m256 ones256(void) { #if defined(HAVE_AVX2) m256 rv = _mm256_set1_epi8(0xFF); #else m256 rv = {ones128(), ones128()}; #endif return rv; } #if defined(HAVE_AVX2) static really_inline m256 and256(m256 a, m256 b) { return _mm256_and_si256(a, b); } #else static really_inline m256 and256(m256 a, m256 b) { m256 rv; rv.lo = and128(a.lo, b.lo); rv.hi = and128(a.hi, b.hi); return rv; } #endif #if defined(HAVE_AVX2) static really_inline m256 or256(m256 a, m256 b) { return _mm256_or_si256(a, b); } #else static really_inline m256 or256(m256 a, m256 b) { m256 rv; rv.lo = or128(a.lo, b.lo); rv.hi = or128(a.hi, b.hi); return rv; } #endif #if defined(HAVE_AVX2) static really_inline m256 xor256(m256 a, m256 b) { return _mm256_xor_si256(a, b); } #else static really_inline m256 xor256(m256 a, m256 b) { m256 rv; rv.lo = xor128(a.lo, b.lo); rv.hi = xor128(a.hi, b.hi); return rv; } #endif #if defined(HAVE_AVX2) static really_inline m256 not256(m256 a) { return _mm256_xor_si256(a, ones256()); } #else static really_inline m256 not256(m256 a) { m256 rv; rv.lo = not128(a.lo); rv.hi = not128(a.hi); return rv; } #endif #if defined(HAVE_AVX2) static really_inline m256 andnot256(m256 a, m256 b) { return _mm256_andnot_si256(a, b); } #else static really_inline m256 andnot256(m256 a, m256 b) { m256 rv; rv.lo = andnot128(a.lo, b.lo); rv.hi = andnot128(a.hi, b.hi); return rv; } #endif static really_inline int diff256(m256 a, m256 b) { #if defined(HAVE_AVX2) return !!(_mm256_movemask_epi8(_mm256_cmpeq_epi8(a, b)) ^ (int)-1); #else return diff128(a.lo, b.lo) || diff128(a.hi, b.hi); #endif } static really_inline int isnonzero256(m256 a) { #if defined(HAVE_AVX2) return !!diff256(a, zeroes256()); #else return isnonzero128(or128(a.lo, a.hi)); #endif } /** * "Rich" version of diff256(). Takes two vectors a and b and returns an 8-bit * mask indicating which 32-bit words contain differences. */ static really_inline u32 diffrich256(m256 a, m256 b) { #if defined(HAVE_AVX2) a = _mm256_cmpeq_epi32(a, b); return ~(_mm256_movemask_ps(_mm256_castsi256_ps(a))) & 0xFF; #else m128 z = zeroes128(); a.lo = _mm_cmpeq_epi32(a.lo, b.lo); a.hi = _mm_cmpeq_epi32(a.hi, b.hi); m128 packed = _mm_packs_epi16(_mm_packs_epi32(a.lo, a.hi), z); return ~(_mm_movemask_epi8(packed)) & 0xff; #endif } /** * "Rich" version of diff256(), 64-bit variant. Takes two vectors a and b and * returns an 8-bit mask indicating which 64-bit words contain differences. */ static really_inline u32 diffrich64_256(m256 a, m256 b) { u32 d = diffrich256(a, b); return (d | (d >> 1)) & 0x55555555; } // aligned load static really_inline m256 load256(const void *ptr) { assert(ISALIGNED_N(ptr, alignof(m256))); #if defined(HAVE_AVX2) return _mm256_load_si256((const m256 *)ptr); #else m256 rv = { load128(ptr), load128((const char *)ptr + 16) }; return rv; #endif } // aligned load of 128-bit value to low and high part of 256-bit value static really_inline m256 load2x128(const void *ptr) { #if defined(HAVE_AVX2) return set2x128(load128(ptr)); #else assert(ISALIGNED_N(ptr, alignof(m128))); m256 rv; rv.hi = rv.lo = load128(ptr); return rv; #endif } static really_inline m256 loadu2x128(const void *ptr) { return set2x128(loadu128(ptr)); } // aligned store static really_inline void store256(void *ptr, m256 a) { assert(ISALIGNED_N(ptr, alignof(m256))); #if defined(HAVE_AVX2) _mm256_store_si256((m256 *)ptr, a); #else ptr = assume_aligned(ptr, 16); *(m256 *)ptr = a; #endif } // unaligned load static really_inline m256 loadu256(const void *ptr) { #if defined(HAVE_AVX2) return _mm256_loadu_si256((const m256 *)ptr); #else m256 rv = { loadu128(ptr), loadu128((const char *)ptr + 16) }; return rv; #endif } // unaligned store static really_inline void storeu256(void *ptr, m256 a) { #if defined(HAVE_AVX2) _mm256_storeu_si256((m256 *)ptr, a); #else storeu128(ptr, a.lo); storeu128((char *)ptr + 16, a.hi); #endif } // packed unaligned store of first N bytes static really_inline void storebytes256(void *ptr, m256 a, unsigned int n) { assert(n <= sizeof(a)); memcpy(ptr, &a, n); } // packed unaligned load of first N bytes, pad with zero static really_inline m256 loadbytes256(const void *ptr, unsigned int n) { m256 a = zeroes256(); assert(n <= sizeof(a)); memcpy(&a, ptr, n); return a; } static really_inline m256 mask1bit256(unsigned int n) { assert(n < sizeof(m256) * 8); u32 mask_idx = ((n % 8) * 64) + 95; mask_idx -= n / 8; return loadu256(&simd_onebit_masks[mask_idx]); } static really_inline m256 set64x4(u64a hi_1, u64a hi_0, u64a lo_1, u64a lo_0) { #if defined(HAVE_AVX2) return _mm256_set_epi64x(hi_1, hi_0, lo_1, lo_0); #else m256 rv; rv.hi = set64x2(hi_1, hi_0); rv.lo = set64x2(lo_1, lo_0); return rv; #endif } #if !defined(HAVE_AVX2) // switches on bit N in the given vector. static really_inline void setbit256(m256 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); m128 *sub; if (n < 128) { sub = &ptr->lo; } else { sub = &ptr->hi; n -= 128; } setbit128(sub, n); } // switches off bit N in the given vector. static really_inline void clearbit256(m256 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); m128 *sub; if (n < 128) { sub = &ptr->lo; } else { sub = &ptr->hi; n -= 128; } clearbit128(sub, n); } // tests bit N in the given vector. static really_inline char testbit256(m256 val, unsigned int n) { assert(n < sizeof(val) * 8); m128 sub; if (n < 128) { sub = val.lo; } else { sub = val.hi; n -= 128; } return testbit128(sub, n); } static really_really_inline m128 movdq_hi(m256 x) { return x.hi; } static really_really_inline m128 movdq_lo(m256 x) { return x.lo; } static really_inline m256 combine2x128(m128 hi, m128 lo) { m256 rv = {lo, hi}; return rv; } #else // AVX2 // switches on bit N in the given vector. static really_inline void setbit256(m256 *ptr, unsigned int n) { *ptr = or256(mask1bit256(n), *ptr); } static really_inline void clearbit256(m256 *ptr, unsigned int n) { *ptr = andnot256(mask1bit256(n), *ptr); } // tests bit N in the given vector. static really_inline char testbit256(m256 val, unsigned int n) { const m256 mask = mask1bit256(n); return !_mm256_testz_si256(mask, val); } static really_really_inline m128 movdq_hi(m256 x) { return _mm256_extracti128_si256(x, 1); } static really_really_inline m128 movdq_lo(m256 x) { return _mm256_extracti128_si256(x, 0); } #define cast256to128(a) _mm256_castsi256_si128(a) #define cast128to256(a) _mm256_castsi128_si256(a) #define swap128in256(a) _mm256_permute4x64_epi64(a, 0x4E) #define insert128to256(a, b, imm) _mm256_inserti128_si256(a, b, imm) #define rshift128_m256(a, count_immed) _mm256_srli_si256(a, count_immed) #define lshift128_m256(a, count_immed) _mm256_slli_si256(a, count_immed) #define extract64from256(a, imm) _mm_extract_epi64(_mm256_extracti128_si256(a, imm >> 1), imm % 2) #define extract32from256(a, imm) _mm_extract_epi32(_mm256_extracti128_si256(a, imm >> 2), imm % 4) #define extractlow64from256(a) _mm_cvtsi128_si64(cast256to128(a)) #define extractlow32from256(a) movd(cast256to128(a)) #define interleave256hi(a, b) _mm256_unpackhi_epi8(a, b) #define interleave256lo(a, b) _mm256_unpacklo_epi8(a, b) #define vpalignr(r, l, offset) _mm256_alignr_epi8(r, l, offset) static really_inline m256 combine2x128(m128 hi, m128 lo) { #if defined(_mm256_set_m128i) return _mm256_set_m128i(hi, lo); #else return insert128to256(cast128to256(lo), hi, 1); #endif } #endif //AVX2 #if defined(HAVE_AVX512) #define extract128from512(a, imm) _mm512_extracti32x4_epi32(a, imm) #define interleave512hi(a, b) _mm512_unpackhi_epi8(a, b) #define interleave512lo(a, b) _mm512_unpacklo_epi8(a, b) #define set2x256(a) _mm512_broadcast_i64x4(a) #define mask_set2x256(src, k, a) _mm512_mask_broadcast_i64x4(src, k, a) #define vpermq512(idx, a) _mm512_permutexvar_epi64(idx, a) #endif /**** **** 384-bit Primitives ****/ static really_inline m384 and384(m384 a, m384 b) { m384 rv; rv.lo = and128(a.lo, b.lo); rv.mid = and128(a.mid, b.mid); rv.hi = and128(a.hi, b.hi); return rv; } static really_inline m384 or384(m384 a, m384 b) { m384 rv; rv.lo = or128(a.lo, b.lo); rv.mid = or128(a.mid, b.mid); rv.hi = or128(a.hi, b.hi); return rv; } static really_inline m384 xor384(m384 a, m384 b) { m384 rv; rv.lo = xor128(a.lo, b.lo); rv.mid = xor128(a.mid, b.mid); rv.hi = xor128(a.hi, b.hi); return rv; } static really_inline m384 not384(m384 a) { m384 rv; rv.lo = not128(a.lo); rv.mid = not128(a.mid); rv.hi = not128(a.hi); return rv; } static really_inline m384 andnot384(m384 a, m384 b) { m384 rv; rv.lo = andnot128(a.lo, b.lo); rv.mid = andnot128(a.mid, b.mid); rv.hi = andnot128(a.hi, b.hi); return rv; } static really_really_inline m384 lshift64_m384(m384 a, unsigned b) { m384 rv; rv.lo = lshift64_m128(a.lo, b); rv.mid = lshift64_m128(a.mid, b); rv.hi = lshift64_m128(a.hi, b); return rv; } static really_inline m384 zeroes384(void) { m384 rv = {zeroes128(), zeroes128(), zeroes128()}; return rv; } static really_inline m384 ones384(void) { m384 rv = {ones128(), ones128(), ones128()}; return rv; } static really_inline int diff384(m384 a, m384 b) { return diff128(a.lo, b.lo) || diff128(a.mid, b.mid) || diff128(a.hi, b.hi); } static really_inline int isnonzero384(m384 a) { return isnonzero128(or128(or128(a.lo, a.mid), a.hi)); } /** * "Rich" version of diff384(). Takes two vectors a and b and returns a 12-bit * mask indicating which 32-bit words contain differences. */ static really_inline u32 diffrich384(m384 a, m384 b) { m128 z = zeroes128(); a.lo = _mm_cmpeq_epi32(a.lo, b.lo); a.mid = _mm_cmpeq_epi32(a.mid, b.mid); a.hi = _mm_cmpeq_epi32(a.hi, b.hi); m128 packed = _mm_packs_epi16(_mm_packs_epi32(a.lo, a.mid), _mm_packs_epi32(a.hi, z)); return ~(_mm_movemask_epi8(packed)) & 0xfff; } /** * "Rich" version of diff384(), 64-bit variant. Takes two vectors a and b and * returns a 12-bit mask indicating which 64-bit words contain differences. */ static really_inline u32 diffrich64_384(m384 a, m384 b) { u32 d = diffrich384(a, b); return (d | (d >> 1)) & 0x55555555; } // aligned load static really_inline m384 load384(const void *ptr) { assert(ISALIGNED_16(ptr)); m384 rv = { load128(ptr), load128((const char *)ptr + 16), load128((const char *)ptr + 32) }; return rv; } // aligned store static really_inline void store384(void *ptr, m384 a) { assert(ISALIGNED_16(ptr)); ptr = assume_aligned(ptr, 16); *(m384 *)ptr = a; } // unaligned load static really_inline m384 loadu384(const void *ptr) { m384 rv = { loadu128(ptr), loadu128((const char *)ptr + 16), loadu128((const char *)ptr + 32)}; return rv; } // packed unaligned store of first N bytes static really_inline void storebytes384(void *ptr, m384 a, unsigned int n) { assert(n <= sizeof(a)); memcpy(ptr, &a, n); } // packed unaligned load of first N bytes, pad with zero static really_inline m384 loadbytes384(const void *ptr, unsigned int n) { m384 a = zeroes384(); assert(n <= sizeof(a)); memcpy(&a, ptr, n); return a; } // switches on bit N in the given vector. static really_inline void setbit384(m384 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); m128 *sub; if (n < 128) { sub = &ptr->lo; } else if (n < 256) { sub = &ptr->mid; } else { sub = &ptr->hi; } setbit128(sub, n % 128); } // switches off bit N in the given vector. static really_inline void clearbit384(m384 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); m128 *sub; if (n < 128) { sub = &ptr->lo; } else if (n < 256) { sub = &ptr->mid; } else { sub = &ptr->hi; } clearbit128(sub, n % 128); } // tests bit N in the given vector. static really_inline char testbit384(m384 val, unsigned int n) { assert(n < sizeof(val) * 8); m128 sub; if (n < 128) { sub = val.lo; } else if (n < 256) { sub = val.mid; } else { sub = val.hi; } return testbit128(sub, n % 128); } /**** **** 512-bit Primitives ****/ #define eq512mask(a, b) _mm512_cmpeq_epi8_mask((a), (b)) #define masked_eq512mask(k, a, b) _mm512_mask_cmpeq_epi8_mask((k), (a), (b)) static really_inline m512 zeroes512(void) { #if defined(HAVE_AVX512) return _mm512_setzero_si512(); #else m512 rv = {zeroes256(), zeroes256()}; return rv; #endif } static really_inline m512 ones512(void) { #if defined(HAVE_AVX512) return _mm512_set1_epi8(0xFF); //return _mm512_xor_si512(_mm512_setzero_si512(), _mm512_setzero_si512()); #else m512 rv = {ones256(), ones256()}; return rv; #endif } #if defined(HAVE_AVX512) static really_inline m512 set64x8(u8 a) { return _mm512_set1_epi8(a); } static really_inline m512 set8x64(u64a a) { return _mm512_set1_epi64(a); } static really_inline m512 set512_64(u64a hi_3, u64a hi_2, u64a hi_1, u64a hi_0, u64a lo_3, u64a lo_2, u64a lo_1, u64a lo_0) { return _mm512_set_epi64(hi_3, hi_2, hi_1, hi_0, lo_3, lo_2, lo_1, lo_0); } static really_inline m512 swap256in512(m512 a) { m512 idx = set512_64(3ULL, 2ULL, 1ULL, 0ULL, 7ULL, 6ULL, 5ULL, 4ULL); return vpermq512(idx, a); } static really_inline m512 set4x128(m128 a) { return _mm512_broadcast_i32x4(a); } #endif static really_inline m512 and512(m512 a, m512 b) { #if defined(HAVE_AVX512) return _mm512_and_si512(a, b); #else m512 rv; rv.lo = and256(a.lo, b.lo); rv.hi = and256(a.hi, b.hi); return rv; #endif } static really_inline m512 or512(m512 a, m512 b) { #if defined(HAVE_AVX512) return _mm512_or_si512(a, b); #else m512 rv; rv.lo = or256(a.lo, b.lo); rv.hi = or256(a.hi, b.hi); return rv; #endif } static really_inline m512 xor512(m512 a, m512 b) { #if defined(HAVE_AVX512) return _mm512_xor_si512(a, b); #else m512 rv; rv.lo = xor256(a.lo, b.lo); rv.hi = xor256(a.hi, b.hi); return rv; #endif } static really_inline m512 not512(m512 a) { #if defined(HAVE_AVX512) return _mm512_xor_si512(a, ones512()); #else m512 rv; rv.lo = not256(a.lo); rv.hi = not256(a.hi); return rv; #endif } static really_inline m512 andnot512(m512 a, m512 b) { #if defined(HAVE_AVX512) return _mm512_andnot_si512(a, b); #else m512 rv; rv.lo = andnot256(a.lo, b.lo); rv.hi = andnot256(a.hi, b.hi); return rv; #endif } #if defined(HAVE_AVX512) static really_really_inline m512 lshift64_m512(m512 a, unsigned b) { #if defined(HAVE__BUILTIN_CONSTANT_P) if (__builtin_constant_p(b)) { return _mm512_slli_epi64(a, b); } #endif m128 x = _mm_cvtsi32_si128(b); return _mm512_sll_epi64(a, x); } #else static really_really_inline m512 lshift64_m512(m512 a, unsigned b) { m512 rv; rv.lo = lshift64_m256(a.lo, b); rv.hi = lshift64_m256(a.hi, b); return rv; } #endif #if defined(HAVE_AVX512) #define rshift64_m512(a, b) _mm512_srli_epi64((a), (b)) #define rshift128_m512(a, count_immed) _mm512_bsrli_epi128(a, count_immed) #define lshift128_m512(a, count_immed) _mm512_bslli_epi128(a, count_immed) #endif #if !defined(_MM_CMPINT_NE) #define _MM_CMPINT_NE 0x4 #endif static really_inline int diff512(m512 a, m512 b) { #if defined(HAVE_AVX512) return !!_mm512_cmp_epi8_mask(a, b, _MM_CMPINT_NE); #else return diff256(a.lo, b.lo) || diff256(a.hi, b.hi); #endif } static really_inline int isnonzero512(m512 a) { #if defined(HAVE_AVX512) return diff512(a, zeroes512()); #elif defined(HAVE_AVX2) m256 x = or256(a.lo, a.hi); return !!diff256(x, zeroes256()); #else m128 x = or128(a.lo.lo, a.lo.hi); m128 y = or128(a.hi.lo, a.hi.hi); return isnonzero128(or128(x, y)); #endif } /** * "Rich" version of diff512(). Takes two vectors a and b and returns a 16-bit * mask indicating which 32-bit words contain differences. */ static really_inline u32 diffrich512(m512 a, m512 b) { #if defined(HAVE_AVX512) return _mm512_cmp_epi32_mask(a, b, _MM_CMPINT_NE); #elif defined(HAVE_AVX2) return diffrich256(a.lo, b.lo) | (diffrich256(a.hi, b.hi) << 8); #else a.lo.lo = _mm_cmpeq_epi32(a.lo.lo, b.lo.lo); a.lo.hi = _mm_cmpeq_epi32(a.lo.hi, b.lo.hi); a.hi.lo = _mm_cmpeq_epi32(a.hi.lo, b.hi.lo); a.hi.hi = _mm_cmpeq_epi32(a.hi.hi, b.hi.hi); m128 packed = _mm_packs_epi16(_mm_packs_epi32(a.lo.lo, a.lo.hi), _mm_packs_epi32(a.hi.lo, a.hi.hi)); return ~(_mm_movemask_epi8(packed)) & 0xffff; #endif } /** * "Rich" version of diffrich(), 64-bit variant. Takes two vectors a and b and * returns a 16-bit mask indicating which 64-bit words contain differences. */ static really_inline u32 diffrich64_512(m512 a, m512 b) { //TODO: cmp_epi64? u32 d = diffrich512(a, b); return (d | (d >> 1)) & 0x55555555; } // aligned load static really_inline m512 load512(const void *ptr) { #if defined(HAVE_AVX512) return _mm512_load_si512(ptr); #else assert(ISALIGNED_N(ptr, alignof(m256))); m512 rv = { load256(ptr), load256((const char *)ptr + 32) }; return rv; #endif } // aligned store static really_inline void store512(void *ptr, m512 a) { assert(ISALIGNED_N(ptr, alignof(m512))); #if defined(HAVE_AVX512) return _mm512_store_si512(ptr, a); #elif defined(HAVE_AVX2) m512 *x = (m512 *)ptr; store256(&x->lo, a.lo); store256(&x->hi, a.hi); #else ptr = assume_aligned(ptr, 16); *(m512 *)ptr = a; #endif } // unaligned load static really_inline m512 loadu512(const void *ptr) { #if defined(HAVE_AVX512) return _mm512_loadu_si512(ptr); #else m512 rv = { loadu256(ptr), loadu256((const char *)ptr + 32) }; return rv; #endif } #if defined(HAVE_AVX512) static really_inline m512 loadu_maskz_m512(__mmask64 k, const void *ptr) { return _mm512_maskz_loadu_epi8(k, ptr); } static really_inline m512 loadu_mask_m512(m512 src, __mmask64 k, const void *ptr) { return _mm512_mask_loadu_epi8(src, k, ptr); } static really_inline m512 set_mask_m512(__mmask64 k) { return _mm512_movm_epi8(k); } #endif // packed unaligned store of first N bytes static really_inline void storebytes512(void *ptr, m512 a, unsigned int n) { assert(n <= sizeof(a)); memcpy(ptr, &a, n); } // packed unaligned load of first N bytes, pad with zero static really_inline m512 loadbytes512(const void *ptr, unsigned int n) { m512 a = zeroes512(); assert(n <= sizeof(a)); memcpy(&a, ptr, n); return a; } static really_inline m512 mask1bit512(unsigned int n) { assert(n < sizeof(m512) * 8); u32 mask_idx = ((n % 8) * 64) + 95; mask_idx -= n / 8; return loadu512(&simd_onebit_masks[mask_idx]); } // switches on bit N in the given vector. static really_inline void setbit512(m512 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); #if !defined(HAVE_AVX2) m128 *sub; if (n < 128) { sub = &ptr->lo.lo; } else if (n < 256) { sub = &ptr->lo.hi; } else if (n < 384) { sub = &ptr->hi.lo; } else { sub = &ptr->hi.hi; } setbit128(sub, n % 128); #elif defined(HAVE_AVX512) *ptr = or512(mask1bit512(n), *ptr); #else m256 *sub; if (n < 256) { sub = &ptr->lo; } else { sub = &ptr->hi; n -= 256; } setbit256(sub, n); #endif } // switches off bit N in the given vector. static really_inline void clearbit512(m512 *ptr, unsigned int n) { assert(n < sizeof(*ptr) * 8); #if !defined(HAVE_AVX2) m128 *sub; if (n < 128) { sub = &ptr->lo.lo; } else if (n < 256) { sub = &ptr->lo.hi; } else if (n < 384) { sub = &ptr->hi.lo; } else { sub = &ptr->hi.hi; } clearbit128(sub, n % 128); #elif defined(HAVE_AVX512) *ptr = andnot512(mask1bit512(n), *ptr); #else m256 *sub; if (n < 256) { sub = &ptr->lo; } else { sub = &ptr->hi; n -= 256; } clearbit256(sub, n); #endif } // tests bit N in the given vector. static really_inline char testbit512(m512 val, unsigned int n) { assert(n < sizeof(val) * 8); #if !defined(HAVE_AVX2) m128 sub; if (n < 128) { sub = val.lo.lo; } else if (n < 256) { sub = val.lo.hi; } else if (n < 384) { sub = val.hi.lo; } else { sub = val.hi.hi; } return testbit128(sub, n % 128); #elif defined(HAVE_AVX512) const m512 mask = mask1bit512(n); return !!_mm512_test_epi8_mask(mask, val); #else m256 sub; if (n < 256) { sub = val.lo; } else { sub = val.hi; n -= 256; } return testbit256(sub, n); #endif } #endif
24.704374
98
0.668295
[ "vector" ]
c144c246f7a98fd59b62c44883479736f508326f
756
h
C
ShaderManager.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
ShaderManager.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
ShaderManager.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <vector> #include <fstream> #include "glew.h" using namespace std; // default shader // can be inherited to edit class ShaderProgram { public: GLuint m_shaderProgramLocation; //matrix locations int m_shaderRotMatLocation; int m_shaderModelMatLocation; int m_shaderViewMatLocation; int m_shaderProjMatLocation; //texture sample locations int m_shaderText1SamplerLocation; ShaderProgram(char * _vertexShaderDir, char * _fragmentShaderDir); ~ShaderProgram(); private: string LoadShader(const char *filePath); bool CheckShaderCompiled(GLint shader); void BuildShader(GLuint &_shaderProgramX, char * vertexShaderDir, char * fragmentShaderDir); };
21.6
94
0.753968
[ "vector" ]
c14a97d441522699eda0af2f9810b0b1128d43d3
3,196
h
C
contrib/vr/OpenVRActionList.h
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
636
2018-06-21T20:46:36.000Z
2022-03-30T13:07:47.000Z
contrib/vr/OpenVRActionList.h
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
218
2018-06-25T00:10:59.000Z
2022-03-23T14:15:48.000Z
contrib/vr/OpenVRActionList.h
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
192
2018-06-21T17:33:10.000Z
2022-03-31T17:53:03.000Z
/* OpenVR for PyMOL Copyright Notice ===================================== The OpenVR for PyMOL source code is copyrighted, but you can freely use and copy it as long as you don't change or remove any of the Copyright notices. OpenVR for PyMOL is made available under the following open-source license terms: ------------------------------------------------------------------------------ Copyright (c) 2018 EPAM Systems, Inc. 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 _H_OpenVRActionList #define _H_OpenVRActionList // system headers #include <vector> // local headers #include "OpenVRAction.h" struct OpenVRActionList { typedef std::vector<OpenVRAction*> ListType; ListType all; vr::VRActionSetHandle_t DefaultSet; OpenVRAction* LeftHand; OpenVRAction* RightHand; OpenVRAction* LGrip; OpenVRAction* RGrip; OpenVRAction* ToggleMenu; OpenVRAction* Laser; OpenVRAction* ActionSetNext; OpenVRAction* ActionSetPrev; OpenVRAction* Action1; OpenVRAction* Action2; OpenVRAction* Action3; explicit OpenVRActionList(vr::IVRInput* Input) { Input->GetActionSetHandle("/actions/pymol", &DefaultSet); #define OPENVR_ADD_ACTION(set, Action, ...) all.push_back(Action = new OpenVRAction(Input, "/actions/" set "/in/" #Action, ##__VA_ARGS__)); OPENVR_ADD_ACTION("pymol", LeftHand, OpenVRAction::TYPE_POSE); OPENVR_ADD_ACTION("pymol", RightHand, OpenVRAction::TYPE_POSE); OPENVR_ADD_ACTION("pymol", LGrip); OPENVR_ADD_ACTION("pymol", RGrip); OPENVR_ADD_ACTION("pymol", ToggleMenu); OPENVR_ADD_ACTION("pymol", Laser); OPENVR_ADD_ACTION("pymol", ActionSetNext); OPENVR_ADD_ACTION("pymol", ActionSetPrev); OPENVR_ADD_ACTION("pymol", Action1); OPENVR_ADD_ACTION("pymol", Action2); OPENVR_ADD_ACTION("pymol", Action3); #undef OPENVR_ADD_ACTION } void Update(vr::IVRInput* Input) { vr::VRActiveActionSet_t activeSet = {DefaultSet}; Input->UpdateActionState(&activeSet, sizeof(activeSet), 1); for (ListType::iterator i = all.begin(), iend = all.end(); i != iend; ++i) { (*i)->Update(Input); } } }; #endif // _H_OpenVRActionList
35.511111
139
0.710263
[ "vector" ]
c14b7f4df38ef3a9d3a5d54f5a76fd64d5e5b48c
77,969
h
C
logdevice/test/utils/IntegrationTestUtils.h
mcrnic/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/test/utils/IntegrationTestUtils.h
mcrnic/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/test/utils/IntegrationTestUtils.h
mcrnic/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include <initializer_list> #include <memory> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <folly/Optional.h> #include <folly/Subprocess.h> #include <folly/experimental/TestUtil.h> #include "folly/io/async/EventBase.h" #include "logdevice/common/EpochMetaData.h" #include "logdevice/common/ShardAuthoritativeStatusMap.h" #include "logdevice/common/ShardID.h" #include "logdevice/common/configuration/Configuration.h" #include "logdevice/common/configuration/InternalLogs.h" #include "logdevice/common/configuration/UpdateableConfig.h" #include "logdevice/common/configuration/logs/LogsConfigTree.h" #include "logdevice/common/debug.h" #include "logdevice/common/event_log/EventLogRecord.h" #include "logdevice/common/replicated_state_machine/RsmVersionTypes.h" #include "logdevice/common/test/NodesConfigurationTestUtil.h" #include "logdevice/common/test/TestUtil.h" #include "logdevice/include/ClientSettings.h" #include "logdevice/include/LogsConfigTypes.h" #include "logdevice/include/types.h" #include "logdevice/test/utils/AdminServer.h" #include "logdevice/test/utils/MetaDataProvisioner.h" #include "logdevice/test/utils/NodesConfigurationFileUpdater.h" #include "logdevice/test/utils/ParamMaps.h" #include "logdevice/test/utils/port_selection.h" namespace facebook { namespace logdevice { /** * @file Utilities for running LogDevice clusters in integration tests. * * In the common case, this suffices to spin up a LogDevice cluster in an * integration test: * * // Start a LogDevice cluster with 5 nodes on localhost. * auto cluster = logdevice::IntegrationTestUtils::ClusterFactory().create(5); * * // Create a Client that can be used to write and read data. * std::shared_ptr<logdevice::Client> client = cluster->createClient(); * * // Cluster shuts down when it goes out of scope. */ /* * Several environment variables alter how the utilities behave and can aid * debugging. * * LOGDEVICE_TEST_PAUSE_FOR_GDB=1 makes ClusterFactory pause the main process * right after starting the cluster, allowing the user to attach to server * processes with GDB. For convenience, command lines to attach GDB are * printed to stderr. * * LOGDEVICE_TEST_LEAVE_DATA=1 makes Cluster not delete data from the * filesystem when shutting down. For convenience, the path is logged at info * level. * * LOGDEVICE_TEST_BINARY controls which binary to run as the server. If not * set, _bin/logdevice/server/logdeviced is used. * * LOGDEVICE_TEST_ADMIN_SERVER_BINARY controls which binary to run as the admin * server. If not set, _bin/logdevice/ops/admin_server/ld-admin-server is used. * LOGDEVICE_TEST_USE_TCP use TCP ports instead of UNIX domain sockets * * LOGDEVICE_LOG_LEVEL set the default log level used by tests * * LOGDEVICE_TEST_FORCE_SSL forces all sockets to be SSL-enabled * * LOGDEVICE_TEST_NO_TIMEOUT do not enforce timeout in tests * * LOGDEVICE_TEST_MESSAGE_ERROR_CHANCE together defines chance and status * LOGDEVICE_TEST_MESSAGE_STATUS parameters for message error injection * */ class Client; class EpochStore; class FileConfigSource; class ShardedLocalLogStore; namespace configuration { namespace nodes { class NodesConfigurationStore; }} // namespace configuration::nodes namespace test { struct ServerInfo; } namespace thrift { class AdminAPIAsyncClient; } namespace IntegrationTestUtils { class Cluster; class Node; // used to specify the type of rockdb local logstore for storage // nodes in the cluster enum class RocksDBType : uint8_t { SINGLE, PARTITIONED }; enum class NodesConfigurationSourceOfTruth { NCM, SERVER_CONFIG }; /** * Configures a cluster and creates it. */ class ClusterFactory { public: ClusterFactory(); /** * Creates a Cluster object, configured with logs 1 and 2. * * Unless setNodes() is called (in which case nnodes is ignored), * Cluster will contain the specified number of nodes. If nnodes = 1, the one * node will act as both a sequencer and storage node. Otherwise, there will * be one sequencer node and the rest will be storage nodes. * * By default, an initial epoch metadata will be provisioned for all logs * in the configuration, both in epoch store and in metadata storage nodes * as metadata log records. The nodeset in the metadata includes ALL nodes in * the cluster and replication factor is the value specified in LogConfig. * Regarding the epoch, for metadata log records in storage nodes, _epoch_ and * _effective_since_ are both EPOCH_MIN, while for metadata in the epoch * store, _epoch_ is set to be EPOCH_MIN+1 with _effective_since_ remains * EPOCH_MIN. * * A side effect of the provison is that sequencer nodes of the cluster * will be started on epoch 2 (EPOCH_MIN+1) and recovery will be performed * on sequencer nodes when the cluster starts. */ std::unique_ptr<Cluster> create(int nnodes); /** * Creates a Cluster, specifying the full config to be used by the * cluster. This allows for fine control of configuration. Only the * addresses of nodes will be overwritten by the factory. */ std::unique_ptr<Cluster> create(const Configuration& config); /** * Call the passed in function on this object. Typically used to * collect settings common to multiple test cases in a single * function, and apply them by adding a single function call in * each test case function. Example: * * static void commonOptions(IntegrationTestUtils::ClusterFactory& cluster) { * cluster * .setRocksDBType(IntegrationTestUtils::RocksDBType::PARTITIONED); * } * * ... * * auto cluster = IntegrationTestUtils::ClusterFactory() * .apply(commonOptions) * .setLogAttributes(log_attrs) * .setEventLogAttributes(log_attrs) * .setNumLogs(1) * .create(nnodes); */ template <typename F> ClusterFactory& apply(F fn) { fn(*this); return *this; } /** * Use tcp ports instead of unix domain sockets. This can be used for tests * that verify behaviors specific to TCP. */ ClusterFactory& useTcp() { use_tcp_ = true; return *this; } /** * Sets the default log attributes to use for logs when using the simple * factory create(nnodes). If this is never called, a default log config will * be used with reasonable replication parameters depending on nnodes. */ ClusterFactory& setLogAttributes(logsconfig::LogAttributes log_attributes) { log_attributes_ = log_attributes; return *this; } /** * Set the attributes for the internal config log. */ ClusterFactory& setConfigLogAttributes(logsconfig::LogAttributes attrs); /** * Set the attributes for the internal event log. */ ClusterFactory& setEventLogAttributes(logsconfig::LogAttributes attrs); /** * Set the attributes for the internal event log delta. * NOTE: unlike setEventLogAttributes() above, does not set attributes * for the "event_log_snapshots" log. */ ClusterFactory& setEventLogDeltaAttributes(logsconfig::LogAttributes attrs); /** * Set the attributes for the internal maintenance log */ ClusterFactory& setMaintenanceLogAttributes(logsconfig::LogAttributes attrs); /** * Enables LogsConfigManager for clusters. Strongly recommend also calling * useHashBasedSequencerAssignment(), especially if creating log groups or * directories after startup, since that will: * a) enable lazy sequencer activation (since static activation won't work) * b) enable gossip, for failure detector, required for lazy activation * c) wait for all nodes to be marked as ALIVE via gossip */ ClusterFactory& enableLogsConfigManager(); /** * Sets the metadata log config to use for logs when using the simple factory * create(nnodes). If this is never called, a default metadata log config * will be used with metadata log stored on all nodes and replication factor * set to be min(3, num_storage_nodes) */ ClusterFactory& setMetaDataLogsConfig(Configuration::MetaDataLogsConfig meta_config) { meta_config_ = meta_config; return *this; } /** * Sets the number of logs in the config. Logs will be numbered 1 through * `n'. Ignored when LogsConfigManager is enabled, use * setNumLogsConfigManagerLogs instead. */ ClusterFactory& setNumLogs(int n) { num_logs_ = n; return *this; } /** * Sets that number of logs that needs to be created if LogsConfigManager is * enabled. It's created by client API calls after after bootstrapping the * cluster. It's ignored when `defer_start_` is true. */ ClusterFactory& setNumLogsConfigManagerLogs(int n) { num_logs_config_manager_logs_ = n; return *this; } /** * If called, create() will use specified node configs. */ ClusterFactory& setNodes(std::shared_ptr<const NodesConfiguration> nodes) { nodes_config_ = std::move(nodes); return *this; } /** * Set number of racks to spread the storage amongst. Ignored if the * node config is overridden with `setNodes()`. By default the number of racks * is 1. Nodes will be assigned to a rack in round robin fashion, ie if there * are 2 racks, nodes with nid % 2 == 0 will be in rack 1 and the others in * rack 2. */ ClusterFactory& setNumRacks(int num_racks) { num_racks_ = num_racks; return *this; } /** * Set the number of shards to use on storage nodes. * Ignored if you configure nodes using setNodes(). */ ClusterFactory& setNumDBShards(int num_db_shards) { num_db_shards_ = num_db_shards; return *this; } /** * Sets the rocksdb type for storage nodes in the cluster */ ClusterFactory& setRocksDBType(RocksDBType db_type) { rocksdb_type_ = db_type; setParam("--rocksdb-partitioned", db_type == RocksDBType::PARTITIONED ? "true" : "false"); return *this; } /** * Sets whether the standalone admin server will be running or not. */ ClusterFactory& useStandaloneAdminServer(bool enable) { use_standalone_admin_server_ = enable; return *this; } /** * If called, epoch metadata will be provisioned in epoch store and metadata * storage nodes on cluster startup. */ ClusterFactory& doPreProvisionEpochMetaData() { provision_epoch_metadata_ = true; return *this; } ClusterFactory& setNodesConfigurationSourceOfTruth(NodesConfigurationSourceOfTruth sot) { nodes_configuration_sot_ = sot; return *this; } /** * By default, epoch store metadata is provisioned and metadata logs are * written by sequencers. If this method is called, sequencers will be * precluded from writing metadata. Note that this will have no effect if * ClusterFactory::setMetaDataLogsConfig() is called with a MetaDataLogsConfig * instance as an argument. */ ClusterFactory& doNotLetSequencersProvisionEpochMetaData() { let_sequencers_provision_metadata_ = false; return *this; } /** * If metadata is to be provisioned by the test cluster, and it already * exists, the default behaviour is to fail provisioning with E::EXISTS. * Call this method to silently use existing metadata instead. */ ClusterFactory& allowExistingMetaData() { allow_existing_metadata_ = true; return *this; } /** * Skips assigning SSL addresses to nodes. */ ClusterFactory& noSSLAddress() { no_ssl_address_ = true; return *this; } enum class EventLogMode { NONE, DELTA_LOG_ONLY, SNAPSHOTTED }; /** * @param mode one of: * - EventLogMode::NONE: an event log is not provisioned * in the cluster's config. TODO(#8466255): currently the event * log is not mandatory in the config file. When we make it * mandatory, all tests that use this option must be modified; * - EventLogMode::DELTA_LOG_ONLY: no snapshot log is provisioned; * - EventLogMode::SNAPSHOTTED: both the delta and snapshot logs * are provisioned. If the --event-log-snapshotting setting is * true, the content of the delta log will be periodically * snapshotted onto this log. */ ClusterFactory& eventLogMode(EventLogMode mode) { event_log_mode_ = mode; return *this; } /** * If called, epoch metadata will be provisioned using the specific nodeset * selector. Otherwise, SELECT_ALL will be used to selecto all nodes in the * cluster as the nodeset */ ClusterFactory& setProvisionNodeSetSelector(std::shared_ptr<NodeSetSelector> selector) { provision_nodeset_selector_ = std::move(selector); return *this; } /** * Sets replication factor to use for internal and metadata logs if * set*LogsConfig() wasn't called. * If not called, the default is 3 for metadata log, 2 for internal logs. */ ClusterFactory& setInternalLogsReplicationFactor(int r) { internal_logs_replication_factor_ = r; return *this; } /** * If called, create() will not immediately start all nodes after creating * a Cluster object. Instead, Cluster::start() should be called to run all * processes. */ ClusterFactory& deferStart() { defer_start_ = true; return *this; } /** * Sets a command line parameter for logdeviced processes. The scope parameter * can be used to specify that the parameter is only for sequencer nodes or * storage nodes. */ ClusterFactory& setParam(std::string key, std::string value, ParamScope scope = ParamScope::ALL) { return setParam(ParamSpec{key, value, scope}); } /** * Same as setParam(key, value, scope) but for parameters without values */ ClusterFactory& setParam(std::string key, ParamScope scope = ParamScope::ALL) { return setParam(ParamSpec{key, "true", scope}); } /** * Same as setParam(key, value, scope) or setParam(key, scope) as appropriate. */ ClusterFactory& setParam(ParamSpec spec) { // If the scope is ParamScope::ALL, we can safely add this to the server // config instead of command line args. // TODO: Codemod all the usages of ParamScope::ALL to use setServerSettings // directly. if (spec.scope_ == ParamScope::ALL) { // Trim the "--" prefix from the command line arg name. auto& key = spec.key_; ld_check(key.substr(0, 2) == "--"); setServerSetting(spec.key_.substr(2), spec.value_); } else { cmd_param_[spec.scope_][spec.key_] = spec.value_; } return *this; } /** * Sets a config setting for logdeviced processes. */ ClusterFactory& setServerSetting(std::string key, std::string value) { server_settings_[std::move(key)] = std::move(value); return *this; } /** * Sets a config setting for clients */ ClusterFactory& setClientSetting(std::string key, std::string value) { client_settings_[std::move(key)] = std::move(value); return *this; } /** * Sets the root directory for all the cluster's data. If never called, a * temporary directory is created. */ ClusterFactory& setRootPath(std::string path) { root_path_.assign(std::move(path)); return *this; } /** * Use a gossip-based failure detector and spread logs across all sequencer * nodes (based on a hash function). */ ClusterFactory& useHashBasedSequencerAssignment(uint32_t gossip_interval_ms = 100, std::string suspect_duration = "0ms", bool use_health_based_hashing = false) { setParam("--gossip-enabled", ParamScope::ALL); setParam("--gossip-interval", std::to_string(gossip_interval_ms) + "ms", ParamScope::ALL); setParam("--suspect-duration", suspect_duration, ParamScope::ALL); // lazy sequencer bringup setParam("--sequencers", "lazy", ParamScope::SEQUENCER); hash_based_sequencer_assignment_ = true; if (!use_health_based_hashing) { setParam("--enable-health-based-sequencer-placement", "false", ParamScope::ALL); } return *this; } // Modify default HM parameters to avoid false positive detection of stalls or // unhealthy states. In many tests gossip interval is modified to be more // frequent causing delays in HM activation that is then detected and an // unhealthy status of tha node is propagated. Modifying the maximum tolerated // stalled percentages is due to the number of workers on each node being // reduced to a very small number (5). // Health based sequencer hashing is disabled by calling // useHashBasedSequencerAssignment, but in HM related tests its behaviour is // often needed, so this method handles toggling this setting too. ClusterFactory& setHealthMonitorParameters( uint32_t health_monitor_max_delay_ms = 240000, uint32_t watchdog_poll_interval = 50000, double worker_stall_percentage = 1.1, double queue_stall_percentage = 1.1, bool enable_health_based_sequencer_placement = true) { setParam("--health-monitor-max-delay", std::to_string(health_monitor_max_delay_ms) + "ms", ParamScope::ALL); setParam("--watchdog-poll-interval", std::to_string(watchdog_poll_interval) + "ms"); setParam("--health-monitor-max-stalled-worker-percentage", std::to_string(worker_stall_percentage), ParamScope::ALL); setParam("--health-monitor-max-overloaded-worker-percentage", std::to_string(queue_stall_percentage), ParamScope::ALL); setParam("--enable-health-based-sequencer-placement", std::to_string(enable_health_based_sequencer_placement), ParamScope::ALL); return *this; } ClusterFactory& enableSelfInitiatedRebuilding(std::string grace_period = "") { if (!grace_period.empty()) { setParam("--self-initiated-rebuilding-grace-period", grace_period); } return setParam("--enable-self-initiated-rebuilding", "true") .setParam("--disable-rebuilding", "false"); } /** */ ClusterFactory& enableMessageErrorInjection(); /** */ ClusterFactory& enableMessageErrorInjection(double chance, Status st) { setParam("--msg-error-injection-chance", std::to_string(chance), ParamScope::ALL); setParam("--msg-error-injection-status", error_name(st), ParamScope::ALL); if (chance != 0) { ld_info("Enabling message error injection with chance %.2f%% " "and status %s", chance, error_name(st)); } return *this; } /** * Sets the path to the server binary (relative to the build root) to use if * a custom one is needed. */ ClusterFactory& setServerBinary(std::string path) { server_binary_ = path; return *this; } /** * Sets the path to the admin server binary (relative to the build root) to * use if a custom one is needed. */ ClusterFactory& setAdminServerBinary(std::string path) { admin_server_binary_ = path; return *this; } /** * By default, the cluster will use a traffic shaping configuration which is * designed for coverage of the traffic shaping logic in tests, but limits * throughput. This method allows traffic shaping to be turned off in cases * where performance matters. */ ClusterFactory& useDefaultTrafficShapingConfig(bool use) { use_default_traffic_shaping_config_ = use; return *this; } /** * This will be passed to logdeviced as --loglevel option. More precisely, * --loglevel will be set to the first item on this list that's defined: * 1. "--loglevel" value set with setParam(), * 2. value passed to setLogLevel(), * 3. LOGDEVICE_LOG_LEVEL environment variable, * 4. "info". */ ClusterFactory& setLogLevel(dbg::Level log_level) { default_log_level_ = log_level; return *this; } /** * Value of the cluster_name property in config. * Affects how stats are exported. */ ClusterFactory& setClusterName(std::string name) { cluster_name_ = name; return *this; } ClusterFactory& setLogGroupName(const std::string& name) { log_group_name_ = name; return *this; } /** * Generates a default log attribute (replication, extras) based on the * cluster size. This is used internally if setLogAttributes() is not called. * Exposed so that the logic can be reused. */ static logsconfig::LogAttributes createDefaultLogAttributes(int nstorage_nodes); private: folly::Optional<logsconfig::LogAttributes> log_attributes_; std::shared_ptr<const NodesConfiguration> nodes_config_; folly::Optional<Configuration::MetaDataLogsConfig> meta_config_; bool enable_logsconfig_manager_ = false; configuration::InternalLogs internal_logs_; ParamMaps cmd_param_; ServerConfig::SettingsConfig server_settings_; ServerConfig::SettingsConfig client_settings_; // If set to true, allocate tcp ports to be used by the tests for the nodes' // protocol and command ports instead of unix domain sockets. bool use_tcp_ = false; // How many times to try the entire process of starting up the cluster (pick // ports, start servers, wait for them to start). Only applies when // `use_tcp_' is true as we don't expect flaky startup with Unix domain // sockets. int outer_tries_ = 5; int outerTries() const { return use_tcp_ ? outer_tries_ : 1; } // Provision the inital epoch metadata in epoch store and storage nodes // that store metadata bool provision_epoch_metadata_ = false; // Controls whether the cluster should also update the NodesConfiguration // whenver the ServerConfig change. This is there only during the migration // period. bool sync_server_config_to_nodes_configuration_ = true; // Whether to let sequencers provision metadata bool let_sequencers_provision_metadata_ = true; // Allow pre-existing metadata when provisioning bool allow_existing_metadata_ = false; // Don't set SSL addresses on nodes bool no_ssl_address_ = false; // @see useDefaultTrafficShapingConfig() bool use_default_traffic_shaping_config_{true}; // Defines how we should provision the event log. EventLogMode event_log_mode_{EventLogMode::DELTA_LOG_ONLY}; // nodeset selector used for provisioning epoch metadata std::shared_ptr<NodeSetSelector> provision_nodeset_selector_; // Don't start all nodes when Cluster is created bool defer_start_ = false; // How many logs in the config int num_logs_ = 2; int num_logs_config_manager_logs_ = 0; // Number of shards for each storage node int num_db_shards_ = 2; // Number of racks to spread the nodes amongst. int num_racks_ = 1; // See setInternalLogsReplicationFactor(). int internal_logs_replication_factor_ = -1; // If set to true, logs are assumed to be spread across all sequencer nodes. // Otherwise, all appends are sent to the first node in the cluster. bool hash_based_sequencer_assignment_{false}; // if unset, use a random choice between the two sources folly::Optional<NodesConfigurationSourceOfTruth> nodes_configuration_sot_; // Whether to start the standalone admin server or not. bool use_standalone_admin_server_ = false; // Type of rocksdb local log store RocksDBType rocksdb_type_ = RocksDBType::PARTITIONED; // Root path for all data if setRootPath() was called folly::Optional<std::string> root_path_; // Server binary if setServerBinary() was called folly::Optional<std::string> server_binary_; // Server binary if setAdminServerBinary() was called folly::Optional<std::string> admin_server_binary_; std::string cluster_name_ = "integration_test"; std::string log_group_name_ = "/ns/test_logs"; // See setLogLevel(). dbg::Level default_log_level_ = getLogLevelFromEnv().value_or(dbg::Level::INFO); // Helper method, one attempt in create(), repeated up to outer_tries_ times std::unique_ptr<Cluster> createOneTry(const Configuration& config); static logsconfig::LogAttributes createLogAttributesStub(int nstorage_nodes); /** * Figures out the full path to the server binary, considering in order of * precedence: * * - the environment variable LOGDEVICE_TEST_BINARY, * - setServerBinary() override * - a default path */ std::string actualServerBinary() const; /** * Figures out the full path to the server binary, considering in order of * precedence: * * - the environment variable LOGDEVICE_ADMIN_SERVER_BINARY, * - setAdminServerBinary() override * - a default path */ std::string actualAdminServerBinary() const; // Set the attributes of an internal log. void setInternalLogAttributes(const std::string& name, logsconfig::LogAttributes attrs); /** * Uses either the provided log_config_ or creates a new default one to * create a new logs config manager based log group. It requires that the * cluster is up and running. */ std::unique_ptr<client::LogGroup> createLogsConfigManagerLogs(std::unique_ptr<Cluster>& cluster); void populateDefaultServerSettings(); std::shared_ptr<const NodesConfiguration> provisionNodesConfiguration(int nnodes) const; }; // All ports logdeviced can listen on. struct ServerAddresses { static constexpr size_t COUNT = 11; Sockaddr protocol; Sockaddr gossip; Sockaddr admin; Sockaddr server_to_server; Sockaddr protocol_ssl; Sockaddr server_thrift_api; Sockaddr client_thrift_api; Sockaddr data_low_priority; Sockaddr data_medium_priority; // If we're holding open sockets on the above ports, this list contains the // fd-s of these sockets. This list is cleared (and sockets closed) just // before starting the server process. std::vector<detail::PortOwner> owners; void toNodeConfig(configuration::nodes::NodeServiceDiscovery& node, bool ssl) { using Priority = configuration::nodes::NodeServiceDiscovery::ClientNetworkPriority; node.default_client_data_address = protocol; node.gossip_address = gossip; if (ssl) { node.ssl_address.assign(protocol_ssl); } node.admin_address.assign(admin); node.server_to_server_address.assign(server_to_server); node.server_thrift_api_address.assign(server_thrift_api); node.client_thrift_api_address.assign(client_thrift_api); node.addresses_per_priority = {{Priority::LOW, data_low_priority}, {Priority::MEDIUM, data_medium_priority}}; } static ServerAddresses withTCPPorts(std::vector<detail::PortOwner> ports) { std::string addr = get_localhost_address_str(); ServerAddresses r; r.protocol = Sockaddr(addr, ports[0].port); r.gossip = Sockaddr(addr, ports[2].port); r.admin = Sockaddr(addr, ports[3].port); r.protocol_ssl = Sockaddr(addr, ports[4].port); r.server_to_server = Sockaddr(addr, ports[6].port); r.server_thrift_api = Sockaddr(addr, ports[7].port); r.client_thrift_api = Sockaddr(addr, ports[8].port); r.data_low_priority = Sockaddr(addr, ports[9].port); r.data_medium_priority = Sockaddr(addr, ports[10].port); r.owners = std::move(ports); return r; } static ServerAddresses withUnixSockets(const std::string& path) { ServerAddresses r; r.protocol = Sockaddr(path + "/socket_main"); r.gossip = Sockaddr(path + "/socket_gossip"); r.admin = Sockaddr(path + "/socket_admin"); r.server_to_server = Sockaddr(path + "/socket_server_to_server"); r.protocol_ssl = Sockaddr(path + "/ssl_socket_main"); r.server_thrift_api = Sockaddr(path + "/server_thrift_api"); r.client_thrift_api = Sockaddr(path + "/client_thrift_api"); r.data_low_priority = Sockaddr(path + "/socket_data_low_pri"); r.data_medium_priority = Sockaddr(path + "/socket_data_medium_pri"); return r; } }; /** * RAII-style container for a LogDevice cluster running on localhost. */ class Cluster { public: using Nodes = std::map<node_index_t, std::unique_ptr<Node>>; ~Cluster(); /** * Used in conjunction with ClusterFactory::deferStart() to run a process for * each node in the cluster. Waits for all nodes to start. * * @param indices if non-empty, only a specified subset of nodes will be * started * * @return 0 on success, -1 if any of the nodes fails to start */ int start(std::vector<node_index_t> indices = {}); /** * Kill all running nodes in the cluster. */ void stop(); /** * DEPRECATED, Will be removed and replaced by the implementation of * expandViaAdminServer in the future. * * Expand the cluster by adding nodes with the given indices. * @return 0 on success, -1 on error. */ int expand(std::vector<node_index_t> new_indices, bool start = true); /** * Expand the cluster by adding `nnodes` with consecutive indices after the * highest existing one. * * The newly added nodes will be distributed among the configured number * of racks in this cluster. * @return 0 on success, -1 on error. */ int expand(int nnodes, bool start = true); /** * Expand the cluster by adding nodes with the given indices. * @return 0 on success, -1 on error. */ int expandViaAdminServer(thrift::AdminAPIAsyncClient& admin_client, std::vector<node_index_t> new_indices, bool start = true, int num_racks = 1); /** * Expand the cluster by adding `nnodes` with consecutive indices after the * highest existing one. * @return 0 on success, -1 on error. */ int expandViaAdminServer(thrift::AdminAPIAsyncClient& admin_client, int nnodes, bool start_nodes = true, int num_racks = 1); /** * Shrink the cluster by removing the given nodes. * @return 0 on success, -1 on error. * * Note that this doesn't do rebuilding. If shrink out nodes that have * some records (including metadata/internal logs), you'll likely see data * loss or underreplication. */ int shrink(std::vector<node_index_t> indices); /** * Shrink the cluster by removing `nnodes` last nodes. * @return 0 on success, -1 on error. */ int shrink(int nnodes); /** * Shrink the cluster by removing nodes with the given indices. * @return 0 on success, -1 on error. */ int shrinkViaAdminServer(thrift::AdminAPIAsyncClient& admin_client, std::vector<node_index_t> new_indices); /** * Shrink the cluster by removing `nnodes` last nodes. * * Note that these nodes must already be fully disabled/drained and stopped. * @return 0 on success, -1 on error. */ int shrinkViaAdminServer(thrift::AdminAPIAsyncClient& admin_client, int nnodes); std::shared_ptr<UpdateableConfig> getConfig() const { return config_; } std::string getConfigPath() const { return config_path_; } std::string getNCSPath() const { return ncs_path_; } /** * This creates a client by calling ClientFactory::create() that does not * share the loaded config_. * * If use_file_based_ncs is set to true, the client will use * FileBasedNodesConfigurationStore to fetch and update the * NodesConfiguration instead of the server based one. Use this *only* if you * want to create a client without estabilishing any connection to the nodes * to fetch the Nodes Config (e.g. when all the nodes are dead). */ std::shared_ptr<Client> createClient(std::chrono::milliseconds timeout = getDefaultTestTimeout(), std::unique_ptr<ClientSettings> settings = std::unique_ptr<ClientSettings>(), std::string credentials = "", bool use_file_based_ncs = false); const Nodes& getNodes() const { return nodes_; } /** * Returns the admin server instance if started. */ AdminServer* FOLLY_NULLABLE getAdminServer() { return admin_server_.get(); } Node& getNode(node_index_t index) { ld_assert(nodes_.count(index)); ld_check(nodes_[index] != nullptr); return *nodes_.at(index); } Node& getSequencerNode() { ld_check(!hash_based_sequencer_assignment_); // For now, the first node is always the sequencer return getNode(0); } // Returns the list of non-stopped storage nodes. std::vector<node_index_t> getRunningStorageNodes() const; // When using hash-based sequencer assignment, the above is not sufficient. // Hash-based sequencer assignment is necessary to have failover. // Returns -1 if there is no sequencer for the log or it is unavailable. int getHashAssignedSequencerNodeId(logid_t log_id, Client* client); // Call function for every node. Function signature is F(Node&). // By default processes each node in its own thread. // Set use_threads = false to do everything in the calling thread. template <typename F> void applyToNodes(F func, bool use_threads = true) { NodeSetIndices nodes; for (auto& node : nodes_) { nodes.push_back(node.first); } applyToNodes(nodes, func, use_threads); } template <typename F> void applyToNodes(const NodeSetIndices& nodeset, F func, bool use_threads = true) { if (use_threads) { std::vector<std::thread> ts; for (node_index_t nidx : nodeset) { ts.emplace_back([this, func, nidx] { func(getNode(nidx)); }); } for (auto& t : ts) { t.join(); } } else { for (node_index_t nidx : nodeset) { func(getNode(nidx)); } } } /** * Returns an EpochStore object representing the store that a sequencer node * will use. Intended to be used with ClusterFactory::deferStart() to set * initial epochs for logs before starting nodes. */ std::unique_ptr<EpochStore> createEpochStore(); /** * Updates epoch store to set the next epoch for log_id */ void setStartingEpoch(logid_t log_id, epoch_t epoch, epoch_t last_expected_epoch = EPOCH_INVALID); /** * Provision the initial epoch metadata on metadata storage nodes, * must be called when the storage nodes are not started * * @param selector nodeset selector for provisioning, if not * given, SELECT_ALL is used * @param allow_existing_metadata whether provisioning will succeed if a log * is already provisioned. If this is false, * it will fail with E::EXISTS. * @return 0 for success, -1 for failure */ int provisionEpochMetaData( std::shared_ptr<NodeSetSelector> selector = nullptr, bool allow_existing_metadata = false); /** * Like `provisionEpochMetaData`, but asks for an specific set of shard * indices to be used. Also needs to be called when storage nodes are not * started. * * @param shard_indices set of shard indices to use. * @allow_existing_metadata see `provisionEpochMetaData` */ int provisionEpochMetadataWithShardIDs(std::set<node_index_t> node_indices, bool allow_existing_metadata = true); /** * Updates the NC on disk via FileBasedNodesConfigurationStore. * @param nodes_config the NC to write * @return 0 for success, -1 for failure */ int updateNodesConfiguration( const configuration::nodes::NodesConfiguration& nodes_config); /** * Replaces the node at the specified index. Kills the current process if * still running, deletes the node's data, then starts up a new one and * updates the cluster config. * * @return 0 on success, -1 if node fails to start or there are no free ports */ int replace(node_index_t index, bool defer_start = false); /** * Replaces the node at the specified index. Kills the current process if * still running, deletes the node's data, then starts up a new one and * updates the cluster config using the Admin API. * * @return 0 on success, -1 if node fails to start or there are no free ports */ int replaceViaAdminServer(thrift::AdminAPIAsyncClient& admin_client, node_index_t index, bool defer_start = false); /** * Bumps up the generation using the Admin API. */ int bumpGeneration(thrift::AdminAPIAsyncClient& admin_client, node_index_t index); /** * Update node's attributes in config */ int updateNodeAttributes( node_index_t index, configuration::StorageState storage_state, int sequencer_weight, folly::Optional<bool> enable_sequencing = folly::none); // A guide to the few wait*() methods below: // - When using static sequencer placement (default), // waitUntilAllSequencersQuiescent() guarantees that subsequent appends // won't fail without a good reason and that sequencers won't reactivate // without a good reason. // - When using hash-based sequencer placement // (useHashBasedSequencerAssignment()), // waitUntilAllStartedAndPropagatedInGossip() guarantees that subsequent // appends won't fail to activate sequencer without a good reason. // If you want to wait for the newly activated sequencer to finish // recovery, metadata log write, unnecessary reactivation, etc, then you // can also call waitUntilAllSequencersQuiescent() after the append that // activated the sequencer. // - waitForConfigUpdate() is for after you updated the config file // (e.g. using writeConfig()). // - Most of the other wait methods are either obsolete or only useful for // particular test cases that want something very specific. // Many call sites are using them inappropriately (e.g. waitForRecovery() // instead of waitUntilAllSequencersQuiescent(), or waitUntilAllAvailable() // instead of waitUntilAllStartedAndPropagatedInGossip()); feel free to fix // those when they make tests flaky; I didn't dare mass-replace them. /** * Wait for all nodes to complete all sequencer activation-related activity: * activation, recoveries, metadata log writes, metadata log recoveries, * reactivations caused by metadata log writes, nodeset updates caused by * config changes, etc. If you're not making any changes to the cluster * (starting/stopping nodes, updating config/settings, etc), after this call * sequencers are not going to reactivate, get stuck in recovery (even if * there's no f-majority of available nodes), or do other unexpected things. * You'll get consecutive LSNs for appends. * * Note that this only applies to sequencers that have already at least * started activation as of the time of this call. If static sequencer * placement is used (i.e. useHashBasedSequencerAssignment() wasn't called), * that's all sequencers; otherwise, that's typically only sequencers for the * logs that received at least one append. Also note that, even though appends * done after this call should all go to the same epoch and get consecutive * LSNs, this may be a higher epoch than for appends done before the call. */ int waitUntilAllSequencersQuiescent( std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Wait until the given nodes see each other and themselves as alive and * started in gossip, and see everyone else as dead. * For a freshly started cluster, until this wait is done, appends may fail * with E::ISOLATED if sequencer node happens to see itself as alive but * others as dead. * * @param nodes The set of nodes that should be alive. If folly::none, all * running nodes (i.e. with Node::stopped_ == false). */ int waitUntilAllStartedAndPropagatedInGossip( folly::Optional<std::set<node_index_t>> nodes = folly::none, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits until all live nodes and clients have processed the * NodesConfiguration with at least the version passed. */ void waitForServersAndClientsToProcessNodesConfiguration( membership::MembershipVersion::Type version); /** * Waits until all live nodes have a view of the config same as getConfig(). * This doesn't guarantees much about server behavior because the * config update takes some time to propagate inside the server process, * e.g. to all workers; this method does *not* wait for such propagation. * * This it not reliable for most purposes. * If you rely on it your test will probably be flaky. */ void waitForServersToPartiallyProcessConfigUpdate(); /** * Wait for all sequencer nodes in the cluster to finish log recovery. * Caller needs to ensure recovery should happen on sequencer nodes. * * Warning: currently the implementation is not fully correct and, when using * hash-based sequencer placement, may incorrectly get stuck in rare cases * if sequencers preempt each other in a somewhat unusual sequence. To avoid * flakiness, prefer either waitUntilAllSequencersQuiescent() * or waiting for recovery of a specific log on a specific node. * * @return 0 if recovery is completed, -1 if the call timed out. */ int waitForRecovery(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); // Waits until all nodes are available through gossip (ALIVE) int waitUntilAllAvailable(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); // Waits until all nodes are healthy through gossip (HEALTHY) int waitUntilAllHealthy(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Wait for all sequencer nodes in the cluster to write metadata log records * for all logs. This shouldn't block if sequencers_write_metadata_logs is * `false` in the metadata logs config. * @return 0 if all metadata logs were written, -1 if the call timed out. */ int waitForMetaDataLogWrites( std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Wait for all nodes in the cluster except the ones specified in the skip * list to see the specified node in a DEAD/ALIVE state (depending on what is * submitted as the `alive` arg */ int waitUntilGossip(bool alive, /* set to false for waiting for dead */ uint64_t targetNode, std::set<uint64_t> nodesToSkip = {}, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Wait for all nodes in the cluster except the ones specified in the skip * list to see the specified node in a certain health status (depending on * what is submitted as the `health_status` arg */ int waitUntilGossipStatus( uint8_t health_status, /* set to 3 for waiting for unhealthy */ uint64_t targetNode, std::set<uint64_t> nodesToSkip = {}, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits until nodes specified in the parameter `nodes` are alive and fully * started (i.e. not in starting state) according to gossip. If `nodes` is * folly::none, all nodes in the cluster will be checked. */ int waitUntilNoOneIsInStartupState( folly::Optional<std::set<uint64_t>> nodes = folly::none, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); int waitUntilAllClientsPickedConfig(const std::string& serialized_config); /** * Same as ClusterFactory::setParam(). Only affects future logdeviced * instances, like the ones created by replace(). */ void setParam(std::string key, ParamScope scope = ParamScope::ALL) { ld_check(!key.empty()); cmd_param_[scope][key] = ParamValue(); } void setParam(std::string key, std::string value, ParamScope scope = ParamScope::ALL) { ld_check(!key.empty()); cmd_param_[scope][key] = value; } /** * Undoes what setParam() did. */ void unsetParam(std::string key, ParamScope scope = ParamScope::ALL) { ld_check(!key.empty()); cmd_param_[scope].erase(key); } // Returns true if gossip is enabled in the ALL scope. // This assumes that the default for the --gossip-enabled flag is true. bool isGossipEnabled() const; /** * Check that all the data in the cluster is correctly replicated. * * @return 0 if all the data is correctly replicated, -1 otherwise. */ using argv_t = std::vector<std::string>; int checkConsistency(argv_t additional_args = argv_t()); /** * Convenience function that creates a MetaDataProvisioner object for * provisioning epoch metadata for logs on the cluster. * User of the provisioner object must ensure that the object will not * outlive the Cluster object. */ std::unique_ptr<MetaDataProvisioner> createMetaDataProvisioner(); /** * Read the event log of the cluster and build a ShardAuthoritativeStatusMap. * @param map Filled with the state read from the event log. * @return 0 on success, -1 on failure and err is set to: * - E::NOTFOUND if the cluster has no event log; * - Any error that can be reported by Client::getTailLSNSync() if this * function could not retrieve the tail LSN of the event log; * - Any error that can be reported by Reader::startReading() if this * function cannot start reading the event log. */ int getShardAuthoritativeStatusMap(ShardAuthoritativeStatusMap& map); /** * Do Node::waitUntilRSMSynced() on all nodes in @param nodes. * If `nodes` is empty, all nodes. */ int waitUntilRSMSynced(const char* rsm, lsn_t sync_lsn, std::vector<node_index_t> nodes = {}, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); int waitUntilEventLogSynced( lsn_t sync_lsn, const std::vector<node_index_t>& nodes = {}, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()) { return waitUntilRSMSynced("event_log", sync_lsn, nodes, deadline); } int waitUntilLogsConfigSynced( lsn_t sync_lsn, const std::vector<node_index_t>& nodes = {}, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()) { return waitUntilRSMSynced("logsconfig_rsm", sync_lsn, nodes, deadline); } /** * Partitions cluster by overwriting individual node's config with invalid * address for each node belonging to a different partition. Note that, upon * receiving the config update, each node is going to close exsiting * connections to nodes outside of their partition. */ void partition(std::vector<std::set<int>> partitions); /** * Requires maintenance manager to be enabled. * This will create an internal maintenance to drain a shard. The created * maintenance will be applied via writing directly to the internal * maintenance log. This might change in the future so the caller should not * rely on this implementation detail. * * Internal maintenances will trigger rebuilding in RESTORE mode. * * @return true if the operation succeeded. On * `false` the value of `err` is set accordingly. */ bool applyInternalMaintenance(Client& client, node_index_t node_id, uint32_t shard_idx, const std::string& reason); /** * A quick helper that applies a maintenance (drain by default) to a given * shard. * * Note: this skips safety checks (creates IMMINENT maintenance) * * @return the created maintenance ID */ std::string applyMaintenance(thrift::AdminAPIAsyncClient& admin_client, node_index_t node_id, uint32_t shard_idx, const std::string& user = "integration_test", bool drain = true, bool force_restore = false, const std::string& reason = "testing", bool disable_sequencer = false); /** * Gracefully shut down the given nodes. Faster than calling shutdown() on * them one by one. * @return 0 if all processes returned zero exit status, -1 otherwise. */ int shutdownNodes(const std::vector<node_index_t>& nodes); /** * Overwrites config file. If wait_for_update is true, waits for config_ to * pick up the update. * Note that if the update is going to be rejected, e.g. because the version * is smaller than current, wait_for_update would make this method wait * forever. * * Use waitForServersToPartiallyProcessConfigUpdate() to wait for nodes to * pick up the update. */ int writeConfig(const ServerConfig* server_cfg, const LogsConfig* logs_cfg, bool wait_for_update = true); int writeConfig(const Configuration& cfg, bool wait_for_update = true); // Convenience wrappers int writeServerConfig(const ServerConfig* server_cfg) { return writeConfig(server_cfg, getConfig()->getLogsConfig().get()); } int writeLogsConfig(const LogsConfig* logs_cfg) { return writeConfig(getConfig()->getServerConfig().get(), logs_cfg); } // see node_replacement_counters_ below node_gen_t getNodeReplacementCounter(node_index_t node) const { return node_replacement_counters_.count(node) > 0 ? node_replacement_counters_.at(node) : 1; } void setNodeReplacementCounter(node_index_t node, node_gen_t rc) { node_replacement_counters_[node] = rc; } void bumpNodeReplacementCounter(node_index_t node) { ++node_replacement_counters_[node]; } void setNodeReplacementCounters(std::map<node_index_t, node_gen_t> counters) { node_replacement_counters_ = std::move(counters); } NodesConfigurationSourceOfTruth getNodesConfigurationSourceOfTruth() const { return nodes_configuration_sot_; } // require @param node must exist in the cluster bool hasStorageRole(node_index_t node) const; // Send admin command `set` to all nodes. void updateSetting(const std::string& name, const std::string& value); void unsetSetting(const std::string& name); // Build a NodesConfigurationStore to modify the NodesConfiguration directly. std::unique_ptr<configuration::nodes::NodesConfigurationStore> buildNodesConfigurationStore() const; // Reads the nodes configuration from the cluster's NodesConfigurationStore. std::shared_ptr<const NodesConfiguration> readNodesConfigurationFromStore() const; // Create a self registering node with a given name. Does not start the // process. std::unique_ptr<Node> createSelfRegisteringNode(const std::string& name) const; private: // Private constructor. Factory (friend class) is only caller. Cluster(std::string root_path, std::unique_ptr<TemporaryDirectory> root_pin, std::string config_path, std::string epoch_store_path, std::string ncs_path, std::string server_binary, std::string admin_server_binary, std::string cluster_name, bool enable_logsconfig_manager, dbg::Level default_log_level, NodesConfigurationSourceOfTruth nodes_configuration_sot); // Directory where to store the data for a node (logs, db, sockets). static std::string getNodeDataPath(const std::string& root, node_index_t index, int replacement_counter) { return getNodeDataPath(root, "N" + std::to_string(index) + ':' + std::to_string(replacement_counter)); } // Directory where to store the data for a node (logs, db, sockets) given the // directory name of the node. static std::string getNodeDataPath(const std::string& root, const std::string& name) { return root + "/" + name; } std::string getNodeDataPath(const std::string& root, node_index_t index) const { return getNodeDataPath(root, index, getNodeReplacementCounter(index)); } // Forms Sockaddr-s for the node. If use_tcp is true, picks and reserves // the ports. Otherwise forms paths for unix fomain sockets. static int pickAddressesForServers( const std::vector<node_index_t>& indices, bool use_tcp, const std::string& root_path, const std::map<node_index_t, node_gen_t>& node_replacement_counters, std::vector<ServerAddresses>& out); // Creates a Node instance for the specified config entry and starts the // process. Does not wait for process to start; call // node->waitUntilStarted() for that. std::unique_ptr<Node> createNode(node_index_t index, ServerAddresses addrs) const; // Helper for createNode(). Figures out the initial command line args for the // specified node ParamMap commandArgsForNode(const Node& node) const; // Creates an admin server instance for this cluster. This does not wait for // the process to start. std::unique_ptr<AdminServer> createAdminServer(); // Helper for createClient() to populate client // settings. void populateClientSettings(std::unique_ptr<ClientSettings>& settings, bool use_file_based_ncs) const; // We keep track whether the cluster was created using tcp ports or unix // domain sockets so that we can use the same method for new nodes created by // the expand() method. bool use_tcp_{false}; // How many times to try starting a server int outer_tries_ = 2; std::string root_path_; // If root_path_ is a temporary directory, this owns it std::unique_ptr<TemporaryDirectory> root_pin_; std::string config_path_; std::string epoch_store_path_; // path for the file-based nodes configuration store std::string ncs_path_; std::string server_binary_; std::string admin_server_binary_; std::string cluster_name_; bool enable_logsconfig_manager_ = false; const NodesConfigurationSourceOfTruth nodes_configuration_sot_; std::shared_ptr<UpdateableConfig> config_; FileConfigSource* config_source_; std::unique_ptr<ClientSettings> client_settings_; std::unique_ptr<NodesConfigurationFileUpdater> nodes_configuration_updater_; // ordered map for convenience Nodes nodes_; // The admin server object if standalone admin server is enabled. std::unique_ptr<AdminServer> admin_server_; // keep track of node replacement events. for nodes with storage role, the // counter should be in sync with the `generation' in its config. For nodes // without storage role, counter is only used for tracking/directory keeping // purpose but not reflected in the config std::map<node_index_t, node_gen_t> node_replacement_counters_; // command line parameters, set by the Factory ParamMaps cmd_param_; int num_db_shards_ = 4; // type of rocksdb local log store RocksDBType rocksdb_type_ = RocksDBType::PARTITIONED; // See ClusterFactory::hash_based_sequencer_assignment_ bool hash_based_sequencer_assignment_{false}; dbg::Level default_log_level_ = dbg::Level::INFO; // Controls whether the cluster should also update the NodesConfiguration // whenver the ServerConfig change. This is there only during the migration // period. bool sync_server_config_to_nodes_configuration_{false}; bool no_ssl_address_{false}; // keep handles around until the cluster is destroyed. std::vector<UpdateableServerConfig::HookHandle> server_config_hook_handles_; // A vector of all the clients that are created for this cluster. std::vector<std::weak_ptr<Client>> created_clients_; friend class ClusterFactory; }; /** * RAII-style container for a LogDevice server that is part of a Cluster. */ class Node { public: std::unique_ptr<folly::Subprocess> logdeviced_; std::string data_path_; std::string config_path_; std::string server_binary_; std::string name_; node_index_t node_index_; ServerAddresses addrs_; int num_db_shards_ = 4; // how many shards storage nodes will use // Random ID generated by constructor. Passed on the command line to the // server. waitUntilStarted() looks for this to verify that we are talking // to the right process. std::string server_id_; // Stopped until start() is called, as well as between suspend() and resume(), // or shutdown() and start(). bool stopped_ = true; bool gossip_enabled_ = true; // type of rocksdb local log store RocksDBType rocksdb_type_ = RocksDBType::PARTITIONED; // override cluster params for this particular node ParamMap cmd_args_; bool is_storage_node_ = true; bool is_sequencer_node_ = true; Node(); ~Node() { kill(); } /** * Creates a local log store instance for this node. Can be used with * ClusterFactory::deferStart() to prepopulate the store before logdeviced * is started, or to inspect the store after the node is stopped. */ std::unique_ptr<ShardedLocalLogStore> createLocalLogStore(); // Corrupts rocksdb DBs for given shards. rocksdb::DB::Open() will fail with // "Corruption" status. // If you've already called createLocalLogStore(), you can pass the result // here as `store` parameter, as an optimization to avoid opening DB again; // this method will close it. void corruptShards(std::vector<uint32_t> shards, std::unique_ptr<ShardedLocalLogStore> sharded_store = nullptr); void updateSetting(std::string name, std::string value); void unsetSetting(std::string name); std::string getDatabasePath() const { return data_path_ + "/db"; } std::string getShardPath(shard_index_t idx) const { return getDatabasePath() + "/shard" + std::to_string(idx); } std::string getLogPath() const { return data_path_ + "/log"; } void signal(int sig) { logdeviced_->sendSignal(sig); } /** * @return true if logdeviced is running. */ bool isRunning() const; void kill(); /** * Wipe the content of a shard on this node. */ void wipeShard(uint32_t shard); /** * Pauses logdeviced by sending SIGSTOP. Waits for the process to stop * accepting connections. */ void suspend(); /** * Resume logdeviced by sending SIGCONT. Waits for the process to start * accepting connections again. */ void resume(); /** * Starts logdeviced if not started already (without waiting for it to become * ready). */ void start(); /** * Restart server process and wait for it to be available if requested */ void restart(bool graceful = true, bool wait_until_available = true); /** * Performs a graceful shutdown of logdeviced by issuing a "stop" admin * command. * * @return logdeviced exit code. */ int shutdown(); // Creates a thrift client for admin server running on this node. std::unique_ptr<thrift::AdminAPIAsyncClient> createAdminClient() const; /** * Waits until the admin API is able to answer requests that need the event * log. This also ensures that we are in the fb303 ALIVE state before * returning. * * Note: this requires that the server is started with * --disable-rebuilding=false */ int waitUntilNodeStateReady(); /** * Waits for the server to start accepting connections. * @return 0 if started, -1 if the call timed out. */ int waitUntilStarted(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits for the server using a gossip-based failure detector to mark itself * as available (i.e. ready to process appends). * @return 0 if available, -1 if the call timed out. */ int waitUntilAvailable(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); void waitUntilKnownDead(node_index_t other_node_index); int waitUntilHealthy(std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits for the server using a gossip-based failure detector to mark another * node as alive (if `alive` is set to `true`) or dead. * * @return 0 if succeeded, -1 if timed out while waiting */ int waitUntilKnownGossipState( node_index_t other_node_index, bool alive, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits for the server using a gossip-based failure detector to mark another * node as having a certain health status. * * @return 0 if succeeded, -1 if timed out while waiting */ int waitUntilKnownGossipStatus( node_index_t other_node_index, uint8_t health_status, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits for the node to activate a sequencer for this log and finish * recovery. */ int waitForRecovery(logid_t log, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * See Cluster::waitUntilAllSequencersQuiescent(). */ int waitUntilAllSequencersQuiescent( std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Waits for the node to advance its LCE of @param log to be at least * @param epoch. */ int waitForPurge(logid_t log, epoch_t epoch, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Wait until the node have read the event log or config log * up to @param sync_lsn and propagated it to all workers. * @param rsm is either "event_log" or "logsconfig_rsm". It gets translated * into admin command "info <rsm> --json", which we poll until the value in * column "Propagated read ptr" becomes >= sync_lsn. * * Note that in case of event_log the propagation is delayed * by --event-log-grace-period, so if you're using this method you probably * want to decrease --event-log-grace-period. In case of logsconfig_rsm, * the delay is --logsconfig-manager-grace-period. */ int waitUntilRSMSynced(const char* rsm, lsn_t sync_lsn, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Shorthand for waitUntilRSMSynced("event_log"/"logsconfig_rsm", ...). */ int waitUntilEventLogSynced( lsn_t sync_lsn, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()) { return waitUntilRSMSynced("event_log", sync_lsn, deadline); } int waitUntilLogsConfigSynced( lsn_t sync_lsn, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()) { return waitUntilRSMSynced("logsconfig_rsm", sync_lsn, deadline); } /** * Wait until all shards of this node are fully authoritative in event log. * Returns the lsn of the last update. * Does NOT wait for this information to propagate to the node itself; * use waitUntilEventLogSynced() for that. */ lsn_t waitUntilAllShardsFullyAuthoritative(std::shared_ptr<Client> client); /** * Wait until all shards of this node are authoritative empty. * Returns the lsn of the last update. * Does NOT wait for this information to propagate to the node itself; * use waitUntilEventLogSynced() for that. */ lsn_t waitUntilAllShardsAuthoritativeEmpty(std::shared_ptr<Client> client); /** * Waits until all internal maintenances are removed for this particular * node. */ bool waitUntilInternalMaintenances( thrift::AdminAPIAsyncClient& admin_client, folly::Function<bool(const std::vector<thrift::MaintenanceDefinition>&)> predicate, const std::string& reason, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); bool waitUntilShardState( thrift::AdminAPIAsyncClient& admin_client, shard_index_t shard, folly::Function<bool(const thrift::ShardState&)> predicate, const std::string& reason, std::chrono::steady_clock::time_point deadline = std::chrono::steady_clock::time_point::max()); /** * Sends admin command `command' to command port and returns the result. */ std::string sendCommand(const std::string& command, std::chrono::milliseconds command_timeout = std::chrono::milliseconds(30000)) const; /** * Does sendCommand() and parses the output as a json table. * If we failed to send the command, or the result is empty, or the result * looks like an error, returns empty vector. If result looks like neither * json nor error message, crashes. */ std::vector<std::map<std::string, std::string>> sendJsonCommand(const std::string& command) const; /** * Returns the admin API address for this node */ folly::SocketAddress getAdminAddress() const; /** * Connects to the admin ports and returns the running server information */ folly::Optional<test::ServerInfo> getServerInfo(std::chrono::milliseconds command_timeout = std::chrono::milliseconds(30000)) const; /** * Waits for the logdeviced process to exit. * @return logdeviced return code. */ int waitUntilExited(); /** * Issues a STATS command to the node's command port and collects all stats * into a map. * * May return an empty map if the node is not up or not ready to accept * admin commands. */ std::map<std::string, int64_t> stats() const; /** * Issues a COMPACT command to the node's command port and force a compaction * on the rocksdb locallogstore shard for the given logid. Pass in * LOGID_INVALID (default) as logid will let the node perform compaction * on all rocksdb shards. */ int compact(logid_t logid = LOGID_INVALID) const; /** * Issues a LOGSTORAGESTATE command to the node's command port and collects * the result into a map. * * May return an empty map if the node is not up or not ready to accept * admin commands. */ std::map<std::string, std::string> logState(logid_t log_id) const; /** * Issues a UP DOWN command to activate a sequencer for a given log_id on a * particular node * Returns a rsponse as a string */ std::string upDown(const logid_t log_id) const; /** * Issues an INFO SEQUENCER command to the node's command port and collects * the results in a map. * Returns an empty map if there is no sequencer for the log. */ std::map<std::string, std::string> sequencerInfo(logid_t log_id) const; /** * Issues a GOSSIP BLACKLIST command, and ld_check-s that it succeeds. */ void gossipBlacklist(node_index_t node_id) const; /** * Issues a GOSSIP WHITELIST command, and ld_check-s that it succeeds. */ void gossipWhitelist(node_index_t node_id) const; /** * Issues an INJECT SHARD_FAULT command * @returns false if in non-debug mode, as the command is only supported for * DEBUG builds, true otherwise. */ bool injectShardFault(std::string shard, std::string data_type, std::string io_type, std::string code, bool single_shot = false, folly::Optional<double> chance = folly::none, folly::Optional<uint32_t> latency_ms = folly::none); /** * Issues a NEWCONNECTIONS command, and ld_check-s that it succeeds. */ void newConnections(bool accept) const; /** * Issues a STARTRECOVERY command, and ld_check-s that it succeeds. */ void startRecovery(logid_t logid) const; /** * Issues an INFO LOGSCONFIG_RSM command to the node's command port and * collects the results in a map. Returns an empty map if the node is not * reading the event log. */ std::map<std::string, std::string> logsConfigInfo() const; /** * Issues an INFO EVENT_LOG command to the node's command port and collects * the results in a map. * Returns an empty map if the node is not reading the event log. */ std::map<std::string, std::string> eventLogInfo() const; /** * Issues an INFO SOCKET command to the node's command port and collects * the results in a vector of maps. */ std::vector<std::map<std::string, std::string>> socketInfo() const; /** * Issues an INFO PARTITIONS command to the node's command port and collects * the results in a vector of maps. */ std::vector<std::map<std::string, std::string>> partitionsInfo() const; /** * Issues an INFO GOSSIP command to the node's command port to collect info * about the availability of other nodes. Results are stored in the map, with * keys corresponding to nodes, and values being either "ALIVE" or "DEAD". * Cluster has to be started with the --gossip-enable option. */ std::map<std::string, std::string> gossipInfo() const; /** * Issues an INFO GOSSIP command to the node's command port to collect info * about the health status of other nodes. Results are stored in the map, with * keys corresponding to nodes, and values being "UNDEFINED", "HEALTHY", * "OVERLOADED" or "UNHEALTHY". Cluster has to be started with the * --gossip-enable option. */ std::map<std::string, std::string> gossipStatusInfo() const; /** * Issues an INFO GOSSIP command to collect information about whether the node * is in starting state and display it. */ std::map<std::string, bool> gossipStarting() const; /* * Sends "info gossip" to command port via nc. * Returns a map with one of the following state strings as value * "" : If node is not in config * "DEAD" : If node is DEAD * "SUSPECT" : If node is SUSPECT * "ALIVE" : If node is ALIVE */ std::map<std::string, std::string> gossipState() const; std::map<node_index_t, std::string> getRsmVersions(logid_t rsm_log, RsmVersionType rsm_type) const; std::pair<std::string, std::string> getTrimmableVersion(logid_t rsm_log) const; /* * Sends "info gossip" to command port via nc. * * Returns a map where the value is a pair of status (like gossipInfo() or * gossipState()) and the count of the number of gossip time intervals where * we haven't recevied a message. */ std::map<std::string, std::pair<std::string, uint64_t>> gossipCount() const; /** * Sends "info gossip" to command port via nc. * * Returns a map where the key is the node name and the value is true if the * node is boycotted, false otherwise */ std::map<std::string, bool> gossipBoycottState() const; void resetBoycott(node_index_t node_index) const; /** * Issues an INFO GOSSIP command to the node's command port to collect info * about the isolation status of local domains in all different node location * scopes. Results are stored in the map, with a special key-value pair of * "enabled" : "true"/"false" indicating if domain isolation dection is * enabled, and key-value pairs of "<scope name>" : "ISOLATED"/"NOT_ISOLATED". * Cluster has to be started with the --gossip-enable option. */ std::map<std::string, std::string> domainIsolationInfo() const; /** * Issues an INFO PARTITIONS command to the node's command port to collect * information about the LocalLogStore time partitions active on the given * shard. The 'level' option is passed directly to the command: '0' = terse, * '1' = detailed, '2' = detailed + expensive to collect fields. */ std::vector<std::map<std::string, std::string>> partitionsInfo(shard_index_t shard, int level) const; /** * Issues a INFO SHARD command to the node's command port and compiles * a map of dirty shard to dirty time ranges. */ std::map<shard_index_t, RebuildingRangesMetadata> dirtyShardInfo() const; /** * Issues a INFO SHARD command to the node and returns the "Rebuilding state" * field per shard. */ std::map<shard_index_t, std::string> rebuildingStateInfo() const; // Issues LOGSDB CREATE command. Returns PARTITION_INVALID if it failed. partition_id_t createPartition(uint32_t shard); Node& setParam(std::string key, std::string value) { cmd_args_[key] = value; return *this; } std::vector<std::string> commandLine() const; }; /** * Write to the event log to trigger rebuilding of a shard. * * @param client Client to use to write to event log. * @param node Node for which to rebuild a shard. * @param shard Shard to rebuild. * @param flags Flags to use. * @param rrm Time ranges for requesting time-ranged rebuilding (aka * mini rebuilding) * @return LSN of the event log record or LSN_INVALID on failure. */ lsn_t requestShardRebuilding(Client& client, node_index_t node, uint32_t shard, SHARD_NEEDS_REBUILD_flags_t flags = 0, RebuildingRangesMetadata* rrm = nullptr); /** * Undrain a shard, ie allow the shard to acknowledge rebuilding. * * @param client Client to use to write to event log. * @param node Node for which a shard is undrained. * @param shard Shard that is undrained. * @return LSN of the event log record or LSN_INVALID on failure. */ lsn_t markShardUndrained(Client& client, node_index_t node, uint32_t shard); /** * Mark a shard as unrecoverable in the event log. * * @param client Client to use to write to event log. * @param node Node for which a shard is marked unrecoverable. * @param shard Shard that is marked unrecoverable. * @return LSN of the event log record or LSN_INVALID on failure. */ lsn_t markShardUnrecoverable(Client& client, node_index_t node, uint32_t shard); /** * Wait until some shards have the given state according to the event log. * @param client Client to use for reading the event log. * @param shards Shards for which to check the state. * @param st Expected authoritative status of the shard. * @param wait_for_rebuilding If true, only return if rebuilding has completed * (regardless of if it was authoritative), ie all * donors completed rebuilding. * @return LSN of the last update. Might be more recent than the update that * triggered the state change we're waiting for. */ lsn_t waitUntilShardsHaveEventLogState(std::shared_ptr<Client> client, std::vector<ShardID> shards, std::set<AuthoritativeStatus> st, bool wait_for_rebuilding); lsn_t waitUntilShardsHaveEventLogState(std::shared_ptr<Client> client, std::vector<ShardID> shards, AuthoritativeStatus st, bool wait_for_rebuilding); lsn_t waitUntilShardHasEventLogState(std::shared_ptr<Client> client, ShardID shard, AuthoritativeStatus st, bool wait_for_rebuilding); struct SequencerState { NodeID node; lsn_t last_released_lsn; lsn_t next_lsn; }; /** * Executes a GetSeqStateRequest to find out which node is the sequencer * for the provided log ID. * * @param client Client to use to send messages to the cluster nodes * @param log_id ID of the lod * @param wait_for_recovery Sets eponym option for GetSeqStateRequest * @return Result of the GetSeqStateRequest */ Status getSeqState(Client* client, logid_t log_id, SequencerState& seq_state, bool wait_for_recovery); // Returns the default path for logdeviced std::string defaultLogdevicedPath(); // Returns the default path for ldquery-markdown std::string defaultMarkdownLDQueryPath(); // Attempts to find a binary, given a relative path to search for. Within FB // we just ask the build system for the path. For open source, calls findFile() std::string findBinary(const std::string& relative_path); } // namespace IntegrationTestUtils }} // namespace facebook::logdevice
36.247792
80
0.685824
[ "object", "vector" ]
268f56daa5b6ffb5d2596c2be419b3ae21d89b9a
681
h
C
algorithms/easy/0566. Reshape the Matrix.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/easy/0566. Reshape the Matrix.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/easy/0566. Reshape the Matrix.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
// 566. Reshape the Matrix // https://leetcode.com/problems/reshape-the-matrix/ // Runtime: 20 ms, faster than 87.74% of C++ online submissions for Reshape the Matrix. // Memory Usage: 11.7 MB, less than 62.67% of C++ online submissions for Reshape the Matrix. class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { const int R = nums.size(); const int C = nums[0].size(); if (R * C != r * c) return nums; if (R == r) return nums; vector<vector<int>> ans(r, vector<int>(c)); for (int k = 0; k < R * C; ++k) ans[k/c][k%c] = nums[k/C][k%C]; return ans; } };
35.842105
92
0.578561
[ "vector" ]
269056bef7c5e37371f747de8eed1937118b1f12
1,246
h
C
apps/autoscheduler/mcts/IState.h
hqjenny/Halide
43ab3fe3b6d3c7e319e2192b2182e94428691d08
[ "Apache-2.0" ]
null
null
null
apps/autoscheduler/mcts/IState.h
hqjenny/Halide
43ab3fe3b6d3c7e319e2192b2182e94428691d08
[ "Apache-2.0" ]
1
2020-05-20T08:42:26.000Z
2020-05-20T08:42:26.000Z
apps/autoscheduler/mcts/IState.h
hqjenny/Halide
43ab3fe3b6d3c7e319e2192b2182e94428691d08
[ "Apache-2.0" ]
2
2020-03-18T06:51:59.000Z
2020-12-23T21:25:49.000Z
#pragma once /* Interface that the State class needs to comply with. It doesn't need to extend this class, in fact, you don't need to include this file This is just here for reference. 'Action' is your custom class containing action information See examples for usage */ #include <vector> #include <string> namespace msa { namespace mcts { struct Action { }; class State { // copy and assignment operators should perform a DEEP clone of the given state State(const State& other); State& operator = (const State& other); // whether or not this state is terminal (reached end) bool is_terminal() const; // agent id (zero-based) for agent who is about to make a decision int agent_id() const; // apply action to state void apply_action(const Action& action); // return possible actions from this state void get_actions(std::vector<Action>& actions) const; // get a random action, return false if no actions found bool get_random_action(Action& action) const; // evaluate this state and return a vector of rewards (for each agent) const std::vector<float> evaluate() const; // return state as string (for debug purposes) std::string to_string() const; }; } }
23.509434
83
0.701445
[ "vector" ]
2692e6de8d5d3b163b5972664156b6cd3a7a6564
12,351
c
C
guest-API-SDK/17.06/wrs-guest-heartbeat-3.0.1/guest_client/src/guest_script.c
WindRiverCode/Titanium-Server
08ec033e391ed6afaff9d2ce9ac238fb53928ffb
[ "BSD-3-Clause" ]
12
2017-08-06T23:25:08.000Z
2021-03-13T01:35:37.000Z
guest-API-SDK/17.06/wrs-guest-heartbeat-3.0.1/guest_client/src/guest_script.c
WindRiverCode/Titanium-Server
08ec033e391ed6afaff9d2ce9ac238fb53928ffb
[ "BSD-3-Clause" ]
null
null
null
guest-API-SDK/17.06/wrs-guest-heartbeat-3.0.1/guest_client/src/guest_script.c
WindRiverCode/Titanium-Server
08ec033e391ed6afaff9d2ce9ac238fb53928ffb
[ "BSD-3-Clause" ]
9
2017-03-14T09:23:09.000Z
2021-01-05T12:57:56.000Z
/* * Copyright (c) 2013-2016, Wind River Systems, Inc. * * 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 Wind River Systems 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. */ #include "guest_script.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/resource.h> #include "guest_limits.h" #include "guest_types.h" #include "guest_debug.h" #include "guest_selobj.h" #include "guest_utils.h" #include "guest_child_death.h" #define GUEST_SCRIPT_SETUP_FAILURE -65535 typedef struct { bool inuse; int pid; int fd; int log_end_ptr; char log_msg[256]; GuestScriptIdT script_id; GuestScriptCallbackT callback; } GuestScriptDataT; static GuestScriptDataT _scripts[GUEST_CHILD_PROCESS_MAX]; // **************************************************************************** // Guest Script - Abort // ==================== void guest_script_abort( GuestScriptIdT script_id ) { int result; GuestScriptDataT* entry; GuestErrorT error; if (GUEST_SCRIPT_ID_INVALID == script_id) return; if (GUEST_CHILD_PROCESS_MAX <= script_id) return; entry = &(_scripts[script_id]); if (entry->inuse) { if (-1 != entry->pid) { error = guest_child_death_deregister(entry->pid); if (GUEST_OKAY != error) { DPRINTFE("Failed to deregister for child death %i, error=%s.", entry->pid, guest_error_str(error)); } result = kill(entry->pid, SIGKILL); if (0 > result) { if (ESRCH == errno) { DPRINTFV("Script pid (%i) not running.", entry->pid); } else { DPRINTFE("Failed to send kill signal to script pid %i, " "error=%s.", entry->pid, strerror(errno)); } } else { DPRINTFD("Script pid (%i) killed.", entry->pid); } } if (-1 != entry->fd) { error = guest_selobj_deregister(entry->fd); if (GUEST_OKAY != error) { DPRINTFE("Failed to deregister selection object %i, error=%s.", entry->fd, guest_error_str(error)); } close(entry->fd); } memset(entry, 0, sizeof(GuestScriptDataT)); entry->pid = -1; entry->fd = -1; entry->script_id = GUEST_SCRIPT_ID_INVALID; } } // **************************************************************************** // **************************************************************************** // Guest Script - Dispatch // ======================= static void guest_script_dispatch( int selobj ) { int bytes_avail; int result; GuestScriptDataT* entry; unsigned int script_i; for (script_i=0; GUEST_CHILD_PROCESS_MAX > script_i; ++script_i) { entry = &(_scripts[script_i]); if (entry->inuse) if (selobj == entry->fd) break; } if (GUEST_CHILD_PROCESS_MAX <= script_i) return; bytes_avail = sizeof(entry->log_msg) - entry->log_end_ptr; result = read(selobj, &(entry->log_msg[entry->log_end_ptr]), bytes_avail); if (0 > result) { if (EINTR == errno) { DPRINTFD("Interrupted on read, error=%s.", strerror(errno)); return; } else { DPRINTFE("Failed to read, error=%s.", strerror(errno)); return; } } else if (0 == result) { DPRINTFD("No message received."); return; } else { DPRINTFD("Received message, msg_size=%i.", result); entry->log_end_ptr += result; } } // **************************************************************************** // **************************************************************************** // Guest Script - Callback // ======================= static void guest_script_callback( pid_t pid, int exit_code ) { GuestScriptDataT* entry; unsigned int script_i; for (script_i=0; GUEST_CHILD_PROCESS_MAX > script_i; ++script_i) { entry = &(_scripts[script_i]); if (entry->inuse) if ((int) pid == entry->pid) break; } if (GUEST_CHILD_PROCESS_MAX <= script_i) return; DPRINTFD("PID %i exited with %i", (int) pid, exit_code); if (NULL != entry->callback) entry->callback(entry->script_id, exit_code, entry->log_msg); guest_script_abort(entry->script_id); } // **************************************************************************** // **************************************************************************** // Guest Script - Invoke // ===================== GuestErrorT guest_script_invoke( char script[], char* script_argv[], GuestScriptCallbackT callback, GuestScriptIdT* script_id ) { int fd[2]; pid_t pid; struct stat stat_data; char* script_name = guest_utils_basename(script); char* script_exec = script; int result; GuestScriptDataT* entry; GuestSelObjCallbacksT callbacks; GuestErrorT error; *script_id = GUEST_SCRIPT_ID_INVALID; unsigned int script_i; for (script_i=1; GUEST_CHILD_PROCESS_MAX > script_i; ++script_i) { entry = &(_scripts[script_i]); if (!entry->inuse) break; } if (GUEST_CHILD_PROCESS_MAX <= script_i) { DPRINTFE("Failed to allocate script data."); return GUEST_FAILED; } memset(entry, 0, sizeof(GuestScriptDataT)); entry->script_id = script_i; entry->callback = callback; entry->pid = -1; entry->fd = -1; result = access(script_exec, F_OK | X_OK); if (0 > result) { DPRINTFE("Script %s access failed, error=%s.", script_exec, strerror(errno)); return GUEST_FAILED; } result = stat(script_exec, &stat_data); if (0 > result) { DPRINTFE("Script %s stat failed, error=%s.", script_exec, strerror( errno ) ); return GUEST_FAILED; } if (0 >= stat_data.st_size) { DPRINTFE("Script %s has zero size.", script_exec); return GUEST_FAILED; } result = pipe(fd); if (0 > result) { DPRINTFE("Script %s pipe creation failed, error=%s.", script_exec, strerror(errno)); return GUEST_FAILED; } result = fcntl(fd[0], F_SETFL, O_NONBLOCK); if (0 > result) { DPRINTFE("Script %s pipe failed to make read end non-blocking, " "error=%s.", script_exec, strerror(errno)); close(fd[0]); close(fd[1]); return GUEST_FAILED; } pid = fork(); if (0 > pid) { DPRINTFE("Failed to fork process for script %s, error=%s.", script_exec, strerror(errno)); close(fd[0]); close(fd[1]); return GUEST_FAILED; } else if (0 == pid) { // Child process. struct rlimit file_limits; close(fd[0]); // close read end of pipe result = setpgid(0, 0); if (0 > result) { DPRINTFE("Failed to set process group id for script %s, " "error=%s.", script_exec, strerror( errno ) ); exit(GUEST_SCRIPT_SETUP_FAILURE); } result = getrlimit(RLIMIT_NOFILE, &file_limits); if (0 > result) { DPRINTFE("Failed to get file limits for script %s, error=%s.", script_exec, strerror(errno)); exit(GUEST_SCRIPT_SETUP_FAILURE); } unsigned int fd_i; for (fd_i=0; fd_i < file_limits.rlim_cur; ++fd_i) if (fd_i != fd[1]) close(fd_i); result = dup2(fd[1], 1); // make stdout into writable end of pipe if (0 > result) { DPRINTFE("Failed to make stdout into writable end of pipe for " "script %s, error=%s.", script_exec, strerror(errno)); exit(GUEST_SCRIPT_SETUP_FAILURE); } result = execv(script_exec, (char**) script_argv); if (0 > result) DPRINTFE("Failed to exec command for script %s, error=%s.", script_exec, strerror(errno)); exit(GUEST_SCRIPT_SETUP_FAILURE); } else { // Parent process. close(fd[1]); // close write end of pipe entry->pid = (int) pid; entry->fd = fd[0]; entry->inuse = true; DPRINTFD("Child process %i created for script %s, script_id=%i.", entry->pid, script_name, entry->script_id); error = guest_child_death_register(pid, guest_script_callback); if (GUEST_OKAY != error) { DPRINTFE("Failed to register for child death %i, error=%s.", entry->pid, guest_error_str(error)); guest_script_abort(entry->script_id); return error; } memset(&callbacks, 0, sizeof(callbacks)); callbacks.read_callback = guest_script_dispatch; error = guest_selobj_register(entry->fd, &callbacks); if (GUEST_OKAY != error) { DPRINTFE("Failed to register selection object %i, error=%s.", entry->fd, guest_error_str(error)); guest_script_abort(entry->script_id); return error; } *script_id = entry->script_id; } return GUEST_OKAY; } // **************************************************************************** // **************************************************************************** // Guest Script - Initialize // ========================= GuestErrorT guest_script_initialize( void ) { GuestScriptDataT* entry; memset(_scripts, 0, sizeof(_scripts)); unsigned int script_i; for (script_i=0; GUEST_CHILD_PROCESS_MAX > script_i; ++script_i) { entry = &(_scripts[script_i]); entry->pid = -1; entry->fd = -1; entry->script_id = GUEST_SCRIPT_ID_INVALID; } return GUEST_OKAY; } // **************************************************************************** // **************************************************************************** // Guest Script - Finalize // ======================= GuestErrorT guest_script_finalize( void ) { GuestScriptDataT* entry; unsigned int script_i; for (script_i=0; GUEST_CHILD_PROCESS_MAX > script_i; ++script_i) { entry = &(_scripts[script_i]); if (entry->inuse) guest_script_abort(entry->script_id); } memset(_scripts, 0, sizeof(_scripts)); return GUEST_OKAY; } // ****************************************************************************
30.051095
87
0.541657
[ "object" ]
2696b588278cde38cfdf36773738e798182b7c91
14,064
h
C
src/deps/icu-small/source/i18n/unicode/coleitr.h
odant/conan-jscript
0e7433ebe9e5ebf331a47c8b2d01a510c7f53952
[ "MIT" ]
null
null
null
src/deps/icu-small/source/i18n/unicode/coleitr.h
odant/conan-jscript
0e7433ebe9e5ebf331a47c8b2d01a510c7f53952
[ "MIT" ]
5
2021-02-13T18:06:42.000Z
2021-02-13T18:06:44.000Z
src/deps/icu-small/source/i18n/unicode/coleitr.h
odant/conan-jscript
0e7433ebe9e5ebf331a47c8b2d01a510c7f53952
[ "MIT" ]
3
2019-03-25T23:01:31.000Z
2020-05-19T01:17:27.000Z
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1997-2014, International Business Machines * Corporation and others. All Rights Reserved. ****************************************************************************** */ /** * \file * \brief C++ API: Collation Element Iterator. */ /** * File coleitr.h * * Created by: Helena Shih * * Modification History: * * Date Name Description * * 8/18/97 helena Added internal API documentation. * 08/03/98 erm Synched with 1.2 version CollationElementIterator.java * 12/10/99 aliu Ported Thai collation support from Java. * 01/25/01 swquek Modified into a C++ wrapper calling C APIs (ucoliter.h) * 02/19/01 swquek Removed CollationElementsIterator() since it is * private constructor and no calls are made to it * 2012-2014 markus Rewritten in C++ again. */ #ifndef COLEITR_H #define COLEITR_H #include "unicode/utypes.h" #if U_SHOW_CPLUSPLUS_API #if !UCONFIG_NO_COLLATION #include "unicode/unistr.h" #include "unicode/uobject.h" struct UCollationElements; struct UHashtable; U_NAMESPACE_BEGIN struct CollationData; class CharacterIterator; class CollationIterator; class RuleBasedCollator; class UCollationPCE; class UVector32; /** * The CollationElementIterator class is used as an iterator to walk through * each character of an international string. Use the iterator to return the * ordering priority of the positioned character. The ordering priority of a * character, which we refer to as a key, defines how a character is collated in * the given collation object. * For example, consider the following in Slovak and in traditional Spanish collation: * <pre> * "ca" -> the first key is key('c') and second key is key('a'). * "cha" -> the first key is key('ch') and second key is key('a').</pre> * And in German phonebook collation, * <pre> \htmlonly "&#x00E6;b"-> the first key is key('a'), the second key is key('e'), and * the third key is key('b'). \endhtmlonly </pre> * The key of a character, is an integer composed of primary order(short), * secondary order(char), and tertiary order(char). Java strictly defines the * size and signedness of its primitive data types. Therefore, the static * functions primaryOrder(), secondaryOrder(), and tertiaryOrder() return * int32_t to ensure the correctness of the key value. * <p>Example of the iterator usage: (without error checking) * <pre> * \code * void CollationElementIterator_Example() * { * UnicodeString str = "This is a test"; * UErrorCode success = U_ZERO_ERROR; * RuleBasedCollator* rbc = * (RuleBasedCollator*) RuleBasedCollator::createInstance(success); * CollationElementIterator* c = * rbc->createCollationElementIterator( str ); * int32_t order = c->next(success); * c->reset(); * order = c->previous(success); * delete c; * delete rbc; * } * \endcode * </pre> * <p> * The method next() returns the collation order of the next character based on * the comparison level of the collator. The method previous() returns the * collation order of the previous character based on the comparison level of * the collator. The Collation Element Iterator moves only in one direction * between calls to reset(), setOffset(), or setText(). That is, next() * and previous() can not be inter-used. Whenever previous() is to be called after * next() or vice versa, reset(), setOffset() or setText() has to be called first * to reset the status, shifting pointers to either the end or the start of * the string (reset() or setText()), or the specified position (setOffset()). * Hence at the next call of next() or previous(), the first or last collation order, * or collation order at the spefcifieid position will be returned. If a change of * direction is done without one of these calls, the result is undefined. * <p> * The result of a forward iterate (next()) and reversed result of the backward * iterate (previous()) on the same string are equivalent, if collation orders * with the value 0 are ignored. * Character based on the comparison level of the collator. A collation order * consists of primary order, secondary order and tertiary order. The data * type of the collation order is <strong>int32_t</strong>. * * Note, CollationElementIterator should not be subclassed. * @see Collator * @see RuleBasedCollator * @version 1.8 Jan 16 2001 */ class U_I18N_API CollationElementIterator U_FINAL : public UObject { public: // CollationElementIterator public data member ------------------------------ enum { /** * NULLORDER indicates that an error has occured while processing * @stable ICU 2.0 */ NULLORDER = (int32_t)0xffffffff }; // CollationElementIterator public constructor/destructor ------------------- /** * Copy constructor. * * @param other the object to be copied from * @stable ICU 2.0 */ CollationElementIterator(const CollationElementIterator& other); /** * Destructor * @stable ICU 2.0 */ virtual ~CollationElementIterator(); // CollationElementIterator public methods ---------------------------------- /** * Returns true if "other" is the same as "this" * * @param other the object to be compared * @return true if "other" is the same as "this" * @stable ICU 2.0 */ UBool operator==(const CollationElementIterator& other) const; /** * Returns true if "other" is not the same as "this". * * @param other the object to be compared * @return true if "other" is not the same as "this" * @stable ICU 2.0 */ UBool operator!=(const CollationElementIterator& other) const; /** * Resets the cursor to the beginning of the string. * @stable ICU 2.0 */ void reset(void); /** * Gets the ordering priority of the next character in the string. * @param status the error code status. * @return the next character's ordering. otherwise returns NULLORDER if an * error has occured or if the end of string has been reached * @stable ICU 2.0 */ int32_t next(UErrorCode& status); /** * Get the ordering priority of the previous collation element in the string. * @param status the error code status. * @return the previous element's ordering. otherwise returns NULLORDER if an * error has occured or if the start of string has been reached * @stable ICU 2.0 */ int32_t previous(UErrorCode& status); /** * Gets the primary order of a collation order. * @param order the collation order * @return the primary order of a collation order. * @stable ICU 2.0 */ static inline int32_t primaryOrder(int32_t order); /** * Gets the secondary order of a collation order. * @param order the collation order * @return the secondary order of a collation order. * @stable ICU 2.0 */ static inline int32_t secondaryOrder(int32_t order); /** * Gets the tertiary order of a collation order. * @param order the collation order * @return the tertiary order of a collation order. * @stable ICU 2.0 */ static inline int32_t tertiaryOrder(int32_t order); /** * Return the maximum length of any expansion sequences that end with the * specified comparison order. * @param order a collation order returned by previous or next. * @return maximum size of the expansion sequences ending with the collation * element or 1 if collation element does not occur at the end of any * expansion sequence * @stable ICU 2.0 */ int32_t getMaxExpansion(int32_t order) const; /** * Gets the comparison order in the desired strength. Ignore the other * differences. * @param order The order value * @stable ICU 2.0 */ int32_t strengthOrder(int32_t order) const; /** * Sets the source string. * @param str the source string. * @param status the error code status. * @stable ICU 2.0 */ void setText(const UnicodeString& str, UErrorCode& status); /** * Sets the source string. * @param str the source character iterator. * @param status the error code status. * @stable ICU 2.0 */ void setText(CharacterIterator& str, UErrorCode& status); /** * Checks if a comparison order is ignorable. * @param order the collation order. * @return true if a character is ignorable, false otherwise. * @stable ICU 2.0 */ static inline UBool isIgnorable(int32_t order); /** * Gets the offset of the currently processed character in the source string. * @return the offset of the character. * @stable ICU 2.0 */ int32_t getOffset(void) const; /** * Sets the offset of the currently processed character in the source string. * @param newOffset the new offset. * @param status the error code status. * @return the offset of the character. * @stable ICU 2.0 */ void setOffset(int32_t newOffset, UErrorCode& status); /** * ICU "poor man's RTTI", returns a UClassID for the actual class. * * @stable ICU 2.2 */ virtual UClassID getDynamicClassID() const; /** * ICU "poor man's RTTI", returns a UClassID for this class. * * @stable ICU 2.2 */ static UClassID U_EXPORT2 getStaticClassID(); #ifndef U_HIDE_INTERNAL_API /** @internal */ static inline CollationElementIterator *fromUCollationElements(UCollationElements *uc) { return reinterpret_cast<CollationElementIterator *>(uc); } /** @internal */ static inline const CollationElementIterator *fromUCollationElements(const UCollationElements *uc) { return reinterpret_cast<const CollationElementIterator *>(uc); } /** @internal */ inline UCollationElements *toUCollationElements() { return reinterpret_cast<UCollationElements *>(this); } /** @internal */ inline const UCollationElements *toUCollationElements() const { return reinterpret_cast<const UCollationElements *>(this); } #endif // U_HIDE_INTERNAL_API private: friend class RuleBasedCollator; friend class UCollationPCE; /** * CollationElementIterator constructor. This takes the source string and the * collation object. The cursor will walk thru the source string based on the * predefined collation rules. If the source string is empty, NULLORDER will * be returned on the calls to next(). * @param sourceText the source string. * @param order the collation object. * @param status the error code status. */ CollationElementIterator(const UnicodeString& sourceText, const RuleBasedCollator* order, UErrorCode& status); // Note: The constructors should take settings & tailoring, not a collator, // to avoid circular dependencies. // However, for operator==() we would need to be able to compare tailoring data for equality // without making CollationData or CollationTailoring depend on TailoredSet. // (See the implementation of RuleBasedCollator::operator==().) // That might require creating an intermediate class that would be used // by both CollationElementIterator and RuleBasedCollator // but only contain the part of RBC== related to data and rules. /** * CollationElementIterator constructor. This takes the source string and the * collation object. The cursor will walk thru the source string based on the * predefined collation rules. If the source string is empty, NULLORDER will * be returned on the calls to next(). * @param sourceText the source string. * @param order the collation object. * @param status the error code status. */ CollationElementIterator(const CharacterIterator& sourceText, const RuleBasedCollator* order, UErrorCode& status); /** * Assignment operator * * @param other the object to be copied */ const CollationElementIterator& operator=(const CollationElementIterator& other); CollationElementIterator(); // default constructor not implemented /** Normalizes dir_=1 (just after setOffset()) to dir_=0 (just after reset()). */ inline int8_t normalizeDir() const { return dir_ == 1 ? 0 : dir_; } static UHashtable *computeMaxExpansions(const CollationData *data, UErrorCode &errorCode); static int32_t getMaxExpansion(const UHashtable *maxExpansions, int32_t order); // CollationElementIterator private data members ---------------------------- CollationIterator *iter_; // owned const RuleBasedCollator *rbc_; // aliased uint32_t otherHalf_; /** * <0: backwards; 0: just after reset() (previous() begins from end); * 1: just after setOffset(); >1: forward */ int8_t dir_; /** * Stores offsets from expansions and from unsafe-backwards iteration, * so that getOffset() returns intermediate offsets for the CEs * that are consistent with forward iteration. */ UVector32 *offsets_; UnicodeString string_; }; // CollationElementIterator inline method definitions -------------------------- inline int32_t CollationElementIterator::primaryOrder(int32_t order) { return (order >> 16) & 0xffff; } inline int32_t CollationElementIterator::secondaryOrder(int32_t order) { return (order >> 8) & 0xff; } inline int32_t CollationElementIterator::tertiaryOrder(int32_t order) { return order & 0xff; } inline UBool CollationElementIterator::isIgnorable(int32_t order) { return (order & 0xffff0000) == 0; } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_COLLATION */ #endif /* U_SHOW_CPLUSPLUS_API */ #endif
34.135922
104
0.669724
[ "object" ]
269deb3cd9d5cd62797ddb40faf214a39a6603f6
1,512
h
C
lib/scipoptsuite-5.0.1/soplex/src/dsvector.h
npwebste/UPS_Controller
a90ce2229108197fd48f956310ae2929e0fa5d9a
[ "AFL-1.1" ]
null
null
null
lib/scipoptsuite-5.0.1/soplex/src/dsvector.h
npwebste/UPS_Controller
a90ce2229108197fd48f956310ae2929e0fa5d9a
[ "AFL-1.1" ]
null
null
null
lib/scipoptsuite-5.0.1/soplex/src/dsvector.h
npwebste/UPS_Controller
a90ce2229108197fd48f956310ae2929e0fa5d9a
[ "AFL-1.1" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the class library */ /* SoPlex --- the Sequential object-oriented simPlex. */ /* */ /* Copyright (C) 1996-2018 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SoPlex is distributed under the terms of the ZIB Academic Licence. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SoPlex; see the file COPYING. If not email to soplex@zib.de. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file dsvector.h * @brief Dynamic sparse vectors. */ #ifndef _DSVECTOR_H_ #define _DSVECTOR_H_ #include "spxdefines.h" #include "basevectors.h" #include "svector.h" // for compatibility namespace soplex { typedef DSVectorBase< Real > DSVector; typedef DSVectorBase< Real > DSVectorReal; typedef DSVectorBase< Rational > DSVectorRational; } // namespace soplex #endif // _DSVECTOR_H_
45.818182
79
0.391534
[ "object" ]
26a0998dc053667e47684818152fd9ebec651b67
1,257
h
C
QuickBackupX/config.h
Jasonzyt/QuickBackupX
cd20c14ba804af269455f8723f66913536a4ff2e
[ "FSFAP" ]
10
2021-02-25T20:40:22.000Z
2022-03-26T14:51:30.000Z
QuickBackupX/config.h
Jasonzyt/QuickBackupX
cd20c14ba804af269455f8723f66913536a4ff2e
[ "FSFAP" ]
2
2021-04-04T03:24:02.000Z
2022-01-22T13:50:55.000Z
QuickBackupX/config.h
Jasonzyt/QuickBackupX
cd20c14ba804af269455f8723f66913536a4ff2e
[ "FSFAP" ]
1
2021-09-17T02:36:02.000Z
2021-09-17T02:36:02.000Z
// Created by JasonZYT on 02/03/2021 #pragma once #ifndef QBX_CONFIG_INCLUDED #define QBX_CONFIG_INCLUDED #include "pch.h" #include "json/json.h" namespace QuickBackupX { class Config { public: Config(); enum class PerType : int { Admin, Backup, Back }; bool debug = false; bool acb = false; // Allow Command Block bool eula = false; // Agree EULA bool aoab = false; int lops = 10; int csl = 60; int abm = 10; std::string bop = ""; // Backup Output Path std::string los = ""; std::string vos = ""; std::vector<std::string> abtime; std::map<std::string, std::string> admins; std::map<std::string, std::string> backup; // Can Backup Player Vector std::map<std::string, std::string> back; // Can Back Player Vector bool getConfig(); bool AddPermission(); bool EditPermissionXuid(PerType per, std::string name, std::string xuid); bool EditPermissionName(PerType per, std::string xuid, std::string name); std::string getBackupDir(); std::string getBackupDirC(); std::string getBackupDisk(); private: Json::Value cfgjv; template<typename retvec> std::vector<retvec> getConfigArray(std::string key); std::map<std::string, std::string> getPermission(PerType per); }; } #endif // QBX_JSON_INCLUDED
26.1875
75
0.686555
[ "vector" ]
26a3b21d731dbfe88b6ac3047a2ad7a0bf55b33a
11,840
h
C
examples/opengl_torus/teapot_low_res.h
mjs513/ArduinoGL_t3
e5fa6b41ffb11df68fd54e6b8a90799622d90efe
[ "MIT" ]
null
null
null
examples/opengl_torus/teapot_low_res.h
mjs513/ArduinoGL_t3
e5fa6b41ffb11df68fd54e6b8a90799622d90efe
[ "MIT" ]
null
null
null
examples/opengl_torus/teapot_low_res.h
mjs513/ArduinoGL_t3
e5fa6b41ffb11df68fd54e6b8a90799622d90efe
[ "MIT" ]
null
null
null
// THERE MUST BE NO MORE THAN 256 VERTICES // scale= 47.36865 #define NTRIANGLES 256 #define NVERTICES 150 PROGMEM const int16_t vertices[NVERTICES*3]={ 49,36,0,43,38,30,53,36,0,22,36,48,23,36,51,-6,36,56,-6,36,59,-35,37,48,-56,37,29,-64,37,0,-56,38,-29, -34,36,-47,-36,36,-50,-6,36,-55,-6,36,-58,23,38,-49,42,36,-27,45,36,-29,54,13,36,63,13,0,60,-7,39,71, -7,0,63,-26,41,74,-26,0,29,13,61,33,-7,67,34,-26,70,-6,13,70,-6,-7,77,-6,-26,80,-40,21,58,-45,-7,67,-47, -26,70,-66,13,36,-73,-7,39,-75,-26,41,-76,13,0,-83,-7,0,-66,13,-35,-73,-7,-38,-75,-26,-40,-41,13,-60, -45,-7,-66,-47,-26,-69,-6,13,-69,-6,-7,-76,-6,-26,-79,29,13,-60,33,-7,-66,34,-26,-69,54,13,-35,60,-7, -38,63,-26,-40,58,-41,38,69,-41,0,43,-59,29,51,-59,0,32,-41,65,23,-59,50,-6,-41,75,-6,-59,57,-44,-41, 65,-35,-59,50,-71,-41,38,-81,-41,0,-63,-59,0,-71,-41,-37,-55,-59,-28,-44,-41,-64,-6,-41,-74,-6,-59,-56, 32,-41,-64,23,-59,-49,58,-41,-37,34,-61,16,-6,-62,0,-22,-61,41,-55,-59,29,-47,-61,-15,-35,-59,-49,9,-61, -40,43,-59,-28,-69,21,8,-116,19,9,-113,14,0,-98,25,8,-121,8,9,-66,27,4,-67,25,-7,-98,27,-2,-119,22,-2, -126,10,-2,-71,19,-2,-108,19,-7,-116,-7,9,-102,-22,9,-107,-9,1,-86,-26,0,-82,-37,4,-107,-23,0,-122,-6, -2,-118,5,-7,-106,-19,-8,-84,-33,-8,62,-5,0,62,-13,18,87,-3,15,85,2,0,100,23,8,97,26,0,62,-29,18,93,-13, 15,102,12,10,122,36,6,62,-38,0,95,-18,0,106,10,0,62,-29,-17,93,-13,-14,102,12,-9,62,-13,-17,87,-3,-14, 127,35,0,118,33,-7,3,63,6,-13,60,14,-6,46,8,-20,60,-7,1,60,-13,-5,46,-7,11,42,10,21,38,33,39,34,27,42, 36,0,20,34,45,-18,42,17,-4,36,49,-39,38,28,-32,34,45,-51,34,27,-23,42,-11,-54,36,1,-34,38,-32,-51,34, -26,-32,34,-44,-7,36,-48,4,42,-17,27,38,-27,20,34,-44,39,34,-26, }; PROGMEM const int16_t normals[NVERTICES*3]={ 11,126,-3,67,96,47,72,104,3,2,126,11,34,95,76,1,126,8,-5,106,69,-40,96,72,-98,57,57,-114,53,-10,-78,80, -58,-2,126,-12,-34,95,-76,-3,126,-11,3,104,-72,47,96,-67,12,126,-2,76,95,-34,101,49,58,117,48,0,106,31, 61,122,31,0,109,-11,62,126,-11,0,58,48,101,61,31,106,63,-11,109,0,48,117,0,31,122,0,-11,126,-61,53,97, -61,32,106,-62,-11,109,-104,48,53,-106,32,61,-109,-11,63,-117,48,0,-122,31,0,-101,49,-58,-106,31,-61, -109,-11,-62,-58,48,-101,-61,31,-106,-63,-11,-109,0,48,-117,0,31,-122,0,-11,-126,58,49,-101,61,31,-106, 62,-11,-109,101,48,-58,106,31,-61,109,-11,-63,93,-67,52,107,-67,-1,58,-109,27,64,-109,-4,60,-62,92,30, -111,52,4,-70,105,0,-113,56,-52,-67,93,-27,-109,58,-92,-67,54,-107,-67,1,-64,-109,4,-93,-67,-52,-58,-109, -27,-54,-67,-92,-1,-67,-107,-4,-109,-64,52,-67,-93,27,-109,-58,92,-67,-54,9,-126,3,0,-127,0,-3,-126,9, -45,-114,30,-9,-126,-3,-30,-114,-45,3,-126,-9,45,-114,-30,6,-24,124,-34,-10,121,108,-52,38,-12,101,75, -53,-11,114,2,119,44,2,64,-109,-13,121,-33,-62,99,-47,-123,23,-20,12,-124,-18,13,-18,-124,-10,-21,124, 22,9,124,105,70,8,-111,59,11,-34,-99,71,-80,-98,1,-112,-53,-25,18,6,-125,7,9,-126,-40,-76,-93,-40,119, 17,-6,44,118,-24,65,105,-82,96,0,-56,45,104,-102,66,-33,49,-78,86,68,-31,102,65,-22,106,47,-23,115,62, -108,-17,98,-80,0,111,-59,-8,31,-37,-117,66,-53,-94,95,-40,-73,-24,86,-89,-12,36,-120,97,-78,19,67,-41, -99,109,44,47,-51,28,112,-23,89,87,-113,27,-49,59,26,-108,50,89,-74,20,124,15,27,120,28,43,114,32,30, 123,0,33,112,47,-12,124,21,0,123,30,-28,120,27,-32,114,43,-47,112,33,-19,124,-14,-30,123,0,-27,120,-28, -43,114,-32,-33,112,-47,0,123,-30,12,124,-21,28,120,-27,32,114,-43,47,112,-33, }; PROGMEM const uint16_t triangles[NTRIANGLES*3]={ 0,1,2,1,3,4,3,5,6,3,6,4,5,7,6,6,7,30,7,8,30,10,11,12,11,13,14,11,14,12,13,15,14,15,16,17,16,0,2,16,2, 17,2,1,18,2,18,19,19,18,20,19,20,21,21,20,22,21,22,23,1,4,24,1,24,18,18,24,25,18,25,20,20,25,26,20,26, 22,4,6,27,4,27,24,24,27,28,24,28,25,25,28,29,25,29,26,6,30,27,27,30,31,27,31,28,28,31,32,28,32,29,30, 8,33,30,33,34,30,34,31,31,34,35,31,35,32,8,9,36,8,36,33,33,36,37,33,37,34,34,37,97,34,97,35,9,10,38,9, 38,36,36,38,39,36,39,37,37,39,40,37,40,97,10,12,41,10,41,38,38,41,42,38,42,39,39,42,43,39,43,40,12,14, 44,12,44,41,41,44,45,41,45,42,42,45,46,42,46,43,14,15,47,14,47,44,44,47,48,44,48,45,45,48,49,45,49,46, 15,17,50,15,50,47,47,50,51,47,51,48,48,51,52,48,52,49,17,2,19,17,19,50,50,19,21,50,21,51,51,21,23,51, 23,52,23,22,53,23,53,54,54,53,55,54,55,56,22,26,57,22,57,53,53,57,58,53,58,55,26,29,59,26,59,57,57,59, 58,58,59,60,29,32,61,29,61,59,59,61,62,59,62,60,32,35,63,32,63,61,61,63,77,61,77,62,35,97,64,35,64,63, 63,64,65,63,65,77,97,40,66,97,66,64,64,66,67,64,67,65,40,43,68,40,68,66,66,68,79,66,79,67,43,46,69,43, 69,68,68,69,70,68,70,79,46,49,71,46,71,69,69,71,72,69,72,70,49,52,73,49,73,71,71,73,81,71,81,72,52,23, 54,52,54,73,73,54,56,73,56,81,56,55,74,55,58,74,58,60,76,58,76,74,74,76,75,60,62,76,62,77,76,77,65,78, 77,78,76,76,78,75,65,67,78,67,79,78,79,70,80,79,80,78,78,80,75,70,72,80,72,81,80,81,56,74,81,74,80,80, 74,75,92,82,83,92,83,84,84,83,86,82,87,85,82,85,83,87,89,85,85,89,90,85,90,83,83,90,91,83,91,86,87,88, 89,88,92,93,88,93,89,89,93,90,90,93,101,90,101,91,93,92,84,93,84,101,84,86,94,84,94,96,96,94,95,96,95, 97,95,98,97,86,91,100,86,100,94,94,100,99,94,99,95,95,99,98,100,102,99,99,102,103,99,103,98,91,101,100, 100,101,102,101,84,96,101,96,102,102,96,97,102,97,103,104,105,106,104,106,107,107,106,108,107,108,109, 105,110,111,105,111,106,106,111,112,106,112,108,108,112,113,110,114,115,110,115,111,111,115,116,111,116, 112,112,116,122,112,122,113,114,117,118,114,118,115,115,118,119,115,119,116,116,119,123,116,123,122,117, 120,121,117,121,118,118,121,119,119,121,123,120,104,107,120,107,121,121,107,109,121,109,123,124,126,129, 124,125,126,127,125,124,125,127,126,127,129,126,128,127,124,127,128,129,128,124,129,129,126,130,130,131, 133,133,131,132,131,134,132,126,135,130,130,135,136,130,136,131,131,136,134,135,137,136,136,137,138,137, 139,138,126,140,135,135,140,141,135,141,137,137,141,139,126,129,140,140,142,141,141,142,143,142,144,143, 129,146,140,140,146,145,140,145,142,142,145,144,146,147,145,145,147,148,147,149,148,129,130,146,146,130, 133,146,133,147,147,133,149, }; PROGMEM const int16_t facenormals[NTRIANGLES*3]={ 11,126,-4,2,126,12,1,126,8,3,126,12,2,126,8,-34,65,103,-74,63,81,-2,126,-12,-2,126,-11,-3,126,-12,-4, 126,-11,12,126,-2,11,126,-2,12,126,-3,111,53,30,112,51,29,115,42,30,115,42,30,121,19,32,121,19,32,82, 52,81,81,52,81,84,42,84,84,42,84,88,19,88,88,19,88,29,51,112,29,51,112,30,42,115,30,42,115,32,19,121, 32,19,121,-28,51,112,-31,44,114,-30,42,115,-32,19,121,-32,19,121,-82,53,80,-83,42,85,-84,44,84,-88,19, 88,-88,19,88,-111,52,29,-111,52,29,-115,42,30,-115,42,30,-121,19,32,-121,19,32,-111,53,-30,-111,51,-29, -115,42,-30,-115,42,-30,-121,19,-32,-121,18,-32,-82,52,-81,-81,52,-81,-84,42,-84,-84,42,-84,-88,19,-88, -88,19,-88,-29,51,-112,-29,51,-112,-30,42,-115,-30,42,-115,-32,19,-121,-32,19,-121,30,53,-111,29,51,-112, 30,42,-115,30,42,-115,32,19,-121,32,19,-121,81,52,-82,81,52,-81,84,42,-84,84,42,-84,88,19,-88,88,19,-88, 112,51,-29,112,51,-29,115,42,-30,115,42,-30,121,19,-32,121,19,-32,116,-40,30,116,-39,30,88,-88,23,88, -88,23,85,-40,85,85,-40,85,64,-88,64,64,-88,64,30,-40,116,30,-39,116,23,-87,88,23,-88,88,-30,-40,116, -30,-39,116,-23,-88,88,-23,-88,88,-85,-40,85,-85,-40,85,-64,-88,64,-64,-88,64,-116,-40,30,-116,-39,30, -88,-88,23,-88,-88,23,-116,-40,-30,-116,-39,-30,-88,-88,-23,-88,-88,-23,-85,-40,-85,-85,-40,-85,-64,-88, -64,-64,-88,-64,-30,-40,-116,-30,-39,-116,-23,-88,-88,-23,-88,-88,30,-40,-116,30,-39,-116,23,-88,-88, 23,-88,-88,85,-40,-85,85,-40,-85,64,-88,-64,64,-88,-64,116,-40,-30,116,-39,-30,88,-88,-23,88,-88,-23, 23,-124,6,13,-125,13,3,-126,13,4,-126,10,1,-126,3,-6,-124,23,-13,-125,13,-13,-126,3,-10,-126,4,-3,-126, 1,-23,-124,-6,-13,-125,-13,-3,-126,-13,-4,-126,-10,-1,-126,-3,6,-124,-23,13,-125,-13,13,-126,-3,10,-126, -4,3,-126,-1,4,-125,17,17,-104,69,105,-35,60,8,64,109,1,12,126,-6,124,26,-26,121,26,-31,116,37,-105,57, 41,-106,42,54,3,125,-18,12,-88,-90,-11,83,-95,-19,88,-88,-47,30,-113,-47,30,-113,8,-110,-62,105,-67,20, 88,24,88,91,22,85,80,74,63,61,77,79,65,51,95,-115,-28,45,-112,-32,49,-94,-75,37,-83,-78,54,-63,-100,44, -84,-81,-48,-63,-96,-52,-58,-109,-26,-72,-18,-102,-62,-24,-107,96,22,-79,108,54,-36,63,83,-70,61,93,-59, -38,108,52,-36,111,48,-105,58,41,-103,54,49,11,0,126,11,5,126,28,14,122,22,20,123,1,15,125,58,-101,49, 58,-101,48,114,-40,36,112,-32,48,88,-76,48,82,-56,78,58,-101,-49,58,-101,-48,116,-36,-35,110,-39,-48, 96,-66,-49,75,-65,-78,14,0,-126,8,5,-126,26,15,-123,84,-55,-77,-35,109,-53,-40,110,-48,-108,53,-38,-53, 63,-96,107,-66,11,53,-24,112,-16,125,4,-105,-64,30,-87,-91,-9,-4,125,-15,-33,-36,-116,113,-56,-3,28,123, 3,26,123,8,38,119,16,47,108,47,14,105,68,4,125,20,2,125,19,19,116,47,-8,124,25,-16,119,38,-47,108,47, -41,119,6,-20,125,3,-20,125,2,-47,116,19,-30,123,-3,-25,124,-8,-38,119,-16,-47,108,-47,-12,112,-58,-4, 125,-21,-2,125,-20,-19,116,-47,8,123,-26,16,119,-38,47,108,-47,42,119,-11,20,125,-5,19,125,-2,47,116, -19, }; #define NEDGES 404 PROGMEM const uint16_t edges[NEDGES*2]={ 0,1,0,2,0,16,1,2,1,3,1,4,1,18,1,24,2,16,2,17,2,18,2,19,3,4,3,5,3,6,4,6,4,24,4,27,5,6,5,7,6,7,6,27,6,30, 7,8,7,30,8,9,8,30,8,33,8,36,9,10,9,36,9,38,10,11,10,12,10,38,10,41,11,12,11,13,11,14,12,14,12,41,12,44, 13,14,13,15,14,15,14,44,14,47,15,16,15,17,15,47,15,50,16,17,17,19,17,50,18,19,18,20,18,24,18,25,19,20, 19,21,19,50,20,21,20,22,20,25,20,26,21,22,21,23,21,50,21,51,22,23,22,26,22,53,22,57,23,51,23,52,23,53, 23,54,24,25,24,27,24,28,25,26,25,28,25,29,26,29,26,57,26,59,27,28,27,30,27,31,28,29,28,31,28,32,29,32, 29,59,29,61,30,31,30,33,30,34,31,32,31,34,31,35,32,35,32,61,32,63,33,34,33,36,33,37,34,35,34,37,34,97, 35,63,35,64,35,97,36,37,36,38,36,39,37,39,37,40,37,97,38,39,38,41,38,42,39,40,39,42,39,43,40,43,40,66, 40,68,40,97,41,42,41,44,41,45,42,43,42,45,42,46,43,46,43,68,43,69,44,45,44,47,44,48,45,46,45,48,45,49, 46,49,46,69,46,71,47,48,47,50,47,51,48,49,48,51,48,52,49,52,49,71,49,73,50,51,51,52,52,54,52,73,53,54, 53,55,53,57,53,58,54,55,54,56,54,73,55,56,55,58,55,74,56,73,56,74,56,81,57,58,57,59,58,59,58,60,58,74, 58,76,59,60,59,61,59,62,60,62,60,76,61,62,61,63,61,77,62,76,62,77,63,64,63,65,63,77,64,65,64,66,64,67, 64,97,65,67,65,77,65,78,66,67,66,68,66,79,66,97,67,78,67,79,68,69,68,70,68,79,69,70,69,71,69,72,70,72, 70,79,70,80,71,72,71,73,71,81,72,80,72,81,73,81,74,75,74,76,74,80,74,81,75,76,75,78,75,80,76,77,76,78, 77,78,78,79,78,80,79,80,80,81,82,83,82,85,82,87,82,92,83,84,83,85,83,86,83,90,83,91,83,92,84,86,84,92, 84,93,84,94,84,96,84,101,85,87,85,89,85,90,86,91,86,94,86,100,87,88,87,89,88,89,88,92,88,93,89,90,89, 93,90,91,90,93,90,101,91,100,91,101,92,93,93,101,94,95,94,96,94,99,94,100,95,96,95,97,95,98,95,99,96, 97,96,101,96,102,97,98,97,102,97,103,98,99,98,103,99,100,99,102,99,103,100,101,100,102,101,102,102,103, 104,105,104,106,104,107,104,120,105,106,105,110,105,111,106,107,106,108,106,111,106,112,107,108,107,109, 107,120,107,121,108,109,108,112,108,113,109,121,109,123,110,111,110,114,110,115,111,112,111,115,111,116, 112,113,112,116,112,122,113,122,114,115,114,117,114,118,115,116,115,118,115,119,116,119,116,122,116,123, 117,118,117,120,117,121,118,119,118,121,119,121,119,123,120,121,121,123,122,123,124,125,124,126,124,127, 124,128,124,129,125,126,125,127,126,127,126,129,126,130,126,135,126,140,127,128,127,129,128,129,129,130, 129,140,129,146,130,131,130,133,130,135,130,136,130,146,131,132,131,133,131,134,131,136,132,133,132,134, 133,146,133,147,133,149,134,136,135,136,135,137,135,140,135,141,136,137,136,138,137,138,137,139,137,141, 138,139,139,141,140,141,140,142,140,145,140,146,141,142,141,143,142,143,142,144,142,145,143,144,144,145, 145,146,145,147,145,148,146,147,147,148,147,149,148,149, }; Model model_data; void init_model() { model_data.NVertices = NVERTICES; model_data.NFaces = NTRIANGLES; model_data.NEdges = NEDGES; model_data.vertices = vertices; model_data.edges = edges; model_data.faces = triangles; model_data.vertexNormals = normals; model_data.faceNormals = facenormals; }
85.797101
105
0.632601
[ "model" ]
26a4e13275bc74f64cc5191c08b6dc7be0fa5840
13,004
h
C
simple/memory.h
plessl/zippy
f3ecb05e76e44a204e070589f83c557728c7a94f
[ "BSD-3-Clause" ]
null
null
null
simple/memory.h
plessl/zippy
f3ecb05e76e44a204e070589f83c557728c7a94f
[ "BSD-3-Clause" ]
null
null
null
simple/memory.h
plessl/zippy
f3ecb05e76e44a204e070589f83c557728c7a94f
[ "BSD-3-Clause" ]
1
2021-01-07T15:59:41.000Z
2021-01-07T15:59:41.000Z
/* * memory.h - flat memory space interfaces * * This file is a part of the SimpleScalar tool suite written by * Todd M. Austin as a part of the Multiscalar Research Project. * * The tool suite is currently maintained by Doug Burger and Todd M. Austin. * * Copyright (C) 1994, 1995, 1996, 1997, 1998 by Todd M. Austin * * This source file is distributed "as is" in the hope that it will be * useful. The tool set comes with no warranty, and no author or * distributor accepts any responsibility for the consequences of its * use. * * Everyone is granted permission to copy, modify and redistribute * this tool set under the following conditions: * * This source code is distributed for non-commercial use only. * Please contact the maintainer for restrictions applying to * commercial use. * * Permission is granted to anyone to make or distribute copies * of this source code, either as received or modified, in any * medium, provided that all copyright notices, permission and * nonwarranty notices are preserved, and that the distributor * grants the recipient permission for further redistribution as * permitted by this document. * * Permission is granted to distribute this file in compiled * or executable form under the same conditions that apply for * source code, provided that either: * * A. it is accompanied by the corresponding machine-readable * source code, * B. it is accompanied by a written offer, with no time limit, * to give anyone a machine-readable copy of the corresponding * source code in return for reimbursement of the cost of * distribution. This written offer must permit verbatim * duplication by anyone, or * C. it is distributed by someone who received only the * executable form, and is accompanied by a copy of the * written offer of source code that they received concurrently. * * In other words, you are welcome to use, share and improve this * source file. You are forbidden to forbid anyone else to use, share * and improve what you give them. * * INTERNET: dburger@cs.wisc.edu * US Mail: 1210 W. Dayton Street, Madison, WI 53706 * * $Id: memory.h,v 1.1.1.1 2003/10/16 09:01:16 enzler Exp $ * * $Log: memory.h,v $ * Revision 1.1.1.1 2003/10/16 09:01:16 enzler * ZIPPY-6 array; initial import * * Revision 1.1.1.1 2003/01/23 14:46:08 plessl * Initial import * * Revision 1.1.1.1 2000/05/26 15:18:58 taustin * SimpleScalar Tool Set * * * Revision 1.8 1999/12/31 18:38:54 taustin * cross-endian execution support added * quad_t naming conflicts removed * * Revision 1.7 1999/12/13 18:43:54 taustin * cross endian execution support added * * Revision 1.6 1998/08/27 15:39:47 taustin * implemented host interface description in host.h * added target interface support * memory module updated to support 64/32 bit address spaces on 64/32 * bit machines, now implemented with a dynamically optimized hashed * page table * added support for qword's * added fault support * added support for register and memory contexts * * Revision 1.5 1997/03/11 01:16:23 taustin * updated copyright * long/int tweaks made for ALPHA target support * major macro reorganization to support CC portability * mem_valid() added, indicates if an address is bogus, used by DLite! * * Revision 1.4 1997/01/06 16:01:24 taustin * HIDE_MEM_TABLE_DEF added to help with sim-fast.c compilation * * Revision 1.3 1996/12/27 15:53:15 taustin * updated comments * * Revision 1.1 1996/12/05 18:50:23 taustin * Initial revision * * */ #ifndef MEMORY_H #define MEMORY_H #include <stdio.h> #include "host.h" #include "misc.h" #include "machine.h" #include "options.h" #include "stats.h" /* number of entries in page translation hash table (must be power-of-two) */ #define MEM_PTAB_SIZE (32*1024) #define MEM_LOG_PTAB_SIZE 15 /* page table entry */ struct mem_pte_t { struct mem_pte_t *next; /* next translation in this bucket */ md_addr_t tag; /* virtual page number tag */ byte_t *page; /* page pointer */ }; /* memory object */ struct mem_t { /* memory object state */ char *name; /* name of this memory space */ struct mem_pte_t *ptab[MEM_PTAB_SIZE];/* inverted page table */ /* memory object stats */ counter_t page_count; /* total number of pages allocated */ counter_t ptab_misses; /* total first level page tbl misses */ counter_t ptab_accesses; /* total page table accesses */ }; /* memory access command */ enum mem_cmd { Read, /* read memory from target (simulated prog) to host */ Write /* write memory from host (simulator) to target */ }; /* memory access function type, this is a generic function exported for the purpose of access the simulated vitual memory space */ typedef enum md_fault_type (*mem_access_fn)(struct mem_t *mem, /* memory space to access */ enum mem_cmd cmd, /* Read or Write */ md_addr_t addr, /* target memory address to access */ void *p, /* where to copy to/from */ int nbytes); /* transfer length in bytes */ /* * virtual to host page translation macros */ /* compute page table set */ #define MEM_PTAB_SET(ADDR) \ (((ADDR) >> MD_LOG_PAGE_SIZE) & (MEM_PTAB_SIZE - 1)) /* compute page table tag */ #define MEM_PTAB_TAG(ADDR) \ ((ADDR) >> (MD_LOG_PAGE_SIZE + MEM_LOG_PTAB_SIZE)) /* convert a pte entry at idx to a block address */ #define MEM_PTE_ADDR(PTE, IDX) \ (((PTE)->tag << (MD_LOG_PAGE_SIZE + MEM_LOG_PTAB_SIZE)) \ | ((IDX) << MD_LOG_PAGE_SIZE)) /* locate host page for virtual address ADDR, returns NULL if unallocated */ #define MEM_PAGE(MEM, ADDR) \ (/* first attempt to hit in first entry, otherwise call xlation fn */ \ ((MEM)->ptab[MEM_PTAB_SET(ADDR)] \ && (MEM)->ptab[MEM_PTAB_SET(ADDR)]->tag == MEM_PTAB_TAG(ADDR)) \ ? (/* hit - return the page address on host */ \ (MEM)->ptab_accesses++, \ (MEM)->ptab[MEM_PTAB_SET(ADDR)]->page) \ : (/* first level miss - call the translation helper function */ \ mem_translate((MEM), (ADDR)))) /* compute address of access within a host page */ #define MEM_OFFSET(ADDR) ((ADDR) & (MD_PAGE_SIZE - 1)) /* memory tickle function, allocates pages when they are first written */ #define MEM_TICKLE(MEM, ADDR) \ (!MEM_PAGE(MEM, ADDR) \ ? (/* allocate page at address ADDR */ \ mem_newpage(MEM, ADDR)) \ : (/* nada... */ (void)0)) /* memory page iterator */ #define MEM_FORALL(MEM, ITER, PTE) \ for ((ITER)=0; (ITER) < MEM_PTAB_SIZE; (ITER)++) \ for ((PTE)=(MEM)->ptab[i]; (PTE) != NULL; (PTE)=(PTE)->next) /* * memory accessors macros, fast but difficult to debug... */ /* safe version, works only with scalar types */ /* FIXME: write a more efficient GNU C expression for this... */ #define MEM_READ(MEM, ADDR, TYPE) \ (MEM_PAGE(MEM, (md_addr_t)(ADDR)) \ ? *((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) \ : /* page not yet allocated, return zero value */ 0) /* unsafe version, works with any type */ #define __UNCHK_MEM_READ(MEM, ADDR, TYPE) \ (*((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR)))) /* safe version, works only with scalar types */ /* FIXME: write a more efficient GNU C expression for this... */ #define MEM_WRITE(MEM, ADDR, TYPE, VAL) \ (MEM_TICKLE(MEM, (md_addr_t)(ADDR)), \ *((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) = (VAL)) /* unsafe version, works with any type */ #define __UNCHK_MEM_WRITE(MEM, ADDR, TYPE, VAL) \ (*((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) = (VAL)) /* fast memory accessor macros, typed versions */ #define MEM_READ_BYTE(MEM, ADDR) MEM_READ(MEM, ADDR, byte_t) #define MEM_READ_SBYTE(MEM, ADDR) MEM_READ(MEM, ADDR, sbyte_t) #define MEM_READ_HALF(MEM, ADDR) MD_SWAPH(MEM_READ(MEM, ADDR, half_t)) #define MEM_READ_SHALF(MEM, ADDR) MD_SWAPH(MEM_READ(MEM, ADDR, shalf_t)) #define MEM_READ_WORD(MEM, ADDR) MD_SWAPW(MEM_READ(MEM, ADDR, word_t)) #define MEM_READ_SWORD(MEM, ADDR) MD_SWAPW(MEM_READ(MEM, ADDR, sword_t)) #ifdef HOST_HAS_QWORD #define MEM_READ_QWORD(MEM, ADDR) MD_SWAPQ(MEM_READ(MEM, ADDR, qword_t)) #define MEM_READ_SQWORD(MEM, ADDR) MD_SWAPQ(MEM_READ(MEM, ADDR, sqword_t)) #endif /* HOST_HAS_QWORD */ #define MEM_WRITE_BYTE(MEM, ADDR, VAL) MEM_WRITE(MEM, ADDR, byte_t, VAL) #define MEM_WRITE_SBYTE(MEM, ADDR, VAL) MEM_WRITE(MEM, ADDR, sbyte_t, VAL) #define MEM_WRITE_HALF(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, half_t, MD_SWAPH(VAL)) #define MEM_WRITE_SHALF(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, shalf_t, MD_SWAPH(VAL)) #define MEM_WRITE_WORD(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, word_t, MD_SWAPW(VAL)) #define MEM_WRITE_SWORD(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, sword_t, MD_SWAPW(VAL)) #define MEM_WRITE_SFLOAT(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, sfloat_t, MD_SWAPW(VAL)) #define MEM_WRITE_DFLOAT(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, dfloat_t, MD_SWAPQ(VAL)) #ifdef HOST_HAS_QWORD #define MEM_WRITE_QWORD(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, qword_t, MD_SWAPQ(VAL)) #define MEM_WRITE_SQWORD(MEM, ADDR, VAL) \ MEM_WRITE(MEM, ADDR, sqword_t, MD_SWAPQ(VAL)) #endif /* HOST_HAS_QWORD */ /* create a flat memory space */ struct mem_t * mem_create(char *name); /* name of the memory space */ /* translate address ADDR in memory space MEM, returns pointer to host page */ byte_t * mem_translate(struct mem_t *mem, /* memory space to access */ md_addr_t addr); /* virtual address to translate */ /* allocate a memory page */ void mem_newpage(struct mem_t *mem, /* memory space to allocate in */ md_addr_t addr); /* virtual address to allocate */ /* generic memory access function, it's safe because alignments and permissions are checked, handles any natural transfer sizes; note, faults out if nbytes is not a power-of-two or larger then MD_PAGE_SIZE */ enum md_fault_type mem_access(struct mem_t *mem, /* memory space to access */ enum mem_cmd cmd, /* Read (from sim mem) or Write */ md_addr_t addr, /* target address to access */ void *vp, /* host memory address to access */ int nbytes); /* number of bytes to access */ /* register memory system-specific statistics */ void mem_reg_stats(struct mem_t *mem, /* memory space to declare */ struct stat_sdb_t *sdb); /* stats data base */ /* initialize memory system, call before loader.c */ void mem_init(struct mem_t *mem); /* memory space to initialize */ /* dump a block of memory, returns any faults encountered */ enum md_fault_type mem_dump(struct mem_t *mem, /* memory space to display */ md_addr_t addr, /* target address to dump */ int len, /* number bytes to dump */ FILE *stream); /* output stream */ /* * memory accessor routines, these routines require a memory access function * definition to access memory, the memory access function provides a "hook" * for programs to instrument memory accesses, this is used by various * simulators for various reasons; for the default operation - direct access * to the memory system, pass mem_access() as the memory access function */ /* copy a '\0' terminated string to/from simulated memory space, returns the number of bytes copied, returns any fault encountered */ enum md_fault_type mem_strcpy(mem_access_fn mem_fn, /* user-specified memory accessor */ struct mem_t *mem, /* memory space to access */ enum mem_cmd cmd, /* Read (from sim mem) or Write */ md_addr_t addr, /* target address to access */ char *s); /* host memory string buffer */ /* copy NBYTES to/from simulated memory space, returns any faults */ enum md_fault_type mem_bcopy(mem_access_fn mem_fn, /* user-specified memory accessor */ struct mem_t *mem, /* memory space to access */ enum mem_cmd cmd, /* Read (from sim mem) or Write */ md_addr_t addr, /* target address to access */ void *vp, /* host memory address to access */ int nbytes); /* number of bytes to access */ /* copy NBYTES to/from simulated memory space, NBYTES must be a multiple of 4 bytes, this function is faster than mem_bcopy(), returns any faults encountered */ enum md_fault_type mem_bcopy4(mem_access_fn mem_fn, /* user-specified memory accessor */ struct mem_t *mem, /* memory space to access */ enum mem_cmd cmd, /* Read (from sim mem) or Write */ md_addr_t addr, /* target address to access */ void *vp, /* host memory address to access */ int nbytes); /* number of bytes to access */ /* zero out NBYTES of simulated memory, returns any faults encountered */ enum md_fault_type mem_bzero(mem_access_fn mem_fn, /* user-specified memory accessor */ struct mem_t *mem, /* memory space to access */ md_addr_t addr, /* target address to access */ int nbytes); /* number of bytes to clear */ #endif /* MEMORY_H */
38.134897
79
0.690557
[ "object" ]
26a576c530215087b130db6814aa9273860fb915
4,653
h
C
Libraries/RobsJuceModules/rosic/effects/rosic_CompShaper.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/effects/rosic_CompShaper.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/effects/rosic_CompShaper.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#ifndef rosic_CompShaper_h #define rosic_CompShaper_h //// rosic-indcludes: //#include "../math/rosic_Interpolation.h" namespace rosic { /** This class implements a waveshaper with a (softknee) compressor alike transfer function. As there is no dynamic behaviour here, there are no attack/release parameters. Threshold, ratio, knee and the boolean limiter flag work entirely similar as in class SoftKneeCompressor, only that here the transfer function here acts in the linear amplitude domain (as opposed to the dB-domain). \todo: implement oversampling */ class CompShaper { public: enum kneeShapes { CUBIC, QUARTIC }; //--------------------------------------------------------------------------------------------- // construction/destruction: /** Constructor. */ CompShaper(); /** Destructor */ ~CompShaper(); //--------------------------------------------------------------------------------------------- // parameter settings (set-functions): /** Sets the input signal gain / drive in dB. */ void setDrive(double newDrive) { driveFactor = RAPT::rsDbToAmp(newDrive); } /** Sets the amount of DC (direct current) to applied to the iput signal (after the drive, before the waveshaper. */ void setDC(double newDC) { dc = newDC; } /** Sets the threshold above which the transfer curve snaps off. */ void setThreshold(double newThreshold) { threshold = RAPT::rsDbToAmp(newThreshold); calculateCoefficients(); } /** Sets the ratio - that is the reciprocal of the transfer function's slope above the the threshold. */ void setRatio(double newRatio) { ratio = newRatio; oneOverRatio = 1.0/ratio; calculateCoefficients(); } /** Switches the waveshaper into clipper mode - levels above the threshold will be mapped to the threshold itself - this corresponds to an infinite ratio. */ void setToClipperMode(bool shouldClip) { clipperMode = shouldClip; calculateCoefficients(); } /** Sets the transition width between the two slopes as a percentage of the threshold. (the value is specified in decibels despite the fact that the transfer curve acts on linear amplitude). */ void setKneeWidth(double newKneeWidth); /** Sets the shape of the transition between threshold-knee/2 and threshold+knee/2. @see kneeShapes */ void setKneeShape(int newKneeShape); //--------------------------------------------------------------------------------------------- // audio processing: /** Calculates one output stereo sample-frame at a time. */ INLINE void getSampleFrameStereo(double *inOutL, double *inOutR); //============================================================================================= /** Returns the value of the transfer curve at a given x - x is assumed to be the current amplitude (envelope) of some signal, expressed in dB. */ INLINE double transferCurveAt(double x); protected: /** Computes the polynomial coefficients. */ void calculateCoefficients(); /** Calculates the polynomial coefficients for the quartic transition. */ void calculateQuarticCoefficients(); /** Calculates the polynomial coefficients for the cubic transition. */ void calculateCubicCoefficients(); double a0, a1, a2, a3, a4; // polynomial coefficients double driveFactor, dc, outputGainFactor, amount, threshold, ratio, oneOverRatio, kneeWidth; int kneeShape; bool clipperMode; }; //----------------------------------------------------------------------------------------------- // from here: definitions of the functions to be inlined, i.e. all functions which are supposed // to be called at audio-rate (they can't be put into the .cpp file): INLINE double CompShaper::transferCurveAt(double x) { double xs = RAPT::rsSign(x); double xa = fabs(x); if( xa < threshold-0.5*kneeWidth*0.01*threshold ) return x; else if( xa > threshold+0.5*kneeWidth*0.01*threshold ) { if( clipperMode ) return xs * threshold; else return xs * (threshold + oneOverRatio * (xa-threshold)); } else return xs * RAPT::rsEvaluateQuartic(xa, a0, a1, a2, a3, a4); } INLINE void CompShaper::getSampleFrameStereo(double *inOutL, double *inOutR) { double tmpL = driveFactor * (*inOutL) + dc; double tmpR = driveFactor * (*inOutR) + dc; tmpL = transferCurveAt(tmpL); tmpR = transferCurveAt(tmpR); *inOutL = tmpL; *inOutR = tmpR; } } // end namespace rosic #endif // #ifndef rosic_CompShaper_h
33
114
0.612293
[ "shape" ]
26a5924ec307f4c499ad792586267f890e8b1fe4
6,263
h
C
indra/newview/llgesturemgr.h
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
indra/newview/llgesturemgr.h
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
indra/newview/llgesturemgr.h
humbletim/archived-casviewer
3b51b1baae7e7cebf1c7dca62d9c02751709ee57
[ "Unlicense" ]
null
null
null
/** * @file llgesturemgr.h * @brief Manager for playing gestures on the viewer * * $LicenseInfo:firstyear=2004&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLGESTUREMGR_H #define LL_LLGESTUREMGR_H #include <map> #include <string> #include <vector> #include "llassetstorage.h" // LLAssetType #include "llinventoryobserver.h" #include "llsingleton.h" #include "llviewerinventory.h" class LLMultiGesture; class LLGestureListener; class LLGestureStep; class LLUUID; class LLVFS; class LLGestureManagerObserver { public: virtual ~LLGestureManagerObserver() { }; virtual void changed() = 0; }; class LLGestureMgr : public LLSingleton<LLGestureMgr>, public LLInventoryFetchItemsObserver { public: typedef boost::function<void (LLMultiGesture* loaded_gesture)> gesture_loaded_callback_t; // Maps inventory item_id to gesture typedef std::map<LLUUID, LLMultiGesture*> item_map_t; typedef std::map<LLUUID, gesture_loaded_callback_t> callback_map_t; LLGestureMgr(); ~LLGestureMgr(); void init(); // Call once per frame to manage gestures void update(); // Loads a gesture out of inventory into the in-memory active form // Note that the inventory item must exist, so we can look up the // asset id. void activateGesture(const LLUUID& item_id); // Activate a list of gestures void activateGestures(LLViewerInventoryItem::item_array_t& items); // If you change a gesture, you need to build a new multigesture // and call this method. void replaceGesture(const LLUUID& item_id, LLMultiGesture* new_gesture, const LLUUID& asset_id); void replaceGesture(const LLUUID& item_id, const LLUUID& asset_id); // Load gesture into in-memory active form. // Can be called even if the inventory item isn't loaded yet. // inform_server TRUE will send message upstream to update database // user_gesture_active table, which isn't necessary on login. // deactivate_similar will cause other gestures with the same trigger phrase // or keybinding to be deactivated. void activateGestureWithAsset(const LLUUID& item_id, const LLUUID& asset_id, BOOL inform_server, BOOL deactivate_similar); // Takes gesture out of active list and deletes it. void deactivateGesture(const LLUUID& item_id); // Deactivates all gestures that match either this trigger phrase, // or this hot key. void deactivateSimilarGestures(LLMultiGesture* gesture, const LLUUID& in_item_id); BOOL isGestureActive(const LLUUID& item_id); BOOL isGesturePlaying(const LLUUID& item_id); BOOL isGesturePlaying(LLMultiGesture* gesture); const item_map_t& getActiveGestures() const { return mActive; } // Force a gesture to be played, for example, if it is being // previewed. void playGesture(LLMultiGesture* gesture); void playGesture(const LLUUID& item_id); // Stop all requested or playing anims for this gesture // Also remove from playing list void stopGesture(LLMultiGesture* gesture); void stopGesture(const LLUUID& item_id); /** * Add cb into callbackMap. * Note: * Manager will call cb after gesture will be loaded and will remove cb automatically. */ void setGestureLoadedCallback(LLUUID inv_item_id, gesture_loaded_callback_t cb) { mCallbackMap[inv_item_id] = cb; } // Trigger the first gesture that matches this key. // Returns TRUE if it finds a gesture bound to that key. BOOL triggerGesture(KEY key, MASK mask); // Trigger all gestures referenced as substrings in this string BOOL triggerAndReviseString(const std::string &str, std::string *revised_string = NULL); // Does some gesture have this key bound? BOOL isKeyBound(KEY key, MASK mask); S32 getPlayingCount() const; void addObserver(LLGestureManagerObserver* observer); void removeObserver(LLGestureManagerObserver* observer); void notifyObservers(); // Overriding so we can update active gesture names and notify observers void changed(U32 mask); BOOL matchPrefix(const std::string& in_str, std::string* out_str); // Copy item ids into the vector void getItemIDs(uuid_vec_t* ids); protected: // Handle the processing of a single gesture void stepGesture(LLMultiGesture* gesture); // Do a single step in a gesture void runStep(LLMultiGesture* gesture, LLGestureStep* step); // LLInventoryCompletionObserver trigger void done(); // Used by loadGesture static void onLoadComplete(LLVFS *vfs, const LLUUID& asset_uuid, LLAssetType::EType type, void* user_data, S32 status, LLExtStat ext_status); // Used by playGesture to load an asset file // required to play a gesture step static void onAssetLoadComplete(LLVFS *vfs, const LLUUID& asset_uuid, LLAssetType::EType type, void* user_data, S32 status, LLExtStat ext_status); // Checks whether all animation and sound assets // needed to play a gesture are loaded. static bool hasLoadingAssets(LLMultiGesture* gesture); private: // Active gestures. // NOTE: The gesture pointer CAN BE NULL. This means that // there is a gesture with that item_id, but the asset data // is still on its way down from the server. item_map_t mActive; S32 mLoadingCount; std::string mDeactivateSimilarNames; std::vector<LLGestureManagerObserver*> mObservers; callback_map_t mCallbackMap; std::vector<LLMultiGesture*> mPlaying; BOOL mValid; std::set<LLUUID> mLoadingAssets; // LLEventHost interface boost::shared_ptr<LLGestureListener> mListener; }; #endif
32.117949
123
0.758582
[ "vector" ]
26a6d2443a97a284f62cc5ada3fd077fa945227d
6,040
h
C
Pods/Headers/Public/ShareSDK2/AGCommon/CMGridView.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/ShareSDK2/AGCommon/CMGridView.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/ShareSDK2/AGCommon/CMGridView.h
binghuizi/LessionBook
97dded66db7e80337c5c9bb53eaf54f11abe72a7
[ "Apache-2.0" ]
null
null
null
#import <UIKit/UIKit.h> #import "ICMGridItemView.h" @class CMGridView; ///#begin zh-cn /** * @brief 表格视图委托 */ ///#end ///#begin en /** * @brief Grid view delegate. */ ///#end @protocol CMGridViewDelegate <NSObject> @required ///#begin zh-cn /** * @brief 表格项渲染 * * @param gridView 表格视图 * @param itemRenderer 表格项渲染器 * @param itemData 表格项数据 * @param index 位置索引 */ ///#end ///#begin en /** * @brief Grid item renderer. * * @param gridView Grid view. * @param itemRenderer Item renderer. * @param itemData Item data. * @param index Index. */ ///#end - (void)gridView:(CMGridView *)gridView itemRenderer:(UIView<ICMGridItemView> *)itemRenderer itemData:(id)itemData index:(NSInteger)index; @optional ///#begin zh-cn /** * @brief 表格视图滚动 * * @param gridView 表格视图 */ ///#end ///#begin en /** * @brief View did scroll * * @param gridView Grid view. */ ///#end - (void)gridViewDidScroll:(CMGridView *)gridView; ///#begin zh-cn /** * @brief 表格视图停止拖动 * * @param gridView 表格视图 * @param decelerate 减速运动标识,YES表示进行减速运动,否则不进行减速运动 */ ///#end ///#begin en /** * @brief View did end dragging. * * @param gridView Grid view object. * @param decelerate Deceleration flag, YES indicates deceleration movement, or not decelerating motion */ ///#end - (void)gridViewDidEndDragging:(CMGridView *)gridView willDecelerate:(BOOL)decelerate; ///#begin zh-cn /** * @brief 表格视图页脚将要显示 * * @param gridView 表格视图 * @param cell 页脚项 */ ///#end ///#begin en /** * @brief Footer will display. * * @param gridView Grid view object. * @param cell Footer cell. */ ///#end - (void)gridView:(CMGridView *)gridView footerWillDisplay:(UITableViewCell *)cell; ///#begin zh-cn /** * @brief 表格视图页脚被选中 * * @param gridView 表格视图 * @param cell 页脚项 */ ///#end ///#begin en /** * @brief Footer did selected. * * @param gridView Grid view object. * @param cell Footer cell. */ ///#end - (void)gridView:(CMGridView *)gridView footerDidSelected:(UITableViewCell *)cell; @end ///#begin zh-cn /** * @brief 表格视图 */ ///#end ///#begin en /** * @brief Grid View. */ ///#end @interface CMGridView : UIView <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate> { @private UITableView *_tableView; Class _itemType; Class _footerType; NSArray *_dataArray; NSInteger _iColumnCount; NSInteger _iRowCount; CGFloat _fLeftPadding; CGFloat _fRightPadding; CGFloat _fTopPadding; CGFloat _fBottomPadding; CGFloat _fHorizontalGap; CGFloat _fVerticalGap; CGSize _itemSize; id _delegate; } ///#begin zh-cn /** * @brief 列表数据. */ ///#end ///#begin en /** * @brief Data array. */ ///#end @property (nonatomic,retain) NSArray *dataArray; ///#begin zh-cn /** * @brief 列表项类型 */ ///#end ///#begin en /** * @brief Item class */ ///#end @property (nonatomic,assign) Class itemType; ///#begin zh-cn /** * @brief 列表项大小 */ ///#end ///#begin en /** * @brief Item size. */ ///#end @property (nonatomic,assign) CGSize itemSize; ///#begin zh-cn /** * @brief 滚动标识 */ ///#end ///#begin en /** * @brief Scroll enable. */ ///#end @property (nonatomic) BOOL scrollEnable; ///#begin zh-cn /** * @brief 左边距 */ ///#end ///#begin en /** * @brief Left padding. */ ///#end @property (nonatomic,readonly) CGFloat fLeftPadding; ///#begin zh-cn /** * @brief 右边距 */ ///#end ///#begin en /** * @brief Right padding. */ ///#end @property (nonatomic,readonly) CGFloat fRightPadding; ///#begin zh-cn /** * @brief 顶部边距 */ ///#end ///#begin en /** * @brief Top padding. */ ///#end @property (nonatomic,readonly) CGFloat fTopPadding; ///#begin zh-cn /** * @brief 底部边距 */ ///#end ///#begin en /** * @brief Bottom padding */ ///#end @property (nonatomic,readonly) CGFloat fBottomPadding; ///#begin zh-cn /** * @brief 水平间距 */ ///#end ///#begin en /** * @brief Horizontal gap */ ///#end @property (nonatomic,readonly) CGFloat fHorizontalGap; ///#begin zh-cn /** * @brief 垂直间距 */ ///#end ///#begin en /** * @brief Vertical gap. */ ///#end @property (nonatomic,readonly) CGFloat fVerticalGap; ///#begin zh-cn /** * @brief 内容偏移量 */ ///#end ///#begin en /** * @brief Content inset. */ ///#end @property (nonatomic) UIEdgeInsets contentInset; ///#begin zh-cn /** * @brief 委托对象 */ ///#end ///#begin en /** * @brief Delegate object. */ ///#end @property (nonatomic,assign) id<CMGridViewDelegate> delegate; ///#begin zh-cn /** * @brief 内容视图 */ ///#end ///#begin en /** * @brief Content view. */ ///#end @property (nonatomic,readonly) UITableView *contentView; ///#begin zh-cn /** * @brief 页脚类型,如果为nil则不显示页脚 */ ///#end ///#begin en /** * @brief Footer class,If nil is not displayed footer */ ///#end @property (nonatomic,assign) Class footerType; ///#begin zh-cn /** * @brief 设置表格边距及间距 * * @param topPadding 顶部边距 * @param rightPadding 右边距 * @param bottomPadding 底部边距 * @param leftPadding 左边距 * @param hGap 水平间距 * @param vGap 垂直间距 */ ///#end ///#begin en /** * @brief Set grid padding and spacing * * @param topPadding Top padding * @param rightPadding Right padding * @param bottomPadding Bottom padding * @param leftPadding Left padding * @param hGap Horizontal gap * @param vGap Vertical gap */ ///#end - (void)setGridTopPadding:(CGFloat)topPadding rightPadding:(CGFloat)rightPadding bottomPadding:(CGFloat)bottomPadding leftPadding:(CGFloat)leftPadding hGap:(CGFloat)hGap vGap:(CGFloat)vGap; ///#begin zh-cn /** * @brief 出队一个尚未使用的单元格 * * @param identifier 引用标识 * * @return 单元格对象,如果没有尚未使用的则返回nil */ ///#end ///#begin en /** * @brief Dequeue a reusable cell. * * @param identifier Cell identifier. * * @return Cell object. If you has not reusable cell return nil */ ///#end - (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; @end
15.56701
105
0.618543
[ "object" ]
26af1ff75e16a3d543644d03ab0675a29f91b470
1,820
h
C
tesseract/tesseract_geometry/include/tesseract_geometry/impl/capsule.h
steviedale/tesseract
745a50fca2f7b2ef12458a8da1bb612fb5cd74af
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
tesseract/tesseract_geometry/include/tesseract_geometry/impl/capsule.h
steviedale/tesseract
745a50fca2f7b2ef12458a8da1bb612fb5cd74af
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
tesseract/tesseract_geometry/include/tesseract_geometry/impl/capsule.h
steviedale/tesseract
745a50fca2f7b2ef12458a8da1bb612fb5cd74af
[ "Apache-2.0", "BSD-2-Clause" ]
null
null
null
/** * @file capsule.h * @brief Tesseract Capsule Geometry * * @author Levi Armstrong * @date January 18, 2018 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2017, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 TESSERACT_GEOMETRY_CAPSULE_H #define TESSERACT_GEOMETRY_CAPSULE_H #include <tesseract_common/macros.h> TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include <memory> TESSERACT_COMMON_IGNORE_WARNINGS_POP #include <tesseract_geometry/geometry.h> namespace tesseract_geometry { class Capsule : public Geometry { public: using Ptr = std::shared_ptr<Capsule>; using ConstPtr = std::shared_ptr<const Capsule>; Capsule(double r, double l) : Geometry(GeometryType::CAPSULE), r_(r), l_(l) {} ~Capsule() override = default; Capsule(const Capsule&) = delete; Capsule& operator=(const Capsule&) = delete; Capsule(Capsule&&) = delete; Capsule& operator=(Capsule&&) = delete; double getRadius() const { return r_; } double getLength() const { return l_; } Geometry::Ptr clone() const override { return std::make_shared<Capsule>(r_, l_); } private: double r_; double l_; }; } // namespace tesseract_geometry #endif // TESSERACT_GEOMETRY_CAPSULE_H
28.888889
84
0.738462
[ "geometry" ]
26b16446c2dbb742e102ac23da1a2c5f65ca784b
19,468
c
C
device/sensor/drv/drv_mag_bosch_bmm150.c
jinlongliu/AliOS-Things
ce051172a775f987183e7aca88bb6f3b809ea7b0
[ "Apache-2.0" ]
3
2018-12-14T08:14:14.000Z
2021-05-24T14:46:01.000Z
device/sensor/drv/drv_mag_bosch_bmm150.c
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
3
2018-12-17T13:06:46.000Z
2018-12-28T01:40:59.000Z
device/sensor/drv/drv_mag_bosch_bmm150.c
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
2
2018-01-23T07:54:08.000Z
2018-01-23T11:38:59.000Z
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited * * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <aos/aos.h> #include <vfs_conf.h> #include <vfs_err.h> #include <vfs_register.h> #include <hal/base.h> #include "common.h" #include "sensor.h" #include "sensor_drv_api.h" #include "sensor_hal.h" #define BMM150_I2C_ADDR1 (0x10<<1) #define BMM150_I2C_ADDR2 (0x11 << 1) #define BMM150_I2C_ADDR3 (0x12 << 1) #define BMM150_I2C_ADDR4 (0x13 << 1) #define BMM150_CHIP_ID_ADDR (0X40) #define BMM150_CHIP_ID_VALUE (0X32) #define BMM150_OP_MODE_ADDR (0x4C) #define BMM150_DATA_X_LSB (0x42) #define BMM150_ODR_ADDR_POS (3) #define BMM150_ODR_ADDR_LEN (3) #define BMM150_ODR_ADDR_MSK (0x31) #define BMM150_ODR_ADDR_REG (BMM150_OP_MODE_ADDR) #define BMM150_POWER_MODE_POS (1) #define BMM150_POWER_MODE_LEN (2) #define BMM150_POWER_MODE_MSK (0xf9) #define BMM150_POWER_MODE_REG (BMM150_OP_MODE_ADDR) #define BMM150_POWER_MODE_NORMAL (0X0) #define BMM150_POWER_MODE_SLEEP (0X3) #define BMM150_POWER_MODE_OFF (0X3) #define BMM150_ODR_2 (2) #define BMM150_ODR_6 (6) #define BMM150_ODR_8 (8) #define BMM150_ODR_10 (10) #define BMM150_ODR_15 (15) #define BMM150_ODR_20 (20) #define BMM150_ODR_25 (25) #define BMM150_ODR_30 (30) #define BMM150_ODR_2_REG (0x1) #define BMM150_ODR_6_REG (0x2) #define BMM150_ODR_8_REG (0x3) #define BMM150_ODR_10_REG (0x0) #define BMM150_ODR_15_REG (0x4) #define BMM150_ODR_20_REG (0x5) #define BMM150_ODR_25_REG (0x6) #define BMM150_ODR_30_REG (0x7) #define BMM150_DIG_X1 (0x5D) #define BMM150_DIG_Y1 (0x5E) #define BMM150_DIG_Z4_LSB (0x62) #define BMM150_DIG_Z4_MSB (0x63) #define BMM150_DIG_X2 (0x64) #define BMM150_DIG_Y2 (0x65) #define BMM150_DIG_Z2_LSB (0x68) #define BMM150_DIG_Z2_MSB (0x69) #define BMM150_DIG_Z1_LSB (0x6A) #define BMM150_DIG_Z1_MSB (0x6B) #define BMM150_DIG_XYZ1_LSB (0x6C) #define BMM150_DIG_XYZ1_MSB (0x6D) #define BMM150_DIG_Z3_LSB (0x6E) #define BMM150_DIG_Z3_MSB (0x6F) #define BMM150_DIG_XY2 (0x70) #define BMM150_DIG_XY1 (0x71) #define BMM150_DATA_X_MSK (0xF8) #define BMM150_DATA_X_POS (0x03) #define BMM150_DATA_Y_MSK (0xF8) #define BMM150_DATA_Y_POS (0x03) #define BMM150_DATA_Z_MSK (0xFE) #define BMM150_DATA_Z_POS (0x01) #define BMM150_DATA_RHALL_MSK (0xFC) #define BMM150_DATA_RHALL_POS (0x02) #define BMM150_DATA_UT_2_MG (10) #define BMM150_OVERFLOW_OUTPUT (-32768) #define BMM150_NEGATIVE_SATURATION_Z (-32767) #define BMM150_POSITIVE_SATURATION_Z (32767) #define BMM150_XYAXES_FLIP_OVERFLOW_ADCVAL (-4096) #define BMM150_ZAXIS_HALL_OVERFLOW_ADCVAL (-16384) #define BMM150_GET_BITSLICE(regvar, bitname) \ ((regvar & bitname##_MSK) >> bitname##_POS) #define BMM150_SET_BITSLICE(regvar, bitname, val) \ ((regvar & (~bitname##_MSK)) | ((val << bitname##_POS) & bitname##_MSK)) typedef struct bmm150_trim_registers { int8_t dig_x1; int8_t dig_y1; int8_t dig_x2; int8_t dig_y2; uint16_t dig_z1; int16_t dig_z2; int16_t dig_z3; int16_t dig_z4; uint8_t dig_xy1; int8_t dig_xy2; uint16_t dig_xyz1; }bmm150_trim_reg_st; bmm150_trim_reg_st g_bmm150_trim_reg = {0}; i2c_dev_t bmm150_ctx = { .port = 3, .config.address_width = 8, .config.freq = 400000, .config.dev_addr = BMM150_I2C_ADDR1, }; int drv_mag_bosch_bmm150_validate_id(i2c_dev_t *drv, uint8_t id_value) { uint8_t value = 0x00; int ret = 0; if (drv == NULL) { return -1; } ret = sensor_i2c_read(drv, BMM150_CHIP_ID_ADDR, &value, I2C_DATA_LEN, I2C_OP_RETRIES); if (unlikely(ret)) { return ret; } if (id_value != value) { return -1; } return 0; } int drv_mag_bosch_bmm150_set_power_mode(i2c_dev_t * drv, dev_power_mode_e mode) { uint8_t value = 0x00; uint8_t value1 = 0x00; int ret = 0; ret = sensor_i2c_read(drv, BMM150_POWER_MODE_REG, &value, I2C_DATA_LEN, I2C_OP_RETRIES); if (unlikely(ret)) { return ret; } switch (mode) { case DEV_POWER_ON: { ret = sensor_i2c_read(drv, 0x4b, &value1, I2C_DATA_LEN, I2C_OP_RETRIES); value1 |= 1; ret = sensor_i2c_write(drv, 0x4b, &value1, I2C_DATA_LEN, I2C_OP_RETRIES); aos_msleep(1); value = BMM150_SET_BITSLICE(value,BMM150_POWER_MODE,BMM150_POWER_MODE_NORMAL); } break; case DEV_POWER_OFF: { value = BMM150_SET_BITSLICE(value,BMM150_POWER_MODE,BMM150_POWER_MODE_OFF); } break; case DEV_SLEEP: { value = BMM150_SET_BITSLICE(value,BMM150_POWER_MODE,BMM150_POWER_MODE_OFF); } break; default: return -1; } ret = sensor_i2c_write(drv, BMM150_POWER_MODE_REG, &value, I2C_DATA_LEN, I2C_OP_RETRIES); if (unlikely(ret)) { return ret; } return 0; } int drv_mag_bosch_bmm150_set_odr(i2c_dev_t *drv, uint32_t odr) { int ret = 0; uint8_t value = 0x00; ret = sensor_i2c_read(drv, BMM150_ODR_ADDR_REG, &value, I2C_DATA_LEN, I2C_OP_RETRIES); if (unlikely(ret)) { return ret; } if (odr >= BMM150_ODR_30) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_30_REG); } else if (odr >= BMM150_ODR_25) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_25_REG); } else if (odr >= BMM150_ODR_20) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_20_REG); } else if (odr >= BMM150_ODR_15) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_15_REG); } else if (odr >= BMM150_ODR_10) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_10_REG); } else if (odr >= BMM150_ODR_8) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_8_REG); } else if (odr >= BMM150_ODR_6) { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_6_REG); } else { value = BMM150_SET_BITSLICE(value,BMM150_ODR_ADDR,BMM150_ODR_2_REG); } ret = sensor_i2c_write(drv, BMM150_ODR_ADDR_REG, &value, I2C_DATA_LEN, I2C_OP_RETRIES); if (unlikely(ret)) { return ret; } return 0; } void drv_mag_bosch_bmm150_irq_handle(void) { /* no handle so far */ } int drv_mag_bosch_bmm150_open(void) { int ret = 0; ret = drv_mag_bosch_bmm150_set_power_mode(&bmm150_ctx, DEV_POWER_ON); if (unlikely(ret)) { return -1; } LOG("%s %s successfully \n", SENSOR_STR, __func__); return 0; } int drv_mag_bosch_bmm150_close(void) { int ret = 0; ret = drv_mag_bosch_bmm150_set_power_mode(&bmm150_ctx, DEV_POWER_OFF); if (unlikely(ret)) { return -1; } return 0; } static int16_t drv_mag_bosch_bmm150_compensate_x(int16_t mag_data_x, uint16_t data_rhall) { int16_t retval; uint16_t process_comp_x0 = 0; int32_t process_comp_x1; uint16_t process_comp_x2; int32_t process_comp_x3; int32_t process_comp_x4; int32_t process_comp_x5; int32_t process_comp_x6; int32_t process_comp_x7; int32_t process_comp_x8; int32_t process_comp_x9; int32_t process_comp_x10; /* Overflow condition check */ if (mag_data_x != BMM150_XYAXES_FLIP_OVERFLOW_ADCVAL) { if (data_rhall != 0) { process_comp_x0 = data_rhall; } else if (g_bmm150_trim_reg.dig_xyz1 != 0) { process_comp_x0 = g_bmm150_trim_reg.dig_xyz1; } else { process_comp_x0 = 0; } if (process_comp_x0 != 0) { process_comp_x1 = ((int32_t)g_bmm150_trim_reg.dig_xyz1) * 16384; process_comp_x2 = ((uint16_t)(process_comp_x1 / process_comp_x0)) - ((uint16_t)0x4000); retval = ((int16_t)process_comp_x2); process_comp_x3 = (((int32_t)retval) * ((int32_t)retval)); process_comp_x4 = (((int32_t)g_bmm150_trim_reg.dig_xy2) * (process_comp_x3 / 128)); process_comp_x5 = (int32_t)(((int16_t)g_bmm150_trim_reg.dig_xy1) * 128); process_comp_x6 = ((int32_t)retval) * process_comp_x5; process_comp_x7 = (((process_comp_x4 + process_comp_x6) / 512) + ((int32_t)0x100000)); process_comp_x8 = ((int32_t)(((int16_t)g_bmm150_trim_reg.dig_x2) + ((int16_t)0xA0))); process_comp_x9 = ((process_comp_x7 * process_comp_x8) / 4096); process_comp_x10 = ((int32_t)mag_data_x) * process_comp_x9; retval = ((int16_t)(process_comp_x10 / 8192)); retval = (retval + (((int16_t)g_bmm150_trim_reg.dig_x1) * 8)) / 16; } else { retval = BMM150_OVERFLOW_OUTPUT; } } else { retval = BMM150_OVERFLOW_OUTPUT; } return retval; } static int16_t drv_mag_bosch_bmm150_compensate_y(int16_t mag_data_y, uint16_t data_rhall) { int16_t retval; uint16_t process_comp_y0 = 0; int32_t process_comp_y1; uint16_t process_comp_y2; int32_t process_comp_y3; int32_t process_comp_y4; int32_t process_comp_y5; int32_t process_comp_y6; int32_t process_comp_y7; int32_t process_comp_y8; int32_t process_comp_y9; if (mag_data_y != BMM150_XYAXES_FLIP_OVERFLOW_ADCVAL) { if (data_rhall != 0) { process_comp_y0 = data_rhall; } else if (g_bmm150_trim_reg.dig_xyz1 != 0) { process_comp_y0 = g_bmm150_trim_reg.dig_xyz1; } else { process_comp_y0 = 0; } if (process_comp_y0 != 0) { process_comp_y1 = (((int32_t)g_bmm150_trim_reg.dig_xyz1) * 16384) / process_comp_y0; process_comp_y2 = ((uint16_t)process_comp_y1) - ((uint16_t)0x4000); retval = ((int16_t)process_comp_y2); process_comp_y3 = ((int32_t) retval) * ((int32_t)retval); process_comp_y4 = ((int32_t)g_bmm150_trim_reg.dig_xy2) * (process_comp_y3 / 128); process_comp_y5 = ((int32_t)(((int16_t)g_bmm150_trim_reg.dig_xy1) * 128)); process_comp_y6 = ((process_comp_y4 + (((int32_t)retval) * process_comp_y5)) / 512); process_comp_y7 = ((int32_t)(((int16_t)g_bmm150_trim_reg.dig_y2) + ((int16_t)0xA0))); process_comp_y8 = (((process_comp_y6 + ((int32_t)0x100000)) * process_comp_y7) / 4096); process_comp_y9 = (((int32_t)mag_data_y) * process_comp_y8); retval = (int16_t)(process_comp_y9 / 8192); retval = (retval + (((int16_t)g_bmm150_trim_reg.dig_y1) * 8)) / 16; } else { retval = BMM150_OVERFLOW_OUTPUT; } } else { retval = BMM150_OVERFLOW_OUTPUT; } return retval; } /*! * @brief This internal API is used to obtain the compensated * magnetometer Z axis data(micro-tesla) in int16_t. */ static int16_t drv_mag_bosch_bmm150_compensate_z(int16_t mag_data_z, uint16_t data_rhall) { int32_t retval; int16_t process_comp_z0; int32_t process_comp_z1; int32_t process_comp_z2; int32_t process_comp_z3; int16_t process_comp_z4; if (mag_data_z != BMM150_ZAXIS_HALL_OVERFLOW_ADCVAL) { if ((g_bmm150_trim_reg.dig_z2 != 0) && (g_bmm150_trim_reg.dig_z1 != 0) && (data_rhall != 0) && (g_bmm150_trim_reg.dig_xyz1 != 0)) { /*Processing compensation equations*/ process_comp_z0 = ((int16_t)data_rhall) - ((int16_t) g_bmm150_trim_reg.dig_xyz1); process_comp_z1 = (((int32_t)g_bmm150_trim_reg.dig_z3) * ((int32_t)(process_comp_z0))) / 4; process_comp_z2 = (((int32_t)(mag_data_z - g_bmm150_trim_reg.dig_z4)) * 32768); process_comp_z3 = ((int32_t)g_bmm150_trim_reg.dig_z1) * (((int16_t)data_rhall) * 2); process_comp_z4 = (int16_t)((process_comp_z3 + (32768)) / 65536); retval = ((process_comp_z2 - process_comp_z1) / (g_bmm150_trim_reg.dig_z2 + process_comp_z4)); /* saturate result to +/- 2 micro-tesla */ if (retval > BMM150_POSITIVE_SATURATION_Z) { retval = BMM150_POSITIVE_SATURATION_Z; } else { if (retval < BMM150_NEGATIVE_SATURATION_Z) retval = BMM150_NEGATIVE_SATURATION_Z; } /* Conversion of LSB to micro-tesla*/ retval = retval / 16; } else { retval = BMM150_OVERFLOW_OUTPUT; } } else { /* Overflow condition*/ retval = BMM150_OVERFLOW_OUTPUT; } return (int16_t)retval; } static int8_t drv_mag_bosch_bmm150_read_calib_reg(i2c_dev_t *drv) { int8_t ret; uint8_t trim_x1y1[2] = {0}; uint8_t trim_xyz_data[4] = {0}; uint8_t trim_xy1xy2[10] = {0}; uint16_t temp_msb = 0; ret = sensor_i2c_read(drv, BMM150_DIG_X1, trim_x1y1, 2, I2C_OP_RETRIES); if (unlikely(ret)) { return -1; } ret = sensor_i2c_read(drv, BMM150_DIG_Z4_LSB, trim_xyz_data, 4, I2C_OP_RETRIES); if (unlikely(ret)) { return -1; } ret = sensor_i2c_read(drv, BMM150_DIG_Z2_LSB, trim_xy1xy2, 10, I2C_OP_RETRIES); if (unlikely(ret)) { return -1; } g_bmm150_trim_reg.dig_x1 = (int8_t)trim_x1y1[0]; g_bmm150_trim_reg.dig_y1 = (int8_t)trim_x1y1[1]; g_bmm150_trim_reg.dig_x2 = (int8_t)trim_xyz_data[2]; g_bmm150_trim_reg.dig_y2 = (int8_t)trim_xyz_data[3]; temp_msb = ((uint16_t)trim_xy1xy2[3]) << 8; g_bmm150_trim_reg.dig_z1 = (uint16_t)(temp_msb | trim_xy1xy2[2]); temp_msb = ((uint16_t)trim_xy1xy2[1]) << 8; g_bmm150_trim_reg.dig_z2 = (int16_t)(temp_msb | trim_xy1xy2[0]); temp_msb = ((uint16_t)trim_xy1xy2[7]) << 8; g_bmm150_trim_reg.dig_z3 = (int16_t)(temp_msb | trim_xy1xy2[6]); temp_msb = ((uint16_t)trim_xyz_data[1]) << 8; g_bmm150_trim_reg.dig_z4 = (int16_t)(temp_msb | trim_xyz_data[0]); g_bmm150_trim_reg.dig_xy1 = trim_xy1xy2[9]; g_bmm150_trim_reg.dig_xy2 = (int8_t)trim_xy1xy2[8]; temp_msb = ((uint16_t)(trim_xy1xy2[5] & 0x7F)) << 8; g_bmm150_trim_reg.dig_xyz1 = (uint16_t)(temp_msb | trim_xy1xy2[4]); return ret; } int drv_mag_bosch_bmm150_read(void *buf, size_t len) { int ret = 0; size_t size = 0; uint8_t reg[8]; int16_t msb_data; int16_t raw_datax; int16_t raw_datay; int16_t raw_dataz; uint16_t raw_data_r; mag_data_t *mag = (mag_data_t *)buf; if (mag == NULL) { return -1; } size = sizeof(mag_data_t); if (len < size) { return -1; } ret = sensor_i2c_read(&bmm150_ctx, BMM150_DATA_X_LSB, &reg[0], 8, I2C_OP_RETRIES); if (unlikely(ret)) { return -1; } reg[0] = BMM150_GET_BITSLICE(reg[0], BMM150_DATA_X); msb_data = ((int16_t)((int8_t)reg[1])) * 32; raw_datax = (int16_t)(msb_data | reg[0]); reg[2] = BMM150_GET_BITSLICE(reg[2], BMM150_DATA_Y); msb_data = ((int16_t)((int8_t)reg[3])) * 32; raw_datay = (int16_t)(msb_data | reg[2]); reg[4] = BMM150_GET_BITSLICE(reg[4], BMM150_DATA_Z); msb_data = ((int16_t)((int8_t)reg[5])) * 128; raw_dataz = (int16_t)(msb_data | reg[4]); reg[6] = BMM150_GET_BITSLICE(reg[6], BMM150_DATA_RHALL); raw_data_r = (uint16_t)(((uint16_t)reg[7] << 6) | reg[6]); mag->data[0] = (int32_t)drv_mag_bosch_bmm150_compensate_x(raw_datax, raw_data_r); mag->data[1] = (int32_t)drv_mag_bosch_bmm150_compensate_y(raw_datay, raw_data_r); mag->data[2] = (int32_t)drv_mag_bosch_bmm150_compensate_z(raw_dataz, raw_data_r); mag->data[0] = mag->data[0] * BMM150_DATA_UT_2_MG; mag->data[1] = mag->data[1] * BMM150_DATA_UT_2_MG; mag->data[2] = mag->data[2] * BMM150_DATA_UT_2_MG; mag->timestamp = aos_now_ms(); return (int)size; } static int drv_mag_bosch_bmm150_ioctl(int cmd, unsigned long arg) { int ret = 0; switch (cmd) { case SENSOR_IOCTL_ODR_SET: { ret = drv_mag_bosch_bmm150_set_odr(&bmm150_ctx, arg); if (unlikely(ret)) { return -1; } } break; case SENSOR_IOCTL_RANGE_SET: { } break; case SENSOR_IOCTL_SET_POWER: { ret = drv_mag_bosch_bmm150_set_power_mode(&bmm150_ctx, arg); if (unlikely(ret)) { return -1; } } break; case SENSOR_IOCTL_GET_INFO: { /* fill the dev info here */ dev_sensor_info_t *info = (dev_sensor_info_t *)arg; info->model = "BMM150"; info->range_max = 2500; info->range_min = 2500; info->unit = udps; } break; default: break; } return 0; } int drv_mag_bosch_bmm150_init(void) { int ret = 0; sensor_obj_t sensor; memset(&sensor, 0, sizeof(sensor)); /* fill the sensor obj parameters here */ sensor.io_port = I2C_PORT; sensor.tag = TAG_DEV_MAG; sensor.path = dev_mag_path; sensor.open = drv_mag_bosch_bmm150_open; sensor.close = drv_mag_bosch_bmm150_close; sensor.read = drv_mag_bosch_bmm150_read; sensor.write = NULL; sensor.ioctl = drv_mag_bosch_bmm150_ioctl; sensor.irq_handle = drv_mag_bosch_bmm150_irq_handle; ret = sensor_create_obj(&sensor); if (unlikely(ret)) { return -1; } ret = drv_mag_bosch_bmm150_set_power_mode(&bmm150_ctx, DEV_POWER_ON); if (unlikely(ret)) { return -1; } aos_msleep(10); ret = drv_mag_bosch_bmm150_validate_id(&bmm150_ctx, BMM150_CHIP_ID_VALUE); if (unlikely(ret)) { return -1; } ret = drv_mag_bosch_bmm150_set_odr(&bmm150_ctx, 2); if (unlikely(ret)) { return -1; } memset(&g_bmm150_trim_reg, 0, sizeof(g_bmm150_trim_reg)); ret = drv_mag_bosch_bmm150_read_calib_reg(&bmm150_ctx); if (unlikely(ret)) { return -1; } /* update the phy sensor info to sensor hal */ LOG("%s %s successfully \n", SENSOR_STR, __func__); return 0; }
32.609715
99
0.6034
[ "model" ]
26b61523a88155d2752b5ab77cbf38e00ab57143
2,780
h
C
multiresmarchingcubes.h
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
multiresmarchingcubes.h
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
multiresmarchingcubes.h
avinfinity/UnmanagedCodeSnippets
2bd848db88d7b271209ad30017c8f62307319be3
[ "MIT" ]
null
null
null
#ifndef __IMT_MULTIRESMARCHINGCUBES_H__ #define __IMT_MULTIRESMARCHINGCUBES_H__ #include "volumeinfo.h" namespace imt { namespace volume { class MultiResMarchingCubes { public: MultiResMarchingCubes( imt::volume::VolumeInfo& volume , int isoThreshold , int maxLevel ); void compute(); protected: struct EdgeInfo { int edgeType; int edgeId; int64_t trianglePointId; Eigen::Vector3f coords; }; class GradientCalculator { public: GradientCalculator(int64_t width, int64_t height, int64_t depth, unsigned short* volumeData); void computeGradient(float x, float y, float z, Eigen::Vector3f& gradient); float valueAt(float x, float y, float z); protected: int64_t _Width, _Height, _Depth; int64_t _ZStep, _YStep; unsigned short *_VolumeData; int _KernelGx[3][3][3], _KernelGy[3][3][3], _KernelGz[3][3][3]; }; //sample corners at resolution level 2 void sampleCorners2( int x , int y , int z, std::vector<float>& grayValues); //sample corners at resolution level 1 void sampleCorners1( int x , int y , int z, std::vector<float>& grayValues); //sample corners at resolution level 0 void sampleCorners( int x , int y , int z, std::vector<float>& grayValues , int step = 1); void sampleCornersFromReinterpolatedSlices(int x, int y, int z, float* reinterpolatedSlices, std::vector<float>& grayValues, int step = 1); double grayValueAtCorner(int x, int y, int z); void createSurface( std::vector< float > &leaf_node, Eigen::Vector3i &index_3d , std::vector<Eigen::Vector3f> &cloud , std::vector<EdgeInfo>& edgeInfos , int step = 1 ); void interpolateEdge( Eigen::Vector3f &p1 , Eigen::Vector3f &p2, float val_p1 , float val_p2 , Eigen::Vector3f &output); void interpolateEdgeX(Eigen::Vector3i& voxelPosition, float val_p1, float val_p2, Eigen::Vector3f &output, int step = 1); void interpolateEdgeY(Eigen::Vector3i& voxelPosition, float val_p1, float val_p2, Eigen::Vector3f &output, int step = 1); void interpolateEdgeZ(Eigen::Vector3i& voxelPosition, float val_p1, float val_p2, Eigen::Vector3f &output, int step = 1); void reinterpolateSlices( int z , int strip , float *reinterpolatedSlices ); protected: void mergeDuplicateVertices(std::vector< MultiResMarchingCubes::EdgeInfo >& edgeInfos, std::vector<Eigen::Vector3f>& surfaceVertices , std::vector<unsigned int>& surfaceIndices , std::vector<Eigen::Vector3f>& mergedVertices ); protected: imt::volume::VolumeInfo& _Volume; int _IsoThreshold , _MaxLevel; int64_t _ZStep, _YStep; double _VolumeReductionCoefficient; unsigned short *_VolumeData; }; } } #endif
22.063492
229
0.692086
[ "vector" ]
26b7d2ea4a9e5bd5fa06b91d5006938139492e37
1,450
h
C
src/Bosskey.h
sudoec/iEdge
2e7895cab79d0ab5bc3676d5d9fe3be60e804d09
[ "MIT" ]
null
null
null
src/Bosskey.h
sudoec/iEdge
2e7895cab79d0ab5bc3676d5d9fe3be60e804d09
[ "MIT" ]
null
null
null
src/Bosskey.h
sudoec/iEdge
2e7895cab79d0ab5bc3676d5d9fe3be60e804d09
[ "MIT" ]
null
null
null
#include "Parsekeys.h" static bool is_hide = false; static std::vector <HWND> hwnd_list; BOOL CALLBACK SearchChromeWindow(HWND hWnd, LPARAM lParam) { //隐藏 if(IsWindowVisible(hWnd)) { wchar_t buff[256]; GetClassNameW(hWnd, buff, 255); if ( wcscmp(buff, L"Chrome_WidgetWin_1")==0 )// || wcscmp(buff, L"Chrome_WidgetWin_2")==0 || wcscmp(buff, L"SysShadow")==0 ) { ShowWindow(hWnd, SW_HIDE); hwnd_list.push_back(hWnd); } } return true; } void OnBosskey() { if(!is_hide) { EnumWindows(SearchChromeWindow, 0); } else { for (auto r_iter = hwnd_list.rbegin(); r_iter != hwnd_list.rend() ; r_iter++) { ShowWindow(*r_iter, SW_SHOW); } hwnd_list.clear(); } is_hide = !is_hide; } void HotKeyRegister(LPARAM lParam) { RegisterHotKey(NULL, 0, LOWORD(lParam), HIWORD(lParam)); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { if (msg.message == WM_HOTKEY) { OnBosskey(); } TranslateMessage(&msg); DispatchMessage(&msg); } } bool Bosskey(const wchar_t *iniPath) { wchar_t keys[256]; GetPrivateProfileStringW(L"基本设置", L"老板键", L"", keys, 256, iniPath); if(keys[0]) { UINT flag = ParseHotkeys(keys); std::thread th(HotKeyRegister, flag); th.detach(); } return keys[0]!='\0'; }
21.014493
132
0.562759
[ "vector" ]
26b8469ab2f85ad93ffbb3fac7684c472af051f2
34,143
h
C
dev/Code/CryEngine/CryAction/IGameObject.h
stickyparticles/lumberyard
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
2
2018-03-29T10:56:36.000Z
2020-12-12T15:28:14.000Z
dev/Code/CryEngine/CryAction/IGameObject.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/CryEngine/CryAction/IGameObject.h
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
3
2019-05-13T09:41:33.000Z
2021-04-09T12:12:38.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_CRYACTION_IGAMEOBJECT_H #define CRYINCLUDE_CRYACTION_IGAMEOBJECT_H #pragma once // FIXME: Cell SDK GCC bug workaround. #ifndef CRYINCLUDE_IGAMEOBJECTSYSTEM_H #include "IGameObjectSystem.h" #endif #define GAME_OBJECT_SUPPORTS_CUSTOM_USER_DATA 1 #include <IComponent.h> #include "SerializeFwd.h" #include "IActionMapManager.h" #include "PoolAllocator.h" #include "IFlowSystem.h" #include "StringUtils.h" #include "CryFixedArray.h" #include "GameWarning.h" struct IGameObjectExtension; struct IGameObjectView; struct IActionListener; struct IMovementController; struct IGameObjectProfileManager; struct IWorldQuery; enum EEntityAspects { eEA_All = NET_ASPECT_ALL, #define ADD_ASPECT(x, y) x = BIT(y), #include "../CryNetwork/GridMate/Compatibility/GridMateNetSerializeAspects.inl" #undef ADD_ASPECT }; enum EEntityPhysicsEvents { eEPE_OnCollisionLogged = 1 << 0, // Logged events on lower byte. eEPE_OnPostStepLogged = 1 << 1, eEPE_OnStateChangeLogged = 1 << 2, eEPE_OnCreateEntityPartLogged = 1 << 3, eEPE_OnUpdateMeshLogged = 1 << 4, eEPE_AllLogged = eEPE_OnCollisionLogged | eEPE_OnPostStepLogged | eEPE_OnStateChangeLogged | eEPE_OnCreateEntityPartLogged | eEPE_OnUpdateMeshLogged, eEPE_OnCollisionImmediate = 1 << 8, // Immediate events on higher byte. eEPE_OnPostStepImmediate = 1 << 9, eEPE_OnStateChangeImmediate = 1 << 10, eEPE_OnCreateEntityPartImmediate = 1 << 11, eEPE_OnUpdateMeshImmediate = 1 << 12, eEPE_AllImmediate = eEPE_OnCollisionImmediate | eEPE_OnPostStepImmediate | eEPE_OnStateChangeImmediate | eEPE_OnCreateEntityPartImmediate | eEPE_OnUpdateMeshImmediate, }; static const int MAX_UPDATE_SLOTS_PER_EXTENSION = 5; enum ERMInvocation { eRMI_ToClientChannel = 0x01, // Send RMI from server to a specific client eRMI_ToOwningClient = 0x04, // Send RMI from server to client that owns the actor eRMI_ToOtherClients = 0x08, // Send RMI from server to all clients except the specified client eRMI_ToOtherRemoteClients = 0x10, // Send RMI from server to all remote clients except the specified client eRMI_ToAllClients = 0x20, // Send RMI from server to all clients eRMI_ToServer = 0x100, // Send RMI from client to server eRMI_NoLocalCalls = 0x1000, // For internal use only // IMPORTANT: Using the RMI shim through GridMate, do not exceed 16 bits or flags will be lost in transit. eRMI_ToRemoteClients = eRMI_NoLocalCalls | eRMI_ToAllClients, // Send RMI from server to all remote clients // Mask aggregating all bits that require dispatching to non-server clients. eRMI_ClientsMask = eRMI_ToAllClients | eRMI_ToOtherClients | eRMI_ToOtherRemoteClients | eRMI_ToOwningClient | eRMI_ToClientChannel, }; enum EUpdateEnableCondition { eUEC_Never, eUEC_Always, eUEC_Visible, eUEC_InRange, eUEC_VisibleAndInRange, eUEC_VisibleOrInRange, eUEC_VisibleOrInRangeIgnoreAI, eUEC_VisibleIgnoreAI, eUEC_WithoutAI, }; enum EPrePhysicsUpdate { ePPU_Never, ePPU_Always, ePPU_WhenAIActivated }; enum EGameObjectAIActivationMode { eGOAIAM_Never, eGOAIAM_Always, eGOAIAM_VisibleOrInRange, // Must be last. eGOAIAM_COUNT_STATES, }; enum EAutoDisablePhysicsMode { eADPM_Never, eADPM_WhenAIDeactivated, eADPM_WhenInvisibleAndFarAway, // Must be last. eADPM_COUNT_STATES, }; enum EBindToNetworkMode { eBTNM_Normal, eBTNM_Force, eBTNM_NowInitialized }; struct SGameObjectExtensionRMI { void GetMemoryUsage(ICrySizer* pSizer) const{} typedef struct INetAtSyncItem* (* DecoderFunction)(TSerialize, EntityId*, struct INetChannel*); DecoderFunction decoder; const char* description; const void* pBase; const struct SNetMessageDef* pMsgDef; ERMIAttachmentType attach; bool isServerCall; bool lowDelay; ENetReliabilityType reliability; }; template <size_t N> class CRMIAllocator { public: static ILINE void* Allocate() { ScopedSwitchToGlobalHeap useGlobalHeap; if (!m_pAllocator) { m_pAllocator = new stl::PoolAllocator<N>; } return m_pAllocator->Allocate(); } static ILINE void Deallocate(void* p) { CRY_ASSERT(m_pAllocator); m_pAllocator->Deallocate(p); } private: static stl::PoolAllocator<N>* m_pAllocator; }; template <size_t N> stl::PoolAllocator<N>* CRMIAllocator<N>::m_pAllocator = 0; // Summary // Interface used to interact with a game object // See Also // IGameObjectExtension struct IGameObject : public IActionListener { public: // bind this entity to the network system (it gets synchronized then...) virtual bool BindToNetwork(EBindToNetworkMode mode = eBTNM_Normal) = 0; // bind this entity to the network system, with a dependency on it's parent virtual bool BindToNetworkWithParent(EBindToNetworkMode mode, EntityId parentId) = 0; // flag that we have changed the state of the game object aspect virtual void ChangedNetworkState(NetworkAspectType aspects) = 0; // enable/disable network aspects on game object virtual void EnableAspect(NetworkAspectType aspects, bool enable) = 0; // enable/disable delegatable aspects virtual void EnableDelegatableAspect(NetworkAspectType aspects, bool enable) = 0; // A one off call to never enable the physics aspect, this needs to be done *before* the BindToNetwork (typically in the GameObject's Init function) virtual void DontSyncPhysics() = 0; // query extension by ID. Returns 0 if extension is not there. virtual IGameObjectExtension* QueryExtension(IGameObjectSystem::ExtensionID id) const = 0; // query extension. returns 0 if extension is not there. virtual IGameObjectExtension* QueryExtension(const char* extension) const = 0; // set extension parameters virtual bool SetExtensionParams(const char* extension, SmartScriptTable params) = 0; // get extension parameters virtual bool GetExtensionParams(const char* extension, SmartScriptTable params) = 0; // send a game object event virtual void SendEvent(const SGameObjectEvent&) = 0; // force the object to update even if extensions' slots are "sleeping"... virtual void ForceUpdate(bool force) = 0; virtual void ForceUpdateExtension(IGameObjectExtension* pGOE, int slot) = 0; // get/set network channel virtual ChannelId GetChannelId() const = 0; virtual void SetChannelId(ChannelId) = 0; // serialize some aspects of the game object virtual void FullSerialize(TSerialize ser) = 0; virtual bool NetSerialize(TSerialize ser, EEntityAspects aspect, uint8 profile, int pflags) = 0; // in case things have to be set after serialization virtual void PostSerialize() = 0; // is the game object probably visible? virtual bool IsProbablyVisible() = 0; virtual bool IsProbablyDistant() = 0; virtual NetworkAspectType GetNetSerializeAspects() = 0; // change the profile of an aspect virtual bool SetAspectProfile(EEntityAspects aspect, uint8 profile, bool fromNetwork = false) = 0; virtual uint8 GetAspectProfile(EEntityAspects aspect) = 0; virtual IGameObjectExtension* GetExtensionWithRMIBase(const void* pBase) = 0; virtual void EnablePrePhysicsUpdate(EPrePhysicsUpdate updateRule) = 0; virtual void SetNetworkParent(EntityId id) = 0; virtual void Pulse(uint32 pulse) = 0; virtual void RegisterAsPredicted() = 0; virtual void RegisterAsValidated(IGameObject* pGO, int predictionHandle) = 0; virtual int GetPredictionHandle() = 0; virtual void RegisterExtForEvents(IGameObjectExtension* piExtension, const int* pEvents, const int numEvents) = 0; virtual void UnRegisterExtForEvents(IGameObjectExtension* piExtension, const int* pEvents, const int numEvents) = 0; // enable/disable sending physics events to this game object virtual void EnablePhysicsEvent(bool enable, int events) = 0; virtual bool WantsPhysicsEvent(int events) = 0; virtual void AttachDistanceChecker() = 0; // enable/disable AI activation flag virtual bool SetAIActivation(EGameObjectAIActivationMode mode) = 0; // enable/disable auto-disabling of physics virtual void SetAutoDisablePhysicsMode(EAutoDisablePhysicsMode mode) = 0; // for debugging updates virtual bool ShouldUpdate() = 0; // register a partial update in the netcode without actually serializing - useful only for working around other bugs virtual void RequestRemoteUpdate(NetworkAspectType aspectMask) = 0; virtual void SerializeSpawnInfo(TSerialize ser, IEntity* entity) = 0; virtual IGameObjectExtension* GetExtensionWithRMIRep(uint32 repId) = 0; template <class ParamsType> void InvokeRMI(IRMIRep& rep, ParamsType&& params, uint32 where, ChannelId channel = kInvalidChannelId) { gEnv->pNetwork->InvokeRMI(this, rep, const_cast<void*>(reinterpret_cast<const void*>(&params)), channel, where); } template <class ParamsType> void InvokeRMIWithDependentObject(IRMIRep& rep, ParamsType&& params, uint32 where, EntityId ent, ChannelId channel = kInvalidChannelId) { // \todo - We may need to support object-dependent RMIs in the Shim. gEnv->pNetwork->InvokeRMI(this, rep, const_cast<void*>(reinterpret_cast<const void*>(&params)), channel, where); } virtual void SetAuthority(bool auth) = 0; // turn an extension on ILINE bool ActivateExtension(const char* extension) { return ChangeExtension(extension, eCE_Activate) != 0; } // turn an extension off ILINE void DeactivateExtension(const char* extension) { ChangeExtension(extension, eCE_Deactivate); } // forcefully get a pointer to an extension (may instantiate if needed) ILINE IGameObjectExtension* AcquireExtension(const char* extension) { return ChangeExtension(extension, eCE_Acquire); } // release a previously acquired extension ILINE void ReleaseExtension(const char* extension) { ChangeExtension(extension, eCE_Release); } // retrieve the hosting entity ILINE IEntity* GetEntity() const { return m_pEntity; } ILINE EntityId GetEntityId() const { return m_entityId; } // for extensions to register for special things virtual bool CaptureView(IGameObjectView* pGOV) = 0; virtual void ReleaseView(IGameObjectView* pGOV) = 0; virtual bool CaptureActions(IActionListener* pAL) = 0; virtual void ReleaseActions(IActionListener* pAL) = 0; virtual bool CaptureProfileManager(IGameObjectProfileManager* pPH) = 0; virtual void ReleaseProfileManager(IGameObjectProfileManager* pPH) = 0; virtual void EnableUpdateSlot(IGameObjectExtension* pExtension, int slot) = 0; virtual void DisableUpdateSlot(IGameObjectExtension* pExtension, int slot) = 0; virtual uint8 GetUpdateSlotEnables(IGameObjectExtension* pExtension, int slot) = 0; virtual void EnablePreUpdates(IGameObjectExtension* pExtension) = 0; virtual void DisablePreUpdates(IGameObjectExtension* pExtension) = 0; virtual void EnablePostUpdates(IGameObjectExtension* pExtension) = 0; virtual void DisablePostUpdates(IGameObjectExtension* pExtension) = 0; virtual void SetUpdateSlotEnableCondition(IGameObjectExtension* pExtension, int slot, EUpdateEnableCondition condition) = 0; virtual void PostUpdate(float frameTime) = 0; virtual IWorldQuery* GetWorldQuery() = 0; virtual bool IsJustExchanging() = 0; ILINE void SetMovementController(IMovementController* pMC) { m_pMovementController = pMC; } virtual ILINE IMovementController* GetMovementController() { return m_pMovementController; } virtual void GetMemoryUsage(ICrySizer* pSizer) const {}; #if GAME_OBJECT_SUPPORTS_CUSTOM_USER_DATA virtual void* GetUserData() const = 0; virtual void SetUserData(void* ptr) = 0; #endif protected: enum EChangeExtension { eCE_Activate, eCE_Deactivate, eCE_Acquire, eCE_Release }; IGameObject() : m_pEntity(0) , m_entityId(0) , m_pMovementController(0) {} EntityId m_entityId; IMovementController* m_pMovementController; IEntity* m_pEntity; private: // change extension activation/reference somehow virtual IGameObjectExtension* ChangeExtension(const char* extension, EChangeExtension change) = 0; }; struct IGameObject; struct SViewParams; template <class T_Derived, class T_Parent, size_t MAX_STATIC_MESSAGES = 64> class CGameObjectExtensionHelper : public T_Parent { public: CGameObjectExtensionHelper() {} public: struct RMIInfo { size_t m_numMessages; IRMIRep* m_rmiReps[ MAX_STATIC_MESSAGES ]; }; private: static RMIInfo s_RMIInfo; public: static IRMIRep* RegisterRMIRep(IRMIRep* rep, uint32 extensionCrc, uint32 rmiCrc) { CRY_ASSERT_MESSAGE(s_RMIInfo.m_numMessages < MAX_STATIC_MESSAGES, "Too many static RMIs for this object."); if (s_RMIInfo.m_numMessages < MAX_STATIC_MESSAGES) { uint32 repId = 0; repId ^= extensionCrc + 0x9e3779b9 + (repId << 6) + (repId >> 2); repId ^= rmiCrc + 0x9e3779b9 + (repId << 6) + (repId >> 2); rep->SetUniqueId(repId); s_RMIInfo.m_rmiReps[ s_RMIInfo.m_numMessages++ ] = rep; auto begin = std::begin(s_RMIInfo.m_rmiReps); auto end = begin + s_RMIInfo.m_numMessages; std::sort(begin, end, [](const IRMIRep* lhs, const IRMIRep* rhs) { return lhs->GetUniqueId() < rhs->GetUniqueId(); } ); return rep; } return nullptr; } bool HasRMIRep(uint32 repId) const override { return !!GetRMIRep(repId); } IRMIRep* GetRMIRep(uint32 repId) const override { auto begin = std::begin(s_RMIInfo.m_rmiReps); auto end = begin + s_RMIInfo.m_numMessages; auto iter = std::lower_bound(begin, end, repId, [](const IRMIRep* rep, uint32 repId) { return rep->GetUniqueId() < repId; } ); if (iter != end && (*iter)->GetUniqueId() == repId) { return *iter; } return nullptr; } static void GetGameObjectExtensionRMIData(void** ppRMI, size_t* nCount) {} const void* GetRMIBase() const override { return nullptr; } }; /// In Gridmate, all RPCs are reliable ordered, so the reliability macro parameter /// is irrelevant, but exists for backward compatibility with existing RMI declarations. /// The same applies for attachment. #define DECLARE_RMI(name, paramsType, reliability, attachment, isServer, lowDelay) \ public: \ template<typename T> \ class RMIRep_##name \ : public IRMIRep \ { \ public: \ typedef paramsType ParamsType; \ typedef bool (T::* InvocationHandler)(const ParamsType& p); \ InvocationHandler m_handler; \ RMIRep_##name(InvocationHandler handler) \ : m_handler(handler) {} \ bool IsServerRMI() const override { return isServer; } \ const char* GetDebugName() const override \ { \ return #name; \ } \ void SerializeParamsToBuffer(TSerialize ser, void* params) override \ { \ ParamsType* p = reinterpret_cast<ParamsType*>(params); \ p->SerializeWith(ser); \ } \ void* SerializeParamsFromBuffer(TSerialize ser) override \ { \ CRY_ASSERT(gEnv->mMainThreadId == CryGetCurrentThreadId()); \ static ParamsType p; \ p.SerializeWith(ser); \ return &p; \ } \ void Invoke(IGameObjectExtension * extension, void* params) override \ { \ ParamsType* p = reinterpret_cast<ParamsType*>(params); \ CRY_ASSERT(m_handler); \ (static_cast<T*>(extension)->*m_handler)(*p); \ } \ }; \ static IRMIRep* RMI_##name; \ bool RMIHandler_##name(const paramsType&params); \ static IRMIRep& name() { return *RMI_##name; } #define IMPLEMENT_RMI(cls, name) \ cls::RMIRep_##name<cls> rep_##name(&cls::RMIHandler_##name); \ IRMIRep* cls::RMI_##name = &rep_##name; \ IRMIRep* reg_##cls##_##name = cls::RegisterRMIRep(&rep_##name, \ CryStringUtils::CalculateHashLowerCase(#cls), \ CryStringUtils::CalculateHashLowerCase(#name)); \ bool cls::RMIHandler_##name(const cls::RMIRep_##name<cls>::ParamsType & params) /* * _FAST versions may send the RMI without waiting for the frame to end; be sure that consistency with the entity is not important! */ // // PreAttach/PostAttach RMI's cannot have their reliability specified (see CGameObjectDispatch::RegisterInterface() for details) #define DECLARE_SERVER_RMI_PREATTACH(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PreAttach, true, false) #define DECLARE_CLIENT_RMI_PREATTACH(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PreAttach, false, false) #define DECLARE_SERVER_RMI_POSTATTACH(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PostAttach, true, false) #define DECLARE_CLIENT_RMI_POSTATTACH(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PostAttach, false, false) #define DECLARE_SERVER_RMI_NOATTACH(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_NoAttach, true, false) #define DECLARE_CLIENT_RMI_NOATTACH(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_NoAttach, false, false) // PreAttach/PostAttach RMI's cannot have their reliability specified (see CGameObjectDispatch::RegisterInterface() for details) #define DECLARE_SERVER_RMI_PREATTACH_FAST(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PreAttach, true, true) #define DECLARE_CLIENT_RMI_PREATTACH_FAST(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PreAttach, false, true) #define DECLARE_SERVER_RMI_POSTATTACH_FAST(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PostAttach, true, true) #define DECLARE_CLIENT_RMI_POSTATTACH_FAST(name, params) DECLARE_RMI(name, params, eNRT_UnreliableOrdered, eRAT_PostAttach, false, true) #define DECLARE_SERVER_RMI_NOATTACH_FAST(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_NoAttach, true, true) #define DECLARE_CLIENT_RMI_NOATTACH_FAST(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_NoAttach, false, true) #if ENABLE_URGENT_RMIS #define DECLARE_SERVER_RMI_URGENT(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_Urgent, true, false) #define DECLARE_CLIENT_RMI_URGENT(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_Urgent, false, false) #else #define DECLARE_SERVER_RMI_URGENT(name, params, reliability) DECLARE_SERVER_RMI_NOATTACH(name, params, reliability) #define DECLARE_CLIENT_RMI_URGENT(name, params, reliability) DECLARE_CLIENT_RMI_NOATTACH(name, params, reliability) #endif // ENABLE_URGENT_RMIS #if ENABLE_INDEPENDENT_RMIS #define DECLARE_SERVER_RMI_INDEPENDENT(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_Independent, true, false) #define DECLARE_CLIENT_RMI_INDEPENDENT(name, params, reliability) DECLARE_RMI(name, params, reliability, eRAT_Independent, false, false) #else #define DECLARE_SERVER_RMI_INDEPENDENT(name, params, reliability) DECLARE_SERVER_RMI_NOATTACH(name, params, reliability) #define DECLARE_CLIENT_RMI_INDEPENDENT(name, params, reliability) DECLARE_CLIENT_RMI_NOATTACH(name, params, reliability) #endif // ENABLE_INDEPENDENT_RMIS /* // Todo: // Temporary, until a good solution for sending noattach fast messages can be found #define DECLARE_SERVER_RMI_NOATTACH_FAST(a,b,c) DECLARE_SERVER_RMI_NOATTACH(a,b,c) #define DECLARE_CLIENT_RMI_NOATTACH_FAST(a,b,c) DECLARE_CLIENT_RMI_NOATTACH(a,b,c) */ // #define DECLARE_INTERFACE_SERVER_RMI_PREATTACH(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PreAttach, true, false) #define DECLARE_INTERFACE_CLIENT_RMI_PREATTACH(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PreAttach, false, false) #define DECLARE_INTERFACE_SERVER_RMI_POSTATTACH(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PostAttach, true, false) #define DECLARE_INTERFACE_CLIENT_RMI_POSTATTACH(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PostAttach, false, false) #define DECLARE_INTERFACE_SERVER_RMI_PREATTACH_FAST(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PreAttach, true, true) #define DECLARE_INTERFACE_CLIENT_RMI_PREATTACH_FAST(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PreAttach, false, true) #define DECLARE_INTERFACE_SERVER_RMI_POSTATTACH_FAST(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PostAttach, true, true) #define DECLARE_INTERFACE_CLIENT_RMI_POSTATTACH_FAST(name, params, reliability) DECLARE_INTERFACE_RMI(name, params, reliability, eRAT_PostAttach, false, true) template <class T, class U, size_t N> typename CGameObjectExtensionHelper<T, U, N>::RMIInfo CGameObjectExtensionHelper<T, U, N>::s_RMIInfo; struct IGameObjectView { virtual ~IGameObjectView(){} virtual void UpdateView(SViewParams& params) = 0; virtual void PostUpdateView(SViewParams& params) = 0; }; struct IGameObjectProfileManager { virtual ~IGameObjectProfileManager(){} virtual bool SetAspectProfile(EEntityAspects aspect, uint8 profile) = 0; virtual uint8 GetDefaultProfile(EEntityAspects aspect) = 0; }; // Summary // Interface used to implement a game object extension struct IGameObjectExtension : public IComponent { virtual ~IGameObjectExtension(){} virtual void GetMemoryUsage(ICrySizer* pSizer) const { } IGameObjectExtension() : m_pGameObject(0) , m_entityId(0) , m_pEntity(0) {} // IComponent // Default implementations ComponentEventPriority GetEventPriority(const int eventID) const override { return EntityEventPriority::User; } void UpdateComponent(SEntityUpdateContext& ctx) override {} // Until IGameObjectExtension is truly no different than a vanilla IComponent, // IGameObjectExtensions should not implement the functions marked final. bool InitComponent(IEntity* pEntity, SEntitySpawnParams& params) final { return true; } void Done() final {} // ~IComponent // Summary // Initialize the extension // Parameters // pGameObject - a pointer to the game object which will use the extension // Remarks // IMPORTANT: It's very important that the implementation of this function // call the protected function SetGameObject() during the execution of the // Init() function. Unexpected results would happen otherwise. virtual bool Init(IGameObject* pGameObject) = 0; // Summary // Post-initialize the extension // Description // During the post-initialization, the extension is now contained in the // game object // Parameters // pGameObject - a pointer to the game object which owns the extension virtual void PostInit(IGameObject* pGameObject) { } // Summary // Initialize the extension (client only) // Description // This initialization function should be use to initialize resource only // used in the client // Parameters // channelId - id of the server channel of the client to receive the // initialization virtual void InitClient(ChannelId channelId) { } // Summary // Post-initialize the extension (client only) // Description // This initialization function should be use to initialize resource only // used in the client. During the post-initialization, the extension is now // contained in the game object // Parameters // channelId - id of the server channel of the client to receive the // initialization virtual void PostInitClient(ChannelId channelId) { } // Summary // Reload the extension // Description // Called when owning entity is reloaded // Parameters // pGameObject - a pointer to the game object which owns the extension // Returns // TRUE if the extension should be kept, FALSE if it should be removed // Remarks // IMPORTANT: It's very important that the implementation of this function // call the protected function ResetGameObject() during the execution of the // ReloadExtension() function. Unexpected results would happen otherwise. virtual bool ReloadExtension(IGameObject* pGameObject, const SEntitySpawnParams& params) { return true; } // Summary // Post-reload the extension // Description // Called when owning entity is reloaded and all its extensions have either // either been reloaded or destroyed // Parameters // pGameObject - a pointer to the game object which owns the extension virtual void PostReloadExtension(IGameObject* pGameObject, const SEntitySpawnParams& params) { } // Summary // Builds a signature to describe the dynamic hierarchy of the parent Entity container // Arguments: // signature - the object to serialize with, forming the signature // Returns: // true - If the signature is thus far valid // Note: // It's the responsibility of the proxy to identify its internal state which may complicate the hierarchy // of the parent Entity i.e., sub-proxies and which actually exist for this instantiation. virtual bool GetEntityPoolSignature(TSerialize signature) { return false; } // Summary // Performs the serialization the extension // Parameters // ser - object used to serialize values // aspect - serialization aspect, used for network serialization // profile - which profile to serialize; 255 == don't care // flags - physics flags to be used for serialization // See Also // ISerialize virtual void FullSerialize(TSerialize ser) { } virtual bool NetSerialize(TSerialize ser, EEntityAspects aspect, uint8 profile, int pflags) { return true; } // Summary // Return the aspects NetSerialize serializes. // Overriding this to return only the aspects used will speed up the net bind of the object. virtual NetworkAspectType GetNetSerializeAspects() { return eEA_All; } // Summary // Performs post serialization fixes virtual void PostSerialize() { } // Summary // Performs the serialization of special spawn information // Parameters // ser - object used to serialize values // See Also // Serialize, ISerialize virtual void SerializeSpawnInfo(TSerialize ser, IEntity* entity) { } virtual ISerializableInfoPtr GetSpawnInfo() { return nullptr; } // Summary // Performs frame dependent extension updates // Parameters // ctx - Update context // updateSlot - updateSlot // See Also // PostUpdate, SEntityUpdateContext, IGameObject::EnableUpdateSlot virtual void Update(SEntityUpdateContext& ctx, int updateSlot) { } // Summary // Processes game specific events // Parameters // event - game event // See Also // SGameObjectEvent virtual void HandleEvent(const SGameObjectEvent& event) { } // Summary // Processes entity specific events. // This is distinct from ProcessEvent(), which is called on all IComponents. // Parameters // event - entity event, see SEntityEvent for more information virtual void ProcessEvent(SEntityEvent& event) = 0; virtual void SetChannelId(ChannelId id) { } virtual void SetAuthority(bool auth) { } // Summary // Retrieves the RMI Base pointer // Description // Internal function used for RMI. It's usually implemented by // CGameObjectExtensionHelper provides a way of checking who should // receive some RMI call. virtual const void* GetRMIBase() const { return nullptr; } // Summary // Performs an update at the start of the frame, must call IGameObject::EnablePreUpdates // to receive this call // Parameters // frameTime - time elapsed since the last frame update // See Also // Update, IGameObject::EnablePreUpdates, IGameObject::DisablePreUpdates virtual void PreUpdate(float frameTime) { } // Summary // Performs an additional update // Parameters // frameTime - time elapsed since the last frame update // See Also // Update, IGameObject::EnablePostUpdates, IGameObject::DisablePostUpdates virtual void PostUpdate(float frameTime) { } // Summary virtual void PostRemoteSpawn() { } // Summary // Retrieves the pointer to the game object // Returns // A pointer to the game object which hold this extension ILINE IGameObject* GetGameObject() const { return m_pGameObject; } // Summary // Retrieves the pointer to the entity // Returns // A pointer to the entity which hold this game object extension ILINE IEntity* GetEntity() const { return m_pEntity; } // Summary // Retrieves the EntityId // Returns // An EntityId to the entity which hold this game object extension ILINE EntityId GetEntityId() const { return m_entityId; } virtual bool HasRMIRep(uint32 repId) const = 0; virtual IRMIRep* GetRMIRep(uint32 repId) const = 0; protected: void SetGameObject(IGameObject* pGameObject) { m_pGameObject = pGameObject; if (pGameObject) { m_pEntity = pGameObject->GetEntity(); m_entityId = pGameObject->GetEntityId(); } } void ResetGameObject() { m_pEntity = (m_pGameObject ? m_pGameObject->GetEntity() : 0); m_entityId = (m_pGameObject ? m_pGameObject->GetEntityId() : 0); } private: IGameObject* m_pGameObject; EntityId m_entityId; IEntity* m_pEntity; }; DECLARE_COMPONENT_POINTERS(IGameObjectExtension); #define CHANGED_NETWORK_STATE(object, aspects) do { /* IEntity * pEntity = object->GetGameObject()->GetEntity(); CryLogAlways("%s changed aspect %x (%s %d)", pEntity ? pEntity->GetName() : "NULL", aspects, __FILE__, __LINE__); */ object->GetGameObject()->ChangedNetworkState(aspects); } while (0) #define CHANGED_NETWORK_STATE_GO(object, aspects) do { /* IEntity * pEntity = object->GetEntity(); CryLogAlways("%s changed aspect %x (%s %d)", pEntity ? pEntity->GetName() : "NULL", aspects, __FILE__, __LINE__); */ object->ChangedNetworkState(aspects); } while (0) #define CHANGED_NETWORK_STATE_REF(object, aspects) do { /* IEntity * pEntity = object.GetGameObject()->GetEntity(); CryLogAlways("%s changed aspect %x (%s %d)", pEntity ? pEntity->GetName() : "NULL", aspects, __FILE__, __LINE__); */ object.GetGameObject()->ChangedNetworkState(aspects); } while (0) #endif // CRYINCLUDE_CRYACTION_IGAMEOBJECT_H
43.273764
304
0.673022
[ "object" ]
26c84a82bf90425436cde0ffb6c98f803ec1403e
11,655
h
C
libtensor/defs.h
maxscheurer/libtensor
288ed0596b24356d187d2fa40c05b0dacd00b413
[ "BSL-1.0" ]
null
null
null
libtensor/defs.h
maxscheurer/libtensor
288ed0596b24356d187d2fa40c05b0dacd00b413
[ "BSL-1.0" ]
11
2020-12-04T20:26:12.000Z
2021-12-03T08:07:09.000Z
libtensor/defs.h
maxscheurer/libtensor
288ed0596b24356d187d2fa40c05b0dacd00b413
[ "BSL-1.0" ]
2
2021-06-17T12:35:47.000Z
2021-11-23T16:27:39.000Z
#ifndef LIBTENSOR_DEFS_H #define LIBTENSOR_DEFS_H #include <cstddef> /** \brief Tensor library \ingroup libtensor **/ namespace libtensor { /** \brief Namespace name **/ extern const char* g_ns; } // namespace libtensor #ifdef __MINGW32__ #include <cstdlib> inline void srand48(long seed) { srand(seed); } inline double drand48() { return (double(rand()) / RAND_MAX); } inline long lrand48() { return rand(); } #endif /** \mainpage Tensor Library The tensor library is an open-source object-oriented C++ library to perform tensor algebra on tensors of arbitrary rank, size and symmetry. The provided classes and functions operate on large tensors by splitting them into small blocks which can be stored in memory or on disk. Parallel divide-and-conquer algorithms are available to perform the tensor algebra operations. \section Contents -# \subpage compile -# \subpage prog_guide -# \subpage reference **/ /** \page compile How to compile \section Requirements To compile libtensor the following programs and libraries are required: - \c cmake -- libtensor uses cmake to configure and set up the build - \c lapack and \c blas libraries (e.g. MKL, ACML, Atlas, CBLAS, GSL) - \c libtest -- Test library (to compile the unit tests for \c libtensor) - \c libutil -- Utilities library (machine-dependent code) - [optional] \c libvmm -- Virtual memory management library The libraries \c libtest, \c libutil, and \c libvmm have to be located in the same directory as \c libtensor for the configuration of the build to work seemlessly. All libraries have to be configured and compiled before \c libtensor can be build. The configuration and build of the libraries is similar to that of \c libtensor (see below). It is necessary to compile the libraries in the same order as they are listed above. \section The Configuration The simplest way to configure the build of \c libtensor (and the other libraries) is to use the shell script \c configure in the main directory. The script accepts two options: - the compiler -- \c gcc, \c mingw32, \c intel, \c open64, \c pgi, or \c ibm - the build type -- \c debug, \c release, or \c relwdeb The script then creates the directory \c build and runs \c cmake in it to set up the build system according to the options provided. \section The Build After the configuration has succeeded \c libtensor can be build by changing into directory \c build and executing \c make. This will create the static library \c libtensor.a in the subdirectory \c libtensor and several unit test suites \c libtensor_.*_tests in the subdirectory \c tests of the build folder. \section Compiling \c libtensor with Other Programs ... coming soon ... **/ /** \page prog_guide Programmer's guide This guide describes the various concepts and components in \c libtensor and how to use them in a program. -# \subpage quick_start -# \subpage concepts -# \subpage components **/ /** \page quick_start Quick-start Guide This guide gives a short introduction into \c libtensor showing how to setup initial \c btensors and use them in an equation. It covers only a small portion of the existing functionality. For a more detailed account on the available classes please refer to the other parts of this manual. \section Setting up dimensions The initial step to create \c btensors is to setup the information on the dimensions and the block structure. For this purpose \c libtensor provides the class \c bispace<N>. A one-dimensional \c bispace (N=1) can be constructed by providing the total length of the dimension. Afterwards the total length can be split into smaller blocks by using the member function \c split. The 1D bispaces can then be combined into higher-dimensional spaces by using the overloaded operators "|" and "&" where the latter is only used, if the two bispaces it combines are identical. \code size_t nalpha, nbeta, nbasis, nb2; size_t nel = nalpha + nbeta; nv = 2 * nbasis - nel; bispace<1> o(nel), v(nv), b(nbasis), s2(nb2); o.split(nalpha); v.split(nbasis - nalpha); // ... add further splits ... for (size_t i = 1; i < (nbasis - 1) / 16; i++) { b.split(i * 16); } bispace<2> oo(o&o), ov(o|v), vv(v&v), bb(b&b); // ... \endcode \section Creating tensors With bispaces available it is straightforward to create one or more btensors. The resulting objects will not yet contain any data beside the information on the basic structure. \code btensor<2, double> f_oo(oo), f_vv(vv), f_bb(bb); btensor<4, double> i_oovv((o&o)|(v&v)); \endcode \section Initializing symmetry After the btensor objects have been created, their symmetry can be set up. This should always be done before adding data to the objects. There are several steps required to add symmetry to a btensor: -# Obtain the symmetry object from the btensor \code block_tensor_wr_ctrl<2, double> ctrl(f_oo); symmetry<2, double> &sym = ctrl.req_symmetry(); \endcode -# Create symmetry element objects: \code // permutational symmetry permutation<2> p01; p01.permute(0, 1); scalar_transf<double> tr; se_perm<2, double> se(p01, tr); // spin symmetry mask<2> msk; msk[0] = msk[1] = true; index<2> i00, i01, i10, i11; i10[0] = i01[1] = 1; i11[0] = i11[1] = 1; se_part<2, double> sp(oo.get_bis(), msk, 2); sp.add_map(i00, i11, tr); sp.mark_forbidden(i01); sp.mark_forbidden(i10); // ... \endcode -# Add the symmetry element objects to the symmetry \code sym.insert(se); sym.insert(sp); \endcode \section Fill a block tensor with data As soon as the symmetry has been set up, a btensor object can be populated with data. There are several ways to do so. For example, the classes \c btod_read and \c btod_import_raw allow to read the tensor data from an input stream or a simple data pointer. The most comprehensive way, however, is to loop over all canonical blocks (i.e. tensor blocks which are allowed by the symmetry and cannot be obtained from previous blocks using a tensor transformation) and write data into each block separately. \subsection Loop over tensor blocks The classes \c orbit_list and \c orbit provide the required functionality to perform the loop over the canonical blocks of a block tensor. \code // Request a control object block_tensor_wr_ctrl<2, double> ctrl(f_oo); // Loop over all canonical blocks using orbit_list orbit_list<2, double> ol(ctrl.req_const_symmetry()); for (orbit_list<2, double>::iterator it = ol.begin(); it != ol.end(); it++) { // Obtain the index of the current canonical block index<2> bidx; ol.get_index(it, bidx); // Request tensor block from control object dense_tensor_wr_i<2, double> &blk = ctrl.req_block(bidx); // Fill with data (see next section) // Return the tensor block (mark as done) ctrl.ret_block(bidx); } \endcode \subsection Fill tensor blocks with data The tensor blocks of a block tensor are themselves tensor objects of type dense_tensor. If a tensor block is requested from a block tensor, it will return a reference to either the read- or the write-interface of the respective dense_tensor (here we only make use of the write-interface). From them we can retrieve a pointer to the actual data array which will be filled with data. \code dense_tensor_wr_i<2, double> &blk = ctrl.req_block(bidx); dense_tensor_wr_ctrl<2, double> tc(blk); // Obtain dimensions of tensor block const dimensions<2> &tdims = blk.get_dims(); // Request data pointer double *ptr = blk.req_dataptr(); for (size_t i = 0; i < tdims.get_size(); i++) { ptr[i] = 0.0; } // Return data pointer blk.ret_dataptr(ptr); \endcode \section Using tensors to store the result of an equation The previous sections described how to put data from external source into some previously created tensor. This is only necessary for the tensors which hold the initial data. For other tensors whose contents can be computed using the initial tensors the "Creating tensors" step is sufficient. As soon as this is done the tensors can be filled with data by employing them as the l.h.s of an expression. The symmetry and contents of the tensor blocks is automatically determined by the expression. \code btensor<2, double> v_ov(o|v), w_ov(o|v); // Fill v_ov with data // ... // Compute w_ov using an expression letter i, j, a, b; w_ov(i|a) = contract(b, i_oovv(i|j|a|b), v_ov(j|b)); \endcode **/ /** \page reference Reference Manual \section Directory Structure - \c cmake/ -- Files related to the build system \c cmake. - \c libtensor/ -- The actual tensor library (for details see below). - \c performance_tests/ -- Set of classes to measure the performance (outdated). - \c tests -- Unit tests for the classes and functions in the tensor library. ... to be continued ... \section Code Structure The source code of the tensor library consists of various parts structured into a number of subdirectories. -# \ref libtensor_core in directory \c core/ -# \ref libtensor_symmetry in directory \c symmetry/ -# \ref libtensor_dense_tensor in directory \c dense_tensor/ -# \ref libtensor_block_tensor in directory \c block_tensor/ -# \ref libtensor_iface in directory \c iface/ -# \ref libtensor_gen_block_tensor in directory \c gen_block_tensor/ -# \ref libtensor_kernels in directory \c kernels/ -# \ref libtensor_linalg in directory \c linalg/ \section wheretostart Where to Start ... coming soon ... **/ /** \defgroup libtensor Tensor library **/ /** \defgroup libtensor_core Core components \ingroup libtensor **/ /** \defgroup libtensor_dense_tensor Dense tensors \brief Implementation of dense tensors of arbitrary element type \ingroup libtensor **/ /** \defgroup libtensor_dense_tensor_tod Tensor operations on dense tensors (double) \brief Operations on tensors with real double precision elements \ingroup libtensor_dense_tensor **/ /** \defgroup libtensor_gen_block_tensor Generalized block tensors \brief Implementation of block tensors with arbitrary types \ingroup libtensor **/ /** \defgroup libtensor_gen_bto Generalized block %tensor operations \brief Implementation of block tensor operations with arbitrary types \ingroup libtensor_gen_block_tensor **/ /** \defgroup libtensor_block_tensor Block tensors of dense tensors \brief Implementation of block tensors with dense tensors, but arbitrary element type \ingroup libtensor **/ /** \defgroup libtensor_block_tensor_btod Block tensor operations (double) \brief Operations on block tensors with real double precision elements \ingroup libtensor_block_tensor **/ /** \defgroup libtensor_iface Block tensor interface \brief Easy to use interface to implement equations with block tensors. \ingroup libtensor **/ /** \defgroup libtensor_symmetry Symmetry related components \brief Easy to use interface to implement equations with block tensors. \ingroup libtensor **/ #endif // LIBTENSOR_DEFS_H
33.880814
84
0.698756
[ "object" ]
26d125d62eb97f90544c9e72db73abf990280994
4,280
c
C
src/list.c
amyinorbit/ccore
a276cdae355ea1a09c997a958d6b98577cb85d39
[ "MIT" ]
1
2022-01-14T09:52:54.000Z
2022-01-14T09:52:54.000Z
src/list.c
amyinorbit/ccore
a276cdae355ea1a09c997a958d6b98577cb85d39
[ "MIT" ]
null
null
null
src/list.c
amyinorbit/ccore
a276cdae355ea1a09c997a958d6b98577cb85d39
[ "MIT" ]
null
null
null
//===--------------------------------------------------------------------------------------------=== // list.c - Doubly-linked list implementation // // Created by Amy Parent <amy@amyparent.com> // Copyright (c) 2019 Amy Parent // Licensed under the MIT License // =^•.•^= //===--------------------------------------------------------------------------------------------=== #include <ccore/list.h> #include <ccore/memory.h> #include <ccore/log.h> static inline cclist_node_t *get_node(const cclist_t *list, const void *ptr) { return (cclist_node_t*)((char *)ptr + list->offset); } static inline void *get_ptr(const cclist_t *list, const cclist_node_t *node) { return (void *)((char *)node - list->offset); } void cclist_init(cclist_t *list, size_t offset) { CCASSERT(list); list->size = 0; list->head.next = &list->head; list->head.prev = &list->head; list->offset = offset; } void cclist_clear(cclist_t *list, cc_destructor des, void *user_data) { CCASSERT(list); for(cclist_node_t *item = list->head.next; item != &list->head;) { void *to_free = get_ptr(list, item); item = item->next; if(des) des(to_free, user_data); } cclist_init(list, list->offset); } static inline cclist_node_t *cclist_nth_item(cclist_t *list, size_t n) { cclist_node_t *item = list->head.next; while(item != &list->head && n--) { item = item->next; } CCASSERT(!n); return item; } static void cclist_do_insert_after(cclist_t *list, void* object, cclist_node_t *node) { cclist_node_t *item = get_node(list, object); item->prev = node; item->next = node->next; node->next->prev = item; node->next = item; list->size += 1; } static void cclist_do_insert_before(cclist_t *list, void* object, cclist_node_t *node) { cclist_node_t *item = get_node(list, object); item->next = node; item->prev = node->prev; node->prev->next = item; node->prev = item; list->size += 1; } void cclist_insert_at(cclist_t *list, void *object, size_t n) { CCASSERT(list); cclist_node_t *nth = cclist_nth_item(list, n); cclist_do_insert_before(list, object, nth); } void cclist_insert_first(cclist_t *list, void *object) { CCASSERT(list); cclist_do_insert_after(list, object, &list->head); } void cclist_insert_last(cclist_t *list, void *object) { CCASSERT(list); cclist_do_insert_before(list, object, &list->head); } void cclist_insert_after(cclist_t *list, void *object, const void *item) { CCASSERT(list); CCASSERT(item); cclist_node_t *node = get_node(list, item); cclist_do_insert_after(list, object, node); } void cclist_insert_before(cclist_t *list, void *object, const void *item) { CCASSERT(list); CCASSERT(item); cclist_node_t *node = get_node(list, item); cclist_do_insert_before(list, object, node); } void cclist_remove(cclist_t *list, void *object) { CCASSERT(list); CCASSERT(object); cclist_node_t *node = get_node(list, object); node->prev->next = node->next; node->next->prev = node->prev; node->prev = node->next = NULL; list->size -= 1; } void cclist_remove_first(cclist_t *list) { CCASSERT(list); if(!list->size) return; list->head.next = list->head.next->next; list->head.next->prev = &list->head; list->size -= 1; } void cclist_remove_last(cclist_t *list) { CCASSERT(list); if(!list->size) return; list->head.prev = list->head.prev->prev; list->head.prev->next = &list->head; list->size -= 1; } void *cclist_first(const cclist_t *list) { CCASSERT(list); if(list->head.next == &list->head) return NULL; return get_ptr(list, list->head.next); } void *cclist_last(const cclist_t *list) { CCASSERT(list); if(list->head.prev == &list->head) return NULL; return get_ptr(list, list->head.prev); } void *cclist_next(const cclist_t *list, const void *current) { cclist_node_t *node = get_node(list, current); if(node->next == &list->head) return NULL; return get_ptr(list, node->next); } void *cclist_prev(const cclist_t *list, const void *current) { cclist_node_t *node = get_node(list, current); if(node->prev == &list->head) return NULL; return get_ptr(list, node->prev); }
28.533333
100
0.627336
[ "object" ]
26d6d5dc6225703a9edc7317e94063e2415646d6
4,568
h
C
arangod/IResearch/IResearchViewDBServer.h
pavelsevcik/arangodb
647a29d1aeab0909147961f5868dfd0618717e96
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchViewDBServer.h
pavelsevcik/arangodb
647a29d1aeab0909147961f5868dfd0618717e96
[ "Apache-2.0" ]
null
null
null
arangod/IResearch/IResearchViewDBServer.h
pavelsevcik/arangodb
647a29d1aeab0909147961f5868dfd0618717e96
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #ifndef ARANGOD_IRESEARCH__IRESEARCH_VIEW_DBSERVER_H #define ARANGOD_IRESEARCH__IRESEARCH_VIEW_DBSERVER_H 1 #include "utils/async_utils.hpp" #include "IResearchView.h" #include "Transaction/Status.h" #include "velocypack/Builder.h" #include "VocBase/LogicalView.h" namespace arangodb { class DatabasePathFeature; class TransactionState; struct ViewFactory; // forward declaration class CollectionNameResolver; namespace transaction { class Methods; // forward declaration } // transaction } // arangodb namespace arangodb { namespace iresearch { class AsyncMeta; class IResearchViewDBServer final: public arangodb::LogicalViewClusterInfo { public: virtual ~IResearchViewDBServer() noexcept; ////////////////////////////////////////////////////////////////////////////// /// @brief ensure there is a view instance for the specified 'cid' /// @param force creation of a new instance if none is available in vocbase /// @return an existing instance or create a new instance if none is registred /// on ptr reset the view will be dropped if it has no collections /// @note view created in vocbase() to match callflow during regular startup ////////////////////////////////////////////////////////////////////////////// std::shared_ptr<arangodb::LogicalView> ensure( TRI_voc_cid_t cid, bool create = true ); ////////////////////////////////////////////////////////////////////////////// /// @brief the factory for this type of view ////////////////////////////////////////////////////////////////////////////// static arangodb::ViewFactory const& factory(); virtual void open() override; virtual arangodb::Result properties( arangodb::velocypack::Slice const& properties, bool partialUpdate ) override; //////////////////////////////////////////////////////////////////////////////// /// @return pointer to an index reader containing the datastore record snapshot /// associated with 'state' /// (nullptr == no view snapshot associated with the specified state) /// if force == true && no snapshot -> associate current snapshot //////////////////////////////////////////////////////////////////////////////// irs::index_reader const* snapshot( transaction::Methods& trx, std::vector<std::string> const& shards, IResearchView::Snapshot mode = IResearchView::Snapshot::Find ) const; ////////////////////////////////////////////////////////////////////////////// /// @brief unlink remove 'cid' from the persisted list of tracked collection /// IDs /// @return success == view does not track collection ////////////////////////////////////////////////////////////////////////////// arangodb::Result unlink(TRI_voc_cid_t cid) noexcept; virtual bool visitCollections( CollectionVisitor const& visitor ) const override; protected: virtual arangodb::Result appendVelocyPackDetailed( arangodb::velocypack::Builder& builder, bool forPersistence ) const override; virtual arangodb::Result dropImpl() override; private: struct ViewFactory; // forward declaration std::map<TRI_voc_cid_t, std::shared_ptr<arangodb::LogicalView>> _collections; std::shared_ptr<AsyncMeta> _meta; // the shared view configuration (never null!!!) mutable irs::async_utils::read_write_mutex _mutex; // for use with members IResearchViewDBServer( TRI_vocbase_t& vocbase, arangodb::velocypack::Slice const& info, arangodb::DatabasePathFeature const& dbPathFeature, uint64_t planVersion, std::shared_ptr<AsyncMeta> meta = nullptr ); }; } // iresearch } // arangodb #endif
34.606061
84
0.603546
[ "vector" ]
c156a7a66e5a8098642a7851fcb176466051dc11
2,919
h
C
include/imgsolver/GridFinder.h
fvbakel/nonogram
7a758cf8f6eb447e06451f8b312b134df61f7c8f
[ "MIT" ]
null
null
null
include/imgsolver/GridFinder.h
fvbakel/nonogram
7a758cf8f6eb447e06451f8b312b134df61f7c8f
[ "MIT" ]
null
null
null
include/imgsolver/GridFinder.h
fvbakel/nonogram
7a758cf8f6eb447e06451f8b312b134df61f7c8f
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <imgsolver/constants.h> #include <imgsolver/NumDetector.h> #include <imgsolver/TesseractDetect.h> #include <imgsolver/DnnDetect.h> #include <imgsolver/ImageDebug.h> #include <solvercore/Nonogram.h> namespace imgsolver { // 40% larger gab than the smallest gab is still considered the same number // TODO: make this a member variable that can be set? static const float Y_CLUE_GAB_FACTOR = 1.4; class GridFinder : public ImageDebug { private: cv::Mat *m_org_img; cv::Mat m_gray_img; cv::Mat m_bw_img; cv::Mat m_tmp_org_subset; cv::Mat m_tmp_bw_subset; NumDetector *m_num_detector = nullptr; detector m_detector = TESSERACT; NonogramInput *m_output; std::vector<int> m_x_lines; std::vector<int> m_x_thickness; std::vector<int> m_y_lines; std::vector<int> m_y_thickness; int m_search_offset = 20; int m_x_right_offset = UNDEFINED; int m_x_left_offset = 0; int m_y_bottom_offset = UNDEFINED; int m_smallest_y_clue_gab = UNDEFINED; int m_largest_y_clue_gab = UNDEFINED; int m_y_clue_gab = UNDEFINED; bool m_has_fixed_y_width = false; int m_y_clue_width = UNDEFINED; int m_y_clue_line_thickness= UNDEFINED; bool m_parsed = false; void cleanup_bw_img(); void clear_left_border(); void clear_top_border(); void determine_fixed_width(); void determine_offsets(); void determine_x_lines(); void determine_y_lines(); void process_x_clues(); void process_y_clues(bool determine_y_clue_gab = false); void update_y_clue_gab(cv::Rect &rect); void check_y_clue_gab(); void parse_x_clue_column(cv::Rect &rect); void parse_y_clue_line(cv::Rect &rect); void parse_y_clue_line_fixed_width(); void parse_y_clue_line_gab_separated(); bool extract_clue(cv::Rect &rect_clue, cv::Mat &result); bool bounding_box(cv::Mat &image, cv::Rect &result); int parse_one_number(cv::Mat &image); public: GridFinder( cv::Mat *img, detector digit_detector = TESSERACT, std::string modelname = DEFAULT_MODEL ); ~GridFinder(); void get_location( int x_index, int y_index, cv::Rect &rect ); NonogramInput *parse(); }; }
33.551724
79
0.55841
[ "vector" ]
c15a2e47d06ace6d5bd5e392ade5ce95eb9a7fcb
8,340
h
C
lib/symbolic/headers/vector.h
Sc-lab-2016/lab3
10d59a72ce87684417e126f84ad14fee8bbbe4fd
[ "MIT" ]
1
2019-10-15T16:20:10.000Z
2019-10-15T16:20:10.000Z
lib/symbolic/headers/vector.h
Sc-lab-2016/lab3
10d59a72ce87684417e126f84ad14fee8bbbe4fd
[ "MIT" ]
null
null
null
lib/symbolic/headers/vector.h
Sc-lab-2016/lab3
10d59a72ce87684417e126f84ad14fee8bbbe4fd
[ "MIT" ]
null
null
null
/* SymbolicC++ : An object oriented computer algebra system written in C++ Copyright (C) 2008 Yorick Hardy and Willi-Hans Steeb This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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. */ // vector.h // Vector class #ifndef MVECTOR_H #define MVECTOR_H #include <cassert> #include <cmath> #include <iostream> #include <vector> #include "identity.h" using namespace std; // definition of class Vector template <class T> class Vector: public vector<T> { public: // Constructors Vector(); Vector(int); Vector(int,const T&); Vector(const Vector<T>&); ~Vector(); // Member Functions T& operator [] (int); const T& operator [] (int) const; void reset(int); void reset(int,const T&); // Arithmetic Operators const Vector<T>& operator = (const T&); Vector<T> operator + () const; Vector<T> operator - () const; Vector<T> operator += (const Vector<T>&); Vector<T> operator -= (const Vector<T>&); Vector<T> operator *= (const Vector<T>&); Vector<T> operator /= (const Vector<T>&); Vector<T> operator + (const Vector<T>&) const; Vector<T> operator - (const Vector<T>&) const; Vector<T> operator * (const Vector<T>&) const; Vector<T> operator / (const Vector<T>&) const; Vector<T> operator += (const T&); Vector<T> operator -= (const T&); Vector<T> operator *= (const T&); Vector<T> operator /= (const T&); Vector<T> operator + (const T&) const; Vector<T> operator - (const T&) const; Vector<T> operator * (const T&) const; Vector<T> operator / (const T&) const; T operator | (const Vector<T>&) const; // Dot product / Inner product Vector<T> operator % (const Vector<T>&) const; // Cross product ostream &output(ostream&) const; istream &input(istream&); }; // implementation of class Vector template <class T> Vector<T>::Vector() : vector<T>() { } template <class T> Vector<T>::Vector(int n) : vector<T>(n) { } template <class T> Vector<T>::Vector(int n,const T &value) : vector<T>(n,value) { } template <class T> Vector<T>::Vector(const Vector<T> &v) : vector<T>(v) { } template <class T> Vector<T>::~Vector() { } template <class T> void Vector<T>::reset(int length) { reset(length, zero(T())); } template <class T> T& Vector<T>::operator [] (int i) { return vector<T>::at(i); } template <class T> const T& Vector<T>::operator [] (int i) const { return vector<T>::at(i); } template <class T> void Vector<T>::reset(int length, const T &value) { vector<T>::resize(length); for(int i=0;i<length;i++) vector<T>::at(i) = value; } template <class T> const Vector<T> & Vector<T>::operator = (const T &value) { int length = vector<T>::size(); for(int i=0;i<length;i++) vector<T>::at(i) = value; return *this; } template <class T> Vector<T> Vector<T>::operator + () const { return *this; } template <class T> Vector<T> Vector<T>::operator - () const { return *this * T(-1); } template <class T> Vector<T> Vector<T>::operator += (const Vector<T> &v) { int length = vector<T>::size(); assert(vector<T>::size()==v.size()); for(int i=0;i<length;i++) vector<T>::at(i) += v[i]; return *this; } template <class T> Vector<T> Vector<T>::operator -= (const Vector<T> &v) { int length = vector<T>::size(); assert(vector<T>::size()==v.size()); for(int i=0;i<length;i++) vector<T>::at(i) -= v[i]; return *this; } template <class T> Vector<T> Vector<T>::operator *= (const Vector<T> &v) { int length = vector<T>::size(); assert(vector<T>::size()==v.size()); for(int i=0;i<length;i++) vector<T>::at(i) *= v[i]; return *this; } template <class T> Vector<T> Vector<T>::operator /= (const Vector<T> &v) { int length = vector<T>::size(); assert(vector<T>::size()==v.size()); for(int i=0;i<length;i++) vector<T>::at(i) /= v[i]; return *this; } template <class T> Vector<T> Vector<T>::operator + (const Vector<T> &v) const { Vector<T> result(*this); return result += v; } template <class T> Vector<T> Vector<T>::operator - (const Vector<T> &v) const { Vector<T> result(*this); return result -= v; } template <class T> Vector<T> Vector<T>::operator * (const Vector<T> &v) const { Vector<T> result(*this); return result *= v; } template <class T> Vector<T> Vector<T>::operator / (const Vector<T> &v) const { Vector<T> result(*this); return result /= v; } template <class T> Vector<T> Vector<T>::operator += (const T &c) { int length = vector<T>::size(); for(int i=0;i<length;i++) vector<T>::at(i) += c; return *this; } template <class T> Vector<T> Vector<T>::operator -= (const T &c) { int length = vector<T>::size(); for(int i=0;i<length;i++) vector<T>::at(i) -= c; return *this; } template <class T> Vector<T> Vector<T>::operator *= (const T &c) { int length = vector<T>::size(); for(int i=0;i<length;i++) vector<T>::at(i) *= c; return *this; } template <class T> Vector<T> Vector<T>::operator /= (const T &c) { int length = vector<T>::size(); for(int i=0;i<length;i++) vector<T>::at(i) /= c; return *this; } template <class T> Vector<T> Vector<T>::operator + (const T &c) const { Vector<T> result(*this); return result += c; } template <class T> Vector<T> Vector<T>::operator - (const T &c) const { Vector<T> result(*this); return result -= c; } template <class T> Vector<T> Vector<T>::operator * (const T &c) const { Vector<T> result(*this); return result *= c; } template <class T> Vector<T> Vector<T>::operator / (const T &c) const { Vector<T> result(*this); return result /= c; } template <class T> Vector<T> operator + (const T &c, const Vector<T> &v) { return v+c; } template <class T> Vector<T> operator - (const T &c, const Vector<T> &v) { return -v+c; } template <class T> Vector<T> operator * (const T &c, const Vector<T> &v) { return v*c; } template <class T> Vector<T> operator / (const T &c, const Vector<T> &v) { int length = v.size(); Vector<T> result(v.size()); for(int i=0;i<length;i++) result[i] = c/v[i]; return result; } // Dot Product / Inner Product template <class T> T Vector<T>::operator | (const Vector<T> &v) const { int length = vector<T>::size(); assert(vector<T>::size() == v.size()); T result(zero(T())); for(int i=0;i<length;i++) result = result + vector<T>::at(i)*v[i]; return result; } // Cross Product template <class T> Vector<T> Vector<T>::operator % (const Vector<T> &v) const { assert(vector<T>::size() == 3 && v.size() == 3); Vector<T> result(3); result[0] = vector<T>::at(1)*v[2]-v[1]*vector<T>::at(2); result[1] = v[0]*vector<T>::at(2)-vector<T>::at(0)*v[2]; result[2] = vector<T>::at(0)*v[1]-v[0]*vector<T>::at(1); return result; } template <class T> ostream& Vector<T>::output(ostream &s) const { int lastnum = vector<T>::size(); for(int i=0;i<lastnum;i++) s << "[" << vector<T>::at(i) << "]" << endl; return s; } template <class T> ostream& operator << (ostream &s,const Vector<T> &v) { return v.output(s); } template <class T> istream& Vector<T>::input(istream &s) { int i, num; s.clear(); // set stream state to good s >> num; // read size of Vector if(! s.good()) return s; // can't get an integer, just return vector<T>::resize(num); for(i=0;i<num;i++) { s >> vector<T>::at(i); // read in entries if(! s.good()) { s.clear(s.rdstate() | ios::badbit); return s; } } return s; } template <class T> istream & operator >> (istream &s,Vector<T> &v) { return v.input(s); } #endif
27.344262
75
0.605036
[ "object", "vector" ]
c15ad9a6136b3bd7fa7164ecf229a2b0a917f58b
3,717
h
C
Modules/Core/Common/include/itkRegion.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2020-10-09T18:12:53.000Z
2020-10-09T18:12:53.000Z
Modules/Core/Common/include/itkRegion.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:28:52.000Z
2017-08-18T19:28:52.000Z
Modules/Core/Common/include/itkRegion.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:07:39.000Z
2017-08-18T19:07:39.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkRegion_h #define itkRegion_h #include "itkObject.h" namespace itk { /** \class Region * \brief A region represents some portion or piece of data. * * Region is an abstract class that represents some portion or * piece of a DataObject. A region is used by the pipeline when * processing just a portion of the data, either because 1) memory * limits dictate that the pipeline cannot fit the entire dataset * into memory; 2) the user has requested that only a piece of the * dataset is to be processed; or 3) parallel (multi-threaded) * processing of the data is required. * * There are two types of regions in itk: a structured region that * specifies a rectangular piece of an image (ImageRegion), and a * unstructured region that specifies piece i of N total pieces * (MeshRegion). Depending on the filter (its input and output * types, and its position in the pipeline), ImageRegion or MeshRegion * will be used to describe the region. * * Region is a light-weight object and not reference counted. This * means that is behaves differently than ITK classes that are * reference counted. For example, smart pointer access is not * provided, and the (subclasses') constructor, destructor, * copy constructor and operator= are all public. * * \sa ImageRegion * \sa MeshRegion * \ingroup DataRepresentation * \ingroup ITKCommon */ class ITKCommon_EXPORT Region { public: /** Standard class type aliases. */ using Self = Region; /** Enums used to describe the extent types. */ enum RegionType { ITK_UNSTRUCTURED_REGION, ITK_STRUCTURED_REGION }; /** Standard part of all itk objects. */ itkTypeMacroNoParent(Region); /** Subclasses must return a region type describing whether the region * is structured or unstructured. */ virtual RegionType GetRegionType() const = 0; /** Print the region. */ virtual void Print(std::ostream & os, Indent indent = 0) const; Region() = default; virtual ~Region() = default; protected: /** Methods invoked by Print() to print information about the object * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ virtual void PrintSelf(std::ostream & os, Indent indent) const; virtual void PrintHeader(std::ostream & os, Indent indent) const; virtual void PrintTrailer(std::ostream & os, Indent indent) const; private: }; } // end namespace itk #endif
36.441176
77
0.672854
[ "object" ]
c15ddfe3ae9a63c8177852c3cd83fb835b35582f
1,871
h
C
media/base/android/media_crypto_context.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
media/base/android/media_crypto_context.h
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
media/base/android/media_crypto_context.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_ANDROID_MEDIA_CRYPTO_CONTEXT_H_ #define MEDIA_BASE_ANDROID_MEDIA_CRYPTO_CONTEXT_H_ #include <memory> #include "base/callback.h" #include "base/macros.h" #include "media/base/android/android_util.h" #include "media/base/media_export.h" namespace media { // A class that provides MediaCrypto from MediaDrm to support decrypting and // decoding of encrypted streams, typically by MediaCodec-based decoders. // // Methods can be called on any thread. The registered callbacks can be fired // on any thread. The caller should make sure that the callbacks are posted to // the correct thread. class MEDIA_EXPORT MediaCryptoContext { public: MediaCryptoContext() = default; MediaCryptoContext(const MediaCryptoContext&) = delete; MediaCryptoContext& operator=(const MediaCryptoContext&) = delete; virtual ~MediaCryptoContext() = default; // Notification called when MediaCrypto object is ready. // Parameters: // |media_crypto| - global reference to MediaCrypto object. |media_crypto| is // always a non-null std::unique_ptr, but the JavaRef it // contains can point to a null object. // |requires_secure_video_codec| - true if secure video decoder is required. // Should be ignored if |media_crypto| // contains null MediaCrypto object. using MediaCryptoReadyCB = base::OnceCallback<void(JavaObjectPtr media_crypto, bool requires_secure_video_codec)>; virtual void SetMediaCryptoReadyCB( MediaCryptoReadyCB media_crypto_ready_cb) = 0; }; } // namespace media #endif // MEDIA_BASE_ANDROID_MEDIA_CRYPTO_CONTEXT_H_
37.42
79
0.721539
[ "object" ]
c15f321cc8593d20d731bfd23921d1edd5a08e81
4,856
h
C
irods_specific_implementation/irods_rest_access_implementation.h
alanking/irods_client_rest_cpp
848775e109d9204836488879028109356938ce18
[ "BSD-3-Clause" ]
null
null
null
irods_specific_implementation/irods_rest_access_implementation.h
alanking/irods_client_rest_cpp
848775e109d9204836488879028109356938ce18
[ "BSD-3-Clause" ]
null
null
null
irods_specific_implementation/irods_rest_access_implementation.h
alanking/irods_client_rest_cpp
848775e109d9204836488879028109356938ce18
[ "BSD-3-Clause" ]
null
null
null
#include "irods_rest_api_base.h" #include "filesystem.hpp" #include "rodsClient.h" #include "irods_random.hpp" #include <chrono> #include <ctime> // this is contractually tied directly to the swagger api definition, and the below implementation #define MACRO_IRODS_ACCESS_API_IMPLEMENTATION \ Pistache::Http::Code code; \ std::string message; \ std::tie(code, message) = irods_access_(headers.getRaw("Authorization").value(), path.get(), base); \ response.send(code, message); namespace irods::rest { namespace sc = std::chrono; using sclk = sc::system_clock; namespace fs = irods::experimental::filesystem; namespace fcli = irods::experimental::filesystem::client; using fsp = fs::path; class access : api_base { public: std::tuple<Pistache::Http::Code &&, std::string> operator()( const std::string& _auth_header, const std::string& _logical_path, const std::string& _base_url) { auto conn = get_connection(_auth_header); try { // TODO: can we ensure this is a canonical path? std::string logical_path{decode_url(_logical_path)}; fsp fs_path{logical_path}; auto size = fcli::data_object_size(*conn(), fs_path); // generate a ticket and create the JSON to return to the client std::string ticket{make_ticket()}; nlohmann::json headers = nlohmann::json::array(); headers += std::string{"X-API-KEY: "}+ticket; nlohmann::json results = nlohmann::json::object(); results["url"] = boost::str( boost::format( "%s/stream?path=%s&offset=0&limit=%d") % _base_url % logical_path % size); results["headers"] = headers; // create the ticket in the catalog std::string create{"create"}, read{"read"}; rx_ticket(conn, create, ticket, read, logical_path); // modify it to a single use std::string mod{"mod"}, uses{"uses"}, one{"1"}; rx_ticket(conn, mod, ticket, uses, one); // set the time limit on usage to 30 seconds auto end_time_p{sclk::now()+sc::seconds(30)}; auto end_time_t{sclk::to_time_t(end_time_p)}; std::stringstream end_ss{}; end_ss << end_time_t; std::string expire{"expire"}, end_time{end_ss.str()}; rx_ticket(conn, mod, ticket, expire, end_time); return std::forward_as_tuple( Pistache::Http::Code::Ok, results.dump()); } catch(const irods::exception& _e) { return std::forward_as_tuple( Pistache::Http::Code::Bad_Request, _e.what()); } catch(const std::exception& _e) { return std::forward_as_tuple( Pistache::Http::Code::Bad_Request, _e.what()); } } // operator() private: std::string make_ticket() { const int ticket_len = 15; // random_bytes must be (unsigned char[]) to guarantee that following // modulo result is positive (i.e. in [0, 61]) unsigned char random_bytes[ticket_len]; irods::getRandomBytes( random_bytes, ticket_len ); const char character_set[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; std::string new_ticket{}; for ( int i = 0; i < ticket_len; ++i ) { const int ix = random_bytes[i] % sizeof(character_set); new_ticket += character_set[ix]; } return new_ticket; } // make_ticket // cannot use const due to lack of const on ticket args void rx_ticket( connection_handle& _conn, std::string& _operation, std::string& _ticket, std::string& _type, std::string& _value) { ticketAdminInp_t ticket_inp{}; ticket_inp.arg1 = &_operation[0]; ticket_inp.arg2 = &_ticket[0]; ticket_inp.arg3 = &_type[0]; ticket_inp.arg4 = &_value[0]; ticket_inp.arg5 = nullptr; ticket_inp.arg6 = nullptr; auto err = rcTicketAdmin(_conn(), &ticket_inp); if(err < 0) { THROW( err, std::string{"Failed to call ticket admin for ticket "} + _ticket); } } // rx_ticket }; // class access }; // namespace irods::rest
35.445255
105
0.533567
[ "object" ]
c16be311bb9172fc10986c3326fac2929ba99e45
1,398
h
C
exportNF/release/windows/obj/include/OffsetMenu.h
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/include/OffsetMenu.h
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
exportNF/release/windows/obj/include/OffsetMenu.h
theblobscp/NekoFreakMod-FridayNightFunkin
232bcb08234cfe881fd6d52b13e6ae443e105fd1
[ "BSD-3-Clause" ]
null
null
null
// Generated by Haxe 4.2.1+bf9ff69 #ifndef INCLUDED_OffsetMenu #define INCLUDED_OffsetMenu #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_Option #include <Option.h> #endif HX_DECLARE_CLASS0(OffsetMenu) HX_DECLARE_CLASS0(Option) class HXCPP_CLASS_ATTRIBUTES OffsetMenu_obj : public ::Option_obj { public: typedef ::Option_obj super; typedef OffsetMenu_obj OBJ_; OffsetMenu_obj(); public: enum { _hx_ClassId = 0x52e4f5b2 }; void __construct(::String desc); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="OffsetMenu") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"OffsetMenu"); } static ::hx::ObjectPtr< OffsetMenu_obj > __new(::String desc); static ::hx::ObjectPtr< OffsetMenu_obj > __alloc(::hx::Ctx *_hx_ctx,::String desc); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~OffsetMenu_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("OffsetMenu",f2,d2,21,3b); } bool press(); ::String updateDisplay(); }; #endif /* INCLUDED_OffsetMenu */
26.377358
97
0.731044
[ "object" ]
c16de47cd51c408a5181943b4345d492678ab288
1,229
c
C
firmware/common/sys.c
codebot/betz_experimental
b3890f31072328ef098d61bcce86f3b782861f17
[ "Apache-2.0" ]
null
null
null
firmware/common/sys.c
codebot/betz_experimental
b3890f31072328ef098d61bcce86f3b782861f17
[ "Apache-2.0" ]
null
null
null
firmware/common/sys.c
codebot/betz_experimental
b3890f31072328ef098d61bcce86f3b782861f17
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdio.h> #include "sys.h" #include "stm32f405xx.h" void sys_run_application() { printf("sys_run_application()\r\n"); __disable_irq(); SCB->VTOR = 0x20000; // move the vector table offset // next, we do some extreme low level action and load the new stack // pointer, set the PC to the application, and brace for impact __asm volatile("ldr r0, =0x08020000 \n" "ldr sp, [r0] \n" "ldr pc, [r0, #4] \n"); // BOOM we have now teleported into the application } void sys_reset() { printf("sys_reset()\r\n"); NVIC_SystemReset(); // BOOM }
30.725
75
0.681855
[ "vector" ]
c16e86b42f7eb93fb2703d51e792daf828b03db8
4,334
h
C
inc/BitFunnel/Index/IShard.h
jasonfeihe/BitFunnel
859f3038e1978d066426ebaef17354c8ec408402
[ "MIT" ]
364
2016-08-08T21:45:24.000Z
2022-03-27T13:46:51.000Z
inc/BitFunnel/Index/IShard.h
jasonfeihe/BitFunnel
859f3038e1978d066426ebaef17354c8ec408402
[ "MIT" ]
321
2016-08-08T22:00:28.000Z
2020-11-30T23:03:16.000Z
inc/BitFunnel/Index/IShard.h
jasonfeihe/BitFunnel
859f3038e1978d066426ebaef17354c8ec408402
[ "MIT" ]
44
2016-08-14T16:20:29.000Z
2021-10-03T07:46:26.000Z
// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <cstddef> // ptrdiff_t return value. #include <iosfwd> // std::ostream parameter. #include "BitFunnel/BitFunnelTypes.h" // DocIndex return value. #include "BitFunnel/IInterface.h" // Base class. #include "BitFunnel/Index/RowId.h" // RowId parameter. #include "BitFunnel/NonCopyable.h" // Base class. namespace BitFunnel { class DocumentHandle; class IFileManager; class ITermToText; class IShard : public IInterface { public: // Returns the Id of the shard. virtual ShardId GetId() const = 0; // Returns capacity of a single Slice in the Shard. All Slices in the // Shard have the same capacity. virtual DocIndex GetSliceCapacity() const = 0; // Return the size of the slice buffer in bytes. virtual size_t GetSliceBufferSize() const = 0; // Returns a vector of slice buffers for this shard. The callers needs // to obtain a Token from ITokenManager to protect the pointer to the // list of slice buffers, as well as the buffers themselves. virtual std::vector<void*> const & GetSliceBuffers() const = 0; // Returns the offset of the row in the slice buffer in a shard. virtual ptrdiff_t GetRowOffset(RowId rowId) const = 0; virtual void TemporaryWriteDocumentFrequencyTable( std::ostream& out, ITermToText const * termToText) const = 0; virtual void TemporaryReadAllSlices(IFileManager& fileManager, size_t nbrSlices) = 0; virtual void TemporaryWriteAllSlices(IFileManager& fileManager) const = 0; // // DocumentHandle iterator // // DESIGN NOTE: Can't use the C++ <iterator> pattern because // iterators cannot be abstract base classes (they must be copyable) // and IShard cannot know the implementation of an iterator of its // subclass. Chose to implement a pattern that is similar to // the C++ iterator pattern. In this approach, const_iterator is an // abstract base class which is provided via and std::unique_ptr // from GetIterator(). class const_iterator : public IInterface, NonCopyable { public: virtual const_iterator& operator++() = 0; virtual DocumentHandle operator*() const = 0; virtual bool AtEnd() const = 0; }; // Returns an iterator to the DocumentHandles corresponding to // documents currently active in the index. This method is // thread safe with respect to document addition and deletion. // WARNING: this iterator holds a Token which will prevent // recycling. Be sure to release iterator when finished. virtual std::unique_ptr<const_iterator> GetIterator() = 0; // Returns an std::vector containing the bit densities for each row in // the RowTable with the specified rank. Bit densities are computed // over all slices, for those columns that correspond to active // documents. virtual std::vector<double> GetDensities(Rank rank) const = 0; }; }
42.490196
93
0.677896
[ "vector" ]
c17082a84adb55a88dbd20d31d24236b9815ace5
3,831
h
C
include/klee/SolverImpl.h
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
10
2018-02-13T17:46:38.000Z
2022-03-15T06:20:24.000Z
include/klee/SolverImpl.h
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
8
2018-07-17T22:35:02.000Z
2019-03-11T07:19:00.000Z
include/klee/SolverImpl.h
sysrel/SIFT
32a952c9b5bcf576bbd91c6a7510182b6cb94748
[ "Apache-2.0" ]
7
2018-05-05T15:16:28.000Z
2020-03-23T09:40:28.000Z
//===-- SolverImpl.h --------------------------------------------*- C++ -*-===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef KLEE_SOLVERIMPL_H #define KLEE_SOLVERIMPL_H #include <vector> namespace klee { class Array; class ExecutionState; class Expr; struct Query; /// SolverImpl - Abstract base clase for solver implementations. class SolverImpl { // DO NOT IMPLEMENT. SolverImpl(const SolverImpl&); void operator=(const SolverImpl&); public: SolverImpl() {} virtual ~SolverImpl(); enum SolverRunStatus { SOLVER_RUN_STATUS_SUCCESS_SOLVABLE, SOLVER_RUN_STATUS_SUCCESS_UNSOLVABLE, SOLVER_RUN_STATUS_FAILURE, SOLVER_RUN_STATUS_TIMEOUT, SOLVER_RUN_STATUS_FORK_FAILED, SOLVER_RUN_STATUS_INTERRUPTED, SOLVER_RUN_STATUS_UNEXPECTED_EXIT_CODE, SOLVER_RUN_STATUS_WAITPID_FAILED }; /// computeValidity - Compute a full validity result for the /// query. /// /// The query expression is guaranteed to be non-constant and have /// bool type. /// /// SolverImpl provides a default implementation which uses /// computeTruth. Clients should override this if a more efficient /// implementation is available. /// /// \param [out] result - if /// \f[ \forall X constraints(X) \to query(X) \f] /// then Solver::True, /// else if /// \f[ \forall X constraints(X) \to \lnot query(X) \f] /// then Solver::False, /// else /// Solver::Unknown /// /// \return True on success virtual bool computeValidity(const Query& query, Solver::Validity &result); /// computeTruth - Determine whether the given query expression is provably true /// given the constraints. /// /// The query expression is guaranteed to be non-constant and have /// bool type. /// /// This method should evaluate the logical formula: /// /// \f[ \forall X constraints(X) \to query(X) \f] /// /// Where \f$X\f$ is some assignment, \f$constraints(X)\f$ are the constraints /// in the query and \f$query(X)\f$ is the query expression. /// /// \param [out] isValid - On success, true iff the logical formula is true. /// \return True on success virtual bool computeTruth(const Query& query, bool &isValid) = 0; /// computeValue - Compute a feasible value for the expression. /// /// The query expression is guaranteed to be non-constant. /// /// \return True on success virtual bool computeValue(const Query& query, ref<Expr> &result) = 0; /// \sa Solver::getInitialValues() virtual bool computeInitialValues(const Query& query, const std::vector<const Array*> &objects, std::vector< std::vector<unsigned char> > &values, bool &hasSolution) = 0; /// getOperationStatusCode - get the status of the last solver operation virtual SolverRunStatus getOperationStatusCode() = 0; /// getOperationStatusString - get string representation of the operation /// status code static const char* getOperationStatusString(SolverRunStatus statusCode); virtual char *getConstraintLog(const Query& query) { // dummy return(NULL); } virtual void setCoreSolverTimeout(double timeout) {}; }; } #endif
34.205357
84
0.58131
[ "vector" ]
c17563432e8ae10b3d0dd8c5b06b3fbb7f19d9d5
1,244
h
C
Userland/Libraries/LibJS/Runtime/Temporal/Now.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibJS/Runtime/Temporal/Now.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibJS/Runtime/Temporal/Now.h
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibJS/Runtime/Completion.h> #include <LibJS/Runtime/Object.h> namespace JS::Temporal { class Now final : public Object { JS_OBJECT(Now, Object); public: explicit Now(GlobalObject&); virtual void initialize(GlobalObject&) override; virtual ~Now() override = default; private: JS_DECLARE_NATIVE_FUNCTION(time_zone); JS_DECLARE_NATIVE_FUNCTION(instant); JS_DECLARE_NATIVE_FUNCTION(plain_date_time); JS_DECLARE_NATIVE_FUNCTION(plain_date_time_iso); JS_DECLARE_NATIVE_FUNCTION(zoned_date_time); JS_DECLARE_NATIVE_FUNCTION(zoned_date_time_iso); JS_DECLARE_NATIVE_FUNCTION(plain_date); JS_DECLARE_NATIVE_FUNCTION(plain_date_iso); JS_DECLARE_NATIVE_FUNCTION(plain_time_iso); }; TimeZone* system_time_zone(GlobalObject&); BigInt* system_utc_epoch_nanoseconds(GlobalObject&); Instant* system_instant(GlobalObject&); ThrowCompletionOr<PlainDateTime*> system_date_time(GlobalObject&, Value temporal_time_zone_like, Value calendar_like); ThrowCompletionOr<ZonedDateTime*> system_zoned_date_time(GlobalObject&, Value temporal_time_zone_like, Value calendar_like); }
30.341463
124
0.794212
[ "object" ]
c17c3c1a4ff703f4965bdd4eab83584b57fde61b
560
h
C
examples/ope_terasort/polysort/src/PartitionSampler.h
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
examples/ope_terasort/polysort/src/PartitionSampler.h
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
examples/ope_terasort/polysort/src/PartitionSampler.h
TANGO-Project/cryptango
be6a2d74d238bffd3f3e899ea0eea01966097ebe
[ "Apache-2.0" ]
null
null
null
/* * PartitionSampling.h * * Created on: 12 Jul 2018 * Author: scsjd */ #ifndef SRC_PARTITIONSAMPLER_H_ #define SRC_PARTITIONSAMPLER_H_ #include <string> #include <vector> #include "PartitionList.h" class PartitionSampler{ private: std::size_t numPartitions; double percentSamples; std::vector<std::string> *inputFiles; public: PartitionSampler(std::size_t numPartitions, double percentSamples, std::vector<std::string> *inputFiles); virtual ~PartitionSampler(); PartitionList createPartitions(); }; #endif /* SRC_PARTITIONSAMPLER_H_ */
19.310345
106
0.753571
[ "vector" ]
c17d80e1fa70ba05b83f1e0a693e1023382dac5f
3,104
h
C
media/midi/midi_manager_mac.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
media/midi/midi_manager_mac.h
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
media/midi/midi_manager_mac.h
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright (c) 2013 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 MEDIA_MIDI_MIDI_MANAGER_MAC_H_ #define MEDIA_MIDI_MIDI_MANAGER_MAC_H_ #include <CoreMIDI/MIDIServices.h> #include <stdint.h> #include <vector> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "base/threading/thread.h" #include "media/midi/midi_export.h" #include "media/midi/midi_manager.h" #include "media/midi/midi_service.mojom.h" namespace midi { class MidiService; class MIDI_EXPORT MidiManagerMac final : public MidiManager { public: explicit MidiManagerMac(MidiService* service); MidiManagerMac(const MidiManagerMac&) = delete; MidiManagerMac& operator=(const MidiManagerMac&) = delete; ~MidiManagerMac() override; // MidiManager implementation. void StartInitialization() override; void DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8_t>& data, base::TimeTicks timestamp) override; private: // Initializes CoreMIDI on |client_thread_| asynchronously. Called from // StartInitialization(). void InitializeCoreMIDI(); // Completes CoreMIDI initialization and asks the thread that ran // StartInitialization() to call CompleteStartSession() safely. void CompleteCoreMIDIInitialization(mojom::Result result); // CoreMIDI callback for MIDI notification. // Receives MIDI related event notifications from CoreMIDI. static void ReceiveMidiNotifyDispatch(const MIDINotification* message, void* refcon); void ReceiveMidiNotify(const MIDINotification* message); // CoreMIDI callback for MIDI data. // Each callback can contain multiple packets, each of which can contain // multiple MIDI messages. static void ReadMidiDispatch(const MIDIPacketList* packet_list, void* read_proc_refcon, void* src_conn_refcon); // An internal callback that runs on MidiSendThread. void SendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8_t>& data, base::TimeTicks timestamp); // CoreMIDI client reference. MIDIClientRef midi_client_ GUARDED_BY(midi_client_lock_) = 0; base::Lock midi_client_lock_; // Following members can be accessed without any lock on kClientTaskRunner, // or on I/O thread before calling BindInstance() or after calling // UnbindInstance(). // CoreMIDI other references. MIDIPortRef midi_input_ = 0; MIDIPortRef midi_output_ = 0; std::vector<uint8_t> midi_buffer_; // Keeps track of all sources. std::vector<MIDIEndpointRef> sources_; // Keeps track of all destinations. std::vector<MIDIEndpointRef> destinations_; }; } // namespace midi #endif // MEDIA_MIDI_MIDI_MANAGER_MAC_H_
33.376344
77
0.71424
[ "vector" ]
c17e3ef1821e7b5f4ba9cae358ad86a195eae295
832
c
C
nitan/d/hangzhou/liuhe5.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/d/hangzhou/liuhe5.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/d/hangzhou/liuhe5.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// liuhe5.c // Date: Nov.1997 by Java #include <room.h> inherit ROOM; void create() { set("short", "六和塔"); set("long", @LONG 這裏是六和塔的五層。窗(window)外是濃粧淡抹的西子湖,塔 中玲瓏八角,青磚砌地,雕欄飛檐間粘連了些許蛛網。 LONG); set("exits", ([ "down" : __DIR__"liuhe4", "up" : __DIR__"liuhe6", ])); set("objects", ([ __DIR__"honghua/wei" :1, ])); set("item_desc", ([ "window": "從窗口望出去,錢江東去。近處農田中,有一農夫正荷鋤耕耘。\n", ])); set("no_clean_up", 0); set("coor/x", 759); set("coor/y", -2121); set("coor/z", 49); setup(); } int valid_leave(object me, string dir) { if (dir == "up" && objectp(present("wei chunhua", environment(me)))) return notify_fail("衞春華大吼一聲:我有九條命,你有幾條?放馬過來!\n"); return ::valid_leave(me, dir); }
24.470588
61
0.516827
[ "object" ]
c1826df467621cbb695b108a8412a0abb5f78fec
38,159
c
C
utils/preAlps_utils.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
6
2019-03-28T12:30:06.000Z
2022-02-25T17:42:29.000Z
utils/preAlps_utils.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
1
2019-03-14T16:11:37.000Z
2019-03-14T16:11:37.000Z
utils/preAlps_utils.c
W-Wuxian/preAlps
9718968d3474be821ceb676ceff8e1dee1dae2f0
[ "BSD-3-Clause" ]
3
2020-11-17T22:41:41.000Z
2021-10-05T11:22:04.000Z
/* ============================================================================ Name : preAlps_utils.c Author : Simplice Donfack Version : 0.1 Description : Utils for preAlps Date : Mai 15, 2017 ============================================================================ */ #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdarg.h> #include <cplm_iarray.h> #include <cplm_v0_ivector.h> #include "cplm_utils.h" #include "cplm_matcsr.h" #include "preAlps_intvector.h" #include "preAlps_doublevector.h" #include "preAlps_utils.h" /* * utils */ /* Display a message and stop the execution of the program */ void preAlps_abort(char *s, ... ){ char buff[1024]; va_list arglist; va_start(arglist, s); vsprintf(buff, s, arglist); va_end(arglist); printf("===================\n"); printf("%s\n", buff); printf("Aborting ...\n"); printf("===================\n"); exit(1); } /* * From an array, set one when the node number is a leave. */ void preAlps_binaryTreeIsLeaves(int nparts, int *isLeave){ int i, twoPowerLevel = nparts+1; for(i=0;i<nparts;i++) isLeave[i] = 0; /* Call the recursive interface */ preAlps_binaryTreeIsNodeAtLevel(2, twoPowerLevel, nparts - 1, isLeave); } /* * From an array, set one when the node number is a node at the target Level. * The array should be initialized with zeros before calling this routine */ void preAlps_binaryTreeIsNodeAtLevel(int targetLevel, int twoPowerLevel, int part_root, int *isNodeLevel){ if(twoPowerLevel == targetLevel){ /*We have reached a target node level */ isNodeLevel[part_root] = 1; }else if(twoPowerLevel>targetLevel){ if(twoPowerLevel>2){ twoPowerLevel = (int) twoPowerLevel/2; /*right*/ preAlps_binaryTreeIsNodeAtLevel(targetLevel, twoPowerLevel , part_root - 1, isNodeLevel); /*left*/ preAlps_binaryTreeIsNodeAtLevel(targetLevel, twoPowerLevel, part_root - twoPowerLevel, isNodeLevel); } } } /* * Create a block arrow structure from a matrix A * comm: * input: the communicator for all the processors calling the routine * m: * input: the number of rows of the global matrix * A: * input: the input matrix * AP: * output: the matrix permuted into a block arrow structure (relevant only on proc 0) * perm: * output: the permutation vector * nbparts: * output: the number of the partition created * partCount: * output: the number of rows in each part * partBegin: * output: the begining rows of each part. */ int preAlps_blockArrowStructCreate(MPI_Comm comm, int m, CPLM_Mat_CSR_t *A, CPLM_Mat_CSR_t *AP, int *perm, int *nbparts, int **partCount, int **partBegin){ int ierr = 0, nbprocs, my_rank, root = 0; int i, j, count = 0, mloc; int *order = NULL, *sizes = NULL, *partCountWork=NULL, *partBeginWork=NULL; int *partwork = NULL; int *mcounts, *moffsets; int *mwork = NULL; //vector array of size m int nparts, level; CPLM_Mat_CSR_t locAP = CPLM_MatCSRNULL(); MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); // Allocate Workspace if ( !(mcounts = (int *) malloc((nbprocs) * sizeof(int))) ) preAlps_abort("Malloc fails for mcounts[]."); if ( !(moffsets = (int *) malloc((nbprocs+1) * sizeof(int))) ) preAlps_abort("Malloc fails for moffsets[]."); // Split the number of rows among the processors for(i=0;i<nbprocs;i++){ CPLM_nsplit(m, nbprocs, i, &mcounts[i], &moffsets[i]); } moffsets[nbprocs] = m; // Remove the diagonal in order to call ParMetis. ParMetis crashes if the diagonal is kept inplace. (use AP as workspace) if(my_rank==root) ierr = CPLM_MatCSRDelDiag(A, AP);preAlps_checkError(ierr); // Distribute the matrix to all procs ierr = CPLM_MatCSRBlockRowScatterv(AP, &locAP, moffsets, root, comm); preAlps_checkError(ierr); mloc = locAP.info.m; /* * Partition the matrix */ nparts = 1; level = 0; while(nparts<nbprocs){ nparts = 2*nparts+1; level++; } if ( !(order = (int *) malloc((mloc*sizeof(int)))) ) preAlps_abort("Malloc fails for order[].");///mloc if ( !(sizes = (int *) malloc((nparts*sizeof(int)))) ) preAlps_abort("Malloc fails for sizes[]."); //2*Ptilde CPLM_IArray_setValue(sizes, nparts, -1); #ifdef MAT_CUSTOM_PARTITIONING /* Custom partitioning */ int *permWork, perm_len, *sizesWork, sizes_len; if ( !(permWork = (int *) malloc(m*sizeof(int))) ) preAlps_abort("Malloc fails for permWork[]."); if ( !(sizes = (int *) malloc((nparts*sizeof(int)))) ) preAlps_abort("Malloc fails for sizes[]."); if(my_rank==0) printf("**** Reading partitioning data from Files\n"); preAlps_intVector_load("dump/partition_perm.txt", &permWork, &perm_len); if(perm_len!=m) { preAlps_abort("Error in the number of rows. Nrows from file:%d, matrix nrows:%d\n", perm_len, m); } memcpy(perm, permWork, perm_len*sizeof(int)); preAlps_intVector_load("dump/partition_sizes.txt", &sizesWork, &sizes_len); if(sizes_len!=nparts) { preAlps_abort("Error in the number of partitions. Nparts from file:%d, matrix nparts:%d\n", sizes_len, nparts); } memcpy(sizes, sizesWork, sizes_len*sizeof(int)); free(permWork); free(sizesWork); #else CPLM_MatCSROrderingND(comm, &locAP, moffsets, order, sizes); preAlps_intVector_printSynchronized(order, mloc, "order", "Order after ordering", comm); // Gather the ordering infos from all to all ierr = MPI_Allgatherv(order, mloc, MPI_INT, perm, mcounts, moffsets, MPI_INT, comm); preAlps_checkError(ierr); #endif preAlps_intVector_printSynchronized(perm, m, "perm", "Permutation vector after ordering", comm); if ( !(mwork = (int *) malloc(m*sizeof(int))) ) preAlps_abort("Malloc fails for mwork[]."); if ( !(partwork = (int *) malloc((nparts*sizeof(int)))) ) preAlps_abort("Malloc fails for partwork[]."); if ( !(partCountWork = (int *) malloc((nparts*sizeof(int)))) ) preAlps_abort("Malloc fails for partCountWork[]."); if ( !(partBeginWork = (int *) malloc((nparts+1)*sizeof(int))) ) preAlps_abort("Malloc fails for partBeginWork[]."); // Permute the array order returned by ParMetis such as children are followed by their parent node (put each separator close to its children) preAlps_NodeNDPostOrder(nparts, sizes, partCountWork); // Compute the begining of each part partBeginWork[0] = 0; for(i=0;i<nparts;i++) partBeginWork[i+1] = partBeginWork[i] + partCountWork[i]; // Get the permutation vector preAlps_pinv_outplace (perm, m, mwork); preAlps_intVector_printSynchronized(mwork, m, "mwork", "Permutation vector after ordering", comm); // Determine the leaves from the partitioning preAlps_binaryTreeIsLeaves(nparts, partwork); // Update the permutation vector in order to permute the separators at the end of the permutated matrix count = 0; int nbLeaves = 0; for(i=0;i<nparts;i++) partCountWork[i] = 0; for(i=0;i<nparts;i++) { if(partwork[i]==1) { //is a leave for(j=partBeginWork[i];j<partBeginWork[i+1];j++){ perm[count++] = mwork[j]; } /* update partCountWork */ partCountWork[nbLeaves] = partBeginWork[i+1] - partBeginWork[i]; nbLeaves++; } } partCountWork[nbLeaves] = 0; for(i=0;i<nparts;i++) { if(partwork[i]==0) { //is a separator for(j=partBeginWork[i];j<partBeginWork[i+1];j++){ perm[count++] = mwork[j]; } /* update partCountWork */ partCountWork[nbLeaves] += partBeginWork[i+1] - partBeginWork[i]; //keep the separator at the end } } // Update the begining position of each partition partBeginWork[0] = 0; for(i=0;i<nparts;i++) partBeginWork[i+1] = partBeginWork[i] + partCountWork[i]; // Permute the input matrix to move the separator to the end if(my_rank==0) { ierr = CPLM_MatCSRPermute(A, AP, perm, perm, PERMUTE);preAlps_checkError(ierr); #ifdef SAVE_PERM preAlps_intVector_save(perm, m, "dump/perm.out.txt", "Permutation vector after NodeND"); preAlps_intVector_save(sizes, nparts, "dump/sizes.out.txt", "Sizes vector after NodeND"); #endif } // free memory free(mwork); if(partwork) free(partwork); if(sizes) free(sizes); free(mcounts); free(moffsets); // Set the output *nbparts = nbLeaves+1; //the number of nodes + the separator *partCount = partCountWork; *partBegin = partBeginWork; return ierr; } /* * Distribute the matrix which has a block Arrow structure to the processors. */ int preAlps_blockArrowStructDistribute(MPI_Comm comm, int m, CPLM_Mat_CSR_t *AP, int *perm, int nparts, int *partCount, int *partBegin, CPLM_Mat_CSR_t *locAP, int *newPerm, CPLM_Mat_CSR_t *Aii, CPLM_Mat_CSR_t *Aig, CPLM_Mat_CSR_t *Agi, CPLM_Mat_CSR_t *locAgg, int *sep_mcounts, int *sep_moffsets){ int ierr = 0; int my_rank, nbprocs, root = 0; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); /* * Distribute the nparts-1 first blocks of the matrix to all procs */ ierr = CPLM_MatCSRBlockRowScatterv(AP, locAP, partBegin, root, comm); preAlps_checkError(ierr); /* * Extract the block Aii, Agi and create Aig = Agi^T */ //Aii CPLM_MatCSRBlockColumnExtract(locAP, nparts, partBegin, my_rank, Aii); //Aig CPLM_MatCSRBlockColumnExtract(locAP, nparts, partBegin, nparts-1, Aig); // Get the matrix Agi: Transpose Aig to get Agi CPLM_MatCSRTranspose(Aig, Agi); /* * Permute and distribute the separator close to each procs */ preAlps_blockArrowStructSeparatorDistribute(comm, m, AP, perm, nparts, partCount, partBegin, locAP, newPerm, locAgg, sep_mcounts, sep_moffsets); return ierr; } /* * Perform a block arrow partitioning of a matrix and distribute the separator to all procs * comm: * input: the communicator for all the processors calling the routine * A: * input: the input matrix on processor 0 * locAP: * output: the local permuted matrix on each proc after the preconditioner is built * partCount: * output: the number of rows in each part * partBegin: * output: the begining rows of each part. * perm: * output: the permutation vector */ int preAlps_blockArrowStructPartitioning(MPI_Comm comm, CPLM_Mat_CSR_t *A, CPLM_Mat_CSR_t *locAP, int **partCount, int **partBegin, int *perm){ int ierr = 0, nbprocs, my_rank, root = 0; int *perm1=NULL, m, n, nnz; int nparts, *partCountWork=NULL, *partBeginWork=NULL; int *sep_mcounts = NULL, *sep_moffsets=NULL; CPLM_Mat_CSR_t AP = CPLM_MatCSRNULL(); CPLM_Mat_CSR_t *Aii = NULL, *Aig =NULL, *Agi=NULL, *Aggloc=NULL; // Let me know who I am at each level MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); // Create matrix objects CPLM_MatCSRCreateNULL(&Aii); CPLM_MatCSRCreateNULL(&Aig); CPLM_MatCSRCreateNULL(&Agi); CPLM_MatCSRCreateNULL(&Aggloc); // Broadcast the global matrix dimension from the root to the other procs CPLM_MatCSRDimensions_Bcast(A, root, &m, &n, &nnz, comm); // Allocate memory for the permutation array //if ( !(perm = (int *) malloc(m*sizeof(int))) ) preAlps_abort("Malloc fails for perm[]."); if ( !(perm1 = (int *) malloc(m*sizeof(int))) ) preAlps_abort("Malloc fails for perm1[]."); // Allocate memory for the distribution of the separator if ( !(sep_mcounts = (int *) malloc((nbprocs) * sizeof(int))) ) preAlps_abort("Malloc fails for sep_mcounts[]."); if ( !(sep_moffsets = (int *) malloc((nbprocs+1) * sizeof(int))) ) preAlps_abort("Malloc fails for sep_moffsets[]."); // Create a block arrow structure of the matrix preAlps_blockArrowStructCreate(comm, m, A, &AP, perm1, &nparts, &partCountWork, &partBeginWork); // Check if each processor has at least one block if(nbprocs!=nparts-1){ preAlps_abort("This number of process is not support yet. Please use a multiple of 2. nbprocs (level 1): %d, nparts created:%d\n", nbprocs, nparts-1); } // Distribute the permuted matrix to all the processors //TODO: create a distribute version which will not allocate the matrices Aii, Aig, Agi, Aggloc when they are not needed preAlps_blockArrowStructDistribute(comm, m, &AP, perm1, nparts, partCountWork, partBeginWork, locAP, perm, Aii, Aig, Agi, Aggloc, sep_mcounts, sep_moffsets); //Save partitioning arrays *partCount = partCountWork; *partBegin = partBeginWork; //Free matrices objects if(Aii) CPLM_MatCSRFree(Aii); if(Aig) CPLM_MatCSRFree(Aig); if(Agi) CPLM_MatCSRFree(Agi); if(Aggloc) CPLM_MatCSRFree(Aggloc); //free separator infos if(sep_mcounts) free(sep_mcounts); if(sep_moffsets) free(sep_moffsets); // Free memory free(perm1); CPLM_MatCSRFree(&AP); return ierr; } /* Distribute the separator to each proc and permute the matrix such as their are contiguous in memory */ int preAlps_blockArrowStructSeparatorDistribute(MPI_Comm comm, int m, CPLM_Mat_CSR_t *AP, int *perm, int nparts, int *partCount, int *partBegin, CPLM_Mat_CSR_t *locAP, int *newPerm, CPLM_Mat_CSR_t *locAgg, int *sep_mcounts, int *sep_moffsets){ int ierr=0, my_rank, nbprocs, root = 0; int sep_nrows; int *mwork, *permIdentity, i, j, count; CPLM_Mat_CSR_t sepAP = CPLM_MatCSRNULL(), sepAPloc = CPLM_MatCSRNULL(), Awork = CPLM_MatCSRNULL(); MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); if(my_rank==root){ // get the separator block (last block rows) CPLM_IVector_t rowPart = CPLM_IVectorNULL(); CPLM_IVectorCreateFromPtr(&rowPart, nparts+1, partBegin); CPLM_MatCSRGetRowPanel(AP, &sepAP, &rowPart, nparts-1); } // Workspace if ( !(mwork = (int *) malloc(m * sizeof(int))) ) preAlps_abort("Malloc fails for mwork[]."); if ( !(permIdentity = (int *) malloc(m * sizeof(int))) ) preAlps_abort("Malloc fails for permIdentity[]."); // Get the number of rows of the separator sep_nrows = partCount[nparts-1]; // Split the separator among all the processors for(i=0;i<nbprocs;i++){ CPLM_nsplit(sep_nrows, nbprocs, i, &sep_mcounts[i], &sep_moffsets[i]); } sep_moffsets[nbprocs] = sep_nrows; //Distribute the separator from the root to each procs ierr = CPLM_MatCSRBlockRowScatterv(&sepAP, &sepAPloc, sep_moffsets, root, comm); preAlps_checkError(ierr); //Extract the local part of the schur complement CPLM_MatCSRBlockColumnExtract(&sepAPloc, nparts, partBegin, nparts-1, locAgg); //merge each block received with the local matrix CPLM_MatCSRRowsMerge(locAP, &sepAPloc, &Awork); // Compute the global permutation vector which bring the rows of each process close to their initial block count = 0; for(i=0;i<nbprocs;i++){ // The initial rows of the processor after the partitioning for(j=0;j<partCount[i];j++){ mwork[count++] = partBegin[i]+j; } // The rows obtained from the separator for(j=0;j<sep_mcounts[i];j++){ mwork[count++] = partBegin[nparts-1]+sep_moffsets[i]+j; } } // Update the global permutation vector preAlps_intVector_permute(mwork, perm, newPerm, m); // Update the number of rows for each procs for(i=0;i<nbprocs;i++) partCount[i] += sep_mcounts[i]; // Update the begining positiong of each partition partBegin[0] = 0; for(i=0;i<nparts;i++) partBegin[i+1] = partBegin[i] + partCount[i]; //Apply the same permutation on the columns of the matrix to preserve the symmetry for(i=0;i<m;i++) permIdentity[i] = i; ierr = CPLM_MatCSRPermute(&Awork, locAP, permIdentity, mwork, PERMUTE);preAlps_checkError(ierr); free(permIdentity); free(mwork); CPLM_MatCSRFree(&Awork); CPLM_MatCSRFree(&sepAPloc); if(my_rank==root) CPLM_MatCSRFree(&sepAP); return ierr; } /* * * First permute the matrix using kway partitioning * Permute each block row such as any row with zeros outside the diagonal move * to the bottom on the matrix (ODB) * * comm: * input: the communicator for all the processors calling the routine * A: * input: the input matrix * locA: * output: the matrix permuted into a block arrow structure on each procs * perm: * output: the permutation vector * partBegin: * output: the begining rows of each part. * nbDiagRows: * output: the number of rows in the diag of each Row block */ int preAlps_blockDiagODBStructCreate(MPI_Comm comm, CPLM_Mat_CSR_t *A, CPLM_Mat_CSR_t *locA, int *perm, int **partBegin, int *nbDiagRows){ int i, ierr=0, my_rank, nbprocs, root = 0; CPLM_IVector_t idxRowBegin = CPLM_IVectorNULL(), idxColBegin = CPLM_IVectorNULL(); CPLM_IVector_t Iperm = CPLM_IVectorNULL(); CPLM_Mat_CSR_t AP = CPLM_MatCSRNULL(); int *workColPerm; int n; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); /* * Partition the matrix on proc 0 and distribute (TODO: use parMETIS) */ if(my_rank==root){ #ifdef MAT_LFAT5 /* The smallest SPD matrix on matrix-market for debugging purpose */ /*DEBUG: reproductible permutation */ ierr = CPLM_IVectorMalloc(&idxRowBegin, nbprocs+1);preAlps_checkError(ierr); //MEtis on Matlab perm[0]=1;perm[1]=5;perm[2]=9;perm[3]=2;perm[4]=6;perm[5]=10;perm[6]=0; perm[7]=3;perm[8]=4;perm[9]=7;perm[10]=8;perm[11]=11;perm[12]=12;perm[13]=13; idxRowBegin.val[0]= 0;idxRowBegin.val[1]= 3;idxRowBegin.val[2]= 6; idxRowBegin.val[3]= 10; idxRowBegin.val[4]= 14; //CPLM_IVectorPrintf("***** ATT: Permutation vector for reproductibility",&perm); //CPLM_IVectorPrintf("***** ATT: Row position for reproductibility",&idxRowBegin); #elif defined(MAT_CUSTOM_PARTITIONING_FILE) /* The custom already permuted matrix and the corresponding permutation vector */ char permFile[250], rowPosFile[250]; sprintf(permFile, "matrix/%s.perm.txt", MAT_CUSTOM_PARTITIONING_FILE); sprintf(rowPosFile, "matrix/%s.rowPos.txt", MAT_CUSTOM_PARTITIONING_FILE); printf("Loading partititioning details from files: Perm vector:%s, rowPos:%s ... \n", permFile, rowPosFile); /* This matrice provides its own permutation vector */ CPLM_IVectorLoad(permFile, &Iperm, 0); //perm.nval CPLM_IVectorLoad(rowPosFile, &idxRowBegin, 0); //idxRowBegin.nval //CPLM_IVectorLoad("matrix/ela12.perm.txt", &perm, A->info.m); //perm.nval //CPLM_IVectorLoad("matrix/ela12.rowPos.txt", &idxRowBegin, nbprocs+1); //idxRowBegin.nval /* Copy and Convert to zero based indexing */ for(i=0;i<Iperm.nval;i++) perm[i]= Iperm[i] - 1; for(i=0;i<idxRowBegin.nval;i++) idxRowBegin.val[i]-=1; #ifdef DEBUG preAlps_permVectorCheck(perm, perm); #endif printf("Loading ... done\n"); //CPLM_IVectorPrintf("***** ATT: CUSTOM matrix, Permutation vector for reproductibility",&perm); //CPLM_IVectorPrintf("***** ATT: CUSTOM matrix, Row position for reproductibility",&idxRowBegin); //Check the size int m_expected = 0; for(i=0;i<nbprocs;i++) m_expected+=(idxRowBegin.val[i+1] - idxRowBegin.val[i]); if(A->info.m!=m_expected){ preAlps_abort("Error: the sum of the rows in the provided partitioning: %d is different to the matrix size:%d\n", m_expected, A->info.m); } CPLM_IVectorFree(&Iperm); #else /* Use metis to partition the matrix */ ierr = CPLM_metisKwayOrdering(A, &Iperm, nbprocs, &idxRowBegin);preAlps_checkError(ierr); //CPLM_IVectorPrintf("Permutation vector returned by Kway",&perm); //CPLM_IVectorPrintf("Row position",&idxRowBegin); for(i=0;i<Iperm.nval;i++) perm[i]= Iperm.val[i]; CPLM_IVectorFree(&Iperm); #endif #ifdef MAT_CUSTOM_PARTITIONING_FILE CPLM_MatCSRCopy(A, &AP); CPLM_MatCSRPrintfInfo("A Info", A); CPLM_MatCSRPrintfInfo("AP info", &AP); #else ierr = CPLM_MatCSRPermute(A, &AP, perm, perm, PERMUTE);preAlps_checkError(ierr); #endif CPLM_MatCSRPrintCoords(&AP, "Permuted matrix from Kway"); #ifdef BUILDING_MATRICES_DUMP printf("Dumping the matrix ...\n"); CPLM_MatCSRSave(&AP, "dump_AP.mtx"); printf("Dumping the matrix ... done\n"); #endif }else{ /*Allocate memory for the partitioning vector*/ ierr = CPLM_IVectorMalloc(&idxRowBegin, nbprocs+1);preAlps_checkError(ierr); } /* * distribute the matrix using block row data distribution */ /*Broadcast the Block row distribution of the global matrix*/ MPI_Bcast(idxRowBegin.val, idxRowBegin.nval, MPI_INT, root, comm); preAlps_intVector_printSynchronized(idxRowBegin.val, idxRowBegin.nval, "idxRowBegin", "after dist.", comm); ierr = CPLM_MatCSRBlockRowScatterv(&AP, locA, idxRowBegin.val, root, comm); preAlps_checkError(ierr); if(my_rank==root){ CPLM_MatCSRFree(&AP); } CPLM_MatCSRPrintSynchronizedCoords (locA, comm, "locA", "Recv locA"); n = locA->info.n; //workspace of the size of the number of column of the global matrix if ( !(workColPerm = (int *) malloc(n * sizeof(int))) ) preAlps_abort("Malloc fails for workColPerm[]."); /* * Permute the off diag rows on each local matrix to the bottom (inplace) */ idxColBegin = idxRowBegin; //The matrix is symmetric preAlps_permuteOffDiagRowsToBottom(locA, idxColBegin.val, nbDiagRows, workColPerm, comm); CPLM_MatCSRPrintSynchronizedCoords (locA, comm, "locA", "2.0 locA after permuteOffDiagrows"); preAlps_int_printSynchronized(*nbDiagRows, "nbDiagRows", comm); *partBegin = idxRowBegin.val; free(workColPerm); return ierr; } /* * Check errors * No need to call this function directly, use preAlps_checkError() instead. */ void preAlps_checkError_srcLine(int err, int line, char *src){ if(err){ char str[250]; sprintf(str, "Error %d, line %d in file %s", err, line, src); preAlps_abort(str); } } /* Create a multilevel communicator by spliting the communicator on two groups based on the number of processors provided*/ int preAlps_comm2LevelsSplit(MPI_Comm comm, int npLevel1, MPI_Comm *commMultilevel){ int ierr = 0, nbprocs, my_rank, npLevel2, masterLevelMark, localLevelMark; MPI_Comm comm_masterLevel = MPI_COMM_NULL, comm_localLevel = MPI_COMM_NULL; //Get some infos about the communicator MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); // Check args if((npLevel1<=0) || (npLevel1>nbprocs)) npLevel1 = nbprocs; // Number of processors within each blocks npLevel2 = nbprocs / npLevel1; //printf("npLevel1:%d, npLevel2:%d\n", npLevel1, npLevel2); // Create a communicator with only the master of each groups of procs masterLevelMark = my_rank%npLevel2; MPI_Comm_split(comm, masterLevelMark==0?0:MPI_UNDEFINED, my_rank, &comm_masterLevel); // Create a communicator with only the process of each local groups localLevelMark = my_rank / npLevel2; MPI_Comm_split(comm, localLevelMark, my_rank, &comm_localLevel); //Save the communicator commMultilevel[0] = comm; commMultilevel[1] = comm_masterLevel; commMultilevel[2] = comm_localLevel; return ierr; } /* Display statistiques min, max and avg of a double*/ void preAlps_dstats_display(MPI_Comm comm, double d, char *str){ int my_rank, nbprocs; int root = 0; double dMin, dMax, dSum; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); MPI_Reduce(&d, &dMin, 1, MPI_DOUBLE, MPI_MIN, root, comm); MPI_Reduce(&d, &dMax, 1, MPI_DOUBLE, MPI_MAX, root, comm); MPI_Reduce(&d, &dSum, 1, MPI_DOUBLE, MPI_SUM, root, comm); if(my_rank==0){ printf("%s: min: %.2f , max: %.2f , avg: %.2f\n", str, dMin, dMax, (double) dSum/nbprocs); } } /* MPI custom function to sum the column of a matrix using MPI_REDUCE */ void preAlps_DtColumnSum(void *invec, void *inoutvec, int *len, MPI_Datatype *dtype) { int i; double *invec_d = (double*) invec; double *inoutvec_d = (double*) inoutvec; for ( i=0; i<*len; i++ ) inoutvec_d[i] += invec_d[i]; } /* * Each processor print the value of type int that it has * Work only in debug (-DDEBUG) mode * a: * The variable to print * s: * The string to display before the variable */ void preAlps_int_printSynchronized(int a, char *s, MPI_Comm comm){ #ifdef DEBUG int i; int TAG_PRINT = 4; MPI_Status status; int b, my_rank, nbprocs; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); if(my_rank ==0){ printf("[%d] %s: %d\n", my_rank, s, a); for(i = 1; i < nbprocs; i++) { MPI_Recv(&b, 1, MPI_INT, i, TAG_PRINT, comm, &status); printf("[%d] %s: %d\n", i, s, b); } } else{ MPI_Send(&a, 1, MPI_INT, 0, TAG_PRINT, comm); } MPI_Barrier(comm); #endif } /*Sort the row index of a CSR matrix*/ void preAlps_matrix_colIndex_sort(int m, int *xa, int *asub, double *a){ int i,j,k; int *asub_ptr, row_nnz, itmp; double *a_ptr, dtmp; for (k=0; k<m; k++){ asub_ptr = &asub[xa[k]]; a_ptr = &a[xa[k]]; row_nnz = xa[k+1] - xa[k]; for(i=0;i<row_nnz;i++){ for(j=0;j<i;j++){ if(asub_ptr[i]<asub_ptr[j]){ /*swap column index*/ itmp=asub_ptr[i]; asub_ptr[i]=asub_ptr[j]; asub_ptr[j]=itmp; /*swap values */ dtmp=a_ptr[i]; a_ptr[i]=a_ptr[j]; a_ptr[j]=dtmp; } } } } } /* * Compute A1 = A(pinv,q) where pinv and q are permutations of 0..m-1 and 0..n-1. * if pinv or q is NULL it is considered as the identity */ void preAlps_matrix_permute (int n, int *xa, int *asub, double *a, int *pinv, int *q,int *xa1, int *asub1,double *a1) { int j, jp, i, nz = 0; for (i = 0 ; i < n ; i++){ xa1 [i] = nz ; jp = q==NULL ? i: q [i]; for (j = xa [jp] ; j < xa [jp+1] ; j++){ asub1 [nz] = pinv==NULL ? asub [j]: pinv [asub [j]] ; a1 [nz] = a [j] ; nz++; } } xa1 [n] = nz ; /*Sort the row index of the matrix*/ preAlps_matrix_colIndex_sort(n, xa1, asub1, a1); } /* * We consider one binary tree A and two array part_in and part_out. * part_in stores the nodes of A as follows: first all the children at the last level n, * then all the children at the level n-1 from left to right, and so on, * while part_out stores the nodes of A in depth first search, so each parent node follows all its children. * The array part_in is compatible with the array sizes returned by ParMETIS_V3_NodeND. * part_out[i] = j means node i in part_in correspond to node j in part_in. */ void preAlps_NodeNDPostOrder(int nparts, int *part_in, int *part_out){ int pos = nparts-1; int twoPowerLevel = nparts+1; int level = twoPowerLevel; while(level>1){ preAlps_NodeNDPostOrder_targetLevel(level, twoPowerLevel, nparts-1, part_in, part_out, &pos); level = (int) level/2; } } /* * Number the nodes at level targetLevel and decrease the value of pos. */ void preAlps_NodeNDPostOrder_targetLevel(int targetLevel, int twoPowerLevel, int part_root, int *part_in, int *part_out, int *pos){ if(twoPowerLevel == targetLevel){ // We have reached the target level, number the node and decrease the value of pos part_out[part_root] = part_in[(*pos)--]; }else if(twoPowerLevel>targetLevel){ if(twoPowerLevel>2){ twoPowerLevel = (int) twoPowerLevel/2; // Right preAlps_NodeNDPostOrder_targetLevel(targetLevel, twoPowerLevel , part_root - 1, part_in, part_out, pos); // Left preAlps_NodeNDPostOrder_targetLevel(targetLevel, twoPowerLevel, part_root - twoPowerLevel, part_in, part_out, pos); } } } /* pinv = p', or p = pinv' */ int *preAlps_pinv (int const *p, int n){ int k, *pinv ; pinv = (int *) malloc (n *sizeof (int)) ; /* allocate memory for the results */ for (k = 0 ; k < n ; k++) pinv [p [k]] = k ;/* invert the permutation */ return (pinv) ; /* return result */ } /* pinv = p', or p = pinv' */ int preAlps_pinv_outplace (int const *p, int n, int *pinv){ int k ; for (k = 0 ; k < n ; k++) pinv [p [k]] = k ;/* invert the permutation */ return 0; /* return result */ } /* * Permute the rows of the matrix with offDiag elements at the bottom * locA: * input: the local part of the matrix owned by the processor calling this routine * idxRowBegin: * input: the global array to indicate the partition of each column * nbDiagRows: * output: the number of rows permuted on the diagonal * colPerm * output: a preallocated vector of the size of the number of columns of A * to return the global permutation vector */ int preAlps_permuteOffDiagRowsToBottom(CPLM_Mat_CSR_t *locA, int *idxColBegin, int *nbDiagRows, int *colPerm, MPI_Comm comm){ int i,j, pos = 0, ierr = 0, nbOffDiagRows = 0, my_rank, nbprocs; int *mark; int *locRowPerm; CPLM_Mat_CSR_t locAP = CPLM_MatCSRNULL(); int *recvcounts; MPI_Comm_rank(comm, &my_rank); MPI_Comm_size(comm, &nbprocs); int mloc = locA->info.m; int n = locA->info.n; preAlps_int_printSynchronized(mloc, "mloc", comm); preAlps_int_printSynchronized(idxColBegin[my_rank], "mcolBegin", comm); preAlps_int_printSynchronized(idxColBegin[my_rank+1], "mcol End", comm); #ifdef DEBUG printf("[%d] permuteOffDiagRowsToBottom mloc:%d, n:%d\n", my_rank, mloc, n); #endif if ( !(mark = (int *) malloc(mloc*sizeof(int))) ) preAlps_abort("Malloc fails for mark[]."); if ( !(locRowPerm = (int *) malloc(mloc*sizeof(int))) ) preAlps_abort("Malloc fails for locRowPerm[]."); //ierr = CPLM_IVectorMalloc(&locRowPerm, locA->info.m); preAlps_checkError(ierr); //Compute the number of rows offDiag for (i=0; i< mloc; i++){ mark[i] = -1; for (j=locA->rowPtr[i]; j<locA->rowPtr[i+1]; j++){ if(locA->colInd[j] < idxColBegin[my_rank] || locA->colInd[j]>=idxColBegin[my_rank+1]){ /* Off Diag element */ mark[i] = pos++; nbOffDiagRows++; break; /* next row*/ } } } //Construct the local row permutation vector pos = 0; /* Set the number of rows permuted on the diagonal*/ *nbDiagRows = mloc - nbOffDiagRows; for (i=0; i<mloc; i++){ if(mark[i]==-1) { locRowPerm[pos++] = i; //diag elements } else { locRowPerm[mark[i] + (*nbDiagRows)] = i; //nbOffDiagRows--; } } #ifdef DEBUG preAlps_intVector_printSynchronized(locRowPerm, mloc, "locRowPerm", "locRowPerm in permuteOffDiag", comm); preAlps_permVectorCheck(locRowPerm, mloc); #endif if ( !(recvcounts = (int *) malloc(nbprocs*sizeof(int))) ) preAlps_abort("Malloc fails for recvcounts[]."); for(i=0;i<nbprocs;i++) recvcounts[i] = idxColBegin[i+1] - idxColBegin[i]; preAlps_intVector_printSynchronized(recvcounts, nbprocs, "recvcounts", "recvcounts in permuteOffDiag", comm); ierr = MPI_Allgatherv(locRowPerm, mloc, MPI_INT, colPerm, recvcounts, idxColBegin, MPI_INT, comm); preAlps_checkError(ierr); #ifdef DEBUG preAlps_intVector_printSynchronized(colPerm, n, "colPerm", "colPerm in permuteOffDiag", comm); #endif //Update global indexes of colPerm for(i=0;i<nbprocs;i++){ for(j=idxColBegin[i];j<idxColBegin[i+1];j++){ colPerm[j]+=idxColBegin[i]; } } //CPLM_IVectorPrintSynchronized (colPerm, comm, "colPerm", "global colPerm in permuteOffDiag"); if(my_rank==0) preAlps_intVector_printSynchronized(colPerm, n, "colPerm", "global colPerm in permuteOffDiag", MPI_COMM_SELF); #ifdef DEBUG printf("[permuteOffDiagRowsToBottom] Checking colPerm \n"); preAlps_permVectorCheck(colPerm, n); #endif /* AP = P x A x P^T */ ierr = CPLM_MatCSRPermute(locA, &locAP, locRowPerm, colPerm, PERMUTE); preAlps_checkError(ierr); /* Replace the matrix with the permuted one*/ CPLM_MatCSRCopy(&locAP, locA); //CPLM_MatCSRFree(&locA); //locA = &locAP; CPLM_MatCSRFree(&locAP); free(locRowPerm); free(mark); free(recvcounts); return 0; } /* * Permute the matrix to create the global matrix structure where all the Block diag are ordered first * followed by the Schur complement. * The permuted local matrix will have the form locA = [... A_{i, Gamma};... A_{gamma,gamma}] * * nbDiagRowsloc: input: the number of diagonal block on the processor callinf this routine * locA: * input: the local part of the matrix owned by the processor calling this routine * idxRowBegin: * input: the global array to indicate the column partitioning * locAP: * output: the permuted matrix * colPerm * output: a preallocated vector of the size of the number of columns of A * to return the global permutation vector * schur_ncols * output: the number of column of the schur complement after the partitioning * */ int preAlps_permuteSchurComplementToBottom(CPLM_Mat_CSR_t *locA, int nbDiagRows, int *idxColBegin, CPLM_Mat_CSR_t *locAP, int *colPerm, int *schur_ncols, MPI_Comm comm){ int nbprocs, my_rank; int *workP; //a workspace of the size of the number of procs int i, j, ierr = 0, sum = 0, count = 0; //CPLM_Mat_CSR_t locAP = CPLM_MatCSRNULL(); int *locRowPerm;//permutation applied on the local matrix int mloc, n, r; mloc = locA->info.m; n = locA->info.n; MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); //Workspace if ( !(workP = (int *) malloc(nbprocs * sizeof(int))) ) preAlps_abort("Malloc fails for workP[]."); if ( !(locRowPerm = (int *) malloc(mloc * sizeof(int))) ) preAlps_abort("Malloc fails for locRowPerm[]."); //Gather the number of elements in the diag for each procs MPI_Allgather(&nbDiagRows, 1, MPI_INT, workP, 1, MPI_INT, comm); sum = 0; for(i=0;i<nbprocs;i++) sum+=workP[i]; count = 0; r = sum; for(i=0;i<nbprocs;i++){ /* First part of the matrix */ for(j=idxColBegin[i];j<idxColBegin[i]+workP[i];j++){ colPerm[count++] = j; } /* Schur complement part of the matrix */ for(j=idxColBegin[i]+workP[i];j<idxColBegin[i+1];j++){ colPerm[r++] = j; } } if(my_rank==0) preAlps_intVector_printSynchronized(colPerm, n, "colPerm", "colPerm in permuteSchurToBottom", MPI_COMM_SELF); *schur_ncols = n - sum; //permute the matrix to form the schur complement for(i=0;i<mloc;i++) locRowPerm[i] = i; //no change in the rows ierr = CPLM_MatCSRPermute(locA, locAP, locRowPerm, colPerm, PERMUTE); preAlps_checkError(ierr); #ifdef DEBUG CPLM_MatCSRPrintSynchronizedCoords (locAP, comm, "locAP", "locAP after permuteSchurToBottom"); #endif /*Copy and free the workspace matrice*/ //CPLM_MatCSRCopy(&locAP, locA); //CPLM_MatCSRFree(&locAP); free(workP); return ierr; } /* * Check the permutation vector for consistency */ int preAlps_permVectorCheck(int *perm, int n){ int i,j, found; for(i=0;i<n;i++){ found = 0; for(j=0;j<n;j++){ if(perm[j]==i) {found = 1; break;} } if(!found) {printf("permVectorCheck: entry %d not found in the vector\n", i); preAlps_abort("Error in permVectorCheck()");} } return 0; } /* * Extract the schur complement of a matrix A * A: * input: the matrix from which we want to extract the schur complement * firstBlock_nrows: * input: the number of rows of the top left block * firstBlock_ncols: * input: the number of cols of the top left block * Agg * output: the schur complement matrix */ int preAlps_schurComplementGet(CPLM_Mat_CSR_t *A, int firstBlock_nrows, int firstBlock_ncols, CPLM_Mat_CSR_t *Agg){ /*Count the element */ int i, j, count, schur_nrows, schur_ncols, ierr = 0; count = 0; for(i=firstBlock_nrows;i<A->info.m;i++){ for(j=A->rowPtr[i];j<A->rowPtr[i+1];j++){ if(A->colInd[j]<firstBlock_ncols) continue; count ++; } } schur_nrows = A->info.m - firstBlock_nrows; schur_ncols = A->info.n - firstBlock_ncols; //preAlps_int_printSynchronized(count, "nnz in Agg", comm); CPLM_MatCSRSetInfo(Agg, schur_nrows, schur_ncols, count, schur_nrows, schur_ncols, count, 1); ierr = CPLM_MatCSRMalloc(Agg); preAlps_checkError(ierr); //Fill the matrix Agg->rowPtr[0] = 0; count = 0; for(i=firstBlock_nrows;i<A->info.m;i++){ for(j=A->rowPtr[i];j<A->rowPtr[i+1];j++){ if(A->colInd[j]<firstBlock_ncols) continue; /* Schur complement element , copy it with local indexing */ Agg->colInd[count] = A->colInd[j]-firstBlock_ncols; Agg->val[count] = A->val[j]; count ++; } Agg->rowPtr[i-firstBlock_nrows+1] = count; } return ierr; } /*Force the current process to sleep few seconds for debugging purpose*/ void preAlps_sleep(int my_rank, int nbseconds){ #ifdef DEBUG printf("[%d] Sleeping: %d (s)\n", my_rank, nbseconds); sleep(nbseconds); #endif } /* Load a vector from a file and distribute the other procs */ int preAlps_loadDistributeFromFile(MPI_Comm comm, char *fileName, int *mcounts, double **x){ int ierr = 0, nbprocs, my_rank, root = 0; int xlen, *moffsets; double *xtmp = NULL; double *xvals; int k, xnval; MPI_Comm_size(comm, &nbprocs); MPI_Comm_rank(comm, &my_rank); //load the vector if(my_rank==0) { preAlps_doubleVector_load(fileName, &xtmp, &xlen); } //distribute xnval = mcounts[my_rank]; moffsets = (int*) malloc((nbprocs+1)*sizeof(int)); xvals = (double*) malloc(xnval*sizeof(double)); moffsets[0] = 0; for(k=0;k<nbprocs;k++) moffsets[k+1] = moffsets[k] + mcounts[k]; MPI_Scatterv(xtmp, mcounts, moffsets, MPI_DOUBLE, xvals, xnval, MPI_DOUBLE, root, comm); free(moffsets); free(xtmp); *x = xvals; return ierr; } /* Create two MPI typeVector which can be use to assemble a local vector to a global one */ int preAlps_multiColumnTypeVectorCreate(int ncols, int local_nrows, int global_nrows, MPI_Datatype *localType, MPI_Datatype *globalType){ int ierr = 0; MPI_Datatype tmpType; MPI_Type_vector(ncols, 1, local_nrows, MPI_DOUBLE, &tmpType); MPI_Type_create_resized(tmpType, 0, 1 * sizeof(double), localType); MPI_Type_commit(localType); MPI_Type_vector(ncols, 1, global_nrows, MPI_DOUBLE, &tmpType); MPI_Type_create_resized(tmpType, 0, 1 * sizeof(double), globalType); MPI_Type_commit(globalType); return ierr; }
30.74859
169
0.674572
[ "vector" ]
c182a2eda19c5396b63158ea38bb383e3a78c619
2,497
h
C
src/lib/gc/common.h
carlzhangweiwen/gazelle_mpc
45818ccf6375100a8fe2680f44f37d713380aa5c
[ "MIT" ]
50
2018-10-05T02:46:53.000Z
2022-03-20T08:47:46.000Z
src/lib/gc/common.h
WeiBenqiang/gazelle_mpc
f4eb3bae09bf4897f2651946eac7dee17e094a6f
[ "MIT" ]
7
2018-10-11T17:19:12.000Z
2022-03-08T16:45:11.000Z
src/lib/gc/common.h
WeiBenqiang/gazelle_mpc
f4eb3bae09bf4897f2651946eac7dee17e094a6f
[ "MIT" ]
20
2018-12-09T17:44:11.000Z
2022-03-01T12:13:21.000Z
/* This file is part of JustGarble. JustGarble 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. JustGarble 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 JustGarble. If not, see <http://www.gnu.org/licenses/>. */ #ifndef common #define common #include <stdlib.h> #include <x86intrin.h> #include <iostream> #include <string> #include <vector> #include <cryptoTools/Common/BitVector.h> #include "aes.h" #include "utils/backend.h" namespace lbcrypto { #define xorBlocks(x,y) _mm_xor_si128(x,y) #define zero_block() _mm_setzero_si128() #define unequal_blocks(x,y) (_mm_movemask_epi8(_mm_cmpeq_epi8(x,y)) != 0xffff) #define getLSB(x) (_mm_cvtsi128_si64(x)&1) #define makeBlock(X,Y) _mm_set_epi64((__m64)(X), (__m64)(Y)) #define getFromBlock(X,i) _mm_extract_epi64(X, i) #define DOUBLE(B) _mm_slli_epi64(B,1) #define SUCCESS 0 #define FAILURE -1 // #define STANDARD #define HALF_GATES #define FIXED_ZERO_GATE 0x00 #define ANDGATE 0x08 #define ORGATE 0x3e #define XORGATE 0x06 #define XNORGATE 0x09 #define NOTGATE 0x05 #define FIXED_ONE_GATE 0x0f #ifdef STANDARD #define TABLE_SIZE 4 #else #define TABLE_SIZE 2 #endif #define TIMES 10 #define RUNNING_TIME_ITER 100 block randomBlock(); typedef struct { block label, label0, label1; } Wire; typedef struct { long input0, input1, output, type; } GarbledGate; typedef struct { block table[TABLE_SIZE]; } GarbledTable; typedef struct { int n, m, q, r; int n_c; block table_key; std::vector<GarbledGate> garbledGates; // Circuit topology std::vector<int> outputs; // Indices of wires that are outputs std::vector<GarbledTable> garbledTable; // Tables std::vector<Wire> wires; // Labels } GarbledCircuit; typedef struct { long wireIndex, gateIndex, tableIndex, outputIndex; } BuildContext; typedef std::vector<std::array<block, 2>> InputLabels; typedef std::vector<block> ExtractedLabels; typedef std::vector<block> OutputLabels; typedef osuCrypto::BitVector InputMap; typedef osuCrypto::BitVector OutputMap; } #endif
23.780952
78
0.742091
[ "vector" ]
c18748b2aab9c2d0f22aa177040bf2e2d5654099
78,612
h
C
sim_test/echo/dx/d3dtypes.h
wanghao-1024/razor
5be35f3d06232a0ead02e56caf53f02a74aa1d7c
[ "MIT" ]
null
null
null
sim_test/echo/dx/d3dtypes.h
wanghao-1024/razor
5be35f3d06232a0ead02e56caf53f02a74aa1d7c
[ "MIT" ]
null
null
null
sim_test/echo/dx/d3dtypes.h
wanghao-1024/razor
5be35f3d06232a0ead02e56caf53f02a74aa1d7c
[ "MIT" ]
null
null
null
/*==========================================================================; * * Copyright (C) Microsoft Corporation. All Rights Reserved. * * File: d3dtypes.h * Content: Direct3D types include file * ***************************************************************************/ #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #ifndef _D3DTYPES_H_ #define _D3DTYPES_H_ #ifndef DIRECT3D_VERSION #define DIRECT3D_VERSION 0x0700 #endif #ifndef _D3DHAL_H_ #if (DIRECT3D_VERSION >= 0x0800) #pragma message("should not include d3dtypes.h when compiling for DX8 or newer interfaces") #endif #endif #include <windows.h> #include <float.h> #include "ddraw.h" #pragma warning(push) #pragma warning(disable:4201) // anonymous unions warning #if defined(_X86_) || defined(_IA64_) #pragma pack(4) #endif /* D3DVALUE is the fundamental Direct3D fractional data type */ #define D3DVALP(val, prec) ((float)(val)) #define D3DVAL(val) ((float)(val)) #ifndef DX_SHARED_DEFINES /* * This definition is shared with other DirectX components whose header files * might already have defined it. Therefore, we don't define this type if * someone else already has (as indicated by the definition of * DX_SHARED_DEFINES). We don't set DX_SHARED_DEFINES here as there are * other types in this header that are also shared. The last of these * shared defines in this file will set DX_SHARED_DEFINES. */ typedef float D3DVALUE, *LPD3DVALUE; #endif /* DX_SHARED_DEFINES */ #define D3DDivide(a, b) (float)((double) (a) / (double) (b)) #define D3DMultiply(a, b) ((a) * (b)) typedef LONG D3DFIXED; #ifndef RGB_MAKE /* * Format of CI colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | color index | fraction | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define CI_GETALPHA(ci) ((ci) >> 24) #define CI_GETINDEX(ci) (((ci) >> 8) & 0xffff) #define CI_GETFRACTION(ci) ((ci) & 0xff) #define CI_ROUNDINDEX(ci) CI_GETINDEX((ci) + 0x80) #define CI_MASKALPHA(ci) ((ci) & 0xffffff) #define CI_MAKE(a, i, f) (((a) << 24) | ((i) << 8) | (f)) /* * Format of RGBA colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define RGBA_GETALPHA(rgb) ((rgb) >> 24) #define RGBA_GETRED(rgb) (((rgb) >> 16) & 0xff) #define RGBA_GETGREEN(rgb) (((rgb) >> 8) & 0xff) #define RGBA_GETBLUE(rgb) ((rgb) & 0xff) #define RGBA_MAKE(r, g, b, a) ((D3DCOLOR) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))) /* D3DRGB and D3DRGBA may be used as initialisers for D3DCOLORs * The float values must be in the range 0..1 */ #define D3DRGB(r, g, b) \ (0xff000000L | ( ((long)((r) * 255)) << 16) | (((long)((g) * 255)) << 8) | (long)((b) * 255)) #define D3DRGBA(r, g, b, a) \ ( (((long)((a) * 255)) << 24) | (((long)((r) * 255)) << 16) \ | (((long)((g) * 255)) << 8) | (long)((b) * 255) \ ) /* * Format of RGB colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ignored | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ #define RGB_GETRED(rgb) (((rgb) >> 16) & 0xff) #define RGB_GETGREEN(rgb) (((rgb) >> 8) & 0xff) #define RGB_GETBLUE(rgb) ((rgb) & 0xff) #define RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff)) #define RGB_MAKE(r, g, b) ((D3DCOLOR) (((r) << 16) | ((g) << 8) | (b))) #define RGBA_TORGB(rgba) ((D3DCOLOR) ((rgba) & 0xffffff)) #define RGB_TORGBA(rgb) ((D3DCOLOR) ((rgb) | 0xff000000)) #endif /* * Flags for Enumerate functions */ /* * Stop the enumeration */ #define D3DENUMRET_CANCEL DDENUMRET_CANCEL /* * Continue the enumeration */ #define D3DENUMRET_OK DDENUMRET_OK typedef HRESULT (CALLBACK* LPD3DVALIDATECALLBACK)(LPVOID lpUserArg, DWORD dwOffset); typedef HRESULT (CALLBACK* LPD3DENUMTEXTUREFORMATSCALLBACK)(LPDDSURFACEDESC lpDdsd, LPVOID lpContext); typedef HRESULT (CALLBACK* LPD3DENUMPIXELFORMATSCALLBACK)(LPDDPIXELFORMAT lpDDPixFmt, LPVOID lpContext); #ifndef DX_SHARED_DEFINES /* * This definition is shared with other DirectX components whose header files * might already have defined it. Therefore, we don't define this type if * someone else already has (as indicated by the definition of * DX_SHARED_DEFINES). We don't set DX_SHARED_DEFINES here as there are * other types in this header that are also shared. The last of these * shared defines in this file will set DX_SHARED_DEFINES. */ #ifndef D3DCOLOR_DEFINED typedef DWORD D3DCOLOR; #define D3DCOLOR_DEFINED #endif typedef DWORD* LPD3DCOLOR; #endif /* DX_SHARED_DEFINES */ typedef DWORD D3DMATERIALHANDLE, *LPD3DMATERIALHANDLE; typedef DWORD D3DTEXTUREHANDLE, *LPD3DTEXTUREHANDLE; typedef DWORD D3DMATRIXHANDLE, *LPD3DMATRIXHANDLE; #ifndef D3DCOLORVALUE_DEFINED typedef struct _D3DCOLORVALUE { union { D3DVALUE r; D3DVALUE dvR; }; union { D3DVALUE g; D3DVALUE dvG; }; union { D3DVALUE b; D3DVALUE dvB; }; union { D3DVALUE a; D3DVALUE dvA; }; } D3DCOLORVALUE; #define D3DCOLORVALUE_DEFINED #endif typedef struct _D3DCOLORVALUE* LPD3DCOLORVALUE; #ifndef D3DRECT_DEFINED typedef struct _D3DRECT { union { LONG x1; LONG lX1; }; union { LONG y1; LONG lY1; }; union { LONG x2; LONG lX2; }; union { LONG y2; LONG lY2; }; } D3DRECT; #define D3DRECT_DEFINED #endif typedef struct _D3DRECT* LPD3DRECT; #ifndef DX_SHARED_DEFINES /* * This definition is shared with other DirectX components whose header files * might already have defined it. Therefore, we don't define this type if * someone else already has (as indicated by the definition of * DX_SHARED_DEFINES). */ #ifndef D3DVECTOR_DEFINED typedef struct _D3DVECTOR { union { D3DVALUE x; D3DVALUE dvX; }; union { D3DVALUE y; D3DVALUE dvY; }; union { D3DVALUE z; D3DVALUE dvZ; }; #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) public: // ===================================== // Constructors // ===================================== _D3DVECTOR() { } _D3DVECTOR(D3DVALUE f); _D3DVECTOR(D3DVALUE _x, D3DVALUE _y, D3DVALUE _z); _D3DVECTOR(const D3DVALUE f[3]); // ===================================== // Access grants // ===================================== const D3DVALUE& operator[](int i) const; D3DVALUE& operator[](int i); // ===================================== // Assignment operators // ===================================== _D3DVECTOR& operator += (const _D3DVECTOR& v); _D3DVECTOR& operator -= (const _D3DVECTOR& v); _D3DVECTOR& operator *= (const _D3DVECTOR& v); _D3DVECTOR& operator /= (const _D3DVECTOR& v); _D3DVECTOR& operator *= (D3DVALUE s); _D3DVECTOR& operator /= (D3DVALUE s); // ===================================== // Unary operators // ===================================== friend _D3DVECTOR operator + (const _D3DVECTOR& v); friend _D3DVECTOR operator - (const _D3DVECTOR& v); // ===================================== // Binary operators // ===================================== // Addition and subtraction friend _D3DVECTOR operator + (const _D3DVECTOR& v1, const _D3DVECTOR& v2); friend _D3DVECTOR operator - (const _D3DVECTOR& v1, const _D3DVECTOR& v2); // Scalar multiplication and division friend _D3DVECTOR operator * (const _D3DVECTOR& v, D3DVALUE s); friend _D3DVECTOR operator * (D3DVALUE s, const _D3DVECTOR& v); friend _D3DVECTOR operator / (const _D3DVECTOR& v, D3DVALUE s); // Memberwise multiplication and division friend _D3DVECTOR operator * (const _D3DVECTOR& v1, const _D3DVECTOR& v2); friend _D3DVECTOR operator / (const _D3DVECTOR& v1, const _D3DVECTOR& v2); // Vector dominance friend int operator < (const _D3DVECTOR& v1, const _D3DVECTOR& v2); friend int operator <= (const _D3DVECTOR& v1, const _D3DVECTOR& v2); // Bitwise equality friend int operator == (const _D3DVECTOR& v1, const _D3DVECTOR& v2); // Length-related functions friend D3DVALUE SquareMagnitude (const _D3DVECTOR& v); friend D3DVALUE Magnitude (const _D3DVECTOR& v); // Returns vector with same direction and unit length friend _D3DVECTOR Normalize (const _D3DVECTOR& v); // Return min/max component of the input vector friend D3DVALUE Min (const _D3DVECTOR& v); friend D3DVALUE Max (const _D3DVECTOR& v); // Return memberwise min/max of input vectors friend _D3DVECTOR Minimize (const _D3DVECTOR& v1, const _D3DVECTOR& v2); friend _D3DVECTOR Maximize (const _D3DVECTOR& v1, const _D3DVECTOR& v2); // Dot and cross product friend D3DVALUE DotProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2); friend _D3DVECTOR CrossProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2); #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DVECTOR; #define D3DVECTOR_DEFINED #endif typedef struct _D3DVECTOR* LPD3DVECTOR; /* * As this is the last of the shared defines to be defined we now set * D3D_SHARED_DEFINES to flag that fact that this header has defined these * types. */ #define DX_SHARED_DEFINES #endif /* DX_SHARED_DEFINES */ /* * Vertex data types supported in an ExecuteBuffer. */ /* * Homogeneous vertices */ typedef struct _D3DHVERTEX { DWORD dwFlags; /* Homogeneous clipping flags */ union { D3DVALUE hx; D3DVALUE dvHX; }; union { D3DVALUE hy; D3DVALUE dvHY; }; union { D3DVALUE hz; D3DVALUE dvHZ; }; } D3DHVERTEX, *LPD3DHVERTEX; /* * Transformed/lit vertices */ typedef struct _D3DTLVERTEX { union { D3DVALUE sx; /* Screen coordinates */ D3DVALUE dvSX; }; union { D3DVALUE sy; D3DVALUE dvSY; }; union { D3DVALUE sz; D3DVALUE dvSZ; }; union { D3DVALUE rhw; /* Reciprocal of homogeneous w */ D3DVALUE dvRHW; }; union { D3DCOLOR color; /* Vertex color */ D3DCOLOR dcColor; }; union { D3DCOLOR specular; /* Specular component of vertex */ D3DCOLOR dcSpecular; }; union { D3DVALUE tu; /* Texture coordinates */ D3DVALUE dvTU; }; union { D3DVALUE tv; D3DVALUE dvTV; }; #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) _D3DTLVERTEX() { } _D3DTLVERTEX(const D3DVECTOR& v, float _rhw, D3DCOLOR _color, D3DCOLOR _specular, float _tu, float _tv) { sx = v.x; sy = v.y; sz = v.z; rhw = _rhw; color = _color; specular = _specular; tu = _tu; tv = _tv; } #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DTLVERTEX, *LPD3DTLVERTEX; /* * Untransformed/lit vertices */ typedef struct _D3DLVERTEX { union { D3DVALUE x; /* Homogeneous coordinates */ D3DVALUE dvX; }; union { D3DVALUE y; D3DVALUE dvY; }; union { D3DVALUE z; D3DVALUE dvZ; }; DWORD dwReserved; union { D3DCOLOR color; /* Vertex color */ D3DCOLOR dcColor; }; union { D3DCOLOR specular; /* Specular component of vertex */ D3DCOLOR dcSpecular; }; union { D3DVALUE tu; /* Texture coordinates */ D3DVALUE dvTU; }; union { D3DVALUE tv; D3DVALUE dvTV; }; #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) _D3DLVERTEX() { } _D3DLVERTEX(const D3DVECTOR& v, D3DCOLOR _color, D3DCOLOR _specular, float _tu, float _tv) { x = v.x; y = v.y; z = v.z; dwReserved = 0; color = _color; specular = _specular; tu = _tu; tv = _tv; } #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DLVERTEX, *LPD3DLVERTEX; /* * Untransformed/unlit vertices */ typedef struct _D3DVERTEX { union { D3DVALUE x; /* Homogeneous coordinates */ D3DVALUE dvX; }; union { D3DVALUE y; D3DVALUE dvY; }; union { D3DVALUE z; D3DVALUE dvZ; }; union { D3DVALUE nx; /* Normal */ D3DVALUE dvNX; }; union { D3DVALUE ny; D3DVALUE dvNY; }; union { D3DVALUE nz; D3DVALUE dvNZ; }; union { D3DVALUE tu; /* Texture coordinates */ D3DVALUE dvTU; }; union { D3DVALUE tv; D3DVALUE dvTV; }; #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) _D3DVERTEX() { } _D3DVERTEX(const D3DVECTOR& v, const D3DVECTOR& n, float _tu, float _tv) { x = v.x; y = v.y; z = v.z; nx = n.x; ny = n.y; nz = n.z; tu = _tu; tv = _tv; } #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DVERTEX, *LPD3DVERTEX; /* * Matrix, viewport, and tranformation structures and definitions. */ #ifndef D3DMATRIX_DEFINED typedef struct _D3DMATRIX { #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) union { struct { #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ D3DVALUE _11, _12, _13, _14; D3DVALUE _21, _22, _23, _24; D3DVALUE _31, _32, _33, _34; D3DVALUE _41, _42, _43, _44; #if(DIRECT3D_VERSION >= 0x0500) #if (defined __cplusplus) && (defined D3D_OVERLOADS) }; D3DVALUE m[4][4]; }; _D3DMATRIX() { } _D3DMATRIX( D3DVALUE _m00, D3DVALUE _m01, D3DVALUE _m02, D3DVALUE _m03, D3DVALUE _m10, D3DVALUE _m11, D3DVALUE _m12, D3DVALUE _m13, D3DVALUE _m20, D3DVALUE _m21, D3DVALUE _m22, D3DVALUE _m23, D3DVALUE _m30, D3DVALUE _m31, D3DVALUE _m32, D3DVALUE _m33 ) { m[0][0] = _m00; m[0][1] = _m01; m[0][2] = _m02; m[0][3] = _m03; m[1][0] = _m10; m[1][1] = _m11; m[1][2] = _m12; m[1][3] = _m13; m[2][0] = _m20; m[2][1] = _m21; m[2][2] = _m22; m[2][3] = _m23; m[3][0] = _m30; m[3][1] = _m31; m[3][2] = _m32; m[3][3] = _m33; } D3DVALUE& operator()(int iRow, int iColumn) { return m[iRow][iColumn]; } const D3DVALUE& operator()(int iRow, int iColumn) const { return m[iRow][iColumn]; } #if(DIRECT3D_VERSION >= 0x0600) friend _D3DMATRIX operator* (const _D3DMATRIX&, const _D3DMATRIX&); #endif /* DIRECT3D_VERSION >= 0x0600 */ #endif #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DMATRIX; #define D3DMATRIX_DEFINED #endif typedef struct _D3DMATRIX* LPD3DMATRIX; #if (defined __cplusplus) && (defined D3D_OVERLOADS) #include "d3dvec.inl" #endif typedef struct _D3DVIEWPORT { DWORD dwSize; DWORD dwX; DWORD dwY; /* Top left */ DWORD dwWidth; DWORD dwHeight; /* Dimensions */ D3DVALUE dvScaleX; /* Scale homogeneous to screen */ D3DVALUE dvScaleY; /* Scale homogeneous to screen */ D3DVALUE dvMaxX; /* Min/max homogeneous x coord */ D3DVALUE dvMaxY; /* Min/max homogeneous y coord */ D3DVALUE dvMinZ; D3DVALUE dvMaxZ; /* Min/max homogeneous z coord */ } D3DVIEWPORT, *LPD3DVIEWPORT; #if(DIRECT3D_VERSION >= 0x0500) typedef struct _D3DVIEWPORT2 { DWORD dwSize; DWORD dwX; DWORD dwY; /* Viewport Top left */ DWORD dwWidth; DWORD dwHeight; /* Viewport Dimensions */ D3DVALUE dvClipX; /* Top left of clip volume */ D3DVALUE dvClipY; D3DVALUE dvClipWidth; /* Clip Volume Dimensions */ D3DVALUE dvClipHeight; D3DVALUE dvMinZ; /* Min/max of clip Volume */ D3DVALUE dvMaxZ; } D3DVIEWPORT2, *LPD3DVIEWPORT2; #endif /* DIRECT3D_VERSION >= 0x0500 */ #if(DIRECT3D_VERSION >= 0x0700) typedef struct _D3DVIEWPORT7 { DWORD dwX; DWORD dwY; /* Viewport Top left */ DWORD dwWidth; DWORD dwHeight; /* Viewport Dimensions */ D3DVALUE dvMinZ; /* Min/max of clip Volume */ D3DVALUE dvMaxZ; } D3DVIEWPORT7, *LPD3DVIEWPORT7; #endif /* DIRECT3D_VERSION >= 0x0700 */ /* * Values for clip fields. */ #if(DIRECT3D_VERSION >= 0x0700) // Max number of user clipping planes, supported in D3D. #define D3DMAXUSERCLIPPLANES 32 // These bits could be ORed together to use with D3DRENDERSTATE_CLIPPLANEENABLE // #define D3DCLIPPLANE0 (1 << 0) #define D3DCLIPPLANE1 (1 << 1) #define D3DCLIPPLANE2 (1 << 2) #define D3DCLIPPLANE3 (1 << 3) #define D3DCLIPPLANE4 (1 << 4) #define D3DCLIPPLANE5 (1 << 5) #endif /* DIRECT3D_VERSION >= 0x0700 */ #define D3DCLIP_LEFT 0x00000001L #define D3DCLIP_RIGHT 0x00000002L #define D3DCLIP_TOP 0x00000004L #define D3DCLIP_BOTTOM 0x00000008L #define D3DCLIP_FRONT 0x00000010L #define D3DCLIP_BACK 0x00000020L #define D3DCLIP_GEN0 0x00000040L #define D3DCLIP_GEN1 0x00000080L #define D3DCLIP_GEN2 0x00000100L #define D3DCLIP_GEN3 0x00000200L #define D3DCLIP_GEN4 0x00000400L #define D3DCLIP_GEN5 0x00000800L /* * Values for d3d status. */ #define D3DSTATUS_CLIPUNIONLEFT D3DCLIP_LEFT #define D3DSTATUS_CLIPUNIONRIGHT D3DCLIP_RIGHT #define D3DSTATUS_CLIPUNIONTOP D3DCLIP_TOP #define D3DSTATUS_CLIPUNIONBOTTOM D3DCLIP_BOTTOM #define D3DSTATUS_CLIPUNIONFRONT D3DCLIP_FRONT #define D3DSTATUS_CLIPUNIONBACK D3DCLIP_BACK #define D3DSTATUS_CLIPUNIONGEN0 D3DCLIP_GEN0 #define D3DSTATUS_CLIPUNIONGEN1 D3DCLIP_GEN1 #define D3DSTATUS_CLIPUNIONGEN2 D3DCLIP_GEN2 #define D3DSTATUS_CLIPUNIONGEN3 D3DCLIP_GEN3 #define D3DSTATUS_CLIPUNIONGEN4 D3DCLIP_GEN4 #define D3DSTATUS_CLIPUNIONGEN5 D3DCLIP_GEN5 #define D3DSTATUS_CLIPINTERSECTIONLEFT 0x00001000L #define D3DSTATUS_CLIPINTERSECTIONRIGHT 0x00002000L #define D3DSTATUS_CLIPINTERSECTIONTOP 0x00004000L #define D3DSTATUS_CLIPINTERSECTIONBOTTOM 0x00008000L #define D3DSTATUS_CLIPINTERSECTIONFRONT 0x00010000L #define D3DSTATUS_CLIPINTERSECTIONBACK 0x00020000L #define D3DSTATUS_CLIPINTERSECTIONGEN0 0x00040000L #define D3DSTATUS_CLIPINTERSECTIONGEN1 0x00080000L #define D3DSTATUS_CLIPINTERSECTIONGEN2 0x00100000L #define D3DSTATUS_CLIPINTERSECTIONGEN3 0x00200000L #define D3DSTATUS_CLIPINTERSECTIONGEN4 0x00400000L #define D3DSTATUS_CLIPINTERSECTIONGEN5 0x00800000L #define D3DSTATUS_ZNOTVISIBLE 0x01000000L /* Do not use 0x80000000 for any status flags in future as it is reserved */ #define D3DSTATUS_CLIPUNIONALL ( \ D3DSTATUS_CLIPUNIONLEFT | \ D3DSTATUS_CLIPUNIONRIGHT | \ D3DSTATUS_CLIPUNIONTOP | \ D3DSTATUS_CLIPUNIONBOTTOM | \ D3DSTATUS_CLIPUNIONFRONT | \ D3DSTATUS_CLIPUNIONBACK | \ D3DSTATUS_CLIPUNIONGEN0 | \ D3DSTATUS_CLIPUNIONGEN1 | \ D3DSTATUS_CLIPUNIONGEN2 | \ D3DSTATUS_CLIPUNIONGEN3 | \ D3DSTATUS_CLIPUNIONGEN4 | \ D3DSTATUS_CLIPUNIONGEN5 \ ) #define D3DSTATUS_CLIPINTERSECTIONALL ( \ D3DSTATUS_CLIPINTERSECTIONLEFT | \ D3DSTATUS_CLIPINTERSECTIONRIGHT | \ D3DSTATUS_CLIPINTERSECTIONTOP | \ D3DSTATUS_CLIPINTERSECTIONBOTTOM | \ D3DSTATUS_CLIPINTERSECTIONFRONT | \ D3DSTATUS_CLIPINTERSECTIONBACK | \ D3DSTATUS_CLIPINTERSECTIONGEN0 | \ D3DSTATUS_CLIPINTERSECTIONGEN1 | \ D3DSTATUS_CLIPINTERSECTIONGEN2 | \ D3DSTATUS_CLIPINTERSECTIONGEN3 | \ D3DSTATUS_CLIPINTERSECTIONGEN4 | \ D3DSTATUS_CLIPINTERSECTIONGEN5 \ ) #define D3DSTATUS_DEFAULT ( \ D3DSTATUS_CLIPINTERSECTIONALL | \ D3DSTATUS_ZNOTVISIBLE) /* * Options for direct transform calls */ #define D3DTRANSFORM_CLIPPED 0x00000001l #define D3DTRANSFORM_UNCLIPPED 0x00000002l typedef struct _D3DTRANSFORMDATA { DWORD dwSize; LPVOID lpIn; /* Input vertices */ DWORD dwInSize; /* Stride of input vertices */ LPVOID lpOut; /* Output vertices */ DWORD dwOutSize; /* Stride of output vertices */ LPD3DHVERTEX lpHOut; /* Output homogeneous vertices */ DWORD dwClip; /* Clipping hint */ DWORD dwClipIntersection; DWORD dwClipUnion; /* Union of all clip flags */ D3DRECT drExtent; /* Extent of transformed vertices */ } D3DTRANSFORMDATA, *LPD3DTRANSFORMDATA; /* * Structure defining position and direction properties for lighting. */ typedef struct _D3DLIGHTINGELEMENT { D3DVECTOR dvPosition; /* Lightable point in model space */ D3DVECTOR dvNormal; /* Normalised unit vector */ } D3DLIGHTINGELEMENT, *LPD3DLIGHTINGELEMENT; /* * Structure defining material properties for lighting. */ typedef struct _D3DMATERIAL { DWORD dwSize; union { D3DCOLORVALUE diffuse; /* Diffuse color RGBA */ D3DCOLORVALUE dcvDiffuse; }; union { D3DCOLORVALUE ambient; /* Ambient color RGB */ D3DCOLORVALUE dcvAmbient; }; union { D3DCOLORVALUE specular; /* Specular 'shininess' */ D3DCOLORVALUE dcvSpecular; }; union { D3DCOLORVALUE emissive; /* Emissive color RGB */ D3DCOLORVALUE dcvEmissive; }; union { D3DVALUE power; /* Sharpness if specular highlight */ D3DVALUE dvPower; }; D3DTEXTUREHANDLE hTexture; /* Handle to texture map */ DWORD dwRampSize; } D3DMATERIAL, *LPD3DMATERIAL; #if(DIRECT3D_VERSION >= 0x0700) typedef struct _D3DMATERIAL7 { union { D3DCOLORVALUE diffuse; /* Diffuse color RGBA */ D3DCOLORVALUE dcvDiffuse; }; union { D3DCOLORVALUE ambient; /* Ambient color RGB */ D3DCOLORVALUE dcvAmbient; }; union { D3DCOLORVALUE specular; /* Specular 'shininess' */ D3DCOLORVALUE dcvSpecular; }; union { D3DCOLORVALUE emissive; /* Emissive color RGB */ D3DCOLORVALUE dcvEmissive; }; union { D3DVALUE power; /* Sharpness if specular highlight */ D3DVALUE dvPower; }; } D3DMATERIAL7, *LPD3DMATERIAL7; #endif /* DIRECT3D_VERSION >= 0x0700 */ #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DLIGHTTYPE { D3DLIGHT_POINT = 1, D3DLIGHT_SPOT = 2, D3DLIGHT_DIRECTIONAL = 3, // Note: The following light type (D3DLIGHT_PARALLELPOINT) // is no longer supported from D3D for DX7 onwards. D3DLIGHT_PARALLELPOINT = 4, #if(DIRECT3D_VERSION < 0x0500) // For backward compatible headers D3DLIGHT_GLSPOT = 5, #endif D3DLIGHT_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DLIGHTTYPE; #else typedef enum _D3DLIGHTTYPE D3DLIGHTTYPE; #define D3DLIGHT_PARALLELPOINT (D3DLIGHTTYPE)4 #define D3DLIGHT_GLSPOT (D3DLIGHTTYPE)5 #endif //(DIRECT3D_VERSION < 0x0800) /* * Structure defining a light source and its properties. */ typedef struct _D3DLIGHT { DWORD dwSize; D3DLIGHTTYPE dltType; /* Type of light source */ D3DCOLORVALUE dcvColor; /* Color of light */ D3DVECTOR dvPosition; /* Position in world space */ D3DVECTOR dvDirection; /* Direction in world space */ D3DVALUE dvRange; /* Cutoff range */ D3DVALUE dvFalloff; /* Falloff */ D3DVALUE dvAttenuation0; /* Constant attenuation */ D3DVALUE dvAttenuation1; /* Linear attenuation */ D3DVALUE dvAttenuation2; /* Quadratic attenuation */ D3DVALUE dvTheta; /* Inner angle of spotlight cone */ D3DVALUE dvPhi; /* Outer angle of spotlight cone */ } D3DLIGHT, *LPD3DLIGHT; #if(DIRECT3D_VERSION >= 0x0700) typedef struct _D3DLIGHT7 { D3DLIGHTTYPE dltType; /* Type of light source */ D3DCOLORVALUE dcvDiffuse; /* Diffuse color of light */ D3DCOLORVALUE dcvSpecular; /* Specular color of light */ D3DCOLORVALUE dcvAmbient; /* Ambient color of light */ D3DVECTOR dvPosition; /* Position in world space */ D3DVECTOR dvDirection; /* Direction in world space */ D3DVALUE dvRange; /* Cutoff range */ D3DVALUE dvFalloff; /* Falloff */ D3DVALUE dvAttenuation0; /* Constant attenuation */ D3DVALUE dvAttenuation1; /* Linear attenuation */ D3DVALUE dvAttenuation2; /* Quadratic attenuation */ D3DVALUE dvTheta; /* Inner angle of spotlight cone */ D3DVALUE dvPhi; /* Outer angle of spotlight cone */ } D3DLIGHT7, *LPD3DLIGHT7; #endif /* DIRECT3D_VERSION >= 0x0700 */ #if(DIRECT3D_VERSION >= 0x0500) /* * Structure defining a light source and its properties. */ /* flags bits */ #define D3DLIGHT_ACTIVE 0x00000001 #define D3DLIGHT_NO_SPECULAR 0x00000002 #define D3DLIGHT_ALL (D3DLIGHT_ACTIVE | D3DLIGHT_NO_SPECULAR) /* maximum valid light range */ #define D3DLIGHT_RANGE_MAX ((float)sqrt(FLT_MAX)) typedef struct _D3DLIGHT2 { DWORD dwSize; D3DLIGHTTYPE dltType; /* Type of light source */ D3DCOLORVALUE dcvColor; /* Color of light */ D3DVECTOR dvPosition; /* Position in world space */ D3DVECTOR dvDirection; /* Direction in world space */ D3DVALUE dvRange; /* Cutoff range */ D3DVALUE dvFalloff; /* Falloff */ D3DVALUE dvAttenuation0; /* Constant attenuation */ D3DVALUE dvAttenuation1; /* Linear attenuation */ D3DVALUE dvAttenuation2; /* Quadratic attenuation */ D3DVALUE dvTheta; /* Inner angle of spotlight cone */ D3DVALUE dvPhi; /* Outer angle of spotlight cone */ DWORD dwFlags; } D3DLIGHT2, *LPD3DLIGHT2; #endif /* DIRECT3D_VERSION >= 0x0500 */ typedef struct _D3DLIGHTDATA { DWORD dwSize; LPD3DLIGHTINGELEMENT lpIn; /* Input positions and normals */ DWORD dwInSize; /* Stride of input elements */ LPD3DTLVERTEX lpOut; /* Output colors */ DWORD dwOutSize; /* Stride of output colors */ } D3DLIGHTDATA, *LPD3DLIGHTDATA; #if(DIRECT3D_VERSION >= 0x0500) /* * Before DX5, these values were in an enum called * D3DCOLORMODEL. This was not correct, since they are * bit flags. A driver can surface either or both flags * in the dcmColorModel member of D3DDEVICEDESC. */ #define D3DCOLOR_MONO 1 #define D3DCOLOR_RGB 2 typedef DWORD D3DCOLORMODEL; #endif /* DIRECT3D_VERSION >= 0x0500 */ /* * Options for clearing */ #define D3DCLEAR_TARGET 0x00000001l /* Clear target surface */ #define D3DCLEAR_ZBUFFER 0x00000002l /* Clear target z buffer */ #if(DIRECT3D_VERSION >= 0x0600) #define D3DCLEAR_STENCIL 0x00000004l /* Clear stencil planes */ #endif /* DIRECT3D_VERSION >= 0x0600 */ /* * Execute buffers are allocated via Direct3D. These buffers may then * be filled by the application with instructions to execute along with * vertex data. */ /* * Supported op codes for execute instructions. */ typedef enum _D3DOPCODE { D3DOP_POINT = 1, D3DOP_LINE = 2, D3DOP_TRIANGLE = 3, D3DOP_MATRIXLOAD = 4, D3DOP_MATRIXMULTIPLY = 5, D3DOP_STATETRANSFORM = 6, D3DOP_STATELIGHT = 7, D3DOP_STATERENDER = 8, D3DOP_PROCESSVERTICES = 9, D3DOP_TEXTURELOAD = 10, D3DOP_EXIT = 11, D3DOP_BRANCHFORWARD = 12, D3DOP_SPAN = 13, D3DOP_SETSTATUS = 14, #if(DIRECT3D_VERSION >= 0x0500) D3DOP_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DOPCODE; typedef struct _D3DINSTRUCTION { BYTE bOpcode; /* Instruction opcode */ BYTE bSize; /* Size of each instruction data unit */ WORD wCount; /* Count of instruction data units to follow */ } D3DINSTRUCTION, *LPD3DINSTRUCTION; /* * Structure for texture loads */ typedef struct _D3DTEXTURELOAD { D3DTEXTUREHANDLE hDestTexture; D3DTEXTUREHANDLE hSrcTexture; } D3DTEXTURELOAD, *LPD3DTEXTURELOAD; /* * Structure for picking */ typedef struct _D3DPICKRECORD { BYTE bOpcode; BYTE bPad; DWORD dwOffset; D3DVALUE dvZ; } D3DPICKRECORD, *LPD3DPICKRECORD; /* * The following defines the rendering states which can be set in the * execute buffer. */ #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DSHADEMODE { D3DSHADE_FLAT = 1, D3DSHADE_GOURAUD = 2, D3DSHADE_PHONG = 3, #if(DIRECT3D_VERSION >= 0x0500) D3DSHADE_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DSHADEMODE; typedef enum _D3DFILLMODE { D3DFILL_POINT = 1, D3DFILL_WIREFRAME = 2, D3DFILL_SOLID = 3, #if(DIRECT3D_VERSION >= 0x0500) D3DFILL_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DFILLMODE; typedef struct _D3DLINEPATTERN { WORD wRepeatFactor; WORD wLinePattern; } D3DLINEPATTERN; #endif //(DIRECT3D_VERSION < 0x0800) typedef enum _D3DTEXTUREFILTER { D3DFILTER_NEAREST = 1, D3DFILTER_LINEAR = 2, D3DFILTER_MIPNEAREST = 3, D3DFILTER_MIPLINEAR = 4, D3DFILTER_LINEARMIPNEAREST = 5, D3DFILTER_LINEARMIPLINEAR = 6, #if(DIRECT3D_VERSION >= 0x0500) D3DFILTER_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DTEXTUREFILTER; #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DBLEND { D3DBLEND_ZERO = 1, D3DBLEND_ONE = 2, D3DBLEND_SRCCOLOR = 3, D3DBLEND_INVSRCCOLOR = 4, D3DBLEND_SRCALPHA = 5, D3DBLEND_INVSRCALPHA = 6, D3DBLEND_DESTALPHA = 7, D3DBLEND_INVDESTALPHA = 8, D3DBLEND_DESTCOLOR = 9, D3DBLEND_INVDESTCOLOR = 10, D3DBLEND_SRCALPHASAT = 11, D3DBLEND_BOTHSRCALPHA = 12, D3DBLEND_BOTHINVSRCALPHA = 13, #if(DIRECT3D_VERSION >= 0x0500) D3DBLEND_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DBLEND; #endif //(DIRECT3D_VERSION < 0x0800) typedef enum _D3DTEXTUREBLEND { D3DTBLEND_DECAL = 1, D3DTBLEND_MODULATE = 2, D3DTBLEND_DECALALPHA = 3, D3DTBLEND_MODULATEALPHA = 4, D3DTBLEND_DECALMASK = 5, D3DTBLEND_MODULATEMASK = 6, D3DTBLEND_COPY = 7, #if(DIRECT3D_VERSION >= 0x0500) D3DTBLEND_ADD = 8, D3DTBLEND_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DTEXTUREBLEND; #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DTEXTUREADDRESS { D3DTADDRESS_WRAP = 1, D3DTADDRESS_MIRROR = 2, D3DTADDRESS_CLAMP = 3, #if(DIRECT3D_VERSION >= 0x0500) D3DTADDRESS_BORDER = 4, D3DTADDRESS_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DTEXTUREADDRESS; typedef enum _D3DCULL { D3DCULL_NONE = 1, D3DCULL_CW = 2, D3DCULL_CCW = 3, #if(DIRECT3D_VERSION >= 0x0500) D3DCULL_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DCULL; typedef enum _D3DCMPFUNC { D3DCMP_NEVER = 1, D3DCMP_LESS = 2, D3DCMP_EQUAL = 3, D3DCMP_LESSEQUAL = 4, D3DCMP_GREATER = 5, D3DCMP_NOTEQUAL = 6, D3DCMP_GREATEREQUAL = 7, D3DCMP_ALWAYS = 8, #if(DIRECT3D_VERSION >= 0x0500) D3DCMP_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DCMPFUNC; #if(DIRECT3D_VERSION >= 0x0600) typedef enum _D3DSTENCILOP { D3DSTENCILOP_KEEP = 1, D3DSTENCILOP_ZERO = 2, D3DSTENCILOP_REPLACE = 3, D3DSTENCILOP_INCRSAT = 4, D3DSTENCILOP_DECRSAT = 5, D3DSTENCILOP_INVERT = 6, D3DSTENCILOP_INCR = 7, D3DSTENCILOP_DECR = 8, D3DSTENCILOP_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DSTENCILOP; #endif /* DIRECT3D_VERSION >= 0x0600 */ typedef enum _D3DFOGMODE { D3DFOG_NONE = 0, D3DFOG_EXP = 1, D3DFOG_EXP2 = 2, #if(DIRECT3D_VERSION >= 0x0500) D3DFOG_LINEAR = 3, D3DFOG_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DFOGMODE; #if(DIRECT3D_VERSION >= 0x0600) typedef enum _D3DZBUFFERTYPE { D3DZB_FALSE = 0, D3DZB_TRUE = 1, // Z buffering D3DZB_USEW = 2, // W buffering D3DZB_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DZBUFFERTYPE; #endif /* DIRECT3D_VERSION >= 0x0600 */ #endif //(DIRECT3D_VERSION < 0x0800) #if(DIRECT3D_VERSION >= 0x0500) typedef enum _D3DANTIALIASMODE { D3DANTIALIAS_NONE = 0, D3DANTIALIAS_SORTDEPENDENT = 1, D3DANTIALIAS_SORTINDEPENDENT = 2, D3DANTIALIAS_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DANTIALIASMODE; // Vertex types supported by Direct3D typedef enum _D3DVERTEXTYPE { D3DVT_VERTEX = 1, D3DVT_LVERTEX = 2, D3DVT_TLVERTEX = 3, D3DVT_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DVERTEXTYPE; #if(DIRECT3D_VERSION < 0x0800) // Primitives supported by draw-primitive API typedef enum _D3DPRIMITIVETYPE { D3DPT_POINTLIST = 1, D3DPT_LINELIST = 2, D3DPT_LINESTRIP = 3, D3DPT_TRIANGLELIST = 4, D3DPT_TRIANGLESTRIP = 5, D3DPT_TRIANGLEFAN = 6, D3DPT_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DPRIMITIVETYPE; #endif //(DIRECT3D_VERSION < 0x0800) #endif /* DIRECT3D_VERSION >= 0x0500 */ /* * Amount to add to a state to generate the override for that state. */ #define D3DSTATE_OVERRIDE_BIAS 256 /* * A state which sets the override flag for the specified state type. */ #define D3DSTATE_OVERRIDE(type) (D3DRENDERSTATETYPE)(((DWORD) (type) + D3DSTATE_OVERRIDE_BIAS)) #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DTRANSFORMSTATETYPE { D3DTRANSFORMSTATE_WORLD = 1, D3DTRANSFORMSTATE_VIEW = 2, D3DTRANSFORMSTATE_PROJECTION = 3, #if(DIRECT3D_VERSION >= 0x0700) D3DTRANSFORMSTATE_WORLD1 = 4, // 2nd matrix to blend D3DTRANSFORMSTATE_WORLD2 = 5, // 3rd matrix to blend D3DTRANSFORMSTATE_WORLD3 = 6, // 4th matrix to blend D3DTRANSFORMSTATE_TEXTURE0 = 16, D3DTRANSFORMSTATE_TEXTURE1 = 17, D3DTRANSFORMSTATE_TEXTURE2 = 18, D3DTRANSFORMSTATE_TEXTURE3 = 19, D3DTRANSFORMSTATE_TEXTURE4 = 20, D3DTRANSFORMSTATE_TEXTURE5 = 21, D3DTRANSFORMSTATE_TEXTURE6 = 22, D3DTRANSFORMSTATE_TEXTURE7 = 23, #endif /* DIRECT3D_VERSION >= 0x0700 */ #if(DIRECT3D_VERSION >= 0x0500) D3DTRANSFORMSTATE_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DTRANSFORMSTATETYPE; #else // // legacy transform state names // typedef enum _D3DTRANSFORMSTATETYPE D3DTRANSFORMSTATETYPE; #define D3DTRANSFORMSTATE_WORLD (D3DTRANSFORMSTATETYPE)1 #define D3DTRANSFORMSTATE_VIEW (D3DTRANSFORMSTATETYPE)2 #define D3DTRANSFORMSTATE_PROJECTION (D3DTRANSFORMSTATETYPE)3 #define D3DTRANSFORMSTATE_WORLD1 (D3DTRANSFORMSTATETYPE)4 #define D3DTRANSFORMSTATE_WORLD2 (D3DTRANSFORMSTATETYPE)5 #define D3DTRANSFORMSTATE_WORLD3 (D3DTRANSFORMSTATETYPE)6 #define D3DTRANSFORMSTATE_TEXTURE0 (D3DTRANSFORMSTATETYPE)16 #define D3DTRANSFORMSTATE_TEXTURE1 (D3DTRANSFORMSTATETYPE)17 #define D3DTRANSFORMSTATE_TEXTURE2 (D3DTRANSFORMSTATETYPE)18 #define D3DTRANSFORMSTATE_TEXTURE3 (D3DTRANSFORMSTATETYPE)19 #define D3DTRANSFORMSTATE_TEXTURE4 (D3DTRANSFORMSTATETYPE)20 #define D3DTRANSFORMSTATE_TEXTURE5 (D3DTRANSFORMSTATETYPE)21 #define D3DTRANSFORMSTATE_TEXTURE6 (D3DTRANSFORMSTATETYPE)22 #define D3DTRANSFORMSTATE_TEXTURE7 (D3DTRANSFORMSTATETYPE)23 #endif //(DIRECT3D_VERSION < 0x0800) typedef enum _D3DLIGHTSTATETYPE { D3DLIGHTSTATE_MATERIAL = 1, D3DLIGHTSTATE_AMBIENT = 2, D3DLIGHTSTATE_COLORMODEL = 3, D3DLIGHTSTATE_FOGMODE = 4, D3DLIGHTSTATE_FOGSTART = 5, D3DLIGHTSTATE_FOGEND = 6, D3DLIGHTSTATE_FOGDENSITY = 7, #if(DIRECT3D_VERSION >= 0x0600) D3DLIGHTSTATE_COLORVERTEX = 8, #endif /* DIRECT3D_VERSION >= 0x0600 */ #if(DIRECT3D_VERSION >= 0x0500) D3DLIGHTSTATE_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DLIGHTSTATETYPE; #if(DIRECT3D_VERSION < 0x0800) typedef enum _D3DRENDERSTATETYPE { D3DRENDERSTATE_ANTIALIAS = 2, /* D3DANTIALIASMODE */ D3DRENDERSTATE_TEXTUREPERSPECTIVE = 4, /* TRUE for perspective correction */ D3DRENDERSTATE_ZENABLE = 7, /* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) */ D3DRENDERSTATE_FILLMODE = 8, /* D3DFILL_MODE */ D3DRENDERSTATE_SHADEMODE = 9, /* D3DSHADEMODE */ D3DRENDERSTATE_LINEPATTERN = 10, /* D3DLINEPATTERN */ D3DRENDERSTATE_ZWRITEENABLE = 14, /* TRUE to enable z writes */ D3DRENDERSTATE_ALPHATESTENABLE = 15, /* TRUE to enable alpha tests */ D3DRENDERSTATE_LASTPIXEL = 16, /* TRUE for last-pixel on lines */ D3DRENDERSTATE_SRCBLEND = 19, /* D3DBLEND */ D3DRENDERSTATE_DESTBLEND = 20, /* D3DBLEND */ D3DRENDERSTATE_CULLMODE = 22, /* D3DCULL */ D3DRENDERSTATE_ZFUNC = 23, /* D3DCMPFUNC */ D3DRENDERSTATE_ALPHAREF = 24, /* D3DFIXED */ D3DRENDERSTATE_ALPHAFUNC = 25, /* D3DCMPFUNC */ D3DRENDERSTATE_DITHERENABLE = 26, /* TRUE to enable dithering */ #if(DIRECT3D_VERSION >= 0x0500) D3DRENDERSTATE_ALPHABLENDENABLE = 27, /* TRUE to enable alpha blending */ #endif /* DIRECT3D_VERSION >= 0x0500 */ D3DRENDERSTATE_FOGENABLE = 28, /* TRUE to enable fog blending */ D3DRENDERSTATE_SPECULARENABLE = 29, /* TRUE to enable specular */ D3DRENDERSTATE_ZVISIBLE = 30, /* TRUE to enable z checking */ D3DRENDERSTATE_STIPPLEDALPHA = 33, /* TRUE to enable stippled alpha (RGB device only) */ D3DRENDERSTATE_FOGCOLOR = 34, /* D3DCOLOR */ D3DRENDERSTATE_FOGTABLEMODE = 35, /* D3DFOGMODE */ #if(DIRECT3D_VERSION >= 0x0700) D3DRENDERSTATE_FOGSTART = 36, /* Fog start (for both vertex and pixel fog) */ D3DRENDERSTATE_FOGEND = 37, /* Fog end */ D3DRENDERSTATE_FOGDENSITY = 38, /* Fog density */ #endif /* DIRECT3D_VERSION >= 0x0700 */ #if(DIRECT3D_VERSION >= 0x0500) D3DRENDERSTATE_EDGEANTIALIAS = 40, /* TRUE to enable edge antialiasing */ D3DRENDERSTATE_COLORKEYENABLE = 41, /* TRUE to enable source colorkeyed textures */ D3DRENDERSTATE_ZBIAS = 47, /* LONG Z bias */ D3DRENDERSTATE_RANGEFOGENABLE = 48, /* Enables range-based fog */ #endif /* DIRECT3D_VERSION >= 0x0500 */ #if(DIRECT3D_VERSION >= 0x0600) D3DRENDERSTATE_STENCILENABLE = 52, /* BOOL enable/disable stenciling */ D3DRENDERSTATE_STENCILFAIL = 53, /* D3DSTENCILOP to do if stencil test fails */ D3DRENDERSTATE_STENCILZFAIL = 54, /* D3DSTENCILOP to do if stencil test passes and Z test fails */ D3DRENDERSTATE_STENCILPASS = 55, /* D3DSTENCILOP to do if both stencil and Z tests pass */ D3DRENDERSTATE_STENCILFUNC = 56, /* D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true */ D3DRENDERSTATE_STENCILREF = 57, /* Reference value used in stencil test */ D3DRENDERSTATE_STENCILMASK = 58, /* Mask value used in stencil test */ D3DRENDERSTATE_STENCILWRITEMASK = 59, /* Write mask applied to values written to stencil buffer */ D3DRENDERSTATE_TEXTUREFACTOR = 60, /* D3DCOLOR used for multi-texture blend */ #endif /* DIRECT3D_VERSION >= 0x0600 */ #if(DIRECT3D_VERSION >= 0x0600) /* * 128 values [128, 255] are reserved for texture coordinate wrap flags. * These are constructed with the D3DWRAP_U and D3DWRAP_V macros. Using * a flags word preserves forward compatibility with texture coordinates * that are >2D. */ D3DRENDERSTATE_WRAP0 = 128, /* wrap for 1st texture coord. set */ D3DRENDERSTATE_WRAP1 = 129, /* wrap for 2nd texture coord. set */ D3DRENDERSTATE_WRAP2 = 130, /* wrap for 3rd texture coord. set */ D3DRENDERSTATE_WRAP3 = 131, /* wrap for 4th texture coord. set */ D3DRENDERSTATE_WRAP4 = 132, /* wrap for 5th texture coord. set */ D3DRENDERSTATE_WRAP5 = 133, /* wrap for 6th texture coord. set */ D3DRENDERSTATE_WRAP6 = 134, /* wrap for 7th texture coord. set */ D3DRENDERSTATE_WRAP7 = 135, /* wrap for 8th texture coord. set */ #endif /* DIRECT3D_VERSION >= 0x0600 */ #if(DIRECT3D_VERSION >= 0x0700) D3DRENDERSTATE_CLIPPING = 136, D3DRENDERSTATE_LIGHTING = 137, D3DRENDERSTATE_EXTENTS = 138, D3DRENDERSTATE_AMBIENT = 139, D3DRENDERSTATE_FOGVERTEXMODE = 140, D3DRENDERSTATE_COLORVERTEX = 141, D3DRENDERSTATE_LOCALVIEWER = 142, D3DRENDERSTATE_NORMALIZENORMALS = 143, D3DRENDERSTATE_COLORKEYBLENDENABLE = 144, D3DRENDERSTATE_DIFFUSEMATERIALSOURCE = 145, D3DRENDERSTATE_SPECULARMATERIALSOURCE = 146, D3DRENDERSTATE_AMBIENTMATERIALSOURCE = 147, D3DRENDERSTATE_EMISSIVEMATERIALSOURCE = 148, D3DRENDERSTATE_VERTEXBLEND = 151, D3DRENDERSTATE_CLIPPLANEENABLE = 152, #endif /* DIRECT3D_VERSION >= 0x0700 */ // // retired renderstates - not supported for DX7 interfaces // D3DRENDERSTATE_TEXTUREHANDLE = 1, /* Texture handle for legacy interfaces (Texture,Texture2) */ D3DRENDERSTATE_TEXTUREADDRESS = 3, /* D3DTEXTUREADDRESS */ D3DRENDERSTATE_WRAPU = 5, /* TRUE for wrapping in u */ D3DRENDERSTATE_WRAPV = 6, /* TRUE for wrapping in v */ D3DRENDERSTATE_MONOENABLE = 11, /* TRUE to enable mono rasterization */ D3DRENDERSTATE_ROP2 = 12, /* ROP2 */ D3DRENDERSTATE_PLANEMASK = 13, /* DWORD physical plane mask */ D3DRENDERSTATE_TEXTUREMAG = 17, /* D3DTEXTUREFILTER */ D3DRENDERSTATE_TEXTUREMIN = 18, /* D3DTEXTUREFILTER */ D3DRENDERSTATE_TEXTUREMAPBLEND = 21, /* D3DTEXTUREBLEND */ D3DRENDERSTATE_SUBPIXEL = 31, /* TRUE to enable subpixel correction */ D3DRENDERSTATE_SUBPIXELX = 32, /* TRUE to enable correction in X only */ D3DRENDERSTATE_STIPPLEENABLE = 39, /* TRUE to enable stippling */ #if(DIRECT3D_VERSION >= 0x0500) D3DRENDERSTATE_BORDERCOLOR = 43, /* Border color for texturing w/border */ D3DRENDERSTATE_TEXTUREADDRESSU = 44, /* Texture addressing mode for U coordinate */ D3DRENDERSTATE_TEXTUREADDRESSV = 45, /* Texture addressing mode for V coordinate */ D3DRENDERSTATE_MIPMAPLODBIAS = 46, /* D3DVALUE Mipmap LOD bias */ D3DRENDERSTATE_ANISOTROPY = 49, /* Max. anisotropy. 1 = no anisotropy */ #endif /* DIRECT3D_VERSION >= 0x0500 */ D3DRENDERSTATE_FLUSHBATCH = 50, /* Explicit flush for DP batching (DX5 Only) */ #if(DIRECT3D_VERSION >= 0x0600) D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT=51, /* BOOL enable sort-independent transparency */ #endif /* DIRECT3D_VERSION >= 0x0600 */ D3DRENDERSTATE_STIPPLEPATTERN00 = 64, /* Stipple pattern 01... */ D3DRENDERSTATE_STIPPLEPATTERN01 = 65, D3DRENDERSTATE_STIPPLEPATTERN02 = 66, D3DRENDERSTATE_STIPPLEPATTERN03 = 67, D3DRENDERSTATE_STIPPLEPATTERN04 = 68, D3DRENDERSTATE_STIPPLEPATTERN05 = 69, D3DRENDERSTATE_STIPPLEPATTERN06 = 70, D3DRENDERSTATE_STIPPLEPATTERN07 = 71, D3DRENDERSTATE_STIPPLEPATTERN08 = 72, D3DRENDERSTATE_STIPPLEPATTERN09 = 73, D3DRENDERSTATE_STIPPLEPATTERN10 = 74, D3DRENDERSTATE_STIPPLEPATTERN11 = 75, D3DRENDERSTATE_STIPPLEPATTERN12 = 76, D3DRENDERSTATE_STIPPLEPATTERN13 = 77, D3DRENDERSTATE_STIPPLEPATTERN14 = 78, D3DRENDERSTATE_STIPPLEPATTERN15 = 79, D3DRENDERSTATE_STIPPLEPATTERN16 = 80, D3DRENDERSTATE_STIPPLEPATTERN17 = 81, D3DRENDERSTATE_STIPPLEPATTERN18 = 82, D3DRENDERSTATE_STIPPLEPATTERN19 = 83, D3DRENDERSTATE_STIPPLEPATTERN20 = 84, D3DRENDERSTATE_STIPPLEPATTERN21 = 85, D3DRENDERSTATE_STIPPLEPATTERN22 = 86, D3DRENDERSTATE_STIPPLEPATTERN23 = 87, D3DRENDERSTATE_STIPPLEPATTERN24 = 88, D3DRENDERSTATE_STIPPLEPATTERN25 = 89, D3DRENDERSTATE_STIPPLEPATTERN26 = 90, D3DRENDERSTATE_STIPPLEPATTERN27 = 91, D3DRENDERSTATE_STIPPLEPATTERN28 = 92, D3DRENDERSTATE_STIPPLEPATTERN29 = 93, D3DRENDERSTATE_STIPPLEPATTERN30 = 94, D3DRENDERSTATE_STIPPLEPATTERN31 = 95, // // retired renderstate names - the values are still used under new naming conventions // D3DRENDERSTATE_FOGTABLESTART = 36, /* Fog table start */ D3DRENDERSTATE_FOGTABLEEND = 37, /* Fog table end */ D3DRENDERSTATE_FOGTABLEDENSITY = 38, /* Fog table density */ #if(DIRECT3D_VERSION >= 0x0500) D3DRENDERSTATE_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ #endif /* DIRECT3D_VERSION >= 0x0500 */ } D3DRENDERSTATETYPE; #else typedef enum _D3DRENDERSTATETYPE D3DRENDERSTATETYPE; // // legacy renderstate names // #define D3DRENDERSTATE_TEXTUREPERSPECTIVE (D3DRENDERSTATETYPE)4 #define D3DRENDERSTATE_ZENABLE (D3DRENDERSTATETYPE)7 #define D3DRENDERSTATE_FILLMODE (D3DRENDERSTATETYPE)8 #define D3DRENDERSTATE_SHADEMODE (D3DRENDERSTATETYPE)9 #define D3DRENDERSTATE_LINEPATTERN (D3DRENDERSTATETYPE)10 #define D3DRENDERSTATE_ZWRITEENABLE (D3DRENDERSTATETYPE)14 #define D3DRENDERSTATE_ALPHATESTENABLE (D3DRENDERSTATETYPE)15 #define D3DRENDERSTATE_LASTPIXEL (D3DRENDERSTATETYPE)16 #define D3DRENDERSTATE_SRCBLEND (D3DRENDERSTATETYPE)19 #define D3DRENDERSTATE_DESTBLEND (D3DRENDERSTATETYPE)20 #define D3DRENDERSTATE_CULLMODE (D3DRENDERSTATETYPE)22 #define D3DRENDERSTATE_ZFUNC (D3DRENDERSTATETYPE)23 #define D3DRENDERSTATE_ALPHAREF (D3DRENDERSTATETYPE)24 #define D3DRENDERSTATE_ALPHAFUNC (D3DRENDERSTATETYPE)25 #define D3DRENDERSTATE_DITHERENABLE (D3DRENDERSTATETYPE)26 #define D3DRENDERSTATE_ALPHABLENDENABLE (D3DRENDERSTATETYPE)27 #define D3DRENDERSTATE_FOGENABLE (D3DRENDERSTATETYPE)28 #define D3DRENDERSTATE_SPECULARENABLE (D3DRENDERSTATETYPE)29 #define D3DRENDERSTATE_ZVISIBLE (D3DRENDERSTATETYPE)30 #define D3DRENDERSTATE_STIPPLEDALPHA (D3DRENDERSTATETYPE)33 #define D3DRENDERSTATE_FOGCOLOR (D3DRENDERSTATETYPE)34 #define D3DRENDERSTATE_FOGTABLEMODE (D3DRENDERSTATETYPE)35 #define D3DRENDERSTATE_FOGSTART (D3DRENDERSTATETYPE)36 #define D3DRENDERSTATE_FOGEND (D3DRENDERSTATETYPE)37 #define D3DRENDERSTATE_FOGDENSITY (D3DRENDERSTATETYPE)38 #define D3DRENDERSTATE_EDGEANTIALIAS (D3DRENDERSTATETYPE)40 #define D3DRENDERSTATE_ZBIAS (D3DRENDERSTATETYPE)47 #define D3DRENDERSTATE_RANGEFOGENABLE (D3DRENDERSTATETYPE)48 #define D3DRENDERSTATE_STENCILENABLE (D3DRENDERSTATETYPE)52 #define D3DRENDERSTATE_STENCILFAIL (D3DRENDERSTATETYPE)53 #define D3DRENDERSTATE_STENCILZFAIL (D3DRENDERSTATETYPE)54 #define D3DRENDERSTATE_STENCILPASS (D3DRENDERSTATETYPE)55 #define D3DRENDERSTATE_STENCILFUNC (D3DRENDERSTATETYPE)56 #define D3DRENDERSTATE_STENCILREF (D3DRENDERSTATETYPE)57 #define D3DRENDERSTATE_STENCILMASK (D3DRENDERSTATETYPE)58 #define D3DRENDERSTATE_STENCILWRITEMASK (D3DRENDERSTATETYPE)59 #define D3DRENDERSTATE_TEXTUREFACTOR (D3DRENDERSTATETYPE)60 #define D3DRENDERSTATE_WRAP0 (D3DRENDERSTATETYPE)128 #define D3DRENDERSTATE_WRAP1 (D3DRENDERSTATETYPE)129 #define D3DRENDERSTATE_WRAP2 (D3DRENDERSTATETYPE)130 #define D3DRENDERSTATE_WRAP3 (D3DRENDERSTATETYPE)131 #define D3DRENDERSTATE_WRAP4 (D3DRENDERSTATETYPE)132 #define D3DRENDERSTATE_WRAP5 (D3DRENDERSTATETYPE)133 #define D3DRENDERSTATE_WRAP6 (D3DRENDERSTATETYPE)134 #define D3DRENDERSTATE_WRAP7 (D3DRENDERSTATETYPE)135 #define D3DRENDERSTATE_CLIPPING (D3DRENDERSTATETYPE)136 #define D3DRENDERSTATE_LIGHTING (D3DRENDERSTATETYPE)137 #define D3DRENDERSTATE_EXTENTS (D3DRENDERSTATETYPE)138 #define D3DRENDERSTATE_AMBIENT (D3DRENDERSTATETYPE)139 #define D3DRENDERSTATE_FOGVERTEXMODE (D3DRENDERSTATETYPE)140 #define D3DRENDERSTATE_COLORVERTEX (D3DRENDERSTATETYPE)141 #define D3DRENDERSTATE_LOCALVIEWER (D3DRENDERSTATETYPE)142 #define D3DRENDERSTATE_NORMALIZENORMALS (D3DRENDERSTATETYPE)143 #define D3DRENDERSTATE_COLORKEYBLENDENABLE (D3DRENDERSTATETYPE)144 #define D3DRENDERSTATE_DIFFUSEMATERIALSOURCE (D3DRENDERSTATETYPE)145 #define D3DRENDERSTATE_SPECULARMATERIALSOURCE (D3DRENDERSTATETYPE)146 #define D3DRENDERSTATE_AMBIENTMATERIALSOURCE (D3DRENDERSTATETYPE)147 #define D3DRENDERSTATE_EMISSIVEMATERIALSOURCE (D3DRENDERSTATETYPE)148 #define D3DRENDERSTATE_VERTEXBLEND (D3DRENDERSTATETYPE)151 #define D3DRENDERSTATE_CLIPPLANEENABLE (D3DRENDERSTATETYPE)152 // // retired renderstates - not supported for DX7 interfaces // #define D3DRENDERSTATE_TEXTUREHANDLE (D3DRENDERSTATETYPE)1 #define D3DRENDERSTATE_ANTIALIAS (D3DRENDERSTATETYPE)2 #define D3DRENDERSTATE_TEXTUREADDRESS (D3DRENDERSTATETYPE)3 #define D3DRENDERSTATE_WRAPU (D3DRENDERSTATETYPE)5 #define D3DRENDERSTATE_WRAPV (D3DRENDERSTATETYPE)6 #define D3DRENDERSTATE_MONOENABLE (D3DRENDERSTATETYPE)11 #define D3DRENDERSTATE_ROP2 (D3DRENDERSTATETYPE)12 #define D3DRENDERSTATE_PLANEMASK (D3DRENDERSTATETYPE)13 #define D3DRENDERSTATE_TEXTUREMAG (D3DRENDERSTATETYPE)17 #define D3DRENDERSTATE_TEXTUREMIN (D3DRENDERSTATETYPE)18 #define D3DRENDERSTATE_TEXTUREMAPBLEND (D3DRENDERSTATETYPE)21 #define D3DRENDERSTATE_SUBPIXEL (D3DRENDERSTATETYPE)31 #define D3DRENDERSTATE_SUBPIXELX (D3DRENDERSTATETYPE)32 #define D3DRENDERSTATE_STIPPLEENABLE (D3DRENDERSTATETYPE)39 #define D3DRENDERSTATE_OLDALPHABLENDENABLE (D3DRENDERSTATETYPE)42 #define D3DRENDERSTATE_BORDERCOLOR (D3DRENDERSTATETYPE)43 #define D3DRENDERSTATE_TEXTUREADDRESSU (D3DRENDERSTATETYPE)44 #define D3DRENDERSTATE_TEXTUREADDRESSV (D3DRENDERSTATETYPE)45 #define D3DRENDERSTATE_MIPMAPLODBIAS (D3DRENDERSTATETYPE)46 #define D3DRENDERSTATE_ANISOTROPY (D3DRENDERSTATETYPE)49 #define D3DRENDERSTATE_FLUSHBATCH (D3DRENDERSTATETYPE)50 #define D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT (D3DRENDERSTATETYPE)51 #define D3DRENDERSTATE_STIPPLEPATTERN00 (D3DRENDERSTATETYPE)64 #define D3DRENDERSTATE_STIPPLEPATTERN01 (D3DRENDERSTATETYPE)65 #define D3DRENDERSTATE_STIPPLEPATTERN02 (D3DRENDERSTATETYPE)66 #define D3DRENDERSTATE_STIPPLEPATTERN03 (D3DRENDERSTATETYPE)67 #define D3DRENDERSTATE_STIPPLEPATTERN04 (D3DRENDERSTATETYPE)68 #define D3DRENDERSTATE_STIPPLEPATTERN05 (D3DRENDERSTATETYPE)69 #define D3DRENDERSTATE_STIPPLEPATTERN06 (D3DRENDERSTATETYPE)70 #define D3DRENDERSTATE_STIPPLEPATTERN07 (D3DRENDERSTATETYPE)71 #define D3DRENDERSTATE_STIPPLEPATTERN08 (D3DRENDERSTATETYPE)72 #define D3DRENDERSTATE_STIPPLEPATTERN09 (D3DRENDERSTATETYPE)73 #define D3DRENDERSTATE_STIPPLEPATTERN10 (D3DRENDERSTATETYPE)74 #define D3DRENDERSTATE_STIPPLEPATTERN11 (D3DRENDERSTATETYPE)75 #define D3DRENDERSTATE_STIPPLEPATTERN12 (D3DRENDERSTATETYPE)76 #define D3DRENDERSTATE_STIPPLEPATTERN13 (D3DRENDERSTATETYPE)77 #define D3DRENDERSTATE_STIPPLEPATTERN14 (D3DRENDERSTATETYPE)78 #define D3DRENDERSTATE_STIPPLEPATTERN15 (D3DRENDERSTATETYPE)79 #define D3DRENDERSTATE_STIPPLEPATTERN16 (D3DRENDERSTATETYPE)80 #define D3DRENDERSTATE_STIPPLEPATTERN17 (D3DRENDERSTATETYPE)81 #define D3DRENDERSTATE_STIPPLEPATTERN18 (D3DRENDERSTATETYPE)82 #define D3DRENDERSTATE_STIPPLEPATTERN19 (D3DRENDERSTATETYPE)83 #define D3DRENDERSTATE_STIPPLEPATTERN20 (D3DRENDERSTATETYPE)84 #define D3DRENDERSTATE_STIPPLEPATTERN21 (D3DRENDERSTATETYPE)85 #define D3DRENDERSTATE_STIPPLEPATTERN22 (D3DRENDERSTATETYPE)86 #define D3DRENDERSTATE_STIPPLEPATTERN23 (D3DRENDERSTATETYPE)87 #define D3DRENDERSTATE_STIPPLEPATTERN24 (D3DRENDERSTATETYPE)88 #define D3DRENDERSTATE_STIPPLEPATTERN25 (D3DRENDERSTATETYPE)89 #define D3DRENDERSTATE_STIPPLEPATTERN26 (D3DRENDERSTATETYPE)90 #define D3DRENDERSTATE_STIPPLEPATTERN27 (D3DRENDERSTATETYPE)91 #define D3DRENDERSTATE_STIPPLEPATTERN28 (D3DRENDERSTATETYPE)92 #define D3DRENDERSTATE_STIPPLEPATTERN29 (D3DRENDERSTATETYPE)93 #define D3DRENDERSTATE_STIPPLEPATTERN30 (D3DRENDERSTATETYPE)94 #define D3DRENDERSTATE_STIPPLEPATTERN31 (D3DRENDERSTATETYPE)95 // // retired renderstates - not supported for DX8 interfaces // #define D3DRENDERSTATE_COLORKEYENABLE (D3DRENDERSTATETYPE)41 #define D3DRENDERSTATE_COLORKEYBLENDENABLE (D3DRENDERSTATETYPE)144 // // retired renderstate names - the values are still used under new naming conventions // #define D3DRENDERSTATE_BLENDENABLE (D3DRENDERSTATETYPE)27 #define D3DRENDERSTATE_FOGTABLESTART (D3DRENDERSTATETYPE)36 #define D3DRENDERSTATE_FOGTABLEEND (D3DRENDERSTATETYPE)37 #define D3DRENDERSTATE_FOGTABLEDENSITY (D3DRENDERSTATETYPE)38 #endif //(DIRECT3D_VERSION < 0x0800) #if(DIRECT3D_VERSION < 0x0800) // Values for material source typedef enum _D3DMATERIALCOLORSOURCE { D3DMCS_MATERIAL = 0, // Color from material is used D3DMCS_COLOR1 = 1, // Diffuse vertex color is used D3DMCS_COLOR2 = 2, // Specular vertex color is used D3DMCS_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum } D3DMATERIALCOLORSOURCE; #if(DIRECT3D_VERSION >= 0x0500) // For back-compatibility with legacy compilations #define D3DRENDERSTATE_BLENDENABLE D3DRENDERSTATE_ALPHABLENDENABLE #endif /* DIRECT3D_VERSION >= 0x0500 */ #if(DIRECT3D_VERSION >= 0x0600) // Bias to apply to the texture coordinate set to apply a wrap to. #define D3DRENDERSTATE_WRAPBIAS 128UL /* Flags to construct the WRAP render states */ #define D3DWRAP_U 0x00000001L #define D3DWRAP_V 0x00000002L #endif /* DIRECT3D_VERSION >= 0x0600 */ #if(DIRECT3D_VERSION >= 0x0700) /* Flags to construct the WRAP render states for 1D thru 4D texture coordinates */ #define D3DWRAPCOORD_0 0x00000001L // same as D3DWRAP_U #define D3DWRAPCOORD_1 0x00000002L // same as D3DWRAP_V #define D3DWRAPCOORD_2 0x00000004L #define D3DWRAPCOORD_3 0x00000008L #endif /* DIRECT3D_VERSION >= 0x0700 */ #endif //(DIRECT3D_VERSION < 0x0800) #define D3DRENDERSTATE_STIPPLEPATTERN(y) (D3DRENDERSTATE_STIPPLEPATTERN00 + (y)) typedef struct _D3DSTATE { union { #if(DIRECT3D_VERSION < 0x0800) D3DTRANSFORMSTATETYPE dtstTransformStateType; #endif //(DIRECT3D_VERSION < 0x0800) D3DLIGHTSTATETYPE dlstLightStateType; D3DRENDERSTATETYPE drstRenderStateType; }; union { DWORD dwArg[1]; D3DVALUE dvArg[1]; }; } D3DSTATE, *LPD3DSTATE; /* * Operation used to load matrices * hDstMat = hSrcMat */ typedef struct _D3DMATRIXLOAD { D3DMATRIXHANDLE hDestMatrix; /* Destination matrix */ D3DMATRIXHANDLE hSrcMatrix; /* Source matrix */ } D3DMATRIXLOAD, *LPD3DMATRIXLOAD; /* * Operation used to multiply matrices * hDstMat = hSrcMat1 * hSrcMat2 */ typedef struct _D3DMATRIXMULTIPLY { D3DMATRIXHANDLE hDestMatrix; /* Destination matrix */ D3DMATRIXHANDLE hSrcMatrix1; /* First source matrix */ D3DMATRIXHANDLE hSrcMatrix2; /* Second source matrix */ } D3DMATRIXMULTIPLY, *LPD3DMATRIXMULTIPLY; /* * Operation used to transform and light vertices. */ typedef struct _D3DPROCESSVERTICES { DWORD dwFlags; /* Do we transform or light or just copy? */ WORD wStart; /* Index to first vertex in source */ WORD wDest; /* Index to first vertex in local buffer */ DWORD dwCount; /* Number of vertices to be processed */ DWORD dwReserved; /* Must be zero */ } D3DPROCESSVERTICES, *LPD3DPROCESSVERTICES; #define D3DPROCESSVERTICES_TRANSFORMLIGHT 0x00000000L #define D3DPROCESSVERTICES_TRANSFORM 0x00000001L #define D3DPROCESSVERTICES_COPY 0x00000002L #define D3DPROCESSVERTICES_OPMASK 0x00000007L #define D3DPROCESSVERTICES_UPDATEEXTENTS 0x00000008L #define D3DPROCESSVERTICES_NOCOLOR 0x00000010L #if(DIRECT3D_VERSION >= 0x0600) #if(DIRECT3D_VERSION < 0x0800) /* * State enumerants for per-stage texture processing. */ typedef enum _D3DTEXTURESTAGESTATETYPE { D3DTSS_COLOROP = 1, /* D3DTEXTUREOP - per-stage blending controls for color channels */ D3DTSS_COLORARG1 = 2, /* D3DTA_* (texture arg) */ D3DTSS_COLORARG2 = 3, /* D3DTA_* (texture arg) */ D3DTSS_ALPHAOP = 4, /* D3DTEXTUREOP - per-stage blending controls for alpha channel */ D3DTSS_ALPHAARG1 = 5, /* D3DTA_* (texture arg) */ D3DTSS_ALPHAARG2 = 6, /* D3DTA_* (texture arg) */ D3DTSS_BUMPENVMAT00 = 7, /* D3DVALUE (bump mapping matrix) */ D3DTSS_BUMPENVMAT01 = 8, /* D3DVALUE (bump mapping matrix) */ D3DTSS_BUMPENVMAT10 = 9, /* D3DVALUE (bump mapping matrix) */ D3DTSS_BUMPENVMAT11 = 10, /* D3DVALUE (bump mapping matrix) */ D3DTSS_TEXCOORDINDEX = 11, /* identifies which set of texture coordinates index this texture */ D3DTSS_ADDRESS = 12, /* D3DTEXTUREADDRESS for both coordinates */ D3DTSS_ADDRESSU = 13, /* D3DTEXTUREADDRESS for U coordinate */ D3DTSS_ADDRESSV = 14, /* D3DTEXTUREADDRESS for V coordinate */ D3DTSS_BORDERCOLOR = 15, /* D3DCOLOR */ D3DTSS_MAGFILTER = 16, /* D3DTEXTUREMAGFILTER filter to use for magnification */ D3DTSS_MINFILTER = 17, /* D3DTEXTUREMINFILTER filter to use for minification */ D3DTSS_MIPFILTER = 18, /* D3DTEXTUREMIPFILTER filter to use between mipmaps during minification */ D3DTSS_MIPMAPLODBIAS = 19, /* D3DVALUE Mipmap LOD bias */ D3DTSS_MAXMIPLEVEL = 20, /* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) */ D3DTSS_MAXANISOTROPY = 21, /* DWORD maximum anisotropy */ D3DTSS_BUMPENVLSCALE = 22, /* D3DVALUE scale for bump map luminance */ D3DTSS_BUMPENVLOFFSET = 23, /* D3DVALUE offset for bump map luminance */ #if(DIRECT3D_VERSION >= 0x0700) D3DTSS_TEXTURETRANSFORMFLAGS = 24, /* D3DTEXTURETRANSFORMFLAGS controls texture transform */ #endif /* DIRECT3D_VERSION >= 0x0700 */ D3DTSS_FORCE_DWORD = 0x7fffffff, /* force 32-bit size enum */ } D3DTEXTURESTAGESTATETYPE; #if(DIRECT3D_VERSION >= 0x0700) // Values, used with D3DTSS_TEXCOORDINDEX, to specify that the vertex data(position // and normal in the camera space) should be taken as texture coordinates // Low 16 bits are used to specify texture coordinate index, to take the WRAP mode from // #define D3DTSS_TCI_PASSTHRU 0x00000000 #define D3DTSS_TCI_CAMERASPACENORMAL 0x00010000 #define D3DTSS_TCI_CAMERASPACEPOSITION 0x00020000 #define D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR 0x00030000 #endif /* DIRECT3D_VERSION >= 0x0700 */ /* * Enumerations for COLOROP and ALPHAOP texture blending operations set in * texture processing stage controls in D3DRENDERSTATE. */ typedef enum _D3DTEXTUREOP { // Control D3DTOP_DISABLE = 1, // disables stage D3DTOP_SELECTARG1 = 2, // the default D3DTOP_SELECTARG2 = 3, // Modulate D3DTOP_MODULATE = 4, // multiply args together D3DTOP_MODULATE2X = 5, // multiply and 1 bit D3DTOP_MODULATE4X = 6, // multiply and 2 bits // Add D3DTOP_ADD = 7, // add arguments together D3DTOP_ADDSIGNED = 8, // add with -0.5 bias D3DTOP_ADDSIGNED2X = 9, // as above but left 1 bit D3DTOP_SUBTRACT = 10, // Arg1 - Arg2, with no saturation D3DTOP_ADDSMOOTH = 11, // add 2 args, subtract product // Arg1 + Arg2 - Arg1*Arg2 // = Arg1 + (1-Arg1)*Arg2 // Linear alpha blend: Arg1*(Alpha) + Arg2*(1-Alpha) D3DTOP_BLENDDIFFUSEALPHA = 12, // iterated alpha D3DTOP_BLENDTEXTUREALPHA = 13, // texture alpha D3DTOP_BLENDFACTORALPHA = 14, // alpha from D3DRENDERSTATE_TEXTUREFACTOR // Linear alpha blend with pre-multiplied arg1 input: Arg1 + Arg2*(1-Alpha) D3DTOP_BLENDTEXTUREALPHAPM = 15, // texture alpha D3DTOP_BLENDCURRENTALPHA = 16, // by alpha of current color // Specular mapping D3DTOP_PREMODULATE = 17, // modulate with next texture before use D3DTOP_MODULATEALPHA_ADDCOLOR = 18, // Arg1.RGB + Arg1.A*Arg2.RGB // COLOROP only D3DTOP_MODULATECOLOR_ADDALPHA = 19, // Arg1.RGB*Arg2.RGB + Arg1.A // COLOROP only D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20, // (1-Arg1.A)*Arg2.RGB + Arg1.RGB // COLOROP only D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21, // (1-Arg1.RGB)*Arg2.RGB + Arg1.A // COLOROP only // Bump mapping D3DTOP_BUMPENVMAP = 22, // per pixel env map perturbation D3DTOP_BUMPENVMAPLUMINANCE = 23, // with luminance channel // This can do either diffuse or specular bump mapping with correct input. // Performs the function (Arg1.R*Arg2.R + Arg1.G*Arg2.G + Arg1.B*Arg2.B) // where each component has been scaled and offset to make it signed. // The result is replicated into all four (including alpha) channels. // This is a valid COLOROP only. D3DTOP_DOTPRODUCT3 = 24, D3DTOP_FORCE_DWORD = 0x7fffffff, } D3DTEXTUREOP; /* * Values for COLORARG1,2 and ALPHAARG1,2 texture blending operations * set in texture processing stage controls in D3DRENDERSTATE. */ #define D3DTA_SELECTMASK 0x0000000f // mask for arg selector #define D3DTA_DIFFUSE 0x00000000 // select diffuse color #define D3DTA_CURRENT 0x00000001 // select result of previous stage #define D3DTA_TEXTURE 0x00000002 // select texture color #define D3DTA_TFACTOR 0x00000003 // select RENDERSTATE_TEXTUREFACTOR #if(DIRECT3D_VERSION >= 0x0700) #define D3DTA_SPECULAR 0x00000004 // select specular color #endif /* DIRECT3D_VERSION >= 0x0700 */ #define D3DTA_COMPLEMENT 0x00000010 // take 1.0 - x #define D3DTA_ALPHAREPLICATE 0x00000020 // replicate alpha to color components #endif //(DIRECT3D_VERSION < 0x0800) /* * IDirect3DTexture2 State Filter Types */ typedef enum _D3DTEXTUREMAGFILTER { D3DTFG_POINT = 1, // nearest D3DTFG_LINEAR = 2, // linear interpolation D3DTFG_FLATCUBIC = 3, // cubic D3DTFG_GAUSSIANCUBIC = 4, // different cubic kernel D3DTFG_ANISOTROPIC = 5, // #if(DIRECT3D_VERSION >= 0x0700) #endif /* DIRECT3D_VERSION >= 0x0700 */ D3DTFG_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum } D3DTEXTUREMAGFILTER; typedef enum _D3DTEXTUREMINFILTER { D3DTFN_POINT = 1, // nearest D3DTFN_LINEAR = 2, // linear interpolation D3DTFN_ANISOTROPIC = 3, // D3DTFN_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum } D3DTEXTUREMINFILTER; typedef enum _D3DTEXTUREMIPFILTER { D3DTFP_NONE = 1, // mipmapping disabled (use MAG filter) D3DTFP_POINT = 2, // nearest D3DTFP_LINEAR = 3, // linear interpolation D3DTFP_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum } D3DTEXTUREMIPFILTER; #endif /* DIRECT3D_VERSION >= 0x0600 */ /* * Triangle flags */ /* * Tri strip and fan flags. * START loads all three vertices * EVEN and ODD load just v3 with even or odd culling * START_FLAT contains a count from 0 to 29 that allows the * whole strip or fan to be culled in one hit. * e.g. for a quad len = 1 */ #define D3DTRIFLAG_START 0x00000000L #define D3DTRIFLAG_STARTFLAT(len) (len) /* 0 < len < 30 */ #define D3DTRIFLAG_ODD 0x0000001eL #define D3DTRIFLAG_EVEN 0x0000001fL /* * Triangle edge flags * enable edges for wireframe or antialiasing */ #define D3DTRIFLAG_EDGEENABLE1 0x00000100L /* v0-v1 edge */ #define D3DTRIFLAG_EDGEENABLE2 0x00000200L /* v1-v2 edge */ #define D3DTRIFLAG_EDGEENABLE3 0x00000400L /* v2-v0 edge */ #define D3DTRIFLAG_EDGEENABLETRIANGLE \ (D3DTRIFLAG_EDGEENABLE1 | D3DTRIFLAG_EDGEENABLE2 | D3DTRIFLAG_EDGEENABLE3) /* * Primitive structures and related defines. Vertex offsets are to types * D3DVERTEX, D3DLVERTEX, or D3DTLVERTEX. */ /* * Triangle list primitive structure */ typedef struct _D3DTRIANGLE { union { WORD v1; /* Vertex indices */ WORD wV1; }; union { WORD v2; WORD wV2; }; union { WORD v3; WORD wV3; }; WORD wFlags; /* Edge (and other) flags */ } D3DTRIANGLE, *LPD3DTRIANGLE; /* * Line list structure. * The instruction count defines the number of line segments. */ typedef struct _D3DLINE { union { WORD v1; /* Vertex indices */ WORD wV1; }; union { WORD v2; WORD wV2; }; } D3DLINE, *LPD3DLINE; /* * Span structure * Spans join a list of points with the same y value. * If the y value changes, a new span is started. */ typedef struct _D3DSPAN { WORD wCount; /* Number of spans */ WORD wFirst; /* Index to first vertex */ } D3DSPAN, *LPD3DSPAN; /* * Point structure */ typedef struct _D3DPOINT { WORD wCount; /* number of points */ WORD wFirst; /* index to first vertex */ } D3DPOINT, *LPD3DPOINT; /* * Forward branch structure. * Mask is logically anded with the driver status mask * if the result equals 'value', the branch is taken. */ typedef struct _D3DBRANCH { DWORD dwMask; /* Bitmask against D3D status */ DWORD dwValue; BOOL bNegate; /* TRUE to negate comparison */ DWORD dwOffset; /* How far to branch forward (0 for exit)*/ } D3DBRANCH, *LPD3DBRANCH; /* * Status used for set status instruction. * The D3D status is initialised on device creation * and is modified by all execute calls. */ typedef struct _D3DSTATUS { DWORD dwFlags; /* Do we set extents or status */ DWORD dwStatus; /* D3D status */ D3DRECT drExtent; } D3DSTATUS, *LPD3DSTATUS; #define D3DSETSTATUS_STATUS 0x00000001L #define D3DSETSTATUS_EXTENTS 0x00000002L #define D3DSETSTATUS_ALL (D3DSETSTATUS_STATUS | D3DSETSTATUS_EXTENTS) #if(DIRECT3D_VERSION >= 0x0500) typedef struct _D3DCLIPSTATUS { DWORD dwFlags; /* Do we set 2d extents, 3D extents or status */ DWORD dwStatus; /* Clip status */ float minx, maxx; /* X extents */ float miny, maxy; /* Y extents */ float minz, maxz; /* Z extents */ } D3DCLIPSTATUS, *LPD3DCLIPSTATUS; #define D3DCLIPSTATUS_STATUS 0x00000001L #define D3DCLIPSTATUS_EXTENTS2 0x00000002L #define D3DCLIPSTATUS_EXTENTS3 0x00000004L #endif /* DIRECT3D_VERSION >= 0x0500 */ /* * Statistics structure */ typedef struct _D3DSTATS { DWORD dwSize; DWORD dwTrianglesDrawn; DWORD dwLinesDrawn; DWORD dwPointsDrawn; DWORD dwSpansDrawn; DWORD dwVerticesProcessed; } D3DSTATS, *LPD3DSTATS; /* * Execute options. * When calling using D3DEXECUTE_UNCLIPPED all the primitives * inside the buffer must be contained within the viewport. */ #define D3DEXECUTE_CLIPPED 0x00000001l #define D3DEXECUTE_UNCLIPPED 0x00000002l typedef struct _D3DEXECUTEDATA { DWORD dwSize; DWORD dwVertexOffset; DWORD dwVertexCount; DWORD dwInstructionOffset; DWORD dwInstructionLength; DWORD dwHVertexOffset; D3DSTATUS dsStatus; /* Status after execute */ } D3DEXECUTEDATA, *LPD3DEXECUTEDATA; /* * Palette flags. * This are or'ed with the peFlags in the PALETTEENTRYs passed to DirectDraw. */ #define D3DPAL_FREE 0x00 /* Renderer may use this entry freely */ #define D3DPAL_READONLY 0x40 /* Renderer may not set this entry */ #define D3DPAL_RESERVED 0x80 /* Renderer may not use this entry */ #if(DIRECT3D_VERSION >= 0x0600) typedef struct _D3DVERTEXBUFFERDESC { DWORD dwSize; DWORD dwCaps; DWORD dwFVF; DWORD dwNumVertices; } D3DVERTEXBUFFERDESC, *LPD3DVERTEXBUFFERDESC; #define D3DVBCAPS_SYSTEMMEMORY 0x00000800l #define D3DVBCAPS_WRITEONLY 0x00010000l #define D3DVBCAPS_OPTIMIZED 0x80000000l #define D3DVBCAPS_DONOTCLIP 0x00000001l /* Vertex Operations for ProcessVertices */ #define D3DVOP_LIGHT (1 << 10) #define D3DVOP_TRANSFORM (1 << 0) #define D3DVOP_CLIP (1 << 2) #define D3DVOP_EXTENTS (1 << 3) #if(DIRECT3D_VERSION < 0x0800) /* The maximum number of vertices user can pass to any d3d drawing function or to create vertex buffer with */ #define D3DMAXNUMVERTICES ((1<<16) - 1) /* The maximum number of primitives user can pass to any d3d drawing function. */ #define D3DMAXNUMPRIMITIVES ((1<<16) - 1) #if(DIRECT3D_VERSION >= 0x0700) /* Bits for dwFlags in ProcessVertices call */ #define D3DPV_DONOTCOPYDATA (1 << 0) #endif /* DIRECT3D_VERSION >= 0x0700 */ #endif //(DIRECT3D_VERSION < 0x0800) //------------------------------------------------------------------- #if(DIRECT3D_VERSION < 0x0800) // Flexible vertex format bits // #define D3DFVF_RESERVED0 0x001 #define D3DFVF_POSITION_MASK 0x00E #define D3DFVF_XYZ 0x002 #define D3DFVF_XYZRHW 0x004 #if(DIRECT3D_VERSION >= 0x0700) #define D3DFVF_XYZB1 0x006 #define D3DFVF_XYZB2 0x008 #define D3DFVF_XYZB3 0x00a #define D3DFVF_XYZB4 0x00c #define D3DFVF_XYZB5 0x00e #endif /* DIRECT3D_VERSION >= 0x0700 */ #define D3DFVF_NORMAL 0x010 #define D3DFVF_RESERVED1 0x020 #define D3DFVF_DIFFUSE 0x040 #define D3DFVF_SPECULAR 0x080 #define D3DFVF_TEXCOUNT_MASK 0xf00 #define D3DFVF_TEXCOUNT_SHIFT 8 #define D3DFVF_TEX0 0x000 #define D3DFVF_TEX1 0x100 #define D3DFVF_TEX2 0x200 #define D3DFVF_TEX3 0x300 #define D3DFVF_TEX4 0x400 #define D3DFVF_TEX5 0x500 #define D3DFVF_TEX6 0x600 #define D3DFVF_TEX7 0x700 #define D3DFVF_TEX8 0x800 #define D3DFVF_RESERVED2 0xf000 // 4 reserved bits #else #define D3DFVF_RESERVED1 0x020 #endif //(DIRECT3D_VERSION < 0x0800) #define D3DFVF_VERTEX ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 ) #define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_RESERVED1 | D3DFVF_DIFFUSE | \ D3DFVF_SPECULAR | D3DFVF_TEX1 ) #define D3DFVF_TLVERTEX ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \ D3DFVF_TEX1 ) typedef struct _D3DDP_PTRSTRIDE { LPVOID lpvData; DWORD dwStride; } D3DDP_PTRSTRIDE; #define D3DDP_MAXTEXCOORD 8 typedef struct _D3DDRAWPRIMITIVESTRIDEDDATA { D3DDP_PTRSTRIDE position; D3DDP_PTRSTRIDE normal; D3DDP_PTRSTRIDE diffuse; D3DDP_PTRSTRIDE specular; D3DDP_PTRSTRIDE textureCoords[D3DDP_MAXTEXCOORD]; } D3DDRAWPRIMITIVESTRIDEDDATA, *LPD3DDRAWPRIMITIVESTRIDEDDATA; //--------------------------------------------------------------------- // ComputeSphereVisibility return values // #define D3DVIS_INSIDE_FRUSTUM 0 #define D3DVIS_INTERSECT_FRUSTUM 1 #define D3DVIS_OUTSIDE_FRUSTUM 2 #define D3DVIS_INSIDE_LEFT 0 #define D3DVIS_INTERSECT_LEFT (1 << 2) #define D3DVIS_OUTSIDE_LEFT (2 << 2) #define D3DVIS_INSIDE_RIGHT 0 #define D3DVIS_INTERSECT_RIGHT (1 << 4) #define D3DVIS_OUTSIDE_RIGHT (2 << 4) #define D3DVIS_INSIDE_TOP 0 #define D3DVIS_INTERSECT_TOP (1 << 6) #define D3DVIS_OUTSIDE_TOP (2 << 6) #define D3DVIS_INSIDE_BOTTOM 0 #define D3DVIS_INTERSECT_BOTTOM (1 << 8) #define D3DVIS_OUTSIDE_BOTTOM (2 << 8) #define D3DVIS_INSIDE_NEAR 0 #define D3DVIS_INTERSECT_NEAR (1 << 10) #define D3DVIS_OUTSIDE_NEAR (2 << 10) #define D3DVIS_INSIDE_FAR 0 #define D3DVIS_INTERSECT_FAR (1 << 12) #define D3DVIS_OUTSIDE_FAR (2 << 12) #define D3DVIS_MASK_FRUSTUM (3 << 0) #define D3DVIS_MASK_LEFT (3 << 2) #define D3DVIS_MASK_RIGHT (3 << 4) #define D3DVIS_MASK_TOP (3 << 6) #define D3DVIS_MASK_BOTTOM (3 << 8) #define D3DVIS_MASK_NEAR (3 << 10) #define D3DVIS_MASK_FAR (3 << 12) #endif /* DIRECT3D_VERSION >= 0x0600 */ #if(DIRECT3D_VERSION < 0x0800) #if(DIRECT3D_VERSION >= 0x0700) // To be used with GetInfo() #define D3DDEVINFOID_TEXTUREMANAGER 1 #define D3DDEVINFOID_D3DTEXTUREMANAGER 2 #define D3DDEVINFOID_TEXTURING 3 typedef enum _D3DSTATEBLOCKTYPE { D3DSBT_ALL = 1, // capture all state D3DSBT_PIXELSTATE = 2, // capture pixel state D3DSBT_VERTEXSTATE = 3, // capture vertex state D3DSBT_FORCE_DWORD = 0xffffffff } D3DSTATEBLOCKTYPE; // The D3DVERTEXBLENDFLAGS type is used with D3DRENDERSTATE_VERTEXBLEND state. // typedef enum _D3DVERTEXBLENDFLAGS { D3DVBLEND_DISABLE = 0, // Disable vertex blending D3DVBLEND_1WEIGHT = 1, // blend between 2 matrices D3DVBLEND_2WEIGHTS = 2, // blend between 3 matrices D3DVBLEND_3WEIGHTS = 3, // blend between 4 matrices } D3DVERTEXBLENDFLAGS; typedef enum _D3DTEXTURETRANSFORMFLAGS { D3DTTFF_DISABLE = 0, // texture coordinates are passed directly D3DTTFF_COUNT1 = 1, // rasterizer should expect 1-D texture coords D3DTTFF_COUNT2 = 2, // rasterizer should expect 2-D texture coords D3DTTFF_COUNT3 = 3, // rasterizer should expect 3-D texture coords D3DTTFF_COUNT4 = 4, // rasterizer should expect 4-D texture coords D3DTTFF_PROJECTED = 256, // texcoords to be divided by COUNTth element D3DTTFF_FORCE_DWORD = 0x7fffffff, } D3DTEXTURETRANSFORMFLAGS; // Macros to set texture coordinate format bits in the FVF id #define D3DFVF_TEXTUREFORMAT2 0 // Two floating point values #define D3DFVF_TEXTUREFORMAT1 3 // One floating point value #define D3DFVF_TEXTUREFORMAT3 1 // Three floating point values #define D3DFVF_TEXTUREFORMAT4 2 // Four floating point values #define D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16)) #define D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2) #define D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16)) #define D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16)) #endif /* DIRECT3D_VERSION >= 0x0700 */ #else // // legacy vertex blend names // typedef enum _D3DVERTEXBLENDFLAGS D3DVERTEXBLENDFLAGS; #define D3DVBLEND_DISABLE (D3DVERTEXBLENDFLAGS)0 #define D3DVBLEND_1WEIGHT (D3DVERTEXBLENDFLAGS)1 #define D3DVBLEND_2WEIGHTS (D3DVERTEXBLENDFLAGS)2 #define D3DVBLEND_3WEIGHTS (D3DVERTEXBLENDFLAGS)3 #endif //(DIRECT3D_VERSION < 0x0800) #pragma pack() #pragma warning(pop) #endif /* _D3DTYPES_H_ */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion
34.478947
140
0.651822
[ "render", "vector", "model", "transform", "3d" ]
c18956c9153a82907cbd49e3cba76bd8d89135f3
350
h
C
SimpleBulletDrawer/NullShape.h
nErumin/SimpleBulletDrawer
054325c5ce69f3aaba73d72fc21f84f2fdeb5e7b
[ "MIT" ]
null
null
null
SimpleBulletDrawer/NullShape.h
nErumin/SimpleBulletDrawer
054325c5ce69f3aaba73d72fc21f84f2fdeb5e7b
[ "MIT" ]
null
null
null
SimpleBulletDrawer/NullShape.h
nErumin/SimpleBulletDrawer
054325c5ce69f3aaba73d72fc21f84f2fdeb5e7b
[ "MIT" ]
null
null
null
#ifndef _NULL_SHAPE_H_ #define _NULL_SHAPE_H_ #include "IShape.h" namespace Shape { class NullShape : public IShape { public: const std::vector<float>& Vertices() const override; const std::vector<float>& Colors() const override; private: std::vector<float> mEmptyVector; }; } #endif // !_NULL_SHAPE_H_
18.421053
60
0.657143
[ "shape", "vector" ]
c18a11dccc0659f918988b80e8f52b7151933ff9
7,884
h
C
UnrealEngine-4.11.2-release/Engine/Source/Editor/Sequencer/Private/SSequencerTreeView.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/Sequencer/Private/SSequencerTreeView.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/Sequencer/Private/SSequencerTreeView.h
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once class FSequencer; class FSequencerNodeTree; class FSequencerDisplayNode; class SSequencerTrackLane; class SSequencerTrackArea; class SSequencerTreeViewRow; typedef TSharedRef<FSequencerDisplayNode> FDisplayNodeRef; enum class ETreeRecursion { Recursive, NonRecursive }; /** Structure used to define a column in the tree view */ struct FSequencerTreeViewColumn { typedef TFunction<TSharedRef<SWidget>(const FDisplayNodeRef&, const TSharedRef<SSequencerTreeViewRow>&)> FOnGenerate; FSequencerTreeViewColumn(const FOnGenerate& InOnGenerate, const TAttribute<float>& InWidth) : Generator(InOnGenerate), Width(InWidth) {} FSequencerTreeViewColumn(FOnGenerate&& InOnGenerate, const TAttribute<float>& InWidth) : Generator(MoveTemp(InOnGenerate)), Width(InWidth) {} /** Function used to generate a cell for this column */ FOnGenerate Generator; /** Attribute specifying the width of this column */ TAttribute<float> Width; }; /** The tree view used in the sequencer */ class SSequencerTreeView : public STreeView<FDisplayNodeRef> { public: SLATE_BEGIN_ARGS(SSequencerTreeView){} /** Externally supplied scroll bar */ SLATE_ARGUMENT( TSharedPtr<SScrollBar>, ExternalScrollbar ) SLATE_END_ARGS() /** Construct this widget */ void Construct(const FArguments& InArgs, const TSharedRef<FSequencerNodeTree>& InNodeTree, const TSharedRef<SSequencerTrackArea>& InTrackArea); virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ); /** Access the underlying tree data */ TSharedPtr<FSequencerNodeTree> GetNodeTree() { return SequencerNodeTree; } public: /** Get the display node at the specified physical vertical position */ TSharedPtr<FSequencerDisplayNode> HitTestNode(float InPhysical) const; /** Convert the specified physical vertical position into an absolute virtual position, ignoring expanded states */ float PhysicalToVirtual(float InPhysical) const; /** Convert the specified absolute virtual position into a physical position in the tree. * @note: Will not work reliably for virtual positions that are outside of the physical space */ float VirtualToPhysical(float InVirtual) const; public: /** Refresh this tree as a result of the underlying tree data changing */ void Refresh(); /** Expand or collapse nodes */ void ToggleExpandCollapseNodes(ETreeRecursion Recursion = ETreeRecursion::Recursive, bool bExpandAll = false); /** Expand nodes */ void ExpandNodes(ETreeRecursion Recursion = ETreeRecursion::Recursive, bool bExpandAll = false); /** Collapse nodes */ void CollapseNodes(ETreeRecursion Recursion = ETreeRecursion::Recursive, bool bExpandAll = false); /** Scroll this tree view by the specified number of slate units */ void ScrollByDelta(float DeltaInSlateUnits); protected: /** Expand or collapse nodes */ void ExpandOrCollapseNodes(ETreeRecursion Recursion, bool bExpandAll, bool bExpand); /** Set the item's expansion state, including all of its children */ void ExpandCollapseNode(const FDisplayNodeRef& InNode, bool bExpansionState, ETreeRecursion Recursion); /** Generate a row for a particular node */ TSharedRef<ITableRow> OnGenerateRow(FDisplayNodeRef InDisplayNode, const TSharedRef<STableViewBase>& OwnerTable); /** Gather the children from the specified node */ void OnGetChildren(FDisplayNodeRef InParent, TArray<FDisplayNodeRef>& OutChildren) const; /** Generate a widget for the specified Node and Column */ TSharedRef<SWidget> GenerateWidgetForColumn(const FDisplayNodeRef& Node, const FName& ColumnId, const TSharedRef<SSequencerTreeViewRow>& Row) const; /** Called when a node has been expanded or collapsed */ void OnExpansionChanged(FDisplayNodeRef InItem, bool bIsExpanded); /** Called when the sequencer outliner selection has been changed externally */ void OnSequencerSelectionChangedExternally(); /** Overridden to keep external selection states up to date */ virtual void Private_SignalSelectionChanged(ESelectInfo::Type SelectInfo) override; public: /** Structure used to cache physical geometry for a particular node */ struct FCachedGeometry { FCachedGeometry(FDisplayNodeRef InNode, float InPhysicalTop, float InPhysicalHeight) : Node(MoveTemp(InNode)), PhysicalTop(InPhysicalTop), PhysicalHeight(InPhysicalHeight) {} FDisplayNodeRef Node; float PhysicalTop, PhysicalHeight; }; /** Access all the physical nodes currently visible on the sequencer */ const TArray<FCachedGeometry>& GetAllVisibleNodes() const { return PhysicalNodes; } /** Retrieve the last reported physical geometry for the specified node, if available */ TOptional<FCachedGeometry> GetPhysicalGeometryForNode(const FDisplayNodeRef& InNode) const; /** Report geometry for a child row */ void ReportChildRowGeometry(const FDisplayNodeRef& InNode, const FGeometry& InGeometry); /** Called when a child row widget has been added/removed */ void OnChildRowRemoved(const FDisplayNodeRef& InNode); protected: /** Linear, sorted array of nodes that we currently have generated widgets for */ TArray<FCachedGeometry> PhysicalNodes; /** Map of cached geometries for visible nodes */ TMap<FDisplayNodeRef, FCachedGeometry> CachedRowGeometry; protected: /** Populate the map of column definitions, and add relevant columns to the header row */ void SetupColumns(const FArguments& InArgs); /** Ensure that the track area column is either show or hidden, depending on the visibility of the curve editor */ void UpdateTrackArea(); private: /** The tree view's header row (hidden) */ TSharedPtr<SHeaderRow> HeaderRow; /** Pointer to the node tree data that is used to populate this tree */ TSharedPtr<FSequencerNodeTree> SequencerNodeTree; /** Cached copy of the root nodes from the tree data */ TArray<FDisplayNodeRef> RootNodes; /** Column definitions for each of the columns in the tree view */ TMap<FName, FSequencerTreeViewColumn> Columns; /** Strong pointer to the track area so we can generate track lanes as we need them */ TSharedPtr<SSequencerTrackArea> TrackArea; }; /** Widget that represents a row in the sequencer's tree control. */ class SSequencerTreeViewRow : public SMultiColumnTableRow<FDisplayNodeRef> { public: DECLARE_DELEGATE_RetVal_ThreeParams(TSharedRef<SWidget>, FOnGenerateWidgetForColumn, const FDisplayNodeRef&, const FName&, const TSharedRef<SSequencerTreeViewRow>&); SLATE_BEGIN_ARGS(SSequencerTreeViewRow){} /** Delegate to invoke to create a new column for this row */ SLATE_EVENT(FOnGenerateWidgetForColumn, OnGenerateWidgetForColumn) SLATE_END_ARGS() ~SSequencerTreeViewRow(); /** Construct function for this widget */ void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView, const FDisplayNodeRef& InNode); /** Get the dispolay node to which this row relates */ TSharedPtr<FSequencerDisplayNode> GetDisplayNode() const; /** Add a reference to the specified track lane, keeping it alive until this row is destroyed */ void AddTrackAreaReference(const TSharedPtr<SSequencerTrackLane>& Lane); virtual void Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) override; /** Overridden from SMultiColumnTableRow. Generates a widget for this column of the tree row. */ virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnId) override; private: /** Cached reference to a track lane that we relate to. This keeps the track lane alive (it's a weak widget) as long as we are in view. */ TSharedPtr<SSequencerTrackLane> TrackLaneReference; /** The item associated with this row of data */ mutable TWeakPtr<FSequencerDisplayNode> Node; /** Delegate to call to create a new widget for a particular column. */ FOnGenerateWidgetForColumn OnGenerateWidgetForColumn; };
38.458537
166
0.7845
[ "geometry" ]
c19bf14b4d10072e34ec78d52ff3c4c230a6dce1
3,770
h
C
dali/internal/event/animation/property-input-indexer.h
pwisbey/dali-core
53117f5d4178001b0d688c5bce14d7bf8e861631
[ "Apache-2.0" ]
1
2016-08-05T09:58:38.000Z
2016-08-05T09:58:38.000Z
dali/internal/event/animation/property-input-indexer.h
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
dali/internal/event/animation/property-input-indexer.h
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
#ifndef __DALI_PROPERTY_INPUT_INDEXER_H__ #define __DALI_PROPERTY_INPUT_INDEXER_H__ /* * Copyright (c) 2014 Samsung Electronics 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. * */ // INTERNAL INCLUDES #include <dali/internal/event/common/property-input-impl.h> namespace Dali { namespace Internal { /** * Helper object to map public-api PropertyInput methods to internal * PropertyInputImpl methods (which require the current buffer index). */ template < typename AccessorType > class PropertyInputIndexer : public PropertyInput { public: /** * Create an indexer object. * @param[in] bufferIndex The current buffer index. * @param[in] input The internal property input. */ PropertyInputIndexer( BufferIndex bufferIndex, const AccessorType* input ) : mBufferIndex( bufferIndex ), mInput( input ) { } /** * Copy constructor */ PropertyInputIndexer( const PropertyInputIndexer& other ) : mBufferIndex( other.mBufferIndex ), mInput( other.mInput ) { } /** * Assignment operator */ PropertyInputIndexer& operator=( const PropertyInputIndexer& other ) { mBufferIndex = other.mBufferIndex; mInput = other.mInput; return *this; } /** * Virtual Destructor */ virtual ~PropertyInputIndexer() { } /** * @copydoc Dali::Internal::PropertyInput::GetType() */ virtual Property::Type GetType() const { return mInput->GetType(); } /** * @copydoc Dali::Internal::PropertyInput::GetBoolean() */ virtual const bool& GetBoolean() const { return mInput->GetConstraintInputBoolean( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetInteger() */ virtual const int& GetInteger() const { return mInput->GetConstraintInputInteger( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetFloat() */ virtual const float& GetFloat() const { return mInput->GetConstraintInputFloat( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetVector2() */ virtual const Vector2& GetVector2() const { return mInput->GetConstraintInputVector2( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetVector3() */ virtual const Vector3& GetVector3() const { return mInput->GetConstraintInputVector3( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetVector4() */ virtual const Vector4& GetVector4() const { return mInput->GetConstraintInputVector4( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetMatrix3() */ virtual const Matrix3& GetMatrix3() const { return mInput->GetConstraintInputMatrix3( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::GetMatrix() */ virtual const Matrix& GetMatrix() const { return mInput->GetConstraintInputMatrix( mBufferIndex ); } /** * @copydoc Dali::Internal::PropertyInput::Quaternion() */ virtual const Quaternion& GetQuaternion() const { return mInput->GetConstraintInputQuaternion( mBufferIndex ); } public: unsigned int mBufferIndex; const AccessorType* mInput; }; } // namespace Internal } // namespace Dali #endif // __DALI_PROPERTY_INPUT_INDEXER_H__
22.440476
76
0.695225
[ "object" ]
c19f0dbe03efdc25dda19a748a9d858e0e8003f9
1,877
h
C
Engine/source/EtCore/stdafx.h
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
Engine/source/EtCore/stdafx.h
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
Engine/source/EtCore/stdafx.h
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
#pragma once #pragma warning( disable : 4250 ) // inherit via dominance #define NOMINMAX #pragma region //C RunTime Header Files #include <wchar.h> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <memory> #include <algorithm> #include <cstdint> #pragma endregion stl #include <rttr/registration> #pragma region #include <EtMath/MathInc.h> #pragma endregion math #pragma region template<class T> inline void SafeDelete(T &pObjectToDelete) { if (pObjectToDelete != nullptr) { delete pObjectToDelete; pObjectToDelete = nullptr; } } #pragma endregion Templates //platform independent utility to suppress unused parameter warnings from https://stackoverflow.com/questions/4851075 // use expression as sub-expression, // then make type of full expression int, discard result #define UNUSED(x) (void)(x) #pragma warning(disable : 4201) //nameless struct union - used in math library #pragma region #include <EtCore/Util/AtomicTypes.h> #include <EtCore/Util/Context.h> #include <EtCore/Util/Time.h> #include <EtCore/Util/Logger.h> #include <EtCore/Util/PerformanceInfo.h> #include <EtCore/Util/StringUtil.h> #include <EtCore/Hashing/HashString.h> #include <EtCore/Reflection/ReflectionUtil.h> //Working singleton Set #define TIME et::core::ContextManager::GetInstance()->GetActiveContext()->time #define LOG(fmt, ...) et::core::Logger::Log(fmt, __VA_ARGS__) #define PERFORMANCE et::core::PerformanceInfo::GetInstance() // assertions #ifdef ET_SHIPPING #define ET_ASSERT(condition, ...) #else #ifdef PLATFORM_Win #define ET_ASSERT(condition, ...) et::core::Logger::ProcessAssert(condition, __FUNCSIG__, FS(__VA_ARGS__)) #else #define ET_ASSERT(condition, ...) et::core::Logger::ProcessAssert(condition, __PRETTY_FUNCTION__, FS(__VA_ARGS__)) #endif // PLATFORM_Win #endif // ET_SHIPPING #pragma endregion Macros
26.814286
117
0.76292
[ "vector" ]
c19f0ff2b1b9ca1bbc993baf6429b1b2ab8d4ad6
601
h
C
CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/WXWeWorkObject.h
ceekay1991/CallTraceForWeChat
5767cb6f781821b6bf9facc8c87e58e15fa88541
[ "MIT" ]
30
2020-03-22T12:30:21.000Z
2022-02-09T08:49:13.000Z
CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/WXWeWorkObject.h
ceekay1991/CallTraceForWeChat
5767cb6f781821b6bf9facc8c87e58e15fa88541
[ "MIT" ]
null
null
null
CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/WXWeWorkObject.h
ceekay1991/CallTraceForWeChat
5767cb6f781821b6bf9facc8c87e58e15fa88541
[ "MIT" ]
8
2020-03-22T12:30:23.000Z
2020-09-22T04:01:47.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> @class NSData, NSString; @interface WXWeWorkObject : NSObject { int _subType; NSData *_data; NSString *_extInfo; } + (id)object; @property(copy, nonatomic) NSString *extInfo; // @synthesize extInfo=_extInfo; @property(nonatomic) int subType; // @synthesize subType=_subType; @property(retain, nonatomic) NSData *data; // @synthesize data=_data; - (void).cxx_destruct; @end
23.115385
90
0.697171
[ "object" ]
c19f45779ce4601d9afeb456db44e0dec541deaa
30,857
h
C
src/ByteEngine/Render/RenderSystem.h
Game-Tek/Game-Studio-Engine
2cf166265bfb8c7782a4d5288e3cf068a6ca671c
[ "MIT" ]
2
2019-03-25T21:53:58.000Z
2020-01-22T00:43:39.000Z
src/ByteEngine/Render/RenderSystem.h
Game-Tek/Game-Studio-Engine
2cf166265bfb8c7782a4d5288e3cf068a6ca671c
[ "MIT" ]
null
null
null
src/ByteEngine/Render/RenderSystem.h
Game-Tek/Game-Studio-Engine
2cf166265bfb8c7782a4d5288e3cf068a6ca671c
[ "MIT" ]
null
null
null
#pragma once #include "ByteEngine/Handle.hpp" #include "ByteEngine/Game/ApplicationManager.h" #include "ByteEngine/Game/System.hpp" #include "RendererAllocator.h" #include "RenderTypes.h" #include <GAL/Vulkan/VulkanQueue.h> #include <GTSL/Bitfield.h> #include <GTSL/Pair.hpp> #include "ByteEngine/Application/WindowSystem.hpp" namespace GTSL { class Window; } class RenderSystem : public BE::System { public: MAKE_HANDLE(uint32, Buffer) MAKE_HANDLE(uint32, Texture); explicit RenderSystem(const InitializeInfo& initializeInfo); ~RenderSystem(); [[nodiscard]] uint8 GetCurrentFrame() const { return currentFrameIndex; } [[nodiscard]] uint8 GetFrameIndex(int32 frameDelta) const { return static_cast<uint8>(frameDelta % pipelinedFrames); } uint8 GetPipelinedFrames() const { return pipelinedFrames; } GAL::FormatDescriptor GetSwapchainFormat() const { return swapchainFormat; } TaskHandle<GTSL::Extent2D> GetResizeHandle() const { return resizeHandle; } GTSL::Range<byte*> GetBufferRange(BufferHandle buffer_handle) const { const auto& buffer = buffers[buffer_handle()]; return { buffer.Size, (byte*)buffer.Allocation.Data }; } MAKE_HANDLE(uint32, CommandList); MAKE_HANDLE(uint32, Workload); MAKE_HANDLE(uint32, AccelerationStructure); MAKE_HANDLE(uint32, BLASInstance); struct WorkloadData { GTSL::StaticVector<CommandListHandle, 16> AssociatedCommandlists; Synchronizer Fence, Semaphore; GAL::PipelineStage PipelineStages; }; GTSL::FixedVector<WorkloadData, BE::PAR> workloads; WorkloadHandle CreateWorkload(GTSL::StringView name, GAL::QueueType type, GAL::PipelineStage pipeline_stages) { uint32 index = workloads.Emplace(); auto& workload = workloads[index]; workload.Fence.Initialize(GetRenderDevice(), name, Synchronizer::Type::FENCE); workload.Semaphore.Initialize(GetRenderDevice(), name, Synchronizer::Type::SEMAPHORE); workload.PipelineStages = pipeline_stages; return WorkloadHandle(index); } CommandListHandle CreateCommandList(const GTSL::StringView name, GAL::QueueType type, GAL::PipelineStage pipeline_stages, bool isSingleFrame = true) { uint32 index = commandLists.GetLength(); auto& commandList = commandLists.EmplaceBack(GetPersistentAllocator()); //commandList.Fence.Initialize(GetRenderDevice(), true); commandList.Semaphore.Initialize(GetRenderDevice(), name, GAL::VulkanSynchronizer::Type::SEMAPHORE); commandList.Fence.Initialize(GetRenderDevice(), name, GAL::VulkanSynchronizer::Type::FENCE); commandList.Operations = type; commandList.PipelineStages = pipeline_stages; if (type & GAL::QueueTypes::GRAPHICS) { commandList.CommandList.Initialize(GetRenderDevice(), name, graphicsQueue.GetQueueKey(), !isSingleFrame); } if (type & GAL::QueueTypes::COMPUTE) { commandList.CommandList.Initialize(GetRenderDevice(), name, computeQueue.GetQueueKey(), !isSingleFrame); } if (type & GAL::QueueTypes::TRANSFER) { commandList.CommandList.Initialize(GetRenderDevice(), name, transferQueue.GetQueueKey(), !isSingleFrame); } return CommandListHandle(index); } void StartCommandList(const CommandListHandle command_list_handle) { auto& commandListData = commandLists[command_list_handle()]; if(commandListData.Fence.State()) { commandListData.Fence.Wait(GetRenderDevice()); commandListData.Fence.Reset(GetRenderDevice()); } commandListData.CommandList.BeginRecording(GetRenderDevice()); { GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> barriers(commandListData.bufferCopyDatas.GetLength(), GetTransientAllocator()); for (auto& e : commandListData.bufferCopyDatas) { commandListData.CommandList.CopyBuffer(GetRenderDevice(), buffers[e.SourceBufferHandle()].Buffer, e.SourceOffset, buffers[e.DestinationBufferHandle()].Buffer, e.DestinationOffset, buffers[e.SourceBufferHandle()].Size); //auto& barrier = barriers.EmplaceBack(GAL::PipelineStages::TRANSFER, GAL::PipelineStages::ACCELERATION_STRUCTURE_BUILD, GAL::AccessTypes::WRITE, GAL::AccessTypes::READ, CommandList::BufferBarrier{ &buffer.Buffer, buffer.Size }); } commandListData.CommandList.AddPipelineBarrier(GetRenderDevice(), barriers, GetTransientAllocator()); commandListData.bufferCopyDatas.Resize(0); } if (auto& textureCopyData = commandListData.textureCopyDatas; textureCopyData) { GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> sourceTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator()); GTSL::Vector<CommandList::BarrierData, BE::TransientAllocatorReference> destinationTextureBarriers(textureCopyData.GetLength(), GetTransientAllocator()); for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) { sourceTextureBarriers.EmplaceBack(GAL::PipelineStages::TRANSFER, commandListData.PipelineStages, GAL::AccessTypes::READ, GAL::AccessTypes::WRITE, CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::UNDEFINED, GAL::TextureLayout::TRANSFER_DESTINATION, textureCopyData[i].Format }); destinationTextureBarriers.EmplaceBack(GAL::PipelineStages::TRANSFER, commandListData.PipelineStages, GAL::AccessTypes::WRITE, GAL::AccessTypes::READ, CommandList::TextureBarrier{ &textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, GAL::TextureLayout::SHADER_READ, textureCopyData[i].Format }); } commandListData.CommandList.AddPipelineBarrier(GetRenderDevice(), sourceTextureBarriers, GetTransientAllocator()); for (uint32 i = 0; i < textureCopyData.GetLength(); ++i) { commandListData.CommandList.CopyBufferToTexture(GetRenderDevice(), textureCopyData[i].SourceBuffer, textureCopyData[i].DestinationTexture, GAL::TextureLayout::TRANSFER_DESTINATION, textureCopyData[i].Format, textureCopyData[i].Extent); } commandListData.CommandList.AddPipelineBarrier(GetRenderDevice(), destinationTextureBarriers, GetTransientAllocator()); } commandListData.textureCopyDatas.Resize(0); } void DispatchBuild(const CommandListHandle command_list_handle, const GTSL::Range<const AccelerationStructureHandle*> handles) { if(!handles.ElementCount()) { return; } auto& commandListData = commandLists[command_list_handle()]; GTSL::StaticVector<GAL::AccelerationStructureBuildInfo, 8> build_datas; GTSL::StaticVector<GAL::Geometry, 8> geometries; for (auto handle : handles) { auto& buildData = build_datas.EmplaceBack(); if (accelerationStructures[handle()].isTop) { const auto& as = accelerationStructures[handle()]; auto& tlas = accelerationStructures[handle()].TopLevel; buildData.DestinationAccelerationStructure = tlas.AccelerationStructures[GetCurrentFrame()]; buildData.ScratchBufferAddress = GetBufferAddress(as.ScratchBuffer); //GTSL::Skim(tlas.PendingUpdates, [&](decltype(tlas.PendingUpdates)::value_type& e) { bool val; e.Second.Get(GetCurrentFrame(), val); if (val) { GTSL::MemCopy(64ull, GetBufferPointer(tlas.InstancesBuffer, uint8(GetCurrentFrame() - uint8(1)) % GetPipelinedFrames()) + e.First * 64, GetBufferPointer(tlas.InstancesBuffer, GetCurrentFrame()) + e.First * 64); return true; } return false; }); //GTSL::MemCopy(64ull * as.PrimitiveCount, GetBufferPointer(tlas.InstancesBuffer, GetCurrentFrame()), GetBufferPointer(tlas.InstancesBuffer, uint8(GetCurrentFrame() - uint8(1)) % GetPipelinedFrames())); //geometries.EmplaceBack(GAL::GeometryInstances{ GetBufferAddress(tlas.InstancesBuffer) }, GAL::GeometryFlag(), as.PrimitiveCount, 0); buildData.Geometries = geometries; } else { const auto& as = accelerationStructures[handle()]; const auto& blas = accelerationStructures[handle()].BottomLevel; buildData.DestinationAccelerationStructure = blas.AccelerationStructure; //buildData.ScratchBufferAddress = GetBufferAddress(as.ScratchBuffer); geometries.EmplaceBack(GAL::Geometry{ GAL::GeometryTriangles{ GAL::ShaderDataType::FLOAT3, GAL::IndexType::UINT16, static_cast<uint8>(blas.VertexSize), GetBufferAddress(blas.VertexBuffer) + blas.VertexByteOffset, GetBufferAddress(blas.IndexBuffer) + blas.IndexBufferByteOffset, 0, blas.VertexCount }, GAL::GeometryFlags::OPAQUE, as.PrimitiveCount, 0 }); buildData.Geometries = geometries; } } switch (accelerationStructureBuildDevice) { case GAL::Device::CPU: break; case GAL::Device::GPU: case GAL::Device::GPU_OR_CPU: { commandListData.CommandList.BuildAccelerationStructure(GetRenderDevice(), build_datas, GetTransientAllocator()); break; } default:; } GTSL::StaticVector<CommandList::BarrierData, 1> barriers; barriers.EmplaceBack(GAL::PipelineStages::ACCELERATION_STRUCTURE_BUILD, GAL::PipelineStages::RAY_TRACING, GAL::AccessTypes::WRITE, GAL::AccessTypes::READ, CommandList::MemoryBarrier{}); commandListData.CommandList.AddPipelineBarrier(GetRenderDevice(), barriers, GetTransientAllocator()); } void StagingCopy(const CommandListHandle command_list, const BufferHandle handle) { commandLists[command_list()].CommandList.CopyBuffer(GetRenderDevice(), buffers[handle()].Buffer, buffers[handle()].Buffer, buffers[handle()].Size); } void EndCommandList(const CommandListHandle command_list_handle) { auto& commandListData = commandLists[command_list_handle()]; commandListData.CommandList.EndRecording(GetRenderDevice()); } void Wait(WorkloadHandle workload_handle) { auto& workloadData = workloads[workload_handle()]; if (workloadData.Fence.State()) { workloadData.Fence.Wait(GetRenderDevice()); workloadData.Fence.Reset(GetRenderDevice()); } } struct WorkUnit { GTSL::Range<const CommandListHandle*> CommandListHandles; GTSL::Range<const WorkloadHandle*> WaitWorkloadHandles, SignalWorkloadHandles; }; void Submit(const GAL::QueueType queue_type, const GTSL::Range<const WorkUnit*> work_units, const WorkloadHandle workload_handle) { GTSL::StaticVector<Queue::WorkUnit<Synchronizer>, 8> workUnits; GTSL::StaticVector<GTSL::StaticVector<const GAL::CommandList*, 8>, 4> command_listses; GTSL::StaticVector<GTSL::StaticVector<Queue::WorkUnit<Synchronizer>::SynchronizerOperationInfo, 8>, 4> waitOperations, signalOperations; for (uint32 wui = 0; wui < work_units.ElementCount(); ++wui) { auto& wu = work_units[wui]; auto& workUnit = workUnits.EmplaceBack(); auto& cl = command_listses.EmplaceBack(); auto& wo = waitOperations.EmplaceBack(); auto& so = signalOperations.EmplaceBack(); for(auto& e : wu.WaitWorkloadHandles) { auto& workload = workloads[e()]; wo.EmplaceBack(&workload.Semaphore, workload.PipelineStages); } for (auto& e : wu.SignalWorkloadHandles) { auto& workload = workloads[e()]; so.EmplaceBack(&workload.Semaphore, workload.PipelineStages); } for (auto& e : wu.CommandListHandles) { auto& c = commandLists[e()]; cl.EmplaceBack(&c.CommandList); } workUnit.CommandLists = cl; workUnit.Signal = so; workUnit.Wait = wo; } auto& workload = workloads[workload_handle()]; if (queue_type & GAL::QueueTypes::GRAPHICS) { graphicsQueue.Submit(GetRenderDevice(), workUnits, workload.Fence); } if (queue_type & GAL::QueueTypes::COMPUTE) { computeQueue.Submit(GetRenderDevice(), workUnits, workload.Fence); } if(queue_type & GAL::QueueTypes::TRANSFER) { transferQueue.Submit(GetRenderDevice(), workUnits, workload.Fence); } } void Present(WindowSystem* window_system, const GTSL::Range<const WorkloadHandle*> wait_workload_handles) { GTSL::StaticVector<Synchronizer*, 8> waitSemaphores; for(auto e : wait_workload_handles) { waitSemaphores.EmplaceBack(&workloads[e()].Semaphore); } if (surface.GetHandle()) { if (!renderContext.Present(GetRenderDevice(), waitSemaphores, imageIndex, graphicsQueue)) { resize(window_system); } } } void AllocateLocalTextureMemory(Texture* texture, const GTSL::StringView name, GAL::TextureUse uses, GAL::FormatDescriptor format, GTSL::Extent3D extent, GAL::Tiling tiling, GTSL::uint8 mipLevels, RenderAllocation* allocation) { GAL::MemoryRequirements memoryRequirements; texture->GetMemoryRequirements(GetRenderDevice(), &memoryRequirements, uses, format, extent, tiling, mipLevels); DeviceMemory memory; uint32 offset = 0; testMutex.Lock(); localMemoryAllocator.AllocateNonLinearMemory(renderDevice, &memory, allocation, memoryRequirements.Size, &offset); testMutex.Unlock(); texture->Initialize(GetRenderDevice(), name, memory, offset); } void DeallocateLocalTextureMemory(const RenderAllocation allocation) { localMemoryAllocator.DeallocateNonLinearMemory(renderDevice, allocation); } void AllocateScratchBufferMemory(uint32 size, GAL::BufferUse flags, GPUBuffer* buffer, RenderAllocation* allocation) { GAL::MemoryRequirements memoryRequirements; buffer->GetMemoryRequirements(GetRenderDevice(), size, flags, &memoryRequirements); DeviceMemory memory; uint32 offset = 0; testMutex.Lock(); scratchMemoryAllocator.AllocateLinearMemory(renderDevice, &memory, allocation, memoryRequirements.Size, &offset); testMutex.Unlock(); buffer->Initialize(GetRenderDevice(), memoryRequirements, memory, offset); } void DeallocateScratchBufferMemory(const RenderAllocation allocation) { scratchMemoryAllocator.DeallocateLinearMemory(renderDevice, allocation); } void AllocateLocalBufferMemory(uint32 size, GAL::BufferUse flags, GPUBuffer* buffer, RenderAllocation* allocation) { GAL::MemoryRequirements memoryRequirements; buffer->GetMemoryRequirements(GetRenderDevice(), size, flags, &memoryRequirements); DeviceMemory memory; uint32 offset = 0; testMutex.Lock(); localMemoryAllocator.AllocateLinearMemory(renderDevice, &memory, allocation, memoryRequirements.Size, &offset); testMutex.Unlock(); buffer->Initialize(GetRenderDevice(), memoryRequirements, memory, offset); } void DeallocateLocalBufferMemory(const RenderAllocation renderAllocation) { localMemoryAllocator.DeallocateLinearMemory(renderDevice, renderAllocation); } RenderDevice* GetRenderDevice() { return &renderDevice; } const RenderDevice* GetRenderDevice() const { return &renderDevice; } GPUBuffer GetBuffer(const RenderSystem::BufferHandle buffer_handle) const { return buffers[buffer_handle()].Buffer; //TODO: is multi } //CommandList* GetTransferCommandBuffer() { return &transferCommandBuffers[currentFrameIndex]; } void AddBufferUpdate(CommandListHandle command_list_handle, const BufferHandle source_buffer_handle, const BufferHandle destination_buffer_handle, uint32 source_offset = 0, uint32 destination_offset = 0) { auto& commandList = commandLists[command_list_handle()]; if(needsStagingBuffer) commandList.bufferCopyDatas.EmplaceBack(source_buffer_handle, destination_buffer_handle, source_offset, destination_offset); } struct TextureCopyData { GPUBuffer SourceBuffer; Texture DestinationTexture; uint32 SourceOffset = 0; RenderAllocation Allocation; GTSL::Extent3D Extent; GAL::TextureLayout Layout; GAL::FormatDescriptor Format; }; void AddTextureCopy(CommandListHandle command_list_handle, const TextureCopyData& textureCopyData) { BE_ASSERT(testMutex.TryLock()); auto& commandList = commandLists[command_list_handle()]; commandList.textureCopyDatas.EmplaceBack(textureCopyData); testMutex.Unlock(); } [[nodiscard]] PipelineCache GetPipelineCache() const; [[nodiscard]] const Texture* GetSwapchainTexture() const { return &swapchainTextures[imageIndex]; } [[nodiscard]] byte* GetBufferPointer(BufferHandle bufferHandle) const { return static_cast<byte*>(buffers[bufferHandle()].Allocation.Data); } [[nodiscard]] GAL::DeviceAddress GetBufferAddress(BufferHandle bufferHandle) const { return buffers[bufferHandle()].Addresses; } //void UpdateBuffer(const CommandListHandle command_list_handle, const BufferHandle buffer_handle) { // auto& buffer = buffers[buffer_handle()]; // // ++buffer.references; // // AddBufferUpdate(command_list_handle, buffer_handle); //} void DestroyBuffer(const BufferHandle handle) { --buffers[handle()].references; } CommandList* GetCommandList(const CommandListHandle handle) { return &commandLists[handle()].CommandList; } const CommandList* GetCommandList(const CommandListHandle handle) const { return &commandLists[handle()].CommandList; } [[nodiscard]] GTSL::Extent2D GetRenderExtent() const { return renderArea; } void onResize(TaskInfo, GTSL::Extent2D extent) { renderArea = extent; } uint32 GetShaderGroupHandleSize() const { return shaderGroupHandleSize; } uint32 GetShaderGroupBaseAlignment() const { return shaderGroupBaseAlignment; } uint32 GetShaderGroupHandleAlignment() const { return shaderGroupHandleAlignment; } AccelerationStructure GetTopLevelAccelerationStructure(AccelerationStructureHandle topLevelAccelerationStructureIndex, uint8 frame) const { return accelerationStructures[topLevelAccelerationStructureIndex()].TopLevel.AccelerationStructures[frame]; } GAL::DeviceAddress GetTopLevelAccelerationStructureAddress(AccelerationStructureHandle topLevelAccelerationStructureIndex, uint8 frame) const { return accelerationStructures[topLevelAccelerationStructureIndex()].TopLevel.AccelerationStructures[frame].GetAddress(GetRenderDevice()); } uint32 GetBufferSubDataAlignment() const { return renderDevice.GetStorageBufferBindingOffsetAlignment(); } [[nodiscard]] TextureHandle CreateTexture(GTSL::Range<const char8_t*> name, GAL::FormatDescriptor formatDescriptor, GTSL::Extent3D extent, GAL::TextureUse textureUses, bool updatable, TextureHandle texture_handle = TextureHandle()); void UpdateTexture(const CommandListHandle command_list_handle, const TextureHandle textureHandle); //TODO: SELECT DATA POINTER BASED ON STAGING BUFFER NECESSITY GTSL::Range<byte*> GetTextureRange(TextureHandle textureHandle) { const auto& texture = textures[textureHandle()]; uint32 size = texture.Extent.Width * texture.Extent.Depth * texture.Extent.Height; size *= texture.FormatDescriptor.GetSize(); return GTSL::Range<byte*>(size, static_cast<byte*>(texture.ScratchAllocation.Data)); } GTSL::Range<const byte*> GetTextureRange(TextureHandle textureHandle) const { const auto& texture = textures[textureHandle()]; uint32 size = texture.Extent.Width * texture.Extent.Depth * texture.Extent.Height; size *= texture.FormatDescriptor.GetSize(); return GTSL::Range(size, static_cast<const byte*>(texture.ScratchAllocation.Data)); } const Texture* GetTexture(const TextureHandle textureHandle) const { return &textures[textureHandle()].Texture; } const TextureView* GetTextureView(const TextureHandle textureHandle) const { return &textures[textureHandle()].TextureView; } void OnRenderEnable(TaskInfo taskInfo, bool oldFocus); void OnRenderDisable(TaskInfo taskInfo, bool oldFocus); GTSL::Result<GTSL::Extent2D> AcquireImage(const WorkloadHandle workload_handle, WindowSystem* window_system); BufferHandle CreateBuffer(uint32 size, GAL::BufferUse flags, bool willWriteFromHost, const BufferHandle buffer_handle); AccelerationStructureHandle CreateTopLevelAccelerationStructure(uint32 estimatedMaxInstances) { uint32 tlasi = accelerationStructures.Emplace(true); auto& as = accelerationStructures[tlasi]; auto& t = accelerationStructures[tlasi].TopLevel; GAL::Geometry geometry(GAL::GeometryInstances(), GAL::GeometryFlag(), estimatedMaxInstances, 0); uint32 size; t.AccelerationStructures[0].GetMemoryRequirements(GetRenderDevice(), GTSL::Range(1, &geometry), accelerationStructureBuildDevice, GAL::AccelerationStructureFlags::PREFER_FAST_TRACE, &size, &as.ScratchSize); for (uint8 f = 0; f < pipelinedFrames; ++f) { AllocateLocalBufferMemory(size, GAL::BufferUses::ACCELERATION_STRUCTURE, &t.AccelerationStructureBuffer[f], &t.AccelerationStructureAllocation[f]); t.AccelerationStructures[f].Initialize(&renderDevice, true, t.AccelerationStructureBuffer[f], size, 0); } //t.InstancesBuffer = CreateBuffer(64 * estimatedMaxInstances, GAL::BufferUses::BUILD_INPUT_READ, true, true, t.InstancesBuffer); //as.ScratchBuffer = CreateBuffer(1024 * 1204, GAL::BufferUses::BUILD_INPUT_READ | GAL::BufferUses::STORAGE, false, true, as.ScratchBuffer); return AccelerationStructureHandle{ tlasi }; } AccelerationStructureHandle CreateBottomLevelAccelerationStructure(uint32 vertexCount, uint32 vertexSize, uint32 indexCount, GAL::IndexType indexType, BufferHandle vertex_buffer_handle, BufferHandle index_buffer_handle, uint32 vertex_buffer_byte_offset = 0, uint32 index_buffer_byte_offset = 0, bool willUpdate = false, bool willRebuild = false, bool isOpaque = true) { uint32 blasi = accelerationStructures.Emplace(false); auto& as = accelerationStructures[blasi]; auto& blas = accelerationStructures[blasi].BottomLevel; blas.VertexCount = vertexCount; blas.VertexSize = vertexSize; blas.VertexBuffer = vertex_buffer_handle; blas.IndexBuffer = index_buffer_handle; as.PrimitiveCount = indexCount / 3; blas.VertexByteOffset = vertex_buffer_byte_offset; blas.IndexBufferByteOffset = index_buffer_byte_offset; GAL::GeometryTriangles geometryTriangles; //todo: add buffer references, so it can't be deleted while blas build consumes it geometryTriangles.IndexType = indexType; geometryTriangles.VertexPositionFormat = GAL::ShaderDataType::FLOAT3; geometryTriangles.MaxVertices = vertexCount; geometryTriangles.VertexData = GAL::DeviceAddress(); geometryTriangles.IndexData = GAL::DeviceAddress(); geometryTriangles.VertexStride = vertexSize; geometryTriangles.FirstVertex = 0; GAL::GeometryFlag geometry_flags; geometry_flags |= isOpaque ? GAL::GeometryFlags::OPAQUE : 0; GAL::Geometry geometry(geometryTriangles, geometry_flags, indexCount / 3, 0); GAL::AccelerationStructureFlag acceleration_structure_flag; acceleration_structure_flag |= !willRebuild ? GAL::AccelerationStructureFlags::ALLOW_COMPACTION : 0; acceleration_structure_flag |= !willUpdate ? GAL::AccelerationStructureFlags::ALLOW_COMPACTION : 0; acceleration_structure_flag |= willUpdate or willRebuild ? GAL::AccelerationStructureFlags::PREFER_FAST_BUILD : 0; acceleration_structure_flag |= willUpdate ? GAL::AccelerationStructureFlags::ALLOW_UPDATE : 0; acceleration_structure_flag |= !willUpdate and !willRebuild ? GAL::AccelerationStructureFlags::PREFER_FAST_TRACE : 0; uint32 bufferSize; blas.AccelerationStructure.GetMemoryRequirements(GetRenderDevice(), GTSL::Range(1, &geometry), GAL::Device::GPU, acceleration_structure_flag, &bufferSize, &as.ScratchSize); AllocateLocalBufferMemory(bufferSize, GAL::BufferUses::ACCELERATION_STRUCTURE, &blas.AccelerationStructureBuffer, &blas.AccelerationStructureAllocation); blas.AccelerationStructure.Initialize(GetRenderDevice(), false, blas.AccelerationStructureBuffer, bufferSize, 0); as.ScratchBuffer = CreateBuffer(1024 * 1204, GAL::BufferUses::BUILD_INPUT_READ | GAL::BufferUses::STORAGE, true, as.ScratchBuffer); return AccelerationStructureHandle{ blasi }; } uint32 CreateAABB(const GTSL::Matrix4& position, const GTSL::Vector3 size) { //auto volume = CreateBuffer(sizeof(float32) * 6, GAL::BufferUses::BUILD_INPUT_READ, true, false); //auto bufferDeviceAddress = GetBufferAddress(volume); //auto bufferPointer = GetBufferPointer(volume); // //*(reinterpret_cast<GTSL::Vector3*>(bufferPointer) + 0) = -size; //*(reinterpret_cast<GTSL::Vector3*>(bufferPointer) + 1) = size; //addRayTracingInstance(GAL::Geometry(GAL::GeometryAABB(bufferDeviceAddress, sizeof(float32) * 6), {}, 1, 0), AccelerationStructureBuildData{ 0, {}, {} }); return 0; } BLASInstanceHandle AddBLASToTLAS(const AccelerationStructureHandle tlash, const AccelerationStructureHandle blash, uint32 instance_custom_index, BLASInstanceHandle instance_handle) { auto& tlas = accelerationStructures[tlash()].TopLevel; uint32 instanceIndex = 0; if (instance_handle) { instanceIndex = instance_handle(); } else { if (tlas.freeSlots) { instanceIndex = tlas.freeSlots.back(); } else { instanceIndex = accelerationStructures[tlash()].PrimitiveCount++; //TODO: check need resize } } if (blash) { const auto& blas = accelerationStructures[blash()].BottomLevel; GAL::WriteInstance(blas.AccelerationStructure, instanceIndex, GAL::GeometryFlags::OPAQUE, GetRenderDevice(), GetBufferPointer(tlas.InstancesBuffer), instance_custom_index, accelerationStructureBuildDevice); } auto& r = tlas.PendingUpdates.EmplaceBack(); //bug: only works if we update acc. str. every frame r.First = instanceIndex; r.Second.Set((GetCurrentFrame() + 1) % GetPipelinedFrames(), true); return BLASInstanceHandle(instanceIndex); } #define BE_LOG_IF(cond, text) if(cond) { BE_LOG_WARNING(text); return; } void SetInstancePosition(AccelerationStructureHandle topLevel, BLASInstanceHandle instance_handle, const GTSL::Matrix3x4& matrix4) { BE_LOG_IF(!static_cast<bool>(instance_handle), u8"TlAS instance handle is invalid."); GAL::WriteInstanceMatrix(matrix4, GetBufferPointer(accelerationStructures[topLevel()].TopLevel.InstancesBuffer), instance_handle()); } void SetAccelerationStructureInstanceIndex(AccelerationStructureHandle topLevel, BLASInstanceHandle instance_handle, uint32 custom_index) { GAL::WriteInstanceIndex(custom_index, GetBufferPointer(accelerationStructures[topLevel()].TopLevel.InstancesBuffer), instance_handle()); } void SetInstanceBindingTableRecordOffset(AccelerationStructureHandle topLevel, BLASInstanceHandle instance_handle, const uint32 offset) { BE_LOG_IF(instance_handle, u8"TlAS instance handle is invalid."); GAL::WriteInstanceBindingTableRecordOffset(offset, GetBufferPointer(accelerationStructures[topLevel()].TopLevel.InstancesBuffer), instance_handle()); } private: GTSL::Mutex testMutex; bool needsStagingBuffer = true; uint8 imageIndex = 0; uint8 pipelinedFrames = 0; bool useHDR = false; RenderDevice renderDevice; Surface surface; RenderContext renderContext; GTSL::Extent2D renderArea, lastRenderArea; struct BufferCopyData { BufferHandle SourceBufferHandle, DestinationBufferHandle; uint32 SourceOffset = 0, DestinationOffset = 0; }; uint32 processedBufferCopies[MAX_CONCURRENT_FRAMES]; Texture swapchainTextures[MAX_CONCURRENT_FRAMES]; TextureView swapchainTextureViews[MAX_CONCURRENT_FRAMES]; GAL::VulkanQueue graphicsQueue, computeQueue, transferQueue; bool breakOnError = false; TaskHandle<GTSL::Extent2D> resizeHandle; struct BufferData { uint32 Size = 0, Counter = 0; GAL::BufferUse Flags; uint32 references = 0; GPUBuffer Buffer; RenderAllocation Allocation; GAL::DeviceAddress Addresses; }; GTSL::FixedVector<BufferData, BE::PAR> buffers; struct AccelerationStructureData { bool isTop = false; GTSL::uint32 PrimitiveCount = 0; BufferHandle ScratchBuffer; uint32 ScratchSize; struct TopLevelAccelerationStructure { AccelerationStructure AccelerationStructures[MAX_CONCURRENT_FRAMES]; RenderAllocation AccelerationStructureAllocation[MAX_CONCURRENT_FRAMES]; GPUBuffer AccelerationStructureBuffer[MAX_CONCURRENT_FRAMES]; BufferHandle InstancesBuffer; GTSL::StaticVector<uint32, 8> freeSlots; GTSL::StaticVector<GTSL::Pair<uint32, GTSL::Bitfield<MAX_CONCURRENT_FRAMES>>, 8> PendingUpdates; }; struct BottomLevelAccelerationStructure { GPUBuffer AccelerationStructureBuffer; RenderAllocation AccelerationStructureAllocation; AccelerationStructure AccelerationStructure; BufferHandle VertexBuffer, IndexBuffer; GTSL::uint32 VertexCount, VertexSize; uint32 VertexByteOffset, IndexBufferByteOffset; }; union { TopLevelAccelerationStructure TopLevel; BottomLevelAccelerationStructure BottomLevel; }; AccelerationStructureData(bool isTopLevel) : isTop(isTopLevel) { if (isTop) { ::new(&TopLevel) TopLevelAccelerationStructure(); } else { ::new(&BottomLevel) BottomLevelAccelerationStructure(); } } AccelerationStructureData(AccelerationStructureData&& other) : isTop(other.isTop), PrimitiveCount(other.PrimitiveCount) { if(isTop) { GTSL::Move(&other.TopLevel, &TopLevel); } else { GTSL::Move(&other.BottomLevel, &BottomLevel); } } ~AccelerationStructureData() { if(isTop) { GTSL::Destroy(TopLevel); } else { GTSL::Destroy(BottomLevel); } } }; GTSL::FixedVector<AccelerationStructureData, BE::PAR> accelerationStructures; struct CommandListData { CommandListData(const BE::PAR& allocator) : bufferCopyDatas(allocator), textureCopyDatas(allocator) {} CommandList CommandList; //Fence Fence; Synchronizer Semaphore, Fence; GAL::QueueType Operations; GAL::PipelineStage PipelineStages; GTSL::Vector<BufferCopyData, BE::PersistentAllocatorReference> bufferCopyDatas; GTSL::Vector<TextureCopyData, BE::PersistentAllocatorReference> textureCopyDatas; }; GTSL::StaticVector<CommandListData, 8> commandLists; GAL::Device accelerationStructureBuildDevice; uint8 currentFrameIndex = 0; GAL::PresentModes swapchainPresentMode; GAL::FormatDescriptor swapchainFormat; GAL::ColorSpaces swapchainColorSpace; void resize(WindowSystem* window_system); void renderFlush(TaskInfo taskInfo); void printError(const GTSL::StringView message, RenderDevice::MessageSeverity messageSeverity) const; void* allocateApiMemory(void* data, uint64 size, uint64 alignment); void* reallocateApiMemory(void* data, void* allocation, uint64 size, uint64 alignment); void deallocateApiMemory(void* data, void* allocation); //GTSL::StaticMap<uint64, GTSL::StaticVector<GAL::ShaderDataType, 8>, 8> vertexFormats; GTSL::Mutex allocationsMutex; GTSL::HashMap<uint64, GTSL::Pair<uint64, uint64>, BE::PersistentAllocatorReference> apiAllocations; ScratchMemoryAllocator scratchMemoryAllocator; LocalMemoryAllocator localMemoryAllocator; GTSL::StaticVector<PipelineCache, 32> pipelineCaches; uint32 shaderGroupHandleAlignment = 0, shaderGroupBaseAlignment = 0, shaderGroupHandleSize = 0; uint32 scratchBufferOffsetAlignment = 0; struct TextureComponent { Texture Texture; TextureView TextureView; RenderAllocation Allocation, ScratchAllocation; GAL::FormatDescriptor FormatDescriptor; GAL::TextureUse Uses; GPUBuffer ScratchBuffer; GAL::TextureLayout Layout; GTSL::Extent3D Extent; }; GTSL::FixedVector<TextureComponent, BE::PersistentAllocatorReference> textures; void initializeFrameResources(const uint8 frameIndex); void freeFrameResources(const uint8 frameIndex); }; class RenderManager : public BE::System { public: RenderManager(const InitializeInfo& initializeInfo, const char8_t* name) : System(initializeInfo, name) {} struct SetupInfo { ApplicationManager* GameInstance; RenderSystem* RenderSystem; //RenderState* RenderState; GTSL::Matrix4 ViewMatrix, ProjectionMatrix; }; };
43.706799
392
0.782254
[ "geometry", "vector" ]
c1a521a98feb82ba7a17e5794703796c8aca5686
1,726
h
C
plugins/robots/interpreters/trikKitInterpreterCommon/include/trikKitInterpreterCommon/trikEmulation/trikkeysinterfacestub.h
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
39
2015-01-26T16:18:43.000Z
2021-12-20T23:36:41.000Z
plugins/robots/interpreters/trikKitInterpreterCommon/include/trikKitInterpreterCommon/trikEmulation/trikkeysinterfacestub.h
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
156
2015-02-06T16:48:19.000Z
2019-03-04T23:09:27.000Z
plugins/robots/interpreters/trikKitInterpreterCommon/include/trikKitInterpreterCommon/trikEmulation/trikkeysinterfacestub.h
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
58
2015-03-03T12:57:28.000Z
2020-05-09T15:54:42.000Z
/* Copyright 2016-2017 CyberTech Labs 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. */ #pragma once #include <QtCore/QSharedPointer> #include <QtCore/QScopedPointer> #include <QtCore/QHash> #include <utils/abstractTimer.h> #include <trikControl/keysInterface.h> namespace kitBase { namespace robotModel { class CommonRobotModel; namespace robotParts { class Button; } } } namespace trik { class TrikKeysInterfaceStub : public trikControl::KeysInterface { public: TrikKeysInterfaceStub(const QSharedPointer<kitBase::robotModel::CommonRobotModel> &model); void init(); void start(); void stop(); virtual Status status() const override { return Status::ready; } public slots: virtual void reset() override; virtual bool wasPressed(int code) override; virtual bool isPressed(int code) override; virtual int buttonCode(bool wait) override; private slots: void handleNewData(int value); private: bool registerButton(int code); QHash<int, QString> mKeycodeMap; QHash<int, bool> mWasPressed; QHash<int, kitBase::robotModel::robotParts::Button *> mButtons; QSharedPointer<kitBase::robotModel::CommonRobotModel> mRobotModel; QScopedPointer<utils::AbstractTimer> mButtonWatchingTimer; }; }
25.761194
91
0.765353
[ "model" ]
c1a562f1eae826898c55c46bc14c62c2195c82e3
457
h
C
exestub/exestub.h
alexanders-code/cmdxmlinstaller
a17abda09635566748887aeae1ee047b8bbf134e
[ "BSD-2-Clause" ]
null
null
null
exestub/exestub.h
alexanders-code/cmdxmlinstaller
a17abda09635566748887aeae1ee047b8bbf134e
[ "BSD-2-Clause" ]
null
null
null
exestub/exestub.h
alexanders-code/cmdxmlinstaller
a17abda09635566748887aeae1ee047b8bbf134e
[ "BSD-2-Clause" ]
null
null
null
// ************************************************************************ // exestub.h - v 0.3 // ************************************************************************ #pragma once #ifndef _CMDINST_EXESTUB_H #define _CMDINST_EXESTUB_H #include <vector> #include "..\sfxclasses\DataStruct.h" extern std::vector< DataBlock > datablockarray; extern HeaderSelf hs; extern std::vector< CommandBlock > commandblockarray; #endif //_CMDINST_EXESTUB_H
25.388889
76
0.509847
[ "vector" ]
fcc5dd00e6ff5ffed89b3aa9e6bac2c8d6b22e7c
2,098
h
C
smtk/model/PropertyListPhrase.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/model/PropertyListPhrase.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/model/PropertyListPhrase.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef __smtk_model_PropertyListPhrase_h #define __smtk_model_PropertyListPhrase_h #include "smtk/model/DescriptivePhrase.h" #include "smtk/model/Manager.h" // For PropertyType enum. #include <string> #include <vector> namespace smtk { namespace model { /**\brief Describe a list of property (name,value) pairs * associated with an entity for user presentation. * * This enumerates properties of a single primitive storage * type (e.g. only string properties or only integer properties), * not all of an entity's properties at once. */ class SMTKCORE_EXPORT PropertyListPhrase : public DescriptivePhrase { public: smtkTypeMacro(PropertyListPhrase); smtkSharedPtrCreateMacro(DescriptivePhrase); Ptr setup(const EntityRef& entity, PropertyType ptype, DescriptivePhrasePtr parent); Ptr setup(const EntityRef& entity, PropertyType ptype, const std::set<std::string>& pnames, DescriptivePhrasePtr parent); virtual std::string title(); virtual std::string subtitle(); virtual smtk::common::UUID relatedEntityId() const; virtual EntityRef relatedEntity() const; virtual PropertyType relatedPropertyType() const; std::set<std::string>& propertyNames() { return this->m_propertyNames; } const std::set<std::string>& propertyNames() const { return this->m_propertyNames; } static DescriptivePhraseType propertyToPhraseType(PropertyType p); protected: PropertyListPhrase(); EntityRef m_entity; PropertyType m_propertyType; std::set<std::string> m_propertyNames; // an optional subset of m_entity's properties }; } // model namespace } // smtk namespace #endif // __smtk_model_DescriptivePhrase_h
34.393443
123
0.711153
[ "vector", "model" ]
fcd82bf88886a33fd70167e3c2d863bf8f463164
42,332
c
C
hexagon/src/expand_transpose_conv_nodes.c
supersat/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
14
2019-01-28T12:40:59.000Z
2022-03-09T10:55:05.000Z
hexagon/src/expand_transpose_conv_nodes.c
supersat/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
1
2018-08-10T10:18:56.000Z
2018-08-10T10:18:56.000Z
hexagon/src/expand_transpose_conv_nodes.c
waau/nnlib
049585daa66f0aeff134310d81305286e2aacdff
[ "BSD-3-Clause-Clear" ]
5
2019-02-14T10:34:32.000Z
2022-03-18T07:47:05.000Z
/* * Copyright (c) 2019-2020, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) 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 Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "nn_prepare.h" #include "expand_nodes.h" #include <nn_graph.h> #include <nn_graph_types.h> #include <data_utils.h> struct expand_transpose_conv_info { int32_t pad_op; int32_t shuffle_op; int32_t conv_op; int32_t channel_scale_op; int32_t bias_add_op; int32_t shrink_op; int32_t requant_op; int32_t d2s_op; int32_t elbytes; int32_t elbytes_bias; int32_t allow_num_filter_pad; int32_t has_depthwise_path; }; static const struct expand_transpose_conv_info transpose_conv_8_8_info = { .pad_op = OP_QuantizedPad_8, .shuffle_op = OP_AxisShuffle_8, .conv_op = OP_QuantizedConv2d_8x8to32, .channel_scale_op = OP_QuantizedChannelScale_32xf, .shrink_op = OP_QuantizeDownAndShrinkRange_32to8, .bias_add_op = OP_QuantizedBiasAdd_8p8to32, .requant_op = OP_Requantize_32to8, .d2s_op = OP_DepthToSpace_8, .elbytes = sizeof(uint8_t), .elbytes_bias = sizeof(uint8_t), .allow_num_filter_pad = 1, .has_depthwise_path = 1}; static const struct expand_transpose_conv_info transpose_conv_8_32_info = { .pad_op = OP_QuantizedPad_8, .shuffle_op = OP_AxisShuffle_8, .conv_op = OP_QuantizedConv2d_8x8to32, .channel_scale_op = OP_QuantizedChannelScale_32xf, .bias_add_op = OP_QuantizedBiasAdd_32p32to32, .requant_op = OP_Requantize_32to8, .d2s_op = OP_DepthToSpace_8, .elbytes = sizeof(uint8_t), .elbytes_bias = sizeof(int32_t), .allow_num_filter_pad = 1, .has_depthwise_path = 1}; static const struct expand_transpose_conv_info transpose_conv_16_info = { .pad_op = OP_QuantizedPad_u16, .shuffle_op = OP_AxisShuffle_16, .conv_op = OP_QuantizedConv2d_16x16to32, .channel_scale_op = OP_QuantizedChannelScale_32xf, .bias_add_op = OP_QuantizedBiasAdd_32p32to32, .requant_op = OP_Requantize_32tou16, .d2s_op = OP_DepthToSpace_16, .elbytes = sizeof(uint16_t), .elbytes_bias = sizeof(int32_t), .allow_num_filter_pad = 0, .has_depthwise_path = 0}; /* * In all cases weights are rotated 180 degrees and Conv input is padded by (fh-1,fw-1) * In all cases pad is optional and shrink op only used in 8 bit bias cases. * In all depthwise cases filters are (if needed) padded to height of 2 and width of 3 or 5 or 7. * * Case 1: * No groups and stride=(1,1) * * pad -> conv -> channel_scale -> shrink -> bias_add -> requant * * * Case 2: * No groups and stride>1 * Weights are transformed by space-to-batch by a factor of strides * * pad -> conv -> channel_scale -> shrink -> bias_add -> requant -> depth_to_space * * * Case 3: * Groups and strides=(1,1) * Weights are split on input depth axis * * -> conv -> channel_scale -> shrink -> bias_add -> requant \ * pad -> split -| #groups |-> concat * -> conv -> channel_scale -> shrink -> bias_add -> requant / * * * Case 4: * Groups and strides>1 * Weights are transformed by space-to-batch by a factor of strides * Weights are split on input depth axis * Biasesa and channel scales split along depth * -> conv -> channel_scale -> shrink -> bias_add -> requant -> depth_to_space \ * pad -> split -| #groups |-> concat * -> conv -> channel_scale -> shrink -> bias_add -> requant -> depth_to_space / * * * Case 5: * Normal Depthwise case (in_depth==groups==out_depth) and stride=(1,1) * * pad -> DWconv -> channel_scale -> shrink -> bias_add -> requant * * * Case 6: * Normal Depthwise case (in_depth==groups==out_depth) and stride>1 * Using subkerneling method. Weights are rearranged into 5-dimensional tensor where 5th dim is the # of subkernels. * # of subkernels == stride_h*stride_w. * * -> DWconv -> channel_scale -> shrink -> bias_add -> requant \ * pad -| # stride_w*stride_h |-> concat -> depth_to_space * -> DWconv -> channel_scale -> shrink -> bias_add -> requant / * * * Case 7: * Channel Multiplier Depthwise case (in_depth==2*groups==2*out_depth) and strides=(1,1) * input and weights are reshaped by: * - channel shuffle with k=in_depth/2 * - reshape (b,h,w,d) -> (b,h,w*2,d/2) * DWconv uses stride=(1,2) * * channel_shuffle -> reshape -> pad -> DWconv -> channel_scale -> shrink -> bias_add -> requant * * * Case 8: * Channel Multiplier Depthwise case (in_depth==2*groups==2*out_depth) and strides>1 * Using subkerneling method. Weights are rearranged into 5-dimensional tensor where 5th dim is the # of subkernels. * # of subkernels == stride_h*stride_w. * input and weights are reshaped by: * - channel shuffle with k=in_depth/2 * - reshape (b,h,w,d) -> (b,h,w*2,d/2) * DWconv uses stride=(1,2) * * -> DWconv -> channel_scale -> shrink -> bias_add -> requant \ * channel_shuffle -> reshape -> pad -| # stride_w*stride_h |-> concat -> depth_to_space * -> DWconv -> channel_scale -> shrink -> bias_add -> requant / * */ int expand_transpose_conv_nodes(struct nn_graph *nn, struct nn_node **transpose_conv_node_p) { struct nn_node *transpose_conv_node = *transpose_conv_node_p; int ntyp = transpose_conv_node->node_type; const struct expand_transpose_conv_info *info; struct input const *original_inputs = transpose_conv_node->input_refs; struct nn_node *producer = NULL; struct nn_node *channel_scale_node = NULL; struct nn_node *pad_node = NULL; struct nn_node *split_node = NULL; struct nn_node *reshape_node = NULL; struct nn_node *shuffle_node = NULL; struct shape input_shape; struct shape original_output_shape; struct shape conv_output_shape; struct shape d2s_output_shape; uint32_t src_id = transpose_conv_node->input_refs[0].src_id; uint8_t has_channel_scale = (transpose_conv_node->n_inputs >= 14) ? 1 : 0; uint8_t has_groups = (transpose_conv_node->n_inputs >= 15) ? 1 : 0; uint32_t groups = 1; uint32_t use_depthwise = 0; uint32_t use_subkerneling = 0; uint32_t need_reshape = 0; uint32_t num_subkernels = 0; uint32_t pad_num_filters = 0; uint32_t chmul = 1; // channel multipler uint32_t qzero = 0; uint8_t bias_qzero8 = 0; int32_t group_depth; // output depth of the conv for a group int32_t d2s_output_depth; // output depth after d2s operation if (ntyp == OP_QuantizedTransposeConv2d_8x8p8to8) { info = &transpose_conv_8_8_info; } else if (ntyp == OP_QuantizedTransposeConv2d_8x8p32to8) { info = &transpose_conv_8_32_info; } else if (ntyp == OP_QuantizedTransposeConv2d_16x16p32to16) { info = &transpose_conv_16_info; } else { return errlog(nn, "Unsupported transpose conv2d data type"); } int32_t conv_op = info->conv_op; if ((producer = find_node(nn, src_id)) == NULL) return errlog(nn, "src id not found transpose conv stuff"); struct nn_node *weight_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[1].src_id); struct nn_node *weight_min_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[4].src_id); struct nn_node *weight_max_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[5].src_id); struct nn_node *paddings_arr_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[6].src_id); struct nn_node *strides_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[7].src_id); struct nn_node *bias_data_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[8].src_id); struct nn_node *bias_min_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[9].src_id); struct nn_node *bias_max_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[10].src_id); if (has_channel_scale) { if (NULL == (channel_scale_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[13].src_id))) { return errlog(nn, "Error QuantizedTransposeConv2d node_id=%x: Unable to find const channel scale node!", transpose_conv_node->node_id); } } if (has_groups) { struct nn_node *group_node; if (NULL == (group_node = find_node_must_be_Const(nn, transpose_conv_node->input_refs[14].src_id))) { return errlog(nn, "Error QuantizedTransposeConv2d node_id=%x: Unable to find const groups node!", transpose_conv_node->node_id); } groups = tensor_get_int32(group_node->outputs[0], 0); } input_shape = producer->outputs[transpose_conv_node->input_refs[0].output_idx]->shape; int32_t *paddings_arr = paddings_arr_node->outputs[0]->data; uint8_t *bias_data = bias_data_node->outputs[0]->data; uint32_t stride_h = strides_node->outputs[0]->shape.height; uint32_t stride_w = strides_node->outputs[0]->shape.width; uint32_t num_filters = weight_node->outputs[0]->shape.batches; uint32_t filt_height = weight_node->outputs[0]->shape.height; uint32_t filt_width = weight_node->outputs[0]->shape.width; uint32_t filt_depth = weight_node->outputs[0]->shape.depth; float weight_min = tensor_get_float(weight_min_node->outputs[0], 0); float weight_max = tensor_get_float(weight_max_node->outputs[0], 0); float bias_min = tensor_get_float(bias_min_node->outputs[0], 0); float bias_max = tensor_get_float(bias_max_node->outputs[0], 0); if (stride_h < 1 || stride_w < 1) return errlog(nn, "Bad strides %d %d for transpose conv node", stride_h, stride_w); uint32_t stride_wxh = stride_w * stride_h; uint32_t padded_filt_height = roundup(filt_height, stride_h); uint32_t padded_filt_width = roundup(filt_width, stride_w); uint32_t padded_filt_depth = roundup(filt_depth, groups); uint32_t depth_padding = padded_filt_depth - filt_depth; pad_num_filters = ((1 < stride_w && stride_w < 5) || stride_w == 8) ? 1 : 0; pad_num_filters = (num_filters < 4 && groups == 1) ? 0 : pad_num_filters; //disable pad num filters if num filters small pad_num_filters &= info->allow_num_filter_pad; uint32_t padded_num_filters = (pad_num_filters) ? roundup(num_filters, 32) : num_filters; // Calculate quantized 0 for use in padding biases & weights if (info->elbytes == sizeof(uint8_t)) { qzero = quantize_uint8(0.0f, weight_min, weight_max); bias_qzero8 = quantize_uint8(0.0f, bias_min, bias_max); } else if (info->elbytes == sizeof(uint16_t)) { qzero = quantize_uint16(0.0f, weight_min, weight_max); } else { return errlog(nn, "Unsupported data type for weights. Cannot find quantized zero"); } shape_from_outdesc(&original_output_shape, &transpose_conv_node->output_defs[0], 0); // regular Depthwise case: (input_depth == groups == output_depth) if(groups > 1 && groups == input_shape.depth && groups == original_output_shape.depth && info->has_depthwise_path) { conv_op = OP_QuantizedDepthwiseConv2d_8x8to32; groups = 1; use_depthwise = 1; pad_num_filters = 0; // Dont pad in depthwise case padded_num_filters = num_filters; padded_filt_depth = filt_depth; depth_padding = 0; if (stride_wxh > 1) { // For the depthwise with striding case we use subkerneling use_subkerneling = 1; num_subkernels = stride_wxh; stride_wxh = 1; // striding will be handled by subkerneling ==> treat strides as 1 } } // Depthwise Channel multiple case (input_depth == 2 * groups == 2 * output_depth) uint32_t depthwise_chmul_filt_width = (filt_width * 2) / stride_w; if (groups > 1 && 2 * groups == input_shape.depth && groups == original_output_shape.depth && info->has_depthwise_path && depthwise_chmul_filt_width < 7 && padded_filt_height / stride_h >= 2) { chmul = 2; // currently only support channel multiplier of 2 because dwconv only supports strides <= 2 // reshape input & weights and use depthwise with DWCONV stride_w == 2 strategy conv_op = OP_QuantizedDepthwiseConv2d_8x8to32; groups = 1; use_depthwise = 1; pad_num_filters = 0; padded_num_filters = num_filters; padded_filt_depth = filt_depth; depth_padding = 0; need_reshape = 1; if (stride_wxh > 1) { // For the depthwise with striding case we use subkerneling use_subkerneling = 1; num_subkernels = stride_wxh; stride_wxh = 1; // striding will be handled by subkerneling ==> treat strides as 1 } } uint32_t iterations = use_subkerneling ? num_subkernels : groups; uint32_t num_core_nodes = (stride_wxh > 1) ? 6 : 5; // extra d2s node if stride_wxh>1 uint32_t num_nodes_to_replace = iterations * num_core_nodes + 5; // 5 extra nodes are: pad, (shuffle & reshape), split, concat and d2s struct nn_node *new_nodes[num_nodes_to_replace]; memset(new_nodes, 0, num_nodes_to_replace * sizeof(struct nn_node *)); // input needs to be channel shuffled and reshaped in the case of depthwise with channel multiplier if (need_reshape) { const uint32_t shuffle_axis_nid = create_const_int32_op(nn, 3); const uint32_t shuffle_groups_nid = create_const_int32_op(nn, input_shape.depth / chmul); struct input data_shuffle_input_refs[5]; data_shuffle_input_refs[0] = original_inputs[0]; data_shuffle_input_refs[1] = (struct input){shuffle_axis_nid, 0}; data_shuffle_input_refs[2] = (struct input){shuffle_groups_nid, 0}; data_shuffle_input_refs[3] = original_inputs[2]; data_shuffle_input_refs[4] = original_inputs[3]; struct output shuffle_output_refs[3]; make_outputdesc_from_shape(&shuffle_output_refs[0], &input_shape, info->elbytes, 0); shuffle_output_refs[1] = Output_ScalarFloat; shuffle_output_refs[2] = Output_ScalarFloat; shuffle_node = create_node(nn, 0, info->shuffle_op, NN_PAD_NA, 5, 3, data_shuffle_input_refs, shuffle_output_refs); input_shape.width *= chmul; input_shape.depth /= chmul; padded_filt_depth = filt_depth = filt_depth / chmul; padded_filt_width *= chmul; // Create const node for new input shape uint32_t new_shape[4] = {input_shape.batches, input_shape.height, input_shape.width, input_shape.depth}; uint32_t new_input_shape_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_input_shape_id, 1, 1, 1, 4, (const uint8_t *) new_shape, 4 * sizeof(uint32_t))) != 0) { errlog(nn, "Can't make a const scalar node"); return 0; } struct input data_reshape_input_refs[4]; data_reshape_input_refs[0] = (struct input){shuffle_node->node_id, 0}; data_reshape_input_refs[1] = (struct input){new_input_shape_id, 0}; data_reshape_input_refs[2] = (struct input){shuffle_node->node_id, 1}; data_reshape_input_refs[3] = (struct input){shuffle_node->node_id, 2}; struct output reshape_output_refs[3]; make_outputdesc_from_shape(&reshape_output_refs[0], &input_shape, info->elbytes, 0); reshape_output_refs[1] = Output_ScalarFloat; reshape_output_refs[2] = Output_ScalarFloat; reshape_node = create_node(nn, 0, OP_QuantizedReshape, NN_PAD_NA, 4, 3, data_reshape_input_refs, reshape_output_refs); } if (use_depthwise) { // In DW case group_depth is full depth of the transpose conv op group_depth = filt_depth * padded_num_filters * stride_wxh; d2s_output_depth = num_filters * filt_depth; } else { group_depth = padded_num_filters * stride_wxh; d2s_output_depth = num_filters; } //r, s, c, k, -> (fh, fw, din, dout) uint32_t k = group_depth; uint32_t r = padded_filt_height / stride_h; uint32_t s = padded_filt_width / stride_w; uint32_t c = padded_filt_depth / groups; uint32_t kernel_padding_height = 0; uint32_t kernel_padding_width = 0; if (use_depthwise) { // depthwise conv currently only supports channel multiplier of 1 k = 1; r = (padded_filt_height / stride_h); s = (padded_filt_width / stride_w); c = padded_filt_depth; // pad kernel width and height up to optimal depthwise shapes uint32_t pre_pad_s = s; uint32_t pre_pad_r = r; if (s <= 3) s = 3; else if (s <= 5) s = 5; else if (s <= 7) s = 7; if (r <= 2) r = 2; kernel_padding_height = r - pre_pad_r; kernel_padding_width = s - pre_pad_s; } // Transform the filters using process_transpose_conv_filter struct transpose_conv_filter_parms tcfparms; uint32_t padded_filt_size = padded_num_filters * stride_h * stride_w * padded_filt_height/stride_h * padded_filt_width/stride_w * padded_filt_depth * info->elbytes; uint32_t filter_buffer_size = padded_filt_size; if (use_depthwise) { filter_buffer_size = padded_num_filters * stride_h * stride_w * (padded_filt_height / stride_h + kernel_padding_height) * (padded_filt_width / stride_h + kernel_padding_width) * padded_filt_depth * info->elbytes; } uint8_t *padded_filters = nn_memalign(128, filter_buffer_size); tcfparms.filt_tensor = weight_node->outputs[0]; tcfparms.out_data = padded_filters; tcfparms.zero_offset = qzero; tcfparms.block_h = stride_h; tcfparms.block_w = stride_w; tcfparms.elbytes = info->elbytes; tcfparms.use_subkerneling = use_subkerneling; tcfparms.use_depthwise = use_depthwise; tcfparms.chmul = chmul; tcfparms.pad_num_filters = pad_num_filters; tcfparms.data_size = padded_filt_size; tcfparms.groups = groups; int vv = nn_os_vector_acquire(); process_transpose_conv_filter(nn, &tcfparms); nn_os_vector_release(vv); uint32_t kernel_size = r * s * c * k; uint8_t *weight_data = tcfparms.out_data; uint8_t **split_weights = (uint8_t **) padded_filters; // Create const node for new strides uint32_t new_strides[4] = {1, 1, chmul, 1}; uint32_t new_strides_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_strides_id, 1, 1, chmul, 1, (const uint8_t *)new_strides, 4 * sizeof(uint32_t))) != 0) { errlog(nn, "Can't make a const scalar node"); return 0; } uint32_t outsize_conv_height = (input_shape.height - 1) + ((r - kernel_padding_height) - 1) + 1; uint32_t outsize_conv_width = (input_shape.width - 1) + ((s - kernel_padding_width) - chmul) + 1; uint32_t d2s_crop_bottom = (input_shape.height - 1 + (r - kernel_padding_height)) * stride_h - paddings_arr[0] - original_output_shape.height; uint32_t d2s_crop_right = (input_shape.width/chmul - 1 + (s - kernel_padding_width)/chmul) * stride_w - paddings_arr[2] - original_output_shape.width; uint32_t pad_input_top = 0; uint32_t pad_input_bottom = 0; uint32_t pad_input_left = 0; uint32_t pad_input_right = 0; //If strides are 1, we need to adjust the padding amount around the input (SAME) if (stride_wxh == 1 && !use_subkerneling) { pad_input_top = paddings_arr[0]; pad_input_bottom = paddings_arr[1]; pad_input_left = paddings_arr[2]; pad_input_right = paddings_arr[3]; outsize_conv_height = original_output_shape.height; outsize_conv_width = original_output_shape.width; } uint32_t paddings[8] = {0, 0, r - 1 - pad_input_top, r - 1 - pad_input_bottom - kernel_padding_height, s - chmul - chmul*pad_input_left , s - chmul - chmul*pad_input_right - kernel_padding_width, 0, depth_padding}; input_shape.height += 2 * ((r - kernel_padding_height) - 1) - pad_input_top - pad_input_bottom + kernel_padding_height; input_shape.width += 2 * ((s - kernel_padding_width) - chmul) - pad_input_left - pad_input_right + kernel_padding_width; input_shape.depth += depth_padding; unsigned pad_node_nid = 0; // if padding needed in either height or width create const node to contain the padding tensor if (paddings[2] != 0 || paddings[3] != 0 || paddings[4] != 0 || paddings[5] != 0 || paddings[7] != 0) { uint32_t new_node_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_node_id, 1, 1, 4, 2, (const uint8_t *)paddings, 8 * sizeof(int32_t))) != 0) return errlog(nn, "Can't make a const scalar node"); struct output pad_output_refs[3]; make_outputdesc_from_shape(&pad_output_refs[0], &input_shape, info->elbytes, 0); pad_output_refs[1] = Output_ScalarFloat; pad_output_refs[2] = Output_ScalarFloat; struct input pad_input_refs[4] = { original_inputs[0], original_inputs[2], original_inputs[3], {new_node_id, 0}}; if (need_reshape) { pad_input_refs[0] = (struct input){reshape_node->node_id, 0}; pad_input_refs[1] = (struct input){reshape_node->node_id, 1}; pad_input_refs[2] = (struct input){reshape_node->node_id, 2}; } pad_node = create_node(nn, 0, info->pad_op, NN_PAD_NA, 4, 3, pad_input_refs, pad_output_refs); pad_node_nid = pad_node->node_id; } if (need_reshape) { new_nodes[0] = shuffle_node; new_nodes[1] = reshape_node; new_nodes[2] = pad_node; // may be NULL, if pad not needed } else { new_nodes[0] = pad_node; // may be NULL, if pad not needed } // Process Channel Scales and Biases float *padded_channel_scales = NULL; uint8_t *padded_biases = nn_memalign(128, groups * group_depth * info->elbytes_bias); struct nn_node *split_channel_scales[groups]; struct nn_node *split_biases[groups]; uint32_t new_bias_id; uint32_t new_channel_scale_id; uint32_t num_biases = bias_data_node->outputs[0]->shape.depth / groups; if (has_channel_scale) { float *channel_scales_data = (float *) channel_scale_node->outputs[0]->data; uint32_t num_channel_scales = channel_scale_node->outputs[0]->shape.depth / groups; padded_channel_scales = nn_memalign(128, groups * group_depth * sizeof(float)); // prefill with 1.0f for (int i = 0; i < groups * group_depth; i++) { padded_channel_scales[i] = 1.0f; } // copy & duplicate channel scales to match s2b changes to weights caused by striding and grouping for (int g = 0; g < groups; g++) { for (int i = 0; i < stride_wxh; i++) { memcpy(padded_channel_scales + i * padded_num_filters + (g * group_depth), channel_scales_data + (g * num_channel_scales), num_channel_scales * sizeof(float)); } } // create channel scale data const nodes for each group for (int g = 0; g < groups; g++) { new_channel_scale_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_channel_scale_id, 1, 1, 1, group_depth, (const uint8_t *) (padded_channel_scales + g * group_depth), group_depth * sizeof(float))) != 0) { errlog(nn, "Can't make a padded const node for channel scales"); return 0; } split_channel_scales[g] = find_node_must_be_Const(nn,new_channel_scale_id); } } // prefill with quantized zeros and // copy biases to match s2b changes to weights caused by striding and grouping if (info->elbytes_bias == sizeof(uint8_t)) { for (int i = 0; i < groups * group_depth; i++) { padded_biases[i] = bias_qzero8; } for (int g = 0; g < groups; g++) { for (int i = 0; i < stride_wxh; i++) { memcpy(padded_biases + i * padded_num_filters + (g * group_depth), bias_data + (g * num_biases), num_biases * info->elbytes_bias); } } } else { int32_t *padded_biases32 = (int32_t *) padded_biases; for (int i = 0; i < groups * group_depth; i++) { padded_biases32[i] = 0; } for (int g = 0; g < groups; g++) { for (int i = 0; i < stride_wxh; i++) { memcpy(padded_biases32 + i * padded_num_filters + (g * group_depth), bias_data + (g * num_biases), num_biases * info->elbytes_bias); } } } // create bias data const nodes for each group for (int g = 0; g < groups; g++) { new_bias_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_bias_id, 1, 1, 1, group_depth, (const uint8_t *) (padded_biases + g * group_depth), group_depth * info->elbytes_bias)) != 0) { errlog(nn, "Can't make a padded const node for biases"); return 0; } split_biases[g] = find_node_must_be_Const(nn,new_bias_id); } struct nn_node *conv_2d_node = NULL; struct nn_node *shrink1_predecessor_node = NULL; struct nn_node *bias_add_predecessor_node = NULL; struct nn_node *shrink1_node = NULL; struct nn_node *bias_add_node = NULL; struct nn_node *shrink_node = NULL; const uint32_t split_dim = 3; // split on the depth const uint32_t split_dim_nid = create_const_int32_op(nn, split_dim); if (groups > 1) { /* add node for split dimension */ const int split_num_outputs = groups + 2; /* Split node for data tensor - inputs */ struct input data_split_input_refs[4]; data_split_input_refs[0] = (struct input){ split_dim_nid, 0 }; //split dim=3 data_split_input_refs[1] = original_inputs[0]; //data tensor data_split_input_refs[2] = original_inputs[2]; //data min data_split_input_refs[3] = original_inputs[3]; //data max if (pad_node_nid != 0) { data_split_input_refs[1] = (struct input){pad_node->node_id, 0}; data_split_input_refs[2] = (struct input){pad_node->node_id, 1}; data_split_input_refs[3] = (struct input){pad_node->node_id, 2}; } /* Split node for data tensor - outputs */ struct output data_split_output_defs[split_num_outputs]; /* make output descriptors for each split node */ for(int i=0; i < groups; i++) { make_outputdesc_from_shape(&data_split_output_defs[i], &input_shape, info->elbytes, 0); data_split_output_defs[i].max_sizes[3] = c; } // split output min and max data_split_output_defs[groups] = data_split_output_defs[groups+1] = Output_ScalarFloat; /* add Split node to graph */ split_node = create_node(nn, 0, OP_QuantizedSplit_8, NN_PAD_NA, 4, split_num_outputs, data_split_input_refs, data_split_output_defs); new_nodes[1] = split_node; } shape_from_outdesc(&conv_output_shape, &transpose_conv_node->output_defs[0], /*add_d32_pad=*/0); conv_output_shape.height = outsize_conv_height; conv_output_shape.width = outsize_conv_width; conv_output_shape.depth = group_depth; // in the regular grouped cases we will create groups # of seperate tracks // in the case of subkerneling we will split the kernel by stride_wxh times and create that many seperate tracks for (int i = 0; i < iterations; i++) { int const_node_idx = use_subkerneling ? 0 : i; uint32_t offset = 0; if (groups > 1) { weight_data = split_weights[i]; } if (use_subkerneling) { offset = i * kernel_size; } //Conv2d uint32_t new_weight_node_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, new_weight_node_id, r, s, c, k, (const uint8_t *) weight_data + offset, kernel_size * info->elbytes)) != 0){ free_node_array(new_nodes, num_nodes_to_replace); return errlog(nn, "Can't make a const weights node for rearranged weights"); } struct input conv_input_refs[7] = { original_inputs[0], {new_weight_node_id, 0}, original_inputs[2], original_inputs[3], original_inputs[4], original_inputs[5], {new_strides_id, 0} }; if (need_reshape) { conv_input_refs[0] = (struct input){reshape_node->node_id, 0}; conv_input_refs[2] = (struct input){reshape_node->node_id, 1}; conv_input_refs[3] = (struct input){reshape_node->node_id, 2}; } if (pad_node_nid != 0) { conv_input_refs[0] = (struct input){pad_node->node_id, 0}; conv_input_refs[2] = (struct input){pad_node->node_id, 1}; conv_input_refs[3] = (struct input){pad_node->node_id, 2}; } if (groups > 1) { conv_input_refs[0] = (struct input){split_node->node_id, i}; conv_input_refs[2] = (struct input){split_node->node_id, groups}; conv_input_refs[3] = (struct input){split_node->node_id, groups + 1}; } struct output conv_output_refs[3]; make_outputdesc_from_shape(&conv_output_refs[0], &conv_output_shape, sizeof(int32_t), 0); conv_output_refs[1] = Output_ScalarFloat; conv_output_refs[2] = Output_ScalarFloat; conv_2d_node = create_node(nn, 0, conv_op, NN_PAD_VALID, 7, 3, conv_input_refs, conv_output_refs); bias_add_predecessor_node = conv_2d_node; shrink1_predecessor_node = conv_2d_node; //Channel Scale if (has_channel_scale) { struct output channel_scale_output_refs[3]; make_outputdesc_from_shape(&channel_scale_output_refs[0], &conv_output_shape, sizeof(int32_t), 0); channel_scale_output_refs[1] = Output_ScalarFloat; channel_scale_output_refs[2] = Output_ScalarFloat; struct input channel_scale_input_refs[4] = { {conv_2d_node->node_id, 0}, {split_channel_scales[const_node_idx]->node_id, 0}, {conv_2d_node->node_id, 1}, {conv_2d_node->node_id, 2}}; channel_scale_node = create_node(nn, 0, info->channel_scale_op, NN_PAD_NA, 4, 3, channel_scale_input_refs, channel_scale_output_refs); bias_add_predecessor_node = channel_scale_node; shrink1_predecessor_node = channel_scale_node; } if (info->bias_add_op == OP_QuantizedBiasAdd_8p8to32) { struct output shrink1_output_refs[3]; make_outputdesc_from_shape(&shrink1_output_refs[0], &conv_output_shape, sizeof(uint8_t), 0); shrink1_output_refs[1] = Output_ScalarFloat; shrink1_output_refs[2] = Output_ScalarFloat; struct input shrink1_input_refs[3] = { {shrink1_predecessor_node->node_id, 0}, {shrink1_predecessor_node->node_id, 1}, {shrink1_predecessor_node->node_id, 2}, }; shrink1_node = create_node(nn, 0, info->shrink_op, NN_PAD_NA, 3, 3, shrink1_input_refs, shrink1_output_refs); bias_add_predecessor_node = shrink1_node; } //Bias add struct output bias_add_output_refs[3]; make_outputdesc_from_shape(&bias_add_output_refs[0], &conv_output_shape, sizeof(int32_t), 0); bias_add_output_refs[1] = Output_ScalarFloat; bias_add_output_refs[2] = Output_ScalarFloat; struct input bias_add_input_refs[6] = { {bias_add_predecessor_node->node_id, 0}, {split_biases[const_node_idx]->node_id, 0}, {bias_add_predecessor_node->node_id, 1}, {bias_add_predecessor_node->node_id, 2}, original_inputs[9], original_inputs[10]}; bias_add_node = create_node(nn, 0, info->bias_add_op, NN_PAD_NA, 6, 3, bias_add_input_refs, bias_add_output_refs); //Shrink struct input shrink_input_refs[5] = { {bias_add_node->node_id, 0}, {bias_add_node->node_id, 1}, {bias_add_node->node_id, 2}, original_inputs[11], original_inputs[12]}; struct output shrink_output_refs[3]; make_outputdesc_from_shape(&shrink_output_refs[0], &conv_output_shape, info->elbytes, 0); shrink_output_refs[1] = Output_ScalarFloat; shrink_output_refs[2] = Output_ScalarFloat; // shrink_node inherits the original node id, if it's the output node. uint32_t is_output_node = stride_wxh == 1 && groups == 1 && !use_subkerneling; shrink_node = create_node(nn, is_output_node ? transpose_conv_node->node_id : 0, info->requant_op, NN_PAD_NA, 5, 3, shrink_input_refs, shrink_output_refs); new_nodes[3 + i * num_core_nodes] = conv_2d_node; new_nodes[3 + i * num_core_nodes + 1] = channel_scale_node; new_nodes[3 + i * num_core_nodes + 2] = shrink1_node; new_nodes[3 + i * num_core_nodes + 3] = bias_add_node; new_nodes[3 + i * num_core_nodes + 4] = shrink_node; // Depth to space before concat only when stride_wxh > 1 // For subkerneling, d2s happens after concat if (stride_wxh > 1) { uint32_t blocksize[2] = {stride_h, stride_w}; uint32_t block_nid = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, block_nid, 1, 1, 1, 2, (const uint8_t *)blocksize, 2 * sizeof(uint32_t))) != 0) { free_node_array(new_nodes, num_nodes_to_replace); return errlog(nn, "Failed to append const node for d2s"); } int32_t d2s_num_paddings = (pad_num_filters ? 5 : 4); int32_t padding_top = paddings_arr[0]; int32_t padding_bottom = d2s_crop_bottom; int32_t padding_left = paddings_arr[2]; int32_t padding_right = d2s_crop_right; int32_t d2s_paddings[5] = {padding_top, padding_bottom, padding_left, padding_right, d2s_output_depth}; uint32_t d2s_paddings_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, d2s_paddings_id, 1, 1, 1, d2s_num_paddings, (const uint8_t *)d2s_paddings, d2s_num_paddings * sizeof(int32_t))) != 0) { free_node_array(new_nodes, num_nodes_to_replace); return errlog(nn, "Failed to append const node for d2s"); } shape_from_outdesc(&d2s_output_shape, &transpose_conv_node->output_defs[0], /*add_d32_pad=*/0); d2s_output_shape.depth = d2s_output_shape.depth / iterations; if (pad_num_filters) d2s_output_shape.depth = roundup(d2s_output_shape.depth, 32) * stride_wxh; struct output d2s_output_refs[3]; make_outputdesc_from_shape(&d2s_output_refs[0], &d2s_output_shape, info->elbytes, 0); d2s_output_refs[1] = Output_ScalarFloat; d2s_output_refs[2] = Output_ScalarFloat; struct input d2s_input_refs[5] = { {shrink_node->node_id, 0}, {block_nid, 0}, {shrink_node->node_id, 1}, {shrink_node->node_id, 2}, {d2s_paddings_id, 0}}; unsigned d2s_nid; if (iterations > 1) { d2s_nid = 0; } else { // final node thats node id of original transpose conv op d2s_nid = transpose_conv_node->node_id; d2s_output_refs[0] = transpose_conv_node->output_defs[0]; } struct nn_node *d2s_node = create_node(nn, d2s_nid, info->d2s_op, NN_PAD_NA, 5, 3, d2s_input_refs, d2s_output_refs); new_nodes[3 + i * num_core_nodes + 5] = d2s_node; } } // if iterations > 1 then separate tracks need to be concatenated together if (iterations > 1) { const int concat_num_inputs = 3*iterations+1; unsigned concat_id; struct output concat_output_refs[3]; struct shape concat_out_shape; concat_out_shape = (stride_wxh > 1) ? d2s_output_shape : conv_output_shape; if (use_subkerneling) { // Final node will be d2s not concat concat_id = 0; } else { // Final node will be concat. Use node id of original transpose conv op concat_id = transpose_conv_node->node_id; } concat_out_shape.depth *= iterations; make_outputdesc_from_shape(&concat_output_refs[0], &concat_out_shape, sizeof(uint8_t), 0); concat_output_refs[1] = Output_ScalarFloat; concat_output_refs[2] = Output_ScalarFloat; //And we concat here struct input concat_input_refs[concat_num_inputs]; concat_input_refs[0] = (struct input){ split_dim_nid, 0 }; int offset = (stride_wxh > 1) ? 5 : 4; for(int i = 1; i <= iterations; i++) { concat_input_refs[i] = (struct input){ new_nodes[3 + (i-1) * num_core_nodes + offset]->node_id, 0 }; //tensor pieces concat_input_refs[iterations+i] = (struct input){ new_nodes[3 + (i-1) * num_core_nodes + offset]->node_id, 1 }; //mins concat_input_refs[2*iterations+i] = (struct input){ new_nodes[3 + (i-1) * num_core_nodes + offset]->node_id, 2 }; //maxes } struct nn_node *concat_node = create_node(nn, concat_id, OP_QuantizedConcat_8, NN_PAD_NA, concat_num_inputs, 3, concat_input_refs, concat_output_refs); uint32_t position = use_subkerneling ? 2 : 1; new_nodes[num_nodes_to_replace - position] = concat_node; } // When using subkerneling, depth2space happens after concat if (use_subkerneling) { uint32_t blocksize[2] = {stride_h, stride_w}; uint32_t block_nid = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, block_nid, 1, 1, 1, 2, (const uint8_t *)blocksize, 2 * sizeof(uint32_t))) != 0) { free_node_array(new_nodes, num_nodes_to_replace); return errlog(nn, "Failed to append const node for d2s"); } int32_t d2s_num_paddings = (pad_num_filters ? 5 : 4); int32_t padding_top = paddings_arr[0]; int32_t padding_bottom = d2s_crop_bottom; int32_t padding_left = paddings_arr[2]; int32_t padding_right = d2s_crop_right; int32_t d2s_paddings[5] = {padding_top, padding_bottom, padding_left, padding_right, d2s_output_depth}; uint32_t d2s_paddings_id = nn_graph_new_internal_node_id(nn); if ((do_prepend_const_node(nn, d2s_paddings_id, 1, 1, 1, d2s_num_paddings, (const uint8_t *)d2s_paddings, d2s_num_paddings * sizeof(int32_t))) != 0) { free_node_array(new_nodes, num_nodes_to_replace); return errlog(nn, "Failed to append const node for d2s"); } struct nn_node *concat_node = new_nodes[num_nodes_to_replace - 2]; shape_from_outdesc(&d2s_output_shape, &transpose_conv_node->output_defs[0], /*add_d32_pad=*/0); if (pad_num_filters) d2s_output_shape.depth = roundup(d2s_output_shape.depth, 32) * stride_wxh; struct input d2s_input_refs[5] = { {concat_node->node_id, 0}, {block_nid, 0}, {concat_node->node_id, 1}, {concat_node->node_id, 2}, {d2s_paddings_id, 0} }; // final node thats node id of original transpose conv op struct nn_node *d2s_node = create_node(nn, transpose_conv_node->node_id, info->d2s_op, NN_PAD_NA, 5, 3, d2s_input_refs, transpose_conv_node->output_defs); new_nodes[num_nodes_to_replace - 1] = d2s_node; } replace_node_with_sequence(nn, transpose_conv_node_p, transpose_conv_node, new_nodes, num_nodes_to_replace); if (padded_channel_scales) { nn_free(padded_channel_scales); } if (padded_biases) { nn_free(padded_biases); } if (groups > 1) { free_splits(split_weights, groups); } if (padded_filters) { nn_free(padded_filters); } return 0; }
48.159272
221
0.655036
[ "shape", "transform" ]
fcde8738e532a2629939dcafb20b57c6db85f6f4
1,692
h
C
AICamera/app/src/main/cpp/caffe2/quantization/server/fully_connected_dnnlowp_op.h
komejisatori/AICamera
31acf56beec21520199974a21d76175ad4995d61
[ "MIT" ]
39
2018-11-29T02:52:10.000Z
2021-07-10T10:42:23.000Z
AICamera/app/src/main/cpp/caffe2/quantization/server/fully_connected_dnnlowp_op.h
RusdiHaizim/deblur2
5cddea2782a304917ca7d1232690b626b42429a6
[ "MIT" ]
5
2018-12-26T10:34:32.000Z
2019-11-01T02:24:21.000Z
AICamera/app/src/main/cpp/caffe2/quantization/server/fully_connected_dnnlowp_op.h
RusdiHaizim/deblur2
5cddea2782a304917ca7d1232690b626b42429a6
[ "MIT" ]
5
2018-12-10T10:47:14.000Z
2019-08-12T16:40:28.000Z
#pragma once #include <fbgemm/Fbgemm.h> #include "caffe2/operators/fully_connected_op.h" #include "caffe2/quantization/server/dnnlowp_op.h" namespace caffe2 { template <typename T> class FullyConnectedDNNLowPOp : public DNNLowPOp<T, FullyConnectedOp<CPUContext>> { public: FullyConnectedDNNLowPOp(const OperatorDef& operator_def, Workspace* ws); bool RunOnDevice() override; USE_OPERATOR_FUNCTIONS(CPUContext); USE_DNNLOWP_OPERATOR_BASE_FUNCTIONS(T, FullyConnectedOp<CPUContext>); protected: bool GetQuantizationParameters_(); std::size_t axis_{1}; std::size_t axis_w_{1}; vector<std::int64_t> Y_shape_cache_; dnnlowp::RequantizationParams requantization_params_; bool requantization_param_selected_{false}; // x86 only provides SIMD instructions that multiply a signed integer with an // unsigned integer. We use signed for weights. using T_signed = typename std::make_signed<T>::type; // used in fast path for T == uint8_t std::shared_ptr<fbgemm::PackBMatrix<std::int8_t>> Wq_packed_; std::vector<std::uint8_t> X_pack_buf_; std::vector<std::int32_t> Y_int32_; // used in slow path for T != uint8_t std::vector<T_signed> W_quantized_; // pre-computed biases and offsets std::vector<std::int32_t> b_quantized_; const std::int32_t* b_quantized_data_{nullptr}; std::vector<std::int32_t> row_offsets_, column_offsets_; // Dequantized bias populated when input bias is quantized and // dequantized_output_ == true std::vector<float> b_dequantized_; const float* b_dequantized_data_{nullptr}; bool is_weight_constant_{true}; float in_qparams0_scale_old_ = 0; }; // class FullyConnectedDNNLowPOp } // namespace caffe2
29.172414
79
0.763593
[ "vector" ]
fcdeaed5e3606481ebc8816f005c3e4a58b9e117
18,290
h
C
src/parsec/facesim/src/Public_Library/Read_Write/READ_WRITE_FUNCTIONS.h
OleksiiOleksenko/fex
f6f165310ecd760808580686fac2fa3f697440fc
[ "MIT" ]
15
2017-02-08T04:02:50.000Z
2021-02-20T16:47:25.000Z
src/parsec/facesim/src/Public_Library/Read_Write/READ_WRITE_FUNCTIONS.h
OleksiiOleksenko/fex
f6f165310ecd760808580686fac2fa3f697440fc
[ "MIT" ]
1
2018-05-24T11:03:07.000Z
2018-05-24T11:03:07.000Z
src/parsec/facesim/src/Public_Library/Read_Write/READ_WRITE_FUNCTIONS.h
OleksiiOleksenko/fex
f6f165310ecd760808580686fac2fa3f697440fc
[ "MIT" ]
4
2018-10-18T14:58:53.000Z
2020-05-08T08:54:49.000Z
//##################################################################### // Copyright 2004, Eran Guendelman, Igor Neverov, Andrew Selle, Eftychios Sifakis. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class READ_WRITE_FUNCTIONS //##################################################################### // // Functions for reading and writing which do the correct thing for objects, pointers, primitive types, etc. In general, use Read/Write_Binary (and Read/Write_Binary_Array) using T for the type // of the object you're reading/writing and RW the underlying floating point scalar type (float/double). // //##################################################################### #ifndef __READ_WRITE_FUNCTIONS__ #define __READ_WRITE_FUNCTIONS__ #include <iostream> #include <assert.h> #include <stdlib.h> namespace PhysBAM { //##################################################################### // Function isLittleEndian //##################################################################### static inline int isLittleEndian() { union { unsigned short int word; unsigned char byte; } endian_test; endian_test.word = 0x00FF; return (endian_test.byte == 0xFF); } //##################################################################### // Function Swap_Endianity //##################################################################### template<class T> inline void Swap_Endianity (T& x) { assert (sizeof (T) <= 8); if (sizeof (T) > 1) { T old = x; for (unsigned int k = 1; k <= sizeof (T); k++) ( (char*) &x) [k - 1] = ( (char*) &old) [sizeof (T) - k]; } } //##################################################################### // Read/Write_Primitive (handles endianness) //##################################################################### #ifdef __sparc__ void sparc_seg_fault_prevent_dummy (void *ptr); #endif template<class T> inline void Read_Primitive (std::istream& input_stream, T& d) { input_stream.read ( (char*) &d, sizeof (T)); if (!isLittleEndian()) Swap_Endianity (d); #ifdef __sparc__ /* For unknown reasons I am getting a segfault on my sparc box compiling with -O3, unless I place a dummy use of the value just read here. Might just be an issue with a particular gcc version. Unfortunately, this function call does affect the region of interest. */ sparc_seg_fault_prevent_dummy ( (void *) &d); #endif } template<class T> inline void Write_Primitive (std::ostream& output_stream, const T& d) { T d2 = d; if (!isLittleEndian()) Swap_Endianity (d2); output_stream.write ( (const char*) &d2, sizeof (T)); } #ifdef __APPLE__ // PhysBAM data formats assume sizeof(bool)==1 but the Mac apparently has bool==int with sizeof(bool)==4, so need to specialize these template<> inline void Read_Primitive<bool> (std::istream& input_stream, bool& d) { char c; input_stream.read (&c, 1); d = (bool) c; } template<> inline void Write_Primitive<bool> (std::ostream& output_stream, const bool& d) { char c = (char) d; output_stream.write (&c, 1); } #endif //##################################################################### // Read/Write_Float_Or_Double //##################################################################### template<class T, class RW> inline void Read_Float_Or_Double (std::istream& input_stream, T& d) { std::cerr << "Read_Float_Or_Double called with bad types" << std::endl; exit (1); } template<class T, class RW> inline void Write_Float_Or_Double (std::ostream& output_stream, T d) { std::cerr << "Write_Float_Or_Double called with bad types" << std::endl; exit (1); } template<> inline void Read_Float_Or_Double<float, float> (std::istream& input_stream, float& d) { Read_Primitive (input_stream, d); // no conversion } template<> inline void Read_Float_Or_Double<double, double> (std::istream& input_stream, double& d) { Read_Primitive (input_stream, d); // no conversion } template<> inline void Read_Float_Or_Double<float, double> (std::istream& input_stream, float& d) { double tmp; // convert types Read_Primitive (input_stream, tmp); d = (float) tmp; } template<> inline void Read_Float_Or_Double<double, float> (std::istream& input_stream, double& d) { float tmp; // convert types Read_Primitive (input_stream, tmp); d = (double) tmp; } template<> inline void Write_Float_Or_Double<float, float> (std::ostream& output_stream, float d) { Write_Primitive (output_stream, d); // no conversion } template<> inline void Write_Float_Or_Double<double, double> (std::ostream& output_stream, double d) { Write_Primitive (output_stream, d); // no conversion } template<> inline void Write_Float_Or_Double<float, double> (std::ostream& output_stream, float d) { Write_Primitive (output_stream, (double) d); // convert types } template<> inline void Write_Float_Or_Double<double, float> (std::ostream& output_stream, double d) { Write_Primitive (output_stream, (float) d); // convert types } //##################################################################### // Read_Write for objects //##################################################################### template<class T> struct Read_Write { template<class RW> static void Read (std::istream& input_stream, T& d) { d.template Read<RW> (input_stream); } template<class RW> static void Write (std::ostream& output_stream, const T& d) { d.template Write<RW> (output_stream); } }; //##################################################################### // Read_Write for primitive types (other than float and double) //##################################################################### #define DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE(TYPE) \ template<> struct Read_Write<TYPE> { \ template<class RW> static void Read(std::istream& input_stream,TYPE& d){Read_Primitive(input_stream,d);} \ template<class RW> static void Write(std::ostream& output_stream,const TYPE& d) {Write_Primitive(output_stream,d);} \ }; DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (bool); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (char); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned char); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (short); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned short); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (int); DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned int); //##################################################################### // Specializations for float and double //##################################################################### template<> struct Read_Write<float> { template<class RW> static void Read (std::istream& input_stream, float& d) { Read_Float_Or_Double<float, RW> (input_stream, d); } template<class RW> static void Write (std::ostream& output_stream, const float& d) { Write_Float_Or_Double<float, RW> (output_stream, d); } }; template<> struct Read_Write<double> { template<class RW> static void Read (std::istream& input_stream, double& d) { Read_Float_Or_Double<double, RW> (input_stream, d); } template<class RW> static void Write (std::ostream& output_stream, const double& d) { Write_Float_Or_Double<double, RW> (output_stream, d); } }; //##################################################################### // Read_Write for pointers to data //##################################################################### template<class T> struct Read_Write<T*> { template<class RW> static void Read (std::istream& input_stream, T*& d) { bool data_exists; Read_Write<bool>::template Read<RW> (input_stream, data_exists); if (data_exists) { d = new T(); // potential memory leak if d pointed elsewhere Read_Write<T>::template Read<RW> (input_stream, *d); } else d = 0; } template<class RW> static void Write (std::ostream& output_stream, T* const& d) { Read_Write<bool>::template Write<RW> (output_stream, d != 0); // Write a bool tag indicating whether pointer's data follows if (d) Read_Write<T>::template Write<RW> (output_stream, *d); } }; //##################################################################### // Read_Write for std::string's //##################################################################### template<> struct Read_Write<std::string> { template<class RW> static void Read (std::istream& input_stream, std::string& d) { int n; Read_Write<int>::template Read<RW> (input_stream, n); char* buffer = new char[n]; input_stream.read (buffer, n); d.assign (buffer, buffer + n); delete[] buffer; } template<class RW> static void Write (std::ostream& output_stream, const std::string& d) { int n = int (d.size()); Read_Write<int>::template Write<RW> (output_stream, n); const char* s = d.c_str(); output_stream.write (s, n); } }; //##################################################################### // Read_Binary //##################################################################### template<class RW, class T1> inline void Read_Binary (std::istream& input_stream, T1& d1) { Read_Write<T1>::template Read<RW> (input_stream, d1); } template<class RW, class T1, class T2> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); } template<class RW, class T1, class T2, class T3> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); } template<class RW, class T1, class T2, class T3, class T4> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); } template<class RW, class T1, class T2, class T3, class T4, class T5> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); Read_Write<T5>::template Read<RW> (input_stream, d5); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); Read_Write<T5>::template Read<RW> (input_stream, d5); Read_Write<T6>::template Read<RW> (input_stream, d6); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); Read_Write<T5>::template Read<RW> (input_stream, d5); Read_Write<T6>::template Read<RW> (input_stream, d6); Read_Write<T7>::template Read<RW> (input_stream, d7); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7, T8& d8) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); Read_Write<T5>::template Read<RW> (input_stream, d5); Read_Write<T6>::template Read<RW> (input_stream, d6); Read_Write<T7>::template Read<RW> (input_stream, d7); Read_Write<T8>::template Read<RW> (input_stream, d8); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7, T8& d8, T9& d9) { Read_Write<T1>::template Read<RW> (input_stream, d1); Read_Write<T2>::template Read<RW> (input_stream, d2); Read_Write<T3>::template Read<RW> (input_stream, d3); Read_Write<T4>::template Read<RW> (input_stream, d4); Read_Write<T5>::template Read<RW> (input_stream, d5); Read_Write<T6>::template Read<RW> (input_stream, d6); Read_Write<T7>::template Read<RW> (input_stream, d7); Read_Write<T8>::template Read<RW> (input_stream, d8); Read_Write<T9>::template Read<RW> (input_stream, d9); } //##################################################################### // Write_Binary //##################################################################### template<class RW, class T1> inline void Write_Binary (std::ostream& output_stream, const T1& d1) { Read_Write<T1>::template Write<RW> (output_stream, d1); } template<class RW, class T1, class T2> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); } template<class RW, class T1, class T2, class T3> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); } template<class RW, class T1, class T2, class T3, class T4> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); } template<class RW, class T1, class T2, class T3, class T4, class T5> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); Read_Write<T5>::template Write<RW> (output_stream, d5); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); Read_Write<T5>::template Write<RW> (output_stream, d5); Read_Write<T6>::template Write<RW> (output_stream, d6); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); Read_Write<T5>::template Write<RW> (output_stream, d5); Read_Write<T6>::template Write<RW> (output_stream, d6); Read_Write<T7>::template Write<RW> (output_stream, d7); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7, const T8& d8) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); Read_Write<T5>::template Write<RW> (output_stream, d5); Read_Write<T6>::template Write<RW> (output_stream, d6); Read_Write<T7>::template Write<RW> (output_stream, d7); Read_Write<T8>::template Write<RW> (output_stream, d8); } template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7, const T8& d8, const T9& d9) { Read_Write<T1>::template Write<RW> (output_stream, d1); Read_Write<T2>::template Write<RW> (output_stream, d2); Read_Write<T3>::template Write<RW> (output_stream, d3); Read_Write<T4>::template Write<RW> (output_stream, d4); Read_Write<T5>::template Write<RW> (output_stream, d5); Read_Write<T6>::template Write<RW> (output_stream, d6); Read_Write<T7>::template Write<RW> (output_stream, d7); Read_Write<T8>::template Write<RW> (output_stream, d8); Read_Write<T9>::template Write<RW> (output_stream, d9); } //##################################################################### // Read/Write_Binary_Array //##################################################################### // array is C-style (zero-based) array template<class RW, class T> inline void Read_Binary_Array (std::istream& input_stream, T* array, const int number_of_elements) { for (int i = 0; i < number_of_elements; i++) Read_Write<T>::template Read<RW> (input_stream, array[i]); } template<class RW, class T> inline void Write_Binary_Array (std::ostream& output_stream, const T* array, const int number_of_elements) { for (int i = 0; i < number_of_elements; i++) Read_Write<T>::template Write<RW> (output_stream, array[i]); } //##################################################################### } #endif
37.556468
193
0.637124
[ "object" ]
fce3f6720dfc004066a2d59ef3bc2ef314df434c
3,005
h
C
Common/gui/guilistbox.h
fernewelten/ags
ab662ebc6fcd682be8cc12a69ad03cffa2fe73eb
[ "Artistic-2.0" ]
1
2019-01-24T13:47:57.000Z
2019-01-24T13:47:57.000Z
Common/gui/guilistbox.h
fernewelten/ags
ab662ebc6fcd682be8cc12a69ad03cffa2fe73eb
[ "Artistic-2.0" ]
null
null
null
Common/gui/guilistbox.h
fernewelten/ags
ab662ebc6fcd682be8cc12a69ad03cffa2fe73eb
[ "Artistic-2.0" ]
null
null
null
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= #ifndef __AC_GUILISTBOX_H #define __AC_GUILISTBOX_H #include <vector> #include "gui/guiobject.h" #include "util/string.h" namespace AGS { namespace Common { class GUIListBox : public GUIObject { public: GUIListBox(); bool AreArrowsShown() const; bool IsBorderShown() const; bool IsSvgIndex() const; bool IsInRightMargin(int x) const; int GetItemAt(int x, int y) const; // Operations int AddItem(const String &text); void Clear(); virtual void Draw(Bitmap *ds) override; int InsertItem(int index, const String &text); void RemoveItem(int index); void SetShowArrows(bool on); void SetShowBorder(bool on); void SetSvgIndex(bool on); // TODO: work around this void SetFont(int font); void SetItemText(int index, const String &textt); // Events virtual bool OnMouseDown() override; virtual void OnMouseMove(int x, int y) override; virtual void OnResized() override; // Serialization virtual void ReadFromFile(Stream *in, GuiVersion gui_version) override; virtual void WriteToFile(Stream *out) const override; virtual void ReadFromSavegame(Common::Stream *in, GuiSvgVersion svg_ver) override; virtual void WriteToSavegame(Common::Stream *out) const override; // TODO: these members are currently public; hide them later public: int32_t Font; color_t TextColor; HorAlignment TextAlignment; color_t SelectedBgColor; color_t SelectedTextColor; int32_t RowHeight; int32_t VisibleItemCount; std::vector<String> Items; std::vector<int16_t> SavedGameIndex; int32_t SelectedItem; int32_t TopItem; Point MousePos; // TODO: remove these later int32_t ItemCount; private: int32_t ListBoxFlags; // A temporary solution for special drawing in the Editor void DrawItemsFix(); void DrawItemsUnfix(); void PrepareTextToDraw(const String &text); // prepared text buffer/cache String _textToDraw; }; } // namespace Common } // namespace AGS extern std::vector<AGS::Common::GUIListBox> guilist; extern int numguilist; #endif // __AC_GUILISTBOX_H
30.353535
86
0.610316
[ "vector" ]
fce6df990f5694e404302b7c09ccacac09e70bfc
4,650
h
C
WOF2/src/WOF/match/spatialQuery/attic/FootballerBallPathInterceptAnalyzedSimulation.h
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
3
2018-12-02T14:09:22.000Z
2021-11-22T07:14:05.000Z
WOF2/src/WOF/match/spatialQuery/attic/FootballerBallPathInterceptAnalyzedSimulation.h
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
1
2018-12-03T22:54:38.000Z
2018-12-03T22:54:38.000Z
WOF2/src/WOF/match/spatialQuery/attic/FootballerBallPathInterceptAnalyzedSimulation.h
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
2
2020-09-22T21:04:14.000Z
2021-05-24T09:43:28.000Z
#ifndef _FootballerBallPathInterceptAnalyzedSimulation_h_WOF_match #define _FootballerBallPathInterceptAnalyzedSimulation_h_WOF_match #include "WE3/WETL/WETLArray.h" #include "WE3/math/WEPlane.h" using namespace WE; #include "../WOFMatchDataTypes.h" #include "../WOFMatchObjectDefines.h" #include "../entity/ball/ballSimul/BallSimulation2.h" #include "SpatialQueryDataTypes.h" namespace WOF { namespace match { class Match; class FootballerBallPathInterceptAnalyzedSimulation { public: enum State { State_None = -1, State_Invalid, State_WaitingForSimul, State_Processing, State_Valid, State_Expired }; struct FootballerState { //float playerReactionTime; //in seconds float distanceTolerance; float vel; float activationTime; float penaltyTime; FootballerState(); void init(Footballer& footballer); }; typedef BallSimulation2::Index SampleIndex; typedef BallSimulation2::Index EventIndex; typedef BallSimulation2::Sample Sample; public: FootballerBallPathInterceptAnalyzedSimulation(); void init(Match& match); State update(Match& match, BallSimulation2& simul, const Time& time); inline const State& getState() { return mState; } inline bool isValid() { return mState == State_Valid; } inline const SimulationID& getSimulID() { return mCurrSimulID; } inline BallSimulation2* getSimul() { return mCurrSimul; } inline const Sample& getSample(const SampleIndex& index) { return mCurrSimul->getSample(index); } void render(Ball& ball, Renderer& renderer, bool flagExtraRenders, RenderPassEnum pass); public: bool checkValidity(Match& match, BallSimulation2& simul, const Time& time); bool updateShortestTimeInterceptState(Match& match, Footballer& footballer, BallSimulation2& simul, const Time& time, const SampleIndex* pStartSampleIndex = NULL); bool getIntersectionTime(Footballer& footballer, const SimulationID& simulID, const FootballerState& footballerState, const SampleIndex& sampleIndex, const BallSimulation2::Sample& sample, PathIntercept& result, const Time& currTime, bool fillSampleData, PathInterceptType filterType = PI_None) const; bool getIntersectionTime(Footballer& footballer, const SimulationID& simulID, const FootballerState& footballerState, const SampleIndex& sampleIndex, const Vector3& samplePos, const Time& _sampleTime, PathIntercept& result, const Time& currTime, bool fillSampleData, PathInterceptType filterType = PI_None) const; bool getIntersectionTime(Footballer& footballer, const SimulationID& simulID, const SampleIndex& sampleIndex, const BallSimulation2::Sample& sample, PathIntercept& result, const Time& currTime, bool fillSampleData, PathInterceptType filterType = PI_None); bool getIntersectionTime(Footballer& footballer, const SimulationID& simulID, const SampleIndex& sampleIndex, const Vector3& samplePos, const Time& _sampleTime, PathIntercept& result, const Time& currTime, bool fillSampleData, PathInterceptType filterType = PI_None); protected: struct SampleInterval { SampleIndex startIndex; SampleIndex endIndex; }; struct StraightTrajectory : SampleInterval { Plane plane; bool getIntersectionTime(Footballer& footballer, const SampleInterval& interval, BallSimulation2& simul, float& intersectionTime) const; }; struct IntervalIntersection : SampleInterval { bool isValid; bool nextAdvanceFirstInterval; //use this to advance 1st or 2nd interval for further intersections }; struct TrajectoryInterval : SampleInterval { const StraightTrajectory* trajectory; }; typedef WETL::CountedArray<StraightTrajectory, false, unsigned int> Trajectories; typedef WETL::CountedArray<SampleInterval, false, unsigned int> SampleIntervals; typedef WETL::CountedArray<TrajectoryInterval, false, unsigned int> TrajectoryIntervals; State mState; SimulationID mCurrSimulID; SoftPtr<BallSimulation2> mCurrSimul; Trajectories mTrajectories; SampleIntervals mAccessibleHeightIntervals; TrajectoryIntervals mConsideredIntervals; SampleIndex mStartSampleIndex; FootballerState mTempFootballerState; void onSimulChanged(Match& match, BallSimulation2& simul, const Time& time); bool updateStartSampleIndex(Match& match, BallSimulation2& simul, const Time& time); void addTrajectory(Match& match, BallSimulation2& simul, SampleIndex& startIndex, SampleIndex& endIndex); void getIntervalIntersection(const SampleInterval& interval1, const SampleInterval& interval2, IntervalIntersection& intersection); }; } } #endif
39.07563
316
0.772903
[ "render" ]
1e00c60dee3f0f0f78c58b1f9153a902685a849f
2,475
h
C
options/linux-headers/include/linux/hdreg.h
Dennisbonke/mlibc
4ac29d952e27f8aefc6def6dfcd113c427eeb391
[ "MIT" ]
480
2018-06-02T06:50:12.000Z
2022-03-31T11:38:56.000Z
options/linux-headers/include/linux/hdreg.h
Dennisbonke/mlibc
4ac29d952e27f8aefc6def6dfcd113c427eeb391
[ "MIT" ]
227
2018-12-23T17:07:38.000Z
2022-03-30T22:49:11.000Z
options/linux-headers/include/linux/hdreg.h
Dennisbonke/mlibc
4ac29d952e27f8aefc6def6dfcd113c427eeb391
[ "MIT" ]
99
2018-06-02T16:19:27.000Z
2022-03-26T02:08:12.000Z
#ifndef _LINUX_HDREG_H #define _LINUX_HDREG_H #define HDIO_GET_IDENTITY 0x030D #ifdef __cplusplus extern "C" { #endif struct hd_driveid { unsigned short config; unsigned short cyls; unsigned short reserved2; unsigned short heads; unsigned short track_bytes; unsigned short sector_bytes; unsigned short sectors; unsigned short vendor0; unsigned short vendor1; unsigned short vendor2; unsigned char serial_no[20]; unsigned short buf_type; unsigned short buf_size; unsigned short ecc_bytes; unsigned char fw_rev[8]; unsigned char model[40]; unsigned char max_multsect; unsigned char vendor3; unsigned short dword_io; unsigned char vendor4; unsigned char capability; unsigned short reserved50; unsigned char vendor5; unsigned char tPIO; unsigned char vendor6; unsigned char tDMA; unsigned short field_valid; unsigned short cur_cyls; unsigned short cur_heads; unsigned short cur_sectors; unsigned short cur_capacity0; unsigned short cur_capacity1; unsigned char multsect; unsigned char multsect_valid; unsigned int lba_capacity; unsigned short dma_1word; unsigned short dma_mword; unsigned short eide_pio_modes; unsigned short eide_dma_min; unsigned short eide_dma_time; unsigned short eide_pio; unsigned short eide_pio_iordy; unsigned short words69_70[2]; unsigned short words71_74[4]; unsigned short queue_depth; unsigned short words76_79[4]; unsigned short major_rev_num; unsigned short minor_rev_num; unsigned short command_set_1; unsigned short command_set_2; unsigned short cfsse; unsigned short cfs_enable_1; unsigned short cfs_enable_2; unsigned short csf_default; unsigned short dma_ultra; unsigned short trseuc; unsigned short trsEuc; unsigned short CurAPMvalues; unsigned short mprc; unsigned short hw_config; unsigned short acoustic; unsigned short msrqs; unsigned short sxfert; unsigned short sal; unsigned int spg; unsigned long long lba_capacity_2; unsigned short words104_125[22]; unsigned short last_lun; unsigned short word127; unsigned short dlf; unsigned short csfo; unsigned short words130_155[26]; unsigned short word156; unsigned short words157_159[3]; unsigned short cfa_power; unsigned short words161_175[15]; unsigned short words176_205[30]; unsigned short words206_254[49]; unsigned short integrity_word; }; #ifdef __cplusplus } #endif #endif // _LINUX_HDREG_H
25
35
0.768081
[ "model" ]
1e1071079bd409d9944b5633d1bd5bb0d5cbc618
1,115
h
C
System/Library/PrivateFrameworks/CameraUI.framework/CAMBufferKeyValueObserverObservanceChange.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
12
2019-06-02T02:42:41.000Z
2021-04-13T07:22:20.000Z
System/Library/PrivateFrameworks/CameraUI.framework/CAMBufferKeyValueObserverObservanceChange.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/CameraUI.framework/CAMBufferKeyValueObserverObservanceChange.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
3
2019-06-11T02:46:10.000Z
2019-12-21T14:58:16.000Z
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:21 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/CameraUI.framework/CameraUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <CameraUI/CAMBufferObservanceChange.h> @class NSString, NSObject, NSDictionary; @interface CAMBufferKeyValueObserverObservanceChange : CAMBufferObservanceChange { NSString* _keyPath; NSObject* _object; NSDictionary* _change; } @property (nonatomic,copy,readonly) NSString * keyPath; //@synthesize keyPath=_keyPath - In the implementation block @property (nonatomic,__weak,readonly) NSObject * object; //@synthesize object=_object - In the implementation block @property (nonatomic,copy,readonly) NSDictionary * change; //@synthesize change=_change - In the implementation block -(NSDictionary *)change; -(id)initWithKeyPath:(id)arg1 ofObject:(id)arg2 withChange:(id)arg3 ; -(NSObject *)object; -(NSString *)keyPath; @end
37.166667
132
0.748879
[ "object" ]
1e1425e7d34b5eaaced3b7754c46c764a6aa8830
341,613
c
C
deps/db/libdb_java/db_java_wrap.c
prescott66/poedit
f52d76beff00198686b27996d5a11fa24252a173
[ "MIT" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
deps/db/libdb_java/db_java_wrap.c
laborautonomo/poedit
4ccc4e40334cc8b147d77077d1e5522a55862b3d
[ "MIT" ]
null
null
null
deps/db/libdb_java/db_java_wrap.c
laborautonomo/poedit
4ccc4e40334cc8b147d77077d1e5522a55862b3d
[ "MIT" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
#include "db_config.h" /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.38 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGJAVA /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # undef _CRT_SECURE_NO_DEPRECATE # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Fix for jlong on some versions of gcc on Windows */ #if defined(__GNUC__) && !defined(__INTEL_COMPILER) typedef long long __int64; #endif /* Fix for jlong on 64-bit x86 Solaris */ #if defined(__x86_64) # ifdef _LP64 # undef _LP64 # endif #endif #include <jni.h> #include <stdlib.h> #include <string.h> /* Support for throwing Java exceptions */ typedef enum { SWIG_JavaOutOfMemoryError = 1, SWIG_JavaIOException, SWIG_JavaRuntimeException, SWIG_JavaIndexOutOfBoundsException, SWIG_JavaArithmeticException, SWIG_JavaIllegalArgumentException, SWIG_JavaNullPointerException, SWIG_JavaDirectorPureVirtual, SWIG_JavaUnknownError } SWIG_JavaExceptionCodes; typedef struct { SWIG_JavaExceptionCodes code; const char *java_exception; } SWIG_JavaExceptions_t; static void SWIGUNUSED SWIG_JavaThrowException(JNIEnv *jenv, SWIG_JavaExceptionCodes code, const char *msg) { jclass excep; static const SWIG_JavaExceptions_t java_exceptions[] = { { SWIG_JavaOutOfMemoryError, "java/lang/OutOfMemoryError" }, { SWIG_JavaIOException, "java/io/IOException" }, { SWIG_JavaRuntimeException, "java/lang/RuntimeException" }, { SWIG_JavaIndexOutOfBoundsException, "java/lang/IndexOutOfBoundsException" }, { SWIG_JavaArithmeticException, "java/lang/ArithmeticException" }, { SWIG_JavaIllegalArgumentException, "java/lang/IllegalArgumentException" }, { SWIG_JavaNullPointerException, "java/lang/NullPointerException" }, { SWIG_JavaDirectorPureVirtual, "java/lang/RuntimeException" }, { SWIG_JavaUnknownError, "java/lang/UnknownError" }, { (SWIG_JavaExceptionCodes)0, "java/lang/UnknownError" } }; const SWIG_JavaExceptions_t *except_ptr = java_exceptions; while (except_ptr->code != code && except_ptr->code) except_ptr++; (*jenv)->ExceptionClear(jenv); excep = (*jenv)->FindClass(jenv, except_ptr->java_exception); if (excep) (*jenv)->ThrowNew(jenv, excep, msg); } /* Contract support */ #define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, msg); return nullreturn; } else #include "db_int.h" #include "dbinc/txn.h" #ifdef HAVE_CRYPTO #define CRYPTO_ONLY(x) (x); #else #define CRYPTO_ONLY(x) #endif /* don't use SWIG's array handling - save code space */ #define SWIG_NOINCLUDE 1 #define DB_ENV_INTERNAL(dbenv) ((dbenv)->api2_internal) #define DB_INTERNAL(db) ((db)->api_internal) #define DB_PKG "com/sleepycat/db/" /* Forward declarations */ static int __dbj_throw(JNIEnv *jenv, int err, const char *msg, jobject obj, jobject jdbenv); /* Global data - JVM handle, classes, fields and methods */ static JavaVM *javavm; static jclass db_class, dbc_class, dbenv_class, dbt_class, dblsn_class; static jclass dbpreplist_class, dbtxn_class; static jclass keyrange_class; static jclass bt_stat_class, compact_class, h_stat_class, lock_stat_class; static jclass log_stat_class, mpool_stat_class, mpool_fstat_class; static jclass mutex_stat_class, qam_stat_class, rep_stat_class; static jclass repmgr_stat_class, repmgr_siteinfo_class, rephost_class; static jclass seq_stat_class, txn_stat_class; static jclass txn_active_class; static jclass lock_class, lockreq_class; static jclass dbex_class, deadex_class, lockex_class, memex_class; static jclass repdupmasterex_class, rephandledeadex_class; static jclass repholdelectionex_class, repjoinfailex_class; static jclass repleaseexpiredex_class, repleasetimeoutex_class; static jclass replockoutex_class, repunavailex_class; static jclass runrecex_class, versionex_class; static jclass filenotfoundex_class, illegalargex_class, outofmemerr_class; static jclass bytearray_class, string_class, outputstream_class; static jfieldID dbc_cptr_fid; static jfieldID dblsn_file_fid, dblsn_offset_fid; static jfieldID dbt_data_fid, dbt_data_nio_fid, dbt_size_fid, dbt_ulen_fid; static jfieldID dbt_dlen_fid, dbt_doff_fid, dbt_flags_fid, dbt_offset_fid; static jfieldID kr_less_fid, kr_equal_fid, kr_greater_fid; static jfieldID lock_cptr_fid; static jfieldID lockreq_op_fid, lockreq_modeflag_fid, lockreq_timeout_fid; static jfieldID lockreq_obj_fid, lockreq_lock_fid; static jfieldID repmgr_siteinfo_status_fid; /* BEGIN-STAT-FIELD-DECLS */ static jfieldID bt_stat_bt_magic_fid; static jfieldID bt_stat_bt_version_fid; static jfieldID bt_stat_bt_metaflags_fid; static jfieldID bt_stat_bt_nkeys_fid; static jfieldID bt_stat_bt_ndata_fid; static jfieldID bt_stat_bt_pagecnt_fid; static jfieldID bt_stat_bt_pagesize_fid; static jfieldID bt_stat_bt_minkey_fid; static jfieldID bt_stat_bt_re_len_fid; static jfieldID bt_stat_bt_re_pad_fid; static jfieldID bt_stat_bt_levels_fid; static jfieldID bt_stat_bt_int_pg_fid; static jfieldID bt_stat_bt_leaf_pg_fid; static jfieldID bt_stat_bt_dup_pg_fid; static jfieldID bt_stat_bt_over_pg_fid; static jfieldID bt_stat_bt_empty_pg_fid; static jfieldID bt_stat_bt_free_fid; static jfieldID bt_stat_bt_int_pgfree_fid; static jfieldID bt_stat_bt_leaf_pgfree_fid; static jfieldID bt_stat_bt_dup_pgfree_fid; static jfieldID bt_stat_bt_over_pgfree_fid; static jfieldID compact_compact_fillpercent_fid; static jfieldID compact_compact_timeout_fid; static jfieldID compact_compact_pages_fid; static jfieldID compact_compact_pages_free_fid; static jfieldID compact_compact_pages_examine_fid; static jfieldID compact_compact_levels_fid; static jfieldID compact_compact_deadlock_fid; static jfieldID compact_compact_pages_truncated_fid; static jfieldID compact_compact_truncate_fid; static jfieldID h_stat_hash_magic_fid; static jfieldID h_stat_hash_version_fid; static jfieldID h_stat_hash_metaflags_fid; static jfieldID h_stat_hash_nkeys_fid; static jfieldID h_stat_hash_ndata_fid; static jfieldID h_stat_hash_pagecnt_fid; static jfieldID h_stat_hash_pagesize_fid; static jfieldID h_stat_hash_ffactor_fid; static jfieldID h_stat_hash_buckets_fid; static jfieldID h_stat_hash_free_fid; static jfieldID h_stat_hash_bfree_fid; static jfieldID h_stat_hash_bigpages_fid; static jfieldID h_stat_hash_big_bfree_fid; static jfieldID h_stat_hash_overflows_fid; static jfieldID h_stat_hash_ovfl_free_fid; static jfieldID h_stat_hash_dup_fid; static jfieldID h_stat_hash_dup_free_fid; static jfieldID lock_stat_st_id_fid; static jfieldID lock_stat_st_cur_maxid_fid; static jfieldID lock_stat_st_maxlocks_fid; static jfieldID lock_stat_st_maxlockers_fid; static jfieldID lock_stat_st_maxobjects_fid; static jfieldID lock_stat_st_partitions_fid; static jfieldID lock_stat_st_nmodes_fid; static jfieldID lock_stat_st_nlockers_fid; static jfieldID lock_stat_st_nlocks_fid; static jfieldID lock_stat_st_maxnlocks_fid; static jfieldID lock_stat_st_maxhlocks_fid; static jfieldID lock_stat_st_locksteals_fid; static jfieldID lock_stat_st_maxlsteals_fid; static jfieldID lock_stat_st_maxnlockers_fid; static jfieldID lock_stat_st_nobjects_fid; static jfieldID lock_stat_st_maxnobjects_fid; static jfieldID lock_stat_st_maxhobjects_fid; static jfieldID lock_stat_st_objectsteals_fid; static jfieldID lock_stat_st_maxosteals_fid; static jfieldID lock_stat_st_nrequests_fid; static jfieldID lock_stat_st_nreleases_fid; static jfieldID lock_stat_st_nupgrade_fid; static jfieldID lock_stat_st_ndowngrade_fid; static jfieldID lock_stat_st_lock_wait_fid; static jfieldID lock_stat_st_lock_nowait_fid; static jfieldID lock_stat_st_ndeadlocks_fid; static jfieldID lock_stat_st_locktimeout_fid; static jfieldID lock_stat_st_nlocktimeouts_fid; static jfieldID lock_stat_st_txntimeout_fid; static jfieldID lock_stat_st_ntxntimeouts_fid; static jfieldID lock_stat_st_part_wait_fid; static jfieldID lock_stat_st_part_nowait_fid; static jfieldID lock_stat_st_part_max_wait_fid; static jfieldID lock_stat_st_part_max_nowait_fid; static jfieldID lock_stat_st_objs_wait_fid; static jfieldID lock_stat_st_objs_nowait_fid; static jfieldID lock_stat_st_lockers_wait_fid; static jfieldID lock_stat_st_lockers_nowait_fid; static jfieldID lock_stat_st_region_wait_fid; static jfieldID lock_stat_st_region_nowait_fid; static jfieldID lock_stat_st_hash_len_fid; static jfieldID lock_stat_st_regsize_fid; static jfieldID log_stat_st_magic_fid; static jfieldID log_stat_st_version_fid; static jfieldID log_stat_st_mode_fid; static jfieldID log_stat_st_lg_bsize_fid; static jfieldID log_stat_st_lg_size_fid; static jfieldID log_stat_st_wc_bytes_fid; static jfieldID log_stat_st_wc_mbytes_fid; static jfieldID log_stat_st_record_fid; static jfieldID log_stat_st_w_bytes_fid; static jfieldID log_stat_st_w_mbytes_fid; static jfieldID log_stat_st_wcount_fid; static jfieldID log_stat_st_wcount_fill_fid; static jfieldID log_stat_st_rcount_fid; static jfieldID log_stat_st_scount_fid; static jfieldID log_stat_st_region_wait_fid; static jfieldID log_stat_st_region_nowait_fid; static jfieldID log_stat_st_cur_file_fid; static jfieldID log_stat_st_cur_offset_fid; static jfieldID log_stat_st_disk_file_fid; static jfieldID log_stat_st_disk_offset_fid; static jfieldID log_stat_st_maxcommitperflush_fid; static jfieldID log_stat_st_mincommitperflush_fid; static jfieldID log_stat_st_regsize_fid; static jfieldID mpool_fstat_file_name_fid; static jfieldID mpool_fstat_st_pagesize_fid; static jfieldID mpool_fstat_st_map_fid; static jfieldID mpool_fstat_st_cache_hit_fid; static jfieldID mpool_fstat_st_cache_miss_fid; static jfieldID mpool_fstat_st_page_create_fid; static jfieldID mpool_fstat_st_page_in_fid; static jfieldID mpool_fstat_st_page_out_fid; static jfieldID mpool_stat_st_gbytes_fid; static jfieldID mpool_stat_st_bytes_fid; static jfieldID mpool_stat_st_ncache_fid; static jfieldID mpool_stat_st_max_ncache_fid; static jfieldID mpool_stat_st_mmapsize_fid; static jfieldID mpool_stat_st_maxopenfd_fid; static jfieldID mpool_stat_st_maxwrite_fid; static jfieldID mpool_stat_st_maxwrite_sleep_fid; static jfieldID mpool_stat_st_pages_fid; static jfieldID mpool_stat_st_map_fid; static jfieldID mpool_stat_st_cache_hit_fid; static jfieldID mpool_stat_st_cache_miss_fid; static jfieldID mpool_stat_st_page_create_fid; static jfieldID mpool_stat_st_page_in_fid; static jfieldID mpool_stat_st_page_out_fid; static jfieldID mpool_stat_st_ro_evict_fid; static jfieldID mpool_stat_st_rw_evict_fid; static jfieldID mpool_stat_st_page_trickle_fid; static jfieldID mpool_stat_st_page_clean_fid; static jfieldID mpool_stat_st_page_dirty_fid; static jfieldID mpool_stat_st_hash_buckets_fid; static jfieldID mpool_stat_st_pagesize_fid; static jfieldID mpool_stat_st_hash_searches_fid; static jfieldID mpool_stat_st_hash_longest_fid; static jfieldID mpool_stat_st_hash_examined_fid; static jfieldID mpool_stat_st_hash_nowait_fid; static jfieldID mpool_stat_st_hash_wait_fid; static jfieldID mpool_stat_st_hash_max_nowait_fid; static jfieldID mpool_stat_st_hash_max_wait_fid; static jfieldID mpool_stat_st_region_nowait_fid; static jfieldID mpool_stat_st_region_wait_fid; static jfieldID mpool_stat_st_mvcc_frozen_fid; static jfieldID mpool_stat_st_mvcc_thawed_fid; static jfieldID mpool_stat_st_mvcc_freed_fid; static jfieldID mpool_stat_st_alloc_fid; static jfieldID mpool_stat_st_alloc_buckets_fid; static jfieldID mpool_stat_st_alloc_max_buckets_fid; static jfieldID mpool_stat_st_alloc_pages_fid; static jfieldID mpool_stat_st_alloc_max_pages_fid; static jfieldID mpool_stat_st_io_wait_fid; static jfieldID mpool_stat_st_sync_interrupted_fid; static jfieldID mpool_stat_st_regsize_fid; static jfieldID mutex_stat_st_mutex_align_fid; static jfieldID mutex_stat_st_mutex_tas_spins_fid; static jfieldID mutex_stat_st_mutex_cnt_fid; static jfieldID mutex_stat_st_mutex_free_fid; static jfieldID mutex_stat_st_mutex_inuse_fid; static jfieldID mutex_stat_st_mutex_inuse_max_fid; static jfieldID mutex_stat_st_region_wait_fid; static jfieldID mutex_stat_st_region_nowait_fid; static jfieldID mutex_stat_st_regsize_fid; static jfieldID qam_stat_qs_magic_fid; static jfieldID qam_stat_qs_version_fid; static jfieldID qam_stat_qs_metaflags_fid; static jfieldID qam_stat_qs_nkeys_fid; static jfieldID qam_stat_qs_ndata_fid; static jfieldID qam_stat_qs_pagesize_fid; static jfieldID qam_stat_qs_extentsize_fid; static jfieldID qam_stat_qs_pages_fid; static jfieldID qam_stat_qs_re_len_fid; static jfieldID qam_stat_qs_re_pad_fid; static jfieldID qam_stat_qs_pgfree_fid; static jfieldID qam_stat_qs_first_recno_fid; static jfieldID qam_stat_qs_cur_recno_fid; static jfieldID rep_stat_st_log_queued_fid; static jfieldID rep_stat_st_startup_complete_fid; static jfieldID rep_stat_st_status_fid; static jfieldID rep_stat_st_next_lsn_fid; static jfieldID rep_stat_st_waiting_lsn_fid; static jfieldID rep_stat_st_max_perm_lsn_fid; static jfieldID rep_stat_st_next_pg_fid; static jfieldID rep_stat_st_waiting_pg_fid; static jfieldID rep_stat_st_dupmasters_fid; static jfieldID rep_stat_st_env_id_fid; static jfieldID rep_stat_st_env_priority_fid; static jfieldID rep_stat_st_bulk_fills_fid; static jfieldID rep_stat_st_bulk_overflows_fid; static jfieldID rep_stat_st_bulk_records_fid; static jfieldID rep_stat_st_bulk_transfers_fid; static jfieldID rep_stat_st_client_rerequests_fid; static jfieldID rep_stat_st_client_svc_req_fid; static jfieldID rep_stat_st_client_svc_miss_fid; static jfieldID rep_stat_st_gen_fid; static jfieldID rep_stat_st_egen_fid; static jfieldID rep_stat_st_log_duplicated_fid; static jfieldID rep_stat_st_log_queued_max_fid; static jfieldID rep_stat_st_log_queued_total_fid; static jfieldID rep_stat_st_log_records_fid; static jfieldID rep_stat_st_log_requested_fid; static jfieldID rep_stat_st_master_fid; static jfieldID rep_stat_st_master_changes_fid; static jfieldID rep_stat_st_msgs_badgen_fid; static jfieldID rep_stat_st_msgs_processed_fid; static jfieldID rep_stat_st_msgs_recover_fid; static jfieldID rep_stat_st_msgs_send_failures_fid; static jfieldID rep_stat_st_msgs_sent_fid; static jfieldID rep_stat_st_newsites_fid; static jfieldID rep_stat_st_nsites_fid; static jfieldID rep_stat_st_nthrottles_fid; static jfieldID rep_stat_st_outdated_fid; static jfieldID rep_stat_st_pg_duplicated_fid; static jfieldID rep_stat_st_pg_records_fid; static jfieldID rep_stat_st_pg_requested_fid; static jfieldID rep_stat_st_txns_applied_fid; static jfieldID rep_stat_st_startsync_delayed_fid; static jfieldID rep_stat_st_elections_fid; static jfieldID rep_stat_st_elections_won_fid; static jfieldID rep_stat_st_election_cur_winner_fid; static jfieldID rep_stat_st_election_gen_fid; static jfieldID rep_stat_st_election_lsn_fid; static jfieldID rep_stat_st_election_nsites_fid; static jfieldID rep_stat_st_election_nvotes_fid; static jfieldID rep_stat_st_election_priority_fid; static jfieldID rep_stat_st_election_status_fid; static jfieldID rep_stat_st_election_tiebreaker_fid; static jfieldID rep_stat_st_election_votes_fid; static jfieldID rep_stat_st_election_sec_fid; static jfieldID rep_stat_st_election_usec_fid; static jfieldID rep_stat_st_max_lease_sec_fid; static jfieldID rep_stat_st_max_lease_usec_fid; static jfieldID repmgr_stat_st_perm_failed_fid; static jfieldID repmgr_stat_st_msgs_queued_fid; static jfieldID repmgr_stat_st_msgs_dropped_fid; static jfieldID repmgr_stat_st_connection_drop_fid; static jfieldID repmgr_stat_st_connect_fail_fid; static jfieldID seq_stat_st_wait_fid; static jfieldID seq_stat_st_nowait_fid; static jfieldID seq_stat_st_current_fid; static jfieldID seq_stat_st_value_fid; static jfieldID seq_stat_st_last_value_fid; static jfieldID seq_stat_st_min_fid; static jfieldID seq_stat_st_max_fid; static jfieldID seq_stat_st_cache_size_fid; static jfieldID seq_stat_st_flags_fid; static jfieldID txn_stat_st_nrestores_fid; static jfieldID txn_stat_st_last_ckp_fid; static jfieldID txn_stat_st_time_ckp_fid; static jfieldID txn_stat_st_last_txnid_fid; static jfieldID txn_stat_st_maxtxns_fid; static jfieldID txn_stat_st_naborts_fid; static jfieldID txn_stat_st_nbegins_fid; static jfieldID txn_stat_st_ncommits_fid; static jfieldID txn_stat_st_nactive_fid; static jfieldID txn_stat_st_nsnapshot_fid; static jfieldID txn_stat_st_maxnactive_fid; static jfieldID txn_stat_st_maxnsnapshot_fid; static jfieldID txn_stat_st_txnarray_fid; static jfieldID txn_stat_st_region_wait_fid; static jfieldID txn_stat_st_region_nowait_fid; static jfieldID txn_stat_st_regsize_fid; static jfieldID txn_active_txnid_fid; static jfieldID txn_active_parentid_fid; static jfieldID txn_active_pid_fid; static jfieldID txn_active_lsn_fid; static jfieldID txn_active_read_lsn_fid; static jfieldID txn_active_mvcc_ref_fid; static jfieldID txn_active_status_fid; static jfieldID txn_active_gid_fid; static jfieldID txn_active_name_fid; /* END-STAT-FIELD-DECLS */ static jmethodID dbenv_construct, dbt_construct, dblsn_construct; static jmethodID dbpreplist_construct, dbtxn_construct; static jmethodID bt_stat_construct, get_err_msg_method, h_stat_construct; static jmethodID lock_stat_construct, log_stat_construct; static jmethodID mpool_stat_construct, mpool_fstat_construct; static jmethodID mutex_stat_construct, qam_stat_construct; static jmethodID rep_stat_construct, repmgr_stat_construct, seq_stat_construct; static jmethodID txn_stat_construct, txn_active_construct; static jmethodID dbex_construct, deadex_construct, lockex_construct; static jmethodID memex_construct, memex_update_method; static jmethodID repdupmasterex_construct, rephandledeadex_construct; static jmethodID repholdelectionex_construct, repjoinfailex_construct; static jmethodID repmgr_siteinfo_construct, rephost_construct, repleaseexpiredex_construct; static jmethodID repleasetimeoutex_construct, replockoutex_construct; static jmethodID repunavailex_construct; static jmethodID runrecex_construct, versionex_construct; static jmethodID filenotfoundex_construct, illegalargex_construct; static jmethodID outofmemerr_construct; static jmethodID lock_construct; static jmethodID app_dispatch_method, errcall_method, env_feedback_method; static jmethodID msgcall_method, paniccall_method, rep_transport_method; static jmethodID panic_event_notify_method, rep_client_event_notify_method; static jmethodID rep_elected_event_notify_method; static jmethodID rep_master_event_notify_method; static jmethodID rep_new_master_event_notify_method; static jmethodID rep_perm_failed_event_notify_method; static jmethodID rep_startup_done_event_notify_method; static jmethodID write_failed_event_notify_method; static jmethodID append_recno_method, bt_compare_method, bt_compress_method; static jmethodID bt_decompress_method, bt_prefix_method; static jmethodID db_feedback_method, dup_compare_method; static jmethodID foreignkey_nullify_method, h_compare_method, h_hash_method; static jmethodID partition_method, seckey_create_method; static jmethodID outputstream_write_method; const struct { jclass *cl; const char *name; } all_classes[] = { { &dbenv_class, DB_PKG "internal/DbEnv" }, { &db_class, DB_PKG "internal/Db" }, { &dbc_class, DB_PKG "internal/Dbc" }, { &dbt_class, DB_PKG "DatabaseEntry" }, { &dblsn_class, DB_PKG "LogSequenceNumber" }, { &dbpreplist_class, DB_PKG "PreparedTransaction" }, { &dbtxn_class, DB_PKG "internal/DbTxn" }, { &bt_stat_class, DB_PKG "BtreeStats" }, { &compact_class, DB_PKG "CompactStats" }, { &h_stat_class, DB_PKG "HashStats" }, { &lock_stat_class, DB_PKG "LockStats" }, { &log_stat_class, DB_PKG "LogStats" }, { &mpool_fstat_class, DB_PKG "CacheFileStats" }, { &mpool_stat_class, DB_PKG "CacheStats" }, { &mutex_stat_class, DB_PKG "MutexStats" }, { &qam_stat_class, DB_PKG "QueueStats" }, { &rep_stat_class, DB_PKG "ReplicationStats" }, { &repmgr_stat_class, DB_PKG "ReplicationManagerStats" }, { &seq_stat_class, DB_PKG "SequenceStats" }, { &txn_stat_class, DB_PKG "TransactionStats" }, { &txn_active_class, DB_PKG "TransactionStats$Active" }, { &keyrange_class, DB_PKG "KeyRange" }, { &lock_class, DB_PKG "internal/DbLock" }, { &lockreq_class, DB_PKG "LockRequest" }, { &dbex_class, DB_PKG "DatabaseException" }, { &deadex_class, DB_PKG "DeadlockException" }, { &lockex_class, DB_PKG "LockNotGrantedException" }, { &memex_class, DB_PKG "MemoryException" }, { &repdupmasterex_class, DB_PKG "ReplicationDuplicateMasterException" }, { &rephandledeadex_class, DB_PKG "ReplicationHandleDeadException" }, { &repholdelectionex_class, DB_PKG "ReplicationHoldElectionException" }, { &rephost_class, DB_PKG "ReplicationHostAddress" }, { &repmgr_siteinfo_class, DB_PKG "ReplicationManagerSiteInfo" }, { &repjoinfailex_class, DB_PKG "ReplicationJoinFailureException" }, { &repleaseexpiredex_class, DB_PKG "ReplicationLeaseExpiredException" }, { &repleasetimeoutex_class, DB_PKG "ReplicationLeaseTimeoutException" }, { &replockoutex_class, DB_PKG "ReplicationLockoutException" }, { &repunavailex_class, DB_PKG "ReplicationSiteUnavailableException" }, { &runrecex_class, DB_PKG "RunRecoveryException" }, { &versionex_class, DB_PKG "VersionMismatchException" }, { &filenotfoundex_class, "java/io/FileNotFoundException" }, { &illegalargex_class, "java/lang/IllegalArgumentException" }, { &outofmemerr_class, "java/lang/OutOfMemoryError" }, { &bytearray_class, "[B" }, { &string_class, "java/lang/String" }, { &outputstream_class, "java/io/OutputStream" } }; const struct { jfieldID *fid; jclass *cl; const char *name; const char *sig; } all_fields[] = { { &dbc_cptr_fid, &dbc_class, "swigCPtr", "J" }, { &dblsn_file_fid, &dblsn_class, "file", "I" }, { &dblsn_offset_fid, &dblsn_class, "offset", "I" }, { &dbt_data_fid, &dbt_class, "data", "[B" }, { &dbt_data_nio_fid, &dbt_class, "data_nio", "Ljava/nio/ByteBuffer;" }, { &dbt_size_fid, &dbt_class, "size", "I" }, { &dbt_ulen_fid, &dbt_class, "ulen", "I" }, { &dbt_dlen_fid, &dbt_class, "dlen", "I" }, { &dbt_doff_fid, &dbt_class, "doff", "I" }, { &dbt_flags_fid, &dbt_class, "flags", "I" }, { &dbt_offset_fid, &dbt_class, "offset", "I" }, { &kr_less_fid, &keyrange_class, "less", "D" }, { &kr_equal_fid, &keyrange_class, "equal", "D" }, { &kr_greater_fid, &keyrange_class, "greater", "D" }, { &lock_cptr_fid, &lock_class, "swigCPtr", "J" }, { &lockreq_op_fid, &lockreq_class, "op", "I" }, { &lockreq_modeflag_fid, &lockreq_class, "modeFlag", "I" }, { &lockreq_timeout_fid, &lockreq_class, "timeout", "I" }, { &lockreq_obj_fid, &lockreq_class, "obj", "L" DB_PKG "DatabaseEntry;" }, { &lockreq_lock_fid, &lockreq_class, "lock", "L" DB_PKG "internal/DbLock;" }, /* BEGIN-STAT-FIELDS */ { &bt_stat_bt_magic_fid, &bt_stat_class, "bt_magic", "I" }, { &bt_stat_bt_version_fid, &bt_stat_class, "bt_version", "I" }, { &bt_stat_bt_metaflags_fid, &bt_stat_class, "bt_metaflags", "I" }, { &bt_stat_bt_nkeys_fid, &bt_stat_class, "bt_nkeys", "I" }, { &bt_stat_bt_ndata_fid, &bt_stat_class, "bt_ndata", "I" }, { &bt_stat_bt_pagecnt_fid, &bt_stat_class, "bt_pagecnt", "I" }, { &bt_stat_bt_pagesize_fid, &bt_stat_class, "bt_pagesize", "I" }, { &bt_stat_bt_minkey_fid, &bt_stat_class, "bt_minkey", "I" }, { &bt_stat_bt_re_len_fid, &bt_stat_class, "bt_re_len", "I" }, { &bt_stat_bt_re_pad_fid, &bt_stat_class, "bt_re_pad", "I" }, { &bt_stat_bt_levels_fid, &bt_stat_class, "bt_levels", "I" }, { &bt_stat_bt_int_pg_fid, &bt_stat_class, "bt_int_pg", "I" }, { &bt_stat_bt_leaf_pg_fid, &bt_stat_class, "bt_leaf_pg", "I" }, { &bt_stat_bt_dup_pg_fid, &bt_stat_class, "bt_dup_pg", "I" }, { &bt_stat_bt_over_pg_fid, &bt_stat_class, "bt_over_pg", "I" }, { &bt_stat_bt_empty_pg_fid, &bt_stat_class, "bt_empty_pg", "I" }, { &bt_stat_bt_free_fid, &bt_stat_class, "bt_free", "I" }, { &bt_stat_bt_int_pgfree_fid, &bt_stat_class, "bt_int_pgfree", "J" }, { &bt_stat_bt_leaf_pgfree_fid, &bt_stat_class, "bt_leaf_pgfree", "J" }, { &bt_stat_bt_dup_pgfree_fid, &bt_stat_class, "bt_dup_pgfree", "J" }, { &bt_stat_bt_over_pgfree_fid, &bt_stat_class, "bt_over_pgfree", "J" }, { &compact_compact_fillpercent_fid, &compact_class, "compact_fillpercent", "I" }, { &compact_compact_timeout_fid, &compact_class, "compact_timeout", "I" }, { &compact_compact_pages_fid, &compact_class, "compact_pages", "I" }, { &compact_compact_pages_free_fid, &compact_class, "compact_pages_free", "I" }, { &compact_compact_pages_examine_fid, &compact_class, "compact_pages_examine", "I" }, { &compact_compact_levels_fid, &compact_class, "compact_levels", "I" }, { &compact_compact_deadlock_fid, &compact_class, "compact_deadlock", "I" }, { &compact_compact_pages_truncated_fid, &compact_class, "compact_pages_truncated", "I" }, { &compact_compact_truncate_fid, &compact_class, "compact_truncate", "I" }, { &h_stat_hash_magic_fid, &h_stat_class, "hash_magic", "I" }, { &h_stat_hash_version_fid, &h_stat_class, "hash_version", "I" }, { &h_stat_hash_metaflags_fid, &h_stat_class, "hash_metaflags", "I" }, { &h_stat_hash_nkeys_fid, &h_stat_class, "hash_nkeys", "I" }, { &h_stat_hash_ndata_fid, &h_stat_class, "hash_ndata", "I" }, { &h_stat_hash_pagecnt_fid, &h_stat_class, "hash_pagecnt", "I" }, { &h_stat_hash_pagesize_fid, &h_stat_class, "hash_pagesize", "I" }, { &h_stat_hash_ffactor_fid, &h_stat_class, "hash_ffactor", "I" }, { &h_stat_hash_buckets_fid, &h_stat_class, "hash_buckets", "I" }, { &h_stat_hash_free_fid, &h_stat_class, "hash_free", "I" }, { &h_stat_hash_bfree_fid, &h_stat_class, "hash_bfree", "J" }, { &h_stat_hash_bigpages_fid, &h_stat_class, "hash_bigpages", "I" }, { &h_stat_hash_big_bfree_fid, &h_stat_class, "hash_big_bfree", "J" }, { &h_stat_hash_overflows_fid, &h_stat_class, "hash_overflows", "I" }, { &h_stat_hash_ovfl_free_fid, &h_stat_class, "hash_ovfl_free", "J" }, { &h_stat_hash_dup_fid, &h_stat_class, "hash_dup", "I" }, { &h_stat_hash_dup_free_fid, &h_stat_class, "hash_dup_free", "J" }, { &lock_stat_st_id_fid, &lock_stat_class, "st_id", "I" }, { &lock_stat_st_cur_maxid_fid, &lock_stat_class, "st_cur_maxid", "I" }, { &lock_stat_st_maxlocks_fid, &lock_stat_class, "st_maxlocks", "I" }, { &lock_stat_st_maxlockers_fid, &lock_stat_class, "st_maxlockers", "I" }, { &lock_stat_st_maxobjects_fid, &lock_stat_class, "st_maxobjects", "I" }, { &lock_stat_st_partitions_fid, &lock_stat_class, "st_partitions", "I" }, { &lock_stat_st_nmodes_fid, &lock_stat_class, "st_nmodes", "I" }, { &lock_stat_st_nlockers_fid, &lock_stat_class, "st_nlockers", "I" }, { &lock_stat_st_nlocks_fid, &lock_stat_class, "st_nlocks", "I" }, { &lock_stat_st_maxnlocks_fid, &lock_stat_class, "st_maxnlocks", "I" }, { &lock_stat_st_maxhlocks_fid, &lock_stat_class, "st_maxhlocks", "I" }, { &lock_stat_st_locksteals_fid, &lock_stat_class, "st_locksteals", "J" }, { &lock_stat_st_maxlsteals_fid, &lock_stat_class, "st_maxlsteals", "J" }, { &lock_stat_st_maxnlockers_fid, &lock_stat_class, "st_maxnlockers", "I" }, { &lock_stat_st_nobjects_fid, &lock_stat_class, "st_nobjects", "I" }, { &lock_stat_st_maxnobjects_fid, &lock_stat_class, "st_maxnobjects", "I" }, { &lock_stat_st_maxhobjects_fid, &lock_stat_class, "st_maxhobjects", "I" }, { &lock_stat_st_objectsteals_fid, &lock_stat_class, "st_objectsteals", "J" }, { &lock_stat_st_maxosteals_fid, &lock_stat_class, "st_maxosteals", "J" }, { &lock_stat_st_nrequests_fid, &lock_stat_class, "st_nrequests", "J" }, { &lock_stat_st_nreleases_fid, &lock_stat_class, "st_nreleases", "J" }, { &lock_stat_st_nupgrade_fid, &lock_stat_class, "st_nupgrade", "J" }, { &lock_stat_st_ndowngrade_fid, &lock_stat_class, "st_ndowngrade", "J" }, { &lock_stat_st_lock_wait_fid, &lock_stat_class, "st_lock_wait", "J" }, { &lock_stat_st_lock_nowait_fid, &lock_stat_class, "st_lock_nowait", "J" }, { &lock_stat_st_ndeadlocks_fid, &lock_stat_class, "st_ndeadlocks", "J" }, { &lock_stat_st_locktimeout_fid, &lock_stat_class, "st_locktimeout", "I" }, { &lock_stat_st_nlocktimeouts_fid, &lock_stat_class, "st_nlocktimeouts", "J" }, { &lock_stat_st_txntimeout_fid, &lock_stat_class, "st_txntimeout", "I" }, { &lock_stat_st_ntxntimeouts_fid, &lock_stat_class, "st_ntxntimeouts", "J" }, { &lock_stat_st_part_wait_fid, &lock_stat_class, "st_part_wait", "J" }, { &lock_stat_st_part_nowait_fid, &lock_stat_class, "st_part_nowait", "J" }, { &lock_stat_st_part_max_wait_fid, &lock_stat_class, "st_part_max_wait", "J" }, { &lock_stat_st_part_max_nowait_fid, &lock_stat_class, "st_part_max_nowait", "J" }, { &lock_stat_st_objs_wait_fid, &lock_stat_class, "st_objs_wait", "J" }, { &lock_stat_st_objs_nowait_fid, &lock_stat_class, "st_objs_nowait", "J" }, { &lock_stat_st_lockers_wait_fid, &lock_stat_class, "st_lockers_wait", "J" }, { &lock_stat_st_lockers_nowait_fid, &lock_stat_class, "st_lockers_nowait", "J" }, { &lock_stat_st_region_wait_fid, &lock_stat_class, "st_region_wait", "J" }, { &lock_stat_st_region_nowait_fid, &lock_stat_class, "st_region_nowait", "J" }, { &lock_stat_st_hash_len_fid, &lock_stat_class, "st_hash_len", "I" }, { &lock_stat_st_regsize_fid, &lock_stat_class, "st_regsize", "I" }, { &log_stat_st_magic_fid, &log_stat_class, "st_magic", "I" }, { &log_stat_st_version_fid, &log_stat_class, "st_version", "I" }, { &log_stat_st_mode_fid, &log_stat_class, "st_mode", "I" }, { &log_stat_st_lg_bsize_fid, &log_stat_class, "st_lg_bsize", "I" }, { &log_stat_st_lg_size_fid, &log_stat_class, "st_lg_size", "I" }, { &log_stat_st_wc_bytes_fid, &log_stat_class, "st_wc_bytes", "I" }, { &log_stat_st_wc_mbytes_fid, &log_stat_class, "st_wc_mbytes", "I" }, { &log_stat_st_record_fid, &log_stat_class, "st_record", "J" }, { &log_stat_st_w_bytes_fid, &log_stat_class, "st_w_bytes", "I" }, { &log_stat_st_w_mbytes_fid, &log_stat_class, "st_w_mbytes", "I" }, { &log_stat_st_wcount_fid, &log_stat_class, "st_wcount", "J" }, { &log_stat_st_wcount_fill_fid, &log_stat_class, "st_wcount_fill", "J" }, { &log_stat_st_rcount_fid, &log_stat_class, "st_rcount", "J" }, { &log_stat_st_scount_fid, &log_stat_class, "st_scount", "J" }, { &log_stat_st_region_wait_fid, &log_stat_class, "st_region_wait", "J" }, { &log_stat_st_region_nowait_fid, &log_stat_class, "st_region_nowait", "J" }, { &log_stat_st_cur_file_fid, &log_stat_class, "st_cur_file", "I" }, { &log_stat_st_cur_offset_fid, &log_stat_class, "st_cur_offset", "I" }, { &log_stat_st_disk_file_fid, &log_stat_class, "st_disk_file", "I" }, { &log_stat_st_disk_offset_fid, &log_stat_class, "st_disk_offset", "I" }, { &log_stat_st_maxcommitperflush_fid, &log_stat_class, "st_maxcommitperflush", "I" }, { &log_stat_st_mincommitperflush_fid, &log_stat_class, "st_mincommitperflush", "I" }, { &log_stat_st_regsize_fid, &log_stat_class, "st_regsize", "I" }, { &mpool_fstat_file_name_fid, &mpool_fstat_class, "file_name", "Ljava/lang/String;" }, { &mpool_fstat_st_pagesize_fid, &mpool_fstat_class, "st_pagesize", "I" }, { &mpool_fstat_st_map_fid, &mpool_fstat_class, "st_map", "I" }, { &mpool_fstat_st_cache_hit_fid, &mpool_fstat_class, "st_cache_hit", "J" }, { &mpool_fstat_st_cache_miss_fid, &mpool_fstat_class, "st_cache_miss", "J" }, { &mpool_fstat_st_page_create_fid, &mpool_fstat_class, "st_page_create", "J" }, { &mpool_fstat_st_page_in_fid, &mpool_fstat_class, "st_page_in", "J" }, { &mpool_fstat_st_page_out_fid, &mpool_fstat_class, "st_page_out", "J" }, { &mpool_stat_st_gbytes_fid, &mpool_stat_class, "st_gbytes", "I" }, { &mpool_stat_st_bytes_fid, &mpool_stat_class, "st_bytes", "I" }, { &mpool_stat_st_ncache_fid, &mpool_stat_class, "st_ncache", "I" }, { &mpool_stat_st_max_ncache_fid, &mpool_stat_class, "st_max_ncache", "I" }, { &mpool_stat_st_mmapsize_fid, &mpool_stat_class, "st_mmapsize", "I" }, { &mpool_stat_st_maxopenfd_fid, &mpool_stat_class, "st_maxopenfd", "I" }, { &mpool_stat_st_maxwrite_fid, &mpool_stat_class, "st_maxwrite", "I" }, { &mpool_stat_st_maxwrite_sleep_fid, &mpool_stat_class, "st_maxwrite_sleep", "I" }, { &mpool_stat_st_pages_fid, &mpool_stat_class, "st_pages", "I" }, { &mpool_stat_st_map_fid, &mpool_stat_class, "st_map", "I" }, { &mpool_stat_st_cache_hit_fid, &mpool_stat_class, "st_cache_hit", "J" }, { &mpool_stat_st_cache_miss_fid, &mpool_stat_class, "st_cache_miss", "J" }, { &mpool_stat_st_page_create_fid, &mpool_stat_class, "st_page_create", "J" }, { &mpool_stat_st_page_in_fid, &mpool_stat_class, "st_page_in", "J" }, { &mpool_stat_st_page_out_fid, &mpool_stat_class, "st_page_out", "J" }, { &mpool_stat_st_ro_evict_fid, &mpool_stat_class, "st_ro_evict", "J" }, { &mpool_stat_st_rw_evict_fid, &mpool_stat_class, "st_rw_evict", "J" }, { &mpool_stat_st_page_trickle_fid, &mpool_stat_class, "st_page_trickle", "J" }, { &mpool_stat_st_page_clean_fid, &mpool_stat_class, "st_page_clean", "I" }, { &mpool_stat_st_page_dirty_fid, &mpool_stat_class, "st_page_dirty", "I" }, { &mpool_stat_st_hash_buckets_fid, &mpool_stat_class, "st_hash_buckets", "I" }, { &mpool_stat_st_pagesize_fid, &mpool_stat_class, "st_pagesize", "I" }, { &mpool_stat_st_hash_searches_fid, &mpool_stat_class, "st_hash_searches", "I" }, { &mpool_stat_st_hash_longest_fid, &mpool_stat_class, "st_hash_longest", "I" }, { &mpool_stat_st_hash_examined_fid, &mpool_stat_class, "st_hash_examined", "J" }, { &mpool_stat_st_hash_nowait_fid, &mpool_stat_class, "st_hash_nowait", "J" }, { &mpool_stat_st_hash_wait_fid, &mpool_stat_class, "st_hash_wait", "J" }, { &mpool_stat_st_hash_max_nowait_fid, &mpool_stat_class, "st_hash_max_nowait", "J" }, { &mpool_stat_st_hash_max_wait_fid, &mpool_stat_class, "st_hash_max_wait", "J" }, { &mpool_stat_st_region_nowait_fid, &mpool_stat_class, "st_region_nowait", "J" }, { &mpool_stat_st_region_wait_fid, &mpool_stat_class, "st_region_wait", "J" }, { &mpool_stat_st_mvcc_frozen_fid, &mpool_stat_class, "st_mvcc_frozen", "J" }, { &mpool_stat_st_mvcc_thawed_fid, &mpool_stat_class, "st_mvcc_thawed", "J" }, { &mpool_stat_st_mvcc_freed_fid, &mpool_stat_class, "st_mvcc_freed", "J" }, { &mpool_stat_st_alloc_fid, &mpool_stat_class, "st_alloc", "J" }, { &mpool_stat_st_alloc_buckets_fid, &mpool_stat_class, "st_alloc_buckets", "J" }, { &mpool_stat_st_alloc_max_buckets_fid, &mpool_stat_class, "st_alloc_max_buckets", "J" }, { &mpool_stat_st_alloc_pages_fid, &mpool_stat_class, "st_alloc_pages", "J" }, { &mpool_stat_st_alloc_max_pages_fid, &mpool_stat_class, "st_alloc_max_pages", "J" }, { &mpool_stat_st_io_wait_fid, &mpool_stat_class, "st_io_wait", "J" }, { &mpool_stat_st_sync_interrupted_fid, &mpool_stat_class, "st_sync_interrupted", "J" }, { &mpool_stat_st_regsize_fid, &mpool_stat_class, "st_regsize", "I" }, { &mutex_stat_st_mutex_align_fid, &mutex_stat_class, "st_mutex_align", "I" }, { &mutex_stat_st_mutex_tas_spins_fid, &mutex_stat_class, "st_mutex_tas_spins", "I" }, { &mutex_stat_st_mutex_cnt_fid, &mutex_stat_class, "st_mutex_cnt", "I" }, { &mutex_stat_st_mutex_free_fid, &mutex_stat_class, "st_mutex_free", "I" }, { &mutex_stat_st_mutex_inuse_fid, &mutex_stat_class, "st_mutex_inuse", "I" }, { &mutex_stat_st_mutex_inuse_max_fid, &mutex_stat_class, "st_mutex_inuse_max", "I" }, { &mutex_stat_st_region_wait_fid, &mutex_stat_class, "st_region_wait", "J" }, { &mutex_stat_st_region_nowait_fid, &mutex_stat_class, "st_region_nowait", "J" }, { &mutex_stat_st_regsize_fid, &mutex_stat_class, "st_regsize", "I" }, { &qam_stat_qs_magic_fid, &qam_stat_class, "qs_magic", "I" }, { &qam_stat_qs_version_fid, &qam_stat_class, "qs_version", "I" }, { &qam_stat_qs_metaflags_fid, &qam_stat_class, "qs_metaflags", "I" }, { &qam_stat_qs_nkeys_fid, &qam_stat_class, "qs_nkeys", "I" }, { &qam_stat_qs_ndata_fid, &qam_stat_class, "qs_ndata", "I" }, { &qam_stat_qs_pagesize_fid, &qam_stat_class, "qs_pagesize", "I" }, { &qam_stat_qs_extentsize_fid, &qam_stat_class, "qs_extentsize", "I" }, { &qam_stat_qs_pages_fid, &qam_stat_class, "qs_pages", "I" }, { &qam_stat_qs_re_len_fid, &qam_stat_class, "qs_re_len", "I" }, { &qam_stat_qs_re_pad_fid, &qam_stat_class, "qs_re_pad", "I" }, { &qam_stat_qs_pgfree_fid, &qam_stat_class, "qs_pgfree", "I" }, { &qam_stat_qs_first_recno_fid, &qam_stat_class, "qs_first_recno", "I" }, { &qam_stat_qs_cur_recno_fid, &qam_stat_class, "qs_cur_recno", "I" }, { &rep_stat_st_log_queued_fid, &rep_stat_class, "st_log_queued", "J" }, { &rep_stat_st_startup_complete_fid, &rep_stat_class, "st_startup_complete", "I" }, { &rep_stat_st_status_fid, &rep_stat_class, "st_status", "I" }, { &rep_stat_st_next_lsn_fid, &rep_stat_class, "st_next_lsn", "L" DB_PKG "LogSequenceNumber;" }, { &rep_stat_st_waiting_lsn_fid, &rep_stat_class, "st_waiting_lsn", "L" DB_PKG "LogSequenceNumber;" }, { &rep_stat_st_max_perm_lsn_fid, &rep_stat_class, "st_max_perm_lsn", "L" DB_PKG "LogSequenceNumber;" }, { &rep_stat_st_next_pg_fid, &rep_stat_class, "st_next_pg", "I" }, { &rep_stat_st_waiting_pg_fid, &rep_stat_class, "st_waiting_pg", "I" }, { &rep_stat_st_dupmasters_fid, &rep_stat_class, "st_dupmasters", "I" }, { &rep_stat_st_env_id_fid, &rep_stat_class, "st_env_id", "I" }, { &rep_stat_st_env_priority_fid, &rep_stat_class, "st_env_priority", "I" }, { &rep_stat_st_bulk_fills_fid, &rep_stat_class, "st_bulk_fills", "J" }, { &rep_stat_st_bulk_overflows_fid, &rep_stat_class, "st_bulk_overflows", "J" }, { &rep_stat_st_bulk_records_fid, &rep_stat_class, "st_bulk_records", "J" }, { &rep_stat_st_bulk_transfers_fid, &rep_stat_class, "st_bulk_transfers", "J" }, { &rep_stat_st_client_rerequests_fid, &rep_stat_class, "st_client_rerequests", "J" }, { &rep_stat_st_client_svc_req_fid, &rep_stat_class, "st_client_svc_req", "J" }, { &rep_stat_st_client_svc_miss_fid, &rep_stat_class, "st_client_svc_miss", "J" }, { &rep_stat_st_gen_fid, &rep_stat_class, "st_gen", "I" }, { &rep_stat_st_egen_fid, &rep_stat_class, "st_egen", "I" }, { &rep_stat_st_log_duplicated_fid, &rep_stat_class, "st_log_duplicated", "J" }, { &rep_stat_st_log_queued_max_fid, &rep_stat_class, "st_log_queued_max", "J" }, { &rep_stat_st_log_queued_total_fid, &rep_stat_class, "st_log_queued_total", "J" }, { &rep_stat_st_log_records_fid, &rep_stat_class, "st_log_records", "J" }, { &rep_stat_st_log_requested_fid, &rep_stat_class, "st_log_requested", "J" }, { &rep_stat_st_master_fid, &rep_stat_class, "st_master", "I" }, { &rep_stat_st_master_changes_fid, &rep_stat_class, "st_master_changes", "J" }, { &rep_stat_st_msgs_badgen_fid, &rep_stat_class, "st_msgs_badgen", "J" }, { &rep_stat_st_msgs_processed_fid, &rep_stat_class, "st_msgs_processed", "J" }, { &rep_stat_st_msgs_recover_fid, &rep_stat_class, "st_msgs_recover", "J" }, { &rep_stat_st_msgs_send_failures_fid, &rep_stat_class, "st_msgs_send_failures", "J" }, { &rep_stat_st_msgs_sent_fid, &rep_stat_class, "st_msgs_sent", "J" }, { &rep_stat_st_newsites_fid, &rep_stat_class, "st_newsites", "J" }, { &rep_stat_st_nsites_fid, &rep_stat_class, "st_nsites", "I" }, { &rep_stat_st_nthrottles_fid, &rep_stat_class, "st_nthrottles", "J" }, { &rep_stat_st_outdated_fid, &rep_stat_class, "st_outdated", "J" }, { &rep_stat_st_pg_duplicated_fid, &rep_stat_class, "st_pg_duplicated", "J" }, { &rep_stat_st_pg_records_fid, &rep_stat_class, "st_pg_records", "J" }, { &rep_stat_st_pg_requested_fid, &rep_stat_class, "st_pg_requested", "J" }, { &rep_stat_st_txns_applied_fid, &rep_stat_class, "st_txns_applied", "J" }, { &rep_stat_st_startsync_delayed_fid, &rep_stat_class, "st_startsync_delayed", "J" }, { &rep_stat_st_elections_fid, &rep_stat_class, "st_elections", "J" }, { &rep_stat_st_elections_won_fid, &rep_stat_class, "st_elections_won", "J" }, { &rep_stat_st_election_cur_winner_fid, &rep_stat_class, "st_election_cur_winner", "I" }, { &rep_stat_st_election_gen_fid, &rep_stat_class, "st_election_gen", "I" }, { &rep_stat_st_election_lsn_fid, &rep_stat_class, "st_election_lsn", "L" DB_PKG "LogSequenceNumber;" }, { &rep_stat_st_election_nsites_fid, &rep_stat_class, "st_election_nsites", "I" }, { &rep_stat_st_election_nvotes_fid, &rep_stat_class, "st_election_nvotes", "I" }, { &rep_stat_st_election_priority_fid, &rep_stat_class, "st_election_priority", "I" }, { &rep_stat_st_election_status_fid, &rep_stat_class, "st_election_status", "I" }, { &rep_stat_st_election_tiebreaker_fid, &rep_stat_class, "st_election_tiebreaker", "I" }, { &rep_stat_st_election_votes_fid, &rep_stat_class, "st_election_votes", "I" }, { &rep_stat_st_election_sec_fid, &rep_stat_class, "st_election_sec", "I" }, { &rep_stat_st_election_usec_fid, &rep_stat_class, "st_election_usec", "I" }, { &rep_stat_st_max_lease_sec_fid, &rep_stat_class, "st_max_lease_sec", "I" }, { &rep_stat_st_max_lease_usec_fid, &rep_stat_class, "st_max_lease_usec", "I" }, { &repmgr_stat_st_perm_failed_fid, &repmgr_stat_class, "st_perm_failed", "J" }, { &repmgr_stat_st_msgs_queued_fid, &repmgr_stat_class, "st_msgs_queued", "J" }, { &repmgr_stat_st_msgs_dropped_fid, &repmgr_stat_class, "st_msgs_dropped", "J" }, { &repmgr_stat_st_connection_drop_fid, &repmgr_stat_class, "st_connection_drop", "J" }, { &repmgr_stat_st_connect_fail_fid, &repmgr_stat_class, "st_connect_fail", "J" }, { &seq_stat_st_wait_fid, &seq_stat_class, "st_wait", "J" }, { &seq_stat_st_nowait_fid, &seq_stat_class, "st_nowait", "J" }, { &seq_stat_st_current_fid, &seq_stat_class, "st_current", "J" }, { &seq_stat_st_value_fid, &seq_stat_class, "st_value", "J" }, { &seq_stat_st_last_value_fid, &seq_stat_class, "st_last_value", "J" }, { &seq_stat_st_min_fid, &seq_stat_class, "st_min", "J" }, { &seq_stat_st_max_fid, &seq_stat_class, "st_max", "J" }, { &seq_stat_st_cache_size_fid, &seq_stat_class, "st_cache_size", "I" }, { &seq_stat_st_flags_fid, &seq_stat_class, "st_flags", "I" }, { &txn_stat_st_nrestores_fid, &txn_stat_class, "st_nrestores", "I" }, { &txn_stat_st_last_ckp_fid, &txn_stat_class, "st_last_ckp", "L" DB_PKG "LogSequenceNumber;" }, { &txn_stat_st_time_ckp_fid, &txn_stat_class, "st_time_ckp", "J" }, { &txn_stat_st_last_txnid_fid, &txn_stat_class, "st_last_txnid", "I" }, { &txn_stat_st_maxtxns_fid, &txn_stat_class, "st_maxtxns", "I" }, { &txn_stat_st_naborts_fid, &txn_stat_class, "st_naborts", "J" }, { &txn_stat_st_nbegins_fid, &txn_stat_class, "st_nbegins", "J" }, { &txn_stat_st_ncommits_fid, &txn_stat_class, "st_ncommits", "J" }, { &txn_stat_st_nactive_fid, &txn_stat_class, "st_nactive", "I" }, { &txn_stat_st_nsnapshot_fid, &txn_stat_class, "st_nsnapshot", "I" }, { &txn_stat_st_maxnactive_fid, &txn_stat_class, "st_maxnactive", "I" }, { &txn_stat_st_maxnsnapshot_fid, &txn_stat_class, "st_maxnsnapshot", "I" }, { &txn_stat_st_txnarray_fid, &txn_stat_class, "st_txnarray", "[L" DB_PKG "TransactionStats$Active;" }, { &txn_stat_st_region_wait_fid, &txn_stat_class, "st_region_wait", "J" }, { &txn_stat_st_region_nowait_fid, &txn_stat_class, "st_region_nowait", "J" }, { &txn_stat_st_regsize_fid, &txn_stat_class, "st_regsize", "I" }, { &txn_active_txnid_fid, &txn_active_class, "txnid", "I" }, { &txn_active_parentid_fid, &txn_active_class, "parentid", "I" }, { &txn_active_pid_fid, &txn_active_class, "pid", "I" }, { &txn_active_lsn_fid, &txn_active_class, "lsn", "L" DB_PKG "LogSequenceNumber;" }, { &txn_active_read_lsn_fid, &txn_active_class, "read_lsn", "L" DB_PKG "LogSequenceNumber;" }, { &txn_active_mvcc_ref_fid, &txn_active_class, "mvcc_ref", "I" }, { &txn_active_status_fid, &txn_active_class, "status", "I" }, { &txn_active_gid_fid, &txn_active_class, "gid", "[B" }, { &txn_active_name_fid, &txn_active_class, "name", "Ljava/lang/String;" }, /* END-STAT-FIELDS */ { &repmgr_siteinfo_status_fid, &repmgr_siteinfo_class, "status", "I" } }; const struct { jmethodID *mid; jclass *cl; const char *name; const char *sig; } all_methods[] = { { &dbenv_construct, &dbenv_class, "<init>", "(JZ)V" }, { &dbt_construct, &dbt_class, "<init>", "()V" }, { &dblsn_construct, &dblsn_class, "<init>", "(II)V" }, { &dbpreplist_construct, &dbpreplist_class, "<init>", "(L" DB_PKG "internal/DbTxn;[B)V" }, { &dbtxn_construct, &dbtxn_class, "<init>", "(JZ)V" }, { &bt_stat_construct, &bt_stat_class, "<init>", "()V" }, { &get_err_msg_method, &dbenv_class, "get_err_msg", "(Ljava/lang/String;)Ljava/lang/String;" }, { &h_stat_construct, &h_stat_class, "<init>", "()V" }, { &lock_stat_construct, &lock_stat_class, "<init>", "()V" }, { &log_stat_construct, &log_stat_class, "<init>", "()V" }, { &mpool_stat_construct, &mpool_stat_class, "<init>", "()V" }, { &mpool_fstat_construct, &mpool_fstat_class, "<init>", "()V" }, { &mutex_stat_construct, &mutex_stat_class, "<init>", "()V" }, { &qam_stat_construct, &qam_stat_class, "<init>", "()V" }, { &rep_stat_construct, &rep_stat_class, "<init>", "()V" }, { &repmgr_stat_construct, &repmgr_stat_class, "<init>", "()V" }, { &seq_stat_construct, &seq_stat_class, "<init>", "()V" }, { &txn_stat_construct, &txn_stat_class, "<init>", "()V" }, { &txn_active_construct, &txn_active_class, "<init>", "()V" }, { &rephost_construct, &rephost_class, "<init>", "(Ljava/lang/String;I)V" }, { &repmgr_siteinfo_construct, &repmgr_siteinfo_class, "<init>", "(L" DB_PKG "ReplicationHostAddress;I)V" }, { &dbex_construct, &dbex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &deadex_construct, &deadex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &lockex_construct, &lockex_class, "<init>", "(Ljava/lang/String;IIL" DB_PKG "DatabaseEntry;L" DB_PKG "internal/DbLock;IL" DB_PKG "internal/DbEnv;)V" }, { &memex_construct, &memex_class, "<init>", "(Ljava/lang/String;L" DB_PKG "DatabaseEntry;IL" DB_PKG "internal/DbEnv;)V" }, { &memex_update_method, &memex_class, "updateDatabaseEntry", "(L" DB_PKG "DatabaseEntry;)V" }, { &repdupmasterex_construct, &repdupmasterex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &rephandledeadex_construct, &rephandledeadex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &repholdelectionex_construct, &repholdelectionex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &repjoinfailex_construct, &repjoinfailex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &repleaseexpiredex_construct, &repleaseexpiredex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &repleasetimeoutex_construct, &repleasetimeoutex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &replockoutex_construct, &replockoutex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &repunavailex_construct, &repunavailex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &runrecex_construct, &runrecex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &versionex_construct, &versionex_class, "<init>", "(Ljava/lang/String;IL" DB_PKG "internal/DbEnv;)V" }, { &filenotfoundex_construct, &filenotfoundex_class, "<init>", "(Ljava/lang/String;)V" }, { &illegalargex_construct, &illegalargex_class, "<init>", "(Ljava/lang/String;)V" }, { &outofmemerr_construct, &outofmemerr_class, "<init>", "(Ljava/lang/String;)V" }, { &lock_construct, &lock_class, "<init>", "(JZ)V" }, { &app_dispatch_method, &dbenv_class, "handle_app_dispatch", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "LogSequenceNumber;I)I" }, { &panic_event_notify_method, &dbenv_class, "handle_panic_event_notify", "()V" }, { &rep_client_event_notify_method, &dbenv_class, "handle_rep_client_event_notify", "()V" }, { &rep_elected_event_notify_method, &dbenv_class, "handle_rep_elected_event_notify" ,"()V" }, { &rep_master_event_notify_method, &dbenv_class, "handle_rep_master_event_notify", "()V" }, { &rep_new_master_event_notify_method, &dbenv_class, "handle_rep_new_master_event_notify", "(I)V" }, { &rep_perm_failed_event_notify_method, &dbenv_class, "handle_rep_perm_failed_event_notify", "()V" }, { &rep_startup_done_event_notify_method, &dbenv_class, "handle_rep_startup_done_event_notify", "()V" }, { &write_failed_event_notify_method, &dbenv_class, "handle_write_failed_event_notify", "(I)V" }, { &env_feedback_method, &dbenv_class, "handle_env_feedback", "(II)V" }, { &errcall_method, &dbenv_class, "handle_error", "(Ljava/lang/String;)V" }, { &msgcall_method, &dbenv_class, "handle_message", "(Ljava/lang/String;)V" }, { &paniccall_method, &dbenv_class, "handle_panic", "(L" DB_PKG "DatabaseException;)V" }, { &rep_transport_method, &dbenv_class, "handle_rep_transport", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "LogSequenceNumber;II)I" }, { &append_recno_method, &db_class, "handle_append_recno", "(L" DB_PKG "DatabaseEntry;I)V" }, { &bt_compare_method, &db_class, "handle_bt_compare", "([B[B)I" }, { &bt_compress_method, &db_class, "handle_bt_compress", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;)I" }, { &bt_decompress_method, &db_class, "handle_bt_decompress", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;)I" }, { &bt_prefix_method, &db_class, "handle_bt_prefix", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;)I" }, { &db_feedback_method, &db_class, "handle_db_feedback", "(II)V" }, { &dup_compare_method, &db_class, "handle_dup_compare", "([B[B)I" }, { &foreignkey_nullify_method, &db_class, "handle_foreignkey_nullify", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;)Z" }, { &h_compare_method, &db_class, "handle_h_compare", "([B[B)I" }, { &h_hash_method, &db_class, "handle_h_hash", "([BI)I" }, { &partition_method, &db_class, "handle_partition", "(L" DB_PKG "DatabaseEntry;)I" }, { &seckey_create_method, &db_class, "handle_seckey_create", "(L" DB_PKG "DatabaseEntry;L" DB_PKG "DatabaseEntry;)[L" DB_PKG "DatabaseEntry;" }, { &outputstream_write_method, &outputstream_class, "write", "([BII)V" } }; #define NELEM(x) (sizeof (x) / sizeof (x[0])) SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_initialize( JNIEnv *jenv, jclass clazz) { jclass cl; unsigned int i, j; COMPQUIET(clazz, NULL); if ((*jenv)->GetJavaVM(jenv, &javavm) != 0) { __db_errx(NULL, "Cannot get Java VM"); return; } for (i = 0; i < NELEM(all_classes); i++) { cl = (*jenv)->FindClass(jenv, all_classes[i].name); if (cl == NULL) { fprintf(stderr, "Failed to load class %s - check CLASSPATH\n", all_classes[i].name); return; } /* * Wrap classes in GlobalRefs so we keep the reference between * calls. */ *all_classes[i].cl = (jclass)(*jenv)->NewGlobalRef(jenv, cl); if (*all_classes[i].cl == NULL) { fprintf(stderr, "Failed to create a global reference for %s\n", all_classes[i].name); return; } } /* Get field IDs */ for (i = 0; i < NELEM(all_fields); i++) { *all_fields[i].fid = (*jenv)->GetFieldID(jenv, *all_fields[i].cl, all_fields[i].name, all_fields[i].sig); if (*all_fields[i].fid == NULL) { fprintf(stderr, "Failed to look up field %s with sig %s\n", all_fields[i].name, all_fields[i].sig); return; } } /* Get method IDs */ for (i = 0; i < NELEM(all_methods); i++) { *all_methods[i].mid = (*jenv)->GetMethodID(jenv, *all_methods[i].cl, all_methods[i].name, all_methods[i].sig); if (*all_methods[i].mid == NULL) { for (j = 0; j < NELEM(all_classes); j++) if (all_methods[i].cl == all_classes[j].cl) break; fprintf(stderr, "Failed to look up method %s.%s with sig %s\n", all_classes[j].name, all_methods[i].name, all_methods[i].sig); return; } } } static JNIEnv *__dbj_get_jnienv(int *needDetach) { /* * Note: Different versions of the JNI disagree on the signature for * AttachCurrentThreadAsDaemon. The most recent documentation seems to * say that (JNIEnv **) is correct, but newer JNIs seem to use * (void **), oddly enough. */ #ifdef JNI_VERSION_1_2 void *jenv = 0; #else JNIEnv *jenv = 0; #endif *needDetach = 0; if ((*javavm)->GetEnv(javavm, &jenv, JNI_VERSION_1_2) == JNI_OK) return ((JNIEnv *)jenv); /* * This should always succeed, as we are called via some Java activity. * I think therefore I am (a thread). */ if ((*javavm)->AttachCurrentThread(javavm, &jenv, 0) != 0) return (0); *needDetach = 1; return ((JNIEnv *)jenv); } static void __dbj_detach() { (void)(*javavm)->DetachCurrentThread(javavm); } static jobject __dbj_wrap_DB_LSN(JNIEnv *jenv, DB_LSN *lsn) { return (*jenv)->NewObject(jenv, dblsn_class, dblsn_construct, lsn->file, lsn->offset); } /* * Macros to find the Java DbEnv object for methods in various classes. * Note that "arg1" is from the code SWIG generates for the "this"/"self". */ #define JDBENV (arg1 ? (jobject)DB_ENV_INTERNAL(arg1) : NULL) #define DB2JDBENV ((jobject)DB_ENV_INTERNAL(arg1->dbenv)) #define DBC2JDBENV ((jobject)DB_ENV_INTERNAL(arg1->dbp->dbenv)) #define TXN2JDBENV ((jobject)DB_ENV_INTERNAL(arg1->mgrp->env->dbenv)) static jthrowable __dbj_get_except(JNIEnv *jenv, int err, const char *msg, jobject obj, jobject jdbenv) { jobject jmsg; if (msg == NULL) msg = db_strerror(err); jmsg = (*jenv)->NewStringUTF(jenv, msg); /* Retrieve error message logged by DB */ if (jdbenv != NULL) { jmsg = (jstring) (*jenv)->CallNonvirtualObjectMethod(jenv, jdbenv, dbenv_class, get_err_msg_method, jmsg); } switch (err) { case EINVAL: return (jthrowable)(*jenv)->NewObject(jenv, illegalargex_class, illegalargex_construct, jmsg); case ENOENT: return (jthrowable)(*jenv)->NewObject(jenv, filenotfoundex_class, filenotfoundex_construct, jmsg); case ENOMEM: return (jthrowable)(*jenv)->NewObject(jenv, outofmemerr_class, outofmemerr_construct, jmsg); case DB_BUFFER_SMALL: return (jthrowable)(*jenv)->NewObject(jenv, memex_class, memex_construct, jmsg, obj, err, jdbenv); case DB_REP_DUPMASTER: return (jthrowable)(*jenv)->NewObject(jenv, repdupmasterex_class, repdupmasterex_construct, jmsg, err, jdbenv); case DB_REP_HANDLE_DEAD: return (jthrowable)(*jenv)->NewObject(jenv, rephandledeadex_class, rephandledeadex_construct, jmsg, err, jdbenv); case DB_REP_HOLDELECTION: return (jthrowable)(*jenv)->NewObject(jenv, repholdelectionex_class, repholdelectionex_construct, jmsg, err, jdbenv); case DB_REP_JOIN_FAILURE: return (jthrowable)(*jenv)->NewObject(jenv, repjoinfailex_class, repjoinfailex_construct, jmsg, err, jdbenv); case DB_REP_LEASE_EXPIRED: return (jthrowable)(*jenv)->NewObject(jenv, repleaseexpiredex_class, repleaseexpiredex_construct, jmsg, err, jdbenv); case DB_REP_LEASE_TIMEOUT: return (jthrowable)(*jenv)->NewObject(jenv, repleasetimeoutex_class, repleasetimeoutex_construct, jmsg, err, jdbenv); case DB_REP_LOCKOUT: return (jthrowable)(*jenv)->NewObject(jenv, replockoutex_class, replockoutex_construct, jmsg, err, jdbenv); case DB_REP_UNAVAIL: return (jthrowable)(*jenv)->NewObject(jenv, repunavailex_class, repunavailex_construct, jmsg, err, jdbenv); case DB_RUNRECOVERY: return (jthrowable)(*jenv)->NewObject(jenv, runrecex_class, runrecex_construct, jmsg, err, jdbenv); case DB_LOCK_DEADLOCK: return (jthrowable)(*jenv)->NewObject(jenv, deadex_class, deadex_construct, jmsg, err, jdbenv); case DB_LOCK_NOTGRANTED: return (jthrowable)(*jenv)->NewObject(jenv, lockex_class, lockex_construct, jmsg, err, 0, NULL, NULL, 0, jdbenv); case DB_VERSION_MISMATCH: return (jthrowable)(*jenv)->NewObject(jenv, versionex_class, versionex_construct, jmsg, err, jdbenv); default: return (jthrowable)(*jenv)->NewObject(jenv, dbex_class, dbex_construct, jmsg, err, jdbenv); } } static int __dbj_throw(JNIEnv *jenv, int err, const char *msg, jobject obj, jobject jdbenv) { jthrowable t; /* If an exception is pending, ignore requests to throw a new one. */ if ((*jenv)->ExceptionOccurred(jenv) == NULL) { t = __dbj_get_except(jenv, err, msg, obj, jdbenv); if (t == NULL) { /* * This is a problem - something went wrong creating an * exception. We have to assume there is an exception * created by the JVM that is pending as a result * (e.g., OutOfMemoryError), but we don't want to lose * this error, so we just call __db_errx here. */ if (msg == NULL) msg = db_strerror(err); __db_errx(NULL, "Couldn't create exception for: '%s'", msg); } else (*jenv)->Throw(jenv, t); } return (err); } typedef struct __dbt_locked { JNIEnv *jenv; jobject jdbt; DBT dbt; jobject jdata_nio; jbyteArray jarr; jint offset; int reuse; u_int32_t orig_size; jsize array_len; } DBT_LOCKED; static int __dbj_dbt_memcopy(DBT *dbt, u_int32_t offset, void *buf, u_int32_t size, u_int32_t flags) { DBT_LOCKED *ldbt = dbt->app_data; JNIEnv *jenv = ldbt->jenv; if (size == 0) return (0); else if (!F_ISSET(dbt, DB_DBT_USERCOPY)) { /* * For simplicity, the Java API calls this function directly, * so it needs to work with regular DBTs. */ switch (flags) { case DB_USERCOPY_GETDATA: memcpy(buf, (u_int8_t *)dbt->data + offset, size); return (0); case DB_USERCOPY_SETDATA: memcpy((u_int8_t *)dbt->data + offset, buf, size); return (0); default: return (EINVAL); } } switch (flags) { case DB_USERCOPY_GETDATA: (*jenv)->GetByteArrayRegion(jenv, ldbt->jarr, ldbt->offset + offset, size, buf); break; case DB_USERCOPY_SETDATA: /* * Check whether this is the first time through the callback by relying * on the offset being zero. */ if (offset == 0 && (!ldbt->reuse || (jsize)(ldbt->offset + dbt->size) > ldbt->array_len)) { if (ldbt->jarr != NULL) (*jenv)->DeleteLocalRef(jenv, ldbt->jarr); ldbt->jarr = (*jenv)->NewByteArray(jenv, (jsize)dbt->size); if (ldbt->jarr == NULL) return (ENOMEM); (*jenv)->SetObjectField(jenv, ldbt->jdbt, dbt_data_fid, ldbt->jarr); /* We've allocated a new array, start from the beginning. */ ldbt->offset = 0; } (*jenv)->SetByteArrayRegion(jenv, ldbt->jarr, ldbt->offset + offset, size, buf); break; default: return (EINVAL); } return ((*jenv)->ExceptionOccurred(jenv) ? EINVAL : 0); } static void __dbj_dbt_copyout( JNIEnv *jenv, const DBT *dbt, jbyteArray *jarr, jobject jdbt) { jbyteArray newarr = (*jenv)->NewByteArray(jenv, (jsize)dbt->size); if (newarr == NULL) return; /* An exception is pending */ (*jenv)->SetByteArrayRegion(jenv, newarr, 0, (jsize)dbt->size, (jbyte *)dbt->data); (*jenv)->SetObjectField(jenv, jdbt, dbt_data_fid, newarr); (*jenv)->SetIntField(jenv, jdbt, dbt_offset_fid, 0); (*jenv)->SetIntField(jenv, jdbt, dbt_size_fid, (jint)dbt->size); if (jarr != NULL) *jarr = newarr; else (*jenv)->DeleteLocalRef(jenv, newarr); } static int __dbj_dbt_copyin( JNIEnv *jenv, DBT_LOCKED *ldbt, DBT **dbtp, jobject jdbt, int allow_null) { DBT *dbt; jlong capacity; memset(ldbt, 0, sizeof (*ldbt)); ldbt->jenv = jenv; ldbt->jdbt = jdbt; if (jdbt == NULL) { if (allow_null) { *dbtp = NULL; return (0); } else { return (__dbj_throw(jenv, EINVAL, "DatabaseEntry must not be null", NULL, NULL)); } } dbt = &ldbt->dbt; if (dbtp != NULL) *dbtp = dbt; ldbt->jdata_nio = (*jenv)->GetObjectField(jenv, jdbt, dbt_data_nio_fid); if (ldbt->jdata_nio != NULL) F_SET(dbt, DB_DBT_USERMEM); else ldbt->jarr = (jbyteArray)(*jenv)->GetObjectField(jenv, jdbt, dbt_data_fid); ldbt->offset = (*jenv)->GetIntField(jenv, jdbt, dbt_offset_fid); dbt->size = (*jenv)->GetIntField(jenv, jdbt, dbt_size_fid); ldbt->orig_size = dbt->size; dbt->flags = (*jenv)->GetIntField(jenv, jdbt, dbt_flags_fid); if (F_ISSET(dbt, DB_DBT_USERMEM)) dbt->ulen = (*jenv)->GetIntField(jenv, jdbt, dbt_ulen_fid); if (F_ISSET(dbt, DB_DBT_PARTIAL)) { dbt->dlen = (*jenv)->GetIntField(jenv, jdbt, dbt_dlen_fid); dbt->doff = (*jenv)->GetIntField(jenv, jdbt, dbt_doff_fid); if ((jint)dbt->doff < 0) return (__dbj_throw(jenv, EINVAL, "DatabaseEntry doff illegal", NULL, NULL)); } /* * We don't support DB_DBT_REALLOC - map anything that's not USERMEM to * MALLOC. */ if (!F_ISSET(dbt, DB_DBT_USERMEM)) { ldbt->reuse = !F_ISSET(dbt, DB_DBT_MALLOC); F_CLR(dbt, DB_DBT_MALLOC | DB_DBT_REALLOC); } /* Verify parameters before allocating or locking data. */ if (ldbt->jdata_nio != NULL) { capacity = (*jenv)->GetDirectBufferCapacity(jenv, ldbt->jdata_nio); if (capacity > (jlong)UINT32_MAX) return (__dbj_throw(jenv, EINVAL, "DirectBuffer may not be larger than 4GB", NULL, NULL)); ldbt->array_len = (u_int32_t)capacity; } else if (ldbt->jarr == NULL) { /* * Some code makes the assumption that if a DBT's size or ulen * is non-zero, there is data to copy from dbt->data. * * Clean up the dbt fields so we don't run into trouble. * (Note that doff, dlen, and flags all may contain * meaningful values.) */ dbt->data = NULL; ldbt->array_len = ldbt->offset = dbt->size = dbt->ulen = 0; } else ldbt->array_len = (*jenv)->GetArrayLength(jenv, ldbt->jarr); if (F_ISSET(dbt, DB_DBT_USERMEM)) { if (ldbt->offset < 0) return (__dbj_throw(jenv, EINVAL, "offset cannot be negative", NULL, NULL)); if (dbt->size > dbt->ulen) return (__dbj_throw(jenv, EINVAL, "size must be less than or equal to ulen", NULL, NULL)); if ((jsize)(ldbt->offset + dbt->ulen) > ldbt->array_len) return (__dbj_throw(jenv, EINVAL, "offset + ulen greater than array length", NULL, NULL)); } if (ldbt->jdata_nio) { dbt->data = (*jenv)->GetDirectBufferAddress(jenv, ldbt->jdata_nio); dbt->data = (u_int8_t *)dbt->data + ldbt->offset; } else if (F_ISSET(dbt, DB_DBT_USERMEM)) { if (ldbt->jarr != NULL && (dbt->data = (*jenv)->GetByteArrayElements(jenv, ldbt->jarr, NULL)) == NULL) return (EINVAL); /* an exception will be pending */ dbt->data = (u_int8_t *)dbt->data + ldbt->offset; } else F_SET(dbt, DB_DBT_USERCOPY); dbt->app_data = ldbt; return (0); } static void __dbj_dbt_release( JNIEnv *jenv, jobject jdbt, DBT *dbt, DBT_LOCKED *ldbt) { jthrowable t; if (dbt == NULL) return; if (dbt->size != ldbt->orig_size) (*jenv)->SetIntField(jenv, jdbt, dbt_size_fid, (jint)dbt->size); if (F_ISSET(dbt, DB_DBT_USERMEM)) { if (ldbt->jarr != NULL) (*jenv)->ReleaseByteArrayElements(jenv, ldbt->jarr, (jbyte *)dbt->data - ldbt->offset, 0); if (dbt->size > dbt->ulen && (t = (*jenv)->ExceptionOccurred(jenv)) != NULL && (*jenv)->IsInstanceOf(jenv, t, memex_class)) { (*jenv)->CallNonvirtualVoidMethod(jenv, t, memex_class, memex_update_method, jdbt); /* * We have to rethrow the exception because calling * into Java clears it. */ (*jenv)->Throw(jenv, t); } } } struct __dbj_verify_data { JNIEnv *jenv; jobject streamobj; jbyteArray bytes; int nbytes; }; static int __dbj_verify_callback(void *handle, const void *str_arg) { char *str; struct __dbj_verify_data *vd; int len; JNIEnv *jenv; str = (char *)str_arg; vd = (struct __dbj_verify_data *)handle; jenv = vd->jenv; len = (int)strlen(str) + 1; if (len > vd->nbytes) { vd->nbytes = len; if (vd->bytes != NULL) (*jenv)->DeleteLocalRef(jenv, vd->bytes); if ((vd->bytes = (*jenv)->NewByteArray(jenv, (jsize)len)) == NULL) return (ENOMEM); } if (vd->bytes != NULL) { (*jenv)->SetByteArrayRegion(jenv, vd->bytes, 0, (jsize)len, (jbyte*)str); (*jenv)->CallVoidMethod(jenv, vd->streamobj, outputstream_write_method, vd->bytes, 0, len - 1); } if ((*jenv)->ExceptionOccurred(jenv) != NULL) return (EIO); return (0); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1vec(JNIEnv *jenv, jclass jcls, jlong jdbenvp, jobject jdbenv, jint locker, jint flags, jobjectArray list, jint offset, jint count) { DB_ENV *dbenv; DB_LOCKREQ *lockreq; DB_LOCKREQ *prereq; /* preprocessed requests */ DB_LOCKREQ *failedreq; DB_LOCK *lockp; DBT_LOCKED *locked_dbts; DBT *obj; ENV *env; int err, alloc_err, i; size_t bytesize, ldbtsize; jobject jlockreq; db_lockop_t op; jobject jobj, jlock; jlong jlockp; int completed; /* * We can't easily #include "dbinc/db_ext.h" because of name * clashes, so we declare this explicitly. */ extern int __dbt_usercopy __P((ENV *, DBT *)); extern void __dbt_userfree __P((ENV *, DBT *, DBT *, DBT *)); COMPQUIET(jcls, NULL); dbenv = *(DB_ENV **)(void *)&jdbenvp; env = dbenv->env; locked_dbts = NULL; lockreq = NULL; if (dbenv == NULL) { __dbj_throw(jenv, EINVAL, "null object", NULL, jdbenv); return; } if ((*jenv)->GetArrayLength(jenv, list) < offset + count) { __dbj_throw(jenv, EINVAL, "DbEnv.lock_vec array not large enough", NULL, jdbenv); return; } bytesize = sizeof(DB_LOCKREQ) * count; if ((err = __os_malloc(env, bytesize, &lockreq)) != 0) { __dbj_throw(jenv, err, NULL, NULL, jdbenv); return; } memset(lockreq, 0, bytesize); ldbtsize = sizeof(DBT_LOCKED) * count; if ((err = __os_malloc(env, ldbtsize, &locked_dbts)) != 0) { __dbj_throw(jenv, err, NULL, NULL, jdbenv); goto err; } memset(locked_dbts, 0, ldbtsize); prereq = &lockreq[0]; /* fill in the lockreq array */ for (i = 0, prereq = &lockreq[0]; i < count; i++, prereq++) { jlockreq = (*jenv)->GetObjectArrayElement(jenv, list, offset + i); if (jlockreq == NULL) { __dbj_throw(jenv, EINVAL, "DbEnv.lock_vec list entry is null", NULL, jdbenv); goto err; } op = (db_lockop_t)(*jenv)->GetIntField( jenv, jlockreq, lockreq_op_fid); prereq->op = op; switch (op) { case DB_LOCK_GET_TIMEOUT: /* Needed: mode, timeout, obj. Returned: lock. */ prereq->op = (db_lockop_t)(*jenv)->GetIntField( jenv, jlockreq, lockreq_timeout_fid); /* FALLTHROUGH */ case DB_LOCK_GET: /* Needed: mode, obj. Returned: lock. */ prereq->mode = (db_lockmode_t)(*jenv)->GetIntField( jenv, jlockreq, lockreq_modeflag_fid); jobj = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_obj_fid); if ((err = __dbj_dbt_copyin(jenv, &locked_dbts[i], &obj, jobj, 0)) != 0 || (err = __dbt_usercopy(env, obj)) != 0) goto err; prereq->obj = obj; break; case DB_LOCK_PUT: /* Needed: lock. Ignored: mode, obj. */ jlock = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_lock_fid); if (jlock == NULL || (jlockp = (*jenv)->GetLongField(jenv, jlock, lock_cptr_fid)) == 0L) { __dbj_throw(jenv, EINVAL, "LockRequest lock field is NULL", NULL, jdbenv); goto err; } lockp = *(DB_LOCK **)(void *)&jlockp; prereq->lock = *lockp; break; case DB_LOCK_PUT_ALL: case DB_LOCK_TIMEOUT: /* Needed: (none). Ignored: lock, mode, obj. */ break; case DB_LOCK_PUT_OBJ: /* Needed: obj. Ignored: lock, mode. */ jobj = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_obj_fid); if ((err = __dbj_dbt_copyin(jenv, &locked_dbts[i], &obj, jobj, 0)) != 0 || (err = __dbt_usercopy(env, obj)) != 0) goto err; prereq->obj = obj; break; default: __dbj_throw(jenv, EINVAL, "DbEnv.lock_vec bad op value", NULL, jdbenv); goto err; } } err = dbenv->lock_vec(dbenv, (u_int32_t)locker, (u_int32_t)flags, lockreq, count, &failedreq); if (err == 0) completed = count; else completed = (int)(failedreq - lockreq); /* do post processing for any and all requests that completed */ for (i = 0; i < completed; i++) { op = lockreq[i].op; if (op == DB_LOCK_PUT) { /* * After a successful put, the DbLock can no longer be * used, so we release the storage related to it. */ jlockreq = (*jenv)->GetObjectArrayElement(jenv, list, i + offset); jlock = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_lock_fid); jlockp = (*jenv)->GetLongField(jenv, jlock, lock_cptr_fid); lockp = *(DB_LOCK **)(void *)&jlockp; __os_free(NULL, lockp); (*jenv)->SetLongField(jenv, jlock, lock_cptr_fid, (jlong)0); } else if (op == DB_LOCK_GET_TIMEOUT || op == DB_LOCK_GET) { /* * Store the lock that was obtained. We need to create * storage for it since the lockreq array only exists * during this method call. */ if ((alloc_err = __os_malloc(env, sizeof(DB_LOCK), &lockp)) != 0) { __dbj_throw(jenv, alloc_err, NULL, NULL, jdbenv); goto err; } *lockp = lockreq[i].lock; *(DB_LOCK **)(void *)&jlockp = lockp; jlockreq = (*jenv)->GetObjectArrayElement(jenv, list, i + offset); jlock = (*jenv)->NewObject(jenv, lock_class, lock_construct, jlockp, JNI_TRUE); if (jlock == NULL) goto err; /* An exception is pending */ (*jenv)->SetLongField(jenv, jlock, lock_cptr_fid, jlockp); (*jenv)->SetObjectField(jenv, jlockreq, lockreq_lock_fid, jlock); } } /* If one of the locks was not granted, build the exception now. */ if (err == DB_LOCK_NOTGRANTED && i < count) { jlockreq = (*jenv)->GetObjectArrayElement(jenv, list, i + offset); jobj = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_obj_fid); jlock = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_lock_fid); (*jenv)->Throw(jenv, (*jenv)->NewObject(jenv, lockex_class, lockex_construct, (*jenv)->NewStringUTF(jenv, "DbEnv.lock_vec incomplete"), lockreq[i].op, lockreq[i].mode, jobj, jlock, i, jdbenv)); } else if (err != 0) __dbj_throw(jenv, err, NULL, NULL, jdbenv); err: for (i = 0, prereq = &lockreq[0]; i < count; i++, prereq++) if (prereq->op == DB_LOCK_GET_TIMEOUT || prereq->op == DB_LOCK_GET || prereq->op == DB_LOCK_PUT_OBJ) { jlockreq = (*jenv)->GetObjectArrayElement(jenv, list, i + offset); jobj = (*jenv)->GetObjectField(jenv, jlockreq, lockreq_obj_fid); __dbt_userfree(env, prereq->obj, NULL, NULL); __dbj_dbt_release(jenv, jobj, prereq->obj, &locked_dbts[i]); } if (locked_dbts != NULL) __os_free(env, locked_dbts); if (lockreq != NULL) __os_free(env, lockreq); } /* * These macros are used by code generated by the s_java script. */ #define JAVADB_STAT_INT(jenv, jobj, fid, statp, name) \ (*jenv)->SetIntField(jenv, jobj, fid, (jint)statp->name) #define JAVADB_STAT_STRING(jenv, jobj, fid, statp, name) \ (*jenv)->SetObjectField(jenv, jobj, fid, \ (*jenv)->NewStringUTF(jenv, statp->name)) #define JAVADB_STAT_LSN(jenv, jobj, fid, statp, name) \ (*jenv)->SetObjectField(jenv, jobj, fid, \ __dbj_wrap_DB_LSN(jenv, &statp->name)) #define JAVADB_STAT_LONG(jenv, jobj, fid, statp, name) \ (*jenv)->SetLongField(jenv, jobj, fid, \ (jlong)statp->name) #define JAVADB_STAT_GID(jenv, jobj, fid, statp, name) { \ jobject jarr = \ (*jenv)->NewByteArray(jenv, (jsize)DB_GID_SIZE); \ (*jenv)->SetByteArrayRegion(jenv, jarr, \ 0, (jsize)DB_GID_SIZE, (jbyte *)statp->name); \ (*jenv)->SetObjectField(jenv, jobj, fid, jarr); \ } /* * We build the active list separately. */ #define JAVADB_STAT_ACTIVE(jenv, cl, jobj, statp, name) \ do {} while(0) #include "java_stat_auto.c" static void __dbj_error(const DB_ENV *dbenv, const char *prefix, const char *msg) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); jobject jmsg; COMPQUIET(prefix, NULL); if (jdbenv != NULL){ jmsg = (*jenv)->NewStringUTF(jenv, msg); (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, errcall_method, jmsg); (*jenv)->DeleteLocalRef(jenv, jmsg); } if (detach) __dbj_detach(); } static void __dbj_env_feedback(DB_ENV *dbenv, int opcode, int percent) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); if (jdbenv != NULL) (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, env_feedback_method, opcode, percent); if (detach) __dbj_detach(); } static void __dbj_message(const DB_ENV *dbenv, const char *msg) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); jobject jmsg; if (jdbenv != NULL){ jmsg = (*jenv)->NewStringUTF(jenv, msg); (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, msgcall_method, jmsg); (*jenv)->DeleteLocalRef(jenv, jmsg); } if (detach) __dbj_detach(); } static void __dbj_panic(DB_ENV *dbenv, int err) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); if (jdbenv != NULL) (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, paniccall_method, __dbj_get_except(jenv, err, NULL, NULL, jdbenv)); if (detach) __dbj_detach(); } static int __dbj_app_dispatch(DB_ENV *dbenv, DBT *dbt, DB_LSN *lsn, db_recops recops) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); jobject jdbt, jlsn; jbyteArray jdbtarr; int ret; if (jdbenv == NULL) { ret = EINVAL; goto err; } jdbt = (*jenv)->NewObject(jenv, dbt_class, dbt_construct); __dbj_dbt_copyout(jenv, dbt, &jdbtarr, jdbt); if (jdbt == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } jlsn = (lsn == NULL) ? NULL : __dbj_wrap_DB_LSN(jenv, lsn); ret = (*jenv)->CallNonvirtualIntMethod(jenv, jdbenv, dbenv_class, app_dispatch_method, jdbt, jlsn, recops); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; } (*jenv)->DeleteLocalRef(jenv, jdbtarr); (*jenv)->DeleteLocalRef(jenv, jdbt); if (jlsn != NULL) (*jenv)->DeleteLocalRef(jenv, jlsn); err: if (detach) __dbj_detach(); return (ret); } static void __dbj_event_notify(DB_ENV *dbenv, u_int32_t event_id, void * info) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); if (jdbenv == NULL) goto done; switch (event_id) { case DB_EVENT_PANIC: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, panic_event_notify_method); break; case DB_EVENT_REP_CLIENT: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_client_event_notify_method); break; case DB_EVENT_REP_ELECTED: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_elected_event_notify_method); break; case DB_EVENT_REP_MASTER: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_master_event_notify_method); break; case DB_EVENT_REP_NEWMASTER: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_new_master_event_notify_method, *(int*)info); break; case DB_EVENT_REP_PERM_FAILED: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_perm_failed_event_notify_method); break; case DB_EVENT_REP_STARTUPDONE: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, rep_startup_done_event_notify_method); break; case DB_EVENT_WRITE_FAILED: (*jenv)->CallNonvirtualVoidMethod(jenv, jdbenv, dbenv_class, write_failed_event_notify_method, *(int*)info); break; default: dbenv->errx(dbenv, "Unhandled event callback in the Java API"); DB_ASSERT(dbenv->env, 0); } done: if (detach) __dbj_detach(); } static int __dbj_rep_transport(DB_ENV *dbenv, const DBT *control, const DBT *rec, const DB_LSN *lsn, int envid, u_int32_t flags) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdbenv = (jobject)DB_ENV_INTERNAL(dbenv); jobject jcontrol, jrec, jlsn; jbyteArray jcontrolarr, jrecarr; int ret; if (jdbenv == NULL) { ret = EINVAL; goto err; } jcontrol = (*jenv)->NewObject(jenv, dbt_class, dbt_construct); jrec = (*jenv)->NewObject(jenv, dbt_class, dbt_construct); if (jcontrol == NULL || jrec == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } __dbj_dbt_copyout(jenv, control, &jcontrolarr, jcontrol); __dbj_dbt_copyout(jenv, rec, &jrecarr, jrec); jlsn = (lsn == NULL) ? NULL : __dbj_wrap_DB_LSN(jenv, (DB_LSN *)lsn); if (jcontrolarr == NULL || jrecarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } ret = (*jenv)->CallNonvirtualIntMethod(jenv, jdbenv, dbenv_class, rep_transport_method, jcontrol, jrec, jlsn, envid, flags); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; } (*jenv)->DeleteLocalRef(jenv, jrecarr); (*jenv)->DeleteLocalRef(jenv, jcontrolarr); (*jenv)->DeleteLocalRef(jenv, jrec); (*jenv)->DeleteLocalRef(jenv, jcontrol); if (jlsn != NULL) (*jenv)->DeleteLocalRef(jenv, jlsn); err: if (detach) __dbj_detach(); return (ret); } static int __dbj_foreignkey_nullify(DB *db, const DBT *key, DBT *data, const DBT *skey, int *changed) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); DBT_LOCKED lresult; jobject jdb = (jobject)DB_INTERNAL(db); jobject jkey, jdata, jskey; jbyteArray jkeyarr, jdataarr, jskeyarr; jboolean jresult; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } jkey = (key->app_data != NULL) ? ((DBT_LOCKED *)key->app_data)->jdbt : (*jenv)->NewObject(jenv, dbt_class, dbt_construct); jdata = (data->app_data != NULL) ? ((DBT_LOCKED *)data->app_data)->jdbt : (*jenv)->NewObject(jenv, dbt_class, dbt_construct); jskey = (skey->app_data != NULL) ? ((DBT_LOCKED *)skey->app_data)->jdbt : (*jenv)->NewObject(jenv, dbt_class, dbt_construct); if (jkey == NULL || jdata == NULL || jskey == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } if (key->app_data == NULL) { __dbj_dbt_copyout(jenv, key, &jkeyarr, jkey); if (jkeyarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } if (data->app_data == NULL) { __dbj_dbt_copyout(jenv, data, &jdataarr, jdata); if (jdataarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } if (skey->app_data == NULL) { __dbj_dbt_copyout(jenv, skey, &jskeyarr, jskey); if (jskeyarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } jresult = (*jenv)->CallNonvirtualBooleanMethod(jenv, jdb, db_class, foreignkey_nullify_method, jkey, jdata, jskey); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } if (jresult == JNI_FALSE) *changed = ret = 0; else{ *changed = 1; /* copy jdata into data */ if ((ret = __dbj_dbt_copyin(jenv, &lresult, NULL, jdata, 0)) != 0) goto err; if (lresult.dbt.size != 0){ data->size = lresult.dbt.size; if ((ret = __os_umalloc( NULL, data->size, &data->data)) != 0) goto err; if ((ret = __dbj_dbt_memcopy(&lresult.dbt, 0, data->data, data->size, DB_USERCOPY_GETDATA)) != 0) goto err; __dbj_dbt_release(jenv, jdata, &lresult.dbt, &lresult); (*jenv)->DeleteLocalRef(jenv, lresult.jarr); F_SET(data, DB_DBT_APPMALLOC); } } err: if (key->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jkeyarr); (*jenv)->DeleteLocalRef(jenv, jkey); } if (data->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jdataarr); (*jenv)->DeleteLocalRef(jenv, jdata); } if (detach) __dbj_detach(); return ret; } static int __dbj_seckey_create(DB *db, const DBT *key, const DBT *data, DBT *result) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jkey, jdata, jresult; jobjectArray jskeys; jsize i, num_skeys; jbyteArray jkeyarr, jdataarr; DBT_LOCKED lresult; DBT *tresult; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } jkey = (key->app_data != NULL) ? ((DBT_LOCKED *)key->app_data)->jdbt : (*jenv)->NewObject(jenv, dbt_class, dbt_construct); jdata = (data->app_data != NULL) ? ((DBT_LOCKED *)data->app_data)->jdbt : (*jenv)->NewObject(jenv, dbt_class, dbt_construct); if (jkey == NULL || jdata == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } if (key->app_data == NULL) { __dbj_dbt_copyout(jenv, key, &jkeyarr, jkey); if (jkeyarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } if (data->app_data == NULL) { __dbj_dbt_copyout(jenv, data, &jdataarr, jdata); if (jdataarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } jskeys = (jobjectArray)(*jenv)->CallNonvirtualObjectMethod(jenv, jdb, db_class, seckey_create_method, jkey, jdata); if (jskeys == NULL || (num_skeys = (*jenv)->GetArrayLength(jenv, jskeys)) == 0) { ret = DB_DONOTINDEX; goto err; } else if (num_skeys == 1) { memset(result, 0, sizeof (DBT)); tresult = result; } else { if ((ret = __os_umalloc(db->env, num_skeys * sizeof (DBT), &result->data)) != 0) goto err; memset(result->data, 0, num_skeys * sizeof (DBT)); result->size = num_skeys; F_SET(result, DB_DBT_APPMALLOC | DB_DBT_MULTIPLE); tresult = (DBT *)result->data; } if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } for (i = 0; i < num_skeys; i++, tresult++) { jresult = (*jenv)->GetObjectArrayElement(jenv, jskeys, i); if ((ret = __dbj_dbt_copyin(jenv, &lresult, NULL, jresult, 0)) != 0) goto err; if (lresult.dbt.size != 0) { /* If there's data, we need to take a copy of it. */ tresult->size = lresult.dbt.size; if ((ret = __os_umalloc(NULL, tresult->size, &tresult->data)) != 0) goto err; if ((ret = __dbj_dbt_memcopy(&lresult.dbt, 0, tresult->data, tresult->size, DB_USERCOPY_GETDATA)) != 0) goto err; __dbj_dbt_release(jenv, jresult, &lresult.dbt, &lresult); (*jenv)->DeleteLocalRef(jenv, lresult.jarr); F_SET(tresult, DB_DBT_APPMALLOC); } (*jenv)->DeleteLocalRef(jenv, jresult); } err: if (key->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jkeyarr); (*jenv)->DeleteLocalRef(jenv, jkey); } if (data->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jdataarr); (*jenv)->DeleteLocalRef(jenv, jdata); } if (detach) __dbj_detach(); return (ret); } static int __dbj_append_recno(DB *db, DBT *dbt, db_recno_t recno) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jdbt; DBT_LOCKED lresult; jbyteArray jdbtarr; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } /* * The dbt we're passed will be from the application, but we can't * just reuse it, since we will have already taken a copy of the data. * Make a new DatabaseEntry object here for the callback. */ jdbt = (*jenv)->NewObject(jenv, dbt_class, dbt_construct); if (jdbt == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } __dbj_dbt_copyout(jenv, dbt, &jdbtarr, jdbt); if (jdbtarr == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } ret = 0; (*jenv)->CallNonvirtualVoidMethod(jenv, jdb, db_class, append_recno_method, jdbt, recno); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } ret = __dbj_dbt_copyin(jenv, &lresult, NULL, jdbt, 0); memset(dbt, 0, sizeof (DBT)); if (ret == 0 && lresult.dbt.size != 0) { /* If there's data, we need to take a copy of it. */ dbt->size = lresult.dbt.size; if ((ret = __os_umalloc(NULL, dbt->size, &dbt->data)) != 0) goto err; if ((ret = __dbj_dbt_memcopy(&lresult.dbt, 0, dbt->data, dbt->size, DB_USERCOPY_GETDATA)) != 0) goto err; __dbj_dbt_release(jenv, jdbt, &lresult.dbt, &lresult); (*jenv)->DeleteLocalRef(jenv, lresult.jarr); F_SET(dbt, DB_DBT_APPMALLOC); } err: (*jenv)->DeleteLocalRef(jenv, jdbtarr); (*jenv)->DeleteLocalRef(jenv, jdbt); if (detach) __dbj_detach(); return (ret); } /* * Shared by __dbj_bt_compare and __dbj_h_compare */ static int __dbj_am_compare(DB *db, const DBT *dbt1, const DBT *dbt2, jmethodID compare_method) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jbyteArray jdbtarr1, jdbtarr2; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } if (dbt1->app_data != NULL) jdbtarr1 = ((DBT_LOCKED *)dbt1->app_data)->jarr; else { jdbtarr1 = (*jenv)->NewByteArray(jenv, (jsize)dbt1->size); if (jdbtarr1 == NULL) { ret = ENOMEM; goto err; } (*jenv)->SetByteArrayRegion(jenv, jdbtarr1, 0, (jsize)dbt1->size, (jbyte *)dbt1->data); } if (dbt2->app_data != NULL) jdbtarr2 = ((DBT_LOCKED *)dbt2->app_data)->jarr; else { jdbtarr2 = (*jenv)->NewByteArray(jenv, (jsize)dbt2->size); if (jdbtarr2 == NULL) { ret = ENOMEM; goto err; } (*jenv)->SetByteArrayRegion(jenv, jdbtarr2, 0, (jsize)dbt2->size, (jbyte *)dbt2->data); } ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, compare_method, jdbtarr1, jdbtarr2); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; } err: if (dbt1->app_data == NULL) (*jenv)->DeleteLocalRef(jenv, jdbtarr1); if (dbt2->app_data == NULL) (*jenv)->DeleteLocalRef(jenv, jdbtarr2); if (detach) __dbj_detach(); return (ret); } static int __dbj_bt_compare(DB *db, const DBT *dbt1, const DBT *dbt2) { return __dbj_am_compare(db, dbt1, dbt2, bt_compare_method); } #define DBT_COPYOUT(num) \ if (dbt##num->app_data != NULL) \ jdbt##num = ((DBT_LOCKED *)dbt##num->app_data)->jdbt; \ else { \ if ((jdbt##num = (*jenv)->NewObject( \ jenv, dbt_class, dbt_construct)) == NULL) { \ ret = ENOMEM; /* An exception is pending */ \ goto err; \ } \ __dbj_dbt_copyout(jenv, dbt##num, &jdbtarr##num, jdbt##num);\ if (jdbtarr##num == NULL) { \ ret = ENOMEM; /* An exception is pending */ \ goto err; \ } \ } #define DBT_COPIED_FREE(num) \ if (dbt##num->app_data == NULL) { \ (*jenv)->DeleteLocalRef(jenv, jdbtarr##num); \ (*jenv)->DeleteLocalRef(jenv, jdbt##num); \ } #define DBT_COPYIN_DATA(num) \ ret = __dbj_dbt_copyin(jenv, &lresult, NULL, jdbt##num, 0); \ memset(dbt##num, 0, sizeof (DBT)); \ if (ret == 0 && lresult.dbt.size != 0) { \ /* If there's data, we need to take a copy of it. */ \ dbt##num->size = lresult.dbt.size; \ if ((ret = __os_umalloc( \ NULL, dbt##num->size, &dbt##num->data)) != 0) \ goto err; \ if ((ret = __dbj_dbt_memcopy(&lresult.dbt, 0, \ dbt##num->data, dbt##num->size, \ DB_USERCOPY_GETDATA)) != 0) \ goto err; \ __dbj_dbt_release(jenv, jdbt##num, &lresult.dbt, &lresult);\ (*jenv)->DeleteLocalRef(jenv, lresult.jarr); \ F_SET(dbt##num, DB_DBT_APPMALLOC); \ } static int __dbj_bt_compress(DB *db, const DBT *dbt1, const DBT *dbt2, const DBT *dbt3, const DBT *dbt4, DBT *dbt5) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jdbt1, jdbt2, jdbt3, jdbt4, jdbt5; jbyteArray jdbtarr1, jdbtarr2, jdbtarr3, jdbtarr4, jdbtarr5; DBT_LOCKED lresult; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } DBT_COPYOUT(1) DBT_COPYOUT(2) DBT_COPYOUT(3) DBT_COPYOUT(4) DBT_COPYOUT(5) ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, bt_compress_method, jdbt1, jdbt2, jdbt3, jdbt4, jdbt5); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } DBT_COPYIN_DATA(5) err: DBT_COPIED_FREE(1) DBT_COPIED_FREE(2) DBT_COPIED_FREE(3) DBT_COPIED_FREE(4) DBT_COPIED_FREE(5) if (detach) __dbj_detach(); return (ret); } static int __dbj_bt_decompress(DB *db, const DBT *dbt1, const DBT *dbt2, DBT *dbt3, DBT *dbt4, DBT *dbt5) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jdbt1, jdbt2, jdbt3, jdbt4, jdbt5; jbyteArray jdbtarr1, jdbtarr2, jdbtarr3, jdbtarr4, jdbtarr5; DBT_LOCKED lresult; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } DBT_COPYOUT(1) DBT_COPYOUT(2) DBT_COPYOUT(3) DBT_COPYOUT(4) DBT_COPYOUT(5) ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, bt_decompress_method, jdbt1, jdbt2, jdbt3, jdbt4, jdbt5); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } DBT_COPYIN_DATA(3) DBT_COPYIN_DATA(4) DBT_COPYIN_DATA(5) err: DBT_COPIED_FREE(1) DBT_COPIED_FREE(2) DBT_COPIED_FREE(3) DBT_COPIED_FREE(4) DBT_COPIED_FREE(5) if (detach) __dbj_detach(); return (ret); } static size_t __dbj_bt_prefix(DB *db, const DBT *dbt1, const DBT *dbt2) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jdbt1, jdbt2; jbyteArray jdbtarr1, jdbtarr2; int ret; if (jdb == NULL) { ret = EINVAL; goto err; } if (dbt1->app_data != NULL) jdbt1 = ((DBT_LOCKED *)dbt1->app_data)->jdbt; else { if ((jdbt1 = (*jenv)->NewObject(jenv, dbt_class, dbt_construct)) == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } __dbj_dbt_copyout(jenv, dbt1, &jdbtarr1, jdbt1); if (jdbtarr1 == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } if (dbt2->app_data != NULL) jdbt2 = ((DBT_LOCKED *)dbt2->app_data)->jdbt; else { if ((jdbt2 = (*jenv)->NewObject(jenv, dbt_class, dbt_construct)) == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } __dbj_dbt_copyout(jenv, dbt2, &jdbtarr2, jdbt2); if (jdbtarr2 == NULL) { ret = ENOMEM; /* An exception is pending */ goto err; } } ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, bt_prefix_method, jdbt1, jdbt2); err: if (dbt1->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jdbtarr1); (*jenv)->DeleteLocalRef(jenv, jdbt1); } if (dbt2->app_data == NULL) { (*jenv)->DeleteLocalRef(jenv, jdbtarr2); (*jenv)->DeleteLocalRef(jenv, jdbt2); } if (detach) __dbj_detach(); return (ret); } static int __dbj_dup_compare(DB *db, const DBT *dbt1, const DBT *dbt2) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jbyteArray jdbtarr1, jdbtarr2; int ret; if (jdb == NULL) return (EINVAL); jdbtarr1 = (*jenv)->NewByteArray(jenv, (jsize)dbt1->size); if (jdbtarr1 == NULL) return (ENOMEM); (*jenv)->SetByteArrayRegion(jenv, jdbtarr1, 0, (jsize)dbt1->size, (jbyte *)dbt1->data); jdbtarr2 = (*jenv)->NewByteArray(jenv, (jsize)dbt2->size); if (jdbtarr2 == NULL) return (ENOMEM); (*jenv)->SetByteArrayRegion(jenv, jdbtarr2, 0, (jsize)dbt2->size, (jbyte *)dbt2->data); ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, dup_compare_method, jdbtarr1, jdbtarr2); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; } (*jenv)->DeleteLocalRef(jenv, jdbtarr2); (*jenv)->DeleteLocalRef(jenv, jdbtarr1); if (detach) __dbj_detach(); return (ret); } static void __dbj_db_feedback(DB *db, int opcode, int percent) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); if (jdb != NULL) (*jenv)->CallNonvirtualVoidMethod(jenv, jdb, db_class, db_feedback_method, opcode, percent); if (detach) __dbj_detach(); } static int __dbj_h_compare(DB *db, const DBT *dbt1, const DBT *dbt2) { return __dbj_am_compare(db, dbt1, dbt2, h_compare_method); } static u_int32_t __dbj_h_hash(DB *db, const void *data, u_int32_t len) { int detach; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jbyteArray jarr = (*jenv)->NewByteArray(jenv, (jsize)len); int ret; if (jdb == NULL) return (EINVAL); if ((jarr = (*jenv)->NewByteArray(jenv, (jsize)len)) == NULL) return (ENOMEM); /* An exception is pending */ (*jenv)->SetByteArrayRegion(jenv, jarr, 0, (jsize)len, (jbyte *)data); ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, h_hash_method, jarr, len); (*jenv)->DeleteLocalRef(jenv, jarr); if (detach) __dbj_detach(); return (ret); } static u_int32_t __dbj_partition(DB *db, DBT *dbt1) { int detach, ret; JNIEnv *jenv = __dbj_get_jnienv(&detach); jobject jdb = (jobject)DB_INTERNAL(db); jobject jdbt1; jbyteArray jdbtarr1; DBT_LOCKED lresult; DBT_COPYOUT(1) ret = (int)(*jenv)->CallNonvirtualIntMethod(jenv, jdb, db_class, partition_method, jdbt1); if ((*jenv)->ExceptionOccurred(jenv)) { /* The exception will be thrown, so this could be any error. */ ret = EINVAL; goto err; } DBT_COPYIN_DATA(1) err: DBT_COPIED_FREE(1) if (detach) __dbj_detach(); return (ret); } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_initDbEnvRef0( JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { DB_ENV *self = *(DB_ENV **)(void *)&jarg1; jlong ret; COMPQUIET(jcls, NULL); COMPQUIET(jarg1_, NULL); DB_ENV_INTERNAL(self) = (void *)(*jenv)->NewGlobalRef(jenv, jarg2); *(jobject *)(void *)&ret = (jobject)DB_ENV_INTERNAL(self); return (ret); } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_initDbRef0( JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { DB *self = *(DB **)(void *)&jarg1; jlong ret; COMPQUIET(jcls, NULL); COMPQUIET(jarg1_, NULL); DB_INTERNAL(self) = (void *)(*jenv)->NewGlobalRef(jenv, jarg2); *(jobject *)(void *)&ret = (jobject)DB_INTERNAL(self); return (ret); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_deleteRef0( JNIEnv *jenv, jclass jcls, jlong jarg1) { jobject jref = *(jobject *)(void *)&jarg1; COMPQUIET(jcls, NULL); if (jref != 0L) (*jenv)->DeleteGlobalRef(jenv, jref); } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_getDbEnv0( JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { DB *self = *(DB **)(void *)&jarg1; jlong ret; COMPQUIET(jenv, NULL); COMPQUIET(jcls, NULL); COMPQUIET(jarg1_, NULL); *(DB_ENV **)(void *)&ret = self->dbenv; return (ret); } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_DbUtil_is_1big_1endian( JNIEnv *jenv, jclass clazz) { COMPQUIET(jenv, NULL); COMPQUIET(clazz, NULL); return (__db_isbigendian() ? JNI_TRUE : JNI_FALSE); } typedef int db_ret_t; typedef int int_bool; struct __db_lk_conflicts { u_int8_t *lk_conflicts; int lk_modes; }; struct __db_out_stream { void *handle; int (*callback) __P((void *, const void *)); }; struct __db_repmgr_sites { DB_REPMGR_SITE *sites; u_int32_t nsites; }; #define Db __db #define Dbc __dbc #define Dbt __db_dbt #define DbEnv __db_env #define DbLock __db_lock_u #define DbLogc __db_log_cursor #define DbLsn __db_lsn #define DbMpoolFile __db_mpoolfile #define DbSequence __db_sequence #define DbTxn __db_txn /* Suppress a compilation warning for an unused symbol */ void *unused = (void *)SWIG_JavaThrowException; SWIGINTERN struct Db *new_Db(DB_ENV *dbenv,u_int32_t flags){ DB *self = NULL; errno = db_create(&self, dbenv, flags); if (errno == 0 && dbenv == NULL) self->env->dbt_usercopy = __dbj_dbt_memcopy; return self; } SWIGINTERN db_ret_t Db_associate(struct Db *self,DB_TXN *txnid,DB *secondary,int (*callback)(DB *,DBT const *,DBT const *,DBT *),u_int32_t flags){ return self->associate(self, txnid, secondary, callback, flags); } SWIGINTERN db_ret_t Db_associate_foreign(struct Db *self,DB *primary,int (*callback)(DB *,DBT const *,DBT *,DBT const *,int *),u_int32_t flags){ return self->associate_foreign(self, primary, callback, flags); } SWIGINTERN db_ret_t Db_compact(struct Db *self,DB_TXN *txnid,DBT *start,DBT *stop,DB_COMPACT *c_data,u_int32_t flags,DBT *end){ return self->compact(self, txnid, start, stop, c_data, flags, end); } SWIGINTERN int Db_close(struct Db *self,u_int32_t flags){ errno = self->close(self, flags); return errno; } SWIGINTERN DBC *Db_cursor(struct Db *self,DB_TXN *txnid,u_int32_t flags){ DBC *cursorp = NULL; errno = self->cursor(self, txnid, &cursorp, flags); return cursorp; } SWIGINTERN int Db_del(struct Db *self,DB_TXN *txnid,DBT *key,u_int32_t flags){ return self->del(self, txnid, key, flags); } SWIGINTERN void Db_err(struct Db *self,int error,char const *message){ self->err(self, error, message); } SWIGINTERN void Db_errx(struct Db *self,char const *message){ self->errx(self, message); } SWIGINTERN int Db_exists(struct Db *self,DB_TXN *txnid,DBT *key,u_int32_t flags){ return self->exists(self, txnid, key, flags); } SWIGINTERN int Db_get(struct Db *self,DB_TXN *txnid,DBT *key,DBT *data,u_int32_t flags){ return self->get(self, txnid, key, data, flags); } SWIGINTERN int_bool Db_get_byteswapped(struct Db *self){ int ret = 0; errno = self->get_byteswapped(self, &ret); return ret; } SWIGINTERN jlong Db_get_cachesize(struct Db *self){ u_int32_t gbytes = 0, bytes = 0; errno = self->get_cachesize(self, &gbytes, &bytes, NULL); return (jlong)gbytes * GIGABYTE + bytes; } SWIGINTERN u_int32_t Db_get_cachesize_ncache(struct Db *self){ int ret = 0; errno = self->get_cachesize(self, NULL, NULL, &ret); return ret; } SWIGINTERN char const *Db_get_create_dir(struct Db *self){ const char *ret; errno = self->get_create_dir(self, &ret); return ret; } SWIGINTERN char const *Db_get_filename(struct Db *self){ const char *ret = NULL; errno = self->get_dbname(self, &ret, NULL); return ret; } SWIGINTERN char const *Db_get_dbname(struct Db *self){ const char *ret = NULL; errno = self->get_dbname(self, NULL, &ret); return ret; } SWIGINTERN u_int32_t Db_get_encrypt_flags(struct Db *self){ u_int32_t ret = 0; CRYPTO_ONLY(errno = self->get_encrypt_flags(self, &ret)) return ret; } SWIGINTERN u_int32_t Db_get_flags(struct Db *self){ u_int32_t ret = 0; errno = self->get_flags(self, &ret); return ret; } SWIGINTERN int Db_get_lorder(struct Db *self){ int ret = 0; errno = self->get_lorder(self, &ret); return ret; } SWIGINTERN DB_MPOOLFILE *Db_get_mpf(struct Db *self){ errno = 0; return self->get_mpf(self); } SWIGINTERN u_int32_t Db_get_open_flags(struct Db *self){ u_int32_t ret = 0; errno = self->get_open_flags(self, &ret); return ret; } SWIGINTERN u_int32_t Db_get_pagesize(struct Db *self){ u_int32_t ret = 0; errno = self->get_pagesize(self, &ret); return ret; } SWIGINTERN u_int32_t Db_get_bt_minkey(struct Db *self){ u_int32_t ret = 0; errno = self->get_bt_minkey(self, &ret); return ret; } SWIGINTERN u_int32_t Db_get_h_ffactor(struct Db *self){ u_int32_t ret = 0; errno = self->get_h_ffactor(self, &ret); return ret; } SWIGINTERN u_int32_t Db_get_h_nelem(struct Db *self){ u_int32_t ret = 0; errno = self->get_h_nelem(self, &ret); return ret; } SWIGINTERN int Db_get_re_delim(struct Db *self){ int ret = 0; errno = self->get_re_delim(self, &ret); return ret; } SWIGINTERN DB_CACHE_PRIORITY Db_get_priority(struct Db *self){ DB_CACHE_PRIORITY ret; errno = self->get_priority(self, &ret); return ret; } SWIGINTERN char const **Db_get_partition_dirs(struct Db *self){ const char **ret; errno = self->get_partition_dirs(self, &ret); return ret; } SWIGINTERN DBT *Db_get_partition_keys(struct Db *self){ DBT *ret = NULL; errno = self->get_partition_keys(self, NULL, &ret); return ret; } SWIGINTERN int Db_get_partition_parts(struct Db *self){ int ret = 0; errno = self->get_partition_keys(self, &ret, NULL); /* If not partitioned by range, check by callback. */ if (ret == 0) errno = self->get_partition_callback(self, &ret, NULL); return ret; } SWIGINTERN u_int32_t Db_get_re_len(struct Db *self){ u_int32_t ret = 0; errno = self->get_re_len(self, &ret); return ret; } SWIGINTERN int Db_get_re_pad(struct Db *self){ int ret = 0; errno = self->get_re_pad(self, &ret); return ret; } SWIGINTERN char const *Db_get_re_source(struct Db *self){ const char *ret = NULL; errno = self->get_re_source(self, &ret); return ret; } SWIGINTERN u_int32_t Db_get_q_extentsize(struct Db *self){ u_int32_t ret = 0; errno = self->get_q_extentsize(self, &ret); return ret; } SWIGINTERN int_bool Db_get_multiple(struct Db *self){ return self->get_multiple(self); } SWIGINTERN int_bool Db_get_transactional(struct Db *self){ return self->get_transactional(self); } SWIGINTERN DBTYPE Db_get_type(struct Db *self){ DBTYPE type = (DBTYPE)0; errno = self->get_type(self, &type); return type; } SWIGINTERN DBC *Db_join(struct Db *self,DBC **curslist,u_int32_t flags){ DBC *dbcp = NULL; errno = self->join(self, curslist, &dbcp, flags); return dbcp; } SWIGINTERN db_ret_t Db_key_range(struct Db *self,DB_TXN *txnid,DBT *key,DB_KEY_RANGE *key_range,u_int32_t flags){ return self->key_range(self, txnid, key, key_range, flags); } SWIGINTERN db_ret_t Db_open(struct Db *self,DB_TXN *txnid,char const *file,char const *database,DBTYPE type,u_int32_t flags,int mode){ return self->open(self, txnid, file, database, type, flags, mode); } SWIGINTERN int Db_pget(struct Db *self,DB_TXN *txnid,DBT *key,DBT *pkey,DBT *data,u_int32_t flags){ return self->pget(self, txnid, key, pkey, data, flags); } SWIGINTERN int Db_put(struct Db *self,DB_TXN *txnid,DBT *key,DBT *db_put_data,u_int32_t flags){ return self->put(self, txnid, key, db_put_data, flags); } SWIGINTERN db_ret_t Db_remove(struct Db *self,char const *file,char const *database,u_int32_t flags){ return self->remove(self, file, database, flags); } SWIGINTERN db_ret_t Db_rename(struct Db *self,char const *file,char const *database,char const *newname,u_int32_t flags){ return self->rename(self, file, database, newname, flags); } SWIGINTERN db_ret_t Db_set_append_recno(struct Db *self,int (*db_append_recno_fcn)(DB *,DBT *,db_recno_t)){ return self->set_append_recno(self, db_append_recno_fcn); } SWIGINTERN db_ret_t Db_set_bt_compare(struct Db *self,int (*bt_compare_fcn)(DB *,DBT const *,DBT const *)){ return self->set_bt_compare(self, bt_compare_fcn); } SWIGINTERN db_ret_t Db_set_bt_minkey(struct Db *self,u_int32_t bt_minkey){ return self->set_bt_minkey(self, bt_minkey); } SWIGINTERN db_ret_t Db_set_bt_compress(struct Db *self,int (*bt_compress_fcn)(DB *,DBT const *,DBT const *,DBT const *,DBT const *,DBT *),int (*bt_decompress_fcn)(DB *,DBT const *,DBT const *,DBT *,DBT *,DBT *)){ return self->set_bt_compress( self, bt_compress_fcn, bt_decompress_fcn); } SWIGINTERN db_ret_t Db_set_bt_prefix(struct Db *self,size_t (*bt_prefix_fcn)(DB *,DBT const *,DBT const *)){ return self->set_bt_prefix(self, bt_prefix_fcn); } SWIGINTERN db_ret_t Db_set_cachesize(struct Db *self,jlong bytes,int ncache){ return self->set_cachesize(self, (u_int32_t)(bytes / GIGABYTE), (u_int32_t)(bytes % GIGABYTE), ncache); } SWIGINTERN db_ret_t Db_set_create_dir(struct Db *self,char const *dir){ return self->set_create_dir(self, dir); } SWIGINTERN db_ret_t Db_set_dup_compare(struct Db *self,int (*dup_compare_fcn)(DB *,DBT const *,DBT const *)){ return self->set_dup_compare(self, dup_compare_fcn); } SWIGINTERN db_ret_t Db_set_encrypt(struct Db *self,char const *passwd,u_int32_t flags){ return self->set_encrypt(self, passwd, flags); } SWIGINTERN db_ret_t Db_set_feedback(struct Db *self,void (*db_feedback_fcn)(DB *,int,int)){ return self->set_feedback(self, db_feedback_fcn); } SWIGINTERN db_ret_t Db_set_flags(struct Db *self,u_int32_t flags){ return self->set_flags(self, flags); } SWIGINTERN db_ret_t Db_set_h_compare(struct Db *self,int (*h_compare_fcn)(DB *,DBT const *,DBT const *)){ return self->set_h_compare(self, h_compare_fcn); } SWIGINTERN db_ret_t Db_set_h_ffactor(struct Db *self,u_int32_t h_ffactor){ return self->set_h_ffactor(self, h_ffactor); } SWIGINTERN db_ret_t Db_set_h_hash(struct Db *self,u_int32_t (*h_hash_fcn)(DB *,void const *,u_int32_t)){ return self->set_h_hash(self, h_hash_fcn); } SWIGINTERN db_ret_t Db_set_h_nelem(struct Db *self,u_int32_t h_nelem){ return self->set_h_nelem(self, h_nelem); } SWIGINTERN db_ret_t Db_set_lorder(struct Db *self,int lorder){ return self->set_lorder(self, lorder); } SWIGINTERN db_ret_t Db_set_pagesize(struct Db *self,u_int32_t pagesize){ return self->set_pagesize(self, pagesize); } SWIGINTERN db_ret_t Db_set_partition(struct Db *self,u_int32_t parts,DBT *keys,u_int32_t (*db_partition_fcn)(DB *,DBT *)){ return self->set_partition(self, parts, keys, db_partition_fcn); } SWIGINTERN db_ret_t Db_set_partition_dirs(struct Db *self,char const **dirp){ return self->set_partition_dirs(self, dirp); } SWIGINTERN db_ret_t Db_set_priority(struct Db *self,DB_CACHE_PRIORITY priority){ return self->set_priority(self, priority); } SWIGINTERN db_ret_t Db_set_re_delim(struct Db *self,int re_delim){ return self->set_re_delim(self, re_delim); } SWIGINTERN db_ret_t Db_set_re_len(struct Db *self,u_int32_t re_len){ return self->set_re_len(self, re_len); } SWIGINTERN db_ret_t Db_set_re_pad(struct Db *self,int re_pad){ return self->set_re_pad(self, re_pad); } SWIGINTERN db_ret_t Db_set_re_source(struct Db *self,char *source){ return self->set_re_source(self, source); } SWIGINTERN db_ret_t Db_set_q_extentsize(struct Db *self,u_int32_t extentsize){ return self->set_q_extentsize(self, extentsize); } SWIGINTERN db_ret_t Db_sort_multiple(struct Db *self,DBT *key,DBT *data){ return self->sort_multiple(self, key, data, 0); } SWIGINTERN void *Db_stat(struct Db *self,DB_TXN *txnid,u_int32_t flags){ void *statp = NULL; errno = self->stat(self, txnid, &statp, flags); return statp; } SWIGINTERN db_ret_t Db_sync(struct Db *self,u_int32_t flags){ return self->sync(self, flags); } SWIGINTERN int Db_truncate(struct Db *self,DB_TXN *txnid,u_int32_t flags){ u_int32_t count = 0; errno = self->truncate(self, txnid, &count, flags); return count; } SWIGINTERN db_ret_t Db_upgrade(struct Db *self,char const *file,u_int32_t flags){ return self->upgrade(self, file, flags); } SWIGINTERN int_bool Db_verify(struct Db *self,char const *file,char const *database,struct __db_out_stream outfile,u_int32_t flags){ /* * We can't easily #include "dbinc/db_ext.h" because of name * clashes, so we declare this explicitly. */ extern int __db_verify_internal __P((DB *, const char *, const char *, void *, int (*)(void *, const void *), u_int32_t)); errno = __db_verify_internal(self, file, database, outfile.handle, outfile.callback, flags); if (errno == DB_VERIFY_BAD) { errno = 0; return 0; } else return 1; } SWIGINTERN db_ret_t Dbc_close(struct Dbc *self){ return self->close(self); } SWIGINTERN int Dbc_cmp(struct Dbc *self,DBC *odbc,u_int32_t flags){ int result = 0; errno = self->cmp(self, odbc, &result, flags); return result; } SWIGINTERN db_recno_t Dbc_count(struct Dbc *self,u_int32_t flags){ db_recno_t count = 0; errno = self->count(self, &count, flags); return count; } SWIGINTERN int Dbc_del(struct Dbc *self,u_int32_t flags){ return self->del(self, flags); } SWIGINTERN DBC *Dbc_dup(struct Dbc *self,u_int32_t flags){ DBC *newcurs = NULL; errno = self->dup(self, &newcurs, flags); return newcurs; } SWIGINTERN int Dbc_get(struct Dbc *self,DBT *key,DBT *data,u_int32_t flags){ return self->get(self, key, data, flags); } SWIGINTERN DB_CACHE_PRIORITY Dbc_get_priority(struct Dbc *self){ DB_CACHE_PRIORITY ret; errno = self->get_priority(self, &ret); return ret; } SWIGINTERN int Dbc_pget(struct Dbc *self,DBT *key,DBT *pkey,DBT *data,u_int32_t flags){ return self->pget(self, key, pkey, data, flags); } SWIGINTERN int Dbc_put(struct Dbc *self,DBT *key,DBT *db_put_data,u_int32_t flags){ return self->put(self, key, db_put_data, flags); } SWIGINTERN db_ret_t Dbc_set_priority(struct Dbc *self,DB_CACHE_PRIORITY priority){ return self->set_priority(self, priority); } SWIGINTERN struct DbEnv *new_DbEnv(u_int32_t flags){ DB_ENV *self = NULL; errno = db_env_create(&self, flags); if (errno == 0) self->env->dbt_usercopy = __dbj_dbt_memcopy; return self; } SWIGINTERN db_ret_t DbEnv_close(struct DbEnv *self,u_int32_t flags){ return self->close(self, flags); } SWIGINTERN db_ret_t DbEnv_dbremove(struct DbEnv *self,DB_TXN *txnid,char const *file,char const *database,u_int32_t flags){ return self->dbremove(self, txnid, file, database, flags); } SWIGINTERN db_ret_t DbEnv_dbrename(struct DbEnv *self,DB_TXN *txnid,char const *file,char const *database,char const *newname,u_int32_t flags){ return self->dbrename(self, txnid, file, database, newname, flags); } SWIGINTERN void DbEnv_err(struct DbEnv *self,int error,char const *message){ self->err(self, error, message); } SWIGINTERN void DbEnv_errx(struct DbEnv *self,char const *message){ self->errx(self, message); } SWIGINTERN DB_TXN *DbEnv_cdsgroup_begin(struct DbEnv *self){ DB_TXN *tid = NULL; errno = self->cdsgroup_begin(self, &tid); return tid; } SWIGINTERN db_ret_t DbEnv_fileid_reset(struct DbEnv *self,char const *file,u_int32_t flags){ return self->fileid_reset(self, file, flags); } SWIGINTERN char const **DbEnv_get_data_dirs(struct DbEnv *self){ const char **ret; errno = self->get_data_dirs(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_encrypt_flags(struct DbEnv *self){ u_int32_t ret = 0; CRYPTO_ONLY(errno = self->get_encrypt_flags(self, &ret)) return ret; } SWIGINTERN u_int32_t DbEnv_get_flags(struct DbEnv *self){ u_int32_t ret; errno = self->get_flags(self, &ret); return ret; } SWIGINTERN char const *DbEnv_get_home(struct DbEnv *self){ const char *ret; errno = self->get_home(self, &ret); return ret; } SWIGINTERN char const *DbEnv_get_intermediate_dir_mode(struct DbEnv *self){ const char *ret; errno = self->get_intermediate_dir_mode(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_open_flags(struct DbEnv *self){ u_int32_t ret; errno = self->get_open_flags(self, &ret); return ret; } SWIGINTERN long DbEnv_get_shm_key(struct DbEnv *self){ long ret; errno = self->get_shm_key(self, &ret); return ret; } SWIGINTERN char const *DbEnv_get_tmp_dir(struct DbEnv *self){ const char *ret; errno = self->get_tmp_dir(self, &ret); return ret; } SWIGINTERN int_bool DbEnv_get_verbose(struct DbEnv *self,u_int32_t which){ int ret; errno = self->get_verbose(self, which, &ret); return ret; } SWIGINTERN int_bool DbEnv_is_bigendian(struct DbEnv *self){ return self->is_bigendian(); } SWIGINTERN db_ret_t DbEnv_lsn_reset(struct DbEnv *self,char const *file,u_int32_t flags){ return self->lsn_reset(self, file, flags); } SWIGINTERN db_ret_t DbEnv_open(struct DbEnv *self,char const *db_home,u_int32_t flags,int mode){ return self->open(self, db_home, flags, mode); } SWIGINTERN db_ret_t DbEnv_remove(struct DbEnv *self,char const *db_home,u_int32_t flags){ return self->remove(self, db_home, flags); } SWIGINTERN db_ret_t DbEnv_set_cachesize(struct DbEnv *self,jlong bytes,int ncache){ return self->set_cachesize(self, (u_int32_t)(bytes / GIGABYTE), (u_int32_t)(bytes % GIGABYTE), ncache); } SWIGINTERN db_ret_t DbEnv_set_cache_max(struct DbEnv *self,jlong bytes){ return self->set_cache_max(self, (u_int32_t)(bytes / GIGABYTE), (u_int32_t)(bytes % GIGABYTE)); } SWIGINTERN db_ret_t DbEnv_set_create_dir(struct DbEnv *self,char const *dir){ return self->set_create_dir(self, dir); } SWIGINTERN db_ret_t DbEnv_set_data_dir(struct DbEnv *self,char const *dir){ return self->set_data_dir(self, dir); } SWIGINTERN db_ret_t DbEnv_set_intermediate_dir_mode(struct DbEnv *self,char const *mode){ return self->set_intermediate_dir_mode(self, mode); } SWIGINTERN db_ret_t DbEnv_set_encrypt(struct DbEnv *self,char const *passwd,u_int32_t flags){ return self->set_encrypt(self, passwd, flags); } SWIGINTERN void DbEnv_set_errcall(struct DbEnv *self,void (*db_errcall_fcn)(DB_ENV const *,char const *,char const *)){ self->set_errcall(self, db_errcall_fcn); } SWIGINTERN db_ret_t DbEnv_set_flags(struct DbEnv *self,u_int32_t flags,int_bool onoff){ return self->set_flags(self, flags, onoff); } SWIGINTERN db_ret_t DbEnv_set_feedback(struct DbEnv *self,void (*env_feedback_fcn)(DB_ENV *,int,int)){ return self->set_feedback(self, env_feedback_fcn); } SWIGINTERN db_ret_t DbEnv_set_mp_max_openfd(struct DbEnv *self,int maxopenfd){ return self->set_mp_max_openfd(self, maxopenfd); } SWIGINTERN db_ret_t DbEnv_set_mp_max_write(struct DbEnv *self,int maxwrite,db_timeout_t maxwrite_sleep){ return self->set_mp_max_write(self, maxwrite, maxwrite_sleep); } SWIGINTERN db_ret_t DbEnv_set_mp_mmapsize(struct DbEnv *self,size_t mp_mmapsize){ return self->set_mp_mmapsize(self, mp_mmapsize); } SWIGINTERN db_ret_t DbEnv_set_mp_pagesize(struct DbEnv *self,size_t mp_pagesize){ return self->set_mp_pagesize(self, mp_pagesize); } SWIGINTERN db_ret_t DbEnv_set_mp_tablesize(struct DbEnv *self,size_t mp_tablesize){ return self->set_mp_tablesize(self, mp_tablesize); } SWIGINTERN void DbEnv_set_msgcall(struct DbEnv *self,void (*db_msgcall_fcn)(DB_ENV const *,char const *)){ self->set_msgcall(self, db_msgcall_fcn); } SWIGINTERN db_ret_t DbEnv_set_paniccall(struct DbEnv *self,void (*db_panic_fcn)(DB_ENV *,int)){ return self->set_paniccall(self, db_panic_fcn); } SWIGINTERN db_ret_t DbEnv_set_rpc_server(struct DbEnv *self,char *host,long cl_timeout,long sv_timeout,u_int32_t flags){ return self->set_rpc_server(self, NULL, host, cl_timeout, sv_timeout, flags); } SWIGINTERN db_ret_t DbEnv_set_shm_key(struct DbEnv *self,long shm_key){ return self->set_shm_key(self, shm_key); } SWIGINTERN db_ret_t DbEnv_set_timeout(struct DbEnv *self,db_timeout_t timeout,u_int32_t flags){ return self->set_timeout(self, timeout, flags); } SWIGINTERN db_ret_t DbEnv_set_tmp_dir(struct DbEnv *self,char const *dir){ return self->set_tmp_dir(self, dir); } SWIGINTERN db_ret_t DbEnv_set_tx_max(struct DbEnv *self,u_int32_t max){ return self->set_tx_max(self, max); } SWIGINTERN db_ret_t DbEnv_set_app_dispatch(struct DbEnv *self,int (*tx_recover)(DB_ENV *,DBT *,DB_LSN *,db_recops)){ return self->set_app_dispatch(self, tx_recover); } SWIGINTERN db_ret_t DbEnv_set_event_notify(struct DbEnv *self,void (*event_notify)(DB_ENV *,u_int32_t,void *)){ return self->set_event_notify(self, event_notify); } SWIGINTERN db_ret_t DbEnv_set_tx_timestamp(struct DbEnv *self,time_t *timestamp){ return self->set_tx_timestamp(self, timestamp); } SWIGINTERN db_ret_t DbEnv_set_verbose(struct DbEnv *self,u_int32_t which,int_bool onoff){ return self->set_verbose(self, which, onoff); } SWIGINTERN struct __db_lk_conflicts DbEnv_get_lk_conflicts(struct DbEnv *self){ struct __db_lk_conflicts ret; errno = self->get_lk_conflicts(self, (const u_int8_t **)&ret.lk_conflicts, &ret.lk_modes); return ret; } SWIGINTERN u_int32_t DbEnv_get_lk_detect(struct DbEnv *self){ u_int32_t ret; errno = self->get_lk_detect(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lk_max_locks(struct DbEnv *self){ u_int32_t ret; errno = self->get_lk_max_locks(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lk_max_lockers(struct DbEnv *self){ u_int32_t ret; errno = self->get_lk_max_lockers(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lk_max_objects(struct DbEnv *self){ u_int32_t ret; errno = self->get_lk_max_objects(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lk_partitions(struct DbEnv *self){ u_int32_t ret; errno = self->get_lk_partitions(self, &ret); return ret; } SWIGINTERN int DbEnv_lock_detect(struct DbEnv *self,u_int32_t flags,u_int32_t atype){ int aborted; errno = self->lock_detect(self, flags, atype, &aborted); return aborted; } SWIGINTERN DB_LOCK *DbEnv_lock_get(struct DbEnv *self,u_int32_t locker,u_int32_t flags,DBT *object,db_lockmode_t lock_mode){ DB_LOCK *lock = NULL; if ((errno = __os_malloc(self->env, sizeof (DB_LOCK), &lock)) == 0) errno = self->lock_get(self, locker, flags, object, lock_mode, lock); return lock; } SWIGINTERN u_int32_t DbEnv_lock_id(struct DbEnv *self){ u_int32_t id; errno = self->lock_id(self, &id); return id; } SWIGINTERN db_ret_t DbEnv_lock_id_free(struct DbEnv *self,u_int32_t id){ return self->lock_id_free(self, id); } SWIGINTERN db_ret_t DbEnv_lock_put(struct DbEnv *self,DB_LOCK *lock){ return self->lock_put(self, lock); } SWIGINTERN DB_LOCK_STAT *DbEnv_lock_stat(struct DbEnv *self,u_int32_t flags){ DB_LOCK_STAT *statp = NULL; errno = self->lock_stat(self, &statp, flags); return statp; } SWIGINTERN db_ret_t DbEnv_set_lk_conflicts(struct DbEnv *self,struct __db_lk_conflicts conflicts){ return self->set_lk_conflicts(self, conflicts.lk_conflicts, conflicts.lk_modes); } SWIGINTERN db_ret_t DbEnv_set_lk_detect(struct DbEnv *self,u_int32_t detect){ return self->set_lk_detect(self, detect); } SWIGINTERN db_ret_t DbEnv_set_lk_max_lockers(struct DbEnv *self,u_int32_t max){ return self->set_lk_max_lockers(self, max); } SWIGINTERN db_ret_t DbEnv_set_lk_max_locks(struct DbEnv *self,u_int32_t max){ return self->set_lk_max_locks(self, max); } SWIGINTERN db_ret_t DbEnv_set_lk_max_objects(struct DbEnv *self,u_int32_t max){ return self->set_lk_max_objects(self, max); } SWIGINTERN db_ret_t DbEnv_set_lk_partitions(struct DbEnv *self,u_int32_t partitions){ return self->set_lk_partitions(self, partitions); } SWIGINTERN u_int32_t DbEnv_get_lg_bsize(struct DbEnv *self){ u_int32_t ret; errno = self->get_lg_bsize(self, &ret); return ret; } SWIGINTERN char const *DbEnv_get_lg_dir(struct DbEnv *self){ const char *ret; errno = self->get_lg_dir(self, &ret); return ret; } SWIGINTERN int DbEnv_get_lg_filemode(struct DbEnv *self){ int ret; errno = self->get_lg_filemode(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lg_max(struct DbEnv *self){ u_int32_t ret; errno = self->get_lg_max(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_get_lg_regionmax(struct DbEnv *self){ u_int32_t ret; errno = self->get_lg_regionmax(self, &ret); return ret; } SWIGINTERN char **DbEnv_log_archive(struct DbEnv *self,u_int32_t flags){ char **list = NULL; errno = self->log_archive(self, &list, flags); return list; } SWIGINTERN int DbEnv_log_compare(DB_LSN const *lsn0,DB_LSN const *lsn1){ return log_compare(lsn0, lsn1); } SWIGINTERN DB_LOGC *DbEnv_log_cursor(struct DbEnv *self,u_int32_t flags){ DB_LOGC *cursor = NULL; errno = self->log_cursor(self, &cursor, flags); return cursor; } SWIGINTERN char *DbEnv_log_file(struct DbEnv *self,DB_LSN *lsn){ char namebuf[DB_MAXPATHLEN]; errno = self->log_file(self, lsn, namebuf, sizeof namebuf); return (errno == 0) ? strdup(namebuf) : NULL; } SWIGINTERN db_ret_t DbEnv_log_flush(struct DbEnv *self,DB_LSN const *lsn_or_null){ return self->log_flush(self, lsn_or_null); } SWIGINTERN int_bool DbEnv_log_get_config(struct DbEnv *self,u_int32_t which){ int ret; errno = self->log_get_config(self, which, &ret); return ret; } SWIGINTERN db_ret_t DbEnv_log_put(struct DbEnv *self,DB_LSN *lsn,DBT const *data,u_int32_t flags){ return self->log_put(self, lsn, data, flags); } SWIGINTERN db_ret_t DbEnv_log_print(struct DbEnv *self,DB_TXN *txn,char const *msg){ return self->log_printf(self, txn, "%s", msg); } SWIGINTERN db_ret_t DbEnv_log_set_config(struct DbEnv *self,u_int32_t which,int_bool onoff){ return self->log_set_config(self, which, onoff); } SWIGINTERN DB_LOG_STAT *DbEnv_log_stat(struct DbEnv *self,u_int32_t flags){ DB_LOG_STAT *sp = NULL; errno = self->log_stat(self, &sp, flags); return sp; } SWIGINTERN db_ret_t DbEnv_set_lg_bsize(struct DbEnv *self,u_int32_t lg_bsize){ return self->set_lg_bsize(self, lg_bsize); } SWIGINTERN db_ret_t DbEnv_set_lg_dir(struct DbEnv *self,char const *dir){ return self->set_lg_dir(self, dir); } SWIGINTERN db_ret_t DbEnv_set_lg_filemode(struct DbEnv *self,int mode){ return self->set_lg_filemode(self, mode); } SWIGINTERN db_ret_t DbEnv_set_lg_max(struct DbEnv *self,u_int32_t lg_max){ return self->set_lg_max(self, lg_max); } SWIGINTERN db_ret_t DbEnv_set_lg_regionmax(struct DbEnv *self,u_int32_t lg_regionmax){ return self->set_lg_regionmax(self, lg_regionmax); } SWIGINTERN jlong DbEnv_get_cachesize(struct DbEnv *self){ u_int32_t gbytes, bytes; errno = self->get_cachesize(self, &gbytes, &bytes, NULL); return (jlong)gbytes * GIGABYTE + bytes; } SWIGINTERN int DbEnv_get_cachesize_ncache(struct DbEnv *self){ int ret; errno = self->get_cachesize(self, NULL, NULL, &ret); return ret; } SWIGINTERN jlong DbEnv_get_cache_max(struct DbEnv *self){ u_int32_t gbytes, bytes; errno = self->get_cache_max(self, &gbytes, &bytes); return (jlong)gbytes * GIGABYTE + bytes; } SWIGINTERN char const *DbEnv_get_create_dir(struct DbEnv *self){ const char *ret; errno = self->get_create_dir(self, &ret); return ret; } SWIGINTERN int DbEnv_get_mp_max_openfd(struct DbEnv *self){ int ret; errno = self->get_mp_max_openfd(self, &ret); return ret; } SWIGINTERN int DbEnv_get_mp_max_write(struct DbEnv *self){ int maxwrite; db_timeout_t sleep; errno = self->get_mp_max_write(self, &maxwrite, &sleep); return maxwrite; } SWIGINTERN db_timeout_t DbEnv_get_mp_max_write_sleep(struct DbEnv *self){ int maxwrite; db_timeout_t sleep; errno = self->get_mp_max_write(self, &maxwrite, &sleep); return sleep; } SWIGINTERN size_t DbEnv_get_mp_mmapsize(struct DbEnv *self){ size_t ret; errno = self->get_mp_mmapsize(self, &ret); return ret; } SWIGINTERN int DbEnv_get_mp_pagesize(struct DbEnv *self){ int ret; errno = self->get_mp_pagesize(self, &ret); return ret; } SWIGINTERN int DbEnv_get_mp_tablesize(struct DbEnv *self){ int ret; errno = self->get_mp_tablesize(self, &ret); return ret; } SWIGINTERN DB_MPOOL_STAT *DbEnv_memp_stat(struct DbEnv *self,u_int32_t flags){ DB_MPOOL_STAT *mp_stat = NULL; errno = self->memp_stat(self, &mp_stat, NULL, flags); return mp_stat; } SWIGINTERN DB_MPOOL_FSTAT **DbEnv_memp_fstat(struct DbEnv *self,u_int32_t flags){ DB_MPOOL_FSTAT **mp_fstat = NULL; errno = self->memp_stat(self, NULL, &mp_fstat, flags); return mp_fstat; } SWIGINTERN db_ret_t DbEnv_memp_sync(struct DbEnv *self,DB_LSN *lsn){ return self->memp_sync(self, lsn); } SWIGINTERN int DbEnv_memp_trickle(struct DbEnv *self,int percent){ int ret; errno = self->memp_trickle(self, percent, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_mutex_get_align(struct DbEnv *self){ u_int32_t ret; errno = self->mutex_get_align(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_mutex_get_increment(struct DbEnv *self){ u_int32_t ret; errno = self->mutex_get_increment(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_mutex_get_max(struct DbEnv *self){ u_int32_t ret; errno = self->mutex_get_max(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_mutex_get_tas_spins(struct DbEnv *self){ u_int32_t ret; errno = self->mutex_get_tas_spins(self, &ret); return ret; } SWIGINTERN db_ret_t DbEnv_mutex_set_align(struct DbEnv *self,u_int32_t align){ return self->mutex_set_align(self, align); } SWIGINTERN db_ret_t DbEnv_mutex_set_increment(struct DbEnv *self,u_int32_t increment){ return self->mutex_set_increment(self, increment); } SWIGINTERN db_ret_t DbEnv_mutex_set_max(struct DbEnv *self,u_int32_t mutex_max){ return self->mutex_set_max(self, mutex_max); } SWIGINTERN db_ret_t DbEnv_mutex_set_tas_spins(struct DbEnv *self,u_int32_t tas_spins){ return self->mutex_set_tas_spins(self, tas_spins); } SWIGINTERN DB_MUTEX_STAT *DbEnv_mutex_stat(struct DbEnv *self,u_int32_t flags){ DB_MUTEX_STAT *statp = NULL; errno = self->mutex_stat(self, &statp, flags); return statp; } SWIGINTERN u_int32_t DbEnv_get_tx_max(struct DbEnv *self){ u_int32_t ret; errno = self->get_tx_max(self, &ret); return ret; } SWIGINTERN time_t DbEnv_get_tx_timestamp(struct DbEnv *self){ time_t ret; errno = self->get_tx_timestamp(self, &ret); return ret; } SWIGINTERN db_timeout_t DbEnv_get_timeout(struct DbEnv *self,u_int32_t flag){ db_timeout_t ret; errno = self->get_timeout(self, &ret, flag); return ret; } SWIGINTERN DB_TXN *DbEnv_txn_begin(struct DbEnv *self,DB_TXN *parent,u_int32_t flags){ DB_TXN *tid = NULL; errno = self->txn_begin(self, parent, &tid, flags); return tid; } SWIGINTERN db_ret_t DbEnv_txn_checkpoint(struct DbEnv *self,u_int32_t kbyte,u_int32_t min,u_int32_t flags){ return self->txn_checkpoint(self, kbyte, min, flags); } SWIGINTERN DB_PREPLIST *DbEnv_txn_recover(struct DbEnv *self,int count,u_int32_t flags){ DB_PREPLIST *preplist; u_int32_t retcount; /* Add a NULL element to terminate the array. */ if ((errno = __os_malloc(self->env, (count + 1) * sizeof(DB_PREPLIST), &preplist)) != 0) return NULL; if ((errno = self->txn_recover(self, preplist, count, &retcount, flags)) != 0) { __os_free(self->env, preplist); return NULL; } preplist[retcount].txn = NULL; return preplist; } SWIGINTERN DB_TXN_STAT *DbEnv_txn_stat(struct DbEnv *self,u_int32_t flags){ DB_TXN_STAT *statp = NULL; errno = self->txn_stat(self, &statp, flags); return statp; } SWIGINTERN jlong DbEnv_rep_get_limit(struct DbEnv *self){ u_int32_t gbytes, bytes; errno = self->rep_get_limit(self, &gbytes, &bytes); return (jlong)gbytes * GIGABYTE + bytes; } SWIGINTERN db_ret_t DbEnv_rep_elect(struct DbEnv *self,u_int32_t nsites,int nvotes,u_int32_t flags){ return self->rep_elect(self, nsites, nvotes, flags); } SWIGINTERN int DbEnv_rep_process_message(struct DbEnv *self,DBT *control,DBT *rec,int envid,DB_LSN *ret_lsn){ return self->rep_process_message(self, control, rec, envid, ret_lsn); } SWIGINTERN db_ret_t DbEnv_rep_flush(struct DbEnv *self){ return self->rep_flush(self); } SWIGINTERN db_ret_t DbEnv_rep_set_config(struct DbEnv *self,u_int32_t which,int_bool onoff){ return self->rep_set_config(self, which, onoff); } SWIGINTERN db_ret_t DbEnv_rep_set_clockskew(struct DbEnv *self,u_int32_t fast_clock,u_int32_t slow_clock){ return self->rep_set_clockskew(self, fast_clock, slow_clock); } SWIGINTERN u_int32_t DbEnv_rep_get_clockskew_fast(struct DbEnv *self){ u_int32_t fast_clock, slow_clock; errno = self->rep_get_clockskew(self, &fast_clock, &slow_clock); return fast_clock; } SWIGINTERN u_int32_t DbEnv_rep_get_clockskew_slow(struct DbEnv *self){ u_int32_t fast_clock, slow_clock; errno = self->rep_get_clockskew(self, &fast_clock, &slow_clock); return slow_clock; } SWIGINTERN db_ret_t DbEnv_rep_start(struct DbEnv *self,DBT *cdata,u_int32_t flags){ return self->rep_start(self, cdata, flags); } SWIGINTERN db_ret_t DbEnv_rep_sync(struct DbEnv *self,u_int32_t flags){ return self->rep_sync(self, flags); } SWIGINTERN int_bool DbEnv_rep_get_config(struct DbEnv *self,u_int32_t which){ int ret; errno = self->rep_get_config(self, which, &ret); return ret; } SWIGINTERN DB_REP_STAT *DbEnv_rep_stat(struct DbEnv *self,u_int32_t flags){ DB_REP_STAT *statp = NULL; errno = self->rep_stat(self, &statp, flags); return statp; } SWIGINTERN db_ret_t DbEnv_rep_set_limit(struct DbEnv *self,jlong bytes){ return self->rep_set_limit(self, (u_int32_t)(bytes / GIGABYTE), (u_int32_t)(bytes % GIGABYTE)); } SWIGINTERN u_int32_t DbEnv_rep_get_request_min(struct DbEnv *self){ u_int32_t min, max; errno = self->rep_get_request(self, &min, &max); return min; } SWIGINTERN u_int32_t DbEnv_rep_get_request_max(struct DbEnv *self){ u_int32_t min, max; errno = self->rep_get_request(self, &min, &max); return max; } SWIGINTERN db_ret_t DbEnv_rep_set_request(struct DbEnv *self,u_int32_t min,u_int32_t max){ return self->rep_set_request(self, min, max); } SWIGINTERN db_ret_t DbEnv_rep_set_transport(struct DbEnv *self,int envid,int (*send)(DB_ENV *,DBT const *,DBT const *,DB_LSN const *,int,u_int32_t)){ return self->rep_set_transport(self, envid, send); } SWIGINTERN u_int32_t DbEnv_rep_get_nsites(struct DbEnv *self){ u_int32_t ret; errno = self->rep_get_nsites(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_rep_get_priority(struct DbEnv *self){ u_int32_t ret; errno = self->rep_get_priority(self, &ret); return ret; } SWIGINTERN u_int32_t DbEnv_rep_get_timeout(struct DbEnv *self,int which){ u_int32_t ret; errno = self->rep_get_timeout(self, which, &ret); return ret; } SWIGINTERN db_ret_t DbEnv_rep_set_nsites(struct DbEnv *self,u_int32_t number){ return self->rep_set_nsites(self, number); } SWIGINTERN db_ret_t DbEnv_rep_set_priority(struct DbEnv *self,u_int32_t priority){ return self->rep_set_priority(self, priority); } SWIGINTERN db_ret_t DbEnv_rep_set_timeout(struct DbEnv *self,int which,db_timeout_t timeout){ return self->rep_set_timeout(self, which, timeout); } SWIGINTERN int DbEnv_repmgr_add_remote_site(struct DbEnv *self,char const *host,u_int32_t port,u_int32_t flags){ int eid; errno = self->repmgr_add_remote_site(self, host, port, &eid, flags); return eid; } SWIGINTERN db_ret_t DbEnv_repmgr_get_ack_policy(struct DbEnv *self){ int ret; errno = self->repmgr_get_ack_policy(self, &ret); return ret; } SWIGINTERN db_ret_t DbEnv_repmgr_set_ack_policy(struct DbEnv *self,int policy){ return self->repmgr_set_ack_policy(self, policy); } SWIGINTERN db_ret_t DbEnv_repmgr_set_local_site(struct DbEnv *self,char const *host,u_int32_t port,u_int32_t flags){ return self->repmgr_set_local_site(self, host, port, flags); } SWIGINTERN struct __db_repmgr_sites DbEnv_repmgr_site_list(struct DbEnv *self){ struct __db_repmgr_sites sites; errno = self->repmgr_site_list(self, &sites.nsites, &sites.sites); return sites; } SWIGINTERN db_ret_t DbEnv_repmgr_start(struct DbEnv *self,int nthreads,u_int32_t flags){ return self->repmgr_start(self, nthreads, flags); } SWIGINTERN DB_REPMGR_STAT *DbEnv_repmgr_stat(struct DbEnv *self,u_int32_t flags){ DB_REPMGR_STAT *statp = NULL; errno = self->repmgr_stat(self, &statp, flags); return statp; } SWIGINTERN char const *DbEnv_strerror(int error){ return db_strerror(error); } SWIGINTERN int DbEnv_get_version_major(){ return DB_VERSION_MAJOR; } SWIGINTERN int DbEnv_get_version_minor(){ return DB_VERSION_MINOR; } SWIGINTERN int DbEnv_get_version_patch(){ return DB_VERSION_PATCH; } SWIGINTERN char const *DbEnv_get_version_string(){ return DB_VERSION_STRING; } SWIGINTERN void delete_DbLock(struct DbLock *self){ __os_free(NULL, self); } SWIGINTERN db_ret_t DbLogc_close(struct DbLogc *self,u_int32_t flags){ return self->close(self, flags); } SWIGINTERN int DbLogc_get(struct DbLogc *self,DB_LSN *lsn,DBT *data,u_int32_t flags){ return self->get(self, lsn, data, flags); } SWIGINTERN u_int32_t DbLogc_version(struct DbLogc *self,u_int32_t flags){ u_int32_t result; errno = self->version(self, &result, flags); return result; } SWIGINTERN DB_CACHE_PRIORITY DbMpoolFile_get_priority(struct DbMpoolFile *self){ DB_CACHE_PRIORITY ret; errno = self->get_priority(self, &ret); return ret; } SWIGINTERN db_ret_t DbMpoolFile_set_priority(struct DbMpoolFile *self,DB_CACHE_PRIORITY priority){ return self->set_priority(self, priority); } SWIGINTERN u_int32_t DbMpoolFile_get_flags(struct DbMpoolFile *self){ u_int32_t ret; errno = self->get_flags(self, &ret); return ret; } SWIGINTERN db_ret_t DbMpoolFile_set_flags(struct DbMpoolFile *self,u_int32_t flags,int_bool onoff){ return self->set_flags(self, flags, onoff); } SWIGINTERN jlong DbMpoolFile_get_maxsize(struct DbMpoolFile *self){ u_int32_t gbytes, bytes; errno = self->get_maxsize(self, &gbytes, &bytes); return (jlong)gbytes * GIGABYTE + bytes; } SWIGINTERN db_ret_t DbMpoolFile_set_maxsize(struct DbMpoolFile *self,jlong bytes){ return self->set_maxsize(self, (u_int32_t)(bytes / GIGABYTE), (u_int32_t)(bytes % GIGABYTE)); } SWIGINTERN struct DbSequence *new_DbSequence(DB *db,u_int32_t flags){ DB_SEQUENCE *self = NULL; errno = db_sequence_create(&self, db, flags); return self; } SWIGINTERN db_ret_t DbSequence_close(struct DbSequence *self,u_int32_t flags){ return self->close(self, flags); } SWIGINTERN db_seq_t DbSequence_get(struct DbSequence *self,DB_TXN *txnid,int32_t delta,u_int32_t flags){ db_seq_t ret = 0; errno = self->get(self, txnid, delta, &ret, flags); return ret; } SWIGINTERN int32_t DbSequence_get_cachesize(struct DbSequence *self){ int32_t ret = 0; errno = self->get_cachesize(self, &ret); return ret; } SWIGINTERN DB *DbSequence_get_db(struct DbSequence *self){ DB *ret = NULL; errno = self->get_db(self, &ret); return ret; } SWIGINTERN u_int32_t DbSequence_get_flags(struct DbSequence *self){ u_int32_t ret = 0; errno = self->get_flags(self, &ret); return ret; } SWIGINTERN db_ret_t DbSequence_get_key(struct DbSequence *self,DBT *key){ return self->get_key(self, key); } SWIGINTERN db_seq_t DbSequence_get_range_min(struct DbSequence *self){ db_seq_t ret = 0; errno = self->get_range(self, &ret, NULL); return ret; } SWIGINTERN db_seq_t DbSequence_get_range_max(struct DbSequence *self){ db_seq_t ret = 0; errno = self->get_range(self, NULL, &ret); return ret; } SWIGINTERN db_ret_t DbSequence_initial_value(struct DbSequence *self,db_seq_t val){ return self->initial_value(self, val); } SWIGINTERN db_ret_t DbSequence_open(struct DbSequence *self,DB_TXN *txnid,DBT *key,u_int32_t flags){ return self->open(self, txnid, key, flags); } SWIGINTERN db_ret_t DbSequence_remove(struct DbSequence *self,DB_TXN *txnid,u_int32_t flags){ return self->remove(self, txnid, flags); } SWIGINTERN db_ret_t DbSequence_set_cachesize(struct DbSequence *self,int32_t size){ return self->set_cachesize(self, size); } SWIGINTERN db_ret_t DbSequence_set_flags(struct DbSequence *self,u_int32_t flags){ return self->set_flags(self, flags); } SWIGINTERN db_ret_t DbSequence_set_range(struct DbSequence *self,db_seq_t min,db_seq_t max){ return self->set_range(self, min, max); } SWIGINTERN DB_SEQUENCE_STAT *DbSequence_stat(struct DbSequence *self,u_int32_t flags){ DB_SEQUENCE_STAT *ret = NULL; errno = self->stat(self, &ret, flags); return ret; } SWIGINTERN db_ret_t DbTxn_abort(struct DbTxn *self){ return self->abort(self); } SWIGINTERN db_ret_t DbTxn_commit(struct DbTxn *self,u_int32_t flags){ return self->commit(self, flags); } SWIGINTERN db_ret_t DbTxn_discard(struct DbTxn *self,u_int32_t flags){ return self->discard(self, flags); } SWIGINTERN char const *DbTxn_get_name(struct DbTxn *self){ const char *name = NULL; errno = self->get_name(self, &name); return name; } SWIGINTERN u_int32_t DbTxn_id(struct DbTxn *self){ return self->id(self); } SWIGINTERN db_ret_t DbTxn_prepare(struct DbTxn *self,u_int8_t *gid){ return self->prepare(self, gid); } SWIGINTERN db_ret_t DbTxn_set_timeout(struct DbTxn *self,db_timeout_t timeout,u_int32_t flags){ return self->set_timeout(self, timeout, flags); } SWIGINTERN db_ret_t DbTxn_set_name(struct DbTxn *self,char const *name){ return self->set_name(self, name); } #ifdef __cplusplus extern "C" { #endif SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_new_1Db(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jlong jresult = 0 ; DB_ENV *arg1 = (DB_ENV *) 0 ; u_int32_t arg2 ; struct Db *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(DB_ENV **)&jarg1; arg2 = (u_int32_t)jarg2; errno = 0; result = (struct Db *)new_Db(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } *(struct Db **)&jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1associate(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jlong jarg3, jobject jarg3_, jboolean jarg4, jint jarg5) { struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DB *arg3 = (DB *) 0 ; int (*arg4)(DB *,DBT const *,DBT const *,DBT *) = (int (*)(DB *,DBT const *,DBT const *,DBT *)) 0 ; u_int32_t arg5 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; (void)jarg3_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = *(DB **)&jarg3; arg4 = (jarg4 == JNI_TRUE) ? __dbj_seckey_create : NULL; arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_associate(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1associate_1foreign(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jboolean jarg3, jint jarg4) { struct Db *arg1 = (struct Db *) 0 ; DB *arg2 = (DB *) 0 ; int (*arg3)(DB *,DBT const *,DBT *,DBT const *,int *) = (int (*)(DB *,DBT const *,DBT *,DBT const *,int *)) 0 ; u_int32_t arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB **)&jarg2; arg3 = (jarg3 == JNI_TRUE) ? __dbj_foreignkey_nullify : NULL; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_associate_foreign(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1compact(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jobject jarg4, jobject jarg5, jint jarg6, jobject jarg7) { struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT *arg4 = (DBT *) 0 ; DB_COMPACT *arg5 = (DB_COMPACT *) 0 ; u_int32_t arg6 ; DBT *arg7 = (DBT *) 0 ; DBT_LOCKED ldbt3 ; DBT_LOCKED ldbt4 ; DB_COMPACT compact5 ; DBT_LOCKED ldbt7 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 1) != 0) { return ; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 1) != 0) { return ; /* An exception will be pending. */ } memset(&compact5, 0, sizeof (DB_COMPACT)); arg5 = &compact5; arg5->compact_fillpercent = (*jenv)->GetIntField(jenv, jarg5, compact_compact_fillpercent_fid); arg5->compact_timeout = (*jenv)->GetIntField(jenv, jarg5, compact_compact_timeout_fid); arg5->compact_pages = (*jenv)->GetIntField(jenv, jarg5, compact_compact_pages_fid); arg6 = (u_int32_t)jarg6; if (__dbj_dbt_copyin(jenv, &ldbt7, &arg7, jarg7, 1) != 0) { return ; /* An exception will be pending. */ } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_compact(arg1,arg2,arg3,arg4,arg5,arg6,arg7); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); __dbj_fill_compact(jenv, jarg5, arg5); __dbj_dbt_release(jenv, jarg7, arg7, &ldbt7); } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1close0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_close(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1cursor(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { jlong jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; u_int32_t arg3 ; DBC *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DBC *)Db_cursor(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } *(DBC **)&jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1del(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jint jarg4) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DBT_LOCKED ldbt3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Db_del(arg1,arg2,arg3,arg4); if (!DB_RETOK_DBDEL(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1err(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jstring jarg3) { struct Db *arg1 = (struct Db *) 0 ; int arg2 ; char *arg3 = (char *) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (int)jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } Db_err(arg1,arg2,(char const *)arg3); if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1errx(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } Db_errx(arg1,(char const *)arg2); if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1exists(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jint jarg4) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DBT_LOCKED ldbt3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Db_exists(arg1,arg2,arg3,arg4); if (!DB_RETOK_EXISTS(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jobject jarg4, jint jarg5) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT *arg4 = (DBT *) 0 ; u_int32_t arg5 ; DBT_LOCKED ldbt3 ; DBT_LOCKED ldbt4 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 0) != 0) { return 0; /* An exception will be pending. */ } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Db_get(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_DBGET(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); return jresult; } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1byteswapped(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jboolean jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int_bool)Db_get_byteswapped(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; jlong result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = Db_get_cachesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1cachesize_1ncache(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_cachesize_ncache(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1create_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)Db_get_create_dir(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1filename(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)Db_get_filename(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1dbname(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)Db_get_dbname(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1encrypt_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_encrypt_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1lorder(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_get_lorder(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1mpf(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_MPOOLFILE *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_MPOOLFILE *)Db_get_mpf(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } *(DB_MPOOLFILE **)&jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1open_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_open_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1pagesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_pagesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1bt_1minkey(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_bt_minkey(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1h_1ffactor(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_h_ffactor(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1h_1nelem(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_h_nelem(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1re_1delim(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_get_re_delim(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_CACHE_PRIORITY result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_CACHE_PRIORITY)Db_get_priority(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1partition_1dirs(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jobjectArray jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char **result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char **)Db_get_partition_dirs(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } { if (result != NULL) { /*@SWIG:../libdb_java/java_typemaps.i,367,STRING_ARRAY_OUT@*/ int i, len; len = 0; while (result[len] != NULL) len++; if ((jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, string_class, NULL)) == NULL) return 0; /* an exception is pending */ for (i = 0; i < len; i++) { jstring str = (*jenv)->NewStringUTF(jenv, result[i]); (*jenv)->SetObjectArrayElement(jenv, jresult, (jsize)i, str); } /*@SWIG@*/ } } return jresult; } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1partition_1keys(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jobject jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DBT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DBT *)Db_get_partition_keys(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jobject)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1partition_1parts(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_get_partition_parts(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1re_1len(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_re_len(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1re_1pad(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_get_re_pad(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1re_1source(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)Db_get_re_source(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1q_1extentsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)Db_get_q_extentsize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1multiple(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jboolean jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int_bool)Db_get_multiple(arg1); jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1transactional(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jboolean jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int_bool)Db_get_transactional(arg1); jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1get_1type(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DBTYPE result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DBTYPE)Db_get_type(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1join(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobjectArray jarg2, jint jarg3) { jlong jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DBC **arg2 = (DBC **) 0 ; u_int32_t arg3 ; DBC *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; { int i, count, err; count = (*jenv)->GetArrayLength(jenv, jarg2); if ((err = __os_malloc(NULL, (count + 1) * sizeof(DBC *), &arg2)) != 0) { __dbj_throw(jenv, err, NULL, NULL, DB2JDBENV); return 0; } for (i = 0; i < count; i++) { jobject jobj = (*jenv)->GetObjectArrayElement(jenv, jarg2, i); /* * A null in the array is treated as an endpoint. */ if (jobj == NULL) { arg2[i] = NULL; break; } else { jlong jptr = (*jenv)->GetLongField(jenv, jobj, dbc_cptr_fid); arg2[i] = *(DBC **)(void *)&jptr; } } arg2[count] = NULL; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DBC *)Db_join(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } *(DBC **)&jresult = result; __os_free(NULL, arg2); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1key_1range(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jobject jarg4, jint jarg5) { struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; DB_KEY_RANGE *arg4 = (DB_KEY_RANGE *) 0 ; u_int32_t arg5 ; DBT_LOCKED ldbt3 ; DB_KEY_RANGE range4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return ; /* An exception will be pending. */ } { arg4 = &range4; } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_key_range(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } { (*jenv)->SetDoubleField(jenv, jarg4, kr_less_fid, arg4->less); (*jenv)->SetDoubleField(jenv, jarg4, kr_equal_fid, arg4->equal); (*jenv)->SetDoubleField(jenv, jarg4, kr_greater_fid, arg4->greater); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1open(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jstring jarg3, jstring jarg4, jint jarg5, jint jarg6, jint jarg7) { struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) 0 ; DBTYPE arg5 ; u_int32_t arg6 ; int arg7 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } arg4 = 0; if (jarg4) { arg4 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg4, 0); if (!arg4) return ; } arg5 = (DBTYPE)jarg5; arg6 = (u_int32_t)jarg6; arg7 = (int)jarg7; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_open(arg1,arg2,(char const *)arg3,(char const *)arg4,arg5,arg6,arg7); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); if (arg4) (*jenv)->ReleaseStringUTFChars(jenv, jarg4, (const char *)arg4); } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1pget(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jobject jarg4, jobject jarg5, jint jarg6) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT *arg4 = (DBT *) 0 ; DBT *arg5 = (DBT *) 0 ; u_int32_t arg6 ; DBT_LOCKED ldbt3 ; DBT_LOCKED ldbt4 ; DBT_LOCKED ldbt5 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt5, &arg5, jarg5, 0) != 0) { return 0; /* An exception will be pending. */ } arg6 = (u_int32_t)jarg6; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Db_pget(arg1,arg2,arg3,arg4,arg5,arg6); if (!DB_RETOK_DBGET(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); __dbj_dbt_release(jenv, jarg5, arg5, &ldbt5); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1put(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jobject jarg4, jint jarg5) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT *arg4 = (DBT *) 0 ; u_int32_t arg5 ; DBT_LOCKED ldbt3 ; DBT_LOCKED ldbt4 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 1) != 0) { return 0; /* An exception will be pending. */ } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Db_put(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_DBPUT(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1remove0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jstring jarg3, jint jarg4) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; u_int32_t arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_remove(arg1,(char const *)arg2,(char const *)arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1rename0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jstring jarg3, jstring jarg4, jint jarg5) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) 0 ; u_int32_t arg5 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } arg4 = 0; if (jarg4) { arg4 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg4, 0); if (!arg4) return ; } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_rename(arg1,(char const *)arg2,(char const *)arg3,(char const *)arg4,arg5); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); if (arg4) (*jenv)->ReleaseStringUTFChars(jenv, jarg4, (const char *)arg4); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1append_1recno(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; int (*arg2)(DB *,DBT *,db_recno_t) = (int (*)(DB *,DBT *,db_recno_t)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_append_recno : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_append_recno(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1bt_1compare(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; int (*arg2)(DB *,DBT const *,DBT const *) = (int (*)(DB *,DBT const *,DBT const *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_bt_compare : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_bt_compare(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1bt_1minkey(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_bt_minkey(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1bt_1compress(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2, jboolean jarg3) { struct Db *arg1 = (struct Db *) 0 ; int (*arg2)(DB *,DBT const *,DBT const *,DBT const *,DBT const *,DBT *) = (int (*)(DB *,DBT const *,DBT const *,DBT const *,DBT const *,DBT *)) 0 ; int (*arg3)(DB *,DBT const *,DBT const *,DBT *,DBT *,DBT *) = (int (*)(DB *,DBT const *,DBT const *,DBT *,DBT *,DBT *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_bt_compress : NULL; arg3 = (jarg3 == JNI_TRUE) ? __dbj_bt_decompress : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_bt_compress(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1bt_1prefix(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; size_t (*arg2)(DB *,DBT const *,DBT const *) = (size_t (*)(DB *,DBT const *,DBT const *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_bt_prefix : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_bt_prefix(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jint jarg3) { struct Db *arg1 = (struct Db *) 0 ; jlong arg2 ; int arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = jarg2; arg3 = (int)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_cachesize(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1create_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_create_dir(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1dup_1compare(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; int (*arg2)(DB *,DBT const *,DBT const *) = (int (*)(DB *,DBT const *,DBT const *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_dup_compare : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_dup_compare(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1encrypt(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_encrypt(arg1,(char const *)arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1feedback(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; void (*arg2)(DB *,int,int) = (void (*)(DB *,int,int)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_db_feedback : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_feedback(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_flags(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1h_1compare(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; int (*arg2)(DB *,DBT const *,DBT const *) = (int (*)(DB *,DBT const *,DBT const *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_h_compare : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_h_compare(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1h_1ffactor(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_h_ffactor(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1h_1hash(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t (*arg2)(DB *,void const *,u_int32_t) = (u_int32_t (*)(DB *,void const *,u_int32_t)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_h_hash : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_h_hash(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1h_1nelem(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_h_nelem(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1lorder(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_lorder(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1pagesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_pagesize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1partition(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jobject jarg3, jboolean jarg4) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; DBT *arg3 = (DBT *) 0 ; u_int32_t (*arg4)(DB *,DBT *) = (u_int32_t (*)(DB *,DBT *)) 0 ; DBT_LOCKED ldbt3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 1) != 0) { return ; /* An exception will be pending. */ } arg4 = (jarg4 == JNI_TRUE) ? __dbj_partition : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_partition(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1partition_1dirs(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobjectArray jarg2) { struct Db *arg1 = (struct Db *) 0 ; char **arg2 = (char **) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = *(char ***)&jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_partition_dirs(arg1,(char const **)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; DB_CACHE_PRIORITY arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (DB_CACHE_PRIORITY)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_priority(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1re_1delim(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_re_delim(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1re_1len(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_re_len(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1re_1pad(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_re_pad(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1re_1source(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_re_source(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1set_1q_1extentsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_set_q_extentsize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1sort_1multiple(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3) { struct Db *arg1 = (struct Db *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT_LOCKED ldbt2 ; DBT_LOCKED ldbt3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return ; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return ; /* An exception will be pending. */ } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_sort_multiple(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { jobject jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; u_int32_t arg3 ; void *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (void *)Db_stat(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } if (result == NULL) jresult = NULL; else { DB *db = (DB *)arg1; DBTYPE dbtype; int err; if ((err = db->get_type(db, &dbtype)) != 0) { __dbj_throw(jenv, err, NULL, NULL, DB2JDBENV); return 0; } switch (dbtype) { /* Btree and recno share the same stat structure */ case DB_BTREE: case DB_RECNO: jresult = (*jenv)->NewObject(jenv, bt_stat_class, bt_stat_construct); if (jresult != NULL) __dbj_fill_bt_stat(jenv, jresult, (DB_BTREE_STAT *)result); break; /* Hash stat structure */ case DB_HASH: jresult = (*jenv)->NewObject(jenv, h_stat_class, h_stat_construct); if (jresult != NULL) __dbj_fill_h_stat(jenv, jresult, (DB_HASH_STAT *)result); break; case DB_QUEUE: jresult = (*jenv)->NewObject(jenv, qam_stat_class, qam_stat_construct); if (jresult != NULL) __dbj_fill_qam_stat(jenv, jresult, (DB_QUEUE_STAT *)result); break; /* That's all the database types we're aware of! */ default: __dbj_throw(jenv, EINVAL, "Db.stat only implemented for" " BTREE, HASH, QUEUE and RECNO", NULL, DB2JDBENV); break; } __os_ufree(db->env, result); } return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1sync(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Db *arg1 = (struct Db *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_sync(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1truncate(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { jint jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; u_int32_t arg3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Db **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Db_truncate(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DB2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1upgrade(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Db_upgrade(arg1,(char const *)arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, DB2JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Db_1verify0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jstring jarg3, jobject jarg4, jint jarg5) { jboolean jresult = 0 ; struct Db *arg1 = (struct Db *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; struct __db_out_stream arg4 ; u_int32_t arg5 ; struct __dbj_verify_data data4 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Db **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return 0; } arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return 0; } { data4.jenv = jenv; data4.streamobj = jarg4; data4.bytes = NULL; data4.nbytes = 0; (&arg4)->handle = &data4; (&arg4)->callback = __dbj_verify_callback; } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int_bool)Db_verify(arg1,(char const *)arg2,(char const *)arg3,arg4,arg5); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (result) ? JNI_TRUE : JNI_FALSE; if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1close0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { struct Dbc *arg1 = (struct Dbc *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)Dbc_close(arg1); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1cmp(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; DBC *arg2 = (DBC *) 0 ; u_int32_t arg3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct Dbc **)&jarg1; arg2 = *(DBC **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)Dbc_cmp(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1count(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; u_int32_t arg2 ; db_recno_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_recno_t)Dbc_count(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1del(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; u_int32_t arg2 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Dbc_del(arg1,arg2); if (!DB_RETOK_DBCDEL(result)) { __dbj_throw(jenv, result, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1dup(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jlong jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; u_int32_t arg2 ; DBC *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DBC *)Dbc_dup(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DBC2JDBENV); } *(DBC **)&jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jint jarg4) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DBT_LOCKED ldbt2 ; DBT_LOCKED ldbt3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Dbc_get(arg1,arg2,arg3,arg4); if (!DB_RETOK_DBCGET(result)) { __dbj_throw(jenv, result, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1get_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; DB_CACHE_PRIORITY result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_CACHE_PRIORITY)Dbc_get_priority(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1pget(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jobject jarg4, jint jarg5) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT *arg3 = (DBT *) 0 ; DBT *arg4 = (DBT *) 0 ; u_int32_t arg5 ; DBT_LOCKED ldbt2 ; DBT_LOCKED ldbt3 ; DBT_LOCKED ldbt4 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 0) != 0) { return 0; /* An exception will be pending. */ } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Dbc_pget(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_DBCGET(result)) { __dbj_throw(jenv, result, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1put(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jint jarg4) { jint jresult = 0 ; struct Dbc *arg1 = (struct Dbc *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DBT_LOCKED ldbt2 ; DBT_LOCKED ldbt3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 1) != 0) { return 0; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int)Dbc_put(arg1,arg2,arg3,arg4); if (!DB_RETOK_DBCPUT(result)) { __dbj_throw(jenv, result, NULL, NULL, DBC2JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_Dbc_1set_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct Dbc *arg1 = (struct Dbc *) 0 ; DB_CACHE_PRIORITY arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct Dbc **)&jarg1; arg2 = (DB_CACHE_PRIORITY)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } errno = 0; result = (db_ret_t)Dbc_set_priority(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, DBC2JDBENV); } } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_new_1DbEnv(JNIEnv *jenv, jclass jcls, jint jarg1) { jlong jresult = 0 ; u_int32_t arg1 ; struct DbEnv *result = 0 ; (void)jenv; (void)jcls; arg1 = (u_int32_t)jarg1; errno = 0; result = (struct DbEnv *)new_DbEnv(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } *(struct DbEnv **)&jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1close0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_close(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1dbremove(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jstring jarg3, jstring jarg4, jint jarg5) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) 0 ; u_int32_t arg5 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbEnv **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } arg4 = 0; if (jarg4) { arg4 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg4, 0); if (!arg4) return ; } arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_dbremove(arg1,arg2,(char const *)arg3,(char const *)arg4,arg5); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); if (arg4) (*jenv)->ReleaseStringUTFChars(jenv, jarg4, (const char *)arg4); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1dbrename(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jstring jarg3, jstring jarg4, jstring jarg5, jint jarg6) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; char *arg3 = (char *) 0 ; char *arg4 = (char *) 0 ; char *arg5 = (char *) 0 ; u_int32_t arg6 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbEnv **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } arg4 = 0; if (jarg4) { arg4 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg4, 0); if (!arg4) return ; } arg5 = 0; if (jarg5) { arg5 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg5, 0); if (!arg5) return ; } arg6 = (u_int32_t)jarg6; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_dbrename(arg1,arg2,(char const *)arg3,(char const *)arg4,(char const *)arg5,arg6); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); if (arg4) (*jenv)->ReleaseStringUTFChars(jenv, jarg4, (const char *)arg4); if (arg5) (*jenv)->ReleaseStringUTFChars(jenv, jarg5, (const char *)arg5); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1err(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jstring jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; char *arg3 = (char *) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } DbEnv_err(arg1,arg2,(char const *)arg3); if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1errx(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } DbEnv_errx(arg1,(char const *)arg2); if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1cdsgroup_1begin(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_TXN *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (DB_TXN *)DbEnv_cdsgroup_begin(arg1); *(DB_TXN **)&jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1fileid_1reset(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_fileid_reset(arg1,(char const *)arg2,arg3); if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1data_1dirs(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char **result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char **)DbEnv_get_data_dirs(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { if (result != NULL) { /*@SWIG:../libdb_java/java_typemaps.i,367,STRING_ARRAY_OUT@*/ int i, len; len = 0; while (result[len] != NULL) len++; if ((jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, string_class, NULL)) == NULL) return 0; /* an exception is pending */ for (i = 0; i < len; i++) { jstring str = (*jenv)->NewStringUTF(jenv, result[i]); (*jenv)->SetObjectArrayElement(jenv, jresult, (jsize)i, str); } /*@SWIG@*/ } } return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1encrypt_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_encrypt_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1home(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_get_home(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1intermediate_1dir_1mode(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_get_intermediate_dir_mode(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1open_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_open_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1shm_1key(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; long result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (long)DbEnv_get_shm_key(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jlong)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1tmp_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_get_tmp_dir(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1verbose(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jboolean jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int_bool)DbEnv_get_verbose(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1is_1bigendian(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jboolean jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (int_bool)DbEnv_is_bigendian(arg1); jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lsn_1reset(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_lsn_reset(arg1,(char const *)arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1open(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3, jint jarg4) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; int arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; arg4 = (int)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_open(arg1,(char const *)arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1remove0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_remove(arg1,(char const *)arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong arg2 ; int arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = jarg2; arg3 = (int)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_cachesize(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1cache_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_cache_max(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1create_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_create_dir(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1data_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_data_dir(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1intermediate_1dir_1mode(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_intermediate_dir_mode(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1encrypt(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_encrypt(arg1,(char const *)arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1errcall(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; void (*arg2)(DB_ENV const *,char const *,char const *) = (void (*)(DB_ENV const *,char const *,char const *)) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_error : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } DbEnv_set_errcall(arg1,arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (jarg3 == JNI_TRUE); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_flags(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1feedback(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; void (*arg2)(DB_ENV *,int,int) = (void (*)(DB_ENV *,int,int)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_env_feedback : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_feedback(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1mp_1max_1openfd(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_mp_max_openfd(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1mp_1max_1write(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jlong jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; db_timeout_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = (db_timeout_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_mp_max_write(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1mp_1mmapsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; size_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (size_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_mp_mmapsize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1mp_1pagesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; size_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (size_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_mp_pagesize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1mp_1tablesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; size_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (size_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_mp_tablesize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1msgcall(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; void (*arg2)(DB_ENV const *,char const *) = (void (*)(DB_ENV const *,char const *)) 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_message : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } DbEnv_set_msgcall(arg1,arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1paniccall(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; void (*arg2)(DB_ENV *,int) = (void (*)(DB_ENV *,int)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_panic : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_paniccall(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1rpc_1server(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jlong jarg3, jlong jarg4, jint jarg5) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; long arg3 ; long arg4 ; u_int32_t arg5 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (long)jarg3; arg4 = (long)jarg4; arg5 = (u_int32_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_rpc_server(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1shm_1key(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; long arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (long)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_shm_key(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1timeout(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; db_timeout_t arg2 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (db_timeout_t)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_timeout(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1tmp_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_tmp_dir(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1tx_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_tx_max(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1app_1dispatch(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int (*arg2)(DB_ENV *,DBT *,DB_LSN *,db_recops) = (int (*)(DB_ENV *,DBT *,DB_LSN *,db_recops)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_app_dispatch : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_app_dispatch(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1event_1notify(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jboolean jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; void (*arg2)(DB_ENV *,u_int32_t,void *) = (void (*)(DB_ENV *,u_int32_t,void *)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (jarg2 == JNI_TRUE) ? __dbj_event_notify : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_event_notify(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1tx_1timestamp0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; time_t *arg2 = (time_t *) 0 ; time_t time2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; time2 = (time_t)jarg2; arg2 = &time2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_tx_timestamp(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1verbose(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (jarg3 == JNI_TRUE); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_verbose(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1conflicts(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; struct __db_lk_conflicts result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_get_lk_conflicts(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { int i; jbyteArray bytes; jresult = (*jenv)->NewObjectArray(jenv, (jsize)(&result)->lk_modes, bytearray_class, NULL); if (jresult == NULL) return 0; /* an exception is pending */ for (i = 0; i < (&result)->lk_modes; i++) { bytes = (*jenv)->NewByteArray(jenv, (jsize)(&result)->lk_modes); if (bytes == NULL) return 0; /* an exception is pending */ (*jenv)->SetByteArrayRegion(jenv, bytes, 0, (jsize)(&result)->lk_modes, (jbyte *)((&result)->lk_conflicts + i * (&result)->lk_modes)); (*jenv)->SetObjectArrayElement(jenv, jresult, (jsize)i, bytes); } } return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1detect(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lk_detect(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1max_1locks(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lk_max_locks(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1max_1lockers(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lk_max_lockers(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1max_1objects(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lk_max_objects(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lk_1partitions(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lk_partitions(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1detect(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; u_int32_t arg3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_lock_detect(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3, jobject jarg4, jint jarg5) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; u_int32_t arg3 ; DBT *arg4 = (DBT *) 0 ; db_lockmode_t arg5 ; DBT_LOCKED ldbt4 ; DB_LOCK *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (u_int32_t)jarg3; if (__dbj_dbt_copyin(jenv, &ldbt4, &arg4, jarg4, 0) != 0) { return 0; /* An exception will be pending. */ } arg5 = (db_lockmode_t)jarg5; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_LOCK *)DbEnv_lock_get(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } *(DB_LOCK **)&jresult = result; __dbj_dbt_release(jenv, jarg4, arg4, &ldbt4); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1id(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_lock_id(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1id_1free(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_lock_id_free(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1put(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_LOCK *arg2 = (DB_LOCK *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbEnv **)&jarg1; arg2 = *(DB_LOCK **)&jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_lock_put(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1lock_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_LOCK_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_LOCK_STAT *)DbEnv_lock_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, lock_stat_class, lock_stat_construct); if (jresult != NULL) __dbj_fill_lock_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1conflicts(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobjectArray jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; struct __db_lk_conflicts arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; { int i, len, err; size_t bytesize; len = (&arg2)->lk_modes = (*jenv)->GetArrayLength(jenv, jarg2); bytesize = sizeof(u_char) * len * len; if ((err = __os_malloc(NULL, bytesize, &(&arg2)->lk_conflicts)) != 0) { __dbj_throw(jenv, err, NULL, NULL, JDBENV); return ; } for (i = 0; i < len; i++) { jobject sub_array = (*jenv)->GetObjectArrayElement(jenv, jarg2, i); (*jenv)->GetByteArrayRegion(jenv,(jbyteArray)sub_array, 0, len, (jbyte *)&(&arg2)->lk_conflicts[i * len]); } } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_conflicts(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } __os_free(NULL, (&arg2)->lk_conflicts); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1detect(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_detect(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1max_1lockers(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_max_lockers(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1max_1locks(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_max_locks(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1max_1objects(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_max_objects(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lk_1partitions(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lk_partitions(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lg_1bsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lg_bsize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lg_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_get_lg_dir(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lg_1filemode(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_lg_filemode(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lg_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lg_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1lg_1regionmax(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_lg_regionmax(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1archive(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; char **result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char **)DbEnv_log_archive(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { if (result != NULL) { /*@SWIG:../libdb_java/java_typemaps.i,367,STRING_ARRAY_OUT@*/ int i, len; len = 0; while (result[len] != NULL) len++; if ((jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, string_class, NULL)) == NULL) return 0; /* an exception is pending */ for (i = 0; i < len; i++) { jstring str = (*jenv)->NewStringUTF(jenv, result[i]); (*jenv)->SetObjectArrayElement(jenv, jresult, (jsize)i, str); } /*@SWIG@*/ __os_ufree(NULL, result); } } return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1compare(JNIEnv *jenv, jclass jcls, jobject jarg1, jobject jarg2) { jint jresult = 0 ; DB_LSN *arg1 = (DB_LSN *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DB_LSN lsn1 ; DB_LSN lsn2 ; int result; (void)jenv; (void)jcls; if (jarg1 == NULL) { arg1 = NULL; } else { arg1 = &lsn1; arg1->file = (*jenv)->GetIntField(jenv, jarg1, dblsn_file_fid); arg1->offset = (*jenv)->GetIntField(jenv, jarg1, dblsn_offset_fid); } if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (arg1 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return 0; } if (arg2 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return 0; } result = (int)DbEnv_log_compare((struct DbLsn const *)arg1,(struct DbLsn const *)arg2); jresult = (jint)result; if (jarg1 != NULL) { (*jenv)->SetIntField(jenv, jarg1, dblsn_file_fid, arg1->file); (*jenv)->SetIntField(jenv, jarg1, dblsn_offset_fid, arg1->offset); } if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1cursor(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_LOGC *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_LOGC *)DbEnv_log_cursor(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } *(DB_LOGC **)&jresult = result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1file(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DB_LSN lsn2 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } if (arg2 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_log_file(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1flush(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DB_LSN lsn2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_log_flush(arg1,(struct DbLsn const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1get_1config(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jboolean jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int_bool)DbEnv_log_get_config(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1put(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jint jarg4) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DB_LSN lsn2 ; DBT_LOCKED ldbt3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return ; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } if (arg2 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return ; } result = (db_ret_t)DbEnv_log_put(arg1,arg2,(struct Dbt const *)arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1print(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jstring jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; char *arg3 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbEnv **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = 0; if (jarg3) { arg3 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg3, 0); if (!arg3) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_log_print(arg1,arg2,(char const *)arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg3) (*jenv)->ReleaseStringUTFChars(jenv, jarg3, (const char *)arg3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1set_1config(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (jarg3 == JNI_TRUE); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_log_set_config(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1log_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_LOG_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_LOG_STAT *)DbEnv_log_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, log_stat_class, log_stat_construct); if (jresult != NULL) __dbj_fill_log_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lg_1bsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lg_bsize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lg_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lg_dir(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lg_1filemode(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lg_filemode(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lg_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lg_max(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1set_1lg_1regionmax(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_set_lg_regionmax(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_get_cachesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1cachesize_1ncache(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_cachesize_ncache(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1cache_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_get_cache_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1create_1dir(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbEnv_get_create_dir(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1max_1openfd(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_mp_max_openfd(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1max_1write(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_mp_max_write(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1max_1write_1sleep(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; db_timeout_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_timeout_t)DbEnv_get_mp_max_write_sleep(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jlong)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1mmapsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; size_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_get_mp_mmapsize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jlong)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1pagesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_mp_pagesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1mp_1tablesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_get_mp_tablesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1memp_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_MPOOL_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_MPOOL_STAT *)DbEnv_memp_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, mpool_stat_class, mpool_stat_construct); if (jresult != NULL) __dbj_fill_mpool_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1memp_1fstat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_MPOOL_FSTAT **result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_MPOOL_FSTAT **)DbEnv_memp_fstat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { int i, len; len = 0; while (result[len] != NULL) len++; jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, mpool_fstat_class, 0); if (jresult == NULL) { __os_ufree(NULL, result); return 0; } for (i = 0; i < len; i++) { jobject obj = (*jenv)->NewObject(jenv, mpool_fstat_class, mpool_fstat_construct); if (obj == NULL) { __os_ufree(NULL, result); return 0; /* an exception is pending */ } (*jenv)->SetObjectArrayElement(jenv, jresult, i, obj); __dbj_fill_mpool_fstat(jenv, obj, result[i]); } __os_ufree(NULL, result); } return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1memp_1sync(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DB_LSN lsn2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } if (arg2 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return ; } errno = 0; result = (db_ret_t)DbEnv_memp_sync(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1memp_1trickle(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_memp_trickle(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1get_1align(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_mutex_get_align(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1get_1increment(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_mutex_get_increment(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1get_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_mutex_get_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1get_1tas_1spins(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_mutex_get_tas_spins(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1set_1align(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_mutex_set_align(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1set_1increment(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_mutex_set_increment(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1set_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_mutex_set_max(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1set_1tas_1spins(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_mutex_set_tas_spins(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1mutex_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_MUTEX_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_MUTEX_STAT *)DbEnv_mutex_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, mutex_stat_class, mutex_stat_construct); if (jresult != NULL) __dbj_fill_mutex_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1tx_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_get_tx_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1tx_1timestamp(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; time_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_get_tx_timestamp(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jlong)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1timeout(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_timeout_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_timeout_t)DbEnv_get_timeout(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jlong)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1txn_1begin(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; u_int32_t arg3 ; DB_TXN *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbEnv **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_TXN *)DbEnv_txn_begin(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } *(DB_TXN **)&jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1txn_1checkpoint(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3, jint jarg4) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; u_int32_t arg3 ; u_int32_t arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (u_int32_t)jarg3; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_txn_checkpoint(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1txn_1recover(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; u_int32_t arg3 ; DB_PREPLIST *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_PREPLIST *)DbEnv_txn_recover(arg1,arg2,arg3); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { int i, len; len = 0; while (result[len].txn != NULL) len++; jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, dbpreplist_class, NULL); if (jresult == NULL) return 0; /* an exception is pending */ for (i = 0; i < len; i++) { jobject jtxn = (*jenv)->NewObject(jenv, dbtxn_class, dbtxn_construct, result[i].txn, JNI_FALSE); jobject bytearr = (*jenv)->NewByteArray(jenv, (jsize)sizeof(result[i].gid)); jobject obj = (*jenv)->NewObject(jenv, dbpreplist_class, dbpreplist_construct, jtxn, bytearr); if (jtxn == NULL || bytearr == NULL || obj == NULL) return 0; /* An exception is pending */ (*jenv)->SetByteArrayRegion(jenv, bytearr, 0, (jsize)sizeof(result[i].gid), (jbyte *)result[i].gid); (*jenv)->SetObjectArrayElement(jenv, jresult, i, obj); } __os_ufree(NULL, result); } return jresult; } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1txn_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_TXN_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_TXN_STAT *)DbEnv_txn_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { unsigned int i; jobjectArray actives; jresult = (*jenv)->NewObject(jenv, txn_stat_class, txn_stat_construct); if (jresult != NULL) __dbj_fill_txn_stat(jenv, jresult, result); actives = (*jenv)->NewObjectArray(jenv, (jsize)result->st_nactive, txn_active_class, 0); if (actives == NULL) { __os_ufree(NULL, result); return 0; } (*jenv)->SetObjectField(jenv, jresult, txn_stat_st_txnarray_fid, actives); for (i = 0; i < result->st_nactive; i++) { jobject obj = (*jenv)->NewObject(jenv, txn_active_class, txn_active_construct); if (obj == NULL) { __os_ufree(NULL, result); return 0; /* an exception is pending */ } (*jenv)->SetObjectArrayElement(jenv, actives, (jsize)i, obj); __dbj_fill_txn_active(jenv, obj, &result->st_txnarray[i]); } __os_ufree(NULL, result); } return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1limit(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_rep_get_limit(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1elect(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3, jint jarg4) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int arg3 ; u_int32_t arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (int)jarg3; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_elect(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1process_1message(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jint jarg4, jobject jarg5) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT *arg3 = (DBT *) 0 ; int arg4 ; DB_LSN *arg5 = (DB_LSN *) 0 ; DBT_LOCKED ldbt2 ; DBT_LOCKED ldbt3 ; DB_LSN lsn5 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return 0; /* An exception will be pending. */ } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } arg4 = (int)jarg4; if (jarg5 == NULL) { arg5 = NULL; } else { arg5 = &lsn5; arg5->file = (*jenv)->GetIntField(jenv, jarg5, dblsn_file_fid); arg5->offset = (*jenv)->GetIntField(jenv, jarg5, dblsn_offset_fid); } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } if (arg5 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return 0; } result = (int)DbEnv_rep_process_message(arg1,arg2,arg3,arg4,arg5); if (!DB_RETOK_REPPMSG(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } jresult = (jint)result; __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); if (jarg5 != NULL) { (*jenv)->SetIntField(jenv, jarg5, dblsn_file_fid, arg5->file); (*jenv)->SetIntField(jenv, jarg5, dblsn_offset_fid, arg5->offset); } return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1flush(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_flush(arg1); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1config(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (jarg3 == JNI_TRUE); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_config(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1clockskew(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_clockskew(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1clockskew_1fast(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_clockskew_fast(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1clockskew_1slow(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_clockskew_slow(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1start(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; DBT *arg2 = (DBT *) 0 ; u_int32_t arg3 ; DBT_LOCKED ldbt2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 1) != 0) { return ; /* An exception will be pending. */ } arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_start(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1sync(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_sync(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jboolean JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1config(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jboolean jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; int_bool result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int_bool)DbEnv_rep_get_config(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (result) ? JNI_TRUE : JNI_FALSE; return jresult; } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_REP_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_REP_STAT *)DbEnv_rep_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, rep_stat_class, rep_stat_construct); if (jresult != NULL) __dbj_fill_rep_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1limit(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; jlong arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_limit(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1request_1min(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_request_min(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1request_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_request_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1request(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_request(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1transport(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; int (*arg3)(DB_ENV *,DBT const *,DBT const *,DB_LSN const *,int,u_int32_t) = (int (*)(DB_ENV *,DBT const *,DBT const *,DB_LSN const *,int,u_int32_t)) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = (jarg3 == JNI_TRUE) ? __dbj_rep_transport : NULL; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_transport(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1nsites(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_nsites(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_priority(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1get_1timeout(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbEnv_rep_get_timeout(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1nsites(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_nsites(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_priority(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1rep_1set_1timeout(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jlong jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; db_timeout_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = (db_timeout_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_rep_set_timeout(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1add_1remote_1site(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3, jint jarg4) { jint jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; u_int32_t arg4 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return 0; } arg3 = (u_int32_t)jarg3; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int)DbEnv_repmgr_add_remote_site(arg1,(char const *)arg2,arg3,arg4); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (jint)result; if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1get_1ack_1policy(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_repmgr_get_ack_policy(arg1); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1set_1ack_1policy(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_repmgr_set_ack_policy(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1set_1local_1site(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2, jint jarg3, jint jarg4) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; char *arg2 = (char *) 0 ; u_int32_t arg3 ; u_int32_t arg4 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } arg3 = (u_int32_t)jarg3; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_repmgr_set_local_site(arg1,(char const *)arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } SWIGEXPORT jobjectArray JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1site_1list(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jobjectArray jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; struct __db_repmgr_sites result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbEnv_repmgr_site_list(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } { int i, len; jobject jrep_addr, jrep_info; len = (&result)->nsites; jresult = (*jenv)->NewObjectArray(jenv, (jsize)len, repmgr_siteinfo_class, NULL); if (jresult == NULL) return 0; /* an exception is pending */ for (i = 0; i < len; i++) { jstring addr_host = (*jenv)->NewStringUTF(jenv, (&result)->sites[i].host); if (addr_host == NULL) return 0; /* An exception is pending */ jrep_addr = (*jenv)->NewObject(jenv, rephost_class, rephost_construct, addr_host, (&result)->sites[i].port); if (jrep_addr == NULL) return 0; /* An exception is pending */ jrep_info = (*jenv)->NewObject(jenv, repmgr_siteinfo_class, repmgr_siteinfo_construct, jrep_addr, (&result)->sites[i].eid); (*jenv)->SetIntField(jenv, jrep_info, repmgr_siteinfo_status_fid, (&result)->sites[i].status); if (jrep_info == NULL) return 0; /* An exception is pending */ (*jenv)->SetObjectArrayElement(jenv, jresult, i, jrep_info); } __os_ufree(NULL, (&result)->sites); } return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1start(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jint jarg3) { struct DbEnv *arg1 = (struct DbEnv *) 0 ; int arg2 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (int)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbEnv_repmgr_start(arg1,arg2,arg3); if (!DB_RETOK_REPMGR_START(result)) { __dbj_throw(jenv, result, NULL, NULL, JDBENV); } } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1repmgr_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbEnv *arg1 = (struct DbEnv *) 0 ; u_int32_t arg2 ; DB_REPMGR_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbEnv **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_REPMGR_STAT *)DbEnv_repmgr_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, JDBENV); } jresult = (*jenv)->NewObject(jenv, repmgr_stat_class, repmgr_stat_construct); if (jresult != NULL) __dbj_fill_repmgr_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1strerror(JNIEnv *jenv, jclass jcls, jint jarg1) { jstring jresult = 0 ; int arg1 ; char *result = 0 ; (void)jenv; (void)jcls; arg1 = (int)jarg1; result = (char *)DbEnv_strerror(arg1); if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1version_1major(JNIEnv *jenv, jclass jcls) { jint jresult = 0 ; int result; (void)jenv; (void)jcls; result = (int)DbEnv_get_version_major(); jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1version_1minor(JNIEnv *jenv, jclass jcls) { jint jresult = 0 ; int result; (void)jenv; (void)jcls; result = (int)DbEnv_get_version_minor(); jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1version_1patch(JNIEnv *jenv, jclass jcls) { jint jresult = 0 ; int result; (void)jenv; (void)jcls; result = (int)DbEnv_get_version_patch(); jresult = (jint)result; return jresult; } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbEnv_1get_1version_1string(JNIEnv *jenv, jclass jcls) { jstring jresult = 0 ; char *result = 0 ; (void)jenv; (void)jcls; result = (char *)DbEnv_get_version_string(); if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_delete_1DbLock(JNIEnv *jenv, jclass jcls, jlong jarg1) { struct DbLock *arg1 = (struct DbLock *) 0 ; (void)jenv; (void)jcls; arg1 = *(struct DbLock **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } delete_DbLock(arg1); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbLogc_1close0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbLogc *arg1 = (struct DbLogc *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbLogc **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbLogc_close(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbLogc_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2, jobject jarg3, jint jarg4) { jint jresult = 0 ; struct DbLogc *arg1 = (struct DbLogc *) 0 ; DB_LSN *arg2 = (DB_LSN *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DB_LSN lsn2 ; DBT_LOCKED ldbt3 ; int result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbLogc **)&jarg1; if (jarg2 == NULL) { arg2 = NULL; } else { arg2 = &lsn2; arg2->file = (*jenv)->GetIntField(jenv, jarg2, dblsn_file_fid); arg2->offset = (*jenv)->GetIntField(jenv, jarg2, dblsn_offset_fid); } if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return 0; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } if (arg2 == NULL) { __dbj_throw(jenv, EINVAL, "null LogSequenceNumber", NULL, NULL); return 0; } result = (int)DbLogc_get(arg1,arg2,arg3,arg4); if (!DB_RETOK_LGGET(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } jresult = (jint)result; if (jarg2 != NULL) { (*jenv)->SetIntField(jenv, jarg2, dblsn_file_fid, arg2->file); (*jenv)->SetIntField(jenv, jarg2, dblsn_offset_fid, arg2->offset); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbLogc_1version(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jint jresult = 0 ; struct DbLogc *arg1 = (struct DbLogc *) 0 ; u_int32_t arg2 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbLogc **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbLogc_version(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1get_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; DB_CACHE_PRIORITY result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_CACHE_PRIORITY)DbMpoolFile_get_priority(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1set_1priority(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; DB_CACHE_PRIORITY arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; arg2 = (DB_CACHE_PRIORITY)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbMpoolFile_set_priority(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1get_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbMpoolFile_get_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1set_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2, jboolean jarg3) { struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; u_int32_t arg2 ; int_bool arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; arg2 = (u_int32_t)jarg2; arg3 = (jarg3 == JNI_TRUE); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbMpoolFile_set_flags(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1get_1maxsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; jlong result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = DbMpoolFile_get_maxsize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbMpoolFile_1set_1maxsize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbMpoolFile *arg1 = (struct DbMpoolFile *) 0 ; jlong arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbMpoolFile **)&jarg1; arg2 = jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbMpoolFile_set_maxsize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_new_1DbSequence(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jlong jresult = 0 ; DB *arg1 = (DB *) 0 ; u_int32_t arg2 ; struct DbSequence *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(DB **)&jarg1; arg2 = (u_int32_t)jarg2; errno = 0; result = (struct DbSequence *)new_DbSequence(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } *(struct DbSequence **)&jresult = result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1close0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_close(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3, jint jarg4) { jlong jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; int32_t arg3 ; u_int32_t arg4 ; db_seq_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbSequence **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (int32_t)jarg3; arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_seq_t)DbSequence_get(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jlong)result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (int32_t)DbSequence_get_cachesize(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1db(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; DB *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB *)DbSequence_get_db(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } *(DB **)&jresult = result; return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (u_int32_t)DbSequence_get_flags(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1key(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jobject jarg2) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; DBT *arg2 = (DBT *) 0 ; DBT_LOCKED ldbt2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (__dbj_dbt_copyin(jenv, &ldbt2, &arg2, jarg2, 0) != 0) { return ; /* An exception will be pending. */ } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_get_key(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } __dbj_dbt_release(jenv, jarg2, arg2, &ldbt2); } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1range_1min(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; db_seq_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_seq_t)DbSequence_get_range_min(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jlong)result; return jresult; } SWIGEXPORT jlong JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1get_1range_1max(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jlong jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; db_seq_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (db_seq_t)DbSequence_get_range_max(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (jlong)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1initial_1value(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; db_seq_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (db_seq_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_initial_value(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1open(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jobject jarg3, jint jarg4) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; DBT *arg3 = (DBT *) 0 ; u_int32_t arg4 ; DBT_LOCKED ldbt3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbSequence **)&jarg1; arg2 = *(DB_TXN **)&jarg2; if (__dbj_dbt_copyin(jenv, &ldbt3, &arg3, jarg3, 0) != 0) { return ; /* An exception will be pending. */ } arg4 = (u_int32_t)jarg4; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_open(arg1,arg2,arg3,arg4); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } __dbj_dbt_release(jenv, jarg3, arg3, &ldbt3); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1remove0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jobject jarg2_, jint jarg3) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; DB_TXN *arg2 = (DB_TXN *) 0 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; (void)jarg2_; arg1 = *(struct DbSequence **)&jarg1; arg2 = *(DB_TXN **)&jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_remove(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1set_1cachesize(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_set_cachesize(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1set_1flags(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_set_flags(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1set_1range(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jlong jarg3) { struct DbSequence *arg1 = (struct DbSequence *) 0 ; db_seq_t arg2 ; db_seq_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (db_seq_t)jarg2; arg3 = (db_seq_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbSequence_set_range(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jobject JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbSequence_1stat(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { jobject jresult = 0 ; struct DbSequence *arg1 = (struct DbSequence *) 0 ; u_int32_t arg2 ; DB_SEQUENCE_STAT *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbSequence **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (DB_SEQUENCE_STAT *)DbSequence_stat(arg1,arg2); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, NULL); } jresult = (*jenv)->NewObject(jenv, seq_stat_class, seq_stat_construct); if (jresult != NULL) __dbj_fill_seq_stat(jenv, jresult, result); __os_ufree(NULL, result); return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1abort0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbTxn_abort(arg1); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1commit0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbTxn_commit(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1discard0(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; u_int32_t arg2 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; arg2 = (u_int32_t)jarg2; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbTxn_discard(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, NULL); } } SWIGEXPORT jstring JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1get_1name(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jstring jresult = 0 ; struct DbTxn *arg1 = (struct DbTxn *) 0 ; char *result = 0 ; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } errno = 0; result = (char *)DbTxn_get_name(arg1); if (!DB_RETOK_STD(errno)) { __dbj_throw(jenv, errno, NULL, NULL, TXN2JDBENV); } if(result) jresult = (*jenv)->NewStringUTF(jenv, (const char *)result); return jresult; } SWIGEXPORT jint JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1id(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_) { jint jresult = 0 ; struct DbTxn *arg1 = (struct DbTxn *) 0 ; u_int32_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return 0; } result = (u_int32_t)DbTxn_id(arg1); jresult = (jint)result; return jresult; } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1prepare(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jbyteArray jarg2) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; u_int8_t *arg2 = (u_int8_t *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; arg2 = (u_int8_t *)(*jenv)->GetByteArrayElements(jenv, jarg2, NULL); if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } if ((*jenv)->GetArrayLength(jenv, jarg2) < DB_GID_SIZE) { __dbj_throw(jenv, EINVAL, "DbTxn.prepare gid array must be >= 128 bytes", NULL, TXN2JDBENV); return ; } result = (db_ret_t)DbTxn_prepare(arg1,arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, TXN2JDBENV); } (*jenv)->ReleaseByteArrayElements(jenv, jarg2, (jbyte *)arg2, 0); } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1set_1timeout(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jlong jarg2, jint jarg3) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; db_timeout_t arg2 ; u_int32_t arg3 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; arg2 = (db_timeout_t)jarg2; arg3 = (u_int32_t)jarg3; if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbTxn_set_timeout(arg1,arg2,arg3); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, TXN2JDBENV); } } SWIGEXPORT void JNICALL Java_com_sleepycat_db_internal_db_1javaJNI_DbTxn_1set_1name(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jstring jarg2) { struct DbTxn *arg1 = (struct DbTxn *) 0 ; char *arg2 = (char *) 0 ; db_ret_t result; (void)jenv; (void)jcls; (void)jarg1_; arg1 = *(struct DbTxn **)&jarg1; arg2 = 0; if (jarg2) { arg2 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg2, 0); if (!arg2) return ; } if (jarg1 == 0) { __dbj_throw(jenv, EINVAL, "call on closed handle", NULL, NULL); return ; } result = (db_ret_t)DbTxn_set_name(arg1,(char const *)arg2); if (!DB_RETOK_STD(result)) { __dbj_throw(jenv, result, NULL, NULL, TXN2JDBENV); } if (arg2) (*jenv)->ReleaseStringUTFChars(jenv, jarg2, (const char *)arg2); } #ifdef __cplusplus } #endif
29.257708
237
0.686683
[ "object" ]
1e146fbad3b4311f0d1b35b17179616c67436d34
3,267
c
C
source/objects/backgrounds/AwesomeCloud/AwesomeCloudBgmapSprite.c
VUEngine/VUEngine-Platformer-Demo
90b249ba9a8c281a455b9919eef462d8076d111f
[ "MIT" ]
2
2021-01-09T19:24:07.000Z
2021-09-02T04:31:52.000Z
source/objects/backgrounds/AwesomeCloud/AwesomeCloudBgmapSprite.c
VUEngine/VUEngine-Platformer-Demo
90b249ba9a8c281a455b9919eef462d8076d111f
[ "MIT" ]
null
null
null
source/objects/backgrounds/AwesomeCloud/AwesomeCloudBgmapSprite.c
VUEngine/VUEngine-Platformer-Demo
90b249ba9a8c281a455b9919eef462d8076d111f
[ "MIT" ]
null
null
null
/** * VUEngine Platformer Demo * * © Jorge Eremiev <jorgech3@gmail.com> and Christian Radke <c.radke@posteo.de> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ //--------------------------------------------------------------------------------------------------------- // INCLUDES //--------------------------------------------------------------------------------------------------------- #include <AwesomeCloudBgmapSprite.h> #include <BgmapTexture.h> //--------------------------------------------------------------------------------------------------------- // CLASS' MACROS //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- // CLASS'S DEFINITION //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- // CLASS'S METHODS //--------------------------------------------------------------------------------------------------------- /** * Class constructor * * @memberof AwesomeCloudBgmapSprite * @public * * @param AwesomeCloudBgmapSpriteSpec Spec to use * @param owner Sprite's owner */ void AwesomeCloudBgmapSprite::constructor(const AwesomeCloudBgmapSpriteSpec* awesomeCloudBgmapSpriteSpec, Object owner) { Base::constructor(&awesomeCloudBgmapSpriteSpec->bgmapSpriteSpec, owner); this->awesomeCloudBgmapSpriteSpec = (AwesomeCloudBgmapSpriteSpec*)awesomeCloudBgmapSpriteSpec; } /** * Class destructor * * @memberof AwesomeCloudBgmapSprite * @public */ void AwesomeCloudBgmapSprite::destructor() { // destroy the super object // must always be called at the end of the destructor Base::destructor(); } /** * Calculate 2D position * * @memberof AwesomeCloudBgmapSprite * @public * * @param position 3D position */ void AwesomeCloudBgmapSprite::position(const Vector3D* position) { Base::position(this, position); } /** * Set 2D position * * @memberof BgmapSprite * @public * * @param position New 2D position */ void AwesomeCloudBgmapSprite::setPosition(const PixelVector* position) { Base::setPosition(this, position); } /** * Write WORLD data to DRAM * * @memberof AwesomeCloudBgmapSprite * @public */ uint16 AwesomeCloudBgmapSprite::doRender(uint16 index, bool evenFrame) { this->drawSpec.textureSource.my += this->awesomeCloudBgmapSpriteSpec->myStep; if((uint16)this->drawSpec.textureSource.my >= (BgmapTexture::getYOffset(this->texture) << 3) + (BgmapTexture::getRows(this->texture) << 3)) { this->drawSpec.textureSource.my = (BgmapTexture::getYOffset(this->texture) << 3); } BgmapSprite::invalidateParamTable(this); uint16 result = Base::doRender(this, index, evenFrame); static WorldAttributes* worldPointer = NULL; worldPointer = &_worldAttributesBaseAddress[index]; //worldPointer->gx -= 20; //worldPointer->w = __SCREEN_WIDTH + 19; worldPointer->h -= 4; // Sprite::print(this, 20, 1); return result; }
27.225
140
0.525865
[ "object", "3d" ]
1e15c67196b75b3cc6890bb68bcc826d1fc60934
2,317
h
C
devmand/gateway/src/devmand/channels/cli/Command.h
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
2
2020-12-09T11:42:30.000Z
2021-09-26T03:28:33.000Z
devmand/gateway/src/devmand/channels/cli/Command.h
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
124
2020-08-21T06:11:21.000Z
2022-03-21T05:25:26.000Z
devmand/gateway/src/devmand/channels/cli/Command.h
yogi8091/magma
edc3b249068ad871047e898c912f3228ee9f2c88
[ "BSD-3-Clause" ]
1
2020-09-21T04:25:06.000Z
2020-09-21T04:25:06.000Z
/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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 <boost/algorithm/string/replace.hpp> #include <folly/futures/Future.h> #include <atomic> #include <iostream> using std::string; using std::vector; namespace devmand { namespace channels { namespace cli { /* * Command struct encapsulating a string to be executed on a device. */ static std::atomic<int> commandCounter; class Command { protected: explicit Command(std::string _command, int idx, bool skipCache); string command; int idx; bool skipCache_; public: Command() = delete; bool isMultiCommand(); vector<Command> splitMultiCommand(); string raw() const { return command; } bool skipCache() const { return skipCache_; } static string escape(string cmd) { boost::replace_all(cmd, "\n", "\\n"); boost::replace_all(cmd, "\r", "\\r"); boost::replace_all(cmd, "\t", "\\t"); boost::replace_all(cmd, "\"", "\\\""); return cmd; } friend std::ostream& operator<<(std::ostream& _stream, Command const& c) { _stream << "[" << c.idx << "] " << Command::escape(c.raw()); return _stream; } }; class WriteCommand : public Command { public: static WriteCommand create(const std::string& cmd, bool skipCache = false); static WriteCommand create(const Command& cmd); WriteCommand(const WriteCommand& wc); WriteCommand& operator=(const WriteCommand& other); private: WriteCommand(const string& command, int idx, bool skipCache); }; class ReadCommand : public Command { public: static ReadCommand create(const std::string& cmd, bool skipCache = false); static ReadCommand create(const Command& cmd); ReadCommand& operator=(const ReadCommand& other); ReadCommand(const ReadCommand& rc); private: ReadCommand(const string& command, int idx, bool skipCache); }; } // namespace cli } // namespace channels } // namespace devmand
24.913978
77
0.712559
[ "vector" ]
1e1a33496d9c7e0f559e6426a4886d22cf9741e0
3,209
h
C
Sorting/SortingShared/SortThreadFunction.h
marcusolini/CrackingCoding
410ac96b7caf006a685bb694e2d87dcc1c9529df
[ "MIT" ]
null
null
null
Sorting/SortingShared/SortThreadFunction.h
marcusolini/CrackingCoding
410ac96b7caf006a685bb694e2d87dcc1c9529df
[ "MIT" ]
null
null
null
Sorting/SortingShared/SortThreadFunction.h
marcusolini/CrackingCoding
410ac96b7caf006a685bb694e2d87dcc1c9529df
[ "MIT" ]
null
null
null
// Copyright 2018 marcusolini@outlook.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. #ifndef SORT_THREAD_FUNCTION_H #define SORT_THREAD_FUNCTION_H #ifdef _WIN32 #include <Windows.h> #else #endif // _WIN32 #include <stdio.h> #include <thread> #include <atomic> #include <vector> #include <sstream> #include <mutex> #include "SortTest.h" #include "../../Error_Checks/ERROR_CHECKS.H" // SORT THREAD FUNCTION static void SortThreadFunction(CSortTest* iTest) { int nStatus = 0; std::wstringstream ss; uint64_t id = 0; std::vector<int> vArray; int* tempArray = nullptr; int* iTempArray = nullptr; std::size_t tempArraySize = 0; std::size_t nNumberOfSorts = 0; std::chrono::duration<double> duration; bool bSortCorrect = false; try { std::this_thread::yield(); iTest->SetState(CSortTest::ESTATE_TYPE::STARTED); ss << std::this_thread::get_id(); id = std::stoull(ss.str()); iTest->SetThreadId(id); std::this_thread::sleep_for(std::chrono::milliseconds{ 750 }); // For Progress Bar Show iTest->SetState(CSortTest::ESTATE_TYPE::RUNNING); // Convet vector to array. vArray = iTest->GetArray(); tempArraySize = vArray.size(); tempArray = new int[tempArraySize]; iTempArray = tempArray; for (auto& iArray : vArray) { *iTempArray = iArray; iTempArray += 1; } switch (iTest->GetSortType()) { case CSortTest::ESORT_TYPE::QUICK_SORT: CHECK_SUCCEEDED_LOG_THROW((CSorting<int, std::size_t>::Sort(ESortingTypes::QuickSort, tempArray, tempArraySize, &nNumberOfSorts, &duration))); break; case CSortTest::ESORT_TYPE::MERGE_SORT: CHECK_SUCCEEDED_LOG_THROW((CSorting<int, std::size_t>::Sort(ESortingTypes::MergeSort, tempArray, tempArraySize, &nNumberOfSorts, &duration))); break; case CSortTest::ESORT_TYPE::BUBBLE_SORT: CHECK_SUCCEEDED_LOG_THROW((CSorting<int, std::size_t>::Sort(ESortingTypes::BubbleSort, tempArray, tempArraySize, &nNumberOfSorts, &duration))); break; default: break; } vArray.clear(); for (std::size_t nIndex = 0; nIndex < tempArraySize; nIndex++) { vArray.push_back(tempArray[nIndex]); } iTest->SetSortedArray(vArray); iTest->SetNumberOfSorts(nNumberOfSorts); iTest->SetDuration(duration); CHECK_SUCCEEDED_LOG_THROW((CSorting<int, std::size_t>::VerifySort(tempArray, tempArraySize, bSortCorrect))); CHECK_BOOL_TRUE_LOG_THROW(bSortCorrect); iTest->SetState(CSortTest::ESTATE_TYPE::SUCCESS); } catch (long& check_catch_lresult) { nStatus = check_catch_lresult; iTest->SetError(nStatus); iTest->SetState(CSortTest::ESTATE_TYPE::FAILED); } iTest->SetIsComplete(); } #endif // SORT_THREAD_FUNCTION_H
27.904348
158
0.616391
[ "vector" ]
1e205f4f37f476288c799f1e37c6740f5ef8cb07
5,072
h
C
include/GLUtilities.h
stonexjr/davinci
40793f19de0919e5d74ecb0de10524c4bd10f084
[ "MIT" ]
1
2018-06-06T13:20:49.000Z
2018-06-06T13:20:49.000Z
include/GLUtilities.h
stonexjr/davinci
40793f19de0919e5d74ecb0de10524c4bd10f084
[ "MIT" ]
null
null
null
include/GLUtilities.h
stonexjr/davinci
40793f19de0919e5d74ecb0de10524c4bd10f084
[ "MIT" ]
null
null
null
/* Copyright (c) 2013-2017 Jinrong Xie (jrxie at ucdavis dot edu) 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. */ //AUTHOR: Jinrong Xie (stonexjr at gmail.com) //CREATED: 2014-03-03 //UPDATED: 2017-10-15 #ifndef _GL_UTILITIES_H_ #define _GL_UTILITIES_H_ #ifdef ENABLE_QT #include <QImage> #endif // ENABLE_QT #include <unordered_map> #include "GLTexture2D.h" #include "constant.h" #include "vec2d.h" #include "mat4.h" #include "BBox2D.h" namespace davinci{ class BBox; class vec4i; class GLUtilities { public: GLUtilities(void); ~GLUtilities(void); static bool checkGLExtension(std::string extension_string); //begin 2D setting, origin of the coordinate system is at the lower left corner //of the screen by default.x-axis is pointing to the right , y-axis is pointing upwards. static void glBegin2D(int scr_width, int scr_height); static void glEnd2D(); //begin 2D setting, origin of the coordinate system is at the center //of the screen by default. x-axis is pointing to the right , y-axis is //pointing upwards. static void glBegin2DCoords(int scrWidth, int scrHeight); static void glEnd2DCoords(); static void glBegin3D(int scr_width, int scr_height); static void glEnd3D(); static void glDrawQuad2Di(davinci::BBox2D& bbox, bool fill); static void glDrawQuad2Di(int xstart, int ystart, int width, int height,bool fill); static void glDrawQuad2Df(davinci::BBox2D& bbox,bool fill ); static void glDrawQuad2Df( float xstart, float ystart, float width, float height,bool fill ); static void glDrawQuad2Df( float xstart, float ystart, float width, float height, float angle ); static void glDrawWedge2Df( float xstart, float ystart, float width, float height, float skew_ratio, bool bFill ); static void glDrawQuadBeveled2Df( float xstart, float ystart, float width, float height, float bevel_ratio, bool bFill ); static void glDrawBackgroundGradient(float w, float h,const float start[4],const float end[4]); //b: bounding box you want to draw //option: 0: wireframe model // 1: filled model static void freeResource(); #ifdef ENABLE_QT //return a pointer to the sub-block of of current frame buffer. //(x,y) is the frame buffer coordinates where x-axis points to the right //and y-axis points upwards. //fileName: full path name of image file to which the frame buffer is saved. //whichBuffer: Indicate which buffer to grab. By default it is GL_BACK //If framebuffer object is used, whichBuffer should refer to one of the //color attachment, i.e. GL_COLORATTACHMENT_0/1/2.... static void grabFrameBuffer(int x, int y, int width, int height, const std::string& fileName, GLenum whichBuffer=GL_BACK, GLenum pixelFormat=GL_BGRA, GLenum pixelType=GL_UNSIGNED_BYTE); static QImage grabFrameBuffer( int x, int y, int width, int height, GLenum whichBuffer=GL_BACK, GLenum pixelFormat=GL_BGRA, GLenum pixelType=GL_UNSIGNED_BYTE); #endif static void glGetViewPort(vec4i& viewport); //Same as gluUnProject() to get the object coordinates that correspond to those window coordinates //srcXY: screen coordinates directly returned by local windows system, where origin is at the top left corner. //Return: output parameter, storing the transformed coordinates in object space. static vec2d PlaneUnproject(const davinci::vec2d& scrXY); static vec3f PlaneUnproject(const davinci::vec3f& scrXYZ, const davinci::mat4 &modelViewMatrix, const davinci::mat4 projMatrix, const int viewport[4]); static vec3f unProject(const vec3i& srcXYZ, const mat4& modelViewMtx, const mat4& projMtx); typedef void (*drawCallBack)(void* params); //Apply supersampling to the renderCallBack. //qualityLevel: int value ranges from 1(equivalent to no supersampling) //to 8 (highest quality). static void glSupersampling(drawCallBack renderCallBack, void* params, int qualityLevel=1); static std::unordered_map<GLint, std::string> m_openglInt2TypeName; static std::unordered_map< std::string, GLint> m_openglTypeName2Int; }; }; #endif
44.884956
153
0.758281
[ "object", "model" ]
1e23724efa3ed3651f68311119585157a88bcb36
106,084
c
C
ast-8.6.2/ellipse.c
astro-datalab/dlapps
18a338a887af19d195b5c1eeed6c0a9e38686125
[ "BSD-3-Clause" ]
1
2020-08-17T21:26:16.000Z
2020-08-17T21:26:16.000Z
ast-8.6.2/ellipse.c
noaodatalab/dlapps
33e8fc6161448f2052369b1fbe2765e854c1ac52
[ "BSD-3-Clause" ]
null
null
null
ast-8.6.2/ellipse.c
noaodatalab/dlapps
33e8fc6161448f2052369b1fbe2765e854c1ac52
[ "BSD-3-Clause" ]
null
null
null
/* *class++ * Name: * Ellipse * Purpose: * An elliptical region within a 2-dimensional Frame. * Constructor Function: c astEllipse f AST_ELLIPSE * Description: * The Ellipse class implements a Region which represents a ellipse * within a 2-dimensional Frame. * Inheritance: * The Ellipse class inherits from the Region class. * Attributes: * The Ellipse class does not define any new attributes beyond * those which are applicable to all Regions. * Functions: c In addition to those functions applicable to all Regions, the c following functions may also be applied to all Ellipses: f In addition to those routines applicable to all Regions, the f following routines may also be applied to all Ellipses: * c - astEllipsePars: Get the geometric parameters of the Ellipse f - AST_ELLIPSEPARS: Get the geometric parameters of the Ellipse * Copyright: * Copyright (C) 1997-2006 Council for the Central Laboratory of the * Research Councils * Copyright (C) 2009 Science & Technology Facilities Council. * All Rights Reserved. * Licence: * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * License along with this program. If not, see * <http://www.gnu.org/licenses/>. * Authors: * DSB: David S. Berry (Starlink) * History: * 7-SEP-2004 (DSB): * Original version. * 4-NOV-2013 (DSB): * Modify RegPins so that it can handle uncertainty regions that straddle * a discontinuity. Previously, such uncertainty Regions could have a huge * bounding box resulting in matching region being far too big. * 6-JAN-2014 (DSB): * Ensure cached information is available in RegCentre even if no new * centre is supplied. *class-- */ /* Module Macros. */ /* ============== */ /* Set the name of the class we are implementing. This indicates to the header files that define class interfaces that they should make "protected" symbols available. */ #define astCLASS Ellipse /* Include files. */ /* ============== */ /* Interface definitions. */ /* ---------------------- */ #include "globals.h" /* Thread-safe global data access */ #include "error.h" /* Error reporting facilities */ #include "memory.h" /* Memory allocation facilities */ #include "object.h" /* Base Object class */ #include "pointset.h" /* Sets of points/coordinates */ #include "region.h" /* Coordinate regions (parent class) */ #include "channel.h" /* I/O channels */ #include "box.h" /* Box Regions */ #include "wcsmap.h" /* Definitons of AST__DPI etc */ #include "circle.h" /* Interface definition for circle class */ #include "ellipse.h" /* Interface definition for this class */ #include "mapping.h" /* Position mappings */ #include "unitmap.h" /* Unit Mapping */ #include "pal.h" /* Positional astronomy library */ /* Error code definitions. */ /* ----------------------- */ #include "ast_err.h" /* AST error codes */ /* C header files. */ /* --------------- */ #include <float.h> #include <math.h> #include <stdarg.h> #include <stddef.h> #include <stdio.h> #include <string.h> /* Module Variables. */ /* ================= */ /* Address of this static variable is used as a unique identifier for member of this class. */ static int class_check; /* Pointers to parent class methods which are extended by this class. */ static AstPointSet *(* parent_transform)( AstMapping *, AstPointSet *, int, AstPointSet *, int * ); static AstMapping *(* parent_simplify)( AstMapping *, int * ); static void (* parent_setregfs)( AstRegion *, AstFrame *, int * ); static void (* parent_resetcache)( AstRegion *, int * ); #ifdef THREAD_SAFE /* Define how to initialise thread-specific globals. */ #define GLOBAL_inits \ globals->Class_Init = 0; /* Create the function that initialises global data for this module. */ astMAKE_INITGLOBALS(Ellipse) /* Define macros for accessing each item of thread specific global data. */ #define class_init astGLOBAL(Ellipse,Class_Init) #define class_vtab astGLOBAL(Ellipse,Class_Vtab) #include <pthread.h> #else /* Define the class virtual function table and its initialisation flag as static variables. */ static AstEllipseVtab class_vtab; /* Virtual function table */ static int class_init = 0; /* Virtual function table initialised? */ #endif /* External Interface Function Prototypes. */ /* ======================================= */ /* The following functions have public prototypes only (i.e. no protected prototypes), so we must provide local prototypes for use within this module. */ AstEllipse *astEllipseId_( void *, int, const double[2], const double[2], const double[2], void *, const char *, ... ); /* Prototypes for Private Member Functions. */ /* ======================================== */ static AstMapping *Simplify( AstMapping *, int * ); static AstPointSet *RegBaseMesh( AstRegion *, int * ); static AstPointSet *Transform( AstMapping *, AstPointSet *, int, AstPointSet *, int * ); static double *RegCentre( AstRegion *this, double *, double **, int, int, int * ); static int RegPins( AstRegion *, AstPointSet *, AstRegion *, int **, int * ); static int RegTrace( AstRegion *, int, double *, double **, int * ); static void Cache( AstEllipse *, int * ); static void CalcPars( AstFrame *, double[2], double[2], double[2], double *, double *, double *, int * ); static void Copy( const AstObject *, AstObject *, int * ); static void Delete( AstObject *, int * ); static void Dump( AstObject *, AstChannel *, int * ); static void EllipsePars( AstEllipse *, double[2], double *, double *, double *, double[2], double[2], int * ); static void RegBaseBox( AstRegion *this, double *, double *, int * ); static void ResetCache( AstRegion *this, int * ); static void SetRegFS( AstRegion *, AstFrame *, int * ); /* Member functions. */ /* ================= */ AstRegion *astBestEllipse_( AstPointSet *mesh, double *cen, AstRegion *unc, int *status ){ /* *+ * Name: * astBestEllipse * Purpose: * Find the best fitting Ellipse through a given mesh of points. * Type: * Protected function. * Synopsis: * #include "ellipse.h" * AstRegion *astBestEllipse( AstPointSet *mesh, double *cen, AstRegion *unc ) * Class Membership: * Ellipse member function * Description: * This function finds the best fitting Ellipse through a given mesh of * points. Ellispes are always 2-dimensional. * Parameters: * mesh * Pointer to a PointSet holding the mesh of points. They are * assumed to be in the Frame represented by "unc". * cen * Pointer to an array holding the coordinates of the new Ellipse * centre. * unc * A Region representing the uncertainty associated with each point * on the mesh. * Returned Value: * Pointer to the best fitting Ellipse. It will inherit the positional * uncertainty and Frame represented by "unc". * Implementation Deficiencies: * - The method used by this function is not very accurate, and assumes * that the supplied mesh provides uniform coverage of the entire ellipse. * Notes: * - A NULL pointer is returned if an error has already occurred, or if * this function should fail for any reason. *- */ /* Local Variables: */ AstFrame *frm; AstPointSet *ps2; AstRegion *result; double **ptr2; double **ptr; double *ang; double *dist; double *px; double *py; double a0; double a; double aa[2]; double at; double b; double c0; double c1; double c2; double c; double d; double den; double e; double f; double mn; double mx; double p[2]; double pa[2]; double pb[2]; double r1; double r2; double r3; double smn; double t1; double t2; double t3; int ip; int maxat; int np; double sw; /* Initialise */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Get no. of points in the mesh. */ np = astGetNpoint( mesh ); /* Get pointers to the axis values. */ ptr = astGetPoints( mesh ); /* Allocate work space */ dist = astMalloc( sizeof( double )*(size_t) np ); ang = astMalloc( sizeof( double )*(size_t) np ); /* Get a pointer to the Frame represented by "unc". This is the Frame to which the supplied mesh points refer. */ frm = astGetFrame( unc->frameset, AST__CURRENT ); /* Check pointers can be used safely */ if( astOK ) { /* Find the first mesh point which is at a non-zero distance from the centre. */ px = ptr[ 0 ]; py = ptr[ 1 ]; for( ip = 0; ip < np; ip++, px++, py++ ) { p[ 0 ] = *px; p[ 1 ] = *py; dist[ ip ] = astDistance( frm, cen, p ); if( dist[ ip ] != AST__BAD && dist[ ip ] != 0.0 ) { break; } else { ang[ ip ] = AST__BAD; dist[ ip ] = AST__BAD; } } /* Find a point which is this distance away from the centre along the second axis. This point is used to define zero angle when calling astAngle below. */ astOffset2( frm, cen, 0.0, dist[ ip ], aa ); ang[ ip ] = astAngle( frm, aa, cen, p ); /* Get the distance from the centre to each of the remaining mesh points. Also find the orientation of the radial lines through the centre to each mesh point. At the same time, find the index of the point with the largest radial distance. */ maxat = ip; r2 = dist[ maxat ]; ip++; px++; py++; for( ; ip < np; ip++, px++, py++ ) { p[ 0 ] = *px; p[ 1 ] = *py; dist[ ip ] = astDistance( frm, cen, p ); ang[ ip ] = astAngle( frm, aa, cen, p ); if( dist[ ip ] != AST__BAD && dist[ ip ] > r2 ) { r2 = dist[ ip ]; maxat = ip; } } /* Find the higher index neighbouring point, wrapping back to the start of the list when the end is reached. Note the radius and position angle at this neighbouring point. */ t2 = 0.0; r3 = AST__BAD; t3 = AST__BAD; a0 = ang[ maxat ]; for( ip = maxat + 1; ip < np; ip++ ) { if( dist[ ip ] != AST__BAD ) { r3 = dist[ ip ]; t3 = palDrange( ang[ ip ] - a0 ); break; } } if( r3 == AST__BAD ) { for( ip = 0; ip < maxat; ip++ ) { if( dist[ ip ] != AST__BAD ) { r3 = dist[ ip ]; t3 = palDrange( ang[ ip ] - a0 ); break; } } } /* Find the lower index neighbouring point, wrapping back to the end of the list when the start is reached. Note the radius and position angle at this neighbouring point. */ r1 = AST__BAD; t1 = AST__BAD; for( ip = maxat - 1; ip > -1; ip-- ) { if( dist[ ip ] != AST__BAD ) { r1 = dist[ ip ]; t1 = palDrange( ang[ ip ] - a0 ); break; } } if( r1 == AST__BAD ) { for( ip = np - 1; ip > maxat; ip-- ) { if( dist[ ip ] != AST__BAD ) { r1 = dist[ ip ]; t1 = palDrange( ang[ ip ] - a0 ); break; } } } /* Fit a quadratic through the three pairs of (radius,angle) values. The centre point (r2,t2) is the point which is furthest from the centre, and the other two are the neighbouring points found above. */ a = r2 - r1; b = t2 - t1; c = t2*t2 - t1*t1; d = r3 - r2; e = t3 - t2; f = t3*t3 - t2*t2; den = c*e - b*f; if( den != 0.0 ) { /* The co-efficients of the interpolating polynomial... */ c1 = ( d*c - a*f )/den; c2 = ( a*e - d*b )/den; c0 = r1 - c1*t1 - c2*t1*t1; /* Find the largest radius (the turning point of the quadratic), and the angle at which it occurs. */ if( c2 < 0.0 ) { mx = ( 4*c0*c2 - c1*c1 )/( 4*c2 ); at = a0 - c1/( 2*c2 ); } else { mx = r2; at = a0 - t2; } /* This point is the end of the ellipse primary axis. Find its (x,y) coords, and store in "pa". */ astOffset2( frm, cen, at, mx, pa ); /* Resolve all the supplied points into components parallel and perpendicular to the line joining the centre and "pa". */ ps2 = astResolvePoints( frm, cen, pa, mesh, NULL ); ptr2 = astGetPoints( ps2 ); if( astOK ) { /* For each other mesh point, work out the length of the secondary axis which would result if we used that point to define the ellipse. Find the mean of these secondary axis lengths, weighted by the length of the y component to reduce influence of poor conditioning at very low y. */ smn = 0.0; sw = 0.0; px = ptr2[ 0 ]; py = ptr2[ 1 ]; for( ip = 0; ip < np; ip++, px++, py++ ) { if( *px != AST__BAD && *py != AST__BAD ) { den = mx*mx - (*px)*(*px); if( den > 0.0 ) { smn += fabs( mx*(*py)*(*py) )/sqrt( den ); sw += fabs( *py ); } } } if( sw > 0 ) { mn = smn/sw; /* Find the coords at the end of the mean secondary axis. */ astOffset2( frm, cen, at + AST__DPIBY2, mn, pb ); /* Create the Ellipse to return. */ result = (AstRegion *) astEllipse( frm, 0, cen, pa, pb, unc, "", status ); } } /* Free resources. */ ps2 = astAnnul( ps2 ); } } dist = astFree( dist ); ang = astFree( ang ); frm = astAnnul( frm ); /* Return NULL if anything went wrong. */ if( !astOK ) result = astAnnul( result ); /* Return the result.*/ return result; } void astInitEllipseVtab_( AstEllipseVtab *vtab, const char *name, int *status ) { /* *+ * Name: * astInitEllipseVtab * Purpose: * Initialise a virtual function table for a Ellipse. * Type: * Protected function. * Synopsis: * #include "ellipse.h" * void astInitEllipseVtab( AstEllipseVtab *vtab, const char *name ) * Class Membership: * Ellipse vtab initialiser. * Description: * This function initialises the component of a virtual function * table which is used by the Ellipse class. * Parameters: * vtab * Pointer to the virtual function table. The components used by * all ancestral classes will be initialised if they have not already * been initialised. * name * Pointer to a constant null-terminated character string which contains * the name of the class to which the virtual function table belongs (it * is this pointer value that will subsequently be returned by the Object * astClass function). *- */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstMappingVtab *mapping; /* Pointer to Mapping component of Vtab */ AstRegionVtab *region; /* Pointer to Region component of Vtab */ /* Check the local error status. */ if ( !astOK ) return; /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(NULL); /* Initialize the component of the virtual function table used by the parent class. */ astInitRegionVtab( (AstRegionVtab *) vtab, name ); /* Store a unique "magic" value in the virtual function table. This will be used (by astIsAEllipse) to determine if an object belongs to this class. We can conveniently use the address of the (static) class_check variable to generate this unique value. */ vtab->id.check = &class_check; vtab->id.parent = &(((AstRegionVtab *) vtab)->id); /* Initialise member function pointers. */ /* ------------------------------------ */ /* Store pointers to the member functions (implemented here) that provide virtual methods for this class. */ vtab->EllipsePars = EllipsePars; /* Save the inherited pointers to methods that will be extended, and replace them with pointers to the new member functions. */ mapping = (AstMappingVtab *) vtab; region = (AstRegionVtab *) vtab; parent_transform = mapping->Transform; mapping->Transform = Transform; parent_simplify = mapping->Simplify; mapping->Simplify = Simplify; parent_setregfs = region->SetRegFS; region->SetRegFS = SetRegFS; parent_resetcache = region->ResetCache; region->ResetCache = ResetCache; region->RegPins = RegPins; region->RegBaseMesh = RegBaseMesh; region->RegBaseBox = RegBaseBox; region->RegCentre = RegCentre; region->RegTrace = RegTrace; /* Store replacement pointers for methods which will be over-ridden by new member functions implemented here. */ /* Declare the copy constructor, destructor and class dump functions. */ astSetDelete( vtab, Delete ); astSetCopy( vtab, Copy ); astSetDump( vtab, Dump, "Ellipse", "Elliptical region" ); /* If we have just initialised the vtab for the current class, indicate that the vtab is now initialised, and store a pointer to the class identifier in the base "object" level of the vtab. */ if( vtab == &class_vtab ) { class_init = 1; astSetVtabClassIdentifier( vtab, &(vtab->id) ); } } static void Cache( AstEllipse *this, int *status ){ /* * Name: * Cache * Purpose: * Calculate intermediate values and cache them in the Ellipse structure. * Type: * Private function. * Synopsis: * #include "ellipse.h" * void Cache( AstEllipse *this, int *status ) * Class Membership: * Ellipse member function * Description: * This function uses the PointSet stored in the parent Region to calculate * some intermediate values which are useful in other methods. These * values are stored within the Ellipse structure. * Parameters: * this * Pointer to the Ellipse. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstFrame *frm; /* Pointer to base Frame in Ellipse */ double **ptr; /* Pointer to data in the encapsulated PointSet */ double *centre; /* Array holding centre coords */ double *point1; /* Array holding coords at end of primary axis */ double *point2; /* Array holding coords at another point on ellipse */ double a; /* The half-length of the primary axis */ double angle; /* Orientation of primary axis */ double b; /* The half-length of the secondary axis */ int i; /* Axis index */ /* Check the global error status. */ if ( !astOK ) return; /* Do Nothing if the cached information is up to date. */ if( this->stale ) { /* Get a pointer to the base Frame. */ frm = astGetFrame( ((AstRegion *) this)->frameset, AST__BASE ); /* Allocate memory. */ centre = (double *) astMalloc( sizeof( double )*2 ); point1 = (double *) astMalloc( sizeof( double )*2 ); point2 = (double *) astMalloc( sizeof( double )*2 ); /* Get pointers to the coordinate data in the parent Region structure. */ ptr = astGetPoints( ((AstRegion *) this)->points ); /* Check pointers can be used safely. */ if( astOK ) { /* Copy the points in to the allocated memory. */ for( i = 0; i < 2; i++ ) { centre[ i ] = ptr[ i ][ 0 ]; point1[ i ] = ptr[ i ][ 1 ]; point2[ i ] = ptr[ i ][ 2 ]; } /* Calculate the geometric parameters of the ellipse. */ CalcPars( frm, centre, point1, point2, &a, &b, &angle, status ); /* Check the returned values. */ if( a <= 0.0 || a == AST__BAD || b <= 0.0 || b == AST__BAD ) { if( astOK ) astError( AST__BADIN, "astInitEllipse(%s): The " "supplied points do not determine an " "ellipse.", status, astGetClass( this ) ); } /* Store useful things in the Ellipse structure. */ if( astOK ) { astFree( this->centre ); this->centre = centre; centre = NULL; astFree( this->point1 ); this->point1 = point1; point1 = NULL; this->a = a; this->b = b; this->angle = angle; } } /* Initialise the bounding box. This is set properly when the astRegBaseMesh function is called. These variables should not be used unless the "basemesh" component of the parent Region structure is set to a non-null value. */ this->lbx = -DBL_MAX; this->ubx = DBL_MAX; this->lby = -DBL_MAX; this->uby = DBL_MAX; /* Free resources */ frm = astAnnul( frm ); if( centre ) centre = astFree( centre ); if( point1 ) point1 = astFree( point1 ); point2 = astFree( point2 ); /* Indicate cached information is up to date. */ this->stale = 0; } } static void CalcPars( AstFrame *frm, double centre[2], double point1[2], double point2[2], double *a, double *b, double *angle, int *status ){ /* * Name: * CalcPars * Purpose: * Calculate ellipse parameters. * Type: * Private function. * Synopsis: * #include "ellipse.h" * void CalcPars( AstFrame *frm, double centre[2], double point1[2], * double point2[2], double *a, double *b, double *angle, * int *status ) * Class Membership: * Ellipse member function * Description: * This function uses the supplied positions to calculate the * geometric parameters of an ellipse. * Parameters: * frm * Pointer to the Frame in which the positions are defined. * centre; * Array holding centre coords. * point1 * Array holding coords at end of primary axis * point2 * Array holding coords at another point on ellipse. On exit it * holds the coords at the end of the secondary axis. * a * Pointer to location at which to store the half-length of the * primary axis. * b * Pointer to location at which to store the half-length of the * secondary axis. * angle * Pointer to location at which to store the angle from the * positive direction of the second Frame axis to the primary * ellipse axis, in radians. Rotation from the second to the first * Frame axis is positive. * status * Pointer to the inherited status variable. */ /* Local Variables: */ double point3[ 2 ]; /* Array holding a point on the primary axis */ double x; /* The offset parallel to the primary axis */ double y; /* The offset perpendicular to the primary axis */ /* Check the global error status. */ if ( !astOK ) return; /* Get the geodesic distance between the centre and point 1 (the end of the primary axis of the ellipse). This is the half length of the primary axis of the ellipse (the axis which joins the centre position to point 1). */ *a = astDistance( frm, centre, point1 ); /* Find the point (point3) on the primary axis which is closest to point 2, and thus get the geodesic offsets (resolved parallel and perpendicular to the primary axis) between the centre and point 2. */ if( *a > 0.0 ) { astResolve( frm, centre, point1, point2, point3, &x, &y ); /* Find the half-length of the secondary ellipse axis. */ if( astOK ) { *b = (*a)*(*a) - x*x; if( *b > 0.0 ) *b = (*a)*y/sqrt( *b ); } else { *b = *a; } /* Find the angle from the positive direction of the second axis to the primary ellipse axis. */ point3[ 0 ] = centre[ 0 ]; point3[ 1 ] = centre[ 1 ] + fabs( 0.1*(*a) ); *angle = astAngle( frm, point3, centre, point1 ); /* Find the end point of the secondary axis. */ (void) astOffset2( frm, centre, *angle + AST__DPIBY2, *b, point2 ); } } static void EllipsePars( AstEllipse *this, double centre[2], double *a, double *b, double *angle, double p1[2], double p2[2], int *status ){ /* *++ * Name: c astEllipsePars f AST_ELLIPSEPARS * Purpose: * Returns the geometric parameters of an Ellipse. * Type: * Public virtual function. * Synopsis: c #include "ellipse.h" c void astEllipsePars( AstEllipse *this, double centre[2], double *a, c double *b, double *angle, double p1[2], double p2[2] ) f CALL AST_ELLIPSEPARS( THIS, CENTRE, A, B, ANGLE, P1, P2, STATUS ) * Class Membership: * Region method. * Description: c This function f This routine * returns the geometric parameters describing the supplied ellipse. * Parameters: c this f THIS = INTEGER (Given) * Pointer to the Region. c centre f CENTRE( 2 ) = DOUBLE PRECISION (Returned) * The coordinates of the Ellipse centre are returned in this arrays. c a f A = DOUBLE PRECISION (Returned) * Returned holding the half-length of the first axis of the * ellipse. c b f B = DOUBLE PRECISION (Returned) * Returned holding the half-length of the second axis of the * ellipse. c angle f ANGLE = DOUBLE PRECISION (Returned) * If the coordinate system in which the Ellipse is defined has * axes (X,Y), then c "*angle" f ANGLE * is returned holding the angle from the positive direction of * the Y axis to the first axis of the ellipse, in radians. * Positive rotation is in the same sense as rotation from the * positive direction of Y to the positive direction of X. c p1 f P1( 2 ) = DOUBLE PRECISION (Returned) * An array in which to return the coordinates at one of the two ends * of the first axis of the ellipse. c A NULL pointer can be supplied if these coordinates are not needed. c p2 f P2( 2 ) = DOUBLE PRECISION (Returned) * An array in which to return the coordinates at one of the two ends * of the second axis of the ellipse. c A NULL pointer can be supplied if these coordinates are not needed. f STATUS = INTEGER (Given and Returned) f The global status. * Notes: * - If the coordinate system represented by the Ellipse has been * changed since it was first created, the returned parameters refer * to the new (changed) coordinate system, rather than the original * coordinate system. Note however that if the transformation from * original to new coordinate system is non-linear, the shape * represented by the supplied Ellipse object may not be an accurate * ellipse. * - Values of AST__BAD are returned for the parameters without error * if the ellipse is degenerate or undefined. *-- */ /* Local Variables: */ AstFrame *frm; /* Current Frame represented by the Ellipse */ AstPointSet *pset; /* PointSet holding PointList axis values */ AstRegion *this_region; /* Parent Region pointer */ double **ptr; /* Pointer to axes values in the PointList */ double *point1; /* Pointer to "p1" or "buf1" */ double *point2; /* Pointer to "p2" or "buf2" */ double buf1[2]; /* Local substitute array for "p1" */ double buf2[2]; /* Local substitute array for "p2" */ int i; /* Axis index */ /* Check the inherited status. */ if( !astOK ) return; /* Store a pointer to the parent region structure. */ this_region = (AstRegion *) this; /* Transform the base Frame axis values into the current Frame. */ pset = astTransform( this_region->frameset, this_region->points, 1, NULL ); /* Get pointers to the coordinate data. */ ptr = astGetPoints( pset ); /* Choose the arrays to use - supplied arrays if possible, local arrays otherwise. */ if( p1 ) { point1 = p1; } else { point1 = buf1; } if( p2 ) { point2 = p2; } else { point2 = buf2; } /* Check pointers can be used safely. */ if( astOK ) { /* Copy the points in to separate arrays. */ for( i = 0; i < 2; i++ ) { centre[ i ] = ptr[ i ][ 0 ]; point1[ i ] = ptr[ i ][ 1 ]; point2[ i ] = ptr[ i ][ 2 ]; } /* Get the Ellipse frame. */ frm = astGetFrame( this_region->frameset, AST__CURRENT ); /* Calculate the geometric parameters of the ellipse. */ CalcPars( frm, centre, point1, point2, a, b, angle, status ); /* Ensure no zero values are returned. */ if( *a <= 0.0 || *b <= 0.0 ) { *a = AST__BAD; *b = AST__BAD; *angle = AST__BAD; } /* Free resources */ frm = astAnnul( frm ); } pset = astAnnul( pset ); } static void RegBaseBox( AstRegion *this_region, double *lbnd, double *ubnd, int *status ){ /* * Name: * RegBaseBox * Purpose: * Returns the bounding box of an un-negated Region in the base Frame of * the encapsulated FrameSet. * Type: * Private function. * Synopsis: * #include "ellipse.h" * void RegBaseBox( AstRegion *this, double *lbnd, double *ubnd, int *status ) * Class Membership: * Ellipse member function (over-rides the astRegBaseBox protected * method inherited from the Region class). * Description: * This function returns the upper and lower axis bounds of a Region in * the base Frame of the encapsulated FrameSet, assuming the Region * has not been negated. That is, the value of the Negated attribute * is ignored. * Parameters: * this * Pointer to the Region. * lbnd * Pointer to an array in which to return the lower axis bounds * covered by the Region in the base Frame of the encapsulated * FrameSet. It should have at least as many elements as there are * axes in the base Frame. * ubnd * Pointer to an array in which to return the upper axis bounds * covered by the Region in the base Frame of the encapsulated * FrameSet. It should have at least as many elements as there are * axes in the base Frame. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstEllipse *this; /* Pointer to Ellipse structure */ /* Check the global error status. */ if ( !astOK ) return; /* Get a pointer to the Ellipse structure */ this = (AstEllipse *) this_region; /* The bounding box of the mesh returned by astRegBaseMesh is used as the bounding box of the Ellipse. These bounds are cached in the Ellipse structure by astRegBaseMesh. Ensure astRegBaseMesh has been invoked, so that it is safe to use the cached bounding box. */ if( !this_region->basemesh ) (void) astAnnul( astRegBaseMesh( this ) ); /* Store the bounding box. */ lbnd[ 0 ] = this->lbx; ubnd[ 0 ] = this->ubx; lbnd[ 1 ] = this->lby; ubnd[ 1 ] = this->uby; } static AstPointSet *RegBaseMesh( AstRegion *this_region, int *status ){ /* * Name: * RegBaseMesh * Purpose: * Return a PointSet containing a mesh of points on the boundary of a * Region in its base Frame. * Type: * Private function. * Synopsis: * #include "ellipse.h" * AstPointSet *astRegBaseMesh( AstRegion *this, int *status ) * Class Membership: * Ellipse member function (over-rides the astRegBaseMesh protected * method inherited from the Region class). * Description: * This function returns a PointSet containing a mesh of points on the * boundary of the Region. The points refer to the base Frame of * the encapsulated FrameSet. * Parameters: * this * Pointer to the Region. * status * Pointer to the inherited status variable. * Returned Value: * Pointer to the PointSet. Annul the pointer using astAnnul when it * is no longer needed. * Notes: * - A NULL pointer is returned if an error has already occurred, or if * this function should fail for any reason. */ /* Local Constants: */ #define NP_EDGE 50 /* No. of points for determining geodesic */ /* Local Variables: */ AstEllipse *this; /* The Ellipse structure */ AstFrame *frm; /* Base Frame in encapsulated FrameSet */ AstPointSet *result; /* Returned pointer */ AstRegion *reg; /* Copy of supplied Ellipse */ double **ptr; /* Pointers to data */ double ang; /* Position angular of primary axis at "dx" */ double angle; /* Ellipse parametric angle at point */ double delta; /* Angular separation of points */ double dist; /* Offset along an axis */ double dx; /* Primary axis offset */ double dy; /* Secondary axis offset */ double lbnd[2]; /* Lower bounding box bounds */ double lbx; /* Lower x bound of mesh bounding box */ double lby; /* Lower y bound of mesh bounding box */ double p2[ 2 ]; /* Position in 2D Frame */ double p[ 2 ]; /* Position in 2D Frame */ double ubnd[2]; /* Upper bounding box bounds */ double ubx; /* Upper x bound of mesh bounding box */ double uby; /* Upper y bound of mesh bounding box */ int i; /* Point index */ int np; /* No. of points in returned PointSet */ /* Initialise */ result= NULL; /* Check the global error status. */ if ( !astOK ) return result; /* If the Region structure contains a pointer to a PointSet holding a previously created mesh, return it. */ if( this_region->basemesh ) { result = astClone( this_region->basemesh ); /* Otherwise, create a new mesh. */ } else { /* Initialise the bounding box of the mesh points. */ lbx = DBL_MAX; ubx = -DBL_MAX; lby = DBL_MAX; uby = -DBL_MAX; /* Get a pointer to the Ellipse structure. */ this = (AstEllipse *) this_region; /* Ensure cached information is available. */ Cache( this, status ); /* Get a pointer to the base Frame in the encapsulated FrameSet. */ frm = astGetFrame( this_region->frameset, AST__BASE ); /* Get the requested number of points to put on the mesh. */ np = astGetMeshSize( this ); /* Store the angular increment between points. */ delta = 2*AST__DPI/np; /* Create a suitable PointSet to hold the returned positions. */ result = astPointSet( np, 2, "", status ); ptr = astGetPoints( result ); if( astOK ) { /* Loop round each point. The angle is the parametric angle, phi, where the ellipse is defined by: dx = a.cos( phi ) dy = a.sin( phi ) measured from the primary ellipse. Positive in the sense of rotation from axis 2 to axis 1. */ angle = 0.0; for( i = 0; i < np; i++ ) { /* Find the offsets from the centre. "dx" is geodesic distance along the primary axis, and dy is geodesic distance along the secondary axis. */ dx = this->a*cos( angle ); dy = this->b*sin( angle ); /* Now find the point which corresponds to this dx and dy, taking account of the potential spherical geometry of hte coordinate system. First move a distance "dx" from the centre along the primary axis. The function value returned is the direction of the geodesic curve at the end point. That is, the angle (in radians) between the positive direction of the second axis and the continuation of the geodesic curve at the requested end point. */ ang = astOffset2( frm, this->centre, this->angle, dx, p ); /* Now move a distance "dy" from the point found above at right angles to the primary axis. */ astOffset2( frm, p, ang + AST__DPIBY2, dy, p2 ); /* Store the resulting axis values. */ ptr[ 0 ][ i ] = p2[ 0 ]; ptr[ 1 ][ i ] = p2[ 1 ]; /* Update the bounds of the mesh bounding box. The box is expressed in terms of axis offsets from the centre, in order to avoid problems with boxes that cross RA=0 or RA=12h */ if( p2[ 0 ] != AST__BAD && p2[ 1 ] != AST__BAD ){ dist = astAxDistance( frm, 1, this->centre[ 0 ], p2[ 0 ] ); if( dist < lbx ) { lbx = dist; } else if( dist > ubx ) { ubx = dist; } dist = astAxDistance( frm, 1, this->centre[ 1 ], p2[ 1 ] ); if( dist < lby ) { lby = dist; } else if( dist > uby ) { uby = dist; } } /* Increment the angular position of the next mesh point. */ angle += delta; } } /* Save the returned pointer in the Region structure so that it does not need to be created again next time this function is called. Also cache the bounding box in the Ellipse structure. */ if( astOK && result ) { this_region->basemesh = astClone( result ); /* Extend the bounding box if it contains any singularies. The astNormBox requires a Mapping which can be used to test points in the base Frame. Create a copy of the Circle and then set its FrameSet so that the current Frame in the copy is the same as the base Frame in the original. */ reg = astCopy( this ); astSetRegFS( reg, frm ); astSetNegated( reg, 0 ); /* Normalise this box. */ lbnd[ 0 ] = this->centre[ 0 ] + lbx; lbnd[ 1 ] = this->centre[ 1 ] + lby; ubnd[ 0 ] = this->centre[ 0 ] + ubx; ubnd[ 1 ] = this->centre[ 1 ] + uby; astNormBox( frm, lbnd, ubnd, reg ); /* Save this box */ this->lbx = lbnd[ 0 ]; this->ubx = ubnd[ 0 ]; this->lby = lbnd[ 1 ]; this->uby = ubnd[ 1 ]; /* Free resources. */ reg = astAnnul( reg ); } frm = astAnnul( frm ); } /* Annul the result if an error has occurred. */ if( !astOK ) result = astAnnul( result ); /* Return a pointer to the output PointSet. */ return result; } static double *RegCentre( AstRegion *this_region, double *cen, double **ptr, int index, int ifrm, int *status ){ /* * Name: * RegCentre * Purpose: * Re-centre a Region. * Type: * Private function. * Synopsis: * #include "ellipse.h" * double *RegCentre( AstRegion *this, double *cen, double **ptr, * int index, int ifrm, int *status ) * Class Membership: * Ellipse member function (over-rides the astRegCentre protected * method inherited from the Region class). * Description: * This function shifts the centre of the supplied Region to a * specified position, or returns the current centre of the Region. * Parameters: * this * Pointer to the Region. * cen * Pointer to an array of axis values, giving the new centre. * Supply a NULL value for this in order to use "ptr" and "index" to * specify the new centre. * ptr * Pointer to an array of points, one for each axis in the Region. * Each pointer locates an array of axis values. This is the format * returned by the PointSet method astGetPoints. Only used if "cen" * is NULL. * index * The index of the point within the arrays identified by "ptr" at * which is stored the coords for the new centre position. Only used * if "cen" is NULL. * ifrm * Should be AST__BASE or AST__CURRENT. Indicates whether the centre * position is supplied and returned in the base or current Frame of * the FrameSet encapsulated within "this". * status * Pointer to the inherited status variable. * Returned Value: * If both "cen" and "ptr" are NULL then a pointer to a newly * allocated dynamic array is returned which contains the centre * coords of the Region. This array should be freed using astFree when * no longer needed. If either of "ptr" or "cen" is not NULL, then a * NULL pointer is returned. * Notes: * - Some Region sub-classes do not have a centre. Such classes will report * an AST__INTER error code if this method is called. */ /* Local Variables: */ AstEllipse *this; /* Pointer to Ellipse structure */ AstFrame *frm; /* Base Frame */ double **rptr; /* Data pointers for Region PointSet */ double *bc; /* Base Frame centre position */ double *result; /* Returned pointer */ double *tmp; /* Temporary array pointer */ double a[ 2 ]; /* Original position */ double angle; /* Orietentation of offset from old to new centre */ double axval; /* Axis value */ double b[ 2 ]; /* New position */ double dist; /* Distance from old to new centre */ double newcen[ 2 ]; /* New centre */ int ic; /* Coordinate index */ int ip; /* Position index */ int ncb; /* Number of base frame coordinate values per point */ int ncc; /* Number of current frame coordinate values per point */ /* Initialise */ result = NULL; /* Check the local error status. */ if ( !astOK ) return result; /* Get a pointer to the Ellipse structure. */ this = (AstEllipse *) this_region; /* Ensure cached information is available. */ Cache( this, status ); /* Get the number of axis values per point in the current Frame. */ ncc = astGetNout( this_region->frameset ); /* An ellipse always has 2 base frame axes. */ ncb = 2; /* If the centre coords are to be returned, return either a copy of the base Frame centre coords, or transform the base Frame centre coords into the current Frame. */ if( !ptr && !cen ) { if( ifrm == AST__CURRENT ) { result = astRegTranPoint( this_region, this->centre, 1, 1 ); } else { result = astStore( NULL, this->centre, sizeof( double )*ncb ); } /* Otherwise, we store the supplied new centre coords and return a NULL pointer. */ } else { /* Get a pointer to the axis values stored in the Region structure. */ rptr = astGetPoints( this_region->points ); /* Check pointers can be used safely */ if( astOK ) { /* If the centre position was supplied in the current Frame, find the corresponding base Frame position... */ if( ifrm == AST__CURRENT ) { if( cen ) { bc = astRegTranPoint( this_region, cen, 1, 0 ); } else { tmp = astMalloc( sizeof( double)*(size_t)ncc ); if( astOK ) { for( ic = 0; ic < ncc; ic++ ) tmp[ ic ] = ptr[ ic ][ index ]; } bc = astRegTranPoint( this_region, tmp, 1, 0 ); tmp = astFree( tmp ); } /* Replace any bad centre values with their current values. */ for( ic = 0; ic < ncb; ic++ ) { if( bc[ ic ] == AST__BAD ) bc[ ic ] = this->centre[ ic ]; } /* If the centre position was supplied in the base Frame, use the supplied "cen" or "ptr" pointer directly to change the coords in the parent Region structure and the cached coords in the Ellipse structure. */ } else { bc = newcen; for( ic = 0; ic < ncb; ic++ ) { axval = cen ? cen[ ic ] : ptr[ ic ][ index ]; newcen[ ic ] = ( axval != AST__BAD ) ? axval : this->centre[ ic ]; } } /* Find the direction and length of the offset between the old and new centre. */ frm = astGetFrame( this_region->frameset, AST__BASE ); angle = astAxAngle( frm, this->centre, bc, 2 ); dist = astDistance( frm, this->centre, bc ); /* Shift each point in the parent Region structure by the same length and direction. */ for( ip = 0; ip < 3; ip++ ) { a[ 0 ] = rptr[ ip ][ 0 ]; a[ 1 ] = rptr[ ip ][ 1 ]; astOffset2( frm, a, angle, dist, b ); rptr[ ip ][ 0 ] = b[ 0 ]; rptr[ ip ][ 1 ] = b[ 1 ]; } /* Indicate that the cache is stale. */ astResetCache( this ); /* Free resources */ frm = astAnnul( frm ); if( bc != newcen ) bc = astFree( bc ); } } /* Return the result. */ return result; } static int RegPins( AstRegion *this_region, AstPointSet *pset, AstRegion *unc, int **mask, int *status ){ /* * Name: * RegPins * Purpose: * Check if a set of points fall on the boundary of a given Ellipse. * Type: * Private function. * Synopsis: * #include "ellipse.h" * int RegPins( AstRegion *this, AstPointSet *pset, AstRegion *unc, * int **mask, int *status ) * Class Membership: * Ellipse member function (over-rides the astRegPins protected * method inherited from the Region class). * Description: * This function returns a flag indicating if the supplied set of * points all fall on the boundary of the given Ellipse. * * Some tolerance is allowed, as specified by the uncertainty Region * stored in the supplied Ellipse "this", and the supplied uncertainty * Region "unc" which describes the uncertainty of the supplied points. * Parameters: * this * Pointer to the Ellipse. * pset * Pointer to the PointSet. The points are assumed to refer to the * base Frame of the FrameSet encapsulated by "this". * unc * Pointer to a Region representing the uncertainties in the points * given by "pset". The Region is assumed to represent the base Frame * of the FrameSet encapsulated by "this". Zero uncertainity is assumed * if NULL is supplied. * mask * Pointer to location at which to return a pointer to a newly * allocated dynamic array of ints. The number of elements in this * array is equal to the value of the Npoint attribute of "pset". * Each element in the returned array is set to 1 if the * corresponding position in "pset" is on the boundary of the Region * and is set to zero otherwise. A NULL value may be supplied * in which case no array is created. If created, the array should * be freed using astFree when no longer needed. * status * Pointer to the inherited status variable. * Returned Value: * Non-zero if the points all fall on the boundary of the given * Region, to within the tolerance specified. Zero otherwise. */ /* Local variables: */ AstEllipse *large_ellipse; /* Ellipse slightly larger than "this" */ AstEllipse *small_ellipse; /* Ellipse slightly smaller than "this" */ AstEllipse *this; /* Pointer to the Ellipse structure. */ AstFrame *frm; /* Base Frame in supplied Ellipse */ AstPointSet *ps1; /* Points masked by larger Ellipse */ AstPointSet *ps2; /* Points masked by larger and smaller Ellipsees */ AstRegion *tunc; /* Uncertainity Region from "this" */ double **ptr; /* Pointer to axis values in "ps2" */ double *p; /* Pointer to next axis value */ double *safe; /* An interior point in "this" */ double drad; /* Radius increment corresponding to border width */ double l1; /* Length of bounding box diagonal */ double l2; /* Length of bounding box diagonal */ double lbnd_tunc[2]; /* Lower bounds of "this" uncertainty Region */ double lbnd_unc[2]; /* Lower bounds of supplied uncertainty Region */ double lim; /* Smallest semi-minor/major axis length */ double p1[2]; /* New ellipse axis lengths */ double ubnd_tunc[2]; /* Upper bounds of "this" uncertainty Region */ double ubnd_unc[2]; /* Upper bounds of supplied uncertainty Region */ int i; /* Axis index */ int j; /* Point index */ int np; /* No. of supplied points */ int result; /* Returned flag */ /* Initialise */ result = 0; if( mask ) *mask = NULL; /* Check the inherited status. */ if( !astOK ) return result; /* Get a pointer to the Ellipse structure. */ this = (AstEllipse *) this_region; /* Check the supplied PointSet has 2 axis values per point. */ if( astGetNcoord( pset ) != 2 && astOK ) { astError( AST__INTER, "astRegPins(%s): Illegal number of axis " "values per point (%d) in the supplied PointSet - should be " "2 (internal AST programming error).", status, astGetClass( this ), astGetNcoord( pset ) ); } /* Get the number of axes in the uncertainty Region and check it is also 2. */ if( unc && astGetNaxes( unc ) != 2 && astOK ) { astError( AST__INTER, "astRegPins(%s): Illegal number of axes (%d) " "in the supplied uncertainty Region - should be 2 " "(internal AST programming error).", status, astGetClass( this ), astGetNaxes( unc ) ); } /* Get the centre of the region in the base Frame. We use this as a "safe" interior point within the region. */ safe = astRegCentre( this, NULL, NULL, 0, AST__BASE ); /* We now find the maximum distance on each axis that a point can be from the boundary of the Ellipse for it still to be considered to be on the boundary. First get the Region which defines the uncertainty within the Ellipse being checked (in its base Frame), re-centre it on the interior point found above (to avoid problems if the uncertainty region straddles a discontinuity), and get its bounding box. */ tunc = astGetUncFrm( this, AST__BASE ); if( safe ) astRegCentre( tunc, safe, NULL, 0, AST__CURRENT ); astGetRegionBounds( tunc, lbnd_tunc, ubnd_tunc ); /* Find the geodesic length within the base Frame of "this" of the diagonal of the bounding box. */ frm = astGetFrame( this_region->frameset, AST__BASE ); l1 = astDistance( frm, lbnd_tunc, ubnd_tunc ); /* Also get the Region which defines the uncertainty of the supplied points and get its bounding box. First re-centre the uncertainty at the interior position to avoid problems from uncertainties that straddle a discontinuity. */ if( unc ) { if( safe ) astRegCentre( unc, safe, NULL, 0, AST__CURRENT ); astGetRegionBounds( unc, lbnd_unc, ubnd_unc ); /* Find the geodesic length of the diagonal of this bounding box. */ l2 = astDistance( frm, lbnd_unc, ubnd_unc ); /* Assume zero uncertainty if no "unc" Region was supplied. */ } else { l2 = 0.0; } /* Ensure cached information is available. */ Cache( this, status ); /* The required border width is half of the total diagonal of the two bounding boxes. */ if( astOK ) { drad = 0.5*( l1 + l2 ); /* Create two new Ellipse, one of which is larger than "this" by the amount found above, and the other of which is smaller than "this" by the amount found above. */ p1[ 0 ] = this->a + 0.5*drad; p1[ 1 ] = this->b + 0.5*drad; large_ellipse = astEllipse( frm, 1, this->centre, p1, &(this->angle), NULL, " ", status ); p1[ 0 ] = this->a - 0.5*drad; p1[ 1 ] = this->b - 0.5*drad; lim = 1.0E-6*drad; if( p1[ 0 ] < lim ) p1[ 0 ] = lim; if( p1[ 1 ] < lim ) p1[ 1 ] = lim; small_ellipse = astEllipse( frm, 1, this->centre, p1, &(this->angle), NULL, " ", status ); /* Negate the smaller region.*/ astNegate( small_ellipse ); /* Points are on the boundary of "this" if they are inside both the large Ellipse and the negated small Ellipse. First transform the supplied PointSet using the large Ellipse, then transform them using the negated smaller Ellipse. */ ps1 = astTransform( large_ellipse, pset, 1, NULL ); ps2 = astTransform( small_ellipse, ps1, 1, NULL ); /* Get a point to the resulting axis values, and the number of axis values per axis. */ ptr = astGetPoints( ps2 ); np = astGetNpoint( ps2 ); /* If a mask array is to be returned, create one. */ if( mask ) { *mask = astMalloc( sizeof(int)*(size_t) np ); /* Check all the resulting points, setting mask values for all of them. */ if( astOK ) { /* Initialise the mask elements on the basis of the first axis values */ result = 1; p = ptr[ 0 ]; for( j = 0; j < np; j++ ) { if( *(p++) == AST__BAD ) { result = 0; (*mask)[ j ] = 0; } else { (*mask)[ j ] = 1; } } /* Now check for bad values on other axes. */ for( i = 1; i < 2; i++ ) { p = ptr[ i ]; for( j = 0; j < np; j++ ) { if( *(p++) == AST__BAD ) { result = 0; (*mask)[ j ] = 0; } } } } /* If no output mask is to be made, we can break out of the check as soon as the first bad value is found. */ } else if( astOK ) { result = 1; for( i = 0; i < 2 && result; i++ ) { p = ptr[ i ]; for( j = 0; j < np; j++ ) { if( *(p++) == AST__BAD ) { result = 0; break; } } } } /* Free resources. */ large_ellipse = astAnnul( large_ellipse ); small_ellipse = astAnnul( small_ellipse ); ps1 = astAnnul( ps1 ); ps2 = astAnnul( ps2 ); } tunc = astAnnul( tunc ); frm = astAnnul( frm ); safe = astFree( safe ); /* If an error has occurred, return zero. */ if( !astOK ) { result = 0; if( mask ) *mask = astAnnul( *mask ); } /* Return the result. */ return result; } static int RegTrace( AstRegion *this_region, int n, double *dist, double **ptr, int *status ){ /* *+ * Name: * RegTrace * Purpose: * Return requested positions on the boundary of a 2D Region. * Type: * Private function. * Synopsis: * #include "ellipse.h" * int astTraceRegion( AstRegion *this, int n, double *dist, double **ptr ); * Class Membership: * Ellipse member function (overrides the astTraceRegion method * inherited from the parent Region class). * Description: * This function returns positions on the boundary of the supplied * Region, if possible. The required positions are indicated by a * supplied list of scalar parameter values in the range zero to one. * Zero corresponds to some arbitrary starting point on the boundary, * and one corresponds to the end (which for a closed region will be * the same place as the start). * Parameters: * this * Pointer to the Region. * n * The number of positions to return. If this is zero, the function * returns without action (but the returned function value still * indicates if the method is supported or not). * dist * Pointer to an array of "n" scalar parameter values in the range * 0 to 1.0. * ptr * A pointer to an array of pointers. The number of elements in * this array should equal tthe number of axes in the Frame spanned * by the Region. Each element of the array should be a pointer to * an array of "n" doubles, in which to return the "n" values for * the corresponding axis. The contents of the arrays are unchanged * if the supplied Region belongs to a class that does not * implement this method. * Returned Value: * Non-zero if the astTraceRegion method is implemented by the class * of Region supplied, and zero if not. *- */ /* Local Variables; */ AstEllipse *this; AstFrame *frm; AstMapping *map; AstPointSet *bpset; AstPointSet *cpset; double **bptr; double ang; double angle; double dx; double dy; double p2[ 2 ]; double p[ 2 ]; int i; int ncur; /* Check inherited status, and the number of points to return, returning a non-zero value to indicate that this class supports the astRegTrace method. */ if( ! astOK || n == 0 ) return 1; /* Get a pointer to the Ellipse structure. */ this = (AstEllipse *) this_region; /* Ensure cached information is available. */ Cache( this, status ); /* Get a pointer to the base Frame in the encapsulated FrameSet. */ frm = astGetFrame( this_region->frameset, AST__BASE ); /* We first determine the required positions in the base Frame of the Region, and then transform them into the current Frame. Get the base->current Mapping, and the number of current Frame axes. */ map = astGetMapping( this_region->frameset, AST__BASE, AST__CURRENT ); /* If it's a UnitMap we do not need to do the transformation, so put the base Frame positions directly into the supplied arrays. */ if( astIsAUnitMap( map ) ) { bpset = NULL; bptr = ptr; ncur = 2; /* Otherwise, create a PointSet to hold the base Frame positions (known to be 2D since this is an ellipse). */ } else { bpset = astPointSet( n, 2, " ", status ); bptr = astGetPoints( bpset ); ncur = astGetNout( map ); } /* Check the pointers can be used safely. */ if( astOK ) { /* Loop round each point. */ for( i = 0; i < n; i++ ) { /* The supplied scalar parameter values are the parametric angles, phi, where the ellipse is defined by: dx = a.cos( phi ) dy = a.sin( phi ) measured from the primary ellipse. Positive in the sense of rotation from axis 2 to axis 1. */ angle = dist[ i ]*2*AST__DPI; /* Find the offsets from the centre. "dx" is geodesic distance along the primary axis, and dy is geodesic distance along the secondary axis. */ dx = this->a*cos( angle ); dy = this->b*sin( angle ); /* Now find the point which corresponds to this dx and dy, taking account of the potential spherical geometry of hte coordinate system. First move a distance "dx" from the centre along the primary axis. The function value returned is the direction of the geodesic curve at the end point. That is, the angle (in radians) between the positive direction of the second axis and the continuation of the geodesic curve at the requested end point. */ ang = astOffset2( frm, this->centre, this->angle, dx, p ); /* Now move a distance "dy" from the point found above at right angles to the primary axis. */ astOffset2( frm, p, ang + AST__DPIBY2, dy, p2 ); /* Store the resulting axis values. */ bptr[ 0 ][ i ] = p2[ 0 ]; bptr[ 1 ][ i ] = p2[ 1 ]; } } /* If required, transform the base frame positions into the current Frame, storing them in the supplied array. Then free resources. */ if( bpset ) { cpset = astPointSet( n, ncur, " ", status ); astSetPoints( cpset, ptr ); (void) astTransform( map, bpset, 1, cpset ); cpset = astAnnul( cpset ); bpset = astAnnul( bpset ); } /* Free remaining resources. */ map = astAnnul( map ); frm = astAnnul( frm ); /* Return a non-zero value to indicate that this class supports the astRegTrace method. */ return 1; } static void ResetCache( AstRegion *this, int *status ){ /* * Name: * ResetCache * Purpose: * Clear cached information within the supplied Region. * Type: * Private function. * Synopsis: * #include "ellipse.h" * void ResetCache( AstRegion *this, int *status ) * Class Membership: * Region member function (overrides the astResetCache method * inherited from the parent Region class). * Description: * This function clears cached information from the supplied Region * structure. * Parameters: * this * Pointer to the Region. * status * Pointer to the inherited status variable. */ if( this ) { ( (AstEllipse *) this )->stale = 1; (*parent_resetcache)( this, status ); } } static void SetRegFS( AstRegion *this_region, AstFrame *frm, int *status ) { /* * Name: * SetRegFS * Purpose: * Stores a new FrameSet in a Region * Type: * Private function. * Synopsis: * #include "ellipse.h" * void SetRegFS( AstRegion *this_region, AstFrame *frm, int *status ) * Class Membership: * Ellipse method (over-rides the astSetRegFS method inherited from * the Region class). * Description: * This function creates a new FrameSet and stores it in the supplied * Region. The new FrameSet contains two copies of the supplied * Frame, connected by a UnitMap. * Parameters: * this * Pointer to the Region. * frm * The Frame to use. * status * Pointer to the inherited status variable. */ /* Check the global error status. */ if ( !astOK ) return; /* Invoke the parent method to store the FrameSet in the parent Region structure. */ (* parent_setregfs)( this_region, frm, status ); /* Indicate that cached information will need to be re-calculated before it is next used. */ astResetCache( this_region ); } static AstMapping *Simplify( AstMapping *this_mapping, int *status ) { /* * Name: * Simplify * Purpose: * Simplify the Mapping represented by a Region. * Type: * Private function. * Synopsis: * #include "ellipse.h" * AstMapping *Simplify( AstMapping *this, int *status ) * Class Membership: * Ellipse method (over-rides the astSimplify method inherited * from the Region class). * Description: * This function invokes the parent Region Simplify method, and then * performs any further region-specific simplification. * * If the Mapping from base to current Frame is not a UnitMap, this * will include attempting to fit a new Region to the boundary defined * in the current Frame. * Parameters: * this * Pointer to the original Region. * status * Pointer to the inherited status variable. * Returned Value: * A pointer to the simplified Region. A cloned pointer to the * supplied Region will be returned if no simplication could be * performed. * Notes: * - A NULL pointer value will be returned if this function is * invoked with the AST error status set, or if it should fail for * any reason. */ /* Local Variables: */ AstMapping *map; /* Base -> current Mapping */ AstMapping *result; /* Result pointer to return */ AstPointSet *mesh; /* Mesh of current Frame positions */ AstPointSet *ps2; /* Ellipse PointSet in current Frame */ AstRegion *new; /* Pointer to simplified Region */ AstRegion *newreg; /* Equivalent circle or ellipse */ AstRegion *this; /* Pointer to supplied Region structure */ AstRegion *unc; /* Pointer to uncertainty Region */ double **ptr2; /* Pointer axis values in "ps2" */ double *cen; /* Pointer to array holding new centre coords */ int ic; /* Axis index */ int nc; /* No. of axis values per point */ int ok; /* Was the new centre found OK? */ int simpler; /* Has some simplication taken place? */ /* Initialise. */ result = NULL; /* Check the global error status. */ if ( !astOK ) return result; /* Get a pointer to the supplied Region structure. */ this = (AstRegion *) this_mapping; /* Invoke the parent Simplify method inherited from the Region class. This will simplify the encapsulated FrameSet and uncertainty Region. */ new = (AstRegion *) (*parent_simplify)( this_mapping, status ); /* Note if any simplification took place. This is assumed to be the case if the pointer returned by the above call is different to the supplied pointer. */ simpler = ( new != this ); /* We attempt to simplify the Ellipse by re-defining it within its current Frame. Transforming the Ellipse from its base to its current Frame may result in the region no longer being an ellipse. We test this by transforming a set of bounds on the Ellipse boundary. */ map = astGetMapping( new->frameset, AST__BASE, AST__CURRENT ); /* Get a mesh of points covering the Ellipse in its current Frame. */ mesh = astRegMesh( new ); /* Get the Region describing the positional uncertainty within the Ellipse in its current Frame. */ unc = astGetUncFrm( new, AST__CURRENT ); /* Transform the PointSet holding the ellipse centre into the current Frame, and copy the axis values into a new array. */ ps2 = astRegTransform( this, this->points, 1, NULL, NULL ); nc = astGetNcoord( ps2 ); cen = astMalloc( sizeof( double )*(size_t) nc ); ptr2 = astGetPoints( ps2 ); if( astOK ) { ok = 1; for( ic = 0; ic < nc; ic++ ) { cen[ ic ] = ptr2[ ic ][ 0 ]; if( cen[ ic ] == AST__BAD ) ok = 0; } /* Find the best fitting Circle (defined in the current Frame) through these points */ newreg = ok ? astBestCircle( mesh, cen, unc ) : NULL; /* See if all points within this mesh fall on the boundary of the best fitting Circle, to within the uncertainty of the Region. */ if( newreg && astRegPins( newreg, mesh, NULL, NULL ) ) { /* If so, use the new Circle in place of the original Region. */ (void) astAnnul( new ); new = astClone( newreg ); simpler =1; /* Otherwise, if the region is 2-d we see if an Ellipse can represent the mesh. */ } else if( ok && nc == 2 ){ /* Find the best fitting Ellipse (defined in the current Frame) through these points */ if( newreg ) (void) astAnnul( newreg ); newreg = astBestEllipse( mesh, cen, unc ); /* See if all points within this mesh fall on the boundary of the best fitting Ellipse, to within the uncertainty of the Region. */ if( newreg && astRegPins( newreg, mesh, NULL, NULL ) ) { /* If so, use the new Ellipse in place of the original Region. */ (void) astAnnul( new ); new = astClone( newreg ); simpler = 1; } } /* Free resources. */ if( newreg ) newreg = astAnnul( newreg ); } ps2 = astAnnul( ps2 ); cen = astFree( cen ); mesh = astAnnul( mesh ); unc = astAnnul( unc ); map = astAnnul( map ); /* If any simplification could be performed, copy Region attributes from the supplied Region to the returned Region, and return a pointer to it. If the supplied Region had no uncertainty, ensure the returned Region has no uncertainty. Otherwise, return a clone of the supplied pointer. */ if( simpler ){ astRegOverlay( new, this, 1 ); result = (AstMapping *) new; } else { new = astAnnul( new ); result = astClone( this ); } /* If an error occurred, annul the returned pointer. */ if ( !astOK ) result = astAnnul( result ); /* Return the result. */ return result; } static AstPointSet *Transform( AstMapping *this_mapping, AstPointSet *in, int forward, AstPointSet *out, int *status ) { /* * Name: * Transform * Purpose: * Apply a Ellipse to transform a set of points. * Type: * Private function. * Synopsis: * #include "ellipse.h" * AstPointSet *Transform( AstMapping *this, AstPointSet *in, * int forward, AstPointSet *out, int *status ) * Class Membership: * Ellipse member function (over-rides the astTransform protected * method inherited from the Mapping class). * Description: * This function takes a Ellipse and a set of points encapsulated in a * PointSet and transforms the points by setting axis values to * AST__BAD for all points which are outside the region. Points inside * the region are copied unchanged from input to output. * Parameters: * this * Pointer to the Ellipse. * in * Pointer to the PointSet holding the input coordinate data. * forward * A non-zero value indicates that the forward coordinate transformation * should be applied, while a zero value requests the inverse * transformation. * out * Pointer to a PointSet which will hold the transformed (output) * coordinate values. A NULL value may also be given, in which case a * new PointSet will be created by this function. * status * Pointer to the inherited status variable. * Returned Value: * Pointer to the output (possibly new) PointSet. * Notes: * - The forward and inverse transformations are identical for a * Region. * - A null pointer will be returned if this function is invoked with the * global error status set, or if it should fail for any reason. * - The number of coordinate values per point in the input PointSet must * match the number of axes in the Frame represented by the Ellipse. * - If an output PointSet is supplied, it must have space for sufficient * number of points and coordinate values per point to accommodate the * result. Any excess space will be ignored. */ /* Local Variables: */ AstEllipse *this; /* Pointer to Ellipse */ AstFrame *frm; /* Pointer to base Frame in FrameSet */ AstPointSet *pset_res; /* Pointer to PointSet holding resolved components */ AstPointSet *pset_tmp; /* Pointer to PointSet holding base Frame positions*/ AstPointSet *result; /* Pointer to output PointSet */ double **ptr_out; /* Pointer to output coordinate data */ double **ptr_res; /* Pointer to resolved components coordinate data */ double *px; /* Pointer to array of primary axis components */ double *py; /* Pointer to array of secondary axis components */ double c1; /* Constant */ double c2; /* Constant */ double d; /* Elliptical distance to current point */ int closed; /* Is the boundary part of the Region? */ int coord; /* Zero-based index for coordinates */ int inside; /* Is the point inside the Region? */ int ncoord_out; /* No. of coordinates per output point */ int neg; /* Has the Region been negated? */ int npoint; /* No. of points */ int point; /* Loop counter for points */ /* Check the global error status. */ if ( !astOK ) return NULL; /* Obtain a pointer to the Ellipse structure. */ this = (AstEllipse *) this_mapping; /* Apply the parent mapping using the stored pointer to the Transform member function inherited from the parent Region class. This function validates all arguments and generates an output PointSet if necessary, containing a copy of the input PointSet. */ result = (*parent_transform)( this_mapping, in, forward, out, status ); /* Ensure cached information is available. */ Cache( this, status ); /* We will now extend the parent astTransform method by performing the calculations needed to generate the output coordinate values. */ /* First use the encapsulated FrameSet to transform the supplied positions from the current Frame in the encapsulated FrameSet (the Frame represented by the Region), to the base Frame (the Frame in which the Region is defined). This call also returns a pointer to the base Frame of the encapsulated FrameSet. Note, the returned pointer may be a clone of the "in" pointer, and so we must be carefull not to modify the contents of the returned PointSet. */ pset_tmp = astRegTransform( this, in, 0, NULL, &frm ); /* Resolve all the base Frame positions into components parallel to and perpendicular to the primary axis, relative to the ellipse centre. The components are returned in a new PointSet. */ pset_res = astResolvePoints( frm, this->centre, this->point1, pset_tmp, NULL ); /* Determine the numbers of points from the component PointSet and obtain pointers for accessing the component and output coordinate values. */ npoint = astGetNpoint( pset_res ); ptr_res = astGetPoints( pset_res ); ncoord_out = astGetNcoord( result ); ptr_out = astGetPoints( result ); /* See if the boundary is part of the Region. */ closed = astGetClosed( this ); /* See if the Region has been negated. */ neg = astGetNegated( this ); /* Form some frequently needed constants. */ c1 = 1.0/(this->a*this->a); c2 = 1.0/(this->b*this->b); /* Perform coordinate arithmetic. */ /* ------------------------------ */ if ( astOK ) { px = ptr_res[ 0 ]; py = ptr_res[ 1 ]; /* Loop round each point */ for ( point = 0; point < npoint; point++, px++, py++ ) { /* Bad input points result in bad output points */ if( *px == AST__BAD || *py == AST__BAD ) { inside = 0; /* If the input points are good... */ } else { /* Find the elliptical distance from the centre to the supplied point (the ellipse circumference has an "elliptical distance" of 1.0 at all points).*/ d = c1*(*px)*(*px) + c2*(*py)*(*py); /* Now consider whether this radius value puts the point in or out of the Ellipse. */ if( d != AST__BAD ){ if( neg ) { if( closed ) { inside = ( d >= 1.0 ); } else { inside = ( d > 1.0 ); } } else { if( closed ) { inside = ( d <= 1.0 ); } else { inside = ( d < 1.0 ); } } } else { inside = 0; } } /* If the point is outside, store bad output values. */ if( !inside ) { for ( coord = 0; coord < ncoord_out; coord++ ) { ptr_out[ coord ][ point ] = AST__BAD; } } } } /* Free resources */ pset_tmp = astAnnul( pset_tmp ); pset_res = astAnnul( pset_res ); frm = astAnnul( frm ); /* Annul the result if an error has occurred. */ if( !astOK ) result = astAnnul( result ); /* Return a pointer to the output PointSet. */ return result; } /* Functions which access class attributes. */ /* ---------------------------------------- */ /* Implement member functions to access the attributes associated with this class using the macros defined for this purpose in the "object.h" file. For a description of each attribute, see the class interface (in the associated .h file). */ /* Copy constructor. */ /* ----------------- */ static void Copy( const AstObject *objin, AstObject *objout, int *status ) { /* * Name: * Copy * Purpose: * Copy constructor for Ellipse objects. * Type: * Private function. * Synopsis: * void Copy( const AstObject *objin, AstObject *objout, int *status ) * Description: * This function implements the copy constructor for Ellipse objects. * Parameters: * objin * Pointer to the object to be copied. * objout * Pointer to the object being constructed. * status * Pointer to the inherited status variable. * Notes: * - This constructor makes a deep copy. */ /* Local Variables: */ AstEllipse *in; /* Pointer to input Ellipse */ AstEllipse *out; /* Pointer to output Ellipse */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain pointers to the input and output Ellipses. */ in = (AstEllipse *) objin; out = (AstEllipse *) objout; /* For safety, first clear any references to the input memory from the output Ellipse. */ out->centre = NULL; out->point1 = NULL; /* Copy dynamic memory contents */ out->centre = astStore( NULL, in->centre, sizeof( double )*2 ); out->point1 = astStore( NULL, in->point1, sizeof( double )*2 ); } /* Destructor. */ /* ----------- */ static void Delete( AstObject *obj, int *status ) { /* * Name: * Delete * Purpose: * Destructor for Ellipse objects. * Type: * Private function. * Synopsis: * void Delete( AstObject *obj, int *status ) * Description: * This function implements the destructor for Ellipse objects. * Parameters: * obj * Pointer to the object to be deleted. * status * Pointer to the inherited status variable. * Notes: * This function attempts to execute even if the global error status is * set. */ /* Local Variables: */ AstEllipse *this; /* Pointer to Ellipse */ /* Obtain a pointer to the Ellipse structure. */ this = (AstEllipse *) obj; /* Annul all resources. */ this->centre = astFree( this->centre ); this->point1 = astFree( this->point1 ); } /* Dump function. */ /* -------------- */ static void Dump( AstObject *this_object, AstChannel *channel, int *status ) { /* * Name: * Dump * Purpose: * Dump function for Ellipse objects. * Type: * Private function. * Synopsis: * void Dump( AstObject *this, AstChannel *channel, int *status ) * Description: * This function implements the Dump function which writes out data * for the Ellipse class to an output Channel. * Parameters: * this * Pointer to the Ellipse whose data are being written. * channel * Pointer to the Channel to which the data are being written. * status * Pointer to the inherited status variable. */ /* Local Variables: */ AstEllipse *this; /* Pointer to the Ellipse structure */ /* Check the global error status. */ if ( !astOK ) return; /* Obtain a pointer to the Ellipse structure. */ this = (AstEllipse *) this_object; /* Write out values representing the instance variables for the Ellipse class. Accompany these with appropriate comment strings, possibly depending on the values being written.*/ /* In the case of attributes, we first use the appropriate (private) Test... member function to see if they are set. If so, we then use the (private) Get... function to obtain the value to be written out. For attributes which are not set, we use the astGet... method to obtain the value instead. This will supply a default value (possibly provided by a derived class which over-rides this method) which is more useful to a human reader as it corresponds to the actual default attribute value. Since "set" will be zero, these values are for information only and will not be read back. */ /* There are no values to write, so return without further action. */ } /* Standard class functions. */ /* ========================= */ /* Implement the astIsAEllipse and astCheckEllipse functions using the macros defined for this purpose in the "object.h" header file. */ astMAKE_ISA(Ellipse,Region) astMAKE_CHECK(Ellipse) AstEllipse *astEllipse_( void *frame_void, int form, const double centre[2], const double point1[2], const double point2[2], AstRegion *unc, const char *options, int *status, ...) { /* *++ * Name: c astEllipse f AST_ELLIPSE * Purpose: * Create a Ellipse. * Type: * Public function. * Synopsis: c #include "ellipse.h" c AstEllipse *astEllipse( AstFrame *frame, int form, const double centre[2], c const double point1[2], const double point2[2], c AstRegion *unc, const char *options, ... ) f RESULT = AST_ELLIPSE( FRAME, FORM, CENTRE, POINT1, POINT2, UNC, OPTIONS, f STATUS ) * Class Membership: * Ellipse constructor. * Description: * This function creates a new Ellipse and optionally initialises its * attributes. * * A Ellipse is a Region which represents a elliptical area within the * supplied 2-dimensional Frame. * Parameters: c frame f FRAME = INTEGER (Given) * A pointer to the Frame in which the region is defined. It must * have exactly 2 axes. A deep copy is taken of the supplied Frame. * This means that any subsequent changes made to the Frame using the * supplied pointer will have no effect the Region. c form f FORM = INTEGER (Given) * Indicates how the ellipse is described by the remaining parameters. * A value of zero indicates that the ellipse is specified by a * centre position and two positions on the circumference. A value of * one indicates that the ellipse is specified by its centre position, * the half-lengths of its two axes, and the orientation of its first * axis. c centre f CENTRE( 2 ) = DOUBLE PRECISION (Given) c An array of 2 doubles, f An array * containing the coordinates at the centre of * the ellipse. c point1 f POINT1( 2 ) = DOUBLE PRECISION (Given) c An array of 2 doubles. If "form" f If FORM * is zero, this array should contain the coordinates of one of the four * points where an axis of the ellipse crosses the circumference of the * ellipse. c If "form" f If FORM * is one, it should contain the lengths of semi-major and * semi-minor axes of the ellipse, given as geodesic distances * within the Frame. c point2 f POINT2( 2 ) = DOUBLE PRECISION (Given) c An array of 2 doubles. If "form" f If FORM * is zero, this array should containing the coordinates at some other * point on the circumference of the ellipse, distinct from c "point1". If "form" f POINT1. If FORM * is one, the first element of this array should hold the angle * between the second axis of the Frame and the first ellipse axis * (i.e. the ellipse axis which is specified first in the c "point1" f POINT1 * array), and the second element will be ignored. The angle should be * given in radians, measured positive in the same sense as rotation * from the positive direction of the second Frame axis to the positive * direction of the first Frame axis. c unc f UNC = INTEGER (Given) * An optional pointer to an existing Region which specifies the * uncertainties associated with the boundary of the Ellipse being created. * The uncertainty in any point on the boundary of the Ellipse is found by * shifting the supplied "uncertainty" Region so that it is centred at * the boundary point being considered. The area covered by the * shifted uncertainty Region then represents the uncertainty in the * boundary position. The uncertainty is assumed to be the same for * all points. * * If supplied, the uncertainty Region must be of a class for which * all instances are centro-symetric (e.g. Box, Circle, Ellipse, etc.) * or be a Prism containing centro-symetric component Regions. A deep * copy of the supplied Region will be taken, so subsequent changes to * the uncertainty Region using the supplied pointer will have no * effect on the created Ellipse. Alternatively, f a null Object pointer (AST__NULL) c a NULL Object pointer * may be supplied, in which case a default uncertainty is used * equivalent to a box 1.0E-6 of the size of the Ellipse being created. * * The uncertainty Region has two uses: 1) when the c astOverlap f AST_OVERLAP * function compares two Regions for equality the uncertainty * Region is used to determine the tolerance on the comparison, and 2) * when a Region is mapped into a different coordinate system and * subsequently simplified (using c astSimplify), f AST_SIMPLIFY), * the uncertainties are used to determine if the transformed boundary * can be accurately represented by a specific shape of Region. c options f OPTIONS = CHARACTER * ( * ) (Given) c Pointer to a null-terminated string containing an optional c comma-separated list of attribute assignments to be used for c initialising the new Ellipse. The syntax used is identical to c that for the astSet function and may include "printf" format c specifiers identified by "%" symbols in the normal way. f A character string containing an optional comma-separated f list of attribute assignments to be used for initialising the f new Ellipse. The syntax used is identical to that for the f AST_SET routine. c ... c If the "options" string contains "%" format specifiers, then c an optional list of additional arguments may follow it in c order to supply values to be substituted for these c specifiers. The rules for supplying these are identical to c those for the astSet function (and for the C "printf" c function). f STATUS = INTEGER (Given and Returned) f The global status. * Returned Value: c astEllipse() f AST_ELLIPSE = INTEGER * A pointer to the new Ellipse. * Notes: * - A null Object pointer (AST__NULL) will be returned if this c function is invoked with the AST error status set, or if it f function is invoked with STATUS set to an error value, or if it * should fail for any reason. *-- */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstFrame *frame; /* Pointer to Frame structure */ AstEllipse *new; /* Pointer to new Ellipse */ va_list args; /* Variable argument list */ /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(NULL); /* Check the global status. */ if ( !astOK ) return NULL; /* Obtain and validate a pointer to the supplied Frame structure. */ frame = astCheckFrame( frame_void ); /* Initialise the Ellipse, allocating memory and initialising the virtual function table as well if necessary. */ new = astInitEllipse( NULL, sizeof( AstEllipse ), !class_init, &class_vtab, "Ellipse", frame, form, centre, point1, point2, unc ); /* If successful, note that the virtual function table has been initialised. */ if ( astOK ) { class_init = 1; /* Obtain the variable argument list and pass it along with the options string to the astVSet method to initialise the new Ellipse's attributes. */ va_start( args, status ); astVSet( new, options, NULL, args ); va_end( args ); /* If an error occurred, clean up by deleting the new object. */ if ( !astOK ) new = astDelete( new ); } /* Return a pointer to the new Ellipse. */ return new; } AstEllipse *astEllipseId_( void *frame_void, int form, const double centre[2], const double point1[2], const double point2[2], void *unc_void, const char *options, ... ) { /* * Name: * astEllipseId_ * Purpose: * Create a Ellipse. * Type: * Private function. * Synopsis: * #include "ellipse.h" * AstEllipse *astEllipseId( void *frame_void, int form, const double centre[2], * const double point1[2], const double point2[2], * void *unc_void, const char *options, ..., int *status ) * Class Membership: * Ellipse constructor. * Description: * This function implements the external (public) interface to the * astEllipse constructor function. It returns an ID value (instead * of a true C pointer) to external users, and must be provided * because astEllipse_ has a variable argument list which cannot be * encapsulated in a macro (where this conversion would otherwise * occur). * * The variable argument list also prevents this function from * invoking astEllipse_ directly, so it must be a re-implementation * of it in all respects, except for the final conversion of the * result to an ID value. * Parameters: * As for astEllipse_. * status * Pointer to the inherited status variable. * Returned Value: * The ID value associated with the new Ellipse. */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstFrame *frame; /* Pointer to Frame structure */ AstEllipse *new; /* Pointer to new Ellipse */ AstRegion *unc; /* Pointer to Region structure */ va_list args; /* Variable argument list */ int *status; /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(NULL); /* Pointer to inherited status value */ /* Get a pointer to the inherited status value. */ status = astGetStatusPtr; /* Check the global status. */ if ( !astOK ) return NULL; /* Obtain a Frame pointer from the supplied ID and validate the pointer to ensure it identifies a valid Frame. */ frame = astVerifyFrame( astMakePointer( frame_void ) ); /* Obtain a Region pointer from the supplied "unc" ID and validate the pointer to ensure it identifies a valid Region . */ unc = unc_void ? astCheckRegion( astMakePointer( unc_void ) ) : NULL; /* Initialise the Ellipse, allocating memory and initialising the virtual function table as well if necessary. */ new = astInitEllipse( NULL, sizeof( AstEllipse ), !class_init, &class_vtab, "Ellipse", frame, form, centre, point1, point2, unc ); /* If successful, note that the virtual function table has been initialised. */ if ( astOK ) { class_init = 1; /* Obtain the variable argument list and pass it along with the options string to the astVSet method to initialise the new Ellipse's attributes. */ va_start( args, options ); astVSet( new, options, NULL, args ); va_end( args ); /* If an error occurred, clean up by deleting the new object. */ if ( !astOK ) new = astDelete( new ); } /* Return an ID value for the new Ellipse. */ return astMakeId( new ); } AstEllipse *astInitEllipse_( void *mem, size_t size, int init, AstEllipseVtab *vtab, const char *name, AstFrame *frame, int form, const double centre[2], const double point1[2], const double point2[2], AstRegion *unc, int *status ){ /* *+ * Name: * astInitEllipse * Purpose: * Initialise a Ellipse. * Type: * Protected function. * Synopsis: * #include "ellipse.h" * AstEllipse *astInitEllipse( void *mem, size_t size, int init, * AstEllipseVtab *vtab, const char *name, * AstFrame *frame, const double centre[2], * const double point1[2], const double point2[2], * AstRegion *unc ) * Class Membership: * Ellipse initialiser. * Description: * This function is provided for use by class implementations to initialise * a new Ellipse object. It allocates memory (if necessary) to accommodate * the Ellipse plus any additional data associated with the derived class. * It then initialises a Ellipse structure at the start of this memory. If * the "init" flag is set, it also initialises the contents of a virtual * function table for a Ellipse at the start of the memory passed via the * "vtab" parameter. * Parameters: * mem * A pointer to the memory in which the Ellipse is to be initialised. * This must be of sufficient size to accommodate the Ellipse data * (sizeof(Ellipse)) plus any data used by the derived class. If a value * of NULL is given, this function will allocate the memory itself using * the "size" parameter to determine its size. * size * The amount of memory used by the Ellipse (plus derived class data). * This will be used to allocate memory if a value of NULL is given for * the "mem" parameter. This value is also stored in the Ellipse * structure, so a valid value must be supplied even if not required for * allocating memory. * init * A logical flag indicating if the Ellipse's virtual function table is * to be initialised. If this value is non-zero, the virtual function * table will be initialised by this function. * vtab * Pointer to the start of the virtual function table to be associated * with the new Ellipse. * name * Pointer to a constant null-terminated character string which contains * the name of the class to which the new object belongs (it is this * pointer value that will subsequently be returned by the astGetClass * method). * frame * A pointer to the Frame in which the region is defined. * form * Indicates how the "point" parameter should be interpreted. * Should be either 0 or 1. * centre * An array of double, with one element for each Frame axis (Naxes * attribute) containing the coordinates of the ellipse centre. * point1 * An array of double, with one element for each Frame axis (Naxes * attribute). If "form" is zero, it should contain the coordinates at * the end of one of the axes of the ellipse. If "form" is one, it * should contain the semi-major and semi-minor axes of the ellipse. * point2 * An array of double, with one element for each Frame axis (Naxes * attribute). If "form" is zero, it should contain the coordinates at * some other point on the circumference of the ellipse. If "form" is * one, element [1] is ignored and element [0] should contain the * angle from the second frame axis to the first ellipse axis, given in * radians, measured positive in the same sense as rotation from the * positive direction of the second Frame axis to the positive * direction of the first Frame axis. The "first" ellipse axis is * whichever of the semi-major or semi-minor axis is specified first in * the "point1" array. * unc * A pointer to a Region which specifies the uncertainty in the * supplied positions (all points on the boundary of the new Ellipse * being initialised are assumed to have the same uncertainty). A NULL * pointer can be supplied, in which case default uncertainties equal to * 1.0E-6 of the dimensions of the new Ellipse's bounding box are used. * If an uncertainty Region is supplied, it must be either a Box, a * Circle or an Ellipse, and its encapsulated Frame must be related * to the Frame supplied for parameter "frame" (i.e. astConvert * should be able to find a Mapping between them). Two positions * the "frame" Frame are considered to be co-incident if their * uncertainty Regions overlap. The centre of the supplied * uncertainty Region is immaterial since it will be re-centred on the * point being tested before use. A deep copy is taken of the supplied * Region. * Returned Value: * A pointer to the new Ellipse. * Notes: * - A null pointer will be returned if this function is invoked with the * global error status set, or if it should fail for any reason. *- */ /* Local Variables: */ AstEllipse *new; /* Pointer to new Ellipse */ AstPointSet *pset; /* PointSet to pass to Region initialiser */ double **ptr; /* Pointer to coords data in pset */ const double *p1; /* Pointer to circumference point 1 */ const double *p2; /* Pointer to circumference point 2 */ int i; /* axis index */ int nc; /* No. of axes */ /* Check the global status. */ if ( !astOK ) return NULL; /* If necessary, initialise the virtual function table. */ if ( init ) astInitEllipseVtab( vtab, name ); /* Initialise. */ new = NULL; /* Check the supplied value for "form" is legal. */ if( form != 0 && form != 1 && astOK ) { astError( AST__BADIN, "astInitEllipse(%s): The value supplied for " "parameter \"form\" (%d) is illegal - it should be 0 or 1 " "(programming error).", status, name, form ); } /* Get the number of axis values required for each position. */ nc = astGetNaxes( frame ); /* Report an error if the Frame is not 2-dimensional. */ if( nc != 2 ) { astError( AST__BADIN, "astInitEllipse(%s): The supplied %s has %d " "axes - ellipses must have exactly 2 axes.", status, name, astGetClass( frame ), nc ); } /* If the ellipse is specified by axis lengths and orientation, find two points on the circumference (ends of the two ellipse axes). */ if( form == 1 ) { p1 = astMalloc( sizeof( double )*2 ); p2 = astMalloc( sizeof( double )*2 ); if( astOK ) { astOffset2( frame, centre, *point2, point1[ 0 ], (double *) p1 ); astOffset2( frame, centre, *point2 + AST__DPIBY2, point1[ 1 ], (double *) p2 ); } /* If the ellipse is specified by two points on the circumference, use them. */ } else { p1 = point1; p2 = point2; } /* Create a PointSet to hold the supplied values, and get points to the data arrays. */ pset = astPointSet( 3, nc, " ", status ); ptr = astGetPoints( pset ); /* Copy the supplied coordinates into the PointSet, checking that no bad values have been supplied. */ for( i = 0; astOK && i < nc; i++ ) { if( centre[ i ] == AST__BAD ) { astError( AST__BADIN, "astInitEllipse(%s): The value of axis %d is " "undefined at the ellipse centre.", status, name, i + 1 ); } if( astOK && p1[ i ] == AST__BAD ) { astError( AST__BADIN, "astInitEllipse(%s): The value of axis %d is " "undefined at point 1 on the circumference of " "the ellipse.", status, name, i + 1 ); } if( astOK && p2[ i ] == AST__BAD ) { astError( AST__BADIN, "astInitEllipse(%s): The value of axis %d is " "undefined at point 2 on the circumference of " "the ellipse.", status, name, i + 1 ); } ptr[ i ][ 0 ] = centre[ i ]; ptr[ i ][ 1 ] = p1[ i ]; ptr[ i ][ 2 ] = p2[ i ]; } /* Check pointers can be used safely. */ if( astOK ) { /* Initialise a Region structure (the parent class) as the first component within the Ellipse structure, allocating memory if necessary. */ new = (AstEllipse *) astInitRegion( mem, size, 0, (AstRegionVtab *) vtab, name, frame, pset, unc ); if ( astOK ) { /* Initialise the Ellipse data. */ /* ------------------------ */ new->stale = 1; /* If an error occurred, clean up by deleting the new Ellipse. */ if ( !astOK ) new = astDelete( new ); } } /* Free resources. */ pset = astAnnul( pset ); if( form == 1 ) { p1 = astFree( (void *) p1 ); p2 = astFree( (void *) p2 ); } /* Return a pointer to the new Ellipse. */ return new; } AstEllipse *astLoadEllipse_( void *mem, size_t size, AstEllipseVtab *vtab, const char *name, AstChannel *channel, int *status ) { /* *+ * Name: * astLoadEllipse * Purpose: * Load a Ellipse. * Type: * Protected function. * Synopsis: * #include "ellipse.h" * AstEllipse *astLoadEllipse( void *mem, size_t size, AstEllipseVtab *vtab, * const char *name, AstChannel *channel ) * Class Membership: * Ellipse loader. * Description: * This function is provided to load a new Ellipse using data read * from a Channel. It first loads the data used by the parent class * (which allocates memory if necessary) and then initialises a * Ellipse structure in this memory, using data read from the input * Channel. * * If the "init" flag is set, it also initialises the contents of a * virtual function table for a Ellipse at the start of the memory * passed via the "vtab" parameter. * Parameters: * mem * A pointer to the memory into which the Ellipse is to be * loaded. This must be of sufficient size to accommodate the * Ellipse data (sizeof(Ellipse)) plus any data used by derived * classes. If a value of NULL is given, this function will * allocate the memory itself using the "size" parameter to * determine its size. * size * The amount of memory used by the Ellipse (plus derived class * data). This will be used to allocate memory if a value of * NULL is given for the "mem" parameter. This value is also * stored in the Ellipse structure, so a valid value must be * supplied even if not required for allocating memory. * * If the "vtab" parameter is NULL, the "size" value is ignored * and sizeof(AstEllipse) is used instead. * vtab * Pointer to the start of the virtual function table to be * associated with the new Ellipse. If this is NULL, a pointer * to the (static) virtual function table for the Ellipse class * is used instead. * name * Pointer to a constant null-terminated character string which * contains the name of the class to which the new object * belongs (it is this pointer value that will subsequently be * returned by the astGetClass method). * * If the "vtab" parameter is NULL, the "name" value is ignored * and a pointer to the string "Ellipse" is used instead. * Returned Value: * A pointer to the new Ellipse. * Notes: * - A null pointer will be returned if this function is invoked * with the global error status set, or if it should fail for any * reason. *- */ /* Local Variables: */ astDECLARE_GLOBALS /* Pointer to thread-specific global data */ AstEllipse *new; /* Pointer to the new Ellipse */ /* Initialise. */ new = NULL; /* Check the global error status. */ if ( !astOK ) return new; /* Get a pointer to the thread specific global data structure. */ astGET_GLOBALS(channel); /* If a NULL virtual function table has been supplied, then this is the first loader to be invoked for this Ellipse. In this case the Ellipse belongs to this class, so supply appropriate values to be passed to the parent class loader (and its parent, etc.). */ if ( !vtab ) { size = sizeof( AstEllipse ); vtab = &class_vtab; name = "Ellipse"; /* If required, initialise the virtual function table for this class. */ if ( !class_init ) { astInitEllipseVtab( vtab, name ); class_init = 1; } } /* Invoke the parent class loader to load data for all the ancestral classes of the current one, returning a pointer to the resulting partly-built Ellipse. */ new = astLoadRegion( mem, size, (AstRegionVtab *) vtab, name, channel ); if ( astOK ) { /* Read input data. */ /* ================ */ /* Request the input Channel to read all the input data appropriate to this class into the internal "values list". */ astReadClassData( channel, "Ellipse" ); /* Now read each individual data item from this list and use it to initialise the appropriate instance variable(s) for this class. */ /* In the case of attributes, we first read the "raw" input value, supplying the "unset" value as the default. If a "set" value is obtained, we then use the appropriate (private) Set... member function to validate and set the value properly. */ /* There are no values to read. */ /* ---------------------------- */ /* Indicate that no cache intermediate results are yet available in the Ellipse structure */ new->stale = 1; /* If an error occurred, clean up by deleting the new Ellipse. */ if ( !astOK ) new = astDelete( new ); } /* Return the new Ellipse pointer. */ return new; } /* Virtual function interfaces. */ /* ============================ */ /* These provide the external interface to the virtual functions defined by this class. Each simply checks the global error status and then locates and executes the appropriate member function, using the function pointer stored in the object's virtual function table (this pointer is located using the astMEMBER macro defined in "object.h"). Note that the member function may not be the one defined here, as it may have been over-ridden by a derived class. However, it should still have the same interface. */ void astEllipsePars_( AstEllipse *this, double centre[2], double *a, double *b, double *angle, double p1[2], double p2[2], int *status ){ if ( !astOK ) return; (**astMEMBER(this,Ellipse,EllipsePars))( this, centre, a, b, angle, p1, p2, status ); }
34.713351
119
0.616738
[ "mesh", "geometry", "object", "shape", "transform" ]
1e244b7bd90f3677bf94a40c19528be8d522c536
9,545
h
C
src/MushMesh/MushMeshArray.h
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
9
2020-11-02T17:20:40.000Z
2021-12-25T15:35:36.000Z
src/MushMesh/MushMeshArray.h
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
2
2020-06-27T23:14:13.000Z
2020-11-02T17:28:32.000Z
src/MushMesh/MushMeshArray.h
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
1
2021-05-12T23:05:42.000Z
2021-05-12T23:05:42.000Z
//%includeGuardStart { #ifndef MUSHMESHARRAY_H #define MUSHMESHARRAY_H //%includeGuardStart } CYljICa3h+r4WSdWcHsDTw //%Header { /***************************************************************************** * * File: src/MushMesh/MushMeshArray.h * * Copyright: Andy Southgate 2002-2007, 2020 * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ****************************************************************************/ //%Header } 1GeQjX8k+qQNxWcCUl8vgg /* * $Id: MushMeshArray.h,v 1.18 2006/06/01 15:39:29 southa Exp $ * $Log: MushMeshArray.h,v $ * Revision 1.18 2006/06/01 15:39:29 southa * DrawArray verification and fixes * * Revision 1.17 2005/07/04 15:59:00 southa * Adanaxis work * * Revision 1.16 2005/05/19 13:02:09 southa * Mac release work * * Revision 1.15 2005/02/03 15:46:51 southa * Quaternion work * * Revision 1.14 2004/03/07 12:05:56 southa * Rendering work * * Revision 1.13 2004/01/08 16:06:11 southa * XML fixes * * Revision 1.12 2004/01/02 21:13:10 southa * Source conditioning * * Revision 1.11 2004/01/01 21:15:46 southa * Created XCode project * * Revision 1.10 2003/10/23 20:03:57 southa * End mesh work * * Revision 1.9 2003/10/20 13:02:53 southa * Patch fixes and testing * * Revision 1.8 2003/10/19 12:41:42 southa * Connectors * * Revision 1.7 2003/10/18 20:28:38 southa * Subdivision speed tests * * Revision 1.6 2003/10/18 12:58:38 southa * Subdivision implementation * * Revision 1.5 2003/10/17 19:33:10 southa * Mesh patches * * Revision 1.4 2003/10/17 12:27:18 southa * Line end fixes and more mesh work * * Revision 1.3 2003/10/15 12:26:58 southa * MushMeshArray neighbour testing and subdivision work * * Revision 1.2 2003/10/15 11:54:54 southa * MushMeshArray neighbour testing and subdivision * * Revision 1.1 2003/10/15 07:08:29 southa * MushMeshArray creation * */ #include "MushMeshStandard.h" #include "MushMeshVector.h" #define MUSHMESHARRAY_VERBOSE_DEBUG #ifdef MUSHMESHARRAY_VERBOSE_DEBUG #include "MushMeshSTL.h" #endif template <class T> class MushMeshArray { public: MushMeshArray(); MushMeshArray(Mushware::U32 inXSize, Mushware::U32 inYSize); const T& Get(Mushware::U32 inX, Mushware::U32 inY) const; const T& RefGet(Mushware::U32 inX, Mushware::U32 inY) const; T& WRefGet(Mushware::U32 inX, Mushware::U32 inY); const T& Get(const Mushware::t2U32& inPos) const; const T *DataPtrGet(Mushware::U32 inX, Mushware::U32 inY) const; const T *DataPtrGet(const Mushware::t2U32& inPos) const; void Set(const T& inValue, Mushware::U32 inX, Mushware::U32 inY); void Set(const T& inValue, const Mushware::t2U32& inPos); const Mushware::t2U32 SizeGet(void) const; void SizeSet(const Mushware::t2U32& inSize); Mushware::U32 XSizeGet(void) const { return m_xSize; } Mushware::U32 YSizeGet(void) const { return m_ySize; } bool EqualIs(const MushMeshArray<T>& inObj) const; void Print(std::ostream& ioOut) const; #ifndef HAVE_RESIZING_VALARRAY_ASSIGNMENT MushMeshArray<T>& operator=(const MushMeshArray<T>& inObj) { // With most compilers we must resize the valarray before assignment m_xSize = inObj.m_xSize; m_ySize = inObj.m_ySize; if (m_values.size() != inObj.m_values.size()) { m_values.resize(0); // Prevent copies in the next resize m_values.resize(inObj.m_values.size()); } m_values = inObj.m_values; return *this; } #endif private: Mushware::U32 m_xSize; Mushware::U32 m_ySize; MushwareValarray<T> m_values; }; template <class T> MushMeshArray<T>::MushMeshArray() : m_xSize(0), m_ySize(0) { } template <class T> MushMeshArray<T>::MushMeshArray(Mushware::U32 inXSize, Mushware::U32 inYSize) : m_xSize(inXSize), m_ySize(inYSize), m_values(inXSize*inYSize) { } template <class T> inline const T& MushMeshArray<T>::Get(Mushware::U32 inX, Mushware::U32 inY) const { #ifdef MUSHMESHARRAY_VERBOSE_DEBUG if (inX >= m_xSize || inY >= m_ySize) { std::ostringstream message; message << "MushMeshArray::Get failed: " << inX << ">=" << m_xSize << " || " << inY << ">=" << m_ySize; throw MushcoreLogicFail(message.str()); } #else MUSHCOREASSERT(inX < m_xSize && inY < m_ySize); #endif return m_values[inX + m_xSize * inY]; } template <class T> inline const T& MushMeshArray<T>::RefGet(Mushware::U32 inX, Mushware::U32 inY) const { #ifdef MUSHMESHARRAY_VERBOSE_DEBUG if (inX >= m_xSize || inY >= m_ySize) { std::ostringstream message; message << "MushMeshArray::RefGet failed: " << inX << ">=" << m_xSize << " || " << inY << ">=" << m_ySize; throw MushcoreLogicFail(message.str()); } #else MUSHCOREASSERT(inX < m_xSize && inY < m_ySize); #endif return m_values[inX + m_xSize * inY]; } template <class T> inline T& MushMeshArray<T>::WRefGet(Mushware::U32 inX, Mushware::U32 inY) { #ifdef MUSHMESHARRAY_VERBOSE_DEBUG if (inX >= m_xSize || inY >= m_ySize) { std::ostringstream message; message << "MushMeshArray::RefGet failed: " << inX << ">=" << m_xSize << " || " << inY << ">=" << m_ySize; throw MushcoreLogicFail(message.str()); } #else MUSHCOREASSERT(inX < m_xSize && inY < m_ySize); #endif return m_values[inX + m_xSize * inY]; } template <class T> inline const T& MushMeshArray<T>::Get(const Mushware::t2U32& inPos) const { return Get(inPos.X(), inPos.Y()); } template <class T> inline const T * MushMeshArray<T>::DataPtrGet(Mushware::U32 inX, Mushware::U32 inY) const { #ifdef MUSHMESHARRAY_VERBOSE_DEBUG if (inX >= m_xSize || inY >= m_ySize) { std::ostringstream message; message << "MushMeshArray::DataPtrGet failed: " << inX << ">=" << m_xSize << " || " << inY << ">=" << m_ySize; throw MushcoreLogicFail(message.str()); } #else MUSHCOREASSERT(inX < m_xSize && inY < m_ySize); #endif return &m_values[inX + m_xSize * inY]; } template <class T> inline const T * MushMeshArray<T>::DataPtrGet(const Mushware::t2U32& inPos) const { return DataPtrGet(inPos.X(), inPos.Y()); } template <class T> inline void MushMeshArray<T>::Set(const T& inValue, Mushware::U32 inX, Mushware::U32 inY) { #ifdef MUSHMESHARRAY_VERBOSE_DEBUG if (inX >= m_xSize || inY >= m_ySize) { std::ostringstream message; message << "MushMeshArray::Set failed: " << inX << ">=" << m_xSize << " || " << inY << ">=" << m_ySize; throw MushcoreLogicFail(message.str()); } #else MUSHCOREASSERT(inX < m_xSize && inY < m_ySize); #endif m_values[inX + m_xSize * inY] = inValue; } template <class T> inline void MushMeshArray<T>::Set(const T& inValue, const Mushware::t2U32& inPos) { Set(inValue, inPos.X(), inPos.Y()); } template <class T> inline const Mushware::t2U32 MushMeshArray<T>::SizeGet(void) const { return Mushware::t2U32(m_xSize, m_ySize); } template <class T> inline void MushMeshArray<T>::SizeSet(const Mushware::t2U32& inSize) { if (Mushware::t2U32(m_xSize, m_ySize) != inSize) { // This is a destructive resize. No previous elements are copied m_values.resize(0); m_xSize = inSize.X(); m_ySize = inSize.Y(); m_values.resize(m_xSize * m_ySize); } } template <class T> inline bool MushMeshArray<T>::EqualIs(const MushMeshArray<T>& inObj) const { if (m_values.size() != inObj.m_values.size()) { return false; } for (Mushware::U32 i=0; i < m_values.size(); ++i) { if (m_values[i] != inObj.m_values[i]) { return false; } } return ((m_xSize == inObj.m_xSize) && (m_ySize == inObj.m_ySize)); } template <class T> inline void MushMeshArray<T>::Print(std::ostream& ioOut) const { ioOut << "["; ioOut << "xSize=" << m_xSize << ", "; ioOut << "ySize=" << m_ySize << ", "; //FIXME ioOut << "values=" << m_values; ioOut << "]"; } template <class T> inline bool operator==(const MushMeshArray<T>& a, const MushMeshArray<T>& b) { return a.EqualIs(b); } template <class T> inline bool operator!=(const MushMeshArray<T>& a, const MushMeshArray<T>& b) { return !a.EqualIs(b); } template <class T> inline std::ostream& operator<<(std::ostream& ioOut, const MushMeshArray<T>& inObj) { inObj.Print(ioOut); return ioOut; } //%includeGuardEnd { #endif //%includeGuardEnd } hNb4yLSsimk5RFvFdUzHEw
27.827988
118
0.65186
[ "mesh" ]
1e29844088d5046714f6dce5612dac4039d0da74
1,788
h
C
smtk/bridge/cgm/operators/CreateBrick.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/bridge/cgm/operators/CreateBrick.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/bridge/cgm/operators/CreateBrick.h
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef __smtk_session_cgm_CreateBrick_h #define __smtk_session_cgm_CreateBrick_h #include "smtk/bridge/cgm/Operator.h" namespace smtk { namespace bridge { namespace cgm { /**\brief Create a brick given width, height, depth **or** * center, axes, and extension. * * If given a width, height, and depth, the cuboid * will have one corner on the origin and reside in * the positive octant. * * If given a center, unit-length \a axes, and * positive \a extensions along each axis then * the cuboid is constructed as a sheet body, * which may be flat (when one entry of the \a extension * vector is 0). * At most, a single extry of \a extension may be * zero. All other entries must be positive and above * the modeling kernel's "RESABS" parameter. * Note that \a extension values are half-widths along * their corresponding axis (i.e., how far the cuboid * extends along the axis from the center point). */ class SMTKCGMSESSION_EXPORT CreateBrick : public Operator { public: smtkTypeMacro(CreateBrick); smtkCreateMacro(CreateBrick); smtkSharedFromThisMacro(Operator); smtkDeclareModelOperator(); protected: virtual smtk::model::OperatorResult operateInternal(); }; } // namespace cgm } // namespace bridge } // namespace smtk #endif // __smtk_session_cgm_CreateBrick_h
32.509091
75
0.667785
[ "vector", "model" ]
1e29c9168cff2ab98dbad141757553c906f6c55a
1,501
h
C
src/game/server/tf2/tf_obj_manned_missilelauncher.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/tf2/tf_obj_manned_missilelauncher.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/tf2/tf_obj_manned_missilelauncher.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef TF_OBJ_MANNED_MISSILELAUNCHER_H #define TF_OBJ_MANNED_MISSILELAUNCHER_H #ifdef _WIN32 #pragma once #endif #include "tf_obj_base_manned_gun.h" // ------------------------------------------------------------------------ // // A stationary gun that players can man that's built by the player // ------------------------------------------------------------------------ // class CObjectMannedMissileLauncher : public CObjectBaseMannedGun { DECLARE_CLASS( CObjectMannedMissileLauncher, CObjectBaseMannedGun ); public: DECLARE_SERVERCLASS(); DECLARE_DATADESC(); static CObjectMannedMissileLauncher* Create(const Vector &vOrigin, const QAngle &vAngles); CObjectMannedMissileLauncher(); virtual void Spawn(); virtual void Precache(); virtual void FinishedBuilding( void ); virtual void SetupTeamModel( void ); void MissileRechargeThink( void ); #if defined( CLIENT_DLL ) virtual bool ShouldPredict( void ) { if ( GetOwner() == C_BasePlayer::GetLocalPlayer() ) return true; return BaseClass::ShouldPredict(); } virtual void PreDataUpdate( DataUpdateType_t updateType ); virtual void PostDataUpdate( DataUpdateType_t updateType ); #endif protected: // Fire the weapon virtual void Fire( void ); int m_nPreviousTeam; int m_nMaxAmmoCount; }; #endif // TF_OBJ_MANNED_MISSILELAUNCHER_H
25.87931
91
0.638907
[ "vector" ]
1e32e138f67492af5a2f49966a540c096fe65a9f
830
h
C
electron/common/api/RemoteObjectFreer.h
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
electron/common/api/RemoteObjectFreer.h
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
electron/common/api/RemoteObjectFreer.h
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_ #define ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_ #include "common/api/ObjectLifeMonitor.h" #include "cef/include/base/cef_macros.h" namespace atom { class RemoteObjectFreer : public ObjectLifeMonitor { public: static void bindTo(v8::Isolate* isolate, v8::Local<v8::Object> target, int objectId); protected: RemoteObjectFreer(v8::Isolate* isolate, v8::Local<v8::Object> target, int objectId); virtual ~RemoteObjectFreer() override; virtual void onRunDestructor() override; private: int m_objectId; DISALLOW_COPY_AND_ASSIGN(RemoteObjectFreer); }; } // namespace atom #endif // ATOM_COMMON_API_REMOTE_OBJECT_FREER_H_
25.9375
89
0.766265
[ "object" ]
1e39b91503fdc656ed9fd91995559f7f28f78d9b
2,005
h
C
gitstatus/src/thread_pool.h
ptavares/powerlevel10k
6aeb13b08aab0b35f0c9b0212f1c0cba89eaa5d3
[ "MIT" ]
27,470
2019-03-02T11:50:28.000Z
2022-03-31T21:59:56.000Z
gitstatus/src/thread_pool.h
ptavares/powerlevel10k
6aeb13b08aab0b35f0c9b0212f1c0cba89eaa5d3
[ "MIT" ]
1,796
2019-03-02T19:45:24.000Z
2022-03-31T10:39:08.000Z
gitstatus/src/thread_pool.h
ptavares/powerlevel10k
6aeb13b08aab0b35f0c9b0212f1c0cba89eaa5d3
[ "MIT" ]
1,863
2019-03-03T14:31:31.000Z
2022-03-30T21:42:34.000Z
#ifndef ROMKATV_GITSTATUS_THREAD_POOL_H_ #define ROMKATV_GITSTATUS_THREAD_POOL_H_ #include <condition_variable> #include <cstddef> #include <cstdint> #include <functional> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <utility> #include "time.h" namespace gitstatus { class ThreadPool { public: explicit ThreadPool(size_t num_threads); ThreadPool(ThreadPool&&) = delete; // Waits for the currently running functions to finish. // Does NOT wait for the queue of functions to drain. // If you want the latter, call Wait() manually. ~ThreadPool(); // Runs `f` on one of the threads at or after time `t`. Can be called // from any thread. Can be called concurrently. // // Does not block. void Schedule(Time t, std::function<void()> f); void Schedule(std::function<void()> f) { Schedule(Clock::now(), std::move(f)); } // Blocks until the work queue is empty and there are no currently // running functions. void Wait(); size_t num_threads() const { return threads_.size(); } private: struct Work { bool operator<(const Work& w) const { return std::tie(w.t, w.idx) < std::tie(t, idx); } Time t; int64_t idx; mutable std::function<void()> f; }; void Loop(size_t tid); int64_t last_idx_ = 0; int64_t num_inflight_; bool exit_ = false; // Do we have a thread waiting on sleeper_cv_? bool have_sleeper_ = false; std::mutex mutex_; // Any number of threads can wait on this condvar. Always without a timeout. std::condition_variable cv_; // At most one thread can wait on this condvar at a time. Always with a timeout. std::condition_variable sleeper_cv_; // Signalled when the work queue is empty and there is nothing inflight. std::condition_variable idle_cv_; std::priority_queue<Work> work_; std::vector<std::thread> threads_; }; void InitGlobalThreadPool(size_t num_threads); ThreadPool* GlobalThreadPool(); } // namespace gitstatus #endif // ROMKATV_GITSTATUS_THREAD_POOL_H_
26.733333
91
0.712718
[ "vector" ]
1e4be4b9c15ca1b1bd27b6e9da1fd1fd274431e3
18,429
h
C
aws-cpp-sdk-rbin/include/aws/rbin/RecycleBinClient.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-rbin/include/aws/rbin/RecycleBinClient.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-rbin/include/aws/rbin/RecycleBinClient.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/rbin/RecycleBin_EXPORTS.h> #include <aws/rbin/RecycleBinErrors.h> #include <aws/core/client/AWSError.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/AWSClient.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/rbin/model/CreateRuleResult.h> #include <aws/rbin/model/DeleteRuleResult.h> #include <aws/rbin/model/GetRuleResult.h> #include <aws/rbin/model/ListRulesResult.h> #include <aws/rbin/model/ListTagsForResourceResult.h> #include <aws/rbin/model/TagResourceResult.h> #include <aws/rbin/model/UntagResourceResult.h> #include <aws/rbin/model/UpdateRuleResult.h> #include <aws/core/client/AsyncCallerContext.h> #include <aws/core/http/HttpTypes.h> #include <future> #include <functional> namespace Aws { namespace Http { class HttpClient; class HttpClientFactory; } // namespace Http namespace Utils { template< typename R, typename E> class Outcome; namespace Threading { class Executor; } // namespace Threading } // namespace Utils namespace Auth { class AWSCredentials; class AWSCredentialsProvider; } // namespace Auth namespace Client { class RetryStrategy; } // namespace Client namespace RecycleBin { namespace Model { class CreateRuleRequest; class DeleteRuleRequest; class GetRuleRequest; class ListRulesRequest; class ListTagsForResourceRequest; class TagResourceRequest; class UntagResourceRequest; class UpdateRuleRequest; typedef Aws::Utils::Outcome<CreateRuleResult, RecycleBinError> CreateRuleOutcome; typedef Aws::Utils::Outcome<DeleteRuleResult, RecycleBinError> DeleteRuleOutcome; typedef Aws::Utils::Outcome<GetRuleResult, RecycleBinError> GetRuleOutcome; typedef Aws::Utils::Outcome<ListRulesResult, RecycleBinError> ListRulesOutcome; typedef Aws::Utils::Outcome<ListTagsForResourceResult, RecycleBinError> ListTagsForResourceOutcome; typedef Aws::Utils::Outcome<TagResourceResult, RecycleBinError> TagResourceOutcome; typedef Aws::Utils::Outcome<UntagResourceResult, RecycleBinError> UntagResourceOutcome; typedef Aws::Utils::Outcome<UpdateRuleResult, RecycleBinError> UpdateRuleOutcome; typedef std::future<CreateRuleOutcome> CreateRuleOutcomeCallable; typedef std::future<DeleteRuleOutcome> DeleteRuleOutcomeCallable; typedef std::future<GetRuleOutcome> GetRuleOutcomeCallable; typedef std::future<ListRulesOutcome> ListRulesOutcomeCallable; typedef std::future<ListTagsForResourceOutcome> ListTagsForResourceOutcomeCallable; typedef std::future<TagResourceOutcome> TagResourceOutcomeCallable; typedef std::future<UntagResourceOutcome> UntagResourceOutcomeCallable; typedef std::future<UpdateRuleOutcome> UpdateRuleOutcomeCallable; } // namespace Model class RecycleBinClient; typedef std::function<void(const RecycleBinClient*, const Model::CreateRuleRequest&, const Model::CreateRuleOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CreateRuleResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::DeleteRuleRequest&, const Model::DeleteRuleOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeleteRuleResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::GetRuleRequest&, const Model::GetRuleOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetRuleResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::ListRulesRequest&, const Model::ListRulesOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListRulesResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::ListTagsForResourceRequest&, const Model::ListTagsForResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListTagsForResourceResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::TagResourceRequest&, const Model::TagResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > TagResourceResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::UntagResourceRequest&, const Model::UntagResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > UntagResourceResponseReceivedHandler; typedef std::function<void(const RecycleBinClient*, const Model::UpdateRuleRequest&, const Model::UpdateRuleOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > UpdateRuleResponseReceivedHandler; /** * <p>This is the <i>Recycle Bin API Reference</i>. This documentation provides * descriptions and syntax for each of the actions and data types in Recycle * Bin.</p> <p>Recycle Bin is a resource recovery feature that enables you to * restore accidentally deleted snapshots and EBS-backed AMIs. When using Recycle * Bin, if your resources are deleted, they are retained in the Recycle Bin for a * time period that you specify.</p> <p>You can restore a resource from the Recycle * Bin at any time before its retention period expires. After you restore a * resource from the Recycle Bin, the resource is removed from the Recycle Bin, and * you can then use it in the same way you use any other resource of that type in * your account. If the retention period expires and the resource is not restored, * the resource is permanently deleted from the Recycle Bin and is no longer * available for recovery. For more information about Recycle Bin, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/snapshot-recycle-bin.html"> * Recycle Bin</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ class AWS_RECYCLEBIN_API RecycleBinClient : public Aws::Client::AWSJsonClient { public: typedef Aws::Client::AWSJsonClient BASECLASS; /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ RecycleBinClient(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ RecycleBinClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ RecycleBinClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); virtual ~RecycleBinClient(); /** * <p>Creates a Recycle Bin retention rule. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recycle-bin-working-with-rules.html#recycle-bin-create-rule"> * Create Recycle Bin retention rules</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/CreateRule">AWS API * Reference</a></p> */ virtual Model::CreateRuleOutcome CreateRule(const Model::CreateRuleRequest& request) const; /** * A Callable wrapper for CreateRule that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::CreateRuleOutcomeCallable CreateRuleCallable(const Model::CreateRuleRequest& request) const; /** * An Async wrapper for CreateRule that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void CreateRuleAsync(const Model::CreateRuleRequest& request, const CreateRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Deletes a Recycle Bin retention rule. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recycle-bin-working-with-rules.html#recycle-bin-delete-rule"> * Delete Recycle Bin retention rules</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/DeleteRule">AWS API * Reference</a></p> */ virtual Model::DeleteRuleOutcome DeleteRule(const Model::DeleteRuleRequest& request) const; /** * A Callable wrapper for DeleteRule that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::DeleteRuleOutcomeCallable DeleteRuleCallable(const Model::DeleteRuleRequest& request) const; /** * An Async wrapper for DeleteRule that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void DeleteRuleAsync(const Model::DeleteRuleRequest& request, const DeleteRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Gets information about a Recycle Bin retention rule.</p><p><h3>See Also:</h3> * <a href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/GetRule">AWS API * Reference</a></p> */ virtual Model::GetRuleOutcome GetRule(const Model::GetRuleRequest& request) const; /** * A Callable wrapper for GetRule that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::GetRuleOutcomeCallable GetRuleCallable(const Model::GetRuleRequest& request) const; /** * An Async wrapper for GetRule that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void GetRuleAsync(const Model::GetRuleRequest& request, const GetRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Lists the Recycle Bin retention rules in the Region.</p><p><h3>See Also:</h3> * <a href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/ListRules">AWS * API Reference</a></p> */ virtual Model::ListRulesOutcome ListRules(const Model::ListRulesRequest& request) const; /** * A Callable wrapper for ListRules that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListRulesOutcomeCallable ListRulesCallable(const Model::ListRulesRequest& request) const; /** * An Async wrapper for ListRules that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListRulesAsync(const Model::ListRulesRequest& request, const ListRulesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Lists the tags assigned to a retention rule.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/ListTagsForResource">AWS * API Reference</a></p> */ virtual Model::ListTagsForResourceOutcome ListTagsForResource(const Model::ListTagsForResourceRequest& request) const; /** * A Callable wrapper for ListTagsForResource that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListTagsForResourceOutcomeCallable ListTagsForResourceCallable(const Model::ListTagsForResourceRequest& request) const; /** * An Async wrapper for ListTagsForResource that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListTagsForResourceAsync(const Model::ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Assigns tags to the specified retention rule.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/TagResource">AWS * API Reference</a></p> */ virtual Model::TagResourceOutcome TagResource(const Model::TagResourceRequest& request) const; /** * A Callable wrapper for TagResource that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::TagResourceOutcomeCallable TagResourceCallable(const Model::TagResourceRequest& request) const; /** * An Async wrapper for TagResource that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void TagResourceAsync(const Model::TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Unassigns a tag from a retention rule.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/UntagResource">AWS * API Reference</a></p> */ virtual Model::UntagResourceOutcome UntagResource(const Model::UntagResourceRequest& request) const; /** * A Callable wrapper for UntagResource that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::UntagResourceOutcomeCallable UntagResourceCallable(const Model::UntagResourceRequest& request) const; /** * An Async wrapper for UntagResource that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void UntagResourceAsync(const Model::UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Updates an existing Recycle Bin retention rule. For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recycle-bin-working-with-rules.html#recycle-bin-update-rule"> * Update Recycle Bin retention rules</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rbin-2021-06-15/UpdateRule">AWS API * Reference</a></p> */ virtual Model::UpdateRuleOutcome UpdateRule(const Model::UpdateRuleRequest& request) const; /** * A Callable wrapper for UpdateRule that returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::UpdateRuleOutcomeCallable UpdateRuleCallable(const Model::UpdateRuleRequest& request) const; /** * An Async wrapper for UpdateRule that queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void UpdateRuleAsync(const Model::UpdateRuleRequest& request, const UpdateRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; void OverrideEndpoint(const Aws::String& endpoint); private: void init(const Aws::Client::ClientConfiguration& clientConfiguration); void CreateRuleAsyncHelper(const Model::CreateRuleRequest& request, const CreateRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void DeleteRuleAsyncHelper(const Model::DeleteRuleRequest& request, const DeleteRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void GetRuleAsyncHelper(const Model::GetRuleRequest& request, const GetRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListRulesAsyncHelper(const Model::ListRulesRequest& request, const ListRulesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListTagsForResourceAsyncHelper(const Model::ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void TagResourceAsyncHelper(const Model::TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void UntagResourceAsyncHelper(const Model::UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void UpdateRuleAsyncHelper(const Model::UpdateRuleRequest& request, const UpdateRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; Aws::String m_uri; Aws::String m_configScheme; std::shared_ptr<Aws::Utils::Threading::Executor> m_executor; }; } // namespace RecycleBin } // namespace Aws
59.834416
248
0.732595
[ "model" ]
1e53a6472047e86b48aa02520ebeef150ae5c890
5,046
h
C
src/ui/RenderPanel.h
ivorob/MetroEx-Tools
04ab6b1cc6f0693d69b2fd1274598c836b5ee1e9
[ "MIT" ]
null
null
null
src/ui/RenderPanel.h
ivorob/MetroEx-Tools
04ab6b1cc6f0693d69b2fd1274598c836b5ee1e9
[ "MIT" ]
null
null
null
src/ui/RenderPanel.h
ivorob/MetroEx-Tools
04ab6b1cc6f0693d69b2fd1274598c836b5ee1e9
[ "MIT" ]
1
2020-04-02T17:01:20.000Z
2020-04-02T17:01:20.000Z
#pragma once #include <dxgi.h> #include <d3d11.h> #include "mymath.h" #include "camera.h" class MetroModel; class MetroSkeleton; class MetroMotion; class MetroTexture; using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; namespace MetroEX { struct RenderTexture { ID3D11Texture2D* tex; ID3D11ShaderResourceView* srv; }; struct RenderGeometry { ID3D11Buffer* vb; ID3D11Buffer* ib; size_t numFaces; RenderTexture* texture; bool isCollision; }; struct ViewingParams { vec2 lastLMPos; vec2 lastRMPos; vec2 offset; float zoom; }; struct ConstantBufferData { vec4 modelBSphere; mat4 matModel; mat4 matView; mat4 matProjection; mat4 matModelView; mat4 matModelViewProj; vec4 camParams; mat4 bones[256]; }; struct AnimBone { size_t idx; size_t parentIdx; }; struct Animation { float time; size_t numBones; AnimBone bones[256]; mat4 bindPoseInv[256]; }; public ref class RenderPanel : public System::Windows::Forms::Panel { public: RenderPanel(); protected: ~RenderPanel() { if (components) { delete components; } } public: bool InitGraphics(); void SetModel(MetroModel* model); void SetLod(const size_t lodId); MetroModel* GetModel(); void SetCubemap(MetroTexture* cubemap); void SetShowWireframe(const bool wireframe); void SetShowCollision(const bool collision); void SwitchMotion(const size_t idx); bool IsPlayingAnim(); void PlayAnim(const bool play); void ResetCamera(const bool forceRender); private: bool CreateRenderTargets(); void UpdateCamera(); void CreateModelGeometries(); void CreateTextures(); void CreateRenderTexture(const MetroTexture* srcTexture, RenderTexture* rt); void ResetAnimation(); void UpdateAnimation(const float dt); void Render(); protected: virtual void OnResize(System::EventArgs^ e) override; virtual void OnPaint(System::Windows::Forms::PaintEventArgs^ e) override; virtual void OnMouseDown(System::Windows::Forms::MouseEventArgs^ e) override; virtual void OnMouseMove(System::Windows::Forms::MouseEventArgs^ e) override; virtual void OnMouseWheel(System::Windows::Forms::MouseEventArgs^ e) override; void AnimationTimer_Tick(System::Object^ sender, System::EventArgs^ e); private: System::ComponentModel::IContainer^ components; private: IDXGISwapChain* mSwapChain; ID3D11Device* mDevice; ID3D11DeviceContext* mDeviceContext; ID3D11RenderTargetView* mRenderTargetView; ID3D11Texture2D* mDepthStencilBuffer; ID3D11DepthStencilState* mDepthStencilState; ID3D11DepthStencilView* mDepthStencilView; ID3D11RasterizerState* mRasterState; ID3D11RasterizerState* mRasterStateWireframe; // model viewer ID3D11VertexShader* mModelViewerVS; ID3D11PixelShader* mModelViewerPS; ID3D11PixelShader* mModelViewerWireframePS; ID3D11InputLayout* mModelInputLayout; ID3D11Buffer* mModelConstantBuffer; ID3D11SamplerState* mModelTextureSampler; array<RenderGeometry*>^ mModelGeometries; System::Collections::Generic::Dictionary<String^,IntPtr>^ mModelTextures; // model viewer stuff MetroModel* mModel; // animations const MetroMotion* mCurrentMotion; Animation* mAnimation; System::Windows::Forms::Timer^ mAnimTimer; // cubemap viewer stuff Camera* mCamera; MetroTexture* mCubemap; RenderTexture* mCubemapTexture; ID3D11VertexShader* mCubemapViewerVS; ID3D11PixelShader* mCubemapViewerPS; PointF mLastLMPos; PointF mLastRMPos; float mZoom; bool mShowWireframe; bool mShowCollision; ConstantBufferData* mConstantBufferData; }; }
31.735849
99
0.563615
[ "render", "object", "model" ]
1e5a58d57da7685e1c018fd96afaf207ef01336a
1,752
h
C
3rdparty/webkit/Source/WebCore/dom/RadioButtonGroups.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
3rdparty/webkit/Source/WebCore/dom/RadioButtonGroups.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/dom/RadioButtonGroups.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
/* * Copyright (C) 2007, 2008, 2009, 2016 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #pragma once #include <memory> #include <wtf/Forward.h> #include <wtf/HashMap.h> #include <wtf/Vector.h> namespace WebCore { class HTMLInputElement; class RadioButtonGroup; class RadioButtonGroups { public: RadioButtonGroups(); ~RadioButtonGroups(); void addButton(HTMLInputElement*); void updateCheckedState(HTMLInputElement*); void requiredAttributeChanged(HTMLInputElement*); void removeButton(HTMLInputElement*); HTMLInputElement* checkedButtonForGroup(const AtomicString& groupName) const; bool hasCheckedButton(const HTMLInputElement*) const; bool isInRequiredGroup(HTMLInputElement*) const; Vector<HTMLInputElement*> groupMembers(const HTMLInputElement&) const; private: typedef HashMap<AtomicStringImpl*, std::unique_ptr<RadioButtonGroup>> NameToGroupMap; std::unique_ptr<NameToGroupMap> m_nameToGroupMap; }; } // namespace WebCore
33.692308
89
0.758562
[ "vector" ]
1e5d7c616d2218094ae96edb805e73b468a83b0a
1,889
h
C
src/build/LanguageInfo.h
phoenix-build/phoenix
5f1adaf90b230959e42481439bc7b674e6a9428f
[ "MIT" ]
8
2015-12-06T20:51:09.000Z
2018-05-15T18:44:36.000Z
src/build/LanguageInfo.h
augustin/phoenix
5f1adaf90b230959e42481439bc7b674e6a9428f
[ "MIT" ]
1
2016-01-11T17:26:42.000Z
2016-01-11T17:26:42.000Z
src/build/LanguageInfo.h
augustin/phoenix
5f1adaf90b230959e42481439bc7b674e6a9428f
[ "MIT" ]
2
2015-08-05T19:52:38.000Z
2016-01-11T17:23:33.000Z
/* * (C) 2015-2016 Augustin Cavalier * All rights reserved. Distributed under the terms of the MIT license. */ #pragma once #include <cinttypes> #include <map> #include <string> #include <vector> #include "build/Generators.h" #include "script/Object.h" #include "script/Stack.h" #include "util/OSUtil.h" #ifdef _WIN32 # define APPLICATION_FILE_EXT ".exe" #else # define APPLICATION_FILE_EXT "" #endif class LanguageInfo { public: // From command-line flags & the like. static std::map<std::string, std::string> sPreferredCompiler; static Script::Stack* sStack; static LanguageInfo* getLanguageInfo(std::string langName); // Basic info std::string name; std::string genName; std::vector<std::string> sourceExtensions; std::vector<std::string> extraExtensions; std::string compilerEnviron; // Compiler info std::string compilerName; std::string compilerBinary; std::string compilerDefaultFlags; std::string compilerDependenciesFlag; Generator::DependencyFormat compilerDependencyFormat; std::string compilerDependencyPrefix; std::string compilerCompileFlag; std::string compilerOutputFlag; std::string compilerOutputExtension; std::string compilerLinkBinaryFlag; std::string compilerDefinition; std::string compilerInclude; // Standards modes struct StandardsMode { std::string test; std::string normalFlag; std::string strictFlag; int8_t status; // 0 is untested, -1 is doesn't work, 1 is OK }; std::map<std::string, StandardsMode> standardsModes; // Checks bool checkStandardsMode(std::string standardsMode); // Generation void generate(Generator* gen); private: LanguageInfo(std::string langName, Script::Object info); bool fGenerated; OSUtil::ExecResult checkIfCompiles(const std::string& testName, const std::string& testContents, const std::string& extraFlags = ""); static std::map<std::string, LanguageInfo*> sData; };
24.217949
71
0.754367
[ "object", "vector" ]
d81028c8335c4d60270ddf0a3016660b1c7b85fd
3,616
h
C
MobileAppTracker.framework/Versions/A/Headers/TuneAdView.h
opentable/tune
e52f4e02a02eb34301b5fd180a06719aaeb9c37b
[ "Apache-2.0" ]
null
null
null
MobileAppTracker.framework/Versions/A/Headers/TuneAdView.h
opentable/tune
e52f4e02a02eb34301b5fd180a06719aaeb9c37b
[ "Apache-2.0" ]
null
null
null
MobileAppTracker.framework/Versions/A/Headers/TuneAdView.h
opentable/tune
e52f4e02a02eb34301b5fd180a06719aaeb9c37b
[ "Apache-2.0" ]
2
2018-11-30T12:34:37.000Z
2019-12-29T18:19:05.000Z
// // TuneAdView.h // Tune // // Created by Harshal Ogale on 11/21/14. // Copyright (c) 2014 Tune Inc. All rights reserved. // #import <UIKit/UIKit.h> @class TuneAd; @protocol TuneAdDelegate; /*! List of errors generated by TuneAdView. */ typedef NS_ENUM(NSInteger, TuneAdError) { /*! Invalid placement value provided. Placement must be a string. */ TuneAdErrorInvalidPlacement, /*! No ads are currently available because the SDK is unable to connect to the internet. */ TuneAdErrorNetworkNotReachable, /*! The Ad server could not find any ads that matched the info provided. */ TuneAdErrorNoMatchingAds, /*! The specified app/site/package name was not found on the server. */ TuneAdErrorNoMatchingSites, /*! An unknown error occurred. */ TuneAdErrorUnknown, /*! The specified advertiser id was not found on the server. */ TuneAdErrorUnknownAdvertiser }; /*! Types of ads */ typedef NS_ENUM(NSInteger, TuneAdType) { TuneAdTypeBanner, TuneAdTypeInterstitial }; /*! List of supported orientations */ typedef NS_OPTIONS(NSUInteger, TuneAdOrientation) { TuneAdOrientationAll = 0, TuneAdOrientationPortrait = 1, TuneAdOrientationLandscape = 1 << 1 }; /*! Tune ad view abstract class extended by TuneBanner and TuneInterstitial. To create an ad view instance, please directly use TuneBanner or TuneInterstitial as appropriate. */ @interface TuneAdView : UIView /*! Delegate that handles callbacks from TuneAdView */ @property (nonatomic, assign) id<TuneAdDelegate> delegate; /*! Allowed orientation(s) for this TuneAdView */ @property (nonatomic, assign, setter=setAllowedOrientations:) TuneAdOrientation adOrientations; /*! Flag to check if the next ad is ready for display */ @property (nonatomic, getter=isReady, readonly) BOOL ready; @end /*! Protocol to be implemented in order to receive callbacks from this TuneAdView */ @protocol TuneAdDelegate <NSObject> @required /*! Required callback method called when the next ad is ready for display @param adView the current ad view object */ - (void)tuneAdDidFetchAdForView:(TuneAdView *)adView placement:(NSString *)placement; @optional /*! Optional callback method called when the user clicks the ad and an action is initiated. @param adView the ad view that the user tapped @param willLeave YES if another application will be launched to execute the action; NO if the action is going to be executed inside your application. */ - (void)tuneAdDidStartActionForView:(TuneAdView *)adView willLeaveApplication:(BOOL)willLeave; /*! Optional callback method called when the user ad click action ends. This method is not called if tuneAdDidStartActionForView:willLeaveApplication: was called with willLeave = YES. @param adView the current ad view object */ - (void)tuneAdDidEndActionForView:(TuneAdView *)adView; /*! Optional callback method called when the user clicks the close button on an interstitial ad. This method is not called for banner ads. @param adView the current ad view object */ - (void)tuneAdDidCloseForView:(TuneAdView *)adView; /*! Optional callback method called when this ad view encounters an error. @param adView the current ad view object */ - (void)tuneAdDidFailWithError:(NSError *)error forView:(TuneAdView *)adView; /*! Optional callback method called when a new ad fetch request is fired. @param adView the current ad view object */ - (void)tuneAdDidFireRequestWithUrl:(NSString *)url data:(NSString *)data forView:(TuneAdView *)adView; @end
26.394161
180
0.736173
[ "object" ]
d8131ad06cd3b3c700d9c3311570164a27735480
4,712
h
C
content/browser/renderer_host/websocket_blob_sender.h
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
content/browser/renderer_host/websocket_blob_sender.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/websocket_blob_sender.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_WEBSOCKET_BLOB_SENDER_H_ #define CONTENT_BROWSER_RENDERER_HOST_WEBSOCKET_BLOB_SENDER_H_ #include <stddef.h> #include <stdint.h> #include <iosfwd> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "net/base/completion_callback.h" #include "net/websockets/websocket_event_interface.h" namespace base { class SingleThreadTaskRunner; } namespace net { class IOBuffer; } namespace storage { class BlobReader; class BlobStorageContext; class FileSystemContext; } namespace content { class WebSocketHost; // Read the contents of a Blob and write it to a WebSocket. Single-use: a new // object must be created each time a Blob is sent. Destroying the object // cancels all pending operations. class CONTENT_EXPORT WebSocketBlobSender final { public: // An abstraction of the WebSocketChannel this object will send frames to. class Channel { public: using ChannelState = net::WebSocketEventInterface::ChannelState; Channel() {} virtual ~Channel() {} // The currently available quota for sending. It must not decrease without // SendFrame() being called. virtual size_t GetSendQuota() const = 0; // Send a binary frame. |fin| is true for the final frame of the message. // |data| is the contents of the frame. data.size() must be less than // GetSendQuota(). If this call returns CHANNEL_DELETED, WebSocketBlobSender // will assume that it has been deleted and return without calling any // callbacks or accessing any other member data. virtual ChannelState SendFrame(bool fin, const std::vector<char>& data) = 0; private: DISALLOW_COPY_AND_ASSIGN(Channel); }; // |channel| will be destroyed when this object is. explicit WebSocketBlobSender(std::unique_ptr<Channel> channel); ~WebSocketBlobSender(); // Checks that the blob identified by |uuid| exists, has the size // |expected_size| and then starts sending it via |channel_|. Returns // ERR_IO_PENDING to indicate that |callback| will be called later with the // result. net::OK indicates synchronous success. Any other net error code // indicates synchronous failure. This method may result in the destruction of // the channel, in which case |*channel_state| will be set to CHANNEL_DELETED. int Start(const std::string& uuid, uint64_t expected_size, storage::BlobStorageContext* context, storage::FileSystemContext* file_system_context, base::SingleThreadTaskRunner* file_task_runner, net::WebSocketEventInterface::ChannelState* channel_state, const net::CompletionCallback& callback); // Sends more data if the object was waiting for quota and the new value of // GetSendQuota() is large enough. void OnNewSendQuota(); uint64_t expected_size() const { return expected_size_; } // ActualSize() should only be called after completion: ie. Start() returned a // value other than ERR_IO_PENDING or |callback_| has been called. uint64_t ActualSize() const; private: // State proceeds through READ_SIZE and READ_SIZE_COMPLETE, then // loops WAIT_FOR_QUOTA -> WAIT_FOR_QUOTA_COMPLETE -> READ // -> READ_COMPLETE -> WAIT_FOR_QUOTA until the Blob is completely // sent. enum class State { NONE = 0, READ_SIZE, READ_SIZE_COMPLETE, WAIT_FOR_QUOTA, WAIT_FOR_QUOTA_COMPLETE, READ, READ_COMPLETE, }; // This is needed to make DCHECK_EQ(), etc. compile. friend std::ostream& operator<<(std::ostream& os, State state); void OnReadComplete(int rv); void OnSizeCalculated(int rv); // |channel_state| should point to CHANNEL_ALIVE when called. If it is // CHANNEL_DELETED on return, the object has been deleted. int DoLoop(int result, Channel::ChannelState* channel_state); void DoLoopAsync(int result); int DoReadSize(); int DoReadSizeComplete(int result); int DoWaitForQuota(); int DoWaitForQuotaComplete(); int DoRead(); int DoReadComplete(int result, Channel::ChannelState* channel_state); State next_state_ = State::NONE; uint64_t expected_size_ = 0; uint64_t bytes_left_ = 0; net::CompletionCallback callback_; scoped_refptr<net::IOBuffer> buffer_; std::unique_ptr<storage::BlobReader> reader_; const std::unique_ptr<Channel> channel_; DISALLOW_COPY_AND_ASSIGN(WebSocketBlobSender); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_WEBSOCKET_BLOB_SENDER_H_
33.41844
80
0.741511
[ "object", "vector" ]
d8133f4ce9acccb5528d2931a66b7d4230d5e097
894
h
C
content/browser/vr/android/cardboard/cardboard_vr_device_provider.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
content/browser/vr/android/cardboard/cardboard_vr_device_provider.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
content/browser/vr/android/cardboard/cardboard_vr_device_provider.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_VR_CARDBOARD_VR_DEVICE_PROVIDER_H #define CONTENT_BROWSER_VR_CARDBOARD_VR_DEVICE_PROVIDER_H #include <map> #include <memory> #include "base/macros.h" #include "content/browser/vr/vr_device.h" #include "content/browser/vr/vr_device_provider.h" namespace content { class CardboardVRDeviceProvider : public VRDeviceProvider { public: CardboardVRDeviceProvider(); ~CardboardVRDeviceProvider() override; void GetDevices(std::vector<VRDevice*>* devices) override; void Initialize() override; private: std::unique_ptr<VRDevice> cardboard_device_; DISALLOW_COPY_AND_ASSIGN(CardboardVRDeviceProvider); }; } // namespace content #endif // CONTENT_BROWSER_VR_CARDBOARD_VR_DEVICE_PROVIDER_H
26.294118
73
0.799776
[ "vector" ]
d81a85d14146beb82e6955ab88fa01aa99946ae2
1,620
h
C
Sources/Internal/UI/UIYamlLoader.h
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Sources/Internal/UI/UIYamlLoader.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/UI/UIYamlLoader.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#ifndef __DAVAENGINE_YAML_LOADER_H__ #define __DAVAENGINE_YAML_LOADER_H__ #include "Base/BaseTypes.h" #include "Base/BaseObject.h" #include "FileSystem/FilePath.h" #include "Render/2D/FontManager.h" namespace DAVA { /** \ingroup controlsystem \brief Class to perform loading of controls from yaml configs This class can help you to load hierarhy of controls from yaml config file. Structure of yaml file is very simple and it allow you to modify the structure of the application easily using configuration files. */ class YamlNode; class UIYamlLoader : public BaseObject { protected: ~UIYamlLoader() = default; UIYamlLoader() = default; public: /** \brief This is main function in UIYamlLoader and it loads fonts from yamlPathname file. \param[in] yamlPathName we get config file using this pathname */ static void LoadFonts(const FilePath& yamlPathname); static FontPreset CreateFontPresetFromYamlNode(const YamlNode* node); static YamlNode* CreateYamlNodeFromFontPreset(const FontPreset& preset); /** \brief This function saves fonts to the YAML file passed. \param[in] yamlPathName path to store fonts to \return true if the save was successful */ static bool SaveFonts(const FilePath& yamlPathname); const FontPreset& GetFontPresetByName(const String& fontName) const; protected: //Internal functions that do actual loading and saving. YamlNode* CreateRootNode(const FilePath& yamlPathname); void LoadFontsFromNode(const YamlNode* node); }; }; #endif // __DAVAENGINE_YAML_LOADER_H__
28.928571
114
0.738889
[ "render" ]
d81dd7a6ecb2bfd1603f8801c02abddc07e10357
5,392
h
C
lib/include/virgil/crypto/foundation/VirgilKDF.h
VirgilSecurity/virgil-crypto
6a8f44c6287b2179cdce6b7a7135ce8275491ea4
[ "BSD-3-Clause" ]
74
2015-12-02T09:04:38.000Z
2022-03-20T11:15:40.000Z
lib/include/virgil/crypto/foundation/VirgilKDF.h
the4kgamer/virgil-crypto
4c51ec37e8456b2947d971aebfe516a5001ba8f1
[ "BSD-3-Clause" ]
6
2016-05-29T12:51:13.000Z
2020-05-15T06:23:59.000Z
lib/include/virgil/crypto/foundation/VirgilKDF.h
the4kgamer/virgil-crypto
4c51ec37e8456b2947d971aebfe516a5001ba8f1
[ "BSD-3-Clause" ]
29
2015-12-15T09:21:08.000Z
2021-07-06T08:47:47.000Z
/** * Copyright (C) 2015-2018 Virgil Security Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (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 AUTHOR ''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 AUTHOR 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. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> */ #ifndef VIRGIL_CRYPTO_KDF_H #define VIRGIL_CRYPTO_KDF_H #include <string> #include <memory> #include "../VirgilByteArray.h" #include "asn1/VirgilAsn1Compatible.h" namespace virgil { namespace crypto { namespace foundation { /** * @brief Provides key derivation function algorithms. * @ingroup kdf */ class VirgilKDF : public asn1::VirgilAsn1Compatible { public: /** * @brief Enumerates possible Key Derivation Function algorithms. */ enum class Algorithm { KDF1, ///< KDF Algorithm: KDF1 (ISO-18033-2) KDF2 ///< KDF Algorithm: KDF2 (ISO-18033-2) }; /** * @name Constructor / Destructor */ ///@{ /** * @brief Create object with undefined algorithm. * @warning SHOULD be used in conjunction with VirgilAsn1Compatible interface, * i.e. VirgilKDF kdf; kdf.fromAsn1(asn1); */ VirgilKDF(); /** * @brief Create object with specific algorithm type. */ explicit VirgilKDF(VirgilKDF::Algorithm alg); /** * @brief Create object with given algorithm name. * @note Names SHOULD be the identical to the VirgilKDF::Algorithm enumeration. */ explicit VirgilKDF(const std::string& name); /** * @brief Create object with given algorithm name. * @note Names SHOULD be the identical to the VirgilKDF::Algorithm enumeration. */ explicit VirgilKDF(const char* name); ///@} /** * @name Info * Provide detail information about object. */ ///@{ /** * @brief Returns name of the key derivation function. * @return Name of the key derivation function. */ std::string name() const; ///@} /** * @name Process key derivation */ ///@{ /** * @brief Derive key from the given key material. * * @param in - input sequence (key material). * @param outSize - size of the output sequence. * @return Output sequence. */ virgil::crypto::VirgilByteArray derive(const virgil::crypto::VirgilByteArray& in, size_t outSize); ///@} /** * @name VirgilAsn1Compatible implementation * @code * Marshalling format: * KeyDerivationFunction ::= AlgorithmIdentifier {{ KDFAlgorithms }} * KDFAlgorithms AlgorithmIdentifier ::= { * { OID id-kdf-kdf1 PARMS HashFunction } | * { OID id-kdf-kdf2 PARMS HashFunction } , * ... -- additional algorithms --- * } * * HashFunction ::= AlgorithmIdentifier {{ HashAlgorithms }} * HashAlgorithms AlgorithmIdentifier ::= { * -- nist identifiers * { OID id-sha1 PARMS NULL } | * { OID id-sha256 PARMS NULL } | * { OID id-sha384 PARMS NULL } | * { OID id-sha512 PARMS NULL } , * ... -- additional algorithms --- * } * @endcode */ ///@{ size_t asn1Write(asn1::VirgilAsn1Writer& asn1Writer, size_t childWrittenBytes = 0) const override; void asn1Read(asn1::VirgilAsn1Reader& asn1Reader) override; ///@} public: //! @cond Doxygen_Suppress VirgilKDF(VirgilKDF&& rhs) noexcept; VirgilKDF& operator=(VirgilKDF&& rhs) noexcept; virtual ~VirgilKDF() noexcept; //! @endcond private: /** * @brief If internal state is not initialized with specific algorithm exception will be thrown. */ void checkState() const; private: class Impl; std::unique_ptr<Impl> impl_; }; }}} namespace std { /** * @brief Returns string representation of the KDF algorithm. * @return KDF algorithm as string. * @ingroup kdf */ string to_string(virgil::crypto::foundation::VirgilKDF::Algorithm alg); } #endif /* VIRGIL_CRYPTO_KDF_H */
31.16763
102
0.653004
[ "object" ]
d8224d1204e1b3dbeaf28522384bbc0869ab47cb
2,483
h
C
core/include/xs/appcontext.h
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
15
2016-01-21T19:57:11.000Z
2021-04-08T08:59:01.000Z
core/include/xs/appcontext.h
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
5
2015-12-05T03:41:43.000Z
2016-10-17T16:25:35.000Z
core/include/xs/appcontext.h
mixtile/gena-xskit
9d273840c60493c509c72b281463a376702539fb
[ "Apache-2.0" ]
10
2016-03-21T09:34:01.000Z
2020-07-21T18:34:07.000Z
#ifndef _XS_APPCONTEXT_H_ #define _XS_APPCONTEXT_H_ #include <xs/runtimecontext.h> #include <xs/launcher.h> //#include <xs/loader.h> #include <xs/stream.h> #include <xs/entry.h> #include <xs/httpconnection.h> class xsAppContext : public xsRuntimeContext { public: static xsAppContext *createInstance(const char *appUri); void destroyInstance(); int start(); void suspend(); int resume(); void exit(); virtual int processEvent(xsEvent *e); inline int getOrient() { return _orient; } inline xsTChar *getName() { return _name; } inline int getLoaded() { return _loaded; } inline int getIndex() const { return _index; } inline void setIndex(int index) { _index = index; } virtual const char *getId() const { return _id; } virtual const int getLoadMode() const { return _loadMode; } virtual const xsTChar *getBasePath() const { return _loadPath; } virtual xsRes getRes() const { return _res; } virtual xsFile getFd() const { return _fd; } public: enum _xsLoadState { LOAD_READY = 0, LOAD_COMPLETE = 10000, LOAD_FAILED = -1 }; protected: xsAppContext(); virtual ~xsAppContext(); private: int prepare(const char *appUri); int fromStage(const char *id); int fromFile(const char *path); int fromLocal(const char *path); int fromRes(const char *name); int fromHttp(const char *url); int fromStream(xsRandomAccessStream &stream, const xsTChar *loadPath, int loadMode); private: char *_id; // application id int _loadMode; // source load mode xsTChar *_loadPath; // source directory/file load from int _loaded; // load progress, 0 - 10000, 10000 indicates complete, -1 indicates failure. xsFile _fd; // application resource file descriptor xsRes _res; // application resource handle xsHttpConnection *_conn; // application download handle, it will destroy self after done. char *_uri; // Application source URI int _index; // index in application list int _orient; // screen default orient xsTChar *_name; // application's name /// Entry function pointer define, see entry.h xsLibInitFunc _libInit; // initial of library xsLibUninitFunc _libUninit; // uninitial of library xsAppCreatorFunc _appCreator; // interface object creator of library xsAppDestroyerFunc _appDestroyer; // interface object destroyer of library xsAppInvokerFunc _appInvoker; // interface object destroyer of library void *_appObject; friend xsAppContext *xsLauncher::load(const char *appUri); }; #endif /* _XS_APPCONTEXT_H_ */
28.215909
91
0.735401
[ "object" ]
d825062df5ddcfb91e10bd64351fb2483012da5c
1,788
h
C
include/tgautils.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
include/tgautils.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
include/tgautils.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/TgaUtils/TgaUtils.h $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * * $Log$ * Revision 1.4 2002/06/09 04:41:15 relnev * added copyright header * * Revision 1.3 2002/05/26 20:22:48 theoddone33 * Most of network/ works * * Revision 1.2 2002/05/04 04:36:56 theoddone33 * More changes, took out a lot of the sound stuff which will bite later but * I don't care. * * Revision 1.1.1.1 2002/05/03 03:28:12 root * Initial import. * * * 3 3/20/99 3:46p Dave * Added support for model-based background nebulae. Added 3 new * sexpressions. * * 2 12/01/98 4:46p Dave * Put in targa bitmap support (16 bit). * * $NoKeywords: $ */ #ifndef __TARGA_H #define __TARGA_H #include "pstypes.h" // -------------------- // // Defines // // -------------------- #define TARGA_ERROR_NONE 0 #define TARGA_ERROR_READING 1 #define TARGA_ERROR_WRITING 2 // -------------------- // // Prototypes // // -------------------- int targa_read_header(char *filename, int *w, int *h, int *bpp, ubyte *palette=NULL ); int targa_read_bitmap(char *filename, ubyte *data, ubyte *palette, int dest_size ); int targa_write_bitmap(char *filename, ubyte *data, ubyte *palette, int w, int h, int bpp); // The following are used by the tools\vani code. int targa_compress(char *out, char *in, int outsize, int pixsize, int bytecount); int targa_uncompress( ubyte *dst, ubyte *src, int bitmap_width, int bytes_per_pixel ); #endif // __TARGA_H
24.493151
91
0.649888
[ "model" ]
d82700553203a8edc6fe394ac67ba4e22c5a00c8
4,252
h
C
NeoSource/NeoVM.h
hangulcode/NeoScript
fc33e8834c45a5cacbcd44a643c2673a1e9f0200
[ "MIT" ]
4
2018-08-19T12:38:29.000Z
2018-10-22T06:41:54.000Z
NeoSource/NeoVM.h
hangulcode/NeoScript
fc33e8834c45a5cacbcd44a643c2673a1e9f0200
[ "MIT" ]
null
null
null
NeoSource/NeoVM.h
hangulcode/NeoScript
fc33e8834c45a5cacbcd44a643c2673a1e9f0200
[ "MIT" ]
null
null
null
#pragma once #include "NeoVMWorker.h" class CNArchive; class CNeoVM { friend CNeoVMWorker; private: u8 * _pCodePtr; int _iCodeLen; void SetCodeData(u8* p, int sz) { _pCodePtr = p; _iCodeLen = sz; } std::vector<VarInfo> m_sVarGlobal; std::vector<SFunctionTable> m_sFunctionPtr; std::map<u32, TableInfo*> _sTables; std::map<u32, StringInfo*> _sStrings; u32 _dwLastIDTable = 0; u32 _dwLastIDString = 0; u32 _dwLastIDVMWorker = 0; SNeoVMHeader _header; std::map<std::string, int> m_sImExportTable; CNeoVMWorker* _pMainWorker; std::map<u32, CNeoVMWorker*> _sVMWorkers; int _BytesSize; inline bool IsDebugInfo() { return (_header._dwFlag & NEO_HEADER_FLAG_DEBUG) != 0; } void Var_AddRef(VarInfo *d); void Var_Release(VarInfo *d); void Var_SetString(VarInfo *d, const char* str); void Var_SetTable(VarInfo *d, TableInfo* p); CNeoVMWorker* WorkerAlloc(int iStackSize); void FreeWorker(CNeoVMWorker *d); StringInfo* StringAlloc(const char* str); void FreeString(VarInfo *d); TableInfo* TableAlloc(); void FreeTable(VarInfo *d); public: bool RunFunction(const std::string& funName); inline int GetBytesSize() { return _BytesSize; } std::string _sErrorMsgDetail; const char* _pErrorMsg = NULL; void RegLibrary(VarInfo* pSystem, const char* pLibName, SNeoFunLib* pFuns); void InitLib(); bool Init(void* pBuffer, int iSize, int iStackSize); inline void SetError(const char* pErrMsg); inline bool IsLocalErrorMsg() { return _pErrorMsg != NULL; } public: CNeoVM(); virtual ~CNeoVM(); int FindFunction(const std::string& name) { auto it = m_sImExportTable.find(name); if (it == m_sImExportTable.end()) return -1; return (*it).second; } bool SetFunction(int iFID, FunctionPtr& fun, int argCount) { fun._argCount = argCount; if (m_sFunctionPtr[iFID]._argsCount != argCount) return false; m_sFunctionPtr[iFID]._fun = fun; return true; } static FunctionPtrNative RegisterNative(Neo_NativeFunction func) { FunctionPtrNative fun; CNeoVMWorker::neo_pushcclosureNative(&fun, func); return fun; } template<typename F> static FunctionPtr Register(F func) { FunctionPtr fun; int argCount = push_functor(&fun, func); fun._argCount = argCount; return fun; } template<typename RVal, typename ... Types> bool Call(RVal* r, const std::string& funName, Types ... args) { return _pMainWorker->Call<RVal>(*r, funName, args...); } template<typename ... Types> bool CallN(const std::string& funName, Types ... args) { return _pMainWorker->CallN(funName, args...); } template<typename RVal, typename ... Types> bool Call_TL(int iTimeout, int iCheckOpCount, RVal* r, const std::string& funName, Types ... args) // Time Limit { int iFID = -1; auto it = m_sImExportTable.find(funName); if (it == m_sImExportTable.end()) return false; iFID = (*it).second; return _pMainWorker->Call_TL<RVal>(iTimeout, iCheckOpCount, r, iFID, args...); } template<typename ... Types> bool CallN_TL(int iTimeout, int iCheckOpCount, const std::string& funName, Types ... args) // Time Limit { int iFID = -1; auto it = m_sImExportTable.find(funName); if (it == m_sImExportTable.end()) return false; iFID = (*it).second; return _pMainWorker->CallN_TL(iTimeout, iCheckOpCount, iFID, args...); } u32 CreateWorker(int iStackSize = 50 * 1024); bool ReleaseWorker(u32 id); bool BindWorkerFunction(u32 id, const std::string& funName); bool IsWorking(u32 id); bool UpdateWorker(u32 id, int iTimeout = -1, int iCheckOpCount = 1000); inline const char* GetLastErrorMsg() { return _sErrorMsgDetail.c_str(); } inline bool IsLastErrorMsg() { return (_sErrorMsgDetail.empty() == false); } void ClearLastErrorMsg() { _pErrorMsg = NULL; _sErrorMsgDetail.clear(); } static CNeoVM* LoadVM(void* pBuffer, int iSize, int iStackSize = 50 * 1024); static void ReleaseVM(CNeoVM* pVM); static bool Compile(void* pBufferSrc, int iLenSrc, CNArchive& arw, std::string& err, bool putASM = false, bool debug = false, bool allowGlobalInitLogic = true); static CNeoVM* CompileAndLoadVM(void* pBufferSrc, int iLenSrc, std::string& err, bool putASM = false, bool debug = false, bool allowGlobalInitLogic = true, int iStackSize = 50 * 1024); };
26.911392
185
0.712841
[ "vector" ]
d82847ac2c5eb1361eda1ad5d74c91aa7d73c88c
3,892
c
C
student-distrib/idt.c
tonyjoo974/Linux-based-OS
e336eeea8ead8643b12084581e0414b70c0a9bb2
[ "AFL-1.1" ]
null
null
null
student-distrib/idt.c
tonyjoo974/Linux-based-OS
e336eeea8ead8643b12084581e0414b70c0a9bb2
[ "AFL-1.1" ]
null
null
null
student-distrib/idt.c
tonyjoo974/Linux-based-OS
e336eeea8ead8643b12084581e0414b70c0a9bb2
[ "AFL-1.1" ]
null
null
null
/* idt.c - Functionality for interrupt descriptor table (IDT) * vim:ts=4 noexpandtab */ #include "lib.h" #include "idt.h" #include "x86_desc.h" #include "isr.h" #include "types.h" #include "handler.h" /* Kernel Data Segment*/ #define KERNEL_SEG 0x0010 #define PIT_NUMBER 32 // PIT at 0x20 #define KEYBOARD_NUMBER 33 // Keyboard at 0x21 #define RTC_NUMBER 40 // RTC at 0x28 #define SYSCALL_NUMBER 128 // System call at 0x80 /* init_idt * Initialize interrupt descriptor table (IDT) * Inputs: none * Outputs: none * Effect: initializes IDT entries with corresponding handlers * See 5.14 of SPG for exception mappings */ void init_idt() { int i; /* set up exceptions - entries 0 to 31 */ set_idt_gate(0, (uint32_t)&exception_0x00, KERNEL_SEG); set_idt_gate(1, (uint32_t)&exception_0x01, KERNEL_SEG); set_idt_gate(2, (uint32_t)&exception_0x02, KERNEL_SEG); set_idt_gate(3, (uint32_t)&exception_0x03, KERNEL_SEG); set_idt_gate(4, (uint32_t)&exception_0x04, KERNEL_SEG); set_idt_gate(5, (uint32_t)&exception_0x05, KERNEL_SEG); set_idt_gate(6, (uint32_t)&exception_0x06, KERNEL_SEG); set_idt_gate(7, (uint32_t)&exception_0x07, KERNEL_SEG); set_idt_gate(8, (uint32_t)&exception_0x08, KERNEL_SEG); set_idt_gate(9, (uint32_t)&exception_0x09, KERNEL_SEG); set_idt_gate(10, (uint32_t)&exception_0x0A, KERNEL_SEG); set_idt_gate(11, (uint32_t)&exception_0x0B, KERNEL_SEG); set_idt_gate(12, (uint32_t)&exception_0x0C, KERNEL_SEG); set_idt_gate(13, (uint32_t)&exception_0x0D, KERNEL_SEG); set_idt_gate(14, (uint32_t)&exception_0x0E, KERNEL_SEG); set_idt_gate(15, (uint32_t)&exception_reserved, KERNEL_SEG); // 15 is skipped set_idt_gate(16, (uint32_t)&exception_0x0F, KERNEL_SEG); set_idt_gate(17, (uint32_t)&exception_0x10, KERNEL_SEG); set_idt_gate(18, (uint32_t)&exception_0x11, KERNEL_SEG); set_idt_gate(19, (uint32_t)&exception_0x12, KERNEL_SEG); /* set up rest of reserved entries to a default exception handler */ for(i = 20; i < 32; i++) { set_idt_gate(i, (uint32_t)&exception_reserved, KERNEL_SEG); } /* set up interrupts from PIC */ for(i = 32; i < 48; i++) { // pit at IRQ0 (0x20 = 32), keyboard at IRQ1 (0x21 = 33), rtc at IRQ8 (0x28 = 40) if (i == PIT_NUMBER) set_idt_gate(i, (uint32_t)&interrupt_pit, KERNEL_SEG); else if(i == KEYBOARD_NUMBER) set_idt_gate(i, (uint32_t)&interrupt_keyboard, KERNEL_SEG); else if(i == RTC_NUMBER) set_idt_gate(i, (uint32_t)&interrupt_rtc, KERNEL_SEG); else set_idt_gate(i, (uint32_t)&interrupt_handler, KERNEL_SEG); } /* set up rest of interrupts to default */ for(i = 48; i < 256; i++) { set_idt_gate(i, (uint32_t)&interrupt_handler, KERNEL_SEG); } /* set up system call (0x80 = 128) */ set_idt_gate(SYSCALL_NUMBER, (uint32_t)&system_call_handler, KERNEL_SEG); } /* set_idt_gate * Sets the idt values to the corresponding vector * Inputs: vector - entry in the IDT * handler - handler to execute for this entry * sel - segment in the kernel * Outputs: none * Effects: modifies entry "vector" in the IDT * See 0.1.2 of descriptors reference and 5.11 of SPG */ void set_idt_gate(uint8_t vector, uint32_t handler, uint16_t sel) { SET_IDT_ENTRY(idt[vector], handler); idt[vector].seg_selector = sel; idt[vector].reserved4 = 0; /* Use trap gates for system calls (reserved3 = 1), otherwise use interrupt gate */ idt[vector].reserved3 = (vector == SYSCALL_NUMBER) ? 1 : 0; idt[vector].reserved2 = 1; idt[vector].reserved1 = 1; idt[vector].size = 1; idt[vector].reserved0 = 0; /* User level for system calls (dpl = 3), otherwise supervisor level */ idt[vector].dpl = (vector == SYSCALL_NUMBER) ? 3 : 0; idt[vector].present = 1; }
37.786408
89
0.681655
[ "vector" ]
d8291e7fcf0d3a94cf4aa20c449ed369661b442d
37,189
c
C
mp_core.c
rofl0r/mp-5.x-1
54e0f7c5feaa273c9ea0f16cc869a46836b388bb
[ "Unlicense" ]
null
null
null
mp_core.c
rofl0r/mp-5.x-1
54e0f7c5feaa273c9ea0f16cc869a46836b388bb
[ "Unlicense" ]
null
null
null
mp_core.c
rofl0r/mp-5.x-1
54e0f7c5feaa273c9ea0f16cc869a46836b388bb
[ "Unlicense" ]
null
null
null
/* Minimum Profit - A Text Editor ttcdt <dev@triptico.com> et al. This software is released into the public domain. NO WARRANTY. See file LICENSE for details. */ #include "config.h" #include <stdio.h> #include <wchar.h> #include <stdlib.h> #include <string.h> #include "mpdm.h" #include "mpsl.h" #include "mp.h" /** data **/ /* exit requested? */ int mp_exit_requested = 0; /** private data for drawing syntax-highlighted text **/ struct drw_1_info { mpdm_t txt; /* the document */ mpdm_t syntax; /* syntax highlight information */ mpdm_t colors; /* color definitions (for attributes) */ mpdm_t word_color_func; /* word color function (just for detection) */ mpdm_t last_search; /* last search regex */ int normal_attr; /* normal attr */ int cursor_attr; /* cursor attr */ int n_lines; /* number of processed lines */ int p_lines; /* number of prereaded lines */ int t_lines; /* total lines in document */ int vx; /* first visible column */ int vy; /* first visible line */ int tx; /* horizontal window size */ int ty; /* vertical window size */ int tab_size; /* tabulator size */ int mod; /* modify count */ int preread_lines; /* lines to pre-read (for synhi blocks) */ int mark_eol; /* mark end of lines */ int redraw; /* redraw trigger */ int xoffset; /* # of columns reserved for line numbers */ int double_page; /* # of columns where double page activates */ wchar_t wc_tab; /* char for marking tabs */ wchar_t wc_formfeed; /* char for marking form feeds */ wchar_t wc_unknown; /* char for marking unknown characters */ wchar_t wc_wordwrap; /* char for marking word wraps */ }; struct drw_1_info drw_1; struct drw_1_info drw_1_o; static struct { int x; /* cursor x */ int y; /* cursor y */ int *offsets; /* offsets of lines */ char *attrs; /* attributes */ int visible; /* offset to the first visible character */ int cursor; /* offset to cursor */ wchar_t *ptr; /* pointer to joined data */ int size; /* size of joined data */ int matchparen_offset; /* offset to matched paren */ int matchparen_o_attr; /* original attribute there */ int cursor_o_attr; /* original attribute under cursor */ mpdm_t v; /* the data */ mpdm_t old; /* the previously generated array */ int mark_offset; /* offset to the marked block */ int mark_size; /* size of mark_o_attr */ char *mark_o_attr; /* saved attributes for the mark */ wchar_t *cmap; int *amap; int *vx2x; int *vy2y; int mx; int my; } drw_2; /** code **/ #define MP_REAL_TAB_SIZE(x) (drw_1.tab_size - ((x) % drw_1.tab_size)) static int drw_wcwidth(int x, wchar_t c) /* returns the wcwidth of c, or the tab spaces for the x column if it's a tab */ { int r; switch (c) { case L'\n': r = 1; break; case L'\t': r = MP_REAL_TAB_SIZE(x); break; default: r = 1; break; } return r < 0 ? 1 : r; } int drw_vx2x(mpdm_t str, int vx) /* returns the character in str that is on column vx */ { const wchar_t *ptr = str->data; int n, x; for (n = x = 0; n < vx && ptr[x] != L'\0'; x++) n += drw_wcwidth(n, ptr[x]); return x; } int drw_x2vx(mpdm_t str, int x) /* returns the column where the character at offset x seems to be */ { const wchar_t *ptr; int n, vx = 0; if (str) { ptr = str->data; for (n = vx = 0; n < x && ptr[n] != L'\0'; n++) vx += drw_wcwidth(vx, ptr[n]); } return vx; } static int drw_line_offset(int l) /* returns the offset into v for line number l */ { return drw_2.offsets[l - drw_1.vy + drw_1.p_lines]; } static int drw_adjust_y(int y, int *vy, int ty) /* adjusts the visual y position */ { int t = *vy; if (*vy < 0) *vy = 0; /* is y above the first visible line? */ if (y < *vy) *vy = y; /* is y below the last visible line? */ if (y > *vy + (ty - 2)) *vy = y - (ty - 2); return t != *vy; } static int drw_adjust_x(int x, int y, int *vx, int tx, wchar_t * ptr) /* adjust the visual x position */ { int n, m; int t = *vx; /* calculate the column for the cursor position */ for (n = m = 0; n < x; n++, ptr++) m += drw_wcwidth(m, *ptr); /* if new cursor column is nearer the leftmost column, set */ if (m < *vx) *vx = m; /* if new cursor column is further the rightmost column, set */ if (m > *vx + (tx - 1)) *vx = m - (tx - 1); return t != *vx; } static int drw_get_attr(wchar_t * color_name) /* returns the attribute number for a color */ { mpdm_t v; int attr = 0; if ((v = mpdm_get_wcs(drw_1.colors, color_name)) != NULL) attr = mpdm_ival(mpdm_get_wcs(v, L"attr")); return attr; } static int drw_prepare(mpdm_t doc) /* prepares the document for screen drawing */ { mpdm_t window = mpdm_ref(mpdm_get_wcs(MP, L"window")); mpdm_t config = mpdm_ref(mpdm_get_wcs(MP, L"config")); mpdm_t txt = mpdm_ref(mpdm_get_wcs(doc, L"txt")); mpdm_t lines = mpdm_ref(mpdm_get_wcs(txt, L"lines")); int x = mpdm_ival(mpdm_get_wcs(txt, L"x")); int y = mpdm_ival(mpdm_get_wcs(txt, L"y")); int n; mpdm_t v; wchar_t *ptr; int ret = 1; mpdm_store(&drw_1.txt, txt); mpdm_store(&drw_1.syntax, mpdm_get_wcs(doc, L"syntax")); mpdm_store(&drw_1.colors, mpdm_get_wcs(MP, L"colors")); mpdm_store(&drw_1.word_color_func, mpdm_get_wcs(MP, L"word_color_func")); mpdm_store(&drw_1.last_search, mpdm_get_wcs(MP, L"last_search")); drw_1.vx = mpdm_ival(mpdm_get_wcs(txt, L"vx")); drw_1.vy = mpdm_ival(mpdm_get_wcs(txt, L"vy")); drw_1.tx = mpdm_ival(mpdm_get_wcs(window, L"tx")); drw_1.ty = mpdm_ival(mpdm_get_wcs(window, L"ty")); drw_1.tab_size = mpdm_ival(mpdm_get_wcs(config, L"tab_size")); drw_1.mod = mpdm_ival(mpdm_get_wcs(txt, L"mod")); drw_1.mark_eol = mpdm_ival(mpdm_get_wcs(config, L"mark_eol")); drw_1.t_lines = mpdm_size(lines); /* get preread_lines from the syntax definition */ drw_1.preread_lines = mpdm_ival(mpdm_get_wcs(drw_1.syntax, L"preread_lines")); /* if it's 0, get it from the configuration */ if (drw_1.preread_lines == 0) drw_1.preread_lines = mpdm_ival(mpdm_get_wcs(config, L"preread_lines")); n = mpdm_ival(mpdm_get_wcs(config, L"double_page")); if (n && drw_1.tx > n) { /* if the usable screen is wider than the double page setting, activate it */ drw_1.tx /= 2; drw_1.ty *= 2; drw_1.double_page = 1; } else drw_1.double_page = 0; /* adjust the visual y coordinate */ if (drw_adjust_y(y, &drw_1.vy, drw_1.ty)) mpdm_set_wcs(txt, MPDM_I(drw_1.vy), L"vy"); /* adjust the visual x coordinate */ if (drw_adjust_x(x, y, &drw_1.vx, drw_1.tx, mpdm_string(mpdm_get_i(lines, y)))) mpdm_set_wcs(txt, MPDM_I(drw_1.vx), L"vx"); /* get the maximum prereadable lines */ drw_1.p_lines = drw_1.vy > drw_1.preread_lines ? drw_1.preread_lines : drw_1.vy; /* maximum lines */ drw_1.n_lines = drw_1.ty + drw_1.p_lines; /* get the most used attributes */ drw_1.normal_attr = drw_get_attr(L"normal"); drw_1.cursor_attr = drw_get_attr(L"cursor"); drw_2.x = x; drw_2.y = y; /* redraw trigger */ drw_1.redraw = mpdm_ival(mpdm_get_wcs(MP, L"redraw_counter")); /* calculate number of lines reserved for line numbers */ n = mpdm_ival(mpdm_get_wcs(config, L"show_line_numbers")); if (n) { char tmp[32]; sprintf(tmp, " %d ", (int) mpdm_size(lines)); drw_1.xoffset = strlen(tmp); } else drw_1.xoffset = 0; mpdm_set_wcs(MP, MPDM_I(drw_1.xoffset), L"xoffset"); /* placeholder Unicode characters */ n = mpdm_ival(mpdm_get_wcs(config, L"use_unicode")); v = mpdm_get_i(mpdm_get_wcs(MP, L"unicode_tbl"), n); if ((ptr = mpdm_string(mpdm_get_wcs(v, L"tab"))) != NULL) drw_1.wc_tab = *ptr; if ((ptr = mpdm_string(mpdm_get_wcs(v, L"formfeed"))) != NULL) drw_1.wc_formfeed = *ptr; if ((ptr = mpdm_string(mpdm_get_wcs(v, L"wordwrap"))) != NULL) drw_1.wc_wordwrap = *ptr; if ((ptr = mpdm_string(mpdm_get_wcs(v, L"unknown"))) != NULL) drw_1.wc_unknown = *ptr; /* compare drw_1 with drw_1_o; if they are the same, no more expensive calculations on drw_2 are needed */ if (memcmp(&drw_1, &drw_1_o, sizeof(drw_1)) != 0) { /* different; store now */ memcpy(&drw_1_o, &drw_1, sizeof(drw_1_o)); /* alloc space for line offsets */ drw_2.offsets = realloc(drw_2.offsets, drw_1.n_lines * sizeof(int)); drw_2.ptr = NULL; drw_2.size = 0; /* add first line */ drw_2.ptr = mpdm_pokev(drw_2.ptr, &drw_2.size, mpdm_get_i(lines, drw_1.vy - drw_1.p_lines)); /* first line start at 0 */ drw_2.offsets[0] = 0; /* add the following lines and store their offsets */ for (n = 1; n < drw_1.n_lines; n++) { /* add the separator */ drw_2.ptr = mpdm_pokews(drw_2.ptr, &drw_2.size, L"\n"); /* this line starts here */ drw_2.offsets[n] = drw_2.size; /* now add it */ drw_2.ptr = mpdm_pokev(drw_2.ptr, &drw_2.size, mpdm_get_i(lines, n + drw_1.vy - drw_1.p_lines)); } drw_2.ptr = mpdm_poke(drw_2.ptr, &drw_2.size, L"", 1, sizeof(wchar_t)); drw_2.size--; /* now create a value */ mpdm_store(&drw_2.v, MPDM_ENS(drw_2.ptr, drw_2.size)); /* alloc and init space for the attributes */ drw_2.attrs = realloc(drw_2.attrs, drw_2.size + 1); memset(drw_2.attrs, drw_1.normal_attr, drw_2.size + 1); drw_2.visible = drw_line_offset(drw_1.vy); /* (re)create the maps */ n = (drw_1.tx + 1) * drw_1.ty; drw_2.cmap = realloc(drw_2.cmap, n * sizeof(wchar_t)); drw_2.amap = realloc(drw_2.amap, n * sizeof(int)); drw_2.vx2x = realloc(drw_2.vx2x, n * sizeof(int)); drw_2.vy2y = realloc(drw_2.vy2y, n * sizeof(int)); drw_2.mx = drw_2.my = -1; } else /* drw_1 didn't change */ ret = 0; mpdm_unref(lines); mpdm_unref(txt); mpdm_unref(config); mpdm_unref(window); return ret; } static int drw_fill_attr(int attr, int offset, int size) /* fill an attribute */ { if (attr != -1) memset(drw_2.attrs + offset, attr, size); return offset + size; } static int drw_fill_attr_regex(int attr) /* fills with an attribute the last regex match */ { return drw_fill_attr(attr, mpdm_regex_offset, mpdm_regex_size); } static void drw_words(void) /* fills the attributes for separate words */ { mpdm_t word_color = NULL; /* take the hash of word colors, if any */ if ((word_color = mpdm_ref(mpdm_get_wcs(MP, L"word_color"))) != NULL) { mpdm_t r; /* get the regex for words */ if ((r = mpdm_ref(mpdm_get_wcs(MP, L"word_regex"))) != NULL) { mpdm_t func, t; int o = drw_2.visible; /* get the word color function */ func = mpdm_ref(mpdm_get_wcs(MP, L"word_color_func")); while ((t = mpdm_ref(mpdm_regex(drw_2.v, r, o))) != NULL) { int attr = -1; mpdm_t v; if ((v = mpdm_get(word_color, t)) != NULL) attr = mpdm_ival(v); else if (func != NULL) attr = mpdm_ival(mpdm_exec_1(func, t, NULL)); o = drw_fill_attr_regex(attr); mpdm_unref(t); } mpdm_unref(func); mpdm_unref(r); } mpdm_unref(word_color); } } static void drw_multiline_regex(mpdm_t a, int attr) /* sets the attribute to all matching (possibly multiline) regexes */ { int n; mpdm_ref(a); for (n = 0; n < mpdm_size(a); n++) { mpdm_t r = mpdm_get_i(a, n); int o = 0; /* if the regex is an array, it's a pair of 'match from this' / 'match until this' */ if (mpdm_type(r) == MPDM_TYPE_ARRAY) { mpdm_t rs = mpdm_get_i(r, 0); mpdm_t re = mpdm_get_i(r, 1); while (!mpdm_is_null(mpdm_regex(drw_2.v, rs, o))) { int s; /* fill the matched part */ o = drw_fill_attr_regex(attr); /* try to match the end */ if (!mpdm_is_null(mpdm_regex(drw_2.v, re, o))) { /* found; fill the attribute to the end of the match */ s = mpdm_regex_size + (mpdm_regex_offset - o); } else { /* not found; fill to the end of the document */ s = drw_2.size - o; } /* fill to there */ o = drw_fill_attr(attr, o, s); } } else { /* must be a scalar */ if (*mpdm_string(r) == L'%') { /* it's a sscanf() expression */ mpdm_t v; while ((v = mpdm_ref(mpdm_sscanf(drw_2.v, r, o))) && mpdm_size(v) == 2) { int i = mpdm_ival(mpdm_get_i(v, 0)); int s = mpdm_ival(mpdm_get_i(v, 1)) - i; o = drw_fill_attr(attr, i, s); mpdm_unref(v); } } else { /* it's a regex */ /* while the regex matches, fill attributes */ while (!mpdm_is_null(mpdm_regex(drw_2.v, r, o)) && mpdm_regex_size) o = drw_fill_attr_regex(attr); } } } mpdm_unref(a); } static void drw_blocks(void) /* fill attributes for multiline blocks */ { mpdm_t defs; if (drw_1.syntax && (defs = mpdm_get_wcs(drw_1.syntax, L"defs"))) { int n; for (n = 0; n < mpdm_size(defs); n += 2) { mpdm_t attr; mpdm_t list; /* get the attribute */ attr = mpdm_get_i(defs, n); attr = mpdm_get(drw_1.colors, attr); attr = mpdm_get_wcs(attr, L"attr"); /* get the list for this word color */ list = mpdm_get_i(defs, n + 1); drw_multiline_regex(list, mpdm_ival(attr)); } } } static void drw_selection(void) /* draws the selected block, if any */ { mpdm_t mark; int bx, by, ex, ey, vertical; int so, eo; int mby, mey; int line_offset, next_line_offset; int y; int len; int attr; /* no mark? return */ if ((mark = mpdm_get_wcs(drw_1.txt, L"mark")) == NULL) return; bx = mpdm_ival(mpdm_get_wcs(mark, L"bx")); by = mpdm_ival(mpdm_get_wcs(mark, L"by")); ex = mpdm_ival(mpdm_get_wcs(mark, L"ex")); ey = mpdm_ival(mpdm_get_wcs(mark, L"ey")); vertical = mpdm_ival(mpdm_get_wcs(mark, L"vertical")); /* if block is not visible, return */ if (ey < drw_1.vy || by >= drw_1.vy + drw_1.ty) return; so = by < drw_1.vy ? drw_2.visible : drw_line_offset(by) + bx; eo = ey >= drw_1.vy + drw_1.ty ? drw_2.size : drw_line_offset(ey) + ex; /* alloc space and save the attributes being destroyed */ drw_2.mark_offset = so; drw_2.mark_size = eo - so + 1; drw_2.mark_o_attr = malloc(eo - so + 1); memcpy(drw_2.mark_o_attr, &drw_2.attrs[so], eo - so + 1); if (vertical == 0) { /* normal selection */ drw_fill_attr(drw_get_attr(L"selection"), so, eo - so); } else { /* vertical selection */ mby = by < drw_1.vy ? drw_1.vy : by; mey = ey >= drw_1.vy + drw_1.ty ? drw_1.vy + drw_1.ty : ey; line_offset = drw_line_offset(mby); attr = drw_get_attr(L"selection"); for (y = mby; y <= mey; y++) { next_line_offset = drw_line_offset(y + 1); len = next_line_offset - line_offset - 1; so = bx > len ? -1 : bx; eo = ex > len ? len : ex; if (so >= 0 && eo >= so) drw_fill_attr(attr, line_offset + so, eo - so + 1); line_offset = next_line_offset; } } } static void drw_search_hit(void) /* colorize the search hit, if any */ { if (drw_1.last_search != NULL) { mpdm_t l = MPDM_A(0); mpdm_set_i(l, drw_1.last_search, 0); drw_multiline_regex(l, drw_get_attr(L"search")); } } static void drw_cursor(void) /* fill the attribute for the cursor */ { /* calculate the cursor offset */ drw_2.cursor = drw_line_offset(drw_2.y) + drw_2.x; drw_2.cursor_o_attr = drw_2.attrs[drw_2.cursor]; drw_fill_attr(drw_1.cursor_attr, drw_2.cursor, 1); } static void drw_matching_paren(void) /* highlights the matching paren */ { int o = drw_2.cursor; int i = 0; wchar_t c; /* by default, no offset has been found */ drw_2.matchparen_offset = -1; /* find the opposite and the increment (direction) */ switch (drw_2.ptr[o]) { case L'(': c = L')'; i = 1; break; case L'{': c = L'}'; i = 1; break; case L'[': c = L']'; i = 1; break; case L')': c = L'('; i = -1; break; case L'}': c = L'{'; i = -1; break; case L']': c = L'['; i = -1; break; } /* if a direction is set, do the searching */ if (i) { wchar_t s = drw_2.ptr[o]; int m = 0; int l = i == -1 ? drw_2.visible - 1 : drw_2.size; while (o != l) { if (drw_2.ptr[o] == s) { /* found the same */ m++; } else if (drw_2.ptr[o] == c) { /* found the opposite */ if (--m == 0) { /* found! fill and exit */ drw_2.matchparen_offset = o; drw_2.matchparen_o_attr = drw_2.attrs[o]; drw_fill_attr(drw_get_attr(L"matching"), o, 1); break; } } o += i; } } } static mpdm_t drw_push_pair(mpdm_t l, int i, int a, wchar_t * tmp) /* pushes a pair of attribute / string into l */ { /* create the array, if doesn't exist yet */ if (l == NULL) l = MPDM_A(0); /* finish the string */ tmp[i] = L'\0'; /* special magic: if the attribute is the one of the cursor and the string is more than one character, create two strings; the cursor is over a tab */ if (a == drw_1.cursor_attr && i > 1) { mpdm_push(l, MPDM_I(a)); mpdm_push(l, MPDM_NS(tmp, 1)); /* the rest of the string has the original attr */ a = drw_2.cursor_o_attr; /* one char less */ tmp[i - 1] = L'\0'; } /* store the attribute and the string */ mpdm_push(l, MPDM_I(a)); mpdm_push(l, MPDM_S(tmp)); return l; } static wchar_t drw_char(wchar_t c, wchar_t pc, int n) /* does possible conversions to the char about to be printed */ { /* real tab */ if (n == 0 && c == L'\t') c = drw_1.wc_tab; /* soft hyphen */ if (c == L'\xad') c = drw_1.wc_wordwrap; /* cedilla */ if (drw_1.mark_eol) { if (c == L'\t') c = L'\xb7'; /* middledot */ else if (c == L'\n' || c == L'\0') { if (pc != L'\xad') c = L'\xb6'; /* pilcrow */ else c = L' '; } } else { if (c == L'\t' || c == L'\n' || c == L'\0') c = L' '; } /* replace form feed with visual representation and the rest of control codes with the Unicode replace char */ if (c == L'\f') c = drw_1.wc_formfeed; else if (c < L' ') c = drw_1.wc_unknown; return c; } static void drw_map_1(int mx, int my, wchar_t c, int a, int x, int y) { int o = mx + my * (drw_1.tx + 1); drw_2.cmap[o] = c; drw_2.amap[o] = a; drw_2.vx2x[o] = x; drw_2.vy2y[o] = y; if (a == drw_1.cursor_attr) { drw_2.mx = mx; drw_2.my = my; } } static void vpos2pos(int mx, int my, int *x, int *y) { if (my < 0) { /* above top margin: pick previous line */ *x = mx; *y = drw_1.vy - 2; } else if (my > drw_1.ty - 1) { /* below bottom margin: pick next line */ *x = mx; *y = drw_1.vy + drw_1.ty; } else { /* in range: pick from the map */ int o = mx + my * (drw_1.tx + 1); *x = drw_2.vx2x[o]; *y = drw_2.vy2y[o]; } } static void drw_remap_truncate(void) { int i = drw_2.offsets[drw_1.p_lines]; int mx, my; int x, y; x = 0; y = drw_1.vy; for (my = 0; my < drw_1.ty; my++) { wchar_t c, pc = 0; int ax = 0; mx = 0; do { c = drw_2.ptr[i]; int t = drw_wcwidth(mx, c); int n; if (c == '\0') break; for (n = 0; n < t && mx < drw_1.tx; n++) { if (ax >= drw_1.vx) drw_map_1(mx++, my, drw_char(c, pc, n), drw_2.attrs[i], x, y); ax++; } i++; if (c == '\n') break; x++; pc = c; } while (mx < drw_1.tx); while (mx < drw_1.tx) drw_map_1(mx++, my, '.', -1, x, y); while (c != '\n' && c != '\0') c = drw_2.ptr[i++]; if (c == '\n') { x = 0; y++; } } } static void drw_double_page(void) /* recompose a double page char-mapped buffer */ { if (drw_1.double_page) { int n, m; wchar_t *dp_cmap = drw_2.cmap; int *dp_amap = drw_2.amap; int *dp_vx2x = drw_2.vx2x; int *dp_vy2y = drw_2.vy2y; int o = 0; n = (drw_1.tx + 1) * drw_1.ty; drw_2.cmap = calloc(n, sizeof(wchar_t)); drw_2.amap = calloc(n, sizeof(int)); drw_2.vx2x = calloc(n, sizeof(int)); drw_2.vy2y = calloc(n, sizeof(int)); for (n = 0; n < drw_1.ty / 2; n++) { int i; /* copy first column */ i = n * (drw_1.tx + 1); for (m = 0; m < drw_1.tx && dp_amap[i] != -1; m++) { drw_2.amap[o] = dp_amap[i]; drw_2.cmap[o] = dp_cmap[i]; drw_2.vx2x[o] = dp_vx2x[i]; drw_2.vy2y[o] = dp_vy2y[i]; i++; o++; } /* fill up to next column with spaces */ for (; m < drw_1.tx; m++) { drw_2.amap[o] = drw_1.normal_attr; drw_2.cmap[o] = L' '; drw_2.vx2x[o] = dp_vx2x[i]; drw_2.vy2y[o] = dp_vy2y[i]; o++; } /* put the column separator */ drw_2.amap[o] = drw_1.normal_attr; drw_2.cmap[o] = L'\x2502'; o++; /* copy the second column */ i = (n - 1 + drw_1.ty / 2) * (drw_1.tx + 1); for (m = 0; m < drw_1.tx; m++) { drw_2.amap[o] = dp_amap[i]; drw_2.cmap[o] = dp_cmap[i]; drw_2.vx2x[o] = dp_vx2x[i]; drw_2.vy2y[o] = dp_vy2y[i]; i++; o++; } } /* restore size */ drw_1.tx *= 2; drw_1.ty /= 2; free(dp_cmap); free(dp_amap); } } static mpdm_t drw_remap_to_array(void) /* converts the char-mapped buffer to arrays of attr, string per line */ { mpdm_t r = MPDM_A(0); wchar_t *line = malloc((drw_1.tx + 1) * sizeof(wchar_t)); int my; mpdm_t fmt = NULL; if (drw_1.xoffset) { fmt = mpdm_ref(mpdm_strcat(MPDM_S(L" %"), mpdm_strcat_wcs(MPDM_I(drw_1.xoffset - 2), L"d "))); } for (my = 0; my < drw_1.ty; my++) { mpdm_t l = MPDM_A(0); int o = my * (drw_1.tx + 1); int mx = 0; if (drw_1.xoffset && drw_1.vy + my < drw_1.t_lines) { mpdm_push(l, MPDM_I(drw_1.normal_attr)); mpdm_push(l, mpdm_fmt(fmt, MPDM_I(drw_1.vy + 1 + my))); } while (mx < drw_1.tx && drw_2.amap[o] != -1) { int i = 0; int a = drw_2.amap[o]; while (a == drw_2.amap[o] && mx++ < drw_1.tx) line[i++] = drw_2.cmap[o++]; line[i] = L'\0'; l = drw_push_pair(l, i, a, line); } mpdm_push(r, l); } free(line); mpdm_unref(fmt); return r; } static mpdm_t drw_optimize_array(mpdm_t a, int optimize) /* optimizes the array, NULLifying all lines that are the same as the last time */ { mpdm_t o = drw_2.old; mpdm_t r = a; mpdm_ref(a); if (optimize && o != NULL) { int n = 0; /* creates a copy */ r = mpdm_clone(a); mpdm_ref(r); /* compare each array */ while (n < mpdm_size(o) && n < mpdm_size(r)) { /* if both lines are equal, optimize out */ if (mpdm_cmp(mpdm_get_i(o, n), mpdm_get_i(r, n)) == 0) mpdm_set_i(r, NULL, n); n++; } mpdm_unrefnd(r); } mpdm_store(&drw_2.old, a); mpdm_unref(a); return r; } static void drw_restore_attrs(void) /* restored the patched attrs */ { /* matching paren, if any */ if (drw_2.matchparen_offset != -1) drw_fill_attr(drw_2.matchparen_o_attr, drw_2.matchparen_offset, 1); /* cursor */ drw_fill_attr(drw_2.cursor_o_attr, drw_2.cursor, 1); /* marked block, if any */ if (drw_2.mark_o_attr != NULL) { memcpy(&drw_2.attrs[drw_2.mark_offset], drw_2.mark_o_attr, drw_2.mark_size); free(drw_2.mark_o_attr); drw_2.mark_o_attr = NULL; } } static mpdm_t drw_draw(mpdm_t doc, int optimize) /* main document drawing function: takes a document and returns an array of arrays of attribute / string pairs */ { mpdm_t r = NULL, w; if (drw_prepare(doc)) { /* colorize separate words */ drw_words(); /* colorize multiline blocks */ drw_blocks(); } /* now set the marked block (if any) */ drw_selection(); /* colorize the search hit */ drw_search_hit(); /* the cursor */ drw_cursor(); /* highlight the matching paren */ drw_matching_paren(); /* convert to an array of string / atribute pairs */ drw_remap_truncate(); drw_double_page(); r = drw_remap_to_array(); /* optimize */ r = drw_optimize_array(r, optimize); /* restore the patched attrs */ drw_restore_attrs(); w = mpdm_get_wcs(MP, L"window"); mpdm_set_wcs(w, MPDM_I(drw_2.mx), L"mx"); mpdm_set_wcs(w, MPDM_I(drw_2.my), L"my"); return r; } /** interface **/ mpdm_t mp_draw(mpdm_t doc, int optimize) /* main generic drawing function for drivers */ { mpdm_t f, r = NULL; static mpdm_t d = NULL; if (doc != d) { optimize = 0; mpdm_store(&d, doc); } if ((f = mpdm_get_wcs(doc, L"render")) != NULL) { /* create a context to contain the object itself (i.e. call as a method) */ mpdm_t ctxt = MPDM_A(0); mpdm_push(ctxt, doc); r = mpdm_exec_2(f, doc, MPDM_I(optimize), ctxt); } return r; } #define THR_SPEED_STEP 10 #define THR_MAX_SPEED 7 int mp_keypress_throttle(int keydown) /* processes key acceleration and throttle */ { #ifdef USE_THROTTLE static int keydowns = 0; static int seq = 0; int redraw = 0; if (keydown) { int speed; /* as keydowns accumulate, speed increases, which is the number of cycles the redraw will be skipped (up to a maximum) */ if ((speed = 1 + (++keydowns / THR_SPEED_STEP)) > THR_MAX_SPEED) speed = THR_MAX_SPEED; if (++seq % speed == 0) redraw = 1; } else { if (keydowns > 1) redraw = 1; keydowns = 0; } return redraw; #else /* USE_THROTTLE */ return 1; #endif /* USE_THROTTLE */ } mpdm_t mp_active(void) /* interface to mp.active() */ { return mpdm_exec(mpdm_get_wcs(MP, L"active"), NULL, NULL); } void mp_process_action(mpdm_t action) /* interface to mp.process_action() */ { mpdm_void(mpdm_exec_1(mpdm_get_wcs(MP, L"process_action"), action, NULL)); } void mp_process_event(mpdm_t keycode) /* interface to mp.process_event() */ { mpdm_void(mpdm_exec_1(mpdm_get_wcs(MP, L"process_event"), keycode, NULL)); } void mp_set_y(mpdm_t doc, int y) /* interface to mp.set_y() */ { mpdm_void(mpdm_exec_2(mpdm_get_wcs(doc, L"set_y"), doc, MPDM_I(y), NULL)); } mpdm_t mp_build_status_line(void) /* interface to mp.build_status_line() */ { return mpdm_exec(mpdm_get_wcs(MP, L"build_status_line"), NULL, NULL); } mpdm_t mp_get_history(mpdm_t key) /* interface to mp.get_history() */ { return mpdm_exec_1(mpdm_get_wcs(MP, L"get_history"), key, NULL); } mpdm_t mp_get_doc_names(void) /* interface to mp.get_doc_names() */ { return mpdm_exec(mpdm_get_wcs(MP, L"get_doc_names"), NULL, NULL); } mpdm_t mp_menu_label(mpdm_t action) /* interface to mp.menu_label() */ { return mpdm_exec_1(mpdm_get_wcs(MP, L"menu_label"), action, NULL); } mpdm_t mp_c_exit(mpdm_t args, mpdm_t ctxt) /* exit the editor (set mp_exit_requested) */ { mp_exit_requested = 1; return NULL; } static mpdm_t mp_c_exit_requested(mpdm_t args, mpdm_t ctxt) /* returns the value of the mp_exit_requested variable */ { return MPDM_I(mp_exit_requested); } mpdm_t mp_c_render(mpdm_t args, mpdm_t ctxt) { return drw_draw(mpdm_get_i(args, 0), mpdm_ival(mpdm_get_i(args, 1))); } mpdm_t mp_c_vx2x(mpdm_t args, mpdm_t ctxt) /* interface to drw_vx2x() */ { return MPDM_I(drw_vx2x(mpdm_get_i(args, 0), mpdm_ival(mpdm_get_i(args, 1)))); } mpdm_t mp_c_x2vx(mpdm_t args, mpdm_t ctxt) /* interface to drw_x2vx() */ { return MPDM_I(drw_x2vx(mpdm_get_i(args, 0), mpdm_ival(mpdm_get_i(args, 1)))); } mpdm_t mp_c_vpos2pos(mpdm_t args, mpdm_t ctxt) { mpdm_t r = MPDM_A(2); int x = mpdm_ival(mpdm_get_i(args, 0)); int y = mpdm_ival(mpdm_get_i(args, 1)); vpos2pos(x, y, &x, &y); mpdm_set_i(r, MPDM_I(x), 0); mpdm_set_i(r, MPDM_I(y), 1); return r; } mpdm_t mp_c_search_hex(mpdm_t args, mpdm_t ctxt) /* search the hex string str in the file */ { mpdm_t fd = mpdm_get_i(args, 0); mpdm_t str = mpdm_get_i(args, 1); FILE *f = mpdm_get_filehandle(fd); wchar_t *s = mpdm_string(str); int n = 0; unsigned char *ptr; off_t o; int found = 0; /* parse str into a binary buffer */ ptr = malloc(wcslen(s) + 1); while (s[0] && s[1]) { char tmp[3]; int c; tmp[0] = (char)s[0]; tmp[1] = (char)s[1]; sscanf(tmp, "%02x", &c); ptr[n++] = (unsigned char) c; s += 2; } ptr[n] = 0; /* start searching */ o = ftell(f); while (!found && !feof(f)) { int c; fseek(f, o, 0); n = 0; while (!found && (c = fgetc(f)) != EOF) { if (c == ptr[n]) { n++; if (ptr[n] == '\0') found = 1; } else { o++; break; } } } if (found) fseek(f, o, 0); free(ptr); return MPDM_I(found); } mpdm_t mp_c_get_offset(mpdm_t args, mpdm_t ctxt) /* gets the character offset at lines[y][0] */ { mpdm_t lines = mpdm_get_i(args, 0); int y = mpdm_ival(mpdm_get_i(args, 1)); int n, o = 0; for (n = 0; n < y; n++) { mpdm_t v = mpdm_get_i(lines, n); wchar_t *ptr = mpdm_string(v); int z = wcslen(ptr); /* count 1 less if it ends in soft-hyphen, 1 more if not */ z += (z && ptr[z - 1] == 0xad) ? -1 : 1; o += z; } return MPDM_I(o); } mpdm_t mp_c_set_offset(mpdm_t args, mpdm_t ctxt) /* gets the x, y position of offset */ { mpdm_t lines = mpdm_get_i(args, 0); int o = mpdm_ival(mpdm_get_i(args, 1)); int n, y = 0; mpdm_t r; for (n = 0; n < mpdm_size(lines); n++) { mpdm_t v = mpdm_get_i(lines, n); wchar_t *ptr = mpdm_string(v); int z = wcslen(ptr); /* count 1 less if it ends in soft-hyphen, 1 more if not */ z += (z && ptr[z - 1] == 0xad) ? -1 : 1; if (o <= z) break; o -= z; y++; } r = MPDM_A(2); mpdm_set_i(r, MPDM_I(o), 0); mpdm_set_i(r, MPDM_I(y), 1); return r; } static mpdm_t find_in_embedded_arch(mpdm_t args, mpdm_t ctxt) /* searches for embedded MPSL code */ { return mpdm_read_arch_mem_s(mpdm_get_i(args, 0), ARCH_START, ARCH_END); } mpdm_t ni_drv_startup(mpdm_t v) { return NULL; } int ni_drv_detect(int *argc, char ***argv) { int n, ret = 0; for (n = 0; n < *argc; n++) { if (strcmp(argv[0][n], "-ni") == 0 || strcmp(argv[0][n], "-F") == 0) ret = 1; } if (ret) { mpdm_t drv; drv = mpdm_set_wcs(mpdm_root(), MPDM_O(), L"mp_drv"); mpdm_set_wcs(drv, MPDM_S(L"ni"), L"id"); mpdm_set_wcs(drv, MPDM_X(ni_drv_startup), L"startup"); } return ret; } void mp_startup(int argc, char *argv[]) { mpdm_t INC; char *ptr; mpdm_t mp_c; mpdm_startup(); mpdm_set_wcs(mpdm_root(), MPDM_MBS(CONFOPT_APPNAME), L"APPID"); mpsl_startup(); /* reset the structures */ memset(&drw_1, '\0', sizeof(drw_1)); memset(&drw_1_o, '\0', sizeof(drw_1_o)); /* set an initial value for drw_1.tab_size: drw_wcwidth() may be called before drw_1 being filled by drw_prepare() (when opening files from the command line and mp.config.visual_wrap == 1) */ drw_1.tab_size = 1; /* new mp_c namespace (C interface) */ mp_c = mpdm_set_wcs(mpdm_root(), MPDM_O(), L"mp_c"); /* version */ mpdm_set_wcs(mp_c, MPDM_S(L"" VERSION), L"VERSION"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_x2vx), L"x2vx"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_vx2x), L"vx2x"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_vpos2pos), L"vpos2pos"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_exit), L"exit"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_exit_requested), L"exit_requested"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_render), L"render"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_search_hex), L"search_hex"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_get_offset), L"get_offset"); mpdm_set_wcs(mp_c, MPDM_X(mp_c_set_offset), L"set_offset"); /* creates the INC (executable path) array */ INC = mpdm_set_wcs(mpdm_root(), MPDM_A(0), L"INC"); /* if the MP_LIBRARY_PATH environment variable is set, put it before anything else */ if ((ptr = getenv("MP_LIBRARY_PATH")) != NULL) mpdm_push(INC, MPDM_MBS(ptr)); /* add code library as embedded archive */ mpdm_push(INC, MPDM_X(find_in_embedded_arch)); /* add code library as externally installed zip */ mpdm_push(INC, mpdm_strcat_wcs( mpdm_get_wcs(mpdm_root(), L"APPDIR"), L"/mp.zip")); /* add code library as externally installed tar */ mpdm_push(INC, mpdm_strcat_wcs( mpdm_get_wcs(mpdm_root(), L"APPDIR"), L"/mp.tar")); if (!ni_drv_detect(&argc, &argv) && !TRY_DRIVERS()) { printf("No usable driver found; exiting.\n"); exit(1); } mpsl_argv(argc, argv); } void mp_mpsl(void) { mpdm_t e; mpdm_void(mpsl_eval(MPDM_S(L"load('mp_core.mpsl');"), NULL, NULL)); if ((e = mpdm_get_wcs(mpdm_root(), L"ERROR")) != NULL) { mpdm_write_wcs(stdout, mpdm_string(e)); printf("\n"); } } void mp_shutdown(void) { /* unref pending values */ mpdm_unref(drw_1.txt); mpdm_unref(drw_2.v); mpdm_unref(drw_2.old); #ifdef DEBUG_CLEANUP mpdm_unref(mpdm_root()); #endif mpsl_shutdown(); } int main(int argc, char *argv[]) { mp_startup(argc, argv); mp_mpsl(); mp_shutdown(); return 0; }
25.195799
84
0.533088
[ "render", "object" ]
d829eabc7f7213e3fa181420057070fe756c16b5
1,980
h
C
System/Library/PrivateFrameworks/AppSupportUI.framework/NUIBoxArrangement.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
4
2019-08-27T18:03:47.000Z
2021-09-18T06:29:00.000Z
System/Library/PrivateFrameworks/AppSupportUI.framework/NUIBoxArrangement.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/AppSupportUI.framework/NUIBoxArrangement.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Saturday, August 24, 2019 at 9:47:27 PM Mountain Standard Time * Operating System: Version 12.4 (Build 16M568) * Image Source: /System/Library/PrivateFrameworks/AppSupportUI.framework/AppSupportUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <AppSupportUI/AppSupportUI-Structs.h> #import <libobjc.A.dylib/_NUIBoxArrangementContainer.h> @protocol NUIArrangementContainer, NUIBoxArrangementDataSource; @class NSString; @interface NUIBoxArrangement : NSObject <_NUIBoxArrangementContainer> { NUIBoxArrangement* _arrangement; id<NUIArrangementContainer> _container; id<NUIBoxArrangementDataSource> _dataSource; struct { unsigned containerDirection : 1; } _flags; double _scale; CGRect _bounds; } @property (nonatomic,__weak,readonly) id<NUIArrangementContainer> container; @property (nonatomic,__weak,readonly) id<NUIBoxArrangementDataSource> dataSource; @property (assign,getter=isBaselineRelativeArrangement,nonatomic) BOOL baselineRelativeArrangement; @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(CGRect)layoutFrameForArrangedSubview:(id)arg1 withProposedContentFrame:(CGRect)arg2 ; -(CGSize)contentLayoutSizeFittingSize:(CGSize)arg1 forArrangedSubview:(id)arg2 ; -(void)_cacheDisplayScaleIfNeeded; -(void)populateBoxArrangementCells:(vector<_NUIBoxArrangementCell, std::__1::allocator<_NUIBoxArrangementCell> >*)arg1 ; -(id)initWithContainer:(id)arg1 dataSource:(id)arg2 ; -(CGSize)layoutSizeFittingSize:(CGSize)arg1 ; -(void)positionItemsInBounds:(CGRect)arg1 block:(/*^block*/id)arg2 ; -(void)dealloc; -(void)reloadData; -(id<NUIArrangementContainer>)container; -(id<NUIBoxArrangementDataSource>)dataSource; -(void)setBaselineRelativeArrangement:(BOOL)arg1 ; -(BOOL)isBaselineRelativeArrangement; @end
39.6
120
0.808081
[ "vector" ]
d83478e66e7e203ca51047cc8ac090df92afe7d1
2,598
c
C
src/lib/wkpf/c/posix.mraa.galileo/native_wuclasses/wuclass_ir_sensor_update.c
wukong-m2m/wukong-darjeeling
429ffdd62384c0a6b7f6695bb780359fc58a804c
[ "BSD-2-Clause-FreeBSD" ]
16
2015-01-07T10:32:47.000Z
2019-01-16T16:13:51.000Z
src/lib/wkpf/c/posix.mraa.galileo/native_wuclasses/wuclass_ir_sensor_update.c
wukong-m2m/wukong-darjeeling
429ffdd62384c0a6b7f6695bb780359fc58a804c
[ "BSD-2-Clause-FreeBSD" ]
14
2015-05-01T04:45:45.000Z
2016-05-11T01:29:23.000Z
src/lib/wkpf/c/posix.mraa.galileo/native_wuclasses/wuclass_ir_sensor_update.c
wukong-m2m/wukong-darjeeling
429ffdd62384c0a6b7f6695bb780359fc58a804c
[ "BSD-2-Clause-FreeBSD" ]
13
2015-06-17T06:42:17.000Z
2020-11-27T18:23:08.000Z
#include "config.h" #if defined(INTEL_GALILEO_GEN1) || defined(INTEL_GALILEO_GEN2) || defined(INTEL_EDISON) #include "debug.h" #include "native_wuclasses.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <sys/resource.h> #include <sys/syscall.h> #include <math.h> void wuclass_ir_sensor_setup(wuobject_t *wuobject) { system("echo -n 37 > /sys/class/gpio/unexport"); system("echo -n 37 > /sys/class/gpio/export"); system("echo -n out > /sys/class/gpio/gpio37/direction"); system("echo -n 0 > /sys/class/gpio/gpio37/value"); } void wuclass_ir_sensor_update(wuobject_t *wuobject) { int16_t fd0=-1; char buf0[4] = {'\\','\\','\\','\\'}; static int16_t dis_buf_0[3] = {0,0,0}; fd0 = open("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", O_RDONLY | O_NONBLOCK); lseek(fd0, 0, SEEK_SET); read(fd0, buf0, 4); close(fd0); int16_t num0=0; int16_t ii=0; // never use atoi // num0 = atoi(buf0); for(ii=0;ii<4;ii++){ if(buf0[ii]>='0' && buf0[ii] <='9') num0 = num0*10 + (buf0[ii] - '0'); } num0 /=4; // this devision should be tuned depending on diffirent ir sensor model. // usually divided by 2 or 4 float volts0 = 10650.08 * pow(num0, -0.935); int16_t distance0 = (int16_t)(volts0 - 10); if(distance0 > 200) distance0 = 200; printf("The distance is: %d cm\n",distance0); int16_t final_dis_0=0; int16_t total_num=0; int16_t max_dis, min_dis; int16_t max_index = 0, min_index = 0; max_dis = distance0; min_dis = distance0; max_index = min_index = -1; final_dis_0 = distance0; total_num = 1; for(ii=0;ii<3;ii++){ if(dis_buf_0[ii] != 0){ final_dis_0 = final_dis_0 + dis_buf_0[ii]; total_num++; } if(dis_buf_0[ii] > max_dis){ max_dis = dis_buf_0[ii]; max_index = ii; } if(dis_buf_0[ii] < min_dis){ min_dis = dis_buf_0[ii]; min_index = ii; } if(ii != 2) dis_buf_0[ii] = dis_buf_0[ii+1]; else dis_buf_0[ii] = distance0; } if(total_num != 1 && max_index != -1){ final_dis_0 = final_dis_0 - max_dis; total_num--; } if(total_num != 1 && min_index != -1){ final_dis_0 = final_dis_0 - min_dis; total_num--; } final_dis_0 = final_dis_0/total_num; printf("The distance after smoothing is: %d cm\n",final_dis_0); wkpf_internal_write_property_int16(wuobject, WKPF_PROPERTY_IR_SENSOR_CURRENT_VALUE, final_dis_0); } #endif
27.0625
98
0.627406
[ "model" ]
d83692a65c9cd96d9e7785f02a34604ae1957d62
312
h
C
src/figline.h
cmatsuoka/piglet
be68d939104dc657a2d1052748af5e909f3be760
[ "MIT" ]
7
2018-10-31T10:43:35.000Z
2019-09-28T23:10:46.000Z
src/figline.h
cmatsuoka/piglet
be68d939104dc657a2d1052748af5e909f3be760
[ "MIT" ]
null
null
null
src/figline.h
cmatsuoka/piglet
be68d939104dc657a2d1052748af5e909f3be760
[ "MIT" ]
null
null
null
#ifndef SRC_FIGLINE_H_ #define SRC_FIGLINE_H_ #include <string> #include <vector> class FIGline : public std::vector<std::wstring> { public: FIGline(); FIGline(int); FIGline(std::initializer_list<std::wstring>); }; std::wostream& operator<<(std::wostream&, FIGline); #endif // SRC_FIGLINE_H_
16.421053
51
0.698718
[ "vector" ]
d83a3b82cc6d0d9594c9b478a293498e86a11a08
14,795
h
C
app/DiskArchive.h
markdavidlong/ciderpress
a914fa03dd2ac9241581abb4129c7ee35e27376d
[ "BSD-3-Clause" ]
84
2015-01-01T00:27:18.000Z
2022-03-28T22:55:56.000Z
app/DiskArchive.h
markdavidlong/ciderpress
a914fa03dd2ac9241581abb4129c7ee35e27376d
[ "BSD-3-Clause" ]
49
2015-01-11T19:58:57.000Z
2022-01-08T00:27:12.000Z
app/DiskArchive.h
markdavidlong/ciderpress
a914fa03dd2ac9241581abb4129c7ee35e27376d
[ "BSD-3-Clause" ]
19
2015-06-06T15:23:18.000Z
2022-01-12T23:26:43.000Z
/* * CiderPress * Copyright (C) 2007 by faddenSoft, LLC. All Rights Reserved. * See the file LICENSE for distribution terms. */ /* * Disk image "archive" support. */ #ifndef APP_DISKARCHIVE_H #define APP_DISKARCHIVE_H #include "GenericArchive.h" #include "../diskimg/DiskImg.h" class RenameEntryDialog; /* * One file in a disk image. */ class DiskEntry : public GenericEntry { public: DiskEntry(A2File* pFile) : fpFile(pFile) {} virtual ~DiskEntry(void) {} virtual int ExtractThreadToBuffer(int which, char** ppText, long* pLength, CString* pErrMsg) const override; virtual int ExtractThreadToFile(int which, FILE* outfp, ConvertEOL conv, ConvertHighASCII convHA, CString* pErrMsg) const override; virtual long GetSelectionSerial(void) const override { return -1; } // idea: T/S block number /* * Figure out whether or not we're allowed to change a file's type and * aux type. */ virtual bool GetFeatureFlag(Feature feature) const override; // return the underlying FS format for this file virtual DiskImg::FSFormat GetFSFormat(void) const { ASSERT(fpFile != NULL); return fpFile->GetFSFormat(); } A2File* GetA2File(void) const { return fpFile; } void SetA2File(A2File* pFile) { fpFile = pFile; } private: /* * Copy data from the open A2File to outfp, possibly converting EOL along * the way. */ DIError CopyData(A2FileDescr* pOpenFile, FILE* outfp, ConvertEOL conv, ConvertHighASCII convHA, CString* pMsg) const; A2File* fpFile; }; /* * Disk image add-ons to GenericArchive. */ class DiskArchive : public GenericArchive { public: DiskArchive(void) : fpPrimaryDiskFS(NULL), fIsReadOnly(false), fpAddDataHead(NULL), fpAddDataTail(NULL), fOverwriteExisting(false), fOverwriteNoAsk(false), fpXferTargetFS(NULL) {} virtual ~DiskArchive(void) { (void) Close(); } /* pass this as the "options" value to the New() function */ typedef struct { DiskImgLib::DiskImg::FSFormat format; DiskImgLib::DiskImg::SectorOrder sectorOrder; } NewOptionsBase; typedef union { NewOptionsBase base; struct { NewOptionsBase base; long numBlocks; } blank; struct { NewOptionsBase base; const WCHAR* volName; long numBlocks; } prodos; struct { NewOptionsBase base; const WCHAR* volName; long numBlocks; } pascalfs; // "pascal" is reserved token in MSVC++ struct { NewOptionsBase base; const WCHAR* volName; long numBlocks; } hfs; struct { NewOptionsBase base; int volumeNum; long numTracks; int numSectors; bool allocDOSTracks; } dos; } NewOptions; /* * Perform one-time initialization of the DiskLib library. */ static CString AppInit(void); /* * Perform one-time cleanup of DiskImgLib at shutdown time. */ static void AppCleanup(void); /* * Finish instantiating a DiskArchive object by opening an existing file. */ virtual OpenResult Open(const WCHAR* filename, bool readOnly, CString* pErrMsg) override; /* * Finish instantiating a DiskArchive object by creating a new archive. * * Returns an error string on failure, or "" on success. */ virtual CString New(const WCHAR* filename, const void* options) override; /* * Flush the DiskArchive object. * * Most of the stuff we do with disk images goes straight through, but in * the case of compressed disks we don't normally re-compress them until * it's time to close them. This forces us to update the copy on disk. * * Returns an empty string on success, or an error message on failure. */ virtual CString Flush(void) override; /* * Reload the stuff from the underlying DiskFS. * * This also does a "lite" flush of the disk data. For files that are * essentially being written as we go, this does little more than clear * the "dirty" flag. Files that need to be recompressed or have some * other slow operation remain dirty. * * We don't need to do the flush as part of the reload -- we can load the * contents with everything in a perfectly dirty state. We don't need to * do it at all. We do it to keep the "dirty" flag clear when nothing is * really dirty, and we do it here because almost all of our functions call * "reload" after making changes, which makes it convenient to call from here. */ virtual CString Reload(void) override; /* * Returns true if the archive has un-flushed modifications pending. */ virtual bool IsModified(void) const override; /* * Return an description of the disk archive, suitable for display in the * main title bar. */ virtual CString GetDescription() const override; virtual bool BulkAdd(ActionProgressDialog* pActionProgress, const AddFilesDialog* pAddOpts) override; virtual bool AddDisk(ActionProgressDialog* pActionProgress, const AddFilesDialog* pAddOpts) override { ASSERT(false); return false; } virtual bool CreateSubdir(CWnd* pMsgWnd, GenericEntry* pParentEntry, const WCHAR* newName) override; virtual bool TestSelection(CWnd* pMsgWnd, SelectionSet* pSelSet) override { ASSERT(false); return false; } virtual bool DeleteSelection(CWnd* pMsgWnd, SelectionSet* pSelSet) override; virtual bool RenameSelection(CWnd* pMsgWnd, SelectionSet* pSelSet) override; virtual CString TestPathName(const GenericEntry* pGenericEntry, const CString& basePath, const CString& newName, char newFssep) const override; virtual bool RenameVolume(CWnd* pMsgWnd, DiskFS* pDiskFS, const WCHAR* newName) override; virtual CString TestVolumeName(const DiskFS* pDiskFS, const WCHAR* newName) const override; virtual bool RecompressSelection(CWnd* pMsgWnd, SelectionSet* pSelSet, const RecompressOptionsDialog* pRecompOpts) override { ASSERT(false); return false; } virtual bool GetComment(CWnd* pMsgWnd, const GenericEntry* pEntry, CString* pStr) override { ASSERT(false); return false; } virtual bool SetComment(CWnd* pMsgWnd, GenericEntry* pEntry, const CString& str) override { ASSERT(false); return false; } virtual bool DeleteComment(CWnd* pMsgWnd, GenericEntry* pEntry) override { ASSERT(false); return false; } virtual bool SetProps(CWnd* pMsgWnd, GenericEntry* pEntry, const FileProps* pProps) override; /* * User has updated their preferences. Take note. * * Setting preferences in a DiskFS causes those prefs to be pushed down * to all sub-volumes. */ virtual void PreferencesChanged(void) override; virtual long GetCapability(Capability cap) override; virtual XferStatus XferSelection(CWnd* pMsgWnd, SelectionSet* pSelSet, ActionProgressDialog* pActionProgress, const XferFileOptions* pXferOpts) override; virtual bool IsReadOnly(void) const { return fIsReadOnly; } const DiskImg* GetDiskImg(void) const { return &fDiskImg; } DiskFS* GetDiskFS(void) const { return fpPrimaryDiskFS; } /* * Progress update callback, called from DiskImgLib during read/write * operations. * * Returns "true" if we should continue; */ static bool ProgressCallback(DiskImgLib::A2FileDescr* pFile, DiskImgLib::di_off_t max, DiskImgLib::di_off_t current, void* state); private: /* * Close the DiskArchive ojbect. */ virtual CString Close(void); virtual void XferPrepare(const XferFileOptions* pXferOpts) override; virtual CString XferFile(LocalFileDetails* pDetails, uint8_t** pDataBuf, long dataLen, uint8_t** pRsrcBuf, long rsrcLen) override; virtual void XferAbort(CWnd* pMsgWnd) override; virtual void XferFinish(CWnd* pMsgWnd) override; /* * Progress update callback, called from DiskImgLib while scanning a volume * during Open(). * * "str" must not contain a '%'. (TODO: fix that) * * Returns "true" if we should continue. */ static bool ScanProgressCallback(void* cookie, const char* str, int count); /* * Internal class used to keep track of files we're adding. */ class FileAddData { public: FileAddData(const LocalFileDetails* pDetails, char* fsNormalPathMOR) { fDetails = *pDetails; fFSNormalPathMOR = fsNormalPathMOR; fpOtherFork = NULL; fpNext = NULL; } virtual ~FileAddData(void) {} FileAddData* GetNext(void) const { return fpNext; } void SetNext(FileAddData* pNext) { fpNext = pNext; } FileAddData* GetOtherFork(void) const { return fpOtherFork; } void SetOtherFork(FileAddData* pData) { fpOtherFork = pData; } const LocalFileDetails* GetDetails(void) const { return &fDetails; } /* * Get the "FS-normal" path, i.e. exactly what we want to appear * on the disk image. This has the result of any conversions, so * we need to store it as a narrow Mac OS Roman string. */ const char* GetFSNormalPath(void) const { return fFSNormalPathMOR; } private: LocalFileDetails fDetails; // The DiskFS-normalized version of the storage name. This is the // name as it will appear on the Apple II disk image. CStringA fFSNormalPathMOR; FileAddData* fpOtherFork; FileAddData* fpNext; }; virtual ArchiveKind GetArchiveKind(void) override { return kArchiveDiskImage; } virtual NuError DoAddFile(const AddFilesDialog* pAddOpts, LocalFileDetails* pDetails) override; /* * Reload the contents of the archive, showing an error message if the * reload fails. * * Returns 0 on success, -1 on failure. */ int InternalReload(CWnd* pMsgWnd); /* * Compare DiskEntry display names in descending order (Z-A). */ static int CompareDisplayNamesDesc(const void* ventry1, const void* ventry2); /* * Load the contents of a "disk archive". Returns 0 on success. */ int LoadContents(void); /* * Load the contents of a DiskFS. * * Recursively handle sub-volumes. "volName" holds the name of the * sub-volume as it should appear in the list. */ int LoadDiskFSContents(DiskFS* pDiskFS, const WCHAR* volName); void DowncaseSubstring(CString* pStr, int startPos, int endPos, bool prevWasSpace); /* * Handle a debug message from the DiskImg library. */ static void DebugMsgHandler(const char* file, int line, const char* msg); /* * A file we're adding clashes with an existing file. Decide what to do * about it. * * Returns one of the following: * kNuOverwrite - overwrite the existing file * kNuSkip - skip adding the existing file * kNuRename - user wants to rename the file * kNuAbort - cancel out of the entire add process * * Side effects: * Sets fOverwriteExisting and fOverwriteNoAsk if a "to all" button is hit * Replaces pDetails->storageName if the user elects to rename */ NuResult HandleReplaceExisting(const A2File* pExisting, LocalFileDetails* pDetails); /* * Process the list of pending file adds. * * This is where the rubber (finally!) meets the road. */ CString ProcessFileAddData(DiskFS* pDiskFS, int addOptsConvEOL); /* * Load a file into a buffer, possibly converting EOL markers and setting * "high ASCII" along the way. * * Returns a pointer to a newly-allocated buffer (new[]) and the data length. * If the file is empty, no buffer will be allocated. * * Returns an empty string on success, or an error message on failure. */ CString LoadFile(const WCHAR* pathName, DiskFS* pDiskFS, uint8_t** pBuf, long* pLen, GenericEntry::ConvertEOL conv, GenericEntry::ConvertHighASCII convHA) const; /* * Add a file with the supplied data to the disk image. * * Forks that exist but are empty have a length of zero. Forks that don't * exist have a length of -1. * * Called by XferFile and ProcessFileAddData. */ DIError AddForksToDisk(DiskFS* pDiskFS, const DiskFS::CreateParms* pParms, const uint8_t* dataBuf, long dataLen, const uint8_t* rsrcBuf, long rsrcLen) const; /* * Add an entry to the end of the FileAddData list. * * If "storageName" (the Windows filename with type goodies stripped, but * without filesystem normalization) matches an entry already in the list, * we check to see if these are forks of the same file. If they are * different forks and we don't already have both forks, we put the * pointer into the "fork pointer" of the existing file rather than adding * it to the end of the list. */ void AddToAddDataList(FileAddData* pData); /* * Free all entries in the FileAddData list. */ void FreeAddDataList(void); /* * Set up a RenameEntryDialog for the entry in "*pEntry". * * Returns true on success, false on failure. */ bool SetRenameFields(CWnd* pMsgWnd, DiskEntry* pEntry, RenameEntryDialog* pDialog); DiskImg fDiskImg; // DiskImg object for entire disk DiskFS* fpPrimaryDiskFS; // outermost DiskFS bool fIsReadOnly; /* active state while adding files */ FileAddData* fpAddDataHead; FileAddData* fpAddDataTail; bool fOverwriteExisting; bool fOverwriteNoAsk; /* state during xfer */ //CString fXferStoragePrefix; DiskFS* fpXferTargetFS; }; #endif /*APP_DISKARCHIVE_H*/
34.976359
89
0.629199
[ "object" ]
d83ebfc97b7dce6978b9e8c07ad26c07a656019b
8,711
h
C
bootstrap/include/panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
bootstrap/include/panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
bootstrap/include/panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
// This file was automatically generated by the Panda compiler #ifndef panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT_H #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT_H extern panda$core$Class panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT_class; #ifndef CLASS_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT #define CLASS_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT struct panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT { panda$core$Class* cl; Int64 _length; panda$collections$PrimitiveArray$LTpanda$collections$MutableMapEntry$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$Z$GT* contents; Int64 threshold; Int64 changeCount; }; #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$convert_$Rpanda$core$String_INDEX 1 typedef panda$core$String*(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$convert_$Rpanda$core$String_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$EQ_panda$core$Object_$Rpanda$core$Bit_INDEX 2 typedef Bit(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$EQ_panda$core$Object_$Rpanda$core$Bit_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$addAll_panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT_INDEX 4 typedef void(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$addAll_panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$remove_panda$core$Object$Z_INDEX 5 typedef void(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$remove_panda$core$Object$Z_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$ARREQ_panda$core$Object$Z_panda$core$Object$Z_INDEX 6 typedef void(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$ARREQ_panda$core$Object$Z_panda$core$Object$Z_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*, panda$core$Object*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$clear_INDEX 7 typedef void(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$clear_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_iterator_$Rpanda$collections$Iterator$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT_INDEX 8 typedef panda$collections$Iterator$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT*(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_iterator_$Rpanda$collections$Iterator$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_count_$Rpanda$core$Int64_INDEX 10 typedef Int64(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_count_$Rpanda$core$Int64_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$ARR_panda$core$Object$Z_$Rpanda$core$Object$Z_INDEX 12 typedef panda$core$Object*(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$$ARR_panda$core$Object$Z_$Rpanda$core$Object$Z_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$contains_panda$core$Object$Z_$Rpanda$core$Bit_INDEX 13 typedef Bit(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$contains_panda$core$Object$Z_$Rpanda$core$Bit_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*); #define panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_iterator_$Rpanda$collections$Iterator$LTpanda$core$Object$Z$GT_INDEX 14 typedef panda$collections$Iterator$LTpanda$core$Object$Z$GT*(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$get_iterator_$Rpanda$collections$Iterator$LTpanda$core$Object$Z$GT_TYPE)(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* new_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init(); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT_panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT*, panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT*); panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* new_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT_panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT(panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT*, panda$collections$PrimitiveArray$LTpanda$core$Object$Z$GT*); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$ListView$LTpanda$core$Object$Z$GT_panda$collections$ListView$LTpanda$core$Object$Z$GT(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$collections$ListView$LTpanda$core$Object$Z$GT*, panda$collections$ListView$LTpanda$core$Object$Z$GT*); panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* new_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$ListView$LTpanda$core$Object$Z$GT_panda$collections$ListView$LTpanda$core$Object$Z$GT(panda$collections$ListView$LTpanda$core$Object$Z$GT*, panda$collections$ListView$LTpanda$core$Object$Z$GT*); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$ListView$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$collections$ListView$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT*); panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* new_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$ListView$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT(panda$collections$ListView$LT$LPpanda$core$Object$Z$Cpanda$core$Object$Z$RP$GT*); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT*); panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* new_panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$init_panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT(panda$collections$MapView$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT*); Int64 panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$indexFor_panda$core$Object$Z_$Rpanda$core$Int64(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self, panda$core$Object*); void panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT$incrementLength(panda$collections$HashMap$LTpanda$core$Object$Z$Cpanda$core$Object$Z$GT* self); extern Int64 class_panda$collections$HashMap$DEFAULT_LENGTH; extern Real64 class_panda$collections$HashMap$LOAD_FACTOR; extern Bit class_panda$collections$HashMap$$classInited; #endif #endif
161.314815
397
0.824934
[ "object" ]
d83edd2cc0d89386e6a19a1e01cf07a4ece68a8b
4,429
h
C
src/oslibs/cocos/cocos-src/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h
dios-game/dios-cocos
b7fbcbafe02f516ef18fdb64b4519dbf806303fc
[ "MIT" ]
1
2017-06-21T10:06:26.000Z
2017-06-21T10:06:26.000Z
src/oslibs/cocos/cocos-src/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h
dios-game/dios-cocos
b7fbcbafe02f516ef18fdb64b4519dbf806303fc
[ "MIT" ]
null
null
null
src/oslibs/cocos/cocos-src/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h
dios-game/dios-cocos
b7fbcbafe02f516ef18fdb64b4519dbf806303fc
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef _NAVMESH_TEST_H_ #define _NAVMESH_TEST_H_ #include "../BaseTest.h" #include "navmesh/CCNavMesh.h" #include <string> DEFINE_TEST_SUITE(NavMeshTests); #if CC_USE_NAVMESH == 0 class NavMeshDisabled : public TestCase { public: CREATE_FUNC(NavMeshDisabled); virtual void onEnter() override; }; #else class NavMeshBaseTestDemo : public TestCase { public: CREATE_FUNC(NavMeshBaseTestDemo); NavMeshBaseTestDemo(void); virtual ~NavMeshBaseTestDemo(void); // overrides virtual bool init() override; virtual void update(float delta) override; virtual void onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event); virtual void onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event); virtual void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event); protected: void initScene(); void createAgent(const cocos2d::Vec3 &pos); void createObstacle(const cocos2d::Vec3 &pos); void moveAgents(const cocos2d::Vec3 &des); virtual void touchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event){}; virtual void touchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event){}; virtual void touchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event){}; protected: cocos2d::Camera *_camera; float _angle; std::vector<std::pair<cocos2d::NavMeshAgent *, cocos2d::Animate3D *> > _agents; bool _needMoveAgents; }; class NavMeshBasicTestDemo : public NavMeshBaseTestDemo { public: CREATE_FUNC(NavMeshBasicTestDemo); NavMeshBasicTestDemo(void); virtual ~NavMeshBasicTestDemo(void); // overrides virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; virtual void onEnter() override; protected: virtual void touchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override{}; virtual void touchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override{}; virtual void touchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override; protected: cocos2d::Label *_debugLabel; }; class NavMeshAdvanceTestDemo : public NavMeshBaseTestDemo { public: CREATE_FUNC(NavMeshAdvanceTestDemo); NavMeshAdvanceTestDemo(void); virtual ~NavMeshAdvanceTestDemo(void); // overrides virtual bool init() override; virtual std::string title() const override; virtual std::string subtitle() const override; virtual void onEnter() override; protected: virtual void touchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override{}; virtual void touchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override{}; virtual void touchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event)override; protected: cocos2d::Label *_obstacleLabel; cocos2d::Label *_agentLabel; cocos2d::Label *_debugLabel; }; #endif #endif
34.601563
109
0.714834
[ "vector" ]
d83fd0af018b49b62e4461d3d74ee4758ed4bb7b
2,547
h
C
include/RealSenseID/Preview.h
NoahRosa/RealSenseID
8710465c534b0825cc0ec90eaccb4c83d8862928
[ "Apache-2.0" ]
null
null
null
include/RealSenseID/Preview.h
NoahRosa/RealSenseID
8710465c534b0825cc0ec90eaccb4c83d8862928
[ "Apache-2.0" ]
null
null
null
include/RealSenseID/Preview.h
NoahRosa/RealSenseID
8710465c534b0825cc0ec90eaccb4c83d8862928
[ "Apache-2.0" ]
null
null
null
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020-2021 Intel Corporation. All Rights Reserved. #pragma once #include "RealSenseIDExports.h" namespace RealSenseID { class PreviewImpl; /** * Preview modes */ enum class PreviewMode { MJPEG_1080P = 0, // default MJPEG_720P = 1, RAW10_1080P = 2 // dump all frames }; /** * Preview configuration */ struct RSID_API PreviewConfig { int cameraNumber = -1; // attempt to auto detect by default PreviewMode previewMode = PreviewMode::MJPEG_1080P; // RAW10 requires custom fw support }; /** * RAW image metadata */ struct RSID_API ImageMetadata { unsigned int timestamp = 0; // sensor timestamp (miliseconds) unsigned int status = 0; unsigned int sensor_id = 0; bool led = false; bool projector = false; }; /** * Image data for preview */ struct RSID_API Image { unsigned char* buffer = nullptr; unsigned int size = 0; unsigned int width = 0; unsigned int height = 0; unsigned int stride = 0; unsigned int number = 0; ImageMetadata metadata; }; /** * User defined callback for preview. * Callback will be used to provide preview image. */ class RSID_API PreviewImageReadyCallback { public: virtual ~PreviewImageReadyCallback() = default; virtual void OnPreviewImageReady(const Image image) = 0; }; /** * Preview Support. Use StartPreview to get callbacks for image frames */ class RSID_API Preview { public: explicit Preview(const PreviewConfig&); ~Preview(); Preview(const Preview&) = delete; Preview& operator=(const Preview&) = delete; /** * Start preview. * * @param callback reference to callback object * @return True on success. */ bool StartPreview(PreviewImageReadyCallback& callback); /** * Pause preview. * * @return True on success. */ bool PausePreview(); /** * Resume preview. * * @return True on success. */ bool ResumePreview(); /** * Stop preview. * * @return True on success. */ bool StopPreview(); /** * Convert Raw Image in_image to RGB24 and fill result in out_image * @param in_image an raw10 Image to convert * @param out_image an Image with pre-allocated buffer in size in_image.width * in_image.height * 3 * @return True on success. */ bool RawToRgb(const Image& in_image, Image& out_image); private: RealSenseID::PreviewImpl* _impl = nullptr; }; } // namespace RealSenseID
21.049587
104
0.656851
[ "object" ]
d8415b63499a974fff2776b242a67d333ee65399
4,008
h
C
include/onnxruntime/core/platform/ort_mutex.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
3
2019-11-25T10:26:57.000Z
2021-05-14T08:11:29.000Z
include/onnxruntime/core/platform/ort_mutex.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
10
2019-03-25T21:47:46.000Z
2019-04-30T02:33:05.000Z
include/onnxruntime/core/platform/ort_mutex.h
hqucms/onnxruntime
6e4e76414639f50836a64546603c8957227857b0
[ "MIT" ]
4
2021-06-05T19:52:22.000Z
2021-11-30T13:58:13.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #ifdef _WIN32 #include <mutex> #include <condition_variable> namespace onnxruntime { using OrtMutex = std::mutex; using OrtCondVar = std::condition_variable; } // namespace onnxruntime #else #ifdef USE_NSYNC #include "nsync.h" #include <mutex> //for unique_lock #include <condition_variable> //for cv_status #else #include <pthread.h> #include <mutex> #include <condition_variable> #include <chrono> #include <cmath> #endif namespace onnxruntime { class OrtMutex { #ifdef USE_NSYNC nsync::nsync_mu data_ = NSYNC_MU_INIT; #else pthread_mutex_t data_ = PTHREAD_MUTEX_INITIALIZER; #endif public: constexpr OrtMutex() = default; #ifdef USE_NSYNC ~OrtMutex() = default; #else ~OrtMutex(); #endif OrtMutex(const OrtMutex&) = delete; OrtMutex& operator=(const OrtMutex&) = delete; void lock(); bool try_lock() noexcept; void unlock() noexcept; #ifdef USE_NSYNC using native_handle_type = nsync::nsync_mu*; #else using native_handle_type = pthread_mutex_t*; #endif native_handle_type native_handle() { return &data_; } }; class OrtCondVar { #ifdef USE_NSYNC nsync::nsync_cv native_cv_object = NSYNC_CV_INIT; #else pthread_cond_t native_cv_object = PTHREAD_COND_INITIALIZER; #endif public: constexpr OrtCondVar() noexcept = default; #ifdef USE_NSYNC ~OrtCondVar() = default; #else ~OrtCondVar(); #endif OrtCondVar(const OrtCondVar&) = delete; OrtCondVar& operator=(const OrtCondVar&) = delete; void notify_one() noexcept; void notify_all() noexcept; void wait(std::unique_lock<OrtMutex>& __lk); template <class _Predicate> void wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred); /** * returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns cv_status::no_timeout. * @param cond_mutex A unique_lock<OrtMutex> object. * @param rel_time A chrono::duration object that specifies the amount of time before the thread wakes up. * @return returns cv_status::timeout if the wait terminates when Rel_time has elapsed. Otherwise, the method returns cv_status::no_timeout */ template <class Rep, class Period> std::cv_status wait_for(std::unique_lock<OrtMutex>& cond_mutex, const std::chrono::duration<Rep, Period>& rel_time); #ifdef USE_NSYNC using native_handle_type = nsync::nsync_cv*; #else using native_handle_type = pthread_cond_t*; #endif native_handle_type native_handle() { return &native_cv_object; } private: void timed_wait_impl(std::unique_lock<OrtMutex>& __lk, std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>); }; template <class _Predicate> void OrtCondVar::wait(std::unique_lock<OrtMutex>& __lk, _Predicate __pred) { while (!__pred()) wait(__lk); } template <class Rep, class Period> std::cv_status OrtCondVar::wait_for(std::unique_lock<OrtMutex>& cond_mutex, const std::chrono::duration<Rep, Period>& rel_time) { //TODO: is it possible to use nsync_from_time_point_ ? using namespace std::chrono; if (rel_time <= duration<Rep, Period>::zero()) return std::cv_status::timeout; using SystemTimePointFloat = time_point<system_clock, duration<long double, std::nano> >; using SystemTimePoint = time_point<system_clock, nanoseconds>; SystemTimePointFloat max_time = SystemTimePoint::max(); steady_clock::time_point steady_now = steady_clock::now(); system_clock::time_point system_now = system_clock::now(); if (max_time - rel_time > system_now) { nanoseconds remain = duration_cast<nanoseconds>(rel_time); if (remain < rel_time) ++remain; timed_wait_impl(cond_mutex, system_now + remain); } else timed_wait_impl(cond_mutex, SystemTimePoint::max()); return steady_clock::now() - steady_now < rel_time ? std::cv_status::no_timeout : std::cv_status::timeout; } }; // namespace onnxruntime #endif
30.135338
141
0.734281
[ "object" ]
d84f34b55e1ec5f102aafcae3beb306183d6f899
28,089
c
C
src/xkb/XKBNames.c
pexip/os-libx11
f43bb64abbf64f2fdea7fa0c1f513db4ce1d7251
[ "BSD-1-Clause" ]
null
null
null
src/xkb/XKBNames.c
pexip/os-libx11
f43bb64abbf64f2fdea7fa0c1f513db4ce1d7251
[ "BSD-1-Clause" ]
null
null
null
src/xkb/XKBNames.c
pexip/os-libx11
f43bb64abbf64f2fdea7fa0c1f513db4ce1d7251
[ "BSD-1-Clause" ]
null
null
null
/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #define NEED_MAP_READERS #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "Xlibint.h" #include <X11/extensions/XKBproto.h> #include "XKBlibint.h" static Status _XkbReadAtoms(XkbReadBufferPtr buf, Atom *atoms, int maxAtoms, CARD32 present) { register int i, bit; for (i = 0, bit = 1; (i < maxAtoms) && (present); i++, bit <<= 1) { if (present & bit) { if (!_XkbReadBufferCopy32(buf, (long *) &atoms[i], 1)) return BadLength; present &= ~bit; } } return Success; } Status _XkbReadGetNamesReply(Display *dpy, xkbGetNamesReply *rep, XkbDescPtr xkb, int *nread_rtrn) { int i, len; XkbReadBufferRec buf; register XkbNamesPtr names; if (xkb->device_spec == XkbUseCoreKbd) xkb->device_spec = rep->deviceID; if ((xkb->names == NULL) && (XkbAllocNames(xkb, rep->which, rep->nRadioGroups, rep->nKeyAliases) != Success)) { return BadAlloc; } names = xkb->names; if (rep->length == 0) return Success; if (!_XkbInitReadBuffer(dpy, &buf, (int) rep->length * 4)) return BadAlloc; if (nread_rtrn) *nread_rtrn = (int) rep->length * 4; if ((rep->which & XkbKeycodesNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->keycodes, 1))) goto BAILOUT; if ((rep->which & XkbGeometryNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->geometry, 1))) goto BAILOUT; if ((rep->which & XkbSymbolsNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->symbols, 1))) goto BAILOUT; if ((rep->which & XkbPhysSymbolsNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->phys_symbols, 1))) goto BAILOUT; if ((rep->which & XkbTypesNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->types, 1))) goto BAILOUT; if ((rep->which & XkbCompatNameMask) && (!_XkbReadBufferCopy32(&buf, (long *) &names->compat, 1))) goto BAILOUT; if (rep->which & XkbKeyTypeNamesMask) { XkbClientMapPtr map = xkb->map; XkbKeyTypePtr type; len = rep->nTypes * 4; if (map != NULL) { type = map->types; for (i = 0; (i < map->num_types) && (i < rep->nTypes); i++, type++) { if (!_XkbReadBufferCopy32(&buf, (long *) &type->name, 1)) goto BAILOUT; len -= 4; } } if ((len > 0) && (!_XkbSkipReadBufferData(&buf, len))) goto BAILOUT; } if (rep->which & XkbKTLevelNamesMask) { CARD8 *nLevels; XkbClientMapPtr map = xkb->map; nLevels = (CARD8 *) _XkbGetReadBufferPtr(&buf, XkbPaddedSize(rep->nTypes)); if (nLevels == NULL) goto BAILOUT; if (map != NULL) { XkbKeyTypePtr type = map->types; for (i = 0; i < (int) rep->nTypes; i++, type++) { if (i >= map->num_types) { if (!_XkbSkipReadBufferData(&buf, nLevels[i] * 4)) goto BAILOUT; continue; } if ((nLevels[i] > 0) && (nLevels[i] != type->num_levels)) { goto BAILOUT; } Xfree(type->level_names); if (nLevels[i] == 0) { type->level_names = NULL; continue; } type->level_names = _XkbTypedCalloc(nLevels[i], Atom); if (type->level_names != NULL) { if (!_XkbReadBufferCopy32(&buf, (long *) type->level_names, nLevels[i])) goto BAILOUT; } else { _XkbSkipReadBufferData(&buf, nLevels[i] * 4); } } } else { for (i = 0; i < (int) rep->nTypes; i++) { _XkbSkipReadBufferData(&buf, nLevels[i] * 4); } } } if (rep->which & XkbIndicatorNamesMask) { if (_XkbReadAtoms(&buf, names->indicators, XkbNumIndicators, rep->indicators) != Success) goto BAILOUT; } if (rep->which & XkbVirtualModNamesMask) { if (_XkbReadAtoms(&buf, names->vmods, XkbNumVirtualMods, (CARD32) rep->virtualMods) != Success) goto BAILOUT; } if (rep->which & XkbGroupNamesMask) { if (_XkbReadAtoms(&buf, names->groups, XkbNumKbdGroups, (CARD32) rep->groupNames) != Success) goto BAILOUT; } if (rep->which & XkbKeyNamesMask) { if (names->keys == NULL) { int nKeys; if (xkb->max_key_code == 0) { xkb->min_key_code = rep->minKeyCode; xkb->max_key_code = rep->maxKeyCode; } nKeys = xkb->max_key_code + 1; names->keys = _XkbTypedCalloc(nKeys, XkbKeyNameRec); } if (((int) rep->firstKey + rep->nKeys) > xkb->max_key_code + 1) goto BAILOUT; if (names->keys != NULL) { if (!_XkbCopyFromReadBuffer(&buf, (char *) &names->keys[rep->firstKey], rep->nKeys * XkbKeyNameLength)) goto BAILOUT; } else _XkbSkipReadBufferData(&buf, rep->nKeys * XkbKeyNameLength); } if (rep->which & XkbKeyAliasesMask && (rep->nKeyAliases > 0)) { if (XkbAllocNames(xkb, XkbKeyAliasesMask, 0, rep->nKeyAliases) != Success) goto BAILOUT; if (!_XkbCopyFromReadBuffer(&buf, (char *) names->key_aliases, rep->nKeyAliases * XkbKeyNameLength * 2)) goto BAILOUT; } if (rep->which & XkbRGNamesMask) { if (rep->nRadioGroups > 0) { Atom *rgNames; if (names->radio_groups == NULL) names->radio_groups = _XkbTypedCalloc(rep->nRadioGroups, Atom); else if (names->num_rg < rep->nRadioGroups) { names->radio_groups = _XkbTypedRealloc(names->radio_groups, rep->nRadioGroups, Atom); } rgNames = names->radio_groups; if (!rgNames) { goto BAILOUT; } if (!_XkbReadBufferCopy32 (&buf, (long *) rgNames, rep->nRadioGroups)) goto BAILOUT; names->num_rg = rep->nRadioGroups; } else if (names->num_rg > 0) { names->num_rg = 0; Xfree(names->radio_groups); } } len = _XkbFreeReadBuffer(&buf); if (len != 0) return BadLength; else return Success; BAILOUT: _XkbFreeReadBuffer(&buf); return BadLength; } Status XkbGetNames(Display *dpy, unsigned which, XkbDescPtr xkb) { register xkbGetNamesReq *req; xkbGetNamesReply rep; Status status; XkbInfoPtr xkbi; if ((dpy->flags & XlibDisplayNoXkb) || (!dpy->xkb_info && !XkbUseExtension(dpy, NULL, NULL))) return BadAccess; LockDisplay(dpy); xkbi = dpy->xkb_info; if (!xkb->names) { xkb->names = _XkbTypedCalloc(1, XkbNamesRec); if (!xkb->names) { UnlockDisplay(dpy); SyncHandle(); return BadAlloc; } } GetReq(kbGetNames, req); req->reqType = xkbi->codes->major_opcode; req->xkbReqType = X_kbGetNames; req->deviceSpec = xkb->device_spec; req->which = which; if (!_XReply(dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return BadImplementation; } status = _XkbReadGetNamesReply(dpy, &rep, xkb, NULL); UnlockDisplay(dpy); SyncHandle(); return status; } /***====================================================================***/ static int _XkbCountBits(int nBitsMax, unsigned long mask) { register unsigned long y, nBits; y = (mask >> 1) & 033333333333; y = mask - y - ((y >> 1) & 033333333333); nBits = ((unsigned int) (((y + (y >> 3)) & 030707070707) % 077)); /* nBitsMax really means max+1 */ return (nBits < nBitsMax) ? nBits : (nBitsMax - 1); } static CARD32 _XkbCountAtoms(Atom *atoms, int maxAtoms, int *count) { register unsigned int i, bit, nAtoms; register CARD32 atomsPresent; for (i = nAtoms = atomsPresent = 0, bit = 1; i < maxAtoms; i++, bit <<= 1) { if (atoms[i] != None) { atomsPresent |= bit; nAtoms++; } } if (count) *count = nAtoms; return atomsPresent; } static void _XkbCopyAtoms(Display *dpy, Atom *atoms, CARD32 mask, int maxAtoms) { register unsigned int i, bit; for (i = 0, bit = 1; i < maxAtoms; i++, bit <<= 1) { if (mask & bit) Data32(dpy, &atoms[i], 4); } return; } Bool XkbSetNames(Display *dpy, unsigned int which, unsigned int firstType, unsigned int nTypes, XkbDescPtr xkb) { register xkbSetNamesReq *req; int nLvlNames = 0; XkbInfoPtr xkbi; XkbNamesPtr names; unsigned firstLvlType, nLvlTypes; int nVMods, nLEDs, nRG, nKA, nGroups; int nKeys = 0, firstKey = 0, nAtoms; CARD32 leds, vmods, groups; if ((dpy->flags & XlibDisplayNoXkb) || (!dpy->xkb_info && !XkbUseExtension(dpy, NULL, NULL))) return False; if ((!xkb) || (!xkb->names)) return False; firstLvlType = firstType; nLvlTypes = nTypes; if (nTypes < 1) which &= ~(XkbKTLevelNamesMask | XkbKeyTypeNamesMask); else if (firstType <= XkbLastRequiredType) { int adjust; adjust = XkbLastRequiredType - firstType + 1; firstType += adjust; nTypes -= adjust; if (nTypes < 1) which &= ~XkbKeyTypeNamesMask; } names = xkb->names; if (which & (XkbKTLevelNamesMask | XkbKeyTypeNamesMask)) { register int i; XkbKeyTypePtr type; if ((xkb->map == NULL) || (xkb->map->types == NULL) || (nTypes == 0) || (firstType + nTypes > xkb->map->num_types) || (firstLvlType + nLvlTypes > xkb->map->num_types)) return False; if (which & XkbKTLevelNamesMask) { type = &xkb->map->types[firstLvlType]; for (i = nLvlNames = 0; i < nLvlTypes; i++, type++) { if (type->level_names != NULL) nLvlNames += type->num_levels; } } } nVMods = nLEDs = nRG = nKA = nAtoms = nGroups = 0; LockDisplay(dpy); xkbi = dpy->xkb_info; GetReq(kbSetNames, req); req->reqType = xkbi->codes->major_opcode; req->xkbReqType = X_kbSetNames; req->deviceSpec = xkb->device_spec; req->firstType = firstType; req->nTypes = nTypes; req->firstKey = xkb->min_key_code; req->nKeys = xkb->max_key_code - xkb->min_key_code + 1; if (which & XkbKeycodesNameMask) nAtoms++; if (which & XkbGeometryNameMask) nAtoms++; if (which & XkbSymbolsNameMask) nAtoms++; if (which & XkbPhysSymbolsNameMask) nAtoms++; if (which & XkbTypesNameMask) nAtoms++; if (which & XkbCompatNameMask) nAtoms++; if (which & XkbKeyTypeNamesMask) nAtoms += nTypes; if (which & XkbKTLevelNamesMask) { req->firstKTLevel = firstLvlType; req->nKTLevels = nLvlTypes; req->length += XkbPaddedSize(nLvlTypes) / 4; /* room for group widths */ nAtoms += nLvlNames; } else req->firstKTLevel = req->nKTLevels = 0; if (which & XkbIndicatorNamesMask) { req->indicators = leds = _XkbCountAtoms(names->indicators, XkbNumIndicators, &nLEDs); if (nLEDs > 0) nAtoms += nLEDs; else which &= ~XkbIndicatorNamesMask; } else req->indicators = leds = 0; if (which & XkbVirtualModNamesMask) { vmods = req->virtualMods = (CARD16) _XkbCountAtoms(names->vmods, XkbNumVirtualMods, &nVMods); if (nVMods > 0) nAtoms += nVMods; else which &= ~XkbVirtualModNamesMask; } else vmods = req->virtualMods = 0; if (which & XkbGroupNamesMask) { groups = req->groupNames = (CARD8) _XkbCountAtoms(names->groups, XkbNumKbdGroups, &nGroups); if (nGroups > 0) nAtoms += nGroups; else which &= ~XkbGroupNamesMask; } else groups = req->groupNames = 0; if ((which & XkbKeyNamesMask) && (names->keys != NULL)) { firstKey = req->firstKey; nKeys = req->nKeys; nAtoms += nKeys; /* technically not atoms, but 4 bytes wide */ } else which &= ~XkbKeyNamesMask; if (which & XkbKeyAliasesMask) { nKA = ((names->key_aliases != NULL) ? names->num_key_aliases : 0); if (nKA > 0) { req->nKeyAliases = nKA; nAtoms += nKA * 2; /* not atoms, but 8 bytes on the wire */ } else { which &= ~XkbKeyAliasesMask; req->nKeyAliases = 0; } } else req->nKeyAliases = 0; if (which & XkbRGNamesMask) { nRG = names->num_rg; if (nRG > 0) nAtoms += nRG; else which &= ~XkbRGNamesMask; } req->which = which; req->nRadioGroups = nRG; req->length += (nAtoms * 4) / 4; if (which & XkbKeycodesNameMask) Data32(dpy, (long *) &names->keycodes, 4); if (which & XkbGeometryNameMask) Data32(dpy, (long *) &names->geometry, 4); if (which & XkbSymbolsNameMask) Data32(dpy, (long *) &names->symbols, 4); if (which & XkbPhysSymbolsNameMask) Data32(dpy, (long *) &names->phys_symbols, 4); if (which & XkbTypesNameMask) Data32(dpy, (long *) &names->types, 4); if (which & XkbCompatNameMask) Data32(dpy, (long *) &names->compat, 4); if (which & XkbKeyTypeNamesMask) { register int i; register XkbKeyTypePtr type; type = &xkb->map->types[firstType]; for (i = 0; i < nTypes; i++, type++) { Data32(dpy, (long *) &type->name, 4); } } if (which & XkbKTLevelNamesMask) { XkbKeyTypePtr type; int i; char *tmp; BufAlloc(char *, tmp, XkbPaddedSize(nLvlTypes)); type = &xkb->map->types[firstLvlType]; for (i = 0; i < nLvlTypes; i++, type++) { *tmp++ = type->num_levels; } type = &xkb->map->types[firstLvlType]; for (i = 0; i < nLvlTypes; i++, type++) { if (type->level_names != NULL) Data32(dpy, (long *) type->level_names, type->num_levels * 4); } } if (which & XkbIndicatorNamesMask) _XkbCopyAtoms(dpy, names->indicators, leds, XkbNumIndicators); if (which & XkbVirtualModNamesMask) _XkbCopyAtoms(dpy, names->vmods, vmods, XkbNumVirtualMods); if (which & XkbGroupNamesMask) _XkbCopyAtoms(dpy, names->groups, groups, XkbNumKbdGroups); if (which & XkbKeyNamesMask) { Data(dpy, (char *) &names->keys[firstKey], nKeys * XkbKeyNameLength); } if (which & XkbKeyAliasesMask) { Data(dpy, (char *) names->key_aliases, nKA * XkbKeyNameLength * 2); } if (which & XkbRGNamesMask) { Data32(dpy, (long *) names->radio_groups, nRG * 4); } UnlockDisplay(dpy); SyncHandle(); return True; } Bool XkbChangeNames(Display *dpy, XkbDescPtr xkb, XkbNameChangesPtr changes) { register xkbSetNamesReq *req; int nLvlNames = 0; XkbInfoPtr xkbi; XkbNamesPtr names; unsigned which, firstType, nTypes; unsigned firstLvlType, nLvlTypes; int nVMods, nLEDs, nRG, nKA, nGroups; int nKeys = 0, firstKey = 0, nAtoms; CARD32 leds = 0, vmods = 0, groups = 0; if ((dpy->flags & XlibDisplayNoXkb) || (!dpy->xkb_info && !XkbUseExtension(dpy, NULL, NULL))) return False; if ((!xkb) || (!xkb->names) || (!changes)) return False; which = changes->changed; firstType = changes->first_type; nTypes = changes->num_types; firstLvlType = changes->first_lvl; nLvlTypes = changes->num_lvls; if (which & XkbKeyTypeNamesMask) { if (nTypes < 1) which &= ~XkbKeyTypeNamesMask; else if (firstType <= XkbLastRequiredType) { int adjust; adjust = XkbLastRequiredType - firstType + 1; firstType += adjust; nTypes -= adjust; if (nTypes < 1) which &= ~XkbKeyTypeNamesMask; } } else firstType = nTypes = 0; if (which & XkbKTLevelNamesMask) { if (nLvlTypes < 1) which &= ~XkbKTLevelNamesMask; } else firstLvlType = nLvlTypes = 0; names = xkb->names; if (which & (XkbKTLevelNamesMask | XkbKeyTypeNamesMask)) { register int i; if ((xkb->map == NULL) || (xkb->map->types == NULL) || (nTypes == 0) || (firstType + nTypes > xkb->map->num_types) || (firstLvlType + nLvlTypes > xkb->map->num_types)) return False; if (which & XkbKTLevelNamesMask) { XkbKeyTypePtr type = &xkb->map->types[firstLvlType]; for (i = nLvlNames = 0; i < nLvlTypes; i++, type++) { if (type->level_names != NULL) nLvlNames += type->num_levels; } } } if (changes->num_keys < 1) which &= ~XkbKeyNamesMask; if ((which & XkbKeyNamesMask) == 0) changes->first_key = changes->num_keys = 0; else if ((changes->first_key < xkb->min_key_code) || (changes->first_key + changes->num_keys > xkb->max_key_code)) { return False; } if ((which & XkbVirtualModNamesMask) == 0) changes->changed_vmods = 0; else if (changes->changed_vmods == 0) which &= ~XkbVirtualModNamesMask; if ((which & XkbIndicatorNamesMask) == 0) changes->changed_indicators = 0; else if (changes->changed_indicators == 0) which &= ~XkbIndicatorNamesMask; if ((which & XkbGroupNamesMask) == 0) changes->changed_groups = 0; else if (changes->changed_groups == 0) which &= ~XkbGroupNamesMask; nVMods = nLEDs = nRG = nKA = nAtoms = nGroups = 0; LockDisplay(dpy); xkbi = dpy->xkb_info; GetReq(kbSetNames, req); req->reqType = xkbi->codes->major_opcode; req->xkbReqType = X_kbSetNames; req->deviceSpec = xkb->device_spec; req->firstType = firstType; req->nTypes = nTypes; req->firstKey = changes->first_key; req->nKeys = changes->num_keys; if (which & XkbKeycodesNameMask) nAtoms++; if (which & XkbGeometryNameMask) nAtoms++; if (which & XkbSymbolsNameMask) nAtoms++; if (which & XkbPhysSymbolsNameMask) nAtoms++; if (which & XkbTypesNameMask) nAtoms++; if (which & XkbCompatNameMask) nAtoms++; if (which & XkbKeyTypeNamesMask) nAtoms += nTypes; if (which & XkbKTLevelNamesMask) { req->firstKTLevel = firstLvlType; req->nKTLevels = nLvlTypes; req->length += XkbPaddedSize(nLvlTypes) / 4; /* room for group widths */ nAtoms += nLvlNames; } else req->firstKTLevel = req->nKTLevels = 0; if (which & XkbIndicatorNamesMask) { leds = req->indicators = (CARD32) changes->changed_indicators; nLEDs = _XkbCountBits(XkbNumIndicators, changes->changed_indicators); if (nLEDs > 0) nAtoms += nLEDs; else which &= ~XkbIndicatorNamesMask; } else req->indicators = 0; if (which & XkbVirtualModNamesMask) { vmods = req->virtualMods = changes->changed_vmods; nVMods = _XkbCountBits(XkbNumVirtualMods, (unsigned long) changes->changed_vmods); if (nVMods > 0) nAtoms += nVMods; else which &= ~XkbVirtualModNamesMask; } else req->virtualMods = 0; if (which & XkbGroupNamesMask) { groups = req->groupNames = changes->changed_groups; nGroups = _XkbCountBits(XkbNumKbdGroups, (unsigned long) changes->changed_groups); if (nGroups > 0) nAtoms += nGroups; else which &= ~XkbGroupNamesMask; } else req->groupNames = 0; if ((which & XkbKeyNamesMask) && (names->keys != NULL)) { firstKey = req->firstKey; nKeys = req->nKeys; nAtoms += nKeys; /* technically not atoms, but 4 bytes wide */ } else which &= ~XkbKeyNamesMask; if (which & XkbKeyAliasesMask) { nKA = ((names->key_aliases != NULL) ? names->num_key_aliases : 0); if (nKA > 0) nAtoms += nKA * 2; /* not atoms, but 8 bytes on the wire */ else which &= ~XkbKeyAliasesMask; } if (which & XkbRGNamesMask) { nRG = names->num_rg; if (nRG > 0) nAtoms += nRG; else which &= ~XkbRGNamesMask; } req->which = which; req->nRadioGroups = nRG; req->length += (nAtoms * 4) / 4; if (which & XkbKeycodesNameMask) Data32(dpy, (long *) &names->keycodes, 4); if (which & XkbGeometryNameMask) Data32(dpy, (long *) &names->geometry, 4); if (which & XkbSymbolsNameMask) Data32(dpy, (long *) &names->symbols, 4); if (which & XkbPhysSymbolsNameMask) Data32(dpy, (long *) &names->phys_symbols, 4); if (which & XkbTypesNameMask) Data32(dpy, (long *) &names->types, 4); if (which & XkbCompatNameMask) Data32(dpy, (long *) &names->compat, 4); if (which & XkbKeyTypeNamesMask) { register int i; register XkbKeyTypePtr type; type = &xkb->map->types[firstType]; for (i = 0; i < nTypes; i++, type++) { Data32(dpy, (long *) &type->name, 4); } } if (which & XkbKTLevelNamesMask) { XkbKeyTypePtr type; int i; char *tmp; BufAlloc(char *, tmp, XkbPaddedSize(nLvlTypes)); type = &xkb->map->types[firstLvlType]; for (i = 0; i < nLvlTypes; i++, type++) { *tmp++ = type->num_levels; } type = &xkb->map->types[firstLvlType]; for (i = 0; i < nLvlTypes; i++, type++) { if (type->level_names != NULL) Data32(dpy, (long *) type->level_names, type->num_levels * 4); } } if (which & XkbIndicatorNamesMask) _XkbCopyAtoms(dpy, names->indicators, leds, XkbNumIndicators); if (which & XkbVirtualModNamesMask) _XkbCopyAtoms(dpy, names->vmods, vmods, XkbNumVirtualMods); if (which & XkbGroupNamesMask) _XkbCopyAtoms(dpy, names->groups, groups, XkbNumKbdGroups); if (which & XkbKeyNamesMask) { Data(dpy, (char *) &names->keys[firstKey], nKeys * XkbKeyNameLength); } if (which & XkbKeyAliasesMask) { Data(dpy, (char *) names->key_aliases, nKA * XkbKeyNameLength * 2); } if (which & XkbRGNamesMask) { Data32(dpy, (long *) names->radio_groups, nRG * 4); } UnlockDisplay(dpy); SyncHandle(); return True; } void XkbNoteNameChanges(XkbNameChangesPtr old, XkbNamesNotifyEvent *new, unsigned int wanted) { int first, last, old_last, new_last; if ((old == NULL) || (new == NULL)) return; wanted &= new->changed; if (wanted == 0) return; if (wanted & XkbKeyTypeNamesMask) { if (old->changed & XkbKeyTypeNamesMask) { new_last = (new->first_type + new->num_types - 1); old_last = (old->first_type + old->num_types - 1); if (new->first_type < old->first_type) first = new->first_type; else first = old->first_type; if (old_last > new_last) last = old_last; else last = new_last; old->first_type = first; old->num_types = (last - first) + 1; } else { old->first_type = new->first_type; old->num_types = new->num_types; } } if (wanted & XkbKTLevelNamesMask) { if (old->changed & XkbKTLevelNamesMask) { new_last = (new->first_lvl + new->num_lvls - 1); old_last = (old->first_lvl + old->num_lvls - 1); if (new->first_lvl < old->first_lvl) first = new->first_lvl; else first = old->first_lvl; if (old_last > new_last) last = old_last; else last = new_last; old->first_lvl = first; old->num_lvls = (last - first) + 1; } else { old->first_lvl = new->first_lvl; old->num_lvls = new->num_lvls; } } if (wanted & XkbIndicatorNamesMask) { if (old->changed & XkbIndicatorNamesMask) old->changed_indicators |= new->changed_indicators; else old->changed_indicators = new->changed_indicators; } if (wanted & XkbKeyNamesMask) { if (old->changed & XkbKeyNamesMask) { new_last = (new->first_key + new->num_keys - 1); old_last = (old->first_key + old->num_keys - 1); first = old->first_key; if (new->first_key < old->first_key) first = new->first_key; if (old_last > new_last) new_last = old_last; old->first_key = first; old->num_keys = (new_last - first) + 1; } else { old->first_key = new->first_key; old->num_keys = new->num_keys; } } if (wanted & XkbVirtualModNamesMask) { if (old->changed & XkbVirtualModNamesMask) old->changed_vmods |= new->changed_vmods; else old->changed_vmods = new->changed_vmods; } if (wanted & XkbGroupNamesMask) { if (old->changed & XkbGroupNamesMask) old->changed_groups |= new->changed_groups; else old->changed_groups = new->changed_groups; } if (wanted & XkbRGNamesMask) old->num_rg = new->num_radio_groups; if (wanted & XkbKeyAliasesMask) old->num_aliases = new->num_aliases; old->changed |= wanted; return; }
31.919318
83
0.546904
[ "geometry" ]
d8525b3034cfe24930b6963293efd8af2c22cf10
12,019
h
C
thrust/iterator/transform_iterator.h
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
thrust/iterator/transform_iterator.h
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
thrust/iterator/transform_iterator.h
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2012 NVIDIA 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. */ /*! \file transform_iterator.h * \brief An iterator which adapts another iterator by applying a function to the result of its dereference */ /* * (C) Copyright David Abrahams 2002. * (C) Copyright Jeremy Siek 2002. * (C) Copyright Thomas Witt 2002. * * Distributed under the Boost Software License, Version 1.0. * (See accompanying NOTICE file for the complete license) * * For more information, see http://www.boost.org */ #pragma once #include <thrust/detail/config.h> // #include the details first #include <thrust/iterator/detail/transform_iterator.inl> #include <thrust/iterator/iterator_facade.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/function.h> namespace thrust { /*! \addtogroup iterators * \{ */ /*! \addtogroup fancyiterator Fancy Iterators * \ingroup iterators * \{ */ /*! \p transform_iterator is an iterator which represents a pointer into a range * of values after transformation by a function. This iterator is useful for * creating a range filled with the result of applying an operation to another range * without either explicitly storing it in memory, or explicitly executing the transformation. * Using \p transform_iterator facilitates kernel fusion by deferring the execution * of a transformation until the value is needed while saving both memory capacity * and bandwidth. * * The following code snippet demonstrates how to create a \p transform_iterator * which represents the result of \c sqrtf applied to the contents of a \p device_vector. * * \code * #include <thrust/iterator/transform_iterator.h> * #include <thrust/device_vector.h> * * // note: functor inherits from unary_function * struct square_root : public thrust::unary_function<float,float> * { * __host__ __device__ * float operator()(float x) const * { * return sqrtf(x); * } * }; * * int main(void) * { * thrust::device_vector<float> v(4); * v[0] = 1.0f; * v[1] = 4.0f; * v[2] = 9.0f; * v[3] = 16.0f; * * typedef thrust::device_vector<float>::iterator FloatIterator; * * thrust::transform_iterator<square_root, FloatIterator> iter(v.begin(), square_root()); * * *iter; // returns 1.0f * iter[0]; // returns 1.0f; * iter[1]; // returns 2.0f; * iter[2]; // returns 3.0f; * iter[3]; // returns 4.0f; * * // iter[4] is an out-of-bounds error * } * \endcode * * This next example demonstrates how to use a \p transform_iterator with the * \p thrust::reduce function to compute the sum of squares of a sequence. * We will create temporary \p transform_iterators with the * \p make_transform_iterator function in order to avoid explicitly specifying their type: * * \code * #include <thrust/iterator/transform_iterator.h> * #include <thrust/device_vector.h> * #include <thrust/reduce.h> * #include <iostream> * * // note: functor inherits from unary_function * struct square : public thrust::unary_function<float,float> * { * __host__ __device__ * float operator()(float x) const * { * return x * x; * } * }; * * int main(void) * { * // initialize a device array * thrust::device_vector<float> v(4); * v[0] = 1.0f; * v[1] = 2.0f; * v[2] = 3.0f; * v[3] = 4.0f; * * float sum_of_squares = * thrust::reduce(thrust::make_transform_iterator(v.begin(), square()), * thrust::make_transform_iterator(v.end(), square())); * * std::cout << "sum of squares: " << sum_of_squares << std::endl; * return 0; * } * \endcode * * Note that in the previous two examples the transform functor (namely \c square_root * and \c square) inherits from \c thrust::unary_function. Inheriting from * \c thrust::unary_function ensures that a functor is a valid \c AdaptableUnaryFunction * and provides all the necessary \c typedef declarations. The \p transform_iterator * can also be applied to a \c UnaryFunction that does not inherit from * \c thrust::unary_function using an optional template argument. The following example * illustrates how to use the third template argument to specify the \c result_type of * the function. * * \code * #include <thrust/iterator/transform_iterator.h> * #include <thrust/device_vector.h> * * // note: functor *does not* inherit from unary_function * struct square_root * { * __host__ __device__ * float operator()(float x) const * { * return sqrtf(x); * } * }; * * int main(void) * { * thrust::device_vector<float> v(4); * v[0] = 1.0f; * v[1] = 4.0f; * v[2] = 9.0f; * v[3] = 16.0f; * * typedef thrust::device_vector<float>::iterator FloatIterator; * * // note: float result_type is specified explicitly * thrust::transform_iterator<square_root, FloatIterator, float> iter(v.begin(), square_root()); * * *iter; // returns 1.0f * iter[0]; // returns 1.0f; * iter[1]; // returns 2.0f; * iter[2]; // returns 3.0f; * iter[3]; // returns 4.0f; * * // iter[4] is an out-of-bounds error * } * \endcode * * \see make_transform_iterator */ template <class AdaptableUnaryFunction, class Iterator, class Reference = use_default, class Value = use_default> class transform_iterator : public detail::transform_iterator_base<AdaptableUnaryFunction, Iterator, Reference, Value>::type { /*! \cond */ public: typedef typename detail::transform_iterator_base<AdaptableUnaryFunction, Iterator, Reference, Value>::type super_t; friend class thrust::iterator_core_access; /*! \endcond */ public: /*! Null constructor does nothing. */ __host__ __device__ transform_iterator() {} /*! This constructor takes as arguments an \c Iterator and an \c AdaptableUnaryFunction * and copies them to a new \p transform_iterator. * * \param x An \c Iterator pointing to the input to this \p transform_iterator's \c AdaptableUnaryFunction. * \param f An \c AdaptableUnaryFunction used to transform the objects pointed to by \p x. */ __host__ __device__ transform_iterator(Iterator const& x, AdaptableUnaryFunction f) : super_t(x), m_f(f) { } /*! This explicit constructor copies the value of a given \c Iterator and creates * this \p transform_iterator's \c AdaptableUnaryFunction using its null constructor. * * \param x An \c Iterator to copy. */ __host__ __device__ explicit transform_iterator(Iterator const& x) : super_t(x) { } /*! This copy constructor creates a new \p transform_iterator from another * \p transform_iterator. * * \param other The \p transform_iterator to copy. */ template<typename OtherAdaptableUnaryFunction, typename OtherIterator, typename OtherReference, typename OtherValue> __host__ __device__ transform_iterator(const transform_iterator<OtherAdaptableUnaryFunction, OtherIterator, OtherReference, OtherValue> &other, typename thrust::detail::enable_if_convertible<OtherIterator, Iterator>::type* = 0, typename thrust::detail::enable_if_convertible<OtherAdaptableUnaryFunction, AdaptableUnaryFunction>::type* = 0) : super_t(other.base()), m_f(other.functor()) {} /*! Copy assignment operator copies from another \p transform_iterator. * \p other The other \p transform_iterator to copy * \return <tt>*this</tt> * * \note If the type of this \p transform_iterator's functor is not copy assignable * (for example, if it is a lambda) it is not an error to call this function. * In this case, however, the functor will not be modified. * * In any case, this \p transform_iterator's underlying iterator will be copy assigned. */ __host__ __device__ transform_iterator &operator=(const transform_iterator &other) { return do_assign(other, // XXX gcc 4.2.1 crashes on is_copy_assignable; just assume the functor is assignable as a WAR #if (THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_GCC) && (THRUST_GCC_VERSION <= 40201) thrust::detail::true_type() #else typename thrust::detail::is_copy_assignable<AdaptableUnaryFunction>::type() #endif // THRUST_HOST_COMPILER ); } /*! This method returns a copy of this \p transform_iterator's \c AdaptableUnaryFunction. * \return A copy of this \p transform_iterator's \c AdaptableUnaryFunction. */ __host__ __device__ AdaptableUnaryFunction functor() const { return m_f; } /*! \cond */ private: __host__ __device__ transform_iterator &do_assign(const transform_iterator &other, thrust::detail::true_type) { super_t::operator=(other); // do assign to m_f m_f = other.functor(); return *this; } __host__ __device__ transform_iterator &do_assign(const transform_iterator &other, thrust::detail::false_type) { super_t::operator=(other); // don't assign to m_f return *this; } __thrust_hd_warning_disable__ __host__ __device__ typename super_t::reference dereference() const { // XXX consider making this a member instead of a temporary created inside dereference thrust::detail::host_device_function<AdaptableUnaryFunction, typename super_t::reference> wrapped_f(m_f); return wrapped_f(*this->base()); } // tag this as mutable per Dave Abrahams in this thread: // http://lists.boost.org/Archives/boost/2004/05/65332.php mutable AdaptableUnaryFunction m_f; /*! \endcond */ }; // end transform_iterator /*! \p make_transform_iterator creates a \p transform_iterator * from an \c Iterator and \c AdaptableUnaryFunction. * * \param it The \c Iterator pointing to the input range of the * newly created \p transform_iterator. * \param fun The \c AdaptableUnaryFunction used to transform the range pointed * bo by \p it in the newly created \p transform_iterator. * \return A new \p transform_iterator which transforms the range at * \p it by \p fun. * \see transform_iterator */ template <class AdaptableUnaryFunction, class Iterator> inline __host__ __device__ transform_iterator<AdaptableUnaryFunction, Iterator> make_transform_iterator(Iterator it, AdaptableUnaryFunction fun) { return transform_iterator<AdaptableUnaryFunction, Iterator>(it, fun); } // end make_transform_iterator /*! \} // end fancyiterators */ /*! \} // end iterators */ } // end thrust
34.837681
134
0.636326
[ "transform" ]
d85c94d03d6553e7083f77a8a692044db1c07fbf
15,832
h
C
headers/fplog.h
kr0st/fplog2
8e660a2a2f9dbd87a336c2af6cb13a44435acafa
[ "BSD-2-Clause" ]
null
null
null
headers/fplog.h
kr0st/fplog2
8e660a2a2f9dbd87a336c2af6cb13a44435acafa
[ "BSD-2-Clause" ]
null
null
null
headers/fplog.h
kr0st/fplog2
8e660a2a2f9dbd87a336c2af6cb13a44435acafa
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <string> #include <set> #include <vector> #include <rapidjson/rapidjson.h> #include <rapidjson/document.h> #include <typeinfo> #include <sprot.h> #include <fplog_exceptions.h> #include <algorithm> #include <mutex> #include <functional> #ifdef FPLOG_EXPORT #ifdef __linux__ #define FPLOG_API __attribute__ ((visibility("default"))) #else #define FPLOG_API __declspec(dllexport) #endif #else #ifdef __linux__ #define FPLOG_API #endif #ifdef __APPLE__ #define FPLOG_API #endif #ifdef _WIN32_WINNT #define FPLOG_API __declspec(dllimport) #endif #endif #if defined(__linux__) || defined(__APPLE__) namespace fplog { std::string demangle_cpp_name(const char* mangled); }; #define CLASSNAME fplog::demangle_cpp_name(typeid(*this).name()).c_str() #endif #ifdef _WIN32_WINNT #define CLASSNAME typeid(*this).name() #endif #define CLASSNAME_SHORT \ (strrchr(CLASSNAME,' ') \ ? strrchr(CLASSNAME,' ')+1 \ : CLASSNAME \ ) #define FUNCTION_SHORT \ (strrchr(__FUNCTION__,':') \ ? strrchr(__FUNCTION__,':')+1 \ : __FUNCTION__ \ ) #ifndef _WIN32_WINNT #define FPL_TRACE(format, ...) fplog::Message(fplog::Prio::debug, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_INFO(format, ...) fplog::Message(fplog::Prio::info, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_WARN(format, ...) fplog::Message(fplog::Prio::warning, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_ERROR(format, ...) fplog::Message(fplog::Prio::error, fplog::get_facility(), format, ##__VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_CTRACE(format, ...) FPL_TRACE(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CINFO(format, ...) FPL_INFO(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CWARN(format, ...) FPL_WARN(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CERROR(format, ...) FPL_ERROR(format, ##__VA_ARGS__).set_class(CLASSNAME_SHORT) #else #define FPL_TRACE(format, ...) fplog::Message(fplog::Prio::debug, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_INFO(format, ...) fplog::Message(fplog::Prio::info, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_WARN(format, ...) fplog::Message(fplog::Prio::warning, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_ERROR(format, ...) fplog::Message(fplog::Prio::error, fplog::get_facility(), format, __VA_ARGS__).set_module(__SHORT_FORM_OF_FILE__).set_line(__LINE__).set_method(FUNCTION_SHORT) #define FPL_CTRACE(format, ...) FPL_TRACE(format, __VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CINFO(format, ...) FPL_INFO(format, __VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CWARN(format, ...) FPL_WARN(format, __VA_ARGS__).set_class(CLASSNAME_SHORT) #define FPL_CERROR(format, ...) FPL_ERROR(format, __VA_ARGS__).set_class(CLASSNAME_SHORT) #endif namespace fplogd { class Impl; }; namespace fplog { struct FPLOG_API Facility { static const char* system; //message from some system component static const char* user; //message from user-level component static const char* security; //security or authorization related message static const char* fplog; //message from fplog directly, could inform about log system malfunction }; struct FPLOG_API Prio { static const char* emergency; //system is unusable static const char* alert; //action must be taken immediately static const char* critical; //critical conditions static const char* error; //error conditions static const char* warning; //warning conditions static const char* notice; //normal but significant condition static const char* info; //informational static const char* debug; //debug/trace info for developers }; class FPLOG_API Message { friend class Fplog_Impl; friend class fplogd::Impl; public: struct FPLOG_API Mandatory_Fields { static const char* facility; //according to syslog static const char* priority; //same as severity for syslog static const char* timestamp; //ISO8601 timestamp with milliseconds and timezone static const char* hostname; //IP address or any specific sending device id, added by fplogd before sending static const char* appname; //name of application or service using this logging library, needed for fplog IPC }; struct FPLOG_API Optional_Fields { static const char* text; //log message text static const char* component; //package name or any logical software component static const char* class_name; //class name if OOP is used static const char* method; //method of a given class if OOP is used or just a function name static const char* module; //source file name static const char* line; //line number in the above mentioned source file static const char* options; //for example encryption method + options when encryption is in use static const char* encrypted; //true/false, if true then Text field contains encrypted JSON values - //the rest of the log message including the plaintext version of Text field static const char* file; //filename when sending a file inside the log message static const char* /*the*/blob; //used when attaching binary fields to the message, resulting JSON object will look //like this: "blob_name":{ "blob":"xckjhKJSHDKDSdJKShdsdsgr=" } //where "xckjhKJSHDKDSdJKShdsdsgr=" is base64 encoded binary object static const char* warning; //contains warning for the user in case there was an issue with this specific log message static const char* sequence; //sequence number that allows to prevent duplicate messages and also to tell //which message was first even if timestamps are the same static const char* batch; //indicator if this message is actually a container for N other shorter messages }; Message(const char* prio, const char *facility, const char* format = 0, ...); Message(const rapidjson::Document& msg); Message(const std::string& msg); Message(const Message &obj) { validate_params_ = obj.validate_params_; msg_.CopyFrom(obj.msg_, msg_.GetAllocator()); } Message& operator= (const Message& rhs) { validate_params_ = rhs.validate_params_; msg_.CopyFrom(rhs.msg_, msg_.GetAllocator()); return *this; } Message& set_timestamp(const char* timestamp = 0); //either sets provided timestamp or uses current system date/time if timestamp is 0 Message& add(const char* param_name, int param){ return add<int>(param_name, param); } Message& add(const char* param_name, long long int param){ return add<long long int>(param_name, param); } Message& add(const char* param_name, double param){ return add<double>(param_name, param); } Message& add(const char* param_name, std::string& param); Message& add(const char* param_name, const char* param); Message& add_binary(const char* param_name, const void* buf, size_t buf_size_bytes); //before adding JSON element make sure it has a name Message& add(rapidjson::Document& param); Message& add(const std::string& json); //here adding json object that is encoded in plaintext string Message& add_batch(rapidjson::Document& batch); bool has_batch(); rapidjson::Document get_batch(); Message& set_text(std::string& text); Message& set_text(const char* text); Message& set_class(std::string& class_name); Message& set_class(const char* class_name); Message& set_module(std::string& module); Message& set_module(const char* module); Message& set_method(std::string& method); Message& set_method(const char* method); Message& set_line(int line); Message& set_file(const char* name); std::string as_string() const; rapidjson::Document as_json(); private: Message(); template <typename T> Message& set(const char* param_name, T param) { validate_params_ = false; Message& msg(*this); try { Message& returned(add(param_name, param)); if (&msg != &returned) msg = returned; } catch(std::exception& e) { validate_params_ = true; throw e; } catch(fplog::exceptions::Generic_Exception& e) { validate_params_ = true; throw e; } validate_params_ = true; return msg; } // trim from start static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);})); return s; } // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int c) {return !std::isspace(c);}).base(), s.end()); return s; } // trim from both ends static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } template <typename T> bool is_valid(const char* param_name, T param) { if (!validate_params_) return true; if (!param_name) return false; std::string lowercased(param_name); trim(lowercased); std::transform(lowercased.begin(), lowercased.end(), lowercased.begin(), ::tolower); bool valid(std::find(reserved_names_.begin(), reserved_names_.end(), lowercased) == reserved_names_.end()); if (!valid) set(Optional_Fields::warning, "Some parameters are missing from this log message because they were malformed."); return valid; } bool is_valid(rapidjson::Document& param); template <typename T> Message& add(const char* param_name, T param) { std::string trimmed(param_name); trim(trimmed); rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> name(trimmed.c_str(), msg_.GetAllocator()); rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> v(param); if (param_name && is_valid(trimmed.c_str(), param)) { auto it(msg_.FindMember(trimmed.c_str())); if (it == msg_.MemberEnd()) msg_.AddMember(name, v, msg_.GetAllocator()); else it->value = v; } return *this; } Message& set_sequence(unsigned long long int sequence); rapidjson::Document msg_; bool validate_params_; static std::vector<std::string> reserved_names_; static void one_time_init(); }; class FPLOG_API File { public: File(const char* prio, const char* name, const void* content, size_t size); Message as_message(){ return msg_; } private: File(); File(File&); Message msg_; char* buf_; }; class FPLOG_API Filter_Base { public: Filter_Base(const char* filter_id) { if (filter_id) filter_id_ = filter_id; else filter_id_ = ""; } virtual bool should_pass(const Message& msg) = 0; std::string get_id(){ std::lock_guard<std::recursive_mutex> lock(mutex_); std::string id(filter_id_); return id; }; virtual ~Filter_Base() {} protected: std::string filter_id_; //just a human-readable name for the filter std::recursive_mutex mutex_; private: Filter_Base(); }; //You need to explicitly state messages of which priorities you need to log by using add/remove. class FPLOG_API Priority_Filter: public Filter_Base { public: Priority_Filter(const char* filter_id): Filter_Base(filter_id){ construct_numeric(); } virtual ~Priority_Filter() {} virtual bool should_pass(const Message& msg); void add(const char* prio){ if (prio) prio_.insert(prio); } void remove(const char* prio = nullptr) //by default removes all { if (prio){ std::set<std::string>::iterator it(prio_.find(prio)); if (it != prio_.end()) { prio_.erase(it); }} else prio_.clear(); } void add_all_above(const char* prio, bool inclusive = false); void add_all_below(const char* prio, bool inclusive = false); private: std::set<std::string> prio_; std::vector<std::string> prio_numeric_; void construct_numeric(); }; //One time per application call. //async_logging means that log messages are going to the queue before dispatching to the destination. //This process is faster than sync logging but it also means that if app crashes with some messages still //in the queue, those messages are lost. If you need to debug some app crash, set this parameter to false //until you find the reason for the crash. FPLOG_API void initlog(const char* appname, sprot::Basic_Transport_Interface* transport, bool async_logging = true); FPLOG_API void initlog(const char* appname, sprot::Address local, sprot::Address remote, bool async_logging = true); //One time per application call to stop logging from an application and free all associated resources. FPLOG_API void shutdownlog(); //Mandatory call from every thread that wants to log some data. Done to increase flexibility: //each thread will have its own filters configuration and can decide independently which stuff to log. //Each filter within one thread must have unique id. FPLOG_API void openlog(const char* facility, Filter_Base* filter = 0); //Optional but advised to call from each thread that logs data right before stopping and exiting the thread. //Doing this will free some memory (amount is really small) that is needed to support logging from a given thread. //Not doing closelog() does not lead to memory leak because everything will be deallocated in any case on app exit, //fplog frees its resources when implementation class instance is destroyed. FPLOG_API void closelog(); //Scope of filter-related functions is a calling thread - all manipulations will apply to calling thread only. //fplog will take ownership of the filter on adding and will deallocate it on removing, closelog() or shutdownlog(). FPLOG_API void add_filter(Filter_Base* filter); FPLOG_API void remove_filter(Filter_Base* filter); FPLOG_API Filter_Base* find_filter(const char* filter_id); FPLOG_API const char* get_facility(); //Should be used from any thread that opened logger, calling from other threads will have no effect. FPLOG_API void write(const Message& msg); FPLOG_API void change_config(const sprot::Params& config); };
38.995074
193
0.665424
[ "object", "vector", "transform" ]
d86690e990ab27a683196a56ec421ccae573bf81
30,360
h
C
libgalois/include/katana/PropertyGraph.h
aneeshdurg/katana
713ac5a12e884c691e619d50f8ea16a5a048bfad
[ "BSD-3-Clause" ]
null
null
null
libgalois/include/katana/PropertyGraph.h
aneeshdurg/katana
713ac5a12e884c691e619d50f8ea16a5a048bfad
[ "BSD-3-Clause" ]
null
null
null
libgalois/include/katana/PropertyGraph.h
aneeshdurg/katana
713ac5a12e884c691e619d50f8ea16a5a048bfad
[ "BSD-3-Clause" ]
null
null
null
#ifndef KATANA_LIBGALOIS_KATANA_PROPERTYGRAPH_H_ #define KATANA_LIBGALOIS_KATANA_PROPERTYGRAPH_H_ #include <bitset> #include <string> #include <utility> #include <vector> #include <arrow/api.h> #include <arrow/chunked_array.h> #include <arrow/type_traits.h> #include "katana/ArrowInterchange.h" #include "katana/Details.h" #include "katana/ErrorCode.h" #include "katana/NUMAArray.h" #include "katana/config.h" #include "tsuba/RDG.h" namespace katana { // TODO(amber): find a better place to put this template < typename T, typename __Unused = std::enable_if_t<std::is_arithmetic<T>::value>> auto ProjectAsArrowArray(const T* buf, const size_t len) noexcept { using ArrowDataType = typename arrow::CTypeTraits<T>::ArrowType; using ArrowArrayType = arrow::NumericArray<ArrowDataType>; return std::make_shared<ArrowArrayType>(len, arrow::Buffer::Wrap(buf, len)); } /// A graph topology represents the adjacency information for a graph in CSR /// format. class KATANA_EXPORT GraphTopology { public: using Node = uint32_t; using Edge = uint64_t; using node_iterator = boost::counting_iterator<Node>; using edge_iterator = boost::counting_iterator<Edge>; using nodes_range = StandardRange<node_iterator>; using edges_range = StandardRange<edge_iterator>; using iterator = node_iterator; GraphTopology() = default; GraphTopology(GraphTopology&&) = default; GraphTopology& operator=(GraphTopology&&) = default; GraphTopology(const GraphTopology&) = delete; GraphTopology& operator=(const GraphTopology&) = delete; GraphTopology( const Edge* adj_indices, size_t numNodes, const Node* dests, size_t numEdges) noexcept; GraphTopology(NUMAArray<Edge>&& adj_indices, NUMAArray<Node>&& dests) noexcept : adj_indices_(std::move(adj_indices)), dests_(std::move(dests)) {} static GraphTopology Copy(const GraphTopology& that) noexcept; uint64_t num_nodes() const noexcept { return adj_indices_.size(); } uint64_t num_edges() const noexcept { return dests_.size(); } const Edge* adj_data() const noexcept { return adj_indices_.data(); } const Node* dest_data() const noexcept { return dests_.data(); } /** * Checks equality against another instance of GraphTopology. * WARNING: Expensive operation due to element-wise checks on large arrays * @param that: GraphTopology instance to compare against * @returns true if topology arrays are equal */ bool Equals(const GraphTopology& that) const noexcept { if (this == &that) { return true; } if (num_nodes() != that.num_nodes()) { return false; } if (num_edges() != that.num_edges()) { return false; } return adj_indices_ == that.adj_indices_ && dests_ == that.dests_; } // Edge accessors edge_iterator edge_begin(Node node) const noexcept { return edge_iterator{node > 0 ? adj_indices_[node - 1] : 0}; } edge_iterator edge_end(Node node) const noexcept { return edge_iterator{adj_indices_[node]}; } /// Gets the edge range of some node. /// /// \param node an iterator pointing to the node to get the edge range of /// \returns iterable edge range for node. edges_range edges(const node_iterator& node) const noexcept { return edges(*node); } // TODO(amp): [[deprecated("use edges(Node node)")]] /// Gets the edge range of some node. /// /// \param node node to get the edge range of /// \returns iterable edge range for node. edges_range edges(Node node) const noexcept { return MakeStandardRange<edge_iterator>(edge_begin(node), edge_end(node)); } Node edge_dest(Edge edge_id) const noexcept { KATANA_LOG_DEBUG_ASSERT(edge_id < dests_.size()); return dests_[edge_id]; } Node edge_dest(const edge_iterator ei) const noexcept { return edge_dest(*ei); } nodes_range nodes(Node begin, Node end) const noexcept { return MakeStandardRange<node_iterator>(begin, end); } // Standard container concepts node_iterator begin() const noexcept { return node_iterator(0); } node_iterator end() const noexcept { return node_iterator(num_nodes()); } size_t size() const noexcept { return num_nodes(); } bool empty() const noexcept { return num_nodes() == 0; } private: NUMAArray<Edge> adj_indices_; NUMAArray<Node> dests_; }; /// A property graph is a graph that has properties associated with its nodes /// and edges. A property has a name and value. Its value may be a primitive /// type, a list of values or a composition of properties. /// /// A PropertyGraph is a representation of a property graph that is backed /// by persistent storage, and it may be a subgraph of a larger, global property /// graph. Another way to view a PropertyGraph is as a container for node /// and edge properties that can be serialized. /// /// The main way to load and store a property graph is via an RDG. An RDG /// manages the serialization of the various partitions and properties that /// comprise the physical representation of the logical property graph. class KATANA_EXPORT PropertyGraph { public: /// TypeSetID uniquely identifies/contains a combination/set of types /// TypeSetID is represented using 8 bits /// TypeSetID for nodes is distinct from TypeSetID for edges using TypeSetID = uint8_t; static constexpr TypeSetID kUnknownType = TypeSetID{0}; static constexpr TypeSetID kInvalidType = std::numeric_limits<TypeSetID>::max(); /// A set of TypeSetIDs using SetOfTypeSetIDs = std::bitset<std::numeric_limits<TypeSetID>::max() + 1>; /// A set of type names using SetOfTypeNames = std::unordered_set<std::string>; /// A map from TypeSetID to the set of the type names it contains using TypeSetIDToSetOfTypeNamesMap = std::vector<SetOfTypeNames>; /// A map from the type name to the set of the TypeSetIDs that contain it using TypeNameToSetOfTypeSetIDsMap = std::unordered_map<std::string, SetOfTypeSetIDs>; // Pass through topology API using node_iterator = GraphTopology::node_iterator; using edge_iterator = GraphTopology::edge_iterator; using edges_range = GraphTopology::edges_range; using iterator = GraphTopology::iterator; using Node = GraphTopology::Node; using Edge = GraphTopology::Edge; private: /// Validate performs a sanity check on the the graph after loading Result<void> Validate(); Result<void> DoWrite( tsuba::RDGHandle handle, const std::string& command_line, tsuba::RDG::RDGVersioningPolicy versioning_action); katana::Result<void> ConductWriteOp( const std::string& uri, const std::string& command_line, tsuba::RDG::RDGVersioningPolicy versioning_action); Result<void> WriteGraph( const std::string& uri, const std::string& command_line); Result<void> WriteView( const std::string& uri, const std::string& command_line); tsuba::RDG rdg_; std::unique_ptr<tsuba::RDGFile> file_; GraphTopology topology_; /// A map from the node TypeSetID to /// the set of the node type names it contains TypeSetIDToSetOfTypeNamesMap node_type_set_id_to_type_names_; /// A map from the edge TypeSetID to /// the set of the edge type names it contains TypeSetIDToSetOfTypeNamesMap edge_type_set_id_to_type_names_; /// A map from the node type name /// to the set of the node TypeSetIDs that contain it TypeNameToSetOfTypeSetIDsMap node_type_name_to_type_set_ids_; /// A map from the edge type name /// to the set of the edge TypeSetIDs that contain it TypeNameToSetOfTypeSetIDsMap edge_type_name_to_type_set_ids_; /// The node TypeSetID for each node in the graph katana::NUMAArray<TypeSetID> node_type_set_id_; /// The edge TypeSetID for each edge in the graph katana::NUMAArray<TypeSetID> edge_type_set_id_; // Keep partition_metadata, master_nodes, mirror_nodes out of the public interface, // while allowing Distribution to read/write it for RDG friend class Distribution; const tsuba::PartitionMetadata& partition_metadata() const { return rdg_.part_metadata(); } void set_partition_metadata(const tsuba::PartitionMetadata& meta) { rdg_.set_part_metadata(meta); } void update_rdg_metadata(const std::string& part_policy, uint32_t num_hosts) { rdg_.set_view_name(fmt::format("rdg-{}-part{}", part_policy, num_hosts)); } /// Per-host vector of master nodes /// /// master_nodes()[this_host].empty() is true /// master_nodes()[host_i][x] contains LocalNodeID of masters // for which host_i has a mirror const std::vector<std::shared_ptr<arrow::ChunkedArray>>& master_nodes() const { return rdg_.master_nodes(); } void set_master_nodes(std::vector<std::shared_ptr<arrow::ChunkedArray>>&& a) { rdg_.set_master_nodes(std::move(a)); } /// Per-host vector of mirror nodes /// /// mirror_nodes()[this_host].empty() is true /// mirror_nodes()[host_i][x] contains LocalNodeID of mirrors /// that have a master on host_i const std::vector<std::shared_ptr<arrow::ChunkedArray>>& mirror_nodes() const { return rdg_.mirror_nodes(); } void set_mirror_nodes(std::vector<std::shared_ptr<arrow::ChunkedArray>>&& a) { rdg_.set_mirror_nodes(std::move(a)); } /// Return the node property table for local nodes const std::shared_ptr<arrow::Table>& node_properties() const { return rdg_.node_properties(); } /// Return the edge property table for local edges const std::shared_ptr<arrow::Table>& edge_properties() const { return rdg_.edge_properties(); } public: /// PropertyView provides a uniform interface when you don't need to /// distinguish operating on edge or node properties struct ReadOnlyPropertyView { const PropertyGraph* const_g; std::shared_ptr<arrow::Schema> (PropertyGraph::*schema_fn)() const; std::shared_ptr<arrow::ChunkedArray> (PropertyGraph::*property_fn_int)( int i) const; std::shared_ptr<arrow::ChunkedArray> (PropertyGraph::*property_fn_str)( const std::string& str) const; int32_t (PropertyGraph::*property_num_fn)() const; std::shared_ptr<arrow::Schema> schema() const { return (const_g->*schema_fn)(); } std::shared_ptr<arrow::ChunkedArray> GetProperty(int i) const { return (const_g->*property_fn_int)(i); } std::shared_ptr<arrow::ChunkedArray> GetProperty( const std::string& str) const { return (const_g->*property_fn_str)(str); } int32_t GetNumProperties() const { return (const_g->*property_num_fn)(); } uint64_t ApproxMemUse() const { uint64_t total_mem_use = 0; for (int32_t i = 0; i < GetNumProperties(); ++i) { const auto& chunked_array = GetProperty(i); for (const auto& array : chunked_array->chunks()) { total_mem_use += katana::ApproxArrayMemUse(array); } } return total_mem_use; } }; struct MutablePropertyView { ReadOnlyPropertyView ropv; PropertyGraph* g; Result<void> (PropertyGraph::*add_properties_fn)( const std::shared_ptr<arrow::Table>& props); Result<void> (PropertyGraph::*upsert_properties_fn)( const std::shared_ptr<arrow::Table>& props); Result<void> (PropertyGraph::*remove_property_int)(int i); Result<void> (PropertyGraph::*remove_property_str)(const std::string& str); std::shared_ptr<arrow::Schema> schema() const { return ropv.schema(); } std::shared_ptr<arrow::ChunkedArray> GetProperty(int i) const { return ropv.GetProperty(i); } std::shared_ptr<arrow::ChunkedArray> GetProperty( const std::string& str) const { return ropv.GetProperty(str); } int32_t GetNumProperties() const { return ropv.GetNumProperties(); } uint64_t ApproxMemUse() const { return ropv.ApproxMemUse(); } Result<void> AddProperties( const std::shared_ptr<arrow::Table>& props) const { return (g->*add_properties_fn)(props); } Result<void> UpsertProperties( const std::shared_ptr<arrow::Table>& props) const { return (g->*upsert_properties_fn)(props); } Result<void> RemoveProperty(int i) const { return (g->*remove_property_int)(i); } Result<void> RemoveProperty(const std::string& str) const { return (g->*remove_property_str)(str); } }; PropertyGraph() = default; PropertyGraph( std::unique_ptr<tsuba::RDGFile>&& rdg_file, tsuba::RDG&& rdg, GraphTopology&& topo) noexcept : rdg_(std::move(rdg)), file_(std::move(rdg_file)), topology_(std::move(topo)) {} PropertyGraph(katana::GraphTopology&& topo_to_assign) noexcept : rdg_(), file_(), topology_(std::move(topo_to_assign)) {} /// Make a property graph from a constructed RDG. Take ownership of the RDG /// and its underlying resources. static Result<std::unique_ptr<PropertyGraph>> Make( std::unique_ptr<tsuba::RDGFile> rdg_file, tsuba::RDG&& rdg); /// Make a property graph from an RDG name. static Result<std::unique_ptr<PropertyGraph>> Make( const std::string& rdg_name, const tsuba::RDGLoadOptions& opts = tsuba::RDGLoadOptions()); /// Make a property graph from topology static Result<std::unique_ptr<PropertyGraph>> Make( GraphTopology&& topo_to_assign); /// \return A copy of this with the same set of properties. The copy shares no /// state with this. Result<std::unique_ptr<PropertyGraph>> Copy() const; /// \param node_properties The node properties to copy. /// \param edge_properties The edge properties to copy. /// \return A copy of this with a subset of the properties. The copy shares no /// state with this. Result<std::unique_ptr<PropertyGraph>> Copy( const std::vector<std::string>& node_properties, const std::vector<std::string>& edge_properties) const; /// Construct node & edge TypeSetIDs from node & edge properties /// Also constructs metadata to convert between types and TypeSetIDs /// Assumes all boolean or uint8 properties are types /// TODO(roshan) move this to be a part of Make() Result<void> ConstructTypeSetIDs(); const std::string& rdg_dir() const { return rdg_.rdg_dir().string(); } uint32_t partition_id() const { return rdg_.partition_id(); } // TODO(witchel): ChunkedArray is inherited from arrow::Table interface but this is // really a ChunkedArray of one chunk, change to arrow::Array. const std::shared_ptr<arrow::ChunkedArray>& host_to_owned_global_node_ids() const { return rdg_.host_to_owned_global_node_ids(); } void set_host_to_owned_global_node_ids( std::shared_ptr<arrow::ChunkedArray>&& a) { rdg_.set_host_to_owned_global_node_ids(std::move(a)); } // TODO(witchel): ChunkedArray is inherited from arrow::Table interface but this is // really a ChunkedArray of one chunk, change to arrow::Array. const std::shared_ptr<arrow::ChunkedArray>& host_to_owned_global_edge_ids() const { return rdg_.host_to_owned_global_edge_ids(); } void set_host_to_owned_global_edge_ids( std::shared_ptr<arrow::ChunkedArray>&& a) { rdg_.set_host_to_owned_global_edge_ids(std::move(a)); } // TODO(witchel): ChunkedArray is inherited from arrow::Table interface but this is // really a ChunkedArray of one chunk, change to arrow::Array. const std::shared_ptr<arrow::ChunkedArray>& local_to_user_id() const { return rdg_.local_to_user_id(); } void set_local_to_user_id(std::shared_ptr<arrow::ChunkedArray>&& a) { rdg_.set_local_to_user_id(std::move(a)); } // TODO(witchel): ChunkedArray is inherited from arrow::Table interface but this is // really a ChunkedArray of one chunk, change to arrow::Array. const std::shared_ptr<arrow::ChunkedArray>& local_to_global_id() const { return rdg_.local_to_global_id(); } void set_local_to_global_id(std::shared_ptr<arrow::ChunkedArray>&& a) { rdg_.set_local_to_global_id(std::move(a)); } /// Create a new storage location for a graph and write everything into it. /// /// \returns io_error if, for instance, a file already exists Result<void> Write( const std::string& rdg_name, const std::string& command_line); /// Commit updates modified state and re-uses graph components already in storage. /// /// Like \ref Write(const std::string&, const std::string&) but can only update /// parts of the original read location of the graph. Result<void> Commit(const std::string& command_line); Result<void> WriteView(const std::string& command_line); /// Tell the RDG where it's data is coming from Result<void> InformPath(const std::string& input_path); /// Determine if two PropertyGraphs are Equal bool Equals(const PropertyGraph* other) const; /// Report the differences between two graphs std::string ReportDiff(const PropertyGraph* other) const; std::shared_ptr<arrow::Schema> node_schema() const { return node_properties()->schema(); } std::shared_ptr<arrow::Schema> edge_schema() const { return edge_properties()->schema(); } /// \returns the number of node types size_t GetNodeTypesNum() const { return node_type_name_to_type_set_ids_.size(); } /// \returns the number of edge types size_t GetEdgeTypesNum() const { return edge_type_name_to_type_set_ids_.size(); } /// \returns true if a node type with @param name exists /// NB: no node may have this type /// TODO(roshan) build an index for the number of nodes with the type bool HasNodeType(const std::string& name) const { return node_type_name_to_type_set_ids_.count(name) == 1; } /// \returns true if an edge type with @param name exists /// NB: no edge may have this type /// TODO(roshan) build an index for the number of edges with the type bool HasEdgeType(const std::string& name) const { return edge_type_name_to_type_set_ids_.count(name) == 1; } /// \returns the set of node TypeSetIDs that contain /// the node type with @param name /// (assumes that the node type exists) const SetOfTypeSetIDs& NodeTypeNameToTypeSetIDs( const std::string& name) const { return node_type_name_to_type_set_ids_.at(name); } /// \returns the set of edge TypeSetIDs that contain /// the edge type with @param name /// (assumes that the edge type exists) const SetOfTypeSetIDs& EdgeTypeNameToTypeSetIDs( const std::string& name) const { return edge_type_name_to_type_set_ids_.at(name); } /// \returns the number of node TypeSetIDs (including kUnknownType) size_t GetNodeTypeSetIDsNum() const { return node_type_set_id_to_type_names_.size(); } /// \returns the number of edge TypeSetIDs (including kUnknownType) size_t GetEdgeTypeSetIDsNum() const { return edge_type_set_id_to_type_names_.size(); } /// \returns the set of node type names that contain /// the node TypeSetID @param node_type_set_id /// (assumes that the node TypeSetID exists) const SetOfTypeNames& NodeTypeSetIDToTypeNames( TypeSetID node_type_set_id) const { return node_type_set_id_to_type_names_.at(node_type_set_id); } /// \returns the set of edge type names that contain /// the edge TypeSetID @param edge_type_set_id /// (assumes that the edge TypeSetID exists) const SetOfTypeNames& EdgeTypeSetIDToTypeNames( TypeSetID edge_type_set_id) const { return edge_type_set_id_to_type_names_.at(edge_type_set_id); } /// \return returns the node TypeSetID for @param node TypeSetID GetNodeTypeSetID(Node node) const { return node_type_set_id_[node]; } /// \return returns the edge TypeSetID for @param edge TypeSetID GetEdgeTypeSetID(Edge edge) const { return edge_type_set_id_[edge]; } // Return type dictated by arrow /// Returns the number of node properties int32_t GetNumNodeProperties() const { return node_schema()->num_fields(); } /// Returns the number of edge properties int32_t GetNumEdgeProperties() const { return edge_schema()->num_fields(); } // num_rows() == num_nodes() (all local nodes) std::shared_ptr<arrow::ChunkedArray> GetNodeProperty(int i) const { if (i >= node_properties()->num_columns()) { return nullptr; } return node_properties()->column(i); } // num_rows() == num_edges() (all local edges) std::shared_ptr<arrow::ChunkedArray> GetEdgeProperty(int i) const { if (i >= edge_properties()->num_columns()) { return nullptr; } return edge_properties()->column(i); } /// \returns true if a node property/type with @param name exists bool HasNodeProperty(const std::string& name) const { return node_schema()->GetFieldIndex(name) != -1; } /// \returns true if an edge property/type with @param name exists bool HasEdgeProperty(const std::string& name) const { return edge_schema()->GetFieldIndex(name) != -1; } /// Get a node property by name. /// /// \param name The name of the property to get. /// \return The property data or NULL if the property is not found. std::shared_ptr<arrow::ChunkedArray> GetNodeProperty( const std::string& name) const { return node_properties()->GetColumnByName(name); } std::string GetNodePropertyName(int32_t i) const { return node_schema()->field(i)->name(); } std::shared_ptr<arrow::ChunkedArray> GetEdgeProperty( const std::string& name) const { return edge_properties()->GetColumnByName(name); } std::string GetEdgePropertyName(int32_t i) const { return edge_schema()->field(i)->name(); } /// Get a node property by name and cast it to a type. /// /// \tparam T The type of the property. /// \param name The name of the property. /// \return The property array or an error if the property does not exist or has a different type. template <typename T> Result<std::shared_ptr<typename arrow::CTypeTraits<T>::ArrayType>> GetNodePropertyTyped(const std::string& name) { auto chunked_array = GetNodeProperty(name); if (!chunked_array) { return ErrorCode::PropertyNotFound; } auto array = std::dynamic_pointer_cast<typename arrow::CTypeTraits<T>::ArrayType>( chunked_array->chunk(0)); if (!array) { return ErrorCode::TypeError; } return array; } /// Get an edge property by name and cast it to a type. /// /// \tparam T The type of the property. /// \param name The name of the property. /// \return The property array or an error if the property does not exist or has a different type. template <typename T> Result<std::shared_ptr<typename arrow::CTypeTraits<T>::ArrayType>> GetEdgePropertyTyped(const std::string& name) { auto chunked_array = GetEdgeProperty(name); if (!chunked_array) { return ErrorCode::PropertyNotFound; } auto array = std::dynamic_pointer_cast<typename arrow::CTypeTraits<T>::ArrayType>( chunked_array->chunk(0)); if (!array) { return ErrorCode::TypeError; } return array; } void MarkAllPropertiesPersistent() { return rdg_.MarkAllPropertiesPersistent(); } /// MarkNodePropertiesPersistent indicates which node properties will be /// serialized when this graph is written. /// /// Properties are "named" by position, so an empty string means don't persist that /// property. Result<void> MarkNodePropertiesPersistent( const std::vector<std::string>& persist_node_props) { return rdg_.MarkNodePropertiesPersistent(persist_node_props); } Result<void> MarkEdgePropertiesPersistent( const std::vector<std::string>& persist_edge_props) { return rdg_.MarkEdgePropertiesPersistent(persist_edge_props); } const GraphTopology& topology() const noexcept { return topology_; } /// Add Node properties that do not exist in the current graph Result<void> AddNodeProperties(const std::shared_ptr<arrow::Table>& props); /// Add Edge properties that do not exist in the current graph Result<void> AddEdgeProperties(const std::shared_ptr<arrow::Table>& props); /// If property name exists, replace it, otherwise insert it Result<void> UpsertNodeProperties(const std::shared_ptr<arrow::Table>& props); /// If property name exists, replace it, otherwise insert it Result<void> UpsertEdgeProperties(const std::shared_ptr<arrow::Table>& props); Result<void> RemoveNodeProperty(int i); Result<void> RemoveNodeProperty(const std::string& prop_name); Result<void> RemoveEdgeProperty(int i); Result<void> RemoveEdgeProperty(const std::string& prop_name); /// Remove all node properties void DropNodeProperties() { rdg_.DropNodeProperties(); } /// Remove all edge properties void DropEdgeProperties() { rdg_.DropEdgeProperties(); } MutablePropertyView NodeMutablePropertyView() { return MutablePropertyView{ .ropv = { .const_g = this, .schema_fn = &PropertyGraph::node_schema, .property_fn_int = &PropertyGraph::GetNodeProperty, .property_fn_str = &PropertyGraph::GetNodeProperty, .property_num_fn = &PropertyGraph::GetNumNodeProperties, }, .g = this, .add_properties_fn = &PropertyGraph::AddNodeProperties, .upsert_properties_fn = &PropertyGraph::UpsertNodeProperties, .remove_property_int = &PropertyGraph::RemoveNodeProperty, .remove_property_str = &PropertyGraph::RemoveNodeProperty, }; } ReadOnlyPropertyView NodeReadOnlyPropertyView() const { return ReadOnlyPropertyView{ .const_g = this, .schema_fn = &PropertyGraph::node_schema, .property_fn_int = &PropertyGraph::GetNodeProperty, .property_fn_str = &PropertyGraph::GetNodeProperty, .property_num_fn = &PropertyGraph::GetNumNodeProperties, }; } MutablePropertyView EdgeMutablePropertyView() { return MutablePropertyView{ .ropv = { .const_g = this, .schema_fn = &PropertyGraph::edge_schema, .property_fn_int = &PropertyGraph::GetEdgeProperty, .property_fn_str = &PropertyGraph::GetEdgeProperty, .property_num_fn = &PropertyGraph::GetNumEdgeProperties, }, .g = this, .add_properties_fn = &PropertyGraph::AddEdgeProperties, .upsert_properties_fn = &PropertyGraph::UpsertEdgeProperties, .remove_property_int = &PropertyGraph::RemoveEdgeProperty, .remove_property_str = &PropertyGraph::RemoveEdgeProperty, }; } ReadOnlyPropertyView EdgeReadOnlyPropertyView() const { return ReadOnlyPropertyView{ .const_g = this, .schema_fn = &PropertyGraph::edge_schema, .property_fn_int = &PropertyGraph::GetEdgeProperty, .property_fn_str = &PropertyGraph::GetEdgeProperty, .property_num_fn = &PropertyGraph::GetNumEdgeProperties, }; } // Standard container concepts node_iterator begin() const { return topology().begin(); } node_iterator end() const { return topology().end(); } /// Return the number of local nodes size_t size() const { return topology().size(); } bool empty() const { return topology().empty(); } /// Return the number of local nodes /// num_nodes in repartitioner is of type LocalNodeID uint64_t num_nodes() const { return topology().num_nodes(); } /// Return the number of local edges uint64_t num_edges() const { return topology().num_edges(); } /// Gets the edge range of some node. /// /// \param node node to get the edge range of /// \returns iterable edge range for node. edges_range edges(Node node) const { return topology().edges(node); } /** * Gets the destination for an edge. * * @param edge edge iterator to get the destination of * @returns node iterator to the edge destination */ node_iterator GetEdgeDest(const edge_iterator& edge) const { auto node_id = topology().edge_dest(*edge); return node_iterator(node_id); } }; /// SortAllEdgesByDest sorts edges for each node by destination /// IDs (ascending order). /// /// Returns the permutation vector (mapping from old /// indices to the new indices) which results due to sorting. KATANA_EXPORT Result<std::unique_ptr<katana::NUMAArray<uint64_t>>> SortAllEdgesByDest(PropertyGraph* pg); /// FindEdgeSortedByDest finds the "node_to_find" id in the /// sorted edgelist of the "node" using binary search. /// /// This returns the matched edge index if 'node_to_find' is present /// in the edgelist of 'node' else edge end if 'node_to_find' is not found. // TODO(amber): make this a method of a sorted topology class in the near future // TODO(amber): this method should return an edge_iterator KATANA_EXPORT GraphTopology::Edge FindEdgeSortedByDest( const PropertyGraph* graph, GraphTopology::Node node, GraphTopology::Node node_to_find); /// Relabel all nodes in the graph by sorting in the descending /// order by node degree. // TODO(amber): this method should return a new sorted topology KATANA_EXPORT Result<void> SortNodesByDegree(PropertyGraph* pg); /// Creates in-memory symmetric (or undirected) graph. /// /// This function creates an symmetric or undirected version of the /// PropertyGraph topology by adding reverse edges in-memory. /// /// For each edge (a, b) in the graph, this function will /// add an additional edge (b, a) except when a == b, in which /// case, no additional edge is added. /// The generated symmetric graph may have duplicate edges. /// \param pg The original property graph /// \return The new symmetric property graph by adding reverse edges // TODO(amber): this function should return a new topology KATANA_EXPORT Result<std::unique_ptr<katana::PropertyGraph>> CreateSymmetricGraph(PropertyGraph* pg); /// Creates in-memory transpose graph. /// /// This function creates transpose version of the /// PropertyGraph topology by reversing the edges in-memory. /// /// For each edge (a, b) in the graph, this function will /// add edge (b, a) without retaining the original edge (a, b) unlike /// CreateSymmetricGraph. /// \param topology The original property graph topology /// \return The new transposed property graph by reversing the edges // TODO(lhc): hack for bfs-direct-opt // TODO(amber): this function should return a new topology KATANA_EXPORT Result<std::unique_ptr<PropertyGraph>> CreateTransposeGraphTopology(const GraphTopology& topology); } // namespace katana #endif
36.229117
100
0.710013
[ "vector" ]
d86c5e244b6fe923841636a01d98146786530c5f
9,799
c
C
commdir/main.c
gom7745/Commdir
a1b4504d1764994ce776068cc66294d73b406b21
[ "BSD-3-Clause" ]
null
null
null
commdir/main.c
gom7745/Commdir
a1b4504d1764994ce776068cc66294d73b406b21
[ "BSD-3-Clause" ]
null
null
null
commdir/main.c
gom7745/Commdir
a1b4504d1764994ce776068cc66294d73b406b21
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include "util.h" #include "commdir.h" void logistic_loss_function(double z, double *value) { double v; if(z>=0) v = log(1+exp(-z)); else v = -z+log(1+exp(z)); *value = v; } void logistic_loss_derivatives(double z, double *first, double *second) { double sigma = 1/(1+exp(-z)); *first = sigma - 1; *second = (1-sigma)*sigma; } struct Loss logistic_loss = { .function = logistic_loss_function, .derivatives = logistic_loss_derivatives }; void l2_loss_function(double z, double *value) { if(1-z <= 0) *value = 0; else *value = (1-z)*(1-z); } void l2_loss_derivatives(double z, double *first, double *second) { if(1-z <= 0){ *first = *second = 0; }else{ *first = -2*(1-z); *second = 2; } } struct Loss l2_loss = { .function = l2_loss_function, .derivatives = l2_loss_derivatives }; enum {L2_HINGE_LOSS, LOGISTIC_LOSS, NR_LOSS}; char loss_name[][100] = { "L2 Hinge Loss : max(1-yi w'xi)^2", "Logistic Loss : log(1+exp(-yi w'xi))" }; Loss loss_from_type(int type) { if(type == LOGISTIC_LOSS){ return logistic_loss; }else if(type == L2_HINGE_LOSS){ return l2_loss; }else{ fprintf(stderr, "No such loss\n"); exit(1); } } void main_predict_exit_with_help(const char *prog_name) { printf("%s test_file model_file output_file\n", prog_name); exit(1); } int main_predict(int argc, const char **argv) { const char *prog_name = argv[0]; if(argc < 4) main_predict_exit_with_help(prog_name); FILE *test_file = fopen_or_abort(argv[1], "r"); FILE *model_file = fopen_or_abort(argv[2], "r"); FILE *output_file = fopen_or_abort(argv[3], "w"); Model model; load_model(model_file, &model); Data data; read_data(test_file, model.bias, &data); int l_with_label = 0, acc = 0; for(int i=0; i<data.l; i++){ const Fnode *sparse_x = NULL; double *dense_x = NULL; if(data.sparse_x != NULL) sparse_x = data.sparse_x[i]; if(data.dense_x != NULL) dense_x = data.dense_x[i]; int predict_label, target_label = data.y[i]; double value; predict_value(model, sparse_x, dense_x, &predict_label, &value); fprintf(output_file, "%d\n", predict_label); if(target_label != NO_LABEL) l_with_label ++; if(predict_label == target_label) acc++; } if(l_with_label != 0) printf("Accuracy = %.3f%% (%d/%d)\n", acc*100./l_with_label, acc, l_with_label); free_data(&data); free_model(&model); fclose(test_file); fclose(model_file); fclose(output_file); return 0; } struct nheavy_param { const char *prog_name; const char *data_fname; FILE *data_file; const char *test_fname; FILE *test_file; char model_fname[FNAME_MAX]; FILE *model_file; int to_log; int loss_type; double C; double eps; double bias; int bias_setted; int m; int max_inner; }; void exit_with_help(struct nheavy_param *p) { printf("%s [options] training_set_file [model_file]\n", p->prog_name); printf("\n"); printf("-l loss_type : set type of loss function (default %d)\n", p->loss_type); for(int i=0; i<NR_LOSS; i++){ printf("\t%d -- %s\n", i, loss_name[i]); } printf("\n"); printf("-c cost : set cost parameter (default %.2f)\n", p->C); printf("-e eps : set eps of stopping condition (default %.2f)\n", p->eps); printf("-m m : set number of descending direction (default auto tune)\n"); printf("-B bias : if bias > 0, instance becomes [x; bias];" " (default -1)\n"); printf("-i : max inner iteration > 0 (default ulimited)\n"); printf("\n"); printf("-x test_set_file : set test set file (default none)\n"); //printf("-z binary_data : use binary data; write one if not exists\n"); printf("\n"); printf("default stopping threshold : |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2\n"); exit(1); } void parse_arguments(int argc, const char **argv, struct nheavy_param *p) { struct nheavy_param def = { .prog_name = p->prog_name, .to_log = 0, .loss_type = L2_HINGE_LOSS, .C = 1, .eps = 0.01, .bias = -1, .bias_setted = 0, .m = 0, .max_inner = 0, .test_file = NULL, .test_fname = NULL }; *p = def; int i; for(i=1; i<argc; i++){ if(argv[i][0] != '-') break; const char *cmd = argv[i]+1; if(++i >= argc) exit_with_help(&def); const char *value = argv[i]; if(strcmp("", cmd) == 0){ }else if(strcmp("l", cmd) == 0){ int d = atoi(value); if(!(0 <= d && d < NR_LOSS)) exit_with_help(&def); p->loss_type = d; }else if(strcmp("c", cmd) == 0){ p->C = atof(value); }else if(strcmp("e", cmd) == 0){ p->eps = atof(value); }else if(strcmp("B", cmd) == 0){ p->bias = atof(value); p->bias_setted = 1; }else if(strcmp("i", cmd) == 0){ p->max_inner = atoi(value); if(p->max_inner <= 0) exit_with_help(&def); }else if(strcmp("n", cmd) == 0){ p->m = atoi(value); if(p->m < 0) exit_with_help(&def); }else if(strcmp("x", cmd) == 0){ p->test_fname = value; p->test_file = fopen_or_abort(value, "r"); }else{ exit_with_help(&def); } } // open data file if(i >= argc) exit_with_help(&def); p->data_fname = argv[i]; p->data_file = fopen_or_abort(p->data_fname, "r"); i++; // open model file if(i < argc){ strncpy(p->model_fname, argv[i], FNAME_MAX); }else{ sprintf(p->model_fname, "%s.hmodel", p->data_fname); } p->model_file = fopen_or_abort(p->model_fname, "w"); } int64_t read_data_and_summarize(FILE *fin, double bias, Data *data) { int64_t time_st, time_ed; time_st = wall_clock_ns(); read_data(fin, bias, data); int nnz = data->nd * data->l; if(data->sparse_x != NULL) nnz += data->nr_fnode - data->l; lprintf("l = %d n = %d nnz = %d (sparsity=%.2e, nnz/l=%.2e, nnz/n=%.2e)\n", data->l, data->n, nnz, nnz*1./data->l/data->n, nnz*1./data->l, nnz*1./data->n); fclose(fin); time_ed = wall_clock_ns(); return time_ed - time_st; } int main_train(int argc, const char** argv) { struct nheavy_param p; p.prog_name = argv[0]; parse_arguments(argc, argv, &p); if(p.to_log) start_logging(p.data_fname); int64_t prog_st, prog_ed; int64_t loading_time, prog_time; prog_st = wall_clock_ns(); Data data; loading_time = read_data_and_summarize(p.data_file, p.bias, &data); Loss loss = loss_from_type(p.loss_type); lprintf("Solving %s\n", loss_name[p.loss_type]); Param param = { .loss_type = p.loss_type, .loss = loss, .C = p.C, .eps = p.eps, .m = p.m, .max_inner = p.max_inner }; Model model; train(data, param, &model); prog_ed = wall_clock_ns(); prog_time = prog_ed - prog_st; lprintf("\nrunning time: %fs loading=%f%%\n", wall_time_diff(prog_ed, prog_st), (double)loading_time*100./(double)prog_time); return 0; int acc = predict_accurate(model, data); lprintf("accuracy = %.2f%%(%d/%d)\n", (double)acc/data.l*100, acc, data.l); if(p.test_file != NULL){ Data test_data; read_data(p.test_file, p.bias, &test_data); acc = predict_accurate(model, test_data); lprintf("test accuracy = %.2f%%(%d/%d)\n", (double)acc/test_data.l*100, acc, test_data.l); free_data(&test_data); } save_model(p.model_file, model); fclose(p.model_file); free_data(&data); free_model(&model); end_logging(); return 0; } int main(int argc, const char **argv) { srandom(0); if(strcmp("npredict", basename(argv[0])) == 0) return main_predict(argc, argv); else return main_train(argc, argv); }
30.150769
106
0.481274
[ "model" ]
d870bace1632af0a6b88a40db8667d0502579b6d
1,643
h
C
courses/su/cse775/project1/DOProject1_Windows/TextSearch/TextSearch.h
wuyuMk7/everything
4e093e5b0eda4f1788a25b0a78973f6fe9a480a5
[ "MIT" ]
3
2020-02-04T15:19:00.000Z
2021-01-18T17:55:14.000Z
courses/su/cse775/project1/DOProject1_Windows/TextSearch/TextSearch.h
wuyuMk7/everything
4e093e5b0eda4f1788a25b0a78973f6fe9a480a5
[ "MIT" ]
1
2022-02-12T09:34:53.000Z
2022-02-12T09:34:53.000Z
courses/su/cse775/project1/DOProject1_Windows/TextSearch/TextSearch.h
wuyuMk7/everything
4e093e5b0eda4f1788a25b0a78973f6fe9a480a5
[ "MIT" ]
null
null
null
// TextSearch.h : Declaration of the CTextSearch #pragma once #include "resource.h" // main symbols #include "TextSearch_i.h" #include "atlcomcli.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." #endif using namespace ATL; // CTextSearch class ATL_NO_VTABLE CTextSearch : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CTextSearch, &CLSID_TextSearch>, public ITextSearch { public: CTextSearch() : pFileManager_(NULL) { } DECLARE_REGISTRY_RESOURCEID(IDR_TEXTSEARCH1) DECLARE_NOT_AGGREGATABLE(CTextSearch) BEGIN_COM_MAP(CTextSearch) COM_INTERFACE_ENTRY(ITextSearch) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: private: IUnknown* pFileManager_; public: STDMETHOD(sendPattern)(BSTR pattern); private: CComBSTR pattern_; public: STDMETHOD(getResult)(VARIANT* filePath, VARIANT* searchResult); STDMETHOD(sendFileManager)(IUnknown* pFileManager); }; OBJECT_ENTRY_AUTO(__uuidof(TextSearch), CTextSearch)
23.471429
473
0.757152
[ "object", "model" ]
9cacb5202983bf375233dcffd494a305dceb43d6
1,492
h
C
src/objects/basic/trace.h
TravisWheelerLab/MMOREseqs
492eda6efa4fd95ac0a787405a40db5a860bf3dc
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/objects/basic/trace.h
TravisWheelerLab/MMOREseqs
492eda6efa4fd95ac0a787405a40db5a860bf3dc
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/objects/basic/trace.h
TravisWheelerLab/MMOREseqs
492eda6efa4fd95ac0a787405a40db5a860bf3dc
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * - FILE: trace.c * - DESC: TRACE Object *******************************************************************************/ #ifndef _TRACE_H #define _TRACE_H /*! FUNCTION: TRACE_Create() * SYNOPSIS: Create an instance of <data>. */ TRACE TRACE_Create(const TRACE data); /*! FUNCTION: TRACE_Destroy() * SYNOPSIS: Destroy instance of <data>. */ TRACE TRACE_Destroy(TRACE data); /*! FUNCTION: TRACE_Clear() * SYNOPSIS: Clear <data>. If pointer data, sets to null. Otherwise, do * nothing. */ TRACE TRACE_Clear(TRACE data); /*! FUNCTION: TRACE_ToString() * SYNOPSIS: Create a string representation of data <d>. * Stores it in a char* buffer <buf>. * * RETURN: Pointer to <buf> */ char* TRACE_ToString(const TRACE data, char* buf); /*! FUNCTION: TRACE_FromString() * SYNOPSIS: Extracts data from string. * * RETURN: Pointer to <buf> */ TRACE TRACE_FromString(char* str); /*! FUNCTION: TRACE_Compare() * SYNOPSIS: Compare <a> and <b>. * * RETURN: POS if (a > b), * 0 if equal, * NEG if (a < b) */ int TRACE_Compare(const TRACE a, const TRACE b); /*! FUNCTION: TRACE_CompareTo() * SYNOPSIS: Generic compare. Casts then compares <a> and <b>. * RETURN: POS if (a > b), * 0 if equal, * NEG if (a < b) */ int TRACE_CompareTo(const void* a, const void* b); #endif /* _TRACE_H */
24.064516
81
0.543566
[ "object" ]
9cb8874ba921cc2789ed50156ad676c1e18ba6d1
7,161
c
C
third_party/tap-windows6/src/tapdrvr.c
clementhk/outline-client
2f4251a7e2d862038e085d1badf0d91627253536
[ "Apache-2.0" ]
7,353
2018-03-20T13:46:41.000Z
2022-03-31T14:33:14.000Z
third_party/tap-windows6/src/tapdrvr.c
shipangzi/outline-client
f629c1bc9df736ed853895b4b792f7946b594f99
[ "Apache-2.0" ]
835
2018-03-21T06:01:59.000Z
2022-03-31T12:23:24.000Z
third_party/tap-windows6/src/tapdrvr.c
shipangzi/outline-client
f629c1bc9df736ed853895b4b792f7946b594f99
[ "Apache-2.0" ]
1,364
2018-03-21T05:30:01.000Z
2022-03-31T10:27:39.000Z
/* * TAP-Windows -- A kernel driver to provide virtual tap * device functionality on Windows. * * This code was inspired by the CIPE-Win32 driver by Damion K. Wilson. * * This source code is Copyright (C) 2002-2014 OpenVPN Technologies, Inc., * and is released under the GPL version 2 (see below). * * 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 (see the file COPYING included with this * distribution); if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //====================================================== // This driver is designed to work on Windows Vista or higher // versions of Windows. // // It is SMP-safe and handles power management. // // By default we operate as a "tap" virtual ethernet // 802.3 interface, but we can emulate a "tun" // interface (point-to-point IPv4) through the // TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT or // TAP_WIN_IOCTL_CONFIG_TUN ioctl. //====================================================== // // Include files. // #include <string.h> #include "tap.h" // Global data TAP_GLOBAL GlobalData; #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #pragma alloc_text(PAGE, TapDriverUnload) #endif // ALLOC_PRAGMA NTSTATUS DriverEntry(__in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath) /*++ Routine Description: In the context of its DriverEntry function, a miniport driver associates itself with NDIS, specifies the NDIS version that it is using, and registers its entry points. Arguments: PVOID DriverObject - pointer to the driver object. PVOID RegistryPath - pointer to the driver registry path. Return Value: NTSTATUS code --*/ { NTSTATUS status; UNREFERENCED_PARAMETER(RegistryPath); DEBUGP(("[TAP] --> DriverEntry; version [%d.%d] %s %s\n", TAP_DRIVER_MAJOR_VERSION, TAP_DRIVER_MINOR_VERSION, __DATE__, __TIME__)); DEBUGP(("[TAP] Registry Path: '%wZ'\n", RegistryPath)); // // Initialize any driver-global variables here. // NdisZeroMemory(&GlobalData, sizeof(GlobalData)); // // The ApaterList in the GlobalData structure is used to track multiple // adapters controlled by this miniport. // NdisInitializeListHead(&GlobalData.AdapterList); // // This lock protects the AdapterList. // NdisInitializeReadWriteLock(&GlobalData.Lock); do { NDIS_MINIPORT_DRIVER_CHARACTERISTICS miniportCharacteristics; NdisZeroMemory(&miniportCharacteristics, sizeof(miniportCharacteristics)); { C_ASSERT(sizeof(miniportCharacteristics) >= NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2); } miniportCharacteristics.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_DRIVER_CHARACTERISTICS; miniportCharacteristics.Header.Size = NDIS_SIZEOF_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; miniportCharacteristics.Header.Revision = NDIS_MINIPORT_DRIVER_CHARACTERISTICS_REVISION_2; miniportCharacteristics.MajorNdisVersion = TAP_NDIS_MAJOR_VERSION; miniportCharacteristics.MinorNdisVersion = TAP_NDIS_MINOR_VERSION; miniportCharacteristics.MajorDriverVersion = TAP_DRIVER_MAJOR_VERSION; miniportCharacteristics.MinorDriverVersion = TAP_DRIVER_MINOR_VERSION; miniportCharacteristics.Flags = 0; // miniportCharacteristics.SetOptionsHandler = MPSetOptions; // Optional miniportCharacteristics.InitializeHandlerEx = AdapterCreate; miniportCharacteristics.HaltHandlerEx = AdapterHalt; miniportCharacteristics.UnloadHandler = TapDriverUnload; miniportCharacteristics.PauseHandler = AdapterPause; miniportCharacteristics.RestartHandler = AdapterRestart; miniportCharacteristics.OidRequestHandler = AdapterOidRequest; miniportCharacteristics.SendNetBufferListsHandler = AdapterSendNetBufferLists; miniportCharacteristics.ReturnNetBufferListsHandler = AdapterReturnNetBufferLists; miniportCharacteristics.CancelSendHandler = AdapterCancelSend; miniportCharacteristics.CheckForHangHandlerEx = AdapterCheckForHangEx; miniportCharacteristics.ResetHandlerEx = AdapterReset; miniportCharacteristics.DevicePnPEventNotifyHandler = AdapterDevicePnpEventNotify; miniportCharacteristics.ShutdownHandlerEx = AdapterShutdownEx; miniportCharacteristics.CancelOidRequestHandler = AdapterCancelOidRequest; // // Associate the miniport driver with NDIS by calling the // NdisMRegisterMiniportDriver. This function returns an NdisDriverHandle. // The miniport driver must retain this handle but it should never attempt // to access or interpret this handle. // // By calling NdisMRegisterMiniportDriver, the driver indicates that it // is ready for NDIS to call the driver's MiniportSetOptions and // MiniportInitializeEx handlers. // DEBUGP(("[TAP] Calling NdisMRegisterMiniportDriver...\n")); // NDIS_DECLARE_MINIPORT_DRIVER_CONTEXT(TAP_GLOBAL); status = NdisMRegisterMiniportDriver(DriverObject, RegistryPath, &GlobalData, &miniportCharacteristics, &GlobalData.NdisDriverHandle); if (NDIS_STATUS_SUCCESS == status) { DEBUGP(("[TAP] Registered miniport successfully\n")); } else { DEBUGP(("[TAP] NdisMRegisterMiniportDriver failed: %8.8X\n", status)); TapDriverUnload(DriverObject); status = NDIS_STATUS_FAILURE; break; } } while (FALSE); DEBUGP(("[TAP] <-- DriverEntry; status = %8.8X\n", status)); return status; } VOID TapDriverUnload(__in PDRIVER_OBJECT DriverObject) /*++ Routine Description: The unload handler is called during driver unload to free up resources acquired in DriverEntry. This handler is registered in DriverEntry through NdisMRegisterMiniportDriver. Note that an unload handler differs from a MiniportHalt function in that this unload handler releases resources that are global to the driver, while the halt handler releases resource for a particular adapter. Runs at IRQL = PASSIVE_LEVEL. Arguments: DriverObject Not used Return Value: None. --*/ { PDEVICE_OBJECT deviceObject = DriverObject->DeviceObject; UNICODE_STRING uniWin32NameString; DEBUGP(("[TAP] --> TapDriverUnload; version [%d.%d] %s %s unloaded\n", TAP_DRIVER_MAJOR_VERSION, TAP_DRIVER_MINOR_VERSION, __DATE__, __TIME__)); PAGED_CODE(); // // Clean up all globals that were allocated in DriverEntry // ASSERT(IsListEmpty(&GlobalData.AdapterList)); if (GlobalData.NdisDriverHandle != NULL) { NdisMDeregisterMiniportDriver(GlobalData.NdisDriverHandle); } DEBUGP(("[TAP] <-- TapDriverUnload\n")); }
34.1
98
0.739143
[ "object" ]
9cc1d7caf451169c6cf2ff275b7f22744c2e2ab7
8,627
h
C
libdts/src/collision/abstractPolyList.h
jamesu/libDTShape
d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5
[ "MIT" ]
2
2019-05-14T07:55:45.000Z
2020-12-31T11:06:27.000Z
libdts/src/collision/abstractPolyList.h
jamesu/libDTShape
d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5
[ "MIT" ]
null
null
null
libdts/src/collision/abstractPolyList.h
jamesu/libDTShape
d6bd9a705fb45ac1dc95a04ac0096fc724fd14b5
[ "MIT" ]
3
2016-09-11T03:08:56.000Z
2019-05-14T07:55:48.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef _ABSTRACTPOLYLIST_H_ #define _ABSTRACTPOLYLIST_H_ #ifndef _MMATH_H_ #include "math/mMath.h" #endif #ifndef _MPLANETRANSFORMER_H_ #include "math/mPlaneTransformer.h" #endif #ifndef _TVECTOR_H_ #include "core/util/tVector.h" #endif //----------------------------------------------------------------------------- BEGIN_NS(DTShape) class SceneObject; class TSMaterialInstance; /// A polygon filtering interface. /// /// The various AbstractPolyList subclasses are used in Torque as an interface to /// handle spatial queries. SceneObject::buildPolyList() takes an implementor of /// AbstractPolyList (such as ConcretePolyList, ClippedPolyList, etc.) and a /// bounding volume. The function runs geometry data from all the objects in the /// bounding volume through the passed PolyList. /// /// This interface only provides a method to get data INTO your implementation. Different /// subclasses provide different interfaces to get data back out, depending on their /// specific quirks. /// /// The physics engine now uses convex hulls for collision detection. /// /// @see Convex class AbstractPolyList { protected: // User set state SceneObject* mCurrObject; MatrixF mBaseMatrix; // Base transform MatrixF mTransformMatrix; // Current object transform MatrixF mMatrix; // Base * current transform Point3F mScale; PlaneTransformer mPlaneTransformer; bool mInterestNormalRegistered; Point3F mInterestNormal; public: AbstractPolyList(); virtual ~AbstractPolyList(); /// @name Common Interface /// @{ void setBaseTransform(const MatrixF& mat); /// Sets the transform applying to the current stream of /// vertices. /// /// @param mat Transformation of the object. (in) /// @param scale Scaling of the object. (in) void setTransform(const MatrixF* mat, const Point3F& scale); /// Gets the transform applying to the current stream of /// vertices. /// /// @param mat Transformation of the object. (out) /// @param scale Scaling of the object. (out) void getTransform(MatrixF* mat, Point3F * scale); /// This is called by the object which is currently feeding us /// vertices, to tell us who it is. void setObject(SceneObject*); /// Add a box via the query interface (below). This wraps some calls /// to addPoint and addPlane. void addBox(const Box3F &box, TSMaterialInstance* material = NULL); void doConstruct(); /// @} /// @name Query Interface /// /// It is through this interface that geometry data is fed to the /// PolyList. The order of calls are: /// - begin() /// - One or more calls to vertex() and one call to plane(), in any order. /// - end() /// /// @code /// // Example code that adds data to a PolyList. /// // See AbstractPolyList::addBox() for the function this was taken from. /// /// // First, we add points... (note that we use base to track the start of adding.) /// U32 base = addPoint(pos); /// pos.y += dy; addPoint(pos); /// pos.x += dx; addPoint(pos); /// pos.y -= dy; addPoint(pos); /// pos.z += dz; addPoint(pos); /// pos.x -= dx; addPoint(pos); /// pos.y += dy; addPoint(pos); /// pos.x += dx; addPoint(pos); /// /// // Now we add our surfaces. (there are six, as we are adding a cube here) /// for (S32 i = 0; i < 6; i++) { /// // Begin a surface /// begin(0,i); /// /// // Calculate the vertex ids; we have a lookup table to tell us offset from base. /// // In your own code, you might use a different method. /// S32 v1 = base + PolyFace[i][0]; /// S32 v2 = base + PolyFace[i][1]; /// S32 v3 = base + PolyFace[i][2]; /// S32 v4 = base + PolyFace[i][3]; /// /// // Reference the four vertices that make up this surface. /// vertex(v1); /// vertex(v2); /// vertex(v3); /// vertex(v4); /// /// // Indicate the plane of this surface. /// plane(v1,v2,v3); /// /// // End the surface. /// end(); /// } /// @endcode /// @{ /// Are we empty of data? virtual bool isEmpty() const = 0; /// Adds a point to the poly list, and returns /// an ID number for that point. virtual U32 addPoint(const Point3F& p) = 0; /// Adds a point and normal to the poly list, and returns /// an ID number for them. Normals are ignored for polylists /// that do not support them. virtual U32 addPointAndNormal(const Point3F& p, const Point3F& normal) { return addPoint( p ); } /// Adds a plane to the poly list, and returns /// an ID number for that point. virtual U32 addPlane(const PlaneF& plane) = 0; /// Start a surface. /// /// @param material A material ID for this surface. /// @param surfaceKey A key value to associate with this surface. virtual void begin(TSMaterialInstance* material,U32 surfaceKey) = 0; /// Indicate the plane of the surface. virtual void plane(U32 v1,U32 v2,U32 v3) = 0; /// Indicate the plane of the surface. virtual void plane(const PlaneF& p) = 0; /// Indicate the plane of the surface. virtual void plane(const U32 index) = 0; /// Reference a vertex which is in this surface. virtual void vertex(U32 vi) = 0; /// Mark the end of a surface. virtual void end() = 0; /// Return list transform and bounds in list space. /// /// @returns False if no data is available. virtual bool getMapping(MatrixF *, Box3F *); /// @} /// @name Interest /// /// This is a mechanism to let you specify interest in a specific normal. /// If you set a normal you're interested in, then any planes facing "away" /// from that normal are culled from the results. /// /// This is handy if you're using this to do a physics check, as you're not /// interested in polygons facing away from you (since you don't collide with /// the backsides/insides of things). /// @{ void setInterestNormal(const Point3F& normal); void clearInterestNormal() { mInterestNormalRegistered = false; } virtual bool isInterestedInPlane(const PlaneF& plane); virtual bool isInterestedInPlane(const U32 index); /// @} protected: /// A helper function to convert a plane index to a PlaneF structure. virtual const PlaneF& getIndexedPlane(const U32 index) = 0; }; inline AbstractPolyList::AbstractPolyList() { doConstruct(); } inline void AbstractPolyList::doConstruct() { mCurrObject = NULL; mBaseMatrix.identity(); mMatrix.identity(); mScale.set(1, 1, 1); mPlaneTransformer.setIdentity(); mInterestNormalRegistered = false; } inline void AbstractPolyList::setBaseTransform(const MatrixF& mat) { mBaseMatrix = mat; } inline void AbstractPolyList::setTransform(const MatrixF* mat, const Point3F& scale) { mMatrix = mBaseMatrix; mTransformMatrix = *mat; mMatrix.mul(*mat); mScale = scale; mPlaneTransformer.set(mMatrix, mScale); } inline void AbstractPolyList::getTransform(MatrixF* mat, Point3F * scale) { *mat = mTransformMatrix; *scale = mScale; } inline void AbstractPolyList::setObject(SceneObject* obj) { mCurrObject = obj; } END_NS #endif // _ABSTRACTPOLYLIST_H_
31.951852
100
0.642518
[ "geometry", "object", "transform" ]
9cc7714f270f9f0bb1e4fdbfd16ede14b2857759
4,647
h
C
src/widgets/modest-attachments-view.h
community-ssu/modest
47e30072309811dc24abc9809952ed1ea846ebfa
[ "BSD-3-Clause" ]
null
null
null
src/widgets/modest-attachments-view.h
community-ssu/modest
47e30072309811dc24abc9809952ed1ea846ebfa
[ "BSD-3-Clause" ]
null
null
null
src/widgets/modest-attachments-view.h
community-ssu/modest
47e30072309811dc24abc9809952ed1ea846ebfa
[ "BSD-3-Clause" ]
2
2020-11-15T13:57:11.000Z
2021-09-01T16:32:55.000Z
/* Copyright (c) 2007, Nokia Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Nokia Corporation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 MODEST_ATTACHMENTS_VIEW_H #define MODEST_ATTACHMENTS_VIEW_H #include <gtk/gtk.h> #include <glib-object.h> #include <tny-msg.h> #define MODEST_ATTACHMENTS_VIEW_SELECTION_PREFIX "modest-attachment:" #define MODEST_ATTACHMENTS_VIEW_CLIPBOARD_TYPE "MODEST_ATTACHMENT" #define MODEST_ATTACHMENTS_VIEW_CLIPBOARD_TYPE_INDEX 0 G_BEGIN_DECLS #define MODEST_TYPE_ATTACHMENTS_VIEW (modest_attachments_view_get_type ()) #define MODEST_ATTACHMENTS_VIEW(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), MODEST_TYPE_ATTACHMENTS_VIEW, ModestAttachmentsView)) #define MODEST_ATTACHMENTS_VIEW_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST ((vtable), MODEST_TYPE_ATTACHMENTS_VIEW, ModestAttachmentsViewClass)) #define MODEST_IS_ATTACHMENTS_VIEW(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MODEST_TYPE_ATTACHMENTS_VIEW)) #define MODEST_IS_ATTACHMENTS_VIEW_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), MODEST_TYPE_ATTACHMENTS_VIEW)) #define MODEST_ATTACHMENTS_VIEW_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), MODEST_TYPE_ATTACHMENTS_VIEW, ModestAttachmentsViewClass)) typedef enum _ModestAttachmentsViewStyle { MODEST_ATTACHMENTS_VIEW_STYLE_SELECTABLE, MODEST_ATTACHMENTS_VIEW_STYLE_LINKS, MODEST_ATTACHMENTS_VIEW_STYLE_NO_FOCUS, } ModestAttachmentsViewStyle; typedef struct _ModestAttachmentsView ModestAttachmentsView; typedef struct _ModestAttachmentsViewClass ModestAttachmentsViewClass; struct _ModestAttachmentsView { GtkEventBox parent; }; struct _ModestAttachmentsViewClass { GtkEventBoxClass parent_class; void (*activate) (ModestAttachmentsView *attachments_view, TnyMimePart *mime_part); void (*delete) (ModestAttachmentsView *attachments_view, TnyMimePart *mime_part); }; GType modest_attachments_view_get_type (void); GtkWidget* modest_attachments_view_new (TnyMsg *msg); void modest_attachments_view_set_message (ModestAttachmentsView *attachments_view, TnyMsg *msg, gboolean want_html); void modest_attachments_view_add_attachment (ModestAttachmentsView *attachments_view, TnyMimePart *part, gboolean detect_size, guint64 size); void modest_attachments_view_remove_attachment (ModestAttachmentsView *attachments_view, TnyMimePart *part); void modest_attachments_view_remove_attachment_by_id (ModestAttachmentsView *attachments_view, const gchar *att_id); TnyList *modest_attachments_view_get_attachments (ModestAttachmentsView *attachments_view); TnyList *modest_attachments_view_get_selection (ModestAttachmentsView *attachments_view); void modest_attachments_view_select_all (ModestAttachmentsView *attachments_view); gboolean modest_attachments_view_has_attachments (ModestAttachmentsView *attachments_view); void modest_attachments_view_get_sizes (ModestAttachmentsView *attachments_view, gint *attachments_count, guint64 *attachments_size); void modest_attachments_view_set_style (ModestAttachmentsView *attachments_view, ModestAttachmentsViewStyle style); guint modest_attachments_view_get_num_attachments (ModestAttachmentsView *atts_view); G_END_DECLS #endif
47.907216
143
0.822466
[ "object" ]
9cca4abe682678462eae0943e68d8c05cbacd09b
1,138
c
C
cmds/mortal/_stuck.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
1
2021-06-10T00:35:51.000Z
2021-06-10T00:35:51.000Z
cmds/mortal/_stuck.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
null
null
null
cmds/mortal/_stuck.c
guille-valencia/shadowgate
a5c63b535e50020b58435d6fbb5b4f60d8f25639
[ "MIT" ]
null
null
null
#include <std.h> #include <magic.h> void unstuck(object obj); int cmd_stuck(string str) { object stuck; if(!objectp(TP)) { return 1; } if(str) { return 0; } if((int)TP->query_property("used_stuck") > time()) { tell_object(TP,"You can not use this command so soon."); log_file("stuck",""+TP->QCN+" tried to use stuck too soon.\n"); return 1; } TP->set_casting(0); TP->remove_property("using instant feat"); TP->remove_property("used_stuck"); TP->set_property("used_stuck",time() + ROUND_LENGTH); tell_object(TP,"%^B_RED%^%^BOLD%^%^CYAN%^Unsticking you. Time is: "+ctime(time())+" This command is for " "OOC game mechanic use only."); log_file("stuck",""+TP->query_true_name()+" used stuck on "+ctime(time())+"\n"); return 1; } int help(string str) { tell_object(TP,"Syntax: stuck\n\n" "This command will free you up when you are stuck in the middle of casting. Please do not " "exploit this command to attempt to cast more spells than you should be able to, all uses " "of the command are logged."); return 1; }
27.756098
110
0.620387
[ "object" ]