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
ca8e5a1f7144b193628edb472ed27d5902235409
3,548
h
C
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/app/usage/CUsageStats.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/app/usage/CUsageStats.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/app/usage/CUsageStats.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #ifndef __ELASTOS_DROID_APP_USAGE_CUSAGE_STATS_H__ #define __ELASTOS_DROID_APP_USAGE_CUSAGE_STATS_H__ #include "_Elastos_Droid_App_Usage_CUsageStats.h" #include <elastos/core/Object.h> namespace Elastos { namespace Droid { namespace App { namespace Usage { /** * Contains usage statistics for an app package for a specific * time range. */ CarClass(CUsageStats) , public Object , public IUsageStats , public IParcelable { public: CAR_INTERFACE_DECL() CAR_OBJECT_DECL() CUsageStats(); CARAPI constructor(); CARAPI constructor( /* [in] */ IUsageStats* stats); CARAPI GetPackageName( /* [out] */ String* result); /** * Get the beginning of the time range this {@link android.app.usage.UsageStats} represents, * measured in milliseconds since the epoch. * <p/> * See {@link System#currentTimeMillis()}. */ CARAPI GetFirstTimeStamp( /* [out] */ Int64* result); /** * Get the end of the time range this {@link android.app.usage.UsageStats} represents, * measured in milliseconds since the epoch. * <p/> * See {@link System#currentTimeMillis()}. */ CARAPI GetLastTimeStamp( /* [out] */ Int64* result); /** * Get the last time this package was used, measured in milliseconds since the epoch. * <p/> * See {@link System#currentTimeMillis()}. */ CARAPI GetLastTimeUsed( /* [out] */ Int64* result); /** * Get the total time this package spent in the foreground, measured in milliseconds. */ CARAPI GetTotalTimeInForeground( /* [out] */ Int64* result); /** * Add the statistics from the right {@link UsageStats} to the left. The package name for * both {@link UsageStats} objects must be the same. * @param right The {@link UsageStats} object to merge into this one. * @throws java.lang.IllegalArgumentException if the package names of the two * {@link UsageStats} objects are different. */ CARAPI Add( /* [in] */ IUsageStats* right); //@Override CARAPI WriteToParcel( /* [in] */ IParcel* dest); CARAPI ReadFromParcel( /* [in] */ IParcel* in); public: /** * {@hide} */ String mPackageName; /** * {@hide} */ Int64 mBeginTimeStamp; /** * {@hide} */ Int64 mEndTimeStamp; /** * {@hide} */ Int64 mLastTimeUsed; /** * {@hide} */ Int64 mTotalTimeInForeground; /** * {@hide} */ Int32 mLaunchCount; /** * {@hide} */ Int32 mLastEvent; }; } // namespace Usage } // namespace App } // namespace Droid } // namespace Elastos #endif //__ELASTOS_DROID_APP_USAGE_CUSAGE_STATS_H__
24.811189
96
0.605411
[ "object" ]
ca90931d133038d32713be8b230cdae0b1275a84
2,114
h
C
src/klee/lib/Expr/ArrayExprOptimizer.h
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
3
2021-10-11T11:21:03.000Z
2021-11-24T03:49:19.000Z
src/klee/lib/Expr/ArrayExprOptimizer.h
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
null
null
null
src/klee/lib/Expr/ArrayExprOptimizer.h
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
null
null
null
//===-- ArrayExprOptimizer.h ----------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef KLEE_ARRAYEXPROPTIMIZER_H #define KLEE_ARRAYEXPROPTIMIZER_H #include <cstdint> #include <map> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "klee/Expr/Expr.h" #include "klee/util/Ref.h" namespace klee { enum ArrayOptimizationType { NONE, ALL, INDEX, VALUE }; using array2idx_ty = std::map<const Array *, std::vector<ref<Expr>>>; using mapIndexOptimizedExpr_ty = std::map<ref<Expr>, std::vector<ref<Expr>>>; class ExprOptimizer { private: std::unordered_map<unsigned, ref<Expr>> cacheExprOptimized; std::unordered_set<unsigned> cacheExprUnapplicable; std::unordered_map<unsigned, ref<Expr>> cacheReadExprOptimized; public: /// Returns the optimised version of e. /// @param e expression to optimise /// @param valueOnly XXX document /// @return optimised expression ref<Expr> optimizeExpr(const ref<Expr> &e, bool valueOnly); private: bool computeIndexes(array2idx_ty &arrays, const ref<Expr> &e, mapIndexOptimizedExpr_ty &idx_valIdx) const; ref<Expr> getSelectOptExpr( const ref<Expr> &e, std::vector<const ReadExpr *> &reads, std::map<const ReadExpr *, std::pair<unsigned, Expr::Width>> &readInfo, bool isSymbolic); ref<Expr> buildConstantSelectExpr(const ref<Expr> &index, std::vector<uint64_t> &arrayValues, Expr::Width width, unsigned elementsInArray) const; ref<Expr> buildMixedSelectExpr(const ReadExpr *re, std::vector<std::pair<uint64_t, bool>> &arrayValues, Expr::Width width, unsigned elementsInArray) const; }; } // namespace klee #endif /* KLEE_ARRAYEXPROPTIMIZER_H */
32.523077
80
0.626774
[ "vector" ]
ca92ff06d3f64b4a09ab23d5520dada5237c320b
54,186
c
C
pre-process.c
jlevon/sparse
22978b6b1e5e2890bb4cb705a0f6674c2b2b6157
[ "MIT" ]
null
null
null
pre-process.c
jlevon/sparse
22978b6b1e5e2890bb4cb705a0f6674c2b2b6157
[ "MIT" ]
null
null
null
pre-process.c
jlevon/sparse
22978b6b1e5e2890bb4cb705a0f6674c2b2b6157
[ "MIT" ]
null
null
null
/* * Do C preprocessing, based on a token list gathered by * the tokenizer. * * This may not be the smartest preprocessor on the planet. * * Copyright (C) 2003 Transmeta Corp. * 2003-2004 Linus Torvalds * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <fcntl.h> #include <limits.h> #include <time.h> #include "lib.h" #include "allocate.h" #include "parse.h" #include "token.h" #include "symbol.h" #include "expression.h" #include "scope.h" static struct ident_list *macros; // only needed for -dD static int false_nesting = 0; static int counter_macro = 0; // __COUNTER__ expansion static int include_level = 0; #define INCLUDEPATHS 300 const char *includepath[INCLUDEPATHS+1] = { "", "/usr/include", "/usr/local/include", NULL }; static const char **quote_includepath = includepath; static const char **angle_includepath = includepath + 1; static const char **isys_includepath = includepath + 1; static const char **sys_includepath = includepath + 1; static const char **dirafter_includepath = includepath + 3; #define dirty_stream(stream) \ do { \ if (!stream->dirty) { \ stream->dirty = 1; \ if (!stream->ifndef) \ stream->protect = NULL; \ } \ } while(0) #define end_group(stream) \ do { \ if (stream->ifndef == stream->top_if) { \ stream->ifndef = NULL; \ if (!stream->dirty) \ stream->protect = NULL; \ else if (stream->protect) \ stream->dirty = 0; \ } \ } while(0) #define nesting_error(stream) \ do { \ stream->dirty = 1; \ stream->ifndef = NULL; \ stream->protect = NULL; \ } while(0) static struct token *alloc_token(struct position *pos) { struct token *token = __alloc_token(0); token->pos.stream = pos->stream; token->pos.line = pos->line; token->pos.pos = pos->pos; token->pos.whitespace = 1; return token; } /* Expand symbol 'sym' at '*list' */ static int expand(struct token **, struct symbol *); static void replace_with_string(struct token *token, const char *str) { int size = strlen(str) + 1; struct string *s = __alloc_string(size); s->length = size; memcpy(s->data, str, size); token_type(token) = TOKEN_STRING; token->string = s; } static void replace_with_integer(struct token *token, unsigned int val) { char *buf = __alloc_bytes(11); sprintf(buf, "%u", val); token_type(token) = TOKEN_NUMBER; token->number = buf; } static struct symbol *lookup_macro(struct ident *ident) { struct symbol *sym = lookup_symbol(ident, NS_MACRO | NS_UNDEF); if (sym && sym->namespace != NS_MACRO) sym = NULL; return sym; } static int token_defined(struct token *token) { if (token_type(token) == TOKEN_IDENT) { struct symbol *sym = lookup_macro(token->ident); if (sym) { sym->used_in = file_scope; return 1; } return 0; } sparse_error(token->pos, "expected preprocessor identifier"); return 0; } static void replace_with_bool(struct token *token, bool val) { static const char *string[] = { "0", "1" }; token_type(token) = TOKEN_NUMBER; token->number = string[val]; } static void replace_with_defined(struct token *token) { replace_with_bool(token, token_defined(token)); } static void replace_with_has_builtin(struct token *token) { struct symbol *sym = lookup_symbol(token->ident, NS_SYMBOL); replace_with_bool(token, sym && sym->builtin); } static void replace_with_has_attribute(struct token *token) { struct symbol *sym = lookup_symbol(token->ident, NS_KEYWORD); replace_with_bool(token, sym && sym->op && sym->op->attribute); } static void expand_line(struct token *token) { replace_with_integer(token, token->pos.line); } static void expand_file(struct token *token) { replace_with_string(token, stream_name(token->pos.stream)); } static void expand_basefile(struct token *token) { replace_with_string(token, base_filename); } static time_t t = 0; static void expand_date(struct token *token) { static char buffer[12]; /* __DATE__: 3 + ' ' + 2 + ' ' + 4 + '\0' */ if (!t) time(&t); strftime(buffer, 12, "%b %e %Y", localtime(&t)); replace_with_string(token, buffer); } static void expand_time(struct token *token) { static char buffer[9]; /* __TIME__: 2 + ':' + 2 + ':' + 2 + '\0' */ if (!t) time(&t); strftime(buffer, 9, "%T", localtime(&t)); replace_with_string(token, buffer); } static void expand_counter(struct token *token) { replace_with_integer(token, counter_macro++); } static void expand_include_level(struct token *token) { replace_with_integer(token, include_level - 1); } static int expand_one_symbol(struct token **list) { struct token *token = *list; struct symbol *sym; if (token->pos.noexpand) return 1; sym = lookup_macro(token->ident); if (!sym) return 1; if (sym->expander) { sym->expander(token); return 1; } else { sym->used_in = file_scope; return expand(list, sym); } } static inline struct token *scan_next(struct token **where) { struct token *token = *where; if (token_type(token) != TOKEN_UNTAINT) return token; do { token->ident->tainted = 0; token = token->next; } while (token_type(token) == TOKEN_UNTAINT); *where = token; return token; } static void expand_list(struct token **list) { struct token *next; while (!eof_token(next = scan_next(list))) { if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list)) list = &next->next; } } static void preprocessor_line(struct stream *stream, struct token **line); static struct token *collect_arg(struct token *prev, int vararg, struct position *pos, int count) { struct stream *stream = input_streams + prev->pos.stream; struct token **p = &prev->next; struct token *next; int nesting = 0; while (!eof_token(next = scan_next(p))) { if (next->pos.newline && match_op(next, '#')) { if (!next->pos.noexpand) { sparse_error(next->pos, "directive in macro's argument list"); preprocessor_line(stream, p); __free_token(next); /* Free the '#' token */ continue; } } switch (token_type(next)) { case TOKEN_STREAMEND: case TOKEN_STREAMBEGIN: *p = &eof_token_entry; return next; case TOKEN_STRING: case TOKEN_WIDE_STRING: if (count > 1) next->string->immutable = 1; break; } if (false_nesting) { *p = next->next; __free_token(next); continue; } if (match_op(next, '(')) { nesting++; } else if (match_op(next, ')')) { if (!nesting--) break; } else if (match_op(next, ',') && !nesting && !vararg) { break; } next->pos.stream = pos->stream; next->pos.line = pos->line; next->pos.pos = pos->pos; p = &next->next; } *p = &eof_token_entry; return next; } /* * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof */ struct arg { struct token *arg; struct token *expanded; struct token *str; int n_normal; int n_quoted; int n_str; }; static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what) { int wanted = arglist->count.normal; struct token *next = NULL; int count = 0; arglist = arglist->next; /* skip counter */ if (!wanted) { next = collect_arg(start, 0, &what->pos, 0); if (eof_token(next)) goto Eclosing; if (!eof_token(start->next) || !match_op(next, ')')) { count++; goto Emany; } } else { for (count = 0; count < wanted; count++) { struct argcount *p = &arglist->next->count; next = collect_arg(start, p->vararg, &what->pos, p->normal); if (eof_token(next)) goto Eclosing; if (p->vararg && wanted == 1 && eof_token(start->next)) break; arglist = arglist->next->next; args[count].arg = start->next; args[count].n_normal = p->normal; args[count].n_quoted = p->quoted; args[count].n_str = p->str; if (match_op(next, ')')) { count++; break; } start = next; } if (count == wanted && !match_op(next, ')')) goto Emany; if (count == wanted - 1) { struct argcount *p = &arglist->next->count; if (!p->vararg) goto Efew; args[count].arg = NULL; args[count].n_normal = p->normal; args[count].n_quoted = p->quoted; args[count].n_str = p->str; } if (count < wanted - 1) goto Efew; } what->next = next->next; return 1; Efew: sparse_error(what->pos, "macro \"%s\" requires %d arguments, but only %d given", show_token(what), wanted, count); goto out; Emany: while (match_op(next, ',')) { next = collect_arg(next, 0, &what->pos, 0); count++; } if (eof_token(next)) goto Eclosing; sparse_error(what->pos, "macro \"%s\" passed %d arguments, but takes just %d", show_token(what), count, wanted); goto out; Eclosing: sparse_error(what->pos, "unterminated argument list invoking macro \"%s\"", show_token(what)); out: what->next = next->next; return 0; } static struct token *dup_list(struct token *list) { struct token *res = NULL; struct token **p = &res; while (!eof_token(list)) { struct token *newtok = __alloc_token(0); *newtok = *list; *p = newtok; p = &newtok->next; list = list->next; } return res; } static const char *show_token_sequence(struct token *token, int quote) { static char buffer[MAX_STRING]; char *ptr = buffer; int whitespace = 0; if (!token && !quote) return "<none>"; while (!eof_token(token)) { const char *val = quote ? quote_token(token) : show_token(token); int len = strlen(val); if (ptr + whitespace + len >= buffer + sizeof(buffer)) { sparse_error(token->pos, "too long token expansion"); break; } if (whitespace) *ptr++ = ' '; memcpy(ptr, val, len); ptr += len; token = token->next; whitespace = token->pos.whitespace; } *ptr = 0; return buffer; } static struct token *stringify(struct token *arg) { const char *s = show_token_sequence(arg, 1); int size = strlen(s)+1; struct token *token = __alloc_token(0); struct string *string = __alloc_string(size); memcpy(string->data, s, size); string->length = size; token->pos = arg->pos; token_type(token) = TOKEN_STRING; token->string = string; token->next = &eof_token_entry; return token; } static void expand_arguments(int count, struct arg *args) { int i; for (i = 0; i < count; i++) { struct token *arg = args[i].arg; if (!arg) arg = &eof_token_entry; if (args[i].n_str) args[i].str = stringify(arg); if (args[i].n_normal) { if (!args[i].n_quoted) { args[i].expanded = arg; args[i].arg = NULL; } else if (eof_token(arg)) { args[i].expanded = arg; } else { args[i].expanded = dup_list(arg); } expand_list(&args[i].expanded); } } } /* * Possibly valid combinations: * - ident + ident -> ident * - ident + number -> ident unless number contains '.', '+' or '-'. * - 'L' + char constant -> wide char constant * - 'L' + string literal -> wide string literal * - number + number -> number * - number + ident -> number * - number + '.' -> number * - number + '+' or '-' -> number, if number used to end on [eEpP]. * - '.' + number -> number, if number used to start with a digit. * - special + special -> either special or an error. */ static enum token_type combine(struct token *left, struct token *right, char *p) { int len; enum token_type t1 = token_type(left), t2 = token_type(right); if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL) return TOKEN_ERROR; if (t1 == TOKEN_IDENT && left->ident == &L_ident) { if (t2 >= TOKEN_CHAR && t2 < TOKEN_WIDE_CHAR) return t2 + TOKEN_WIDE_CHAR - TOKEN_CHAR; if (t2 == TOKEN_STRING) return TOKEN_WIDE_STRING; } if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL) return TOKEN_ERROR; strcpy(p, show_token(left)); strcat(p, show_token(right)); len = strlen(p); if (len >= 256) return TOKEN_ERROR; if (t1 == TOKEN_IDENT) { if (t2 == TOKEN_SPECIAL) return TOKEN_ERROR; if (t2 == TOKEN_NUMBER && strpbrk(p, "+-.")) return TOKEN_ERROR; return TOKEN_IDENT; } if (t1 == TOKEN_NUMBER) { if (t2 == TOKEN_SPECIAL) { switch (right->special) { case '.': break; case '+': case '-': if (strchr("eEpP", p[len - 2])) break; default: return TOKEN_ERROR; } } return TOKEN_NUMBER; } if (p[0] == '.' && isdigit((unsigned char)p[1])) return TOKEN_NUMBER; return TOKEN_SPECIAL; } static int merge(struct token *left, struct token *right) { static char buffer[512]; enum token_type res = combine(left, right, buffer); int n; switch (res) { case TOKEN_IDENT: left->ident = built_in_ident(buffer); left->pos.noexpand = 0; return 1; case TOKEN_NUMBER: token_type(left) = TOKEN_NUMBER; /* could be . + num */ left->number = xstrdup(buffer); return 1; case TOKEN_SPECIAL: if (buffer[2] && buffer[3]) break; for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) { if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) { left->special = n; return 1; } } break; case TOKEN_WIDE_CHAR: case TOKEN_WIDE_STRING: token_type(left) = res; left->pos.noexpand = 0; left->string = right->string; return 1; case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3: token_type(left) = res; left->pos.noexpand = 0; memcpy(left->embedded, right->embedded, 4); return 1; default: ; } sparse_error(left->pos, "'##' failed: concatenation is not a valid token"); return 0; } static struct token *dup_token(struct token *token, struct position *streampos) { struct token *alloc = alloc_token(streampos); token_type(alloc) = token_type(token); alloc->pos.newline = token->pos.newline; alloc->pos.whitespace = token->pos.whitespace; alloc->number = token->number; alloc->pos.noexpand = token->pos.noexpand; return alloc; } static struct token **copy(struct token **where, struct token *list, int *count) { int need_copy = --*count; while (!eof_token(list)) { struct token *token; if (need_copy) token = dup_token(list, &list->pos); else token = list; if (token_type(token) == TOKEN_IDENT && token->ident->tainted) token->pos.noexpand = 1; *where = token; where = &token->next; list = list->next; } *where = &eof_token_entry; return where; } static int handle_kludge(struct token **p, struct arg *args) { struct token *t = (*p)->next->next; while (1) { struct arg *v = &args[t->argnum]; if (token_type(t->next) != TOKEN_CONCAT) { if (v->arg) { /* ignore the first ## */ *p = (*p)->next; return 0; } /* skip the entire thing */ *p = t; return 1; } if (v->arg && !eof_token(v->arg)) return 0; /* no magic */ t = t->next->next; } } static struct token **substitute(struct token **list, struct token *body, struct arg *args) { struct position *base_pos = &(*list)->pos; int *count; enum {Normal, Placeholder, Concat} state = Normal; for (; !eof_token(body); body = body->next) { struct token *added, *arg; struct token **tail; struct token *t; switch (token_type(body)) { case TOKEN_GNU_KLUDGE: /* * GNU kludge: if we had <comma>##<vararg>, behaviour * depends on whether we had enough arguments to have * a vararg. If we did, ## is just ignored. Otherwise * both , and ## are ignored. Worse, there can be * an arbitrary number of ##<arg> in between; if all of * those are empty, we act as if they hadn't been there, * otherwise we act as if the kludge didn't exist. */ t = body; if (handle_kludge(&body, args)) { if (state == Concat) state = Normal; else state = Placeholder; continue; } added = dup_token(t, base_pos); token_type(added) = TOKEN_SPECIAL; tail = &added->next; break; case TOKEN_STR_ARGUMENT: arg = args[body->argnum].str; count = &args[body->argnum].n_str; goto copy_arg; case TOKEN_QUOTED_ARGUMENT: arg = args[body->argnum].arg; count = &args[body->argnum].n_quoted; if (!arg || eof_token(arg)) { if (state == Concat) state = Normal; else state = Placeholder; continue; } goto copy_arg; case TOKEN_MACRO_ARGUMENT: arg = args[body->argnum].expanded; count = &args[body->argnum].n_normal; if (eof_token(arg)) { state = Normal; continue; } copy_arg: tail = copy(&added, arg, count); added->pos.newline = body->pos.newline; added->pos.whitespace = body->pos.whitespace; break; case TOKEN_CONCAT: if (state == Placeholder) state = Normal; else state = Concat; continue; case TOKEN_IDENT: added = dup_token(body, base_pos); if (added->ident->tainted) added->pos.noexpand = 1; tail = &added->next; break; default: added = dup_token(body, base_pos); tail = &added->next; break; } /* * if we got to doing real concatenation, we already have * added something into the list, so containing_token() is OK. */ if (state == Concat && merge(containing_token(list), added)) { *list = added->next; if (tail != &added->next) list = tail; } else { *list = added; list = tail; } state = Normal; } *list = &eof_token_entry; return list; } static int expand(struct token **list, struct symbol *sym) { struct token *last; struct token *token = *list; struct ident *expanding = token->ident; struct token **tail; int nargs = sym->arglist ? sym->arglist->count.normal : 0; struct arg args[nargs]; if (expanding->tainted) { token->pos.noexpand = 1; return 1; } if (sym->arglist) { if (!match_op(scan_next(&token->next), '(')) return 1; if (!collect_arguments(token->next, sym->arglist, args, token)) return 1; expand_arguments(nargs, args); } expanding->tainted = 1; last = token->next; tail = substitute(list, sym->expansion, args); /* * Note that it won't be eof - at least TOKEN_UNTAINT will be there. * We still can lose the newline flag if the sucker expands to nothing, * but the price of dealing with that is probably too high (we'd need * to collect the flags during scan_next()) */ (*list)->pos.newline = token->pos.newline; (*list)->pos.whitespace = token->pos.whitespace; *tail = last; return 0; } static const char *token_name_sequence(struct token *token, int endop, struct token *start) { static char buffer[256]; char *ptr = buffer; while (!eof_token(token) && !match_op(token, endop)) { int len; const char *val = token->string->data; if (token_type(token) != TOKEN_STRING) val = show_token(token); len = strlen(val); memcpy(ptr, val, len); ptr += len; token = token->next; } *ptr = 0; if (endop && !match_op(token, endop)) sparse_error(start->pos, "expected '>' at end of filename"); return buffer; } static int already_tokenized(const char *path) { int stream, next; for (stream = *hash_stream(path); stream >= 0 ; stream = next) { struct stream *s = input_streams + stream; next = s->next_stream; if (s->once) { if (strcmp(path, s->name)) continue; return 1; } if (s->constant != CONSTANT_FILE_YES) continue; if (strcmp(path, s->name)) continue; if (s->protect && !lookup_macro(s->protect)) continue; return 1; } return 0; } /* Handle include of header files. * The relevant options are made compatible with gcc. The only options that * are not supported is -withprefix and friends. * * Three set of include paths are known: * quote_includepath: Path to search when using #include "file.h" * angle_includepath: Paths to search when using #include <file.h> * isys_includepath: Paths specified with -isystem, come before the * built-in system include paths. Gcc would suppress * warnings from system headers. Here we separate * them from the angle_ ones to keep search ordering. * * sys_includepath: Built-in include paths. * dirafter_includepath Paths added with -dirafter. * * The above is implemented as one array with pointers * +--------------+ * quote_includepath ---> | | * +--------------+ * | | * +--------------+ * angle_includepath ---> | | * +--------------+ * isys_includepath ---> | | * +--------------+ * sys_includepath ---> | | * +--------------+ * dirafter_includepath -> | | * +--------------+ * * -I dir insert dir just before isys_includepath and move the rest * -I- makes all dirs specified with -I before to quote dirs only and * angle_includepath is set equal to isys_includepath. * -nostdinc removes all sys dirs by storing NULL in entry pointed * to by * sys_includepath. Note that this will reset all dirs built-in * and added before -nostdinc by -isystem and -idirafter. * -isystem dir adds dir where isys_includepath points adding this dir as * first systemdir * -idirafter dir adds dir to the end of the list */ static void set_stream_include_path(struct stream *stream) { const char *path = stream->path; if (!path) { const char *p = strrchr(stream->name, '/'); path = ""; if (p) { int len = p - stream->name + 1; char *m = malloc(len+1); /* This includes the final "/" */ memcpy(m, stream->name, len); m[len] = 0; path = m; } stream->path = path; } includepath[0] = path; } #ifndef PATH_MAX #define PATH_MAX 4096 // for Hurd where it's not defined #endif static int try_include(const char *path, const char *filename, int flen, struct token **where, const char **next_path) { int fd; int plen = strlen(path); static char fullname[PATH_MAX]; memcpy(fullname, path, plen); if (plen && path[plen-1] != '/') { fullname[plen] = '/'; plen++; } memcpy(fullname+plen, filename, flen); if (already_tokenized(fullname)) return 1; fd = open(fullname, O_RDONLY); if (fd >= 0) { char *streamname = xmemdup(fullname, plen + flen); *where = tokenize(streamname, fd, *where, next_path); close(fd); return 1; } return 0; } static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen) { const char *path; while ((path = *pptr++) != NULL) { if (!try_include(path, filename, flen, list, pptr)) continue; return 1; } return 0; } static int free_preprocessor_line(struct token *token) { while (token_type(token) != TOKEN_EOF) { struct token *free = token; token = token->next; __free_token(free); }; return 1; } static int handle_include_path(struct stream *stream, struct token **list, struct token *token, int how) { const char *filename; struct token *next; const char **path; int expect; int flen; next = token->next; expect = '>'; if (!match_op(next, '<')) { expand_list(&token->next); expect = 0; next = token; if (match_op(token->next, '<')) { next = token->next; expect = '>'; } } token = next->next; filename = token_name_sequence(token, expect, token); flen = strlen(filename) + 1; /* Absolute path? */ if (filename[0] == '/') { if (try_include("", filename, flen, list, includepath)) return 0; goto out; } switch (how) { case 1: path = stream->next_path; break; case 2: includepath[0] = ""; path = includepath; break; default: /* Dir of input file is first dir to search for quoted includes */ set_stream_include_path(stream); path = expect ? angle_includepath : quote_includepath; break; } /* Check the standard include paths.. */ if (do_include_path(path, list, token, filename, flen)) return 0; out: error_die(token->pos, "unable to open '%s'", filename); } static int handle_include(struct stream *stream, struct token **list, struct token *token) { return handle_include_path(stream, list, token, 0); } static int handle_include_next(struct stream *stream, struct token **list, struct token *token) { return handle_include_path(stream, list, token, 1); } static int handle_argv_include(struct stream *stream, struct token **list, struct token *token) { return handle_include_path(stream, list, token, 2); } static int token_different(struct token *t1, struct token *t2) { int different; if (token_type(t1) != token_type(t2)) return 1; switch (token_type(t1)) { case TOKEN_IDENT: different = t1->ident != t2->ident; break; case TOKEN_ARG_COUNT: case TOKEN_UNTAINT: case TOKEN_CONCAT: case TOKEN_GNU_KLUDGE: different = 0; break; case TOKEN_NUMBER: different = strcmp(t1->number, t2->number); break; case TOKEN_SPECIAL: different = t1->special != t2->special; break; case TOKEN_MACRO_ARGUMENT: case TOKEN_QUOTED_ARGUMENT: case TOKEN_STR_ARGUMENT: different = t1->argnum != t2->argnum; break; case TOKEN_CHAR_EMBEDDED_0 ... TOKEN_CHAR_EMBEDDED_3: case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3: different = memcmp(t1->embedded, t2->embedded, 4); break; case TOKEN_CHAR: case TOKEN_WIDE_CHAR: case TOKEN_STRING: case TOKEN_WIDE_STRING: { struct string *s1, *s2; s1 = t1->string; s2 = t2->string; different = 1; if (s1->length != s2->length) break; different = memcmp(s1->data, s2->data, s1->length); break; } default: different = 1; break; } return different; } static int token_list_different(struct token *list1, struct token *list2) { for (;;) { if (list1 == list2) return 0; if (!list1 || !list2) return 1; if (token_different(list1, list2)) return 1; list1 = list1->next; list2 = list2->next; } } static inline void set_arg_count(struct token *token) { token_type(token) = TOKEN_ARG_COUNT; token->count.normal = token->count.quoted = token->count.str = token->count.vararg = 0; } static struct token *parse_arguments(struct token *list) { struct token *arg = list->next, *next = list; struct argcount *count = &list->count; set_arg_count(list); if (match_op(arg, ')')) { next = arg->next; list->next = &eof_token_entry; return next; } while (token_type(arg) == TOKEN_IDENT) { if (arg->ident == &__VA_ARGS___ident) goto Eva_args; if (!++count->normal) goto Eargs; next = arg->next; if (match_op(next, ',')) { set_arg_count(next); arg = next->next; continue; } if (match_op(next, ')')) { set_arg_count(next); next = next->next; arg->next->next = &eof_token_entry; return next; } /* normal cases are finished here */ if (match_op(next, SPECIAL_ELLIPSIS)) { if (match_op(next->next, ')')) { set_arg_count(next); next->count.vararg = 1; next = next->next; arg->next->next = &eof_token_entry; return next->next; } arg = next; goto Enotclosed; } if (eof_token(next)) { goto Enotclosed; } else { arg = next; goto Ebadstuff; } } if (match_op(arg, SPECIAL_ELLIPSIS)) { next = arg->next; token_type(arg) = TOKEN_IDENT; arg->ident = &__VA_ARGS___ident; if (!match_op(next, ')')) goto Enotclosed; if (!++count->normal) goto Eargs; set_arg_count(next); next->count.vararg = 1; next = next->next; arg->next->next = &eof_token_entry; return next; } if (eof_token(arg)) { arg = next; goto Enotclosed; } if (match_op(arg, ',')) goto Emissing; else goto Ebadstuff; Emissing: sparse_error(arg->pos, "parameter name missing"); return NULL; Ebadstuff: sparse_error(arg->pos, "\"%s\" may not appear in macro parameter list", show_token(arg)); return NULL; Enotclosed: sparse_error(arg->pos, "missing ')' in macro parameter list"); return NULL; Eva_args: sparse_error(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro"); return NULL; Eargs: sparse_error(arg->pos, "too many arguments in macro definition"); return NULL; } static int try_arg(struct token *token, enum token_type type, struct token *arglist) { struct ident *ident = token->ident; int nr; if (!arglist || token_type(token) != TOKEN_IDENT) return 0; arglist = arglist->next; for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) { if (arglist->ident == ident) { struct argcount *count = &arglist->next->count; int n; token->argnum = nr; token_type(token) = type; switch (type) { case TOKEN_MACRO_ARGUMENT: n = ++count->normal; break; case TOKEN_QUOTED_ARGUMENT: n = ++count->quoted; break; default: n = ++count->str; } if (n) return count->vararg ? 2 : 1; /* * XXX - need saner handling of that * (>= 1024 instances of argument) */ token_type(token) = TOKEN_ERROR; return -1; } } return 0; } static struct token *handle_hash(struct token **p, struct token *arglist) { struct token *token = *p; if (arglist) { struct token *next = token->next; if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist)) goto Equote; next->pos.whitespace = token->pos.whitespace; __free_token(token); token = *p = next; } else { token->pos.noexpand = 1; } return token; Equote: sparse_error(token->pos, "'#' is not followed by a macro parameter"); return NULL; } /* token->next is ## */ static struct token *handle_hashhash(struct token *token, struct token *arglist) { struct token *last = token; struct token *concat; int state = match_op(token, ','); try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist); while (1) { struct token *t; int is_arg; /* eat duplicate ## */ concat = token->next; while (match_op(t = concat->next, SPECIAL_HASHHASH)) { token->next = t; __free_token(concat); concat = t; } token_type(concat) = TOKEN_CONCAT; if (eof_token(t)) goto Econcat; if (match_op(t, '#')) { t = handle_hash(&concat->next, arglist); if (!t) return NULL; } is_arg = try_arg(t, TOKEN_QUOTED_ARGUMENT, arglist); if (state == 1 && is_arg) { state = is_arg; } else { last = t; state = match_op(t, ','); } token = t; if (!match_op(token->next, SPECIAL_HASHHASH)) break; } /* handle GNU ,##__VA_ARGS__ kludge, in all its weirdness */ if (state == 2) token_type(last) = TOKEN_GNU_KLUDGE; return token; Econcat: sparse_error(concat->pos, "'##' cannot appear at the ends of macro expansion"); return NULL; } static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name) { struct token *token = expansion; struct token **p; if (match_op(token, SPECIAL_HASHHASH)) goto Econcat; for (p = &expansion; !eof_token(token); p = &token->next, token = *p) { if (match_op(token, '#')) { token = handle_hash(p, arglist); if (!token) return NULL; } if (match_op(token->next, SPECIAL_HASHHASH)) { token = handle_hashhash(token, arglist); if (!token) return NULL; } else { try_arg(token, TOKEN_MACRO_ARGUMENT, arglist); } switch (token_type(token)) { case TOKEN_ERROR: goto Earg; case TOKEN_STRING: case TOKEN_WIDE_STRING: token->string->immutable = 1; break; } } token = alloc_token(&expansion->pos); token_type(token) = TOKEN_UNTAINT; token->ident = name; token->next = *p; *p = token; return expansion; Econcat: sparse_error(token->pos, "'##' cannot appear at the ends of macro expansion"); return NULL; Earg: sparse_error(token->pos, "too many instances of argument in body"); return NULL; } static int do_define(struct position pos, struct token *token, struct ident *name, struct token *arglist, struct token *expansion, int attr) { struct symbol *sym; int ret = 1; expansion = parse_expansion(expansion, arglist, name); if (!expansion) return 1; sym = lookup_symbol(name, NS_MACRO | NS_UNDEF); if (sym) { int clean; if (attr < sym->attr) goto out; clean = (attr == sym->attr && sym->namespace == NS_MACRO); if (token_list_different(sym->expansion, expansion) || token_list_different(sym->arglist, arglist)) { ret = 0; if ((clean && attr == SYM_ATTR_NORMAL) || sym->used_in == file_scope) { warning(pos, "preprocessor token %.*s redefined", name->len, name->name); info(sym->pos, "this was the original definition"); } } else if (clean) goto out; } if (!sym || sym->scope != file_scope) { sym = alloc_symbol(pos, SYM_NODE); bind_symbol(sym, name, NS_MACRO); add_ident(&macros, name); ret = 0; } if (!ret) { sym->expansion = expansion; sym->arglist = arglist; if (token) /* Free the "define" token, but not the rest of the line */ __free_token(token); } sym->namespace = NS_MACRO; sym->used_in = NULL; sym->attr = attr; out: return ret; } /// // predefine a macro with a printf-formatted value // @name: the name of the macro // @weak: 0/1 for a normal or a weak define // @fmt: the printf format followed by it's arguments. // // The type of the value is automatically infered: // TOKEN_NUMBER if it starts by a digit, TOKEN_IDENT otherwise. // If @fmt is null or empty, the macro is defined with an empty definition. void predefine(const char *name, int weak, const char *fmt, ...) { struct ident *ident = built_in_ident(name); struct token *value = &eof_token_entry; int attr = weak ? SYM_ATTR_WEAK : SYM_ATTR_NORMAL; if (fmt && fmt[0]) { static char buf[256]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); value = __alloc_token(0); if (isdigit(buf[0])) { token_type(value) = TOKEN_NUMBER; value->number = xstrdup(buf); } else { token_type(value) = TOKEN_IDENT; value->ident = built_in_ident(buf); } value->pos.whitespace = 1; value->next = &eof_token_entry; } do_define(value->pos, NULL, ident, NULL, value, attr); } static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int attr) { struct token *arglist, *expansion; struct token *left = token->next; struct ident *name; if (token_type(left) != TOKEN_IDENT) { sparse_error(token->pos, "expected identifier to 'define'"); return 1; } name = left->ident; arglist = NULL; expansion = left->next; if (!expansion->pos.whitespace) { if (match_op(expansion, '(')) { arglist = expansion; expansion = parse_arguments(expansion); if (!expansion) return 1; } else if (!eof_token(expansion)) { warning(expansion->pos, "no whitespace before object-like macro body"); } } return do_define(left->pos, token, name, arglist, expansion, attr); } static int handle_define(struct stream *stream, struct token **line, struct token *token) { return do_handle_define(stream, line, token, SYM_ATTR_NORMAL); } static int handle_weak_define(struct stream *stream, struct token **line, struct token *token) { return do_handle_define(stream, line, token, SYM_ATTR_WEAK); } static int handle_strong_define(struct stream *stream, struct token **line, struct token *token) { return do_handle_define(stream, line, token, SYM_ATTR_STRONG); } static int do_handle_undef(struct stream *stream, struct token **line, struct token *token, int attr) { struct token *left = token->next; struct symbol *sym; if (token_type(left) != TOKEN_IDENT) { sparse_error(token->pos, "expected identifier to 'undef'"); return 1; } sym = lookup_symbol(left->ident, NS_MACRO | NS_UNDEF); if (sym) { if (attr < sym->attr) return 1; if (attr == sym->attr && sym->namespace == NS_UNDEF) return 1; } else if (attr <= SYM_ATTR_NORMAL) return 1; if (!sym || sym->scope != file_scope) { sym = alloc_symbol(left->pos, SYM_NODE); bind_symbol(sym, left->ident, NS_MACRO); } sym->namespace = NS_UNDEF; sym->used_in = NULL; sym->attr = attr; return 1; } static int handle_undef(struct stream *stream, struct token **line, struct token *token) { return do_handle_undef(stream, line, token, SYM_ATTR_NORMAL); } static int handle_strong_undef(struct stream *stream, struct token **line, struct token *token) { return do_handle_undef(stream, line, token, SYM_ATTR_STRONG); } static int preprocessor_if(struct stream *stream, struct token *token, int cond) { token_type(token) = false_nesting ? TOKEN_SKIP_GROUPS : TOKEN_IF; free_preprocessor_line(token->next); token->next = stream->top_if; stream->top_if = token; if (false_nesting || cond != 1) false_nesting++; return 0; } static int handle_ifdef(struct stream *stream, struct token **line, struct token *token) { struct token *next = token->next; int arg; if (token_type(next) == TOKEN_IDENT) { arg = token_defined(next); } else { dirty_stream(stream); if (!false_nesting) sparse_error(token->pos, "expected preprocessor identifier"); arg = -1; } return preprocessor_if(stream, token, arg); } static int handle_ifndef(struct stream *stream, struct token **line, struct token *token) { struct token *next = token->next; int arg; if (token_type(next) == TOKEN_IDENT) { if (!stream->dirty && !stream->ifndef) { if (!stream->protect) { stream->ifndef = token; stream->protect = next->ident; } else if (stream->protect == next->ident) { stream->ifndef = token; stream->dirty = 1; } } arg = !token_defined(next); } else { dirty_stream(stream); if (!false_nesting) sparse_error(token->pos, "expected preprocessor identifier"); arg = -1; } return preprocessor_if(stream, token, arg); } static const char *show_token_sequence(struct token *token, int quote); /* * Expression handling for #if and #elif; it differs from normal expansion * due to special treatment of "defined". */ static int expression_value(struct token **where) { struct expression *expr; struct token *p; struct token **list = where, **beginning = NULL; long long value; int state = 0; while (!eof_token(p = scan_next(list))) { switch (state) { case 0: if (token_type(p) != TOKEN_IDENT) break; if (p->ident == &defined_ident) { state = 1; beginning = list; break; } else if (p->ident == &__has_builtin_ident) { state = 4; beginning = list; break; } else if (p->ident == &__has_attribute_ident) { state = 6; beginning = list; break; } if (!expand_one_symbol(list)) continue; if (token_type(p) != TOKEN_IDENT) break; token_type(p) = TOKEN_ZERO_IDENT; break; case 1: if (match_op(p, '(')) { state = 2; } else { state = 0; replace_with_defined(p); *beginning = p; } break; case 2: if (token_type(p) == TOKEN_IDENT) state = 3; else state = 0; replace_with_defined(p); *beginning = p; break; case 3: state = 0; if (!match_op(p, ')')) sparse_error(p->pos, "missing ')' after \"defined\""); *list = p->next; continue; // __has_builtin(x) or __has_attribute(x) case 4: case 6: if (match_op(p, '(')) { state++; } else { sparse_error(p->pos, "missing '(' after \"__has_%s\"", state == 4 ? "builtin" : "attribute"); state = 0; } *beginning = p; break; case 5: case 7: if (token_type(p) != TOKEN_IDENT) { sparse_error(p->pos, "identifier expected"); state = 0; break; } if (!match_op(p->next, ')')) sparse_error(p->pos, "missing ')' after \"__has_%s\"", state == 5 ? "builtin" : "attribute"); if (state == 5) replace_with_has_builtin(p); else replace_with_has_attribute(p); state = 8; *beginning = p; break; case 8: state = 0; *list = p->next; continue; } list = &p->next; } p = constant_expression(*where, &expr); if (!eof_token(p)) sparse_error(p->pos, "garbage at end: %s", show_token_sequence(p, 0)); value = get_expression_value(expr); return value != 0; } static int handle_if(struct stream *stream, struct token **line, struct token *token) { int value = 0; if (!false_nesting) value = expression_value(&token->next); dirty_stream(stream); return preprocessor_if(stream, token, value); } static int handle_elif(struct stream * stream, struct token **line, struct token *token) { struct token *top_if = stream->top_if; end_group(stream); if (!top_if) { nesting_error(stream); sparse_error(token->pos, "unmatched #elif within stream"); return 1; } if (token_type(top_if) == TOKEN_ELSE) { nesting_error(stream); sparse_error(token->pos, "#elif after #else"); if (!false_nesting) false_nesting = 1; return 1; } dirty_stream(stream); if (token_type(top_if) != TOKEN_IF) return 1; if (false_nesting) { false_nesting = 0; if (!expression_value(&token->next)) false_nesting = 1; } else { false_nesting = 1; token_type(top_if) = TOKEN_SKIP_GROUPS; } return 1; } static int handle_else(struct stream *stream, struct token **line, struct token *token) { struct token *top_if = stream->top_if; end_group(stream); if (!top_if) { nesting_error(stream); sparse_error(token->pos, "unmatched #else within stream"); return 1; } if (token_type(top_if) == TOKEN_ELSE) { nesting_error(stream); sparse_error(token->pos, "#else after #else"); } if (false_nesting) { if (token_type(top_if) == TOKEN_IF) false_nesting = 0; } else { false_nesting = 1; } token_type(top_if) = TOKEN_ELSE; return 1; } static int handle_endif(struct stream *stream, struct token **line, struct token *token) { struct token *top_if = stream->top_if; end_group(stream); if (!top_if) { nesting_error(stream); sparse_error(token->pos, "unmatched #endif in stream"); return 1; } if (false_nesting) false_nesting--; stream->top_if = top_if->next; __free_token(top_if); return 1; } static int handle_warning(struct stream *stream, struct token **line, struct token *token) { warning(token->pos, "%s", show_token_sequence(token->next, 0)); return 1; } static int handle_error(struct stream *stream, struct token **line, struct token *token) { sparse_error(token->pos, "%s", show_token_sequence(token->next, 0)); return 1; } static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token) { /* * Do we have any non-system includes? * Clear them out if so.. */ *sys_includepath = NULL; return 1; } static inline void update_inc_ptrs(const char ***where) { if (*where <= dirafter_includepath) { dirafter_includepath++; /* If this was the entry that we prepend, don't * rise the lower entries, even if they are at * the same level. */ if (where == &dirafter_includepath) return; } if (*where <= sys_includepath) { sys_includepath++; if (where == &sys_includepath) return; } if (*where <= isys_includepath) { isys_includepath++; if (where == &isys_includepath) return; } /* angle_includepath is actually never updated, since we * don't suppport -iquote rught now. May change some day. */ if (*where <= angle_includepath) { angle_includepath++; if (where == &angle_includepath) return; } } /* Add a path before 'where' and update the pointers associated with the * includepath array */ static void add_path_entry(struct token *token, const char *path, const char ***where) { const char **dst; const char *next; /* Need one free entry.. */ if (includepath[INCLUDEPATHS-2]) error_die(token->pos, "too many include path entries"); /* check that this is not a duplicate */ dst = includepath; while (*dst) { if (strcmp(*dst, path) == 0) return; dst++; } next = path; dst = *where; update_inc_ptrs(where); /* * Move them all up starting at dst, * insert the new entry.. */ do { const char *tmp = *dst; *dst = next; next = tmp; dst++; } while (next); } static int handle_add_include(struct stream *stream, struct token **line, struct token *token) { for (;;) { token = token->next; if (eof_token(token)) return 1; if (token_type(token) != TOKEN_STRING) { warning(token->pos, "expected path string"); return 1; } add_path_entry(token, token->string->data, &isys_includepath); } } static int handle_add_isystem(struct stream *stream, struct token **line, struct token *token) { for (;;) { token = token->next; if (eof_token(token)) return 1; if (token_type(token) != TOKEN_STRING) { sparse_error(token->pos, "expected path string"); return 1; } add_path_entry(token, token->string->data, &sys_includepath); } } static int handle_add_system(struct stream *stream, struct token **line, struct token *token) { for (;;) { token = token->next; if (eof_token(token)) return 1; if (token_type(token) != TOKEN_STRING) { sparse_error(token->pos, "expected path string"); return 1; } add_path_entry(token, token->string->data, &dirafter_includepath); } } /* Add to end on includepath list - no pointer updates */ static void add_dirafter_entry(struct token *token, const char *path) { const char **dst = includepath; /* Need one free entry.. */ if (includepath[INCLUDEPATHS-2]) error_die(token->pos, "too many include path entries"); /* Add to the end */ while (*dst) dst++; *dst = path; dst++; *dst = NULL; } static int handle_add_dirafter(struct stream *stream, struct token **line, struct token *token) { for (;;) { token = token->next; if (eof_token(token)) return 1; if (token_type(token) != TOKEN_STRING) { sparse_error(token->pos, "expected path string"); return 1; } add_dirafter_entry(token, token->string->data); } } static int handle_split_include(struct stream *stream, struct token **line, struct token *token) { /* * -I- * From info gcc: * Split the include path. Any directories specified with `-I' * options before `-I-' are searched only for headers requested with * `#include "FILE"'; they are not searched for `#include <FILE>'. * If additional directories are specified with `-I' options after * the `-I-', those directories are searched for all `#include' * directives. * In addition, `-I-' inhibits the use of the directory of the current * file directory as the first search directory for `#include "FILE"'. */ quote_includepath = includepath+1; angle_includepath = sys_includepath; return 1; } /* * We replace "#pragma xxx" with "__pragma__" in the token * stream. Just as an example. * * We'll just #define that away for now, but the theory here * is that we can use this to insert arbitrary token sequences * to turn the pragmas into internal front-end sequences for * when we actually start caring about them. * * So eventually this will turn into some kind of extended * __attribute__() like thing, except called __pragma__(xxx). */ static int handle_pragma(struct stream *stream, struct token **line, struct token *token) { struct token *next = *line; if (match_ident(token->next, &once_ident) && eof_token(token->next->next)) { stream->once = 1; return 1; } token->ident = &pragma_ident; token->pos.newline = 1; token->pos.whitespace = 1; token->pos.pos = 1; *line = token; token->next = next; return 0; } /* * We ignore #line for now. */ static int handle_line(struct stream *stream, struct token **line, struct token *token) { return 1; } static int handle_ident(struct stream *stream, struct token **line, struct token *token) { return 1; } static int handle_nondirective(struct stream *stream, struct token **line, struct token *token) { sparse_error(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token, 0)); return 1; } static void init_preprocessor(void) { int i; int stream = init_stream("preprocessor", -1, includepath); static struct { const char *name; int (*handler)(struct stream *, struct token **, struct token *); } normal[] = { { "define", handle_define }, { "weak_define", handle_weak_define }, { "strong_define", handle_strong_define }, { "undef", handle_undef }, { "strong_undef", handle_strong_undef }, { "warning", handle_warning }, { "error", handle_error }, { "include", handle_include }, { "include_next", handle_include_next }, { "pragma", handle_pragma }, { "line", handle_line }, { "ident", handle_ident }, // our internal preprocessor tokens { "nostdinc", handle_nostdinc }, { "add_include", handle_add_include }, { "add_isystem", handle_add_isystem }, { "add_system", handle_add_system }, { "add_dirafter", handle_add_dirafter }, { "split_include", handle_split_include }, { "argv_include", handle_argv_include }, }, special[] = { { "ifdef", handle_ifdef }, { "ifndef", handle_ifndef }, { "else", handle_else }, { "endif", handle_endif }, { "if", handle_if }, { "elif", handle_elif }, }; static struct { const char *name; void (*expander)(struct token *); } dynamic[] = { { "__LINE__", expand_line }, { "__FILE__", expand_file }, { "__BASE_FILE__", expand_basefile }, { "__DATE__", expand_date }, { "__TIME__", expand_time }, { "__COUNTER__", expand_counter }, { "__INCLUDE_LEVEL__", expand_include_level }, }; for (i = 0; i < ARRAY_SIZE(normal); i++) { struct symbol *sym; sym = create_symbol(stream, normal[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR); sym->handler = normal[i].handler; sym->normal = 1; } for (i = 0; i < ARRAY_SIZE(special); i++) { struct symbol *sym; sym = create_symbol(stream, special[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR); sym->handler = special[i].handler; sym->normal = 0; } for (i = 0; i < ARRAY_SIZE(dynamic); i++) { struct symbol *sym; sym = create_symbol(stream, dynamic[i].name, SYM_NODE, NS_MACRO); sym->expander = dynamic[i].expander; } counter_macro = 0; } static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start) { int (*handler)(struct stream *, struct token **, struct token *); struct token *token = start->next; int is_normal = 1; if (eof_token(token)) return; if (token_type(token) == TOKEN_IDENT) { struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR); if (sym) { handler = sym->handler; is_normal = sym->normal; } else { handler = handle_nondirective; } } else if (token_type(token) == TOKEN_NUMBER) { handler = handle_line; } else { handler = handle_nondirective; } if (is_normal) { dirty_stream(stream); if (false_nesting) goto out; } if (!handler(stream, line, token)) /* all set */ return; out: free_preprocessor_line(token); } static void preprocessor_line(struct stream *stream, struct token **line) { struct token *start = *line, *next; struct token **tp = &start->next; for (;;) { next = *tp; if (next->pos.newline) break; tp = &next->next; } *line = next; *tp = &eof_token_entry; handle_preprocessor_line(stream, line, start); } static void do_preprocess(struct token **list) { struct token *next; while (!eof_token(next = scan_next(list))) { struct stream *stream = input_streams + next->pos.stream; if (next->pos.newline && match_op(next, '#')) { if (!next->pos.noexpand) { preprocessor_line(stream, list); __free_token(next); /* Free the '#' token */ continue; } } switch (token_type(next)) { case TOKEN_STREAMEND: if (stream->top_if) { nesting_error(stream); sparse_error(stream->top_if->pos, "unterminated preprocessor conditional"); stream->top_if = NULL; false_nesting = 0; } if (!stream->dirty) stream->constant = CONSTANT_FILE_YES; *list = next->next; include_level--; continue; case TOKEN_STREAMBEGIN: *list = next->next; include_level++; continue; default: dirty_stream(stream); if (false_nesting) { *list = next->next; __free_token(next); continue; } if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list)) list = &next->next; } } } struct token * preprocess(struct token *token) { preprocessing = 1; init_preprocessor(); do_preprocess(&token); // Drop all expressions from preprocessing, they're not used any more. // This is not true when we have multiple files, though ;/ // clear_expression_alloc(); preprocessing = 0; return token; } static int is_VA_ARGS_token(struct token *token) { return (token_type(token) == TOKEN_IDENT) && (token->ident == &__VA_ARGS___ident); } static void dump_macro(struct symbol *sym) { int nargs = sym->arglist ? sym->arglist->count.normal : 0; struct token *args[nargs]; struct token *token; printf("#define %s", show_ident(sym->ident)); token = sym->arglist; if (token) { const char *sep = ""; int narg = 0; putchar('('); for (; !eof_token(token); token = token->next) { if (token_type(token) == TOKEN_ARG_COUNT) continue; if (is_VA_ARGS_token(token)) printf("%s...", sep); else printf("%s%s", sep, show_token(token)); args[narg++] = token; sep = ","; } putchar(')'); } token = sym->expansion; while (token_type(token) != TOKEN_UNTAINT) { struct token *next = token->next; if (token->pos.whitespace) putchar(' '); switch (token_type(token)) { case TOKEN_CONCAT: printf("##"); break; case TOKEN_STR_ARGUMENT: printf("#"); /* fall-through */ case TOKEN_QUOTED_ARGUMENT: case TOKEN_MACRO_ARGUMENT: token = args[token->argnum]; /* fall-through */ default: printf("%s", show_token(token)); } token = next; } putchar('\n'); } void dump_macro_definitions(void) { struct ident *name; FOR_EACH_PTR(macros, name) { struct symbol *sym = lookup_macro(name); if (sym) dump_macro(sym); } END_FOR_EACH_PTR(name); }
24.179384
119
0.656184
[ "object" ]
a99eabc8d26708414ad4c71ead49c1a280c03a0e
14,717
h
C
aws-cpp-sdk-sns/include/aws/sns/model/CreateTopicRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-sns/include/aws/sns/model/CreateTopicRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-sns/include/aws/sns/model/CreateTopicRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/sns/SNS_EXPORTS.h> #include <aws/sns/SNSRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> namespace Aws { namespace SNS { namespace Model { /** * <p>Input for CreateTopic action.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/sns-2010-03-31/CreateTopicInput">AWS * API Reference</a></p> */ class AWS_SNS_API CreateTopicRequest : public SNSRequest { public: CreateTopicRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateTopic"; } Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline CreateTopicRequest& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline CreateTopicRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the topic you want to create.</p> <p>Constraints: Topic names * must be made up of only uppercase and lowercase ASCII letters, numbers, * underscores, and hyphens, and must be between 1 and 256 characters long.</p> */ inline CreateTopicRequest& WithName(const char* value) { SetName(value); return *this;} /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline const Aws::Map<Aws::String, Aws::String>& GetAttributes() const{ return m_attributes; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline void SetAttributes(const Aws::Map<Aws::String, Aws::String>& value) { m_attributesHasBeenSet = true; m_attributes = value; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline void SetAttributes(Aws::Map<Aws::String, Aws::String>&& value) { m_attributesHasBeenSet = true; m_attributes = std::move(value); } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& WithAttributes(const Aws::Map<Aws::String, Aws::String>& value) { SetAttributes(value); return *this;} /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& WithAttributes(Aws::Map<Aws::String, Aws::String>&& value) { SetAttributes(std::move(value)); return *this;} /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(const Aws::String& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, value); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(Aws::String&& key, const Aws::String& value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), value); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(const Aws::String& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, std::move(value)); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(Aws::String&& key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), std::move(value)); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(const char* key, Aws::String&& value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, std::move(value)); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(Aws::String&& key, const char* value) { m_attributesHasBeenSet = true; m_attributes.emplace(std::move(key), value); return *this; } /** * <p>A map of attributes with their corresponding values.</p> <p>The following * lists the names, descriptions, and values of the special request parameters that * the <code>CreateTopic</code> action uses:</p> <ul> <li> <p> * <code>DeliveryPolicy</code> – The policy that defines how Amazon SNS retries * failed deliveries to HTTP/S endpoints.</p> </li> <li> <p> * <code>DisplayName</code> – The display name to use for a topic with SMS * subscriptions.</p> </li> <li> <p> <code>Policy</code> – The policy that defines * who can access your topic. By default, only the topic owner can publish or * subscribe to the topic.</p> </li> </ul> */ inline CreateTopicRequest& AddAttributes(const char* key, const char* value) { m_attributesHasBeenSet = true; m_attributes.emplace(key, value); return *this; } private: Aws::String m_name; bool m_nameHasBeenSet; Aws::Map<Aws::String, Aws::String> m_attributes; bool m_attributesHasBeenSet; }; } // namespace Model } // namespace SNS } // namespace Aws
54.306273
189
0.672827
[ "model" ]
a9a55cff54b1420be524aecfd0877f368975ef8d
2,339
h
C
build/cpp/include/verb/core/HeapElement.h
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
build/cpp/include/verb/core/HeapElement.h
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
build/cpp/include/verb/core/HeapElement.h
harmanpa/verb
f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.4 #ifndef INCLUDED_verb_core_HeapElement #define INCLUDED_verb_core_HeapElement #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_STACK_FRAME(_hx_pos_0bfb9540fffe3df5_290_new) HX_DECLARE_CLASS2(verb,core,HeapElement) namespace verb{ namespace core{ class HXCPP_CLASS_ATTRIBUTES HeapElement_obj : public ::hx::Object { public: typedef ::hx::Object super; typedef HeapElement_obj OBJ_; HeapElement_obj(); public: enum { _hx_ClassId = 0x7ae5c092 }; void __construct( ::Dynamic obj,Float value); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="verb.core.HeapElement") { 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,"verb.core.HeapElement"); } inline static ::hx::ObjectPtr< HeapElement_obj > __new( ::Dynamic obj,Float value) { ::hx::ObjectPtr< HeapElement_obj > __this = new HeapElement_obj(); __this->__construct(obj,value); return __this; } inline static ::hx::ObjectPtr< HeapElement_obj > __alloc(::hx::Ctx *_hx_ctx, ::Dynamic obj,Float value) { HeapElement_obj *__this = (HeapElement_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(HeapElement_obj), true, "verb.core.HeapElement")); *(void **)__this = HeapElement_obj::_hx_vtable; { HX_STACKFRAME(&_hx_pos_0bfb9540fffe3df5_290_new) HXLINE( 291) ( ( ::verb::core::HeapElement)(__this) )->obj = obj; HXLINE( 292) ( ( ::verb::core::HeapElement)(__this) )->value = value; } return __this; } static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~HeapElement_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); ::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("HeapElement",d0,02,20,e3); } ::Dynamic obj; Float value; }; } // end namespace verb } // end namespace core #endif /* INCLUDED_verb_core_HeapElement */
32.041096
131
0.719538
[ "object" ]
a9a63cb95129302645ecf4a462401e2d51ca0943
7,590
h
C
GTE/Mathematics/TCBSplineCurve.h
tranthaiphi/GeometricTools
451e412a0715dbb4fcafbe486ca33d84a404b78d
[ "BSL-1.0" ]
null
null
null
GTE/Mathematics/TCBSplineCurve.h
tranthaiphi/GeometricTools
451e412a0715dbb4fcafbe486ca33d84a404b78d
[ "BSL-1.0" ]
null
null
null
GTE/Mathematics/TCBSplineCurve.h
tranthaiphi/GeometricTools
451e412a0715dbb4fcafbe486ca33d84a404b78d
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2021 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ParametricCurve.h> namespace gte { template <int N, typename Real> class TCBSplineCurve : public ParametricCurve<N, Real> { public: // Construction and destruction. The object copies the input arrays. // The number of points must be at least 2. To validate construction, // create an object as shown: // TCBSplineCurve<N, Real> curve(parameters); // if (!curve) { <constructor failed, handle accordingly>; } TCBSplineCurve(int numPoints, Vector<N, Real> const* points, Real const* times, Real const* tension, Real const* continuity, Real const* bias) : ParametricCurve<N, Real>(numPoints - 1, times) { LogAssert(numPoints >= 2 && points != nullptr, "Invalid input."); mPoints.resize(numPoints); mTension.resize(numPoints); mContinuity.resize(numPoints); mBias.resize(numPoints); std::copy(points, points + numPoints, mPoints.begin()); std::copy(tension, tension + numPoints, mTension.begin()); std::copy(continuity, continuity + numPoints, mContinuity.begin()); std::copy(bias, bias + numPoints, mBias.begin()); int numSegments = numPoints - 1; mA.resize(numSegments); mB.resize(numSegments); mC.resize(numSegments); mD.resize(numSegments); // For now, treat the first point as if it occurred twice. ComputePoly(0, 0, 1, 2); for (int i = 1; i < numSegments - 1; ++i) { ComputePoly(i - 1, i, i + 1, i + 2); } // For now, treat the last point as if it occurred twice. ComputePoly(numSegments - 2, numSegments - 1, numSegments, numSegments); this->mConstructed = true; } virtual ~TCBSplineCurve() { } // Member access. inline int GetNumPoints() const { return static_cast<int>(mPoints.size()); } inline Vector<N, Real> const* GetPoints() const { return &mPoints[0]; } inline Real const* GetTensions() const { return &mTension[0]; } inline Real const* GetContinuities() const { return &mContinuity[0]; } inline Real const* GetBiases() const { return &mBias[0]; } // Evaluation of the curve. The function supports derivative // calculation through order 3; that is, order <= 3 is required. If // you want/ only the position, pass in order of 0. If you want the // position and first derivative, pass in order of 1, and so on. The // output array 'jet' must have enough storage to support the maximum // order. The values are ordered as: position, first derivative, // second derivative, third derivative. virtual void Evaluate(Real t, unsigned int order, Vector<N, Real>* jet) const override { unsigned int const supOrder = ParametricCurve<N, Real>::SUP_ORDER; if (!this->mConstructed || order >= supOrder) { // Return a zero-valued jet for invalid state. for (unsigned int i = 0; i < supOrder; ++i) { jet[i].MakeZero(); } return; } int key; Real dt; GetKeyInfo(t, key, dt); dt /= (this->mTime[key + 1] - this->mTime[key]); // Compute position. jet[0] = mA[key] + dt * (mB[key] + dt * (mC[key] + dt * mD[key])); if (order >= 1) { // Compute first derivative. jet[1] = mB[key] + dt * ((Real)2 * mC[key] + ((Real)3 * dt) * mD[key]); if (order >= 2) { // Compute second derivative. jet[2] = (Real)2 * mC[key] + ((Real)6 * dt) * mD[key]; if (order == 3) { jet[3] = (Real)6 * mD[key]; } } } } protected: // Support for construction. void ComputePoly(int i0, int i1, int i2, int i3) { Vector<N, Real> diff = mPoints[i2] - mPoints[i1]; Real dt = this->mTime[i2] - this->mTime[i1]; // Build multipliers at P1. Real oneMinusT0 = (Real)1 - mTension[i1]; Real oneMinusC0 = (Real)1 - mContinuity[i1]; Real onePlusC0 = (Real)1 + mContinuity[i1]; Real oneMinusB0 = (Real)1 - mBias[i1]; Real onePlusB0 = (Real)1 + mBias[i1]; Real adj0 = (Real)2 * dt / (this->mTime[i2] - this->mTime[i0]); Real out0 = (Real)0.5 * adj0 * oneMinusT0 * onePlusC0 * onePlusB0; Real out1 = (Real)0.5 * adj0 * oneMinusT0 * oneMinusC0 * oneMinusB0; // Build outgoing tangent at P1. Vector<N, Real> tOut = out1 * diff + out0 * (mPoints[i1] - mPoints[i0]); // Build multipliers at point P2. Real oneMinusT1 = (Real)1 - mTension[i2]; Real oneMinusC1 = (Real)1 - mContinuity[i2]; Real onePlusC1 = (Real)1 + mContinuity[i2]; Real oneMinusB1 = (Real)1 - mBias[i2]; Real onePlusB1 = (Real)1 + mBias[i2]; Real adj1 = (Real)2 * dt / (this->mTime[i3] - this->mTime[i1]); Real in0 = (Real)0.5 * adj1 * oneMinusT1 * oneMinusC1 * onePlusB1; Real in1 = (Real)0.5 * adj1 * oneMinusT1 * onePlusC1 * oneMinusB1; // Build incoming tangent at P2. Vector<N, Real> tIn = in1 * (mPoints[i3] - mPoints[i2]) + in0 * diff; mA[i1] = mPoints[i1]; mB[i1] = tOut; mC[i1] = (Real)3 * diff - (Real)2 * tOut - tIn; mD[i1] = (Real)-2 * diff + tOut + tIn; } // Determine the index i for which times[i] <= t < times[i+1]. void GetKeyInfo(Real t, int& key, Real& dt) const { int numSegments = static_cast<int>(mA.size()); if (t <= this->mTime[0]) { key = 0; dt = (Real)0; return; } if (t < this->mTime[numSegments]) { for (int i = 0; i < numSegments; ++i) { if (t < this->mTime[i + 1]) { key = i; dt = t - this->mTime[i]; return; } } } key = numSegments - 1; dt = this->mTime[numSegments] - this->mTime[numSegments - 1]; } std::vector<Vector<N, Real>> mPoints; std::vector<Real> mTension, mContinuity, mBias; // Polynomial coefficients. mA are the degree 0 coefficients, mB are // the degree 1 coefficients, mC are the degree 2 coefficients, and mD // are the degree 3 coefficients. std::vector<Vector<N, Real>> mA, mB, mC, mD; }; }
36.142857
94
0.505007
[ "object", "vector" ]
a9ad44ab6b897fe9e5f99e728f6409741f1a8374
962
h
C
src/math/mesh/Mesh.h
gaetano-foster/SoftwareRasterizer_PGE
85ba331de3a95d424a8663caf6491ac57af375ef
[ "MIT" ]
null
null
null
src/math/mesh/Mesh.h
gaetano-foster/SoftwareRasterizer_PGE
85ba331de3a95d424a8663caf6491ac57af375ef
[ "MIT" ]
null
null
null
src/math/mesh/Mesh.h
gaetano-foster/SoftwareRasterizer_PGE
85ba331de3a95d424a8663caf6491ac57af375ef
[ "MIT" ]
null
null
null
#ifndef MESH_H #define MESH_H #include "../Maths.h" struct Mesh { std::vector<Triangle> tris; olc::Sprite *texture; bool LoadFromObjectFile(std::string file_name, bool has_texture = false); void Render(Vec3D vCamera, Mat4x4 matProj, olc::PixelGameEngine *engine, float *pDepthBuffer, Mat4x4 matWorld, Mat4x4 matView, bool wireframe = false); }; struct RasterableTriangle { Triangle tri; float brightness; void Raster(olc::PixelGameEngine *engine, olc::Sprite *texture, float *depth_buffer, bool wireframe = false); }; int TriangleClipAgainstPlane(Vec3D plane_p, Vec3D plane_n, Triangle &in_tri, Triangle &out_tri1, Triangle &out_tri2); void ShadeTriangle(int x1, int y1, float u1, float v1, float w1, int x2, int y2, float u2, float v2, float w2, int x3, int y3, float u3, float v3, float w3, olc::Sprite *tex, olc::PixelGameEngine *engine, float *depth_buffer, float brightness); #endif
34.357143
155
0.706861
[ "mesh", "render", "vector" ]
a9ad65807918f584710c590bdb6a1f022b4106e9
9,405
h
C
include/fastrtps/log/Log.h
nuclearsandwich/Fast-RTPS
1daad8f65541b292ff4a023021fd87f0eb6c2faa
[ "Apache-2.0" ]
2
2019-03-08T17:38:46.000Z
2019-07-25T15:01:49.000Z
include/fastrtps/log/Log.h
nuclearsandwich/Fast-RTPS
1daad8f65541b292ff4a023021fd87f0eb6c2faa
[ "Apache-2.0" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/fastrtps/log/Log.h
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2018-12-20T17:38:24.000Z
2019-04-12T07:48:37.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef _FASTRTPS_LOG_LOG_H_ #define _FASTRTPS_LOG_LOG_H_ #include <fastrtps/utils/DBQueue.h> #include <fastrtps/fastrtps_dll.h> #include <thread> #include <sstream> #include <atomic> #include <regex> /** * eProsima log layer. Logging categories and verbosities can be specified dynamically at runtime. However, even on a category * not covered by the current verbosity level, there is some overhead on calling a log macro. For maximum performance, you can * opt out of logging any particular level by defining the following symbols: * * * #define LOG_NO_ERROR * * #define LOG_NO_WARNING * * #define LOG_NO_INFO * * Additionally. the lowest level (Info) is disabled by default on release branches. */ // Logging API: //! Logs an info message. Disable it through Log::SetVerbosity, #define LOG_NO_INFO, or being in a release branch #define logInfo(cat, msg) logInfo_(cat, msg) //! Logs a warning. Disable reporting through Log::SetVerbosity or #define LOG_NO_WARNING #define logWarning(cat, msg) logWarning_(cat, msg) //! Logs an error. Disable reporting through #define LOG_NO_ERROR #define logError(cat, msg) logError_(cat, msg) namespace eprosima { namespace fastrtps { class LogConsumer; /** * Logging utilities. * Logging is accessed through the three macros above, and configuration on the log output * can be achieved through static methods on the class. Logging at various levels can be * disabled dynamically (through the Verbosity level) or statically (through the LOG_NO_[VERB] * macros) for maximum performance. * @ingroup COMMON_MODULE */ class Log { public: /** * Types of log entry. * * Error: Maximum priority. Can only be disabled statically through #define LOG_NO_ERROR. * * Warning: Medium priority. Can be disabled statically and dynamically. * * Info: Low priority. Useful for debugging. Disabled by default on release branches. */ enum Kind { Error, Warning, Info, }; /** * Registers an user defined consumer to route log output. * There is a default stdout consumer active as default. * @param consumer r-value to a consumer unique_ptr. It will be invalidated after the call. */ RTPS_DllAPI static void RegisterConsumer(std::unique_ptr<LogConsumer> &&); //! Removes all registered consumers, including the default stdout. RTPS_DllAPI static void ClearConsumers(); //! Enables the reporting of filenames in log entries. Disabled by default. RTPS_DllAPI static void ReportFilenames(bool); //! Enables the reporting of function names in log entries. Enabled by default when supported. RTPS_DllAPI static void ReportFunctions(bool); //! Sets the verbosity level, allowing for messages equal or under that priority to be logged. RTPS_DllAPI static void SetVerbosity(Log::Kind); //! Returns the current verbosity level. RTPS_DllAPI static Log::Kind GetVerbosity(); //! Sets a filter that will pattern-match against log categories, dropping any unmatched categories. RTPS_DllAPI static void SetCategoryFilter(const std::regex &); //! Sets a filter that will pattern-match against filenames, dropping any unmatched categories. RTPS_DllAPI static void SetFilenameFilter(const std::regex &); //! Sets a filter that will pattern-match against the provided error string, dropping any unmatched categories. RTPS_DllAPI static void SetErrorStringFilter(const std::regex &); //! Returns the logging engine to configuration defaults. RTPS_DllAPI static void Reset(); //! Stops the logging thread. It will re-launch on the next call to a successful log macro. RTPS_DllAPI static void KillThread(); // Note: In VS2013, if you're linking this class statically, you will have to call KillThread before leaving // main, due to an unsolved MSVC bug. struct Context { const char *filename; int line; const char *function; const char *category; }; struct Entry { std::string message; Log::Context context; Log::Kind kind; std::string timestamp; }; /** * Not recommended to call this method directly! Use the following macros: * * logInfo(cat, msg); * * logWarning(cat, msg); * * logError(cat, msg); */ RTPS_DllAPI static void QueueLog(const std::string &message, const Log::Context &, Log::Kind); private: struct Resources { DBQueue<Entry> mLogs; std::vector<std::unique_ptr<LogConsumer>> mConsumers; std::unique_ptr<std::thread> mLoggingThread; // Condition variable segment. std::condition_variable mCv; std::mutex mCvMutex; bool mLogging; bool mWork; // Context configuration. std::mutex mConfigMutex; bool mFilenames; bool mFunctions; std::unique_ptr<std::regex> mCategoryFilter; std::unique_ptr<std::regex> mFilenameFilter; std::unique_ptr<std::regex> mErrorStringFilter; std::atomic<Log::Kind> mVerbosity; Resources(); ~Resources(); }; static struct Resources mResources; // Applies transformations to the entries compliant with the options selected (such as // erasure of certain context information, or filtering by category. Returns false // if the log entry is blacklisted. static bool Preprocess(Entry &); static void LaunchThread(); static void Run(); static void GetTimestamp(std::string &); }; /** * Consumes a log entry to output it somewhere. */ class LogConsumer { public: virtual ~LogConsumer(){}; virtual void Consume(const Log::Entry &) = 0; protected: void PrintTimestamp(std::ostream &stream, const Log::Entry &, bool color) const; void PrintHeader(std::ostream &stream, const Log::Entry &, bool color) const; void PrintContext(std::ostream &stream, const Log::Entry &, bool color) const; void PrintMessage(std::ostream &stream, const Log::Entry &, bool color) const; void PrintNewLine(std::ostream &stream, bool color) const; }; #if defined(WIN32) #define __func__ __FUNCTION__ #endif #ifndef LOG_NO_ERROR #define logError_(cat, msg) \ { \ std::stringstream ss; \ ss << msg; \ Log::QueueLog(ss.str(), Log::Context{__FILE__, __LINE__, __func__, #cat}, Log::Kind::Error); \ } #else #define logError_(cat, msg) #endif #ifndef LOG_NO_WARNING #define logWarning_(cat, msg) \ { \ if (Log::GetVerbosity() >= Log::Kind::Warning) \ { \ std::stringstream ss; \ ss << msg; \ Log::QueueLog(ss.str(), Log::Context{__FILE__, __LINE__, __func__, #cat}, Log::Kind::Warning); \ } \ } #else #define logWarning_(cat, msg) #endif #if (defined(__INTERNALDEBUG) || defined(_INTERNALDEBUG)) && (defined(_DEBUG) || defined(__DEBUG)) && (!defined(LOG_NO_INFO)) #define logInfo_(cat, msg) \ { \ if (Log::GetVerbosity() >= Log::Kind::Info) \ { \ std::stringstream ss; \ ss << msg; \ Log::QueueLog(ss.str(), Log::Context{__FILE__, __LINE__, __func__, #cat}, Log::Kind::Info); \ } \ } #else #define logInfo_(cat, msg) #endif } // namespace fastrtps } // namespace eprosima #endif
40.538793
126
0.578416
[ "vector" ]
a9aff379d0f93d28897a0f567fa569b39eaa8a54
1,604
h
C
include/public/BlackBox/Profiler/Hole_array.h
kovdennik/TestEngine
43e8d51f64c1a576ff812126d44ee43d8e25bdef
[ "MIT" ]
1
2019-12-10T00:37:05.000Z
2019-12-10T00:37:05.000Z
include/public/BlackBox/Profiler/Hole_array.h
kovdennik/TestEngine
43e8d51f64c1a576ff812126d44ee43d8e25bdef
[ "MIT" ]
3
2020-02-17T21:12:09.000Z
2022-01-19T10:28:02.000Z
include/public/BlackBox/Profiler/Hole_array.h
kovdennik/TestEngine
43e8d51f64c1a576ff812126d44ee43d8e25bdef
[ "MIT" ]
3
2019-03-14T16:28:47.000Z
2020-05-17T20:42:55.000Z
// hole_array.h #ifndef HOLE_ARRAY_H #define HOLE_ARRAY_H #include <stddef.h> #include <assert.h> #include <vector> template<class T, const size_t max_size> class HoleArray { public: static const size_t MAX_SIZE = max_size; private: T m_elements[MAX_SIZE]; std::vector<bool> m_used; // vector<bool> is optimized for space volatile size_t m_size; public: HoleArray() : m_used(MAX_SIZE, false), m_size(0) { } size_t getSize()const { return m_size; } size_t getMaxSize() const { return MAX_SIZE; } T* getPtr() { return m_elements; } const T* getPtr() const { return m_elements; } T& operator[](size_t i) { assert(m_used[i]); return m_elements[i]; } const T& operator[](size_t i) const { assert(m_used[i]); return m_elements[i]; } T& get(size_t i) { assert(m_used[i]); return m_elements[i]; } const T& get(size_t i) const { assert(m_used[i]); return m_elements[i]; } bool isUsed(size_t i) const { return m_used[i]; } size_t add() { assert(m_size + 1 < MAX_SIZE); size_t i = 0; while (m_used[i]) i++; m_used[i] = true; m_size++; return i; } void remove(size_t i) { assert(i < MAX_SIZE); m_used[i] = false; m_size--; } // Usage: for(size_t i = array.begin(); i != array.getMaxSize() ; i = array.next(i)) size_t begin() const { if (m_size == 0) return MAX_SIZE; size_t i = 0; while (i < MAX_SIZE && !m_used[i]) i++; return i; } size_t next(size_t i) const { i++; while (i < MAX_SIZE && !m_used[i]) i++; return i; } }; #endif // HOLE_ARRAY_H
20.05
86
0.611596
[ "vector" ]
a9b730ddba119ea69e6f420bd9bf22a9a37487aa
6,639
h
C
aistreams/c/c_api.h
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
null
null
null
aistreams/c/c_api.h
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
null
null
null
aistreams/c/c_api.h
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AISTREAMS_C_C_API_H_ #define AISTREAMS_C_C_API_H_ #include <stddef.h> #include <stdint.h> #include "aistreams/c/ais_gstreamer_buffer.h" #include "aistreams/c/ais_packet.h" #include "aistreams/c/ais_packet_as.h" #include "aistreams/c/ais_status.h" // -------------------------------------------------------------------------- // C API for AI Streamer. // // + We use the prefix AIS_ for everything in the API. // + Objects are always passed around as pointers to opaque structs // and these structs are allocated/deallocated via the API. // + Every call that has a AIS_Status* argument clears it on success // and fills it with error info on failure. // + unsigned char is used for booleans, rather than using the "bool" macro // defined in stdbool.h. #ifdef __cplusplus extern "C" { #endif // -------------------------------------------------------------------------- // AIS_ConnectionOptions contain options to connect to an AI Streamer server. typedef struct AIS_ConnectionOptions AIS_ConnectionOptions; // Return a new connection options object. extern AIS_ConnectionOptions* AIS_NewConnectionOptions(void); // Delete a connection options object. extern void AIS_DeleteConnectionOptions(AIS_ConnectionOptions*); // Set the target address (ip:port) to the server (the k8s Ingress). extern void AIS_SetTargetAddress(const char* target_adress, AIS_ConnectionOptions* options); // Set to 1 when interacting with the google managed service; 0 otherwise. extern void AIS_SetAuthenticateWithGoogle( unsigned char authenticate_with_google, AIS_ConnectionOptions* options); // Set whether to use an insecure connection to the server. extern void AIS_SetUseInsecureChannel(unsigned char use_insecure_channel, AIS_ConnectionOptions* options); // Set the expected SSL domain name of the server. // // You are required to supply this if you do not use an insecure channel. extern void AIS_SetSslDomainName(const char* ssl_domain_name, AIS_ConnectionOptions* options); // Set the path to the root CA certificate. // // You are required to supply this if you do not use an insecure channel. extern void AIS_SetSslRootCertPath(const char* ssl_root_cert_path, AIS_ConnectionOptions* options); // -------------------------------------------------------------------------- // Functions to manage remote stream resources that reside on the server. // Create a stream named `stream_name` on the server specified by `options`. extern void AIS_CreateStream(const AIS_ConnectionOptions* options, const char* stream_name, AIS_Status* ais_status); // Delete a stream named `stream_name` on the server specified by `options`. extern void AIS_DeleteStream(const AIS_ConnectionOptions* options, const char* stream_name, AIS_Status* ais_status); // -------------------------------------------------------------------------- // Functions to send packets to a stream on the server. // Represents a packet sender. typedef struct AIS_Sender AIS_Sender; // Return a new packet sender object on success and NULL otherwise. // // On success, the AIS_Sender will have established a connection to the stream // server specified in options and fully initialized for use. extern AIS_Sender* AIS_NewSender(const AIS_ConnectionOptions* options, const char* stream_name, AIS_Status* ais_status); // Delete a packet sender object. extern void AIS_DeleteSender(AIS_Sender* ais_sender); // Send a packet through the packet sender. // // Typically, you would use one of the packet creaters in ais_packet.h to // create a Packet. You are still the owner of the AIS_Packet and you should // make sure to delete. // // After this call, the packet supplied will be in a deletable state; however, // attemping to access values in the packet afterwards is undefined behavior. extern void AIS_SendPacket(AIS_Sender* ais_sender, AIS_Packet* ais_packet, AIS_Status* ais_status); // -------------------------------------------------------------------------- // Functions to receive packets from a stream on the server. // Represents a packet receiver. typedef struct AIS_Receiver AIS_Receiver; // Return a new packet receiver object. NULL otherwise. // // `stream_name`: specifies the name of the stream from which to receive from. // `receiver_name`: specifies a name you use to receive. A random name will be // generated for you if NULL. extern AIS_Receiver* AIS_NewReceiver(const AIS_ConnectionOptions* options, const char* stream_name, const char* receiver_name, AIS_Status* ais_status); // Delete a packet receiver object. extern void AIS_DeleteReceiver(AIS_Receiver* ais_receiver); // Receive a packet through the packet receiver. // // You need to create a new packet object to receive the value from the // receiver. As usual, you will have to delete the packet when you are done. // // On success, the packet supplied will contain a fresh packet value from the // receiver. On failure, the packet supplied will be in a deleteable state but // accessing its value is undefined behavior. You may re-use the same packet to // receive new values across multiple calls independent of whether the previous // calls succeeded or failed. // // `timeout_in_sec`: If non-negative, then this call will block up to the // the specified number of seconds to receive a packet // from the server. If negative, then wait with no timeout. extern void AIS_ReceivePacket(AIS_Receiver* ais_receiver, AIS_Packet* ais_packet, int timeout_in_sec, AIS_Status* ais_status); #ifdef __cplusplus } // end extern "C" #endif #endif // AISTREAMS_C_C_API_H_
41.754717
79
0.673144
[ "object" ]
a9c0e4331eacff05dcf91d9d3613954508f4ef9d
1,613
h
C
Gems/Atom/RHI/Metal/Code/Source/RHI/ImagePool.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RHI/Metal/Code/Source/RHI/ImagePool.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RHI/Metal/Code/Source/RHI/ImagePool.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <Atom/RHI/ImagePool.h> namespace AZ { namespace Metal { class ImagePoolResolver; class Device; class ImagePool final : public RHI::ImagePool { using Base = RHI::ImagePool; public: AZ_CLASS_ALLOCATOR(ImagePool, AZ::SystemAllocator, 0); AZ_RTTI(ImagePool, "{04E85806-9E84-4BD0-99F6-EEBA32B1C4F7}", RHI::ImagePool); static RHI::Ptr<ImagePool> Create(); Device& GetDevice() const; ImagePoolResolver* GetResolver(); private: ImagePool() = default; void AddMemoryUsage(size_t bytesToAdd); void SubtractMemoryUsage(size_t bytesToSubtract); ////////////////////////////////////////////////////////////////////////// // RHI::ImagePool RHI::ResultCode InitInternal(RHI::Device&, const RHI::ImagePoolDescriptor&) override; RHI::ResultCode InitImageInternal(const RHI::ImageInitRequest& request) override; RHI::ResultCode UpdateImageContentsInternal(const RHI::ImageUpdateRequest& request) override; void ShutdownResourceInternal(RHI::Resource& resourceBase) override; ////////////////////////////////////////////////////////////////////////// }; } }
34.319149
105
0.550527
[ "3d" ]
a9c2ffcf3e9443090af582713cc051c1e6d39313
15,430
c
C
src/compiler/nir/nir_lower_gs_intrinsics.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/compiler/nir/nir_lower_gs_intrinsics.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
src/compiler/nir/nir_lower_gs_intrinsics.c
SoftReaper/Mesa-Renoir-deb
8d1de1f66058d62b41fe55d36522efea2bdf996d
[ "MIT" ]
null
null
null
/* * Copyright © 2015 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "nir.h" #include "nir_builder.h" #include "nir_xfb_info.h" /** * \file nir_lower_gs_intrinsics.c * * Geometry Shaders can call EmitVertex()/EmitStreamVertex() to output an * arbitrary number of vertices. However, the shader must declare the maximum * number of vertices that it will ever output - further attempts to emit * vertices result in undefined behavior according to the GLSL specification. * * Drivers might use this maximum number of vertices to allocate enough space * to hold the geometry shader's output. Some drivers (such as i965) need to * implement "safety checks" which ensure that the shader hasn't emitted too * many vertices, to avoid overflowing that space and trashing other memory. * * The count of emitted vertices can also be useful in buffer offset * calculations, so drivers know where to write the GS output. * * However, for simple geometry shaders that emit a statically determinable * number of vertices, this extra bookkeeping is unnecessary and inefficient. * By tracking the vertex count in NIR, we allow constant folding/propagation * and dead control flow optimizations to eliminate most of it where possible. * * This pass introduces a new global variable which stores the current vertex * count (initialized to 0), and converts emit_vertex/end_primitive intrinsics * to their *_with_counter variants. emit_vertex is also wrapped in a safety * check to avoid buffer overflows. Finally, it adds a set_vertex_count * intrinsic at the end of the program, informing the driver of the final * vertex count. */ struct state { nir_builder *builder; nir_variable *vertex_count_vars[NIR_MAX_XFB_STREAMS]; nir_variable *vtxcnt_per_prim_vars[NIR_MAX_XFB_STREAMS]; nir_variable *primitive_count_vars[NIR_MAX_XFB_STREAMS]; bool per_stream; bool count_prims; bool count_vtx_per_prim; bool overwrite_incomplete; bool progress; }; /** * Replace emit_vertex intrinsics with: * * if (vertex_count < max_vertices) { * emit_vertex_with_counter vertex_count, vertex_count_per_primitive (optional) ... * vertex_count += 1 * vertex_count_per_primitive += 1 * } */ static void rewrite_emit_vertex(nir_intrinsic_instr *intrin, struct state *state) { nir_builder *b = state->builder; unsigned stream = nir_intrinsic_stream_id(intrin); /* Load the vertex count */ b->cursor = nir_before_instr(&intrin->instr); assert(state->vertex_count_vars[stream] != NULL); nir_ssa_def *count = nir_load_var(b, state->vertex_count_vars[stream]); nir_ssa_def *count_per_primitive; if (state->count_vtx_per_prim) count_per_primitive = nir_load_var(b, state->vtxcnt_per_prim_vars[stream]); else count_per_primitive = nir_ssa_undef(b, 1, 32); nir_ssa_def *max_vertices = nir_imm_int(b, b->shader->info.gs.vertices_out); /* Create: if (vertex_count < max_vertices) and insert it. * * The new if statement needs to be hooked up to the control flow graph * before we start inserting instructions into it. */ nir_push_if(b, nir_ilt(b, count, max_vertices)); nir_emit_vertex_with_counter(b, count, count_per_primitive, stream); /* Increment the vertex count by 1 */ nir_store_var(b, state->vertex_count_vars[stream], nir_iadd_imm(b, count, 1), 0x1); /* .x */ if (state->count_vtx_per_prim) { /* Increment the per-primitive vertex count by 1 */ nir_variable *var = state->vtxcnt_per_prim_vars[stream]; nir_ssa_def *vtx_per_prim_cnt = nir_load_var(b, var); nir_store_var(b, var, nir_iadd_imm(b, vtx_per_prim_cnt, 1), 0x1); /* .x */ } nir_pop_if(b, NULL); nir_instr_remove(&intrin->instr); state->progress = true; } /** * Emits code that overwrites incomplete primitives and their vertices. * * A primitive is considered incomplete when it doesn't have enough vertices. * For example, a triangle strip that has 2 or fewer vertices, or a line strip * with 1 vertex are considered incomplete. * * After each end_primitive and at the end of the shader before emitting * set_vertex_and_primitive_count, we check if the primitive that is being * emitted has enough vertices or not, and we adjust the vertex and primitive * counters accordingly. * * This means that the following emit_vertex can reuse the vertex index of * a previous vertex, if the previous primitive was incomplete, so the compiler * backend is expected to simply overwrite any data that belonged to those. */ static void overwrite_incomplete_primitives(struct state *state, unsigned stream) { assert(state->count_vtx_per_prim); nir_builder *b = state->builder; enum shader_prim outprim = b->shader->info.gs.output_primitive; unsigned outprim_min_vertices; if (outprim == SHADER_PRIM_POINTS) outprim_min_vertices = 1; else if (outprim == SHADER_PRIM_LINE_STRIP) outprim_min_vertices = 2; else if (outprim == SHADER_PRIM_TRIANGLE_STRIP) outprim_min_vertices = 3; else unreachable("Invalid GS output primitive type."); /* Total count of vertices emitted so far. */ nir_ssa_def *vtxcnt_total = nir_load_var(b, state->vertex_count_vars[stream]); /* Number of vertices emitted for the last primitive */ nir_ssa_def *vtxcnt_per_primitive = nir_load_var(b, state->vtxcnt_per_prim_vars[stream]); /* See if the current primitive is a incomplete */ nir_ssa_def *is_inc_prim = nir_ilt(b, vtxcnt_per_primitive, nir_imm_int(b, outprim_min_vertices)); /* Number of vertices in the incomplete primitive */ nir_ssa_def *num_inc_vtx = nir_bcsel(b, is_inc_prim, vtxcnt_per_primitive, nir_imm_int(b, 0)); /* Store corrected total vertex count */ nir_store_var(b, state->vertex_count_vars[stream], nir_isub(b, vtxcnt_total, num_inc_vtx), 0x1); /* .x */ if (state->count_prims) { /* Number of incomplete primitives (0 or 1) */ nir_ssa_def *num_inc_prim = nir_b2i32(b, is_inc_prim); /* Store corrected primitive count */ nir_ssa_def *prim_cnt = nir_load_var(b, state->primitive_count_vars[stream]); nir_store_var(b, state->primitive_count_vars[stream], nir_isub(b, prim_cnt, num_inc_prim), 0x1); /* .x */ } } /** * Replace end_primitive with end_primitive_with_counter. */ static void rewrite_end_primitive(nir_intrinsic_instr *intrin, struct state *state) { nir_builder *b = state->builder; unsigned stream = nir_intrinsic_stream_id(intrin); b->cursor = nir_before_instr(&intrin->instr); assert(state->vertex_count_vars[stream] != NULL); nir_ssa_def *count = nir_load_var(b, state->vertex_count_vars[stream]); nir_ssa_def *count_per_primitive; if (state->count_vtx_per_prim) count_per_primitive = nir_load_var(b, state->vtxcnt_per_prim_vars[stream]); else count_per_primitive = nir_ssa_undef(b, count->num_components, count->bit_size); nir_end_primitive_with_counter(b, count, count_per_primitive, stream); if (state->count_prims) { /* Increment the primitive count by 1 */ nir_ssa_def *prim_cnt = nir_load_var(b, state->primitive_count_vars[stream]); nir_store_var(b, state->primitive_count_vars[stream], nir_iadd_imm(b, prim_cnt, 1), 0x1); /* .x */ } if (state->count_vtx_per_prim) { if (state->overwrite_incomplete) overwrite_incomplete_primitives(state, stream); /* Store 0 to per-primitive vertex count */ nir_store_var(b, state->vtxcnt_per_prim_vars[stream], nir_imm_int(b, 0), 0x1); /* .x */ } nir_instr_remove(&intrin->instr); state->progress = true; } static bool rewrite_intrinsics(nir_block *block, struct state *state) { nir_foreach_instr_safe(instr, block) { if (instr->type != nir_instr_type_intrinsic) continue; nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr); switch (intrin->intrinsic) { case nir_intrinsic_emit_vertex: case nir_intrinsic_emit_vertex_with_counter: rewrite_emit_vertex(intrin, state); break; case nir_intrinsic_end_primitive: case nir_intrinsic_end_primitive_with_counter: rewrite_end_primitive(intrin, state); break; default: /* not interesting; skip this */ break; } } return true; } /** * Add a set_vertex_and_primitive_count intrinsic at the end of the program * (representing the final total vertex and primitive count). */ static void append_set_vertex_and_primitive_count(nir_block *end_block, struct state *state) { nir_builder *b = state->builder; nir_shader *shader = state->builder->shader; /* Insert the new intrinsic in all of the predecessors of the end block, * but before any jump instructions (return). */ set_foreach(end_block->predecessors, entry) { nir_block *pred = (nir_block *) entry->key; b->cursor = nir_after_block_before_jump(pred); for (unsigned stream = 0; stream < NIR_MAX_XFB_STREAMS; ++stream) { /* When it's not per-stream, we only need to write one variable. */ if (!state->per_stream && stream != 0) continue; nir_ssa_def *vtx_cnt; nir_ssa_def *prim_cnt; if (state->per_stream && !(shader->info.gs.active_stream_mask & (1 << stream))) { /* Inactive stream: vertex count is 0, primitive count is 0 or undef. */ vtx_cnt = nir_imm_int(b, 0); prim_cnt = state->count_prims ? nir_imm_int(b, 0) : nir_ssa_undef(b, 1, 32); } else { if (state->overwrite_incomplete) overwrite_incomplete_primitives(state, stream); vtx_cnt = nir_load_var(b, state->vertex_count_vars[stream]); prim_cnt = state->count_prims ? nir_load_var(b, state->primitive_count_vars[stream]) : nir_ssa_undef(b, 1, 32); } nir_set_vertex_and_primitive_count(b, vtx_cnt, prim_cnt, stream); state->progress = true; } } } /** * Check to see if there are any blocks that need set_vertex_and_primitive_count * * If every block that could need the set_vertex_and_primitive_count intrinsic * already has one, there is nothing for this pass to do. */ static bool a_block_needs_set_vertex_and_primitive_count(nir_block *end_block, bool per_stream) { set_foreach(end_block->predecessors, entry) { nir_block *pred = (nir_block *) entry->key; for (unsigned stream = 0; stream < NIR_MAX_XFB_STREAMS; ++stream) { /* When it's not per-stream, we only need to write one variable. */ if (!per_stream && stream != 0) continue; bool found = false; nir_foreach_instr_reverse(instr, pred) { if (instr->type != nir_instr_type_intrinsic) continue; const nir_intrinsic_instr *const intrin = nir_instr_as_intrinsic(instr); if (intrin->intrinsic == nir_intrinsic_set_vertex_and_primitive_count && intrin->const_index[0] == stream) { found = true; break; } } if (!found) return true; } } return false; } bool nir_lower_gs_intrinsics(nir_shader *shader, nir_lower_gs_intrinsics_flags options) { bool per_stream = options & nir_lower_gs_intrinsics_per_stream; bool count_primitives = options & nir_lower_gs_intrinsics_count_primitives; bool overwrite_incomplete = options & nir_lower_gs_intrinsics_overwrite_incomplete; bool count_vtx_per_prim = overwrite_incomplete || (options & nir_lower_gs_intrinsics_count_vertices_per_primitive); struct state state; state.progress = false; state.count_prims = count_primitives; state.count_vtx_per_prim = count_vtx_per_prim; state.overwrite_incomplete = overwrite_incomplete; state.per_stream = per_stream; nir_function_impl *impl = nir_shader_get_entrypoint(shader); assert(impl); if (!a_block_needs_set_vertex_and_primitive_count(impl->end_block, per_stream)) return false; nir_builder b; nir_builder_init(&b, impl); state.builder = &b; b.cursor = nir_before_cf_list(&impl->body); for (unsigned i = 0; i < NIR_MAX_XFB_STREAMS; i++) { if (per_stream && !(shader->info.gs.active_stream_mask & (1 << i))) continue; if (i == 0 || per_stream) { state.vertex_count_vars[i] = nir_local_variable_create(impl, glsl_uint_type(), "vertex_count"); /* initialize to 0 */ nir_store_var(&b, state.vertex_count_vars[i], nir_imm_int(&b, 0), 0x1); if (count_primitives) { state.primitive_count_vars[i] = nir_local_variable_create(impl, glsl_uint_type(), "primitive_count"); /* initialize to 1 */ nir_store_var(&b, state.primitive_count_vars[i], nir_imm_int(&b, 1), 0x1); } if (count_vtx_per_prim) { state.vtxcnt_per_prim_vars[i] = nir_local_variable_create(impl, glsl_uint_type(), "vertices_per_primitive"); /* initialize to 0 */ nir_store_var(&b, state.vtxcnt_per_prim_vars[i], nir_imm_int(&b, 0), 0x1); } } else { /* If per_stream is false, we only have one counter of each kind which we * want to use for all streams. Duplicate the counter pointers so all * streams use the same counters. */ state.vertex_count_vars[i] = state.vertex_count_vars[0]; if (count_primitives) state.primitive_count_vars[i] = state.primitive_count_vars[0]; if (count_vtx_per_prim) state.vtxcnt_per_prim_vars[i] = state.vtxcnt_per_prim_vars[0]; } } nir_foreach_block_safe(block, impl) rewrite_intrinsics(block, &state); /* This only works because we have a single main() function. */ append_set_vertex_and_primitive_count(impl->end_block, &state); nir_metadata_preserve(impl, 0); return state.progress; }
35.967366
91
0.687103
[ "geometry" ]
a9c6128f86acc064907fb019f5e0db0d733f4fea
11,138
h
C
src/utils/xrSE_Factory/script_properties_list_helper.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/utils/xrSE_Factory/script_properties_list_helper.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/utils/xrSE_Factory/script_properties_list_helper.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
//////////////////////////////////////////////////////////////////////////// // Module : script_properties_list_helper.h // Created : 14.07.2004 // Modified : 14.07.2004 // Author : Dmitriy Iassenev // Description : Script properties list helper //////////////////////////////////////////////////////////////////////////// #pragma once #include "xrCDB/xrCDB.h" #ifndef XRGAME_EXPORTS #include "xrSound/Sound.h" #endif #include "xrServerEntities\xrEProps.h" #include "xrServerEntities\script_rtoken_list.h" #include "script_space.h" class CScriptTokenList; struct CScriptPropertiesListHelper { public: bool FvectorRDOnAfterEdit(PropValue* sender, Fvector& edit_val); void FvectorRDOnBeforeEdit(PropValue* sender, Fvector& edit_val); // void FvectorRDOnDraw (PropValue* sender, LPCSTR& draw_val); bool floatRDOnAfterEdit(PropValue* sender, float& edit_val); void floatRDOnBeforeEdit(PropValue* sender, float& edit_val); // void floatRDOnDraw (PropValue* sender, LPCSTR& draw_val); // name edit bool NameAfterEdit(PropValue* sender, LPCSTR& edit_val); void NameBeforeEdit(PropValue* sender, LPCSTR& edit_val); // void NameDraw (PropValue* sender, LPCSTR& draw_val); public: CaptionValue* CreateCaption(PropItemVec* items, LPCSTR key, LPCSTR val); CanvasValue* CreateCanvas(PropItemVec* items, LPCSTR key, LPCSTR val, int height); ButtonValue* CreateButton(PropItemVec* items, LPCSTR key, LPCSTR val, u32 flags); ChooseValue* CreateChoose(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mode); ChooseValue* CreateChoose( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mode, LPCSTR path); ChooseValue* CreateChoose( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mode, LPCSTR path, LPCSTR fill_param); ChooseValue* CreateChoose(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mode, LPCSTR path, LPCSTR fill_param, u32 sub_item_cnt); // S8Value* CreateS8 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR // name); // S8Value* CreateS8 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, //s8 // mn); // S8Value* CreateS8 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s8 //mn, // s8 mx); // S8Value* CreateS8 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s8 //mn, // s8 mx, s8 inc); S16Value* CreateS16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); S16Value* CreateS16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s16 mn); S16Value* CreateS16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s16 mn, s16 mx); S16Value* CreateS16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s16 mn, s16 mx, s16 inc); S32Value* CreateS32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); S32Value* CreateS32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s32 mn); S32Value* CreateS32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s32 mn, s32 mx); S32Value* CreateS32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, s32 mn, s32 mx, s32 inc); U8Value* CreateU8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); U8Value* CreateU8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mn); U8Value* CreateU8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mn, u8 mx); U8Value* CreateU8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mn, u8 mx, u8 inc); U16Value* CreateU16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); U16Value* CreateU16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mn); U16Value* CreateU16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mn, u16 mx); U16Value* CreateU16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mn, u16 mx, u16 inc); U32Value* CreateU32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); U32Value* CreateU32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mn); U32Value* CreateU32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mn, u32 mx); U32Value* CreateU32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mn, u32 mx, u32 inc); FloatValue* CreateFloat(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); FloatValue* CreateFloat(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn); FloatValue* CreateFloat(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx); FloatValue* CreateFloat( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc); FloatValue* CreateFloat( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc, int decim); BOOLValue* CreateBOOL(PropItemVec* items, LPCSTR key, luabind::object object, luabind::object table, LPCSTR name); VectorValue* CreateVector(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); VectorValue* CreateVector(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn); VectorValue* CreateVector(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx); VectorValue* CreateVector( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc); VectorValue* CreateVector( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc, int decim); Flag8Value* CreateFlag8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mask); Flag8Value* CreateFlag8(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mask, LPCSTR c0); Flag8Value* CreateFlag8( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mask, LPCSTR c0, LPCSTR c1); Flag8Value* CreateFlag8( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u8 mask, LPCSTR c0, LPCSTR c1, u32 flags); Flag16Value* CreateFlag16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mask); Flag16Value* CreateFlag16(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mask, LPCSTR c0); Flag16Value* CreateFlag16( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mask, LPCSTR c0, LPCSTR c1); Flag16Value* CreateFlag16( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u16 mask, LPCSTR c0, LPCSTR c1, u32 flags); Flag32Value* CreateFlag32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mask); Flag32Value* CreateFlag32(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mask, LPCSTR c0); Flag32Value* CreateFlag32( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mask, LPCSTR c0, LPCSTR c1); Flag32Value* CreateFlag32( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, u32 mask, LPCSTR c0, LPCSTR c1, u32 flags); Token8Value* CreateToken8( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, CScriptTokenList* token); Token16Value* CreateToken16( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, CScriptTokenList* token); Token32Value* CreateToken32( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, CScriptTokenList* token); // RToken8Value* CreateRToken8 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // RTokenVec* token); // RToken16Value* CreateRToken16 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // RTokenVec* token); // RToken32Value* CreateRToken32 (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // RTokenVec* token); // TokenValueSH* CreateTokenSH (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // u32 cnt, const TokenValueSH::Item* lst); RListValue* CreateRList( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, CScriptRTokenList* tokens); U32Value* CreateColor(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); ColorValue* CreateFColor(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); VectorValue* CreateVColor(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); RTextValue* CreateRText(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); // WaveValue* CreateWave (PropItemVec* items, LPCSTR key, WaveForm* val); FloatValue* CreateTime(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); FloatValue* CreateTime(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn); FloatValue* CreateTime(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx); FloatValue* CreateAngle(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); FloatValue* CreateAngle(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn); FloatValue* CreateAngle(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx); FloatValue* CreateAngle( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc); FloatValue* CreateAngle( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc, int decim); VectorValue* CreateAngle3(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name); VectorValue* CreateAngle3(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn); VectorValue* CreateAngle3(PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx); VectorValue* CreateAngle3( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc); VectorValue* CreateAngle3( PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR name, float mn, float mx, float inc, int decim); // RTextValue* CreateName (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // ListItem* owner); // RTextValue* CreateNameCB (PropItemVec* items, LPCSTR key, luabind::object object, LPCSTR //name, // TOnDrawTextEvent=0, RTextValue::TOnBeforeEditEvent=0, RTextValue::TOnAfterEditEvent=0 };
64.011494
120
0.712516
[ "object" ]
a9c72e5fc958430b5269d61d6ba5e58ed37572e8
16,730
c
C
src/audio/tdfb/tdfb_direction.c
jairaj-arava/sof
bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79
[ "BSD-3-Clause" ]
null
null
null
src/audio/tdfb/tdfb_direction.c
jairaj-arava/sof
bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79
[ "BSD-3-Clause" ]
null
null
null
src/audio/tdfb/tdfb_direction.c
jairaj-arava/sof
bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79
[ "BSD-3-Clause" ]
1
2022-01-09T19:23:11.000Z
2022-01-09T19:23:11.000Z
// SPDX-License-Identifier: BSD-3-Clause // // Copyright(c) 2021 Intel Corporation. All rights reserved. // // Author: Seppo Ingalsuo <seppo.ingalsuo@linux.intel.com> #include <ipc/topology.h> #include <sof/audio/tdfb/tdfb_comp.h> #include <sof/lib/alloc.h> #include <sof/math/iir_df2t.h> #include <sof/math/trig.h> #include <sof/math/sqrt.h> #include <user/eq.h> #include <stdint.h> /* Generic definitions */ #define COEF_DEG_TO_RAD Q_CONVERT_FLOAT(0.017453, 15) /* Q1.15 */ #define COEF_RAD_TO_DEG Q_CONVERT_FLOAT(57.296, 9) /* Q6.9 */ #define PI_Q12 Q_CONVERT_FLOAT(3.1416, 12) #define PIMUL2_Q12 Q_CONVERT_FLOAT(6.2832, 12) #define PIDIV2_Q12 Q_CONVERT_FLOAT(1.5708, 12) /* Sound levels filtering related, these form a primitive voice activity * detector. Sound levels below ambient estimate times threshold (kind of dB offset) * are not scanned for sound direction. */ #define SLOW_LEVEL_SHIFT 12 #define FAST_LEVEL_SHIFT 1 #define POWER_THRESHOLD Q_CONVERT_FLOAT(15.849, 10) /* 12 dB, value is 10^(dB/10) */ /* Iteration parameters, smaller step and larger iterations is more accurate but * consumes more cycles. */ #define AZ_STEP Q_CONVERT_FLOAT(0.6, 12) /* Radians as Q4.12 (~34 deg) */ #define AZ_ITERATIONS 8 /* loops in min err search */ #define SOURCE_DISTANCE Q_CONVERT_FLOAT(3.0, 12) /* source distance in m Q4.12 */ /* Sound direction angle filtering */ #define SLOW_AZ_C1 Q_CONVERT_FLOAT(0.02, 15) #define SLOW_AZ_C2 Q_CONVERT_FLOAT(0.98, 15) /* Threshold for notifying user space, no more often than every 200 ms */ #define CONTROL_UPDATE_MIN_TIME Q_CONVERT_FLOAT(0.2, 16) /* Emphasis filters for sound direction (IIR). These coefficients were * created with the script tools/tune/tdfb/example_direction_emphasis.m * from output files tdfb_iir_emphasis_48k.h and tdfb_iir_emphasis_16k.h. */ uint32_t iir_emphasis_48k[20] = { 0x00000002, 0x00000002, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xc8cf47b5, 0x7689916a, 0x1dc95968, 0xc46d4d30, 0x1dc95968, 0x00000000, 0x00004000, 0xe16f20ea, 0x51e57f66, 0x01966267, 0x032cc4ce, 0x01966267, 0xfffffffe, 0x00004222 }; uint32_t iir_emphasis_16k[20] = { 0x00000002, 0x00000002, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xd6f418ae, 0x63e7b85c, 0x19ae069b, 0xcca3f2ca, 0x19ae069b, 0x00000000, 0x00004000, 0xf504f334, 0x00000000, 0x09651419, 0x12ca2831, 0x09651419, 0xfffffffe, 0x0000414c }; /** * \brief This function copies data to sound direction estimation * * Function to copy data from component source to cross correlation buffer. The copy * operation includes emphasis filtering. The copy is skipped if tracking is not * enabled. * * \param[in,out] cd Component data * \param[in] ch_count Number of channels in audio stream * \param[in,out] ch Current channel for emphasis, incremented * and reset to zero after channel_count -1. * \param[in] x Input PCM sample */ void tdfb_direction_copy_emphasis(struct tdfb_comp_data *cd, int ch_count, int *ch, int32_t x) { int32_t y; if (!cd->direction_updates) return; y = iir_df2t(&cd->direction.emphasis[*ch], x); *cd->direction.wp = sat_int16(Q_SHIFT_RND(y, 31, 18)); /* 18 dB boost after high-pass */ cd->direction.wp++; tdfb_cinc_s16(&cd->direction.wp, cd->direction.d_end, cd->direction.d_size); (*ch)++; if (*ch == ch_count) *ch = 0; } /* Use function y = sqrt_int16(x), where x is Q4.12 unsigned, y is Q4.12 * TODO: Add scaling of input to Q4.12 with a suitable N^2 or (1/N)^2 value * to increase sqrt() computation precision and avoid MIN() function to * saturate for large distances (over 4m). The current virtual source * distance 3m allows max 1m size array for this to work correctly without * hitting the saturation. */ static inline int16_t tdfb_mic_distance_sqrt(int32_t x) { int32_t xs; xs = Q_SHIFT_RND(x, 24, 12); xs = MIN(xs, UINT16_MAX); return sqrt_int16((uint16_t)xs); } static int16_t max_mic_distance(struct tdfb_comp_data *cd) { int16_t d; int16_t dx; int16_t dy; int16_t dz; int32_t d2; int32_t d2_max = 0; int i; int j; /* Max lag based on largest array dimension. Microphone coordinates are Q4.12 meters */ for (i = 0; i < cd->config->num_mic_locations; i++) { for (j = 0; i < cd->config->num_mic_locations; i++) { if (j == i) continue; dx = cd->mic_locations[i].x - cd->mic_locations[j].x; dy = cd->mic_locations[i].y - cd->mic_locations[j].y; dz = cd->mic_locations[i].z - cd->mic_locations[j].z; /* d2 is Q8.24 meters */ d2 = dx * dx + dy * dy + dz * dz; if (d2 > d2_max) d2_max = d2; } } /* Squared distance is Q8.24, return Q4.12 meters */ d = tdfb_mic_distance_sqrt(d2_max); return d; } static bool line_array_mode_check(struct tdfb_comp_data *cd) { int32_t px, py, pz; int16_t a, b, c, d, e, f; int i; int num_mic_locations = cd->config->num_mic_locations; if (num_mic_locations == 2) return true; /* Cross product of vectors AB and AC is (0, 0, 0) if they are co-linear. * Form vector AB(a,b,c) from x(i+1) - x(i), y(i+1) - y(i), z(i+1) - z(i) * Form vector AC(d,e,f) from x(i+2) - x(i), y(i+2) - y(1), z(i+2) - z(i) */ for (i = 0; i < num_mic_locations - 3; i++) { a = cd->mic_locations[i + 1].x - cd->mic_locations[i].x; b = cd->mic_locations[i + 1].y - cd->mic_locations[i].y; c = cd->mic_locations[i + 1].z - cd->mic_locations[i].z; d = cd->mic_locations[i + 2].x - cd->mic_locations[i].x; e = cd->mic_locations[i + 2].y - cd->mic_locations[i].y; f = cd->mic_locations[i + 2].z - cd->mic_locations[i].z; cross_product_s16(&px, &py, &pz, a, b, c, d, e, f); /* Allow small room for rounding error with |x| > 1 in check */ if (ABS(px) > 1 || ABS(py) > 1 || ABS(pz) > 1) return false; } return true; } int tdfb_direction_init(struct tdfb_comp_data *cd, int32_t fs, int ch_count) { struct sof_eq_iir_header_df2t *filt; int64_t *delay; int32_t d_max; int32_t t_max; size_t size; int n; int i; /* Select emphasis response per sample rate */ switch (fs) { case 16000: filt = (struct sof_eq_iir_header_df2t *)iir_emphasis_16k; break; case 48000: filt = (struct sof_eq_iir_header_df2t *)iir_emphasis_48k; break; default: return -EINVAL; } /* Allocate delay lines for IIR filters and initialize them */ size = ch_count * iir_delay_size_df2t(filt); delay = rzalloc(SOF_MEM_ZONE_RUNTIME, 0, SOF_MEM_CAPS_RAM, size); if (!delay) return -ENOMEM; cd->direction.df2t_delay = delay; for (i = 0; i < ch_count; i++) { iir_init_coef_df2t(&cd->direction.emphasis[i], filt); iir_init_delay_df2t(&cd->direction.emphasis[i], &delay); } /* Unit delay length in Q1.31 seconds */ cd->direction.unit_delay = Q_SHIFT_LEFT(1LL, 0, 31) / fs; /* Get max possible mic-mic distance, then from max distance to max time t = d_max / v, * t is Q1.15, d is Q4.12, v is Q9.0 */ d_max = max_mic_distance(cd); t_max = Q_SHIFT_LEFT(d_max, 12, 15) / SPEED_OF_SOUND; /* Calculate max lag to search and allocate delay line for cross correlation * compute. Add one to make sure max possible lag is in search window. */ cd->direction.max_lag = Q_MULTSR_32X32(fs, t_max, 0, 15, 0) + 1; n = (cd->max_frames + (2 * cd->direction.max_lag + 1)) * ch_count; cd->direction.d_size = n * sizeof(int16_t); cd->direction.d = rzalloc(SOF_MEM_ZONE_RUNTIME, 0, SOF_MEM_CAPS_RAM, cd->direction.d_size); if (!cd->direction.d) goto err_free_iir; /* Set needed pointers to xcorr delay line, advance write pointer by max_lag to keep read * always behind write */ cd->direction.d_end = cd->direction.d + n; cd->direction.rp = cd->direction.d; cd->direction.wp = cd->direction.d + ch_count * (cd->direction.max_lag + 1); /* xcorr result is temporary but too large for stack so it is allocated here */ cd->direction.r_size = (2 * cd->direction.max_lag + 1) * sizeof(int32_t); cd->direction.r = rzalloc(SOF_MEM_ZONE_RUNTIME, 0, SOF_MEM_CAPS_RAM, cd->direction.r_size); if (!cd->direction.r) goto err_free_all; /* Check for line array mode */ cd->direction.line_array = line_array_mode_check(cd); /* Initialize direction to zero radians, set initial step sign to +1 */ cd->direction.az = 0; cd->direction.step_sign = 1; return 0; err_free_all: rfree(cd->direction.d); cd->direction.d = NULL; err_free_iir: rfree(cd->direction.df2t_delay); cd->direction.df2t_delay = NULL; return -ENOMEM; } void tdfb_direction_free(struct tdfb_comp_data *cd) { rfree(cd->direction.df2t_delay); rfree(cd->direction.d); rfree(cd->direction.r); } /* Measure level of one channel */ static void level_update(struct tdfb_comp_data *cd, int frames, int ch_count, int channel) { int64_t tmp = 0; int64_t ambient; int64_t level; int16_t s; int16_t *p = cd->direction.rp + channel; int shift; int thr; int n; /* Calculate mean square level */ for (n = 0; n < frames; n++) { s = *p; p += ch_count; tdfb_cinc_s16(&p, cd->direction.d_end, cd->direction.d_size); tmp += ((int64_t)s * s); } /* Calculate mean square power */ cd->direction.level = sat_int32(tmp / frames); /* Slow track minimum level and use it as ambient noise level estimate */ level = ((int64_t)cd->direction.level) << 32; ambient = cd->direction.level_ambient; shift = (level < ambient) ? FAST_LEVEL_SHIFT : SLOW_LEVEL_SHIFT; ambient = (level >> shift) - (ambient >> shift) + ambient; thr = sat_int32(Q_MULTS_32X32(ambient >> 32, POWER_THRESHOLD, 31, 10, 31)); cd->direction.level_ambient = ambient; cd->direction.trigger <<= 1; if (cd->direction.level > thr) cd->direction.trigger |= 1; /* Levels update runs always when tracking, increment frame counter until wrap */ cd->direction.frame_count_since_control += frames; if (cd->direction.frame_count_since_control < 0) cd->direction.frame_count_since_control = INT32_MAX; } static int find_max_value_index(int32_t *v, int length) { int idx = 0; int i; for (i = 1; i < length; i++) { if (v[i] > v[idx]) idx = i; } return idx; } static void time_differences(struct tdfb_comp_data *cd, int frames, int ch_count) { int64_t r; int16_t *x; int16_t *y; int r_max_idx; int max_lag = cd->direction.max_lag; int c; int k; int i; int32_t maxval = 0; /* Calculate xcorr for channel 0 vs. 1 .. (ch_count-1). Scan -maxlag .. +maxlag*/ for (c = 1; c < ch_count; c++) { for (k = -max_lag; k <= max_lag; k++) { y = cd->direction.rp; /* First channel */ x = y + k * ch_count + c; /* other channel C */ tdfb_cinc_s16(&x, cd->direction.d_end, cd->direction.d_size); tdfb_cdec_s16(&x, cd->direction.d, cd->direction.d_size); r = 0; for (i = 0; i < frames; i++) { if (maxval < *y) maxval = *y; r += (int32_t)*x * *y; y += ch_count; tdfb_cinc_s16(&y, cd->direction.d_end, cd->direction.d_size); x += ch_count; tdfb_cinc_s16(&x, cd->direction.d_end, cd->direction.d_size); } /* Scale for max. 20 ms 48 kHz frame */ cd->direction.r[k + max_lag] = sat_int32(((r >> 8) + 1) >> 1); } r_max_idx = find_max_value_index(&cd->direction.r[0], 2 * max_lag + 1); cd->direction.timediff[c - 1] = (int32_t)(r_max_idx - max_lag) * cd->direction.unit_delay; } cd->direction.rp += frames * ch_count; tdfb_cinc_s16(&cd->direction.rp, cd->direction.d_end, cd->direction.d_size); } static int16_t distance_from_source(struct tdfb_comp_data *cd, int mic_n, int16_t x, int16_t y, int16_t z) { int32_t d2; int16_t dx; int16_t dy; int16_t dz; int16_t d; dx = x - cd->mic_locations[mic_n].x; dy = y - cd->mic_locations[mic_n].y; dz = z - cd->mic_locations[mic_n].z; /* d2 is Q8.24 meters */ d2 = dx * dx + dy * dy + dz * dz; /* Squared distance is Q8.24, return Q4.12 meters */ d = tdfb_mic_distance_sqrt(d2); return d; } static void theoretical_time_differences(struct tdfb_comp_data *cd, int16_t az) { int16_t d[PLATFORM_MAX_CHANNELS]; int16_t src_x; int16_t src_y; int16_t sin_az; int16_t cos_az; int32_t delta_d; int n_mic = cd->config->num_mic_locations; int i; sin_az = sin_fixed_16b(Q_SHIFT_LEFT((int32_t)az, 12, 28)); /* Q1.15 */ cos_az = cos_fixed_16b(Q_SHIFT_LEFT((int32_t)az, 12, 28)); /* Q1.15 */ src_x = Q_MULTSR_32X32((int32_t)cos_az, SOURCE_DISTANCE, 15, 12, 12); src_y = Q_MULTSR_32X32((int32_t)sin_az, SOURCE_DISTANCE, 15, 12, 12); for (i = 0; i < n_mic; i++) d[i] = distance_from_source(cd, i, src_x, src_y, 0); for (i = 0; i < n_mic - 1; i++) { delta_d = d[i + 1] - d[0]; /* Meters Q4.12 */ cd->direction.timediff_iter[i] = (int32_t)((((int64_t)delta_d) << 19) / SPEED_OF_SOUND); } } static int64_t mean_square_time_difference_err(struct tdfb_comp_data *cd) { int64_t err = 0; int32_t delta; int i; for (i = 0; i < cd->config->num_mic_locations - 1; i++) { delta = cd->direction.timediff[i] - cd->direction.timediff_iter[i]; err += (int64_t)delta * delta; } return err; } static int unwrap_radians(int radians) { int a = radians; if (a > PI_Q12) a -= PIMUL2_Q12; if (a < -PI_Q12) a += PIMUL2_Q12; return a; } static void iterate_source_angle(struct tdfb_comp_data *cd) { int64_t err_prev; int64_t err; int32_t ds1; int32_t ds2; int az_slow; int i; int az_step = AZ_STEP * cd->direction.step_sign; int az = cd->direction.az_slow; /* Start next iteration opposite direction */ cd->direction.step_sign *= -1; /* Get theoretical time differences for previous angle */ theoretical_time_differences(cd, az); err_prev = mean_square_time_difference_err(cd); for (i = 0; i < AZ_ITERATIONS; i++) { az += az_step; theoretical_time_differences(cd, az); err = mean_square_time_difference_err(cd); if (err > err_prev) { az_step = -(az_step >> 1); if (az_step == 0) break; } err_prev = err; } az = unwrap_radians(az); if (cd->direction.line_array) { /* Line array azimuth angle is -90 .. +90 */ if (az > PIDIV2_Q12) az = PI_Q12 - az; if (az < -PIDIV2_Q12) az = -PI_Q12 - az; } cd->direction.az = az; /* Avoid low-pass filtering to zero the angle in 360 degree arrays * due to discontinuity at -180 or +180 degree point and estimation * noise. Try to camp on either side of the circle. */ ds1 = cd->direction.az_slow - az; ds1 = ds1 * ds1; ds2 = cd->direction.az_slow - (az - 360); ds2 = ds2 * ds2; if (ds2 < ds1) { az -= 360; } else { ds2 = cd->direction.az_slow - (az + 360); ds2 = ds2 * ds2; if (ds2 < ds1) az += 360; } az_slow = Q_MULTSR_32X32((int32_t)az, SLOW_AZ_C1, 12, 15, 12) + Q_MULTSR_32X32((int32_t)cd->direction.az_slow, SLOW_AZ_C2, 12, 15, 12); cd->direction.az_slow = unwrap_radians(az_slow); } static void updates_when_no_trigger(struct tdfb_comp_data *cd, int frames, int ch_count) { cd->direction.rp += frames * ch_count; tdfb_cinc_s16(&cd->direction.rp, cd->direction.d_end, cd->direction.d_size); } static int convert_angle_to_enum(struct tdfb_comp_data *cd) { int16_t deg; int new_az_value; /* Update azimuth enum with radians to degrees to enum step conversion. First * convert radians to deg, subtract angle offset, and make angles positive. */ deg = Q_MULTS_32X32((int32_t)cd->direction.az_slow, COEF_RAD_TO_DEG, 12, 9, 0) - cd->config->angle_enum_offs; /* Divide and round to enum angle scale, remove duplicate 0 and 360 degree angle * representation to have single zero degree enum. */ new_az_value = ((2 * deg / cd->config->angle_enum_mult) + 1) >> 1; if (new_az_value * cd->config->angle_enum_mult == 360) new_az_value -= 360 / cd->config->angle_enum_mult; return new_az_value; } /* Placeholder function for sound direction estimate */ void tdfb_direction_estimate(struct tdfb_comp_data *cd, int frames, int ch_count) { int32_t time_since; int new_az_value; if (!cd->direction_updates) return; /* Update levels, skip rest of estimation if level does not exceed well ambient */ level_update(cd, frames, ch_count, 0); if (!(cd->direction.trigger & 1)) { updates_when_no_trigger(cd, frames, ch_count); return; } /* Compute time differences of ch_count vs. reference channel 1 */ time_differences(cd, frames, ch_count); /* Determine direction angle */ iterate_source_angle(cd); /* Convert radians to enum*/ new_az_value = convert_angle_to_enum(cd); /* Time after last control as Q16.16, unit delay is Q1.131, count is Q0. */ time_since = Q_MULTS_32X32((int64_t)cd->direction.unit_delay, cd->direction.frame_count_since_control, 31, 0, 16); /* Need a new enum value, sufficient time since last update and four measurement frames * to update user space. */ if (new_az_value != cd->az_value_estimate && time_since > CONTROL_UPDATE_MIN_TIME && (cd->direction.trigger & 0x15) == 0x15) { cd->az_value_estimate = new_az_value; cd->direction.frame_count_since_control = 0; cd->direction_change = true; } }
29.610619
94
0.690197
[ "vector" ]
a9c8d8583e2434d64c91d379c8adfb31630c5612
1,248
h
C
device/fido/scoped_virtual_fido_device.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
device/fido/scoped_virtual_fido_device.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
device/fido/scoped_virtual_fido_device.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_FIDO_SCOPED_VIRTUAL_FIDO_DEVICE_H_ #define DEVICE_FIDO_SCOPED_VIRTUAL_FIDO_DEVICE_H_ #include <memory> #include "base/macros.h" #include "device/fido/fido_discovery.h" #include "device/fido/virtual_fido_device.h" namespace device { namespace test { // Creating a |ScopedVirtualFidoDevice| causes normal device discovery to be // hijacked while the object is in scope. Instead a |VirtualFidoDevice| will // always be discovered. This object pretends to be a HID device. class ScopedVirtualFidoDevice : public ::device::internal::ScopedFidoDiscoveryFactory { public: ScopedVirtualFidoDevice(); ~ScopedVirtualFidoDevice() override; VirtualFidoDevice::State* mutable_state(); protected: std::unique_ptr<FidoDiscovery> CreateFidoDiscovery( FidoTransportProtocol transport, ::service_manager::Connector* connector) override; private: scoped_refptr<VirtualFidoDevice::State> state_; DISALLOW_COPY_AND_ASSIGN(ScopedVirtualFidoDevice); }; } // namespace test } // namespace device #endif // DEVICE_FIDO_SCOPED_VIRTUAL_FIDO_DEVICE_H_
29.714286
76
0.78766
[ "object" ]
a9cdac5c10b60050789916c43431920871fb20fc
3,551
h
C
src/platform/cocoa/PAGText.h
snowHe2017/libpag
b42b456fbae415208c63f5c8b561966347401ec7
[ "BSL-1.0", "CC0-1.0", "MIT" ]
1,546
2022-01-14T02:09:47.000Z
2022-03-31T10:38:42.000Z
src/platform/cocoa/PAGText.h
Hparty/libpag
915a4731948dea9a01905143fc21a432f2ae46b7
[ "BSL-1.0", "CC0-1.0", "MIT" ]
86
2022-01-14T04:50:28.000Z
2022-03-31T01:54:31.000Z
src/platform/cocoa/PAGText.h
kevingpqi123/libpag
c58e59b42050cf23427d360c1940d7a843c4fe9c
[ "BSL-1.0", "CC0-1.0", "MIT" ]
207
2022-01-14T02:09:52.000Z
2022-03-31T08:34:49.000Z
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // unless required by applicable law or agreed to in writing, software distributed under the // license is distributed on an "as is" basis, without warranties or conditions of any kind, // either express or implied. see the license for the specific language governing permissions // and limitations under the license. // ///////////////////////////////////////////////////////////////////////////////////////////////// #import <Foundation/Foundation.h> #include "CocoaUtils.h" #import "PAG.h" enum { PAGJustificationLeftJustify = 0, PAGJustificationCenterJustify = 1, PAGJustificationRightJustify = 2, PAGJustificationFullJustifyLastLineLeft = 3, PAGJustificationFullJustifyLastLineRight = 4, PAGJustificationFullJustifyLastLineCenter = 5, PAGJustificationFullJustifyLastLineFull = 6 }; /** * The PAGText object stores a value for a TextLayer's Source Text property. */ PAG_API @interface PAGText : NSObject /** * When true, the text layer shows a fill. */ @property(nonatomic, assign) bool applyFill; /** * When true, the text layer shows a stroke. */ @property(nonatomic, assign) bool applyStroke; @property(nonatomic, assign) float baselineShift; /** * When true, the text layer is paragraph (bounded) text. */ @property(nonatomic, assign) bool boxText; /** * For box text, the pixel boundary for the text bounds. */ @property(nonatomic, assign) CGRect boxTextRect; @property(nonatomic, assign) float firstBaseLine; @property(nonatomic, assign) bool fauxBold; @property(nonatomic, assign) bool fauxItalic; /** * The text layer’s fill color. */ @property(nonatomic, strong) CocoaColor* fillColor; /** * A string with the name of the font family. **/ @property(nonatomic, copy) NSString* fontFamily; /** * A string with the style information — e.g., “bold”, “italic”. **/ @property(nonatomic, copy) NSString* fontStyle; /** * The text layer’s font size in pixels. */ @property(nonatomic, assign) float fontSize; /** * The text layer’s stroke color. */ @property(nonatomic, strong) CocoaColor* strokeColor; /** * Indicates the rendering order for the fill and stroke of a text layer. */ @property(nonatomic, assign) bool strokeOverFill; /** * The text layer’s stroke thickness. */ @property(nonatomic, assign) float strokeWidth; /** * The text layer’s Source Text value. */ @property(nonatomic, copy) NSString* text; /** * The paragraph justification for the text layer. Such as : PAGJustificationLeftJustify, * PAGJustificationCenterJustify... */ @property(nonatomic, assign) uint8_t justification; /** * The space between lines, 0 indicates 'auto', which is fontSize * 1.2 */ @property(nonatomic, assign) float leading; /** * The text layer’s spacing between characters. */ @property(nonatomic, assign) float tracking; /** * The text layer’s background color. */ @property(nonatomic, strong) CocoaColor* backgroundColor; /** * The text layer’s background alpha. 0 = 100% transparent, 255 = 100% opaque. */ @property(nonatomic, assign) int backgroundAlpha; @end
26.901515
97
0.689102
[ "object" ]
a9d53e67f220cca479ff96b4b4a5fe6787fccb93
7,431
h
C
EventFilter/SiStripRawToDigi/plugins/SiStripRawToDigiUnpacker.h
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2020-01-27T15:21:37.000Z
2020-05-11T11:13:18.000Z
EventFilter/SiStripRawToDigi/plugins/SiStripRawToDigiUnpacker.h
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
7
2016-07-17T02:34:54.000Z
2019-08-13T07:58:37.000Z
EventFilter/SiStripRawToDigi/plugins/SiStripRawToDigiUnpacker.h
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2019-09-27T08:33:22.000Z
2019-11-14T10:52:30.000Z
#ifndef EventFilter_SiStripRawToDigi_SiStripRawToDigiUnpacker_H #define EventFilter_SiStripRawToDigi_SiStripRawToDigiUnpacker_H #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/DetId/interface/DetIdCollection.h" #include "DataFormats/SiStripCommon/interface/SiStripConstants.h" #include "EventFilter/SiStripRawToDigi/interface/SiStripFEDBuffer.h" #include "WarningSummary.h" /// sistrip classes namespace sistrip { class RawToClustersLazyUnpacker; } namespace sistrip { class RawToDigiUnpacker; } /// other classes class FEDRawDataCollection; class FEDRawData; class SiStripDigi; class SiStripRawDigi; class SiStripEventSummary; class SiStripFedCabling; namespace sistrip { class dso_hidden RawToDigiUnpacker { friend class RawToClustersLazyUnpacker; public: typedef edm::DetSetVector<SiStripDigi> Digis; typedef edm::DetSetVector<SiStripRawDigi> RawDigis; /// constructor RawToDigiUnpacker(int16_t appended_bytes, int16_t fed_buffer_dump_freq, int16_t fed_event_dump_freq, int16_t trigger_fed_id, bool using_fed_key, bool unpack_bad_channels, bool mark_missing_feds, const uint32_t errorThreshold); /// default constructor ~RawToDigiUnpacker(); /// creates digis void createDigis(const SiStripFedCabling&, const FEDRawDataCollection&, SiStripEventSummary&, RawDigis& scope_mode, RawDigis& virgin_raw, RawDigis& proc_raw, Digis& zero_suppr, DetIdCollection&, RawDigis& common_mode); /// trigger info void triggerFed(const FEDRawDataCollection&, SiStripEventSummary&, const uint32_t& event); /// Removes any data appended prior to FED buffer and reorders 32-bit words if swapped. void locateStartOfFedBuffer(const uint16_t& fed_id, const FEDRawData& input, FEDRawData& output); /// verbosity inline void quiet(bool); /// EventSummary update request -> not yet implemented for FEDBuffer class inline void useDaqRegister(bool); inline void extractCm(bool); inline void doFullCorruptBufferChecks(bool); inline void doAPVEmulatorCheck(bool); inline void legacy(bool); void printWarningSummary() const { warnings_.printSummary(); } private: /// fill DetSetVectors using registries void update( RawDigis& scope_mode, RawDigis& virgin_raw, RawDigis& proc_raw, Digis& zero_suppr, RawDigis& common_mode); /// private default constructor RawToDigiUnpacker() = delete; /// sets the SiStripEventSummary -> not yet implemented for FEDBuffer class void updateEventSummary(const sistrip::FEDBuffer&, SiStripEventSummary&); /// order of strips inline void readoutOrder(uint16_t& physical_order, uint16_t& readout_order); /// order of strips inline void physicalOrder(uint16_t& readout_order, uint16_t& physical_order); /// returns buffer format inline sistrip::FedBufferFormat fedBufferFormat(const uint16_t& register_value); /// returns buffer readout mode inline sistrip::FedReadoutMode fedReadoutMode(const uint16_t& register_value); /// dumps raw data to stdout (NB: payload is byte-swapped,headers/trailer are not). static void dumpRawData(uint16_t fed_id, const FEDRawData&, std::stringstream&); /// catches all possible exceptions and rethrows them as cms::Exceptions void handleException(std::string method_name, std::string extra_info = ""); /// method to clear registries and digi collections void cleanupWorkVectors(); /// private class to register start and end index of digis in a collection class Registry { public: /// constructor Registry(uint32_t aDetid, uint16_t firstStrip, size_t indexInVector, uint16_t numberOfDigis) : detid(aDetid), first(firstStrip), index(indexInVector), length(numberOfDigis) {} /// < operator to sort registries bool operator<(const Registry& other) const { return (detid != other.detid ? detid < other.detid : first < other.first); } /// public data members uint32_t detid; uint16_t first; size_t index; uint16_t length; }; /// configurables int16_t headerBytes_; int16_t fedBufferDumpFreq_; int16_t fedEventDumpFreq_; int16_t triggerFedId_; bool useFedKey_; bool unpackBadChannels_; bool markMissingFeds_; /// other values uint32_t event_; bool once_; bool first_; bool useDaqRegister_; bool quiet_; bool extractCm_; bool doFullCorruptBufferChecks_; bool doAPVEmulatorCheck_; bool legacy_; uint32_t errorThreshold_; /// registries std::vector<Registry> zs_work_registry_; std::vector<Registry> virgin_work_registry_; std::vector<Registry> scope_work_registry_; std::vector<Registry> proc_work_registry_; std::vector<Registry> cm_work_registry_; /// digi collections std::vector<SiStripDigi> zs_work_digis_; std::vector<SiStripRawDigi> virgin_work_digis_; std::vector<SiStripRawDigi> scope_work_digis_; std::vector<SiStripRawDigi> proc_work_digis_; std::vector<SiStripRawDigi> cm_work_digis_; WarningSummary warnings_; }; } // namespace sistrip void sistrip::RawToDigiUnpacker::readoutOrder(uint16_t& physical_order, uint16_t& readout_order) { readout_order = (4 * ((static_cast<uint16_t>((static_cast<float>(physical_order) / 8.0))) % 4) + static_cast<uint16_t>(static_cast<float>(physical_order) / 32.0) + 16 * (physical_order % 8)); } void sistrip::RawToDigiUnpacker::physicalOrder(uint16_t& readout_order, uint16_t& physical_order) { physical_order = ((32 * (readout_order % 4)) + (8 * static_cast<uint16_t>(static_cast<float>(readout_order) / 4.0)) - (31 * static_cast<uint16_t>(static_cast<float>(readout_order) / 16.0))); } sistrip::FedBufferFormat sistrip::RawToDigiUnpacker::fedBufferFormat(const uint16_t& register_value) { if ((register_value & 0xF) == 0x1) { return sistrip::FULL_DEBUG_FORMAT; } else if ((register_value & 0xF) == 0x2) { return sistrip::APV_ERROR_FORMAT; } else if ((register_value & 0xF) == 0x0) { return sistrip::UNDEFINED_FED_BUFFER_FORMAT; } else { return sistrip::UNKNOWN_FED_BUFFER_FORMAT; } } sistrip::FedReadoutMode sistrip::RawToDigiUnpacker::fedReadoutMode(const uint16_t& register_value) { return static_cast<sistrip::FedReadoutMode>(register_value & 0xF); } void sistrip::RawToDigiUnpacker::quiet(bool quiet) { quiet_ = quiet; } void sistrip::RawToDigiUnpacker::useDaqRegister(bool use) { useDaqRegister_ = use; } void sistrip::RawToDigiUnpacker::extractCm(bool extract_cm) { extractCm_ = extract_cm; } void sistrip::RawToDigiUnpacker::doFullCorruptBufferChecks(bool do_full_corrupt_buffer_checks) { doFullCorruptBufferChecks_ = do_full_corrupt_buffer_checks; } void sistrip::RawToDigiUnpacker::doAPVEmulatorCheck(bool do_APVEmulator_check) { doAPVEmulatorCheck_ = do_APVEmulator_check; } void sistrip::RawToDigiUnpacker::legacy(bool legacy) { legacy_ = legacy; } #endif // EventFilter_SiStripRawToDigi_SiStripRawToDigiUnpacker_H
34.724299
119
0.714978
[ "vector" ]
a9d5f19eca6179e14debe125b8178ef8cf0e0649
40,110
h
C
android/android/view/KeyEvent.h
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
5
2016-12-07T10:51:48.000Z
2018-11-26T07:21:10.000Z
android/android/view/KeyEvent.h
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
null
null
null
android/android/view/KeyEvent.h
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
5
2016-12-06T13:06:20.000Z
2021-07-24T03:33:35.000Z
/* * Copyright (C) 2016 Naver Corp.All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <android/view/InputEvent.h> namespace android { namespace view { class KeyEventPrivate; class KeyEvent : public InputEvent { friend class KeyEventPrivate; public: // getAction() value: the key has been pressed down. static const int32_t ACTION_DOWN = 0; // getAction() value: multiple duplicate key events have occurred in a row, or a complex string is being delivered. static const int32_t ACTION_MULTIPLE = 2; // getAction() value: the key has been released. static const int32_t ACTION_UP = 1; // When associated with up key events, this indicates that the key press has been canceled. static const int32_t FLAG_CANCELED = 32; // Set when a key event has FLAG_CANCELED set because a long press action was executed while it was down. static const int32_t FLAG_CANCELED_LONG_PRESS = 256; // This mask is used for compatibility, to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done". static const int32_t FLAG_EDITOR_ACTION = 16; // Set when a key event has been synthesized to implement default behavior for an event that the application did not handle. static const int32_t FLAG_FALLBACK = 1024; // This mask is set if an event was known to come from a trusted part of the system. static const int32_t FLAG_FROM_SYSTEM = 8; // This mask is set if we don't want the key event to cause us to leave touch mode. static const int32_t FLAG_KEEP_TOUCH_MODE = 4; // This flag is set for the first key repeat that occurs after the long press timeout. static const int32_t FLAG_LONG_PRESS = 128; // This mask is set if the key event was generated by a software keyboard. static const int32_t FLAG_SOFT_KEYBOARD = 2; // Set for ACTION_UP when this event's key code is still being tracked from its initial down. static const int32_t FLAG_TRACKING = 512; // This key event was generated by a virtual (on-screen) hard key area. static const int32_t FLAG_VIRTUAL_HARD_KEY = 64; // This constant was deprecated in API level 20. This flag will never be set by the system since the system consumes all wake keys itself. static const int32_t FLAG_WOKE_HERE = 1; // Key code constant: '0' key. static const int32_t KEYCODE_0 = 7; // Key code constant: '1' key. static const int32_t KEYCODE_1 = 8; // Key code constant: '11' key. static const int32_t KEYCODE_11 = 227; // Key code constant: '12' key. static const int32_t KEYCODE_12 = 228; // Key code constant: '2' key. static const int32_t KEYCODE_2 = 9; // Key code constant: '3' key. static const int32_t KEYCODE_3 = 10; // Key code constant: 3D Mode key. static const int32_t KEYCODE_3D_MODE = 206; // Key code constant: '4' key. static const int32_t KEYCODE_4 = 11; // Key code constant: '5' key. static const int32_t KEYCODE_5 = 12; // Key code constant: '6' key. static const int32_t KEYCODE_6 = 13; // Key code constant: '7' key. static const int32_t KEYCODE_7 = 14; // Key code constant: '8' key. static const int32_t KEYCODE_8 = 15; // Key code constant: '9' key. static const int32_t KEYCODE_9 = 16; // Key code constant: 'A' key. static const int32_t KEYCODE_A = 29; // Key code constant: Left Alt modifier key. static const int32_t KEYCODE_ALT_LEFT = 57; // Key code constant: Right Alt modifier key. static const int32_t KEYCODE_ALT_RIGHT = 58; // Key code constant: ''' (apostrophe) key. static const int32_t KEYCODE_APOSTROPHE = 75; // Key code constant: App switch key. static const int32_t KEYCODE_APP_SWITCH = 187; // Key code constant: Assist key. static const int32_t KEYCODE_ASSIST = 219; // Key code constant: '@' key. static const int32_t KEYCODE_AT = 77; // Key code constant: A/V Receiver input key. static const int32_t KEYCODE_AVR_INPUT = 182; // Key code constant: A/V Receiver power key. static const int32_t KEYCODE_AVR_POWER = 181; // Key code constant: 'B' key. static const int32_t KEYCODE_B = 30; // Key code constant: Back key. static const int32_t KEYCODE_BACK = 4; // Key code constant: '\' key. static const int32_t KEYCODE_BACKSLASH = 73; // Key code constant: Bookmark key. static const int32_t KEYCODE_BOOKMARK = 174; // Key code constant: Break / Pause key. static const int32_t KEYCODE_BREAK = 121; // Key code constant: Brightness Down key. static const int32_t KEYCODE_BRIGHTNESS_DOWN = 220; // Key code constant: Brightness Up key. static const int32_t KEYCODE_BRIGHTNESS_UP = 221; // Key code constant: Generic Game Pad Button #1. static const int32_t KEYCODE_BUTTON_1 = 188; // Key code constant: Generic Game Pad Button #10. static const int32_t KEYCODE_BUTTON_10 = 197; // Key code constant: Generic Game Pad Button #11. static const int32_t KEYCODE_BUTTON_11 = 198; // Key code constant: Generic Game Pad Button #12. static const int32_t KEYCODE_BUTTON_12 = 199; // Key code constant: Generic Game Pad Button #13. static const int32_t KEYCODE_BUTTON_13 = 200; // Key code constant: Generic Game Pad Button #14. static const int32_t KEYCODE_BUTTON_14 = 201; // Key code constant: Generic Game Pad Button #15. static const int32_t KEYCODE_BUTTON_15 = 202; // Key code constant: Generic Game Pad Button #16. static const int32_t KEYCODE_BUTTON_16 = 203; // Key code constant: Generic Game Pad Button #2. static const int32_t KEYCODE_BUTTON_2 = 189; // Key code constant: Generic Game Pad Button #3. static const int32_t KEYCODE_BUTTON_3 = 190; // Key code constant: Generic Game Pad Button #4. static const int32_t KEYCODE_BUTTON_4 = 191; // Key code constant: Generic Game Pad Button #5. static const int32_t KEYCODE_BUTTON_5 = 192; // Key code constant: Generic Game Pad Button #6. static const int32_t KEYCODE_BUTTON_6 = 193; // Key code constant: Generic Game Pad Button #7. static const int32_t KEYCODE_BUTTON_7 = 194; // Key code constant: Generic Game Pad Button #8. static const int32_t KEYCODE_BUTTON_8 = 195; // Key code constant: Generic Game Pad Button #9. static const int32_t KEYCODE_BUTTON_9 = 196; // Key code constant: A Button key. static const int32_t KEYCODE_BUTTON_A = 96; // Key code constant: B Button key. static const int32_t KEYCODE_BUTTON_B = 97; // Key code constant: C Button key. static const int32_t KEYCODE_BUTTON_C = 98; // Key code constant: L1 Button key. static const int32_t KEYCODE_BUTTON_L1 = 102; // Key code constant: L2 Button key. static const int32_t KEYCODE_BUTTON_L2 = 104; // Key code constant: Mode Button key. static const int32_t KEYCODE_BUTTON_MODE = 110; // Key code constant: R1 Button key. static const int32_t KEYCODE_BUTTON_R1 = 103; // Key code constant: R2 Button key. static const int32_t KEYCODE_BUTTON_R2 = 105; // Key code constant: Select Button key. static const int32_t KEYCODE_BUTTON_SELECT = 109; // Key code constant: Start Button key. static const int32_t KEYCODE_BUTTON_START = 108; // Key code constant: Left Thumb Button key. static const int32_t KEYCODE_BUTTON_THUMBL = 106; // Key code constant: Right Thumb Button key. static const int32_t KEYCODE_BUTTON_THUMBR = 107; // Key code constant: X Button key. static const int32_t KEYCODE_BUTTON_X = 99; // Key code constant: Y Button key. static const int32_t KEYCODE_BUTTON_Y = 100; // Key code constant: Z Button key. static const int32_t KEYCODE_BUTTON_Z = 101; // Key code constant: 'C' key. static const int32_t KEYCODE_C = 31; // Key code constant: Calculator special function key. static const int32_t KEYCODE_CALCULATOR = 210; // Key code constant: Calendar special function key. static const int32_t KEYCODE_CALENDAR = 208; // Key code constant: Call key. static const int32_t KEYCODE_CALL = 5; // Key code constant: Camera key. static const int32_t KEYCODE_CAMERA = 27; // Key code constant: Caps Lock key. static const int32_t KEYCODE_CAPS_LOCK = 115; // Key code constant: Toggle captions key. static const int32_t KEYCODE_CAPTIONS = 175; // Key code constant: Channel down key. static const int32_t KEYCODE_CHANNEL_DOWN = 167; // Key code constant: Channel up key. static const int32_t KEYCODE_CHANNEL_UP = 166; // Key code constant: Clear key. static const int32_t KEYCODE_CLEAR = 28; // Key code constant: ',' key. static const int32_t KEYCODE_COMMA = 55; // Key code constant: Contacts special function key. static const int32_t KEYCODE_CONTACTS = 207; // Key code constant: Copy key. static const int32_t KEYCODE_COPY = 278; // Key code constant: Left Control modifier key. static const int32_t KEYCODE_CTRL_LEFT = 113; // Key code constant: Right Control modifier key. static const int32_t KEYCODE_CTRL_RIGHT = 114; // Key code constant: Cut key. static const int32_t KEYCODE_CUT = 277; // Key code constant: 'D' key. static const int32_t KEYCODE_D = 32; // Key code constant: Backspace key. static const int32_t KEYCODE_DEL = 67; // Key code constant: Directional Pad Center key. static const int32_t KEYCODE_DPAD_CENTER = 23; // Key code constant: Directional Pad Down key. static const int32_t KEYCODE_DPAD_DOWN = 20; // Key code constant: Directional Pad Down-Left static const int32_t KEYCODE_DPAD_DOWN_LEFT = 269; // Key code constant: Directional Pad Down-Right static const int32_t KEYCODE_DPAD_DOWN_RIGHT = 271; // Key code constant: Directional Pad Left key. static const int32_t KEYCODE_DPAD_LEFT = 21; // Key code constant: Directional Pad Right key. static const int32_t KEYCODE_DPAD_RIGHT = 22; // Key code constant: Directional Pad Up key. static const int32_t KEYCODE_DPAD_UP = 19; // Key code constant: Directional Pad Up-Left static const int32_t KEYCODE_DPAD_UP_LEFT = 268; // Key code constant: Directional Pad Up-Right static const int32_t KEYCODE_DPAD_UP_RIGHT = 270; // Key code constant: DVR key. static const int32_t KEYCODE_DVR = 173; // Key code constant: 'E' key. static const int32_t KEYCODE_E = 33; // Key code constant: Japanese alphanumeric key. static const int32_t KEYCODE_EISU = 212; // Key code constant: End Call key. static const int32_t KEYCODE_ENDCALL = 6; // Key code constant: Enter key. static const int32_t KEYCODE_ENTER = 66; // Key code constant: Envelope special function key. static const int32_t KEYCODE_ENVELOPE = 65; // Key code constant: '=' key. static const int32_t KEYCODE_EQUALS = 70; // Key code constant: Escape key. static const int32_t KEYCODE_ESCAPE = 111; // Key code constant: Explorer special function key. static const int32_t KEYCODE_EXPLORER = 64; // Key code constant: 'F' key. static const int32_t KEYCODE_F = 34; // Key code constant: F1 key. static const int32_t KEYCODE_F1 = 131; // Key code constant: F10 key. static const int32_t KEYCODE_F10 = 140; // Key code constant: F11 key. static const int32_t KEYCODE_F11 = 141; // Key code constant: F12 key. static const int32_t KEYCODE_F12 = 142; // Key code constant: F2 key. static const int32_t KEYCODE_F2 = 132; // Key code constant: F3 key. static const int32_t KEYCODE_F3 = 133; // Key code constant: F4 key. static const int32_t KEYCODE_F4 = 134; // Key code constant: F5 key. static const int32_t KEYCODE_F5 = 135; // Key code constant: F6 key. static const int32_t KEYCODE_F6 = 136; // Key code constant: F7 key. static const int32_t KEYCODE_F7 = 137; // Key code constant: F8 key. static const int32_t KEYCODE_F8 = 138; // Key code constant: F9 key. static const int32_t KEYCODE_F9 = 139; // Key code constant: Camera Focus key. static const int32_t KEYCODE_FOCUS = 80; // Key code constant: Forward key. static const int32_t KEYCODE_FORWARD = 125; // Key code constant: Forward Delete key. static const int32_t KEYCODE_FORWARD_DEL = 112; // Key code constant: Function modifier key. static const int32_t KEYCODE_FUNCTION = 119; // Key code constant: 'G' key. static const int32_t KEYCODE_G = 35; // Key code constant: '`' (backtick) key. static const int32_t KEYCODE_GRAVE = 68; // Key code constant: Guide key. static const int32_t KEYCODE_GUIDE = 172; // Key code constant: 'H' key. static const int32_t KEYCODE_H = 36; // Key code constant: Headset Hook key. static const int32_t KEYCODE_HEADSETHOOK = 79; // Key code constant: Help key. static const int32_t KEYCODE_HELP = 259; // Key code constant: Japanese conversion key. static const int32_t KEYCODE_HENKAN = 214; // Key code constant: Home key. static const int32_t KEYCODE_HOME = 3; // Key code constant: 'I' key. static const int32_t KEYCODE_I = 37; // Key code constant: Info key. static const int32_t KEYCODE_INFO = 165; // Key code constant: Insert key. static const int32_t KEYCODE_INSERT = 124; // Key code constant: 'J' key. static const int32_t KEYCODE_J = 38; // Key code constant: 'K' key. static const int32_t KEYCODE_K = 39; // Key code constant: Japanese kana key. static const int32_t KEYCODE_KANA = 218; // Key code constant: Japanese katakana / hiragana key. static const int32_t KEYCODE_KATAKANA_HIRAGANA = 215; // Key code constant: 'L' key. static const int32_t KEYCODE_L = 40; // Key code constant: Language Switch key. static const int32_t KEYCODE_LANGUAGE_SWITCH = 204; // Key code constant: Last Channel key. static const int32_t KEYCODE_LAST_CHANNEL = 229; // Key code constant: '[' key. static const int32_t KEYCODE_LEFT_BRACKET = 71; // Key code constant: 'M' key. static const int32_t KEYCODE_M = 41; // Key code constant: Manner Mode key. static const int32_t KEYCODE_MANNER_MODE = 205; // Key code constant: Audio Track key. static const int32_t KEYCODE_MEDIA_AUDIO_TRACK = 222; // Key code constant: Close media key. static const int32_t KEYCODE_MEDIA_CLOSE = 128; // Key code constant: Eject media key. static const int32_t KEYCODE_MEDIA_EJECT = 129; // Key code constant: Fast Forward media key. static const int32_t KEYCODE_MEDIA_FAST_FORWARD = 90; // Key code constant: Play Next media key. static const int32_t KEYCODE_MEDIA_NEXT = 87; // Key code constant: Pause media key. static const int32_t KEYCODE_MEDIA_PAUSE = 127; // Key code constant: Play media key. static const int32_t KEYCODE_MEDIA_PLAY = 126; // Key code constant: Play/Pause media key. static const int32_t KEYCODE_MEDIA_PLAY_PAUSE = 85; // Key code constant: Play Previous media key. static const int32_t KEYCODE_MEDIA_PREVIOUS = 88; // Key code constant: Record media key. static const int32_t KEYCODE_MEDIA_RECORD = 130; // Key code constant: Rewind media key. static const int32_t KEYCODE_MEDIA_REWIND = 89; // Key code constant: Skip backward media key. static const int32_t KEYCODE_MEDIA_SKIP_BACKWARD = 273; // Key code constant: Skip forward media key. static const int32_t KEYCODE_MEDIA_SKIP_FORWARD = 272; // Key code constant: Step backward media key. static const int32_t KEYCODE_MEDIA_STEP_BACKWARD = 275; // Key code constant: Step forward media key. static const int32_t KEYCODE_MEDIA_STEP_FORWARD = 274; // Key code constant: Stop media key. static const int32_t KEYCODE_MEDIA_STOP = 86; // Key code constant: Media Top Menu key. static const int32_t KEYCODE_MEDIA_TOP_MENU = 226; // Key code constant: Menu key. static const int32_t KEYCODE_MENU = 82; // Key code constant: Left Meta modifier key. static const int32_t KEYCODE_META_LEFT = 117; // Key code constant: Right Meta modifier key. static const int32_t KEYCODE_META_RIGHT = 118; // Key code constant: '-'. static const int32_t KEYCODE_MINUS = 69; // Key code constant: End Movement key. static const int32_t KEYCODE_MOVE_END = 123; // Key code constant: Home Movement key. static const int32_t KEYCODE_MOVE_HOME = 122; // Key code constant: Japanese non-conversion key. static const int32_t KEYCODE_MUHENKAN = 213; // Key code constant: Music special function key. static const int32_t KEYCODE_MUSIC = 209; // Key code constant: Mute key. static const int32_t KEYCODE_MUTE = 91; // Key code constant: 'N' key. static const int32_t KEYCODE_N = 42; // Key code constant: Navigate in key. static const int32_t KEYCODE_NAVIGATE_IN = 262; // Key code constant: Navigate to next key. static const int32_t KEYCODE_NAVIGATE_NEXT = 261; // Key code constant: Navigate out key. static const int32_t KEYCODE_NAVIGATE_OUT = 263; // Key code constant: Navigate to previous key. static const int32_t KEYCODE_NAVIGATE_PREVIOUS = 260; // Key code constant: Notification key. static const int32_t KEYCODE_NOTIFICATION = 83; // Key code constant: Number modifier key. static const int32_t KEYCODE_NUM = 78; // Key code constant: Numeric keypad '0' key. static const int32_t KEYCODE_NUMPAD_0 = 144; // Key code constant: Numeric keypad '1' key. static const int32_t KEYCODE_NUMPAD_1 = 145; // Key code constant: Numeric keypad '2' key. static const int32_t KEYCODE_NUMPAD_2 = 146; // Key code constant: Numeric keypad '3' key. static const int32_t KEYCODE_NUMPAD_3 = 147; // Key code constant: Numeric keypad '4' key. static const int32_t KEYCODE_NUMPAD_4 = 148; // Key code constant: Numeric keypad '5' key. static const int32_t KEYCODE_NUMPAD_5 = 149; // Key code constant: Numeric keypad '6' key. static const int32_t KEYCODE_NUMPAD_6 = 150; // Key code constant: Numeric keypad '7' key. static const int32_t KEYCODE_NUMPAD_7 = 151; // Key code constant: Numeric keypad '8' key. static const int32_t KEYCODE_NUMPAD_8 = 152; // Key code constant: Numeric keypad '9' key. static const int32_t KEYCODE_NUMPAD_9 = 153; // Key code constant: Numeric keypad '+' key (for addition). static const int32_t KEYCODE_NUMPAD_ADD = 157; // Key code constant: Numeric keypad ',' key (for decimals or digit grouping). static const int32_t KEYCODE_NUMPAD_COMMA = 159; // Key code constant: Numeric keypad '/' key (for division). static const int32_t KEYCODE_NUMPAD_DIVIDE = 154; // Key code constant: Numeric keypad '.' key (for decimals or digit grouping). static const int32_t KEYCODE_NUMPAD_DOT = 158; // Key code constant: Numeric keypad Enter key. static const int32_t KEYCODE_NUMPAD_ENTER = 160; // Key code constant: Numeric keypad '=' key. static const int32_t KEYCODE_NUMPAD_EQUALS = 161; // Key code constant: Numeric keypad '(' key. static const int32_t KEYCODE_NUMPAD_LEFT_PAREN = 162; // Key code constant: Numeric keypad '*' key (for multiplication). static const int32_t KEYCODE_NUMPAD_MULTIPLY = 155; // Key code constant: Numeric keypad ')' key. static const int32_t KEYCODE_NUMPAD_RIGHT_PAREN = 163; // Key code constant: Numeric keypad '-' key (for subtraction). static const int32_t KEYCODE_NUMPAD_SUBTRACT = 156; // Key code constant: Num Lock key. static const int32_t KEYCODE_NUM_LOCK = 143; // Key code constant: 'O' key. static const int32_t KEYCODE_O = 43; // Key code constant: 'P' key. static const int32_t KEYCODE_P = 44; // Key code constant: Page Down key. static const int32_t KEYCODE_PAGE_DOWN = 93; // Key code constant: Page Up key. static const int32_t KEYCODE_PAGE_UP = 92; // Key code constant: Pairing key. static const int32_t KEYCODE_PAIRING = 225; // Key code constant: Paste key. static const int32_t KEYCODE_PASTE = 279; // Key code constant: '.' key. static const int32_t KEYCODE_PERIOD = 56; // Key code constant: Picture Symbols modifier key. static const int32_t KEYCODE_PICTSYMBOLS = 94; // Key code constant: '+' key. static const int32_t KEYCODE_PLUS = 81; // Key code constant: '#' key. static const int32_t KEYCODE_POUND = 18; // Key code constant: Power key. static const int32_t KEYCODE_POWER = 26; // Key code constant: Blue "programmable" key. static const int32_t KEYCODE_PROG_BLUE = 186; // Key code constant: Green "programmable" key. static const int32_t KEYCODE_PROG_GREEN = 184; // Key code constant: Red "programmable" key. static const int32_t KEYCODE_PROG_RED = 183; // Key code constant: Yellow "programmable" key. static const int32_t KEYCODE_PROG_YELLOW = 185; // Key code constant: 'Q' key. static const int32_t KEYCODE_Q = 45; // Key code constant: 'R' key. static const int32_t KEYCODE_R = 46; // Key code constant: ']' key. static const int32_t KEYCODE_RIGHT_BRACKET = 72; // Key code constant: Japanese Ro key. static const int32_t KEYCODE_RO = 217; // Key code constant: 'S' key. static const int32_t KEYCODE_S = 47; // Key code constant: Scroll Lock key. static const int32_t KEYCODE_SCROLL_LOCK = 116; // Key code constant: Search key. static const int32_t KEYCODE_SEARCH = 84; // Key code constant: ';' key. static const int32_t KEYCODE_SEMICOLON = 74; // Key code constant: Settings key. static const int32_t KEYCODE_SETTINGS = 176; // Key code constant: Left Shift modifier key. static const int32_t KEYCODE_SHIFT_LEFT = 59; // Key code constant: Right Shift modifier key. static const int32_t KEYCODE_SHIFT_RIGHT = 60; // Key code constant: '/' key. static const int32_t KEYCODE_SLASH = 76; // Key code constant: Sleep key. static const int32_t KEYCODE_SLEEP = 223; // Key code constant: Soft Left key. static const int32_t KEYCODE_SOFT_LEFT = 1; // Key code constant: Soft Right key. static const int32_t KEYCODE_SOFT_RIGHT = 2; // Key code constant: put device to sleep unless a wakelock is held. static const int32_t KEYCODE_SOFT_SLEEP = 276; // Key code constant: Space key. static const int32_t KEYCODE_SPACE = 62; // Key code constant: '*' key. static const int32_t KEYCODE_STAR = 17; // Key code constant: Set-top-box input key. static const int32_t KEYCODE_STB_INPUT = 180; // Key code constant: Set-top-box power key. static const int32_t KEYCODE_STB_POWER = 179; // Key code constant: Generic stem key 1 for Wear static const int32_t KEYCODE_STEM_1 = 265; // Key code constant: Generic stem key 2 for Wear static const int32_t KEYCODE_STEM_2 = 266; // Key code constant: Generic stem key 3 for Wear static const int32_t KEYCODE_STEM_3 = 267; // Key code constant: Primary stem key for Wear Main power/reset button on watch. static const int32_t KEYCODE_STEM_PRIMARY = 264; // Key code constant: Switch Charset modifier key. static const int32_t KEYCODE_SWITCH_CHARSET = 95; // Key code constant: Symbol modifier key. static const int32_t KEYCODE_SYM = 63; // Key code constant: System Request / Print Screen key. static const int32_t KEYCODE_SYSRQ = 120; // Key code constant: Consumed by the system for navigation down static const int32_t KEYCODE_SYSTEM_NAVIGATION_DOWN = 281; // Key code constant: Consumed by the system for navigation left static const int32_t KEYCODE_SYSTEM_NAVIGATION_LEFT = 282; // Key code constant: Consumed by the system for navigation right static const int32_t KEYCODE_SYSTEM_NAVIGATION_RIGHT = 283; // Key code constant: Consumed by the system for navigation up static const int32_t KEYCODE_SYSTEM_NAVIGATION_UP = 280; // Key code constant: 'T' key. static const int32_t KEYCODE_T = 48; // Key code constant: Tab key. static const int32_t KEYCODE_TAB = 61; // Key code constant: TV key. static const int32_t KEYCODE_TV = 170; // Key code constant: Antenna/Cable key. static const int32_t KEYCODE_TV_ANTENNA_CABLE = 242; // Key code constant: Audio description key. static const int32_t KEYCODE_TV_AUDIO_DESCRIPTION = 252; // Key code constant: Audio description mixing volume down key. static const int32_t KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254; // Key code constant: Audio description mixing volume up key. static const int32_t KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253; // Key code constant: Contents menu key. static const int32_t KEYCODE_TV_CONTENTS_MENU = 256; // Key code constant: TV data service key. static const int32_t KEYCODE_TV_DATA_SERVICE = 230; // Key code constant: TV input key. static const int32_t KEYCODE_TV_INPUT = 178; // Key code constant: Component #1 key. static const int32_t KEYCODE_TV_INPUT_COMPONENT_1 = 249; // Key code constant: Component #2 key. static const int32_t KEYCODE_TV_INPUT_COMPONENT_2 = 250; // Key code constant: Composite #1 key. static const int32_t KEYCODE_TV_INPUT_COMPOSITE_1 = 247; // Key code constant: Composite #2 key. static const int32_t KEYCODE_TV_INPUT_COMPOSITE_2 = 248; // Key code constant: HDMI #1 key. static const int32_t KEYCODE_TV_INPUT_HDMI_1 = 243; // Key code constant: HDMI #2 key. static const int32_t KEYCODE_TV_INPUT_HDMI_2 = 244; // Key code constant: HDMI #3 key. static const int32_t KEYCODE_TV_INPUT_HDMI_3 = 245; // Key code constant: HDMI #4 key. static const int32_t KEYCODE_TV_INPUT_HDMI_4 = 246; // Key code constant: VGA #1 key. static const int32_t KEYCODE_TV_INPUT_VGA_1 = 251; // Key code constant: Media context menu key. static const int32_t KEYCODE_TV_MEDIA_CONTEXT_MENU = 257; // Key code constant: Toggle Network key. static const int32_t KEYCODE_TV_NETWORK = 241; // Key code constant: Number entry key. static const int32_t KEYCODE_TV_NUMBER_ENTRY = 234; // Key code constant: TV power key. static const int32_t KEYCODE_TV_POWER = 177; // Key code constant: Radio key. static const int32_t KEYCODE_TV_RADIO_SERVICE = 232; // Key code constant: Satellite key. static const int32_t KEYCODE_TV_SATELLITE = 237; // Key code constant: BS key. static const int32_t KEYCODE_TV_SATELLITE_BS = 238; // Key code constant: CS key. static const int32_t KEYCODE_TV_SATELLITE_CS = 239; // Key code constant: BS/CS key. static const int32_t KEYCODE_TV_SATELLITE_SERVICE = 240; // Key code constant: Teletext key. static const int32_t KEYCODE_TV_TELETEXT = 233; // Key code constant: Analog Terrestrial key. static const int32_t KEYCODE_TV_TERRESTRIAL_ANALOG = 235; // Key code constant: Digital Terrestrial key. static const int32_t KEYCODE_TV_TERRESTRIAL_DIGITAL = 236; // Key code constant: Timer programming key. static const int32_t KEYCODE_TV_TIMER_PROGRAMMING = 258; // Key code constant: Zoom mode key. static const int32_t KEYCODE_TV_ZOOM_MODE = 255; // Key code constant: 'U' key. static const int32_t KEYCODE_U = 49; // Key code constant: Unknown key code. static const int32_t KEYCODE_UNKNOWN = 0; // Key code constant: 'V' key. static const int32_t KEYCODE_V = 50; // Key code constant: Voice Assist key. static const int32_t KEYCODE_VOICE_ASSIST = 231; // Key code constant: Volume Down key. static const int32_t KEYCODE_VOLUME_DOWN = 25; // Key code constant: Volume Mute key. static const int32_t KEYCODE_VOLUME_MUTE = 164; // Key code constant: Volume Up key. static const int32_t KEYCODE_VOLUME_UP = 24; // Key code constant: 'W' key. static const int32_t KEYCODE_W = 51; // Key code constant: Wakeup key. static const int32_t KEYCODE_WAKEUP = 224; // Key code constant: Window key. static const int32_t KEYCODE_WINDOW = 171; // Key code constant: 'X' key. static const int32_t KEYCODE_X = 52; // Key code constant: 'Y' key. static const int32_t KEYCODE_Y = 53; // Key code constant: Japanese Yen key. static const int32_t KEYCODE_YEN = 216; // Key code constant: 'Z' key. static const int32_t KEYCODE_Z = 54; // Key code constant: Japanese full-width / half-width key. static const int32_t KEYCODE_ZENKAKU_HANKAKU = 211; // Key code constant: Zoom in key. static const int32_t KEYCODE_ZOOM_IN = 168; // Key code constant: Zoom out key. static const int32_t KEYCODE_ZOOM_OUT = 169; // This constant was deprecated in API level 3. There are now more than MAX_KEYCODE keycodes. Use getMaxKeyCode() instead. static const int32_t MAX_KEYCODE = 84; // This mask is used to check whether the left ALT meta key is pressed. static const int32_t META_ALT_LEFT_ON = 16; // This mask is a combination of META_ALT_ON, META_ALT_LEFT_ON and META_ALT_RIGHT_ON. static const int32_t META_ALT_MASK = 50; // This mask is used to check whether one of the ALT meta keys is pressed. static const int32_t META_ALT_ON = 2; // This mask is used to check whether the right the ALT meta key is pressed. static const int32_t META_ALT_RIGHT_ON = 32; // This mask is used to check whether the CAPS LOCK meta key is on. static const int32_t META_CAPS_LOCK_ON = 1048576; // This mask is used to check whether the left CTRL meta key is pressed. static const int32_t META_CTRL_LEFT_ON = 8192; // This mask is a combination of META_CTRL_ON, META_CTRL_LEFT_ON and META_CTRL_RIGHT_ON. static const int32_t META_CTRL_MASK = 28672; // This mask is used to check whether one of the CTRL meta keys is pressed. static const int32_t META_CTRL_ON = 4096; // This mask is used to check whether the right CTRL meta key is pressed. static const int32_t META_CTRL_RIGHT_ON = 16384; // This mask is used to check whether the FUNCTION meta key is pressed. static const int32_t META_FUNCTION_ON = 8; // This mask is used to check whether the left META meta key is pressed. static const int32_t META_META_LEFT_ON = 131072; // This mask is a combination of META_META_ON, META_META_LEFT_ON and META_META_RIGHT_ON. static const int32_t META_META_MASK = 458752; // This mask is used to check whether one of the META meta keys is pressed. static const int32_t META_META_ON = 65536; // This mask is used to check whether the right META meta key is pressed. static const int32_t META_META_RIGHT_ON = 262144; // This mask is used to check whether the NUM LOCK meta key is on. static const int32_t META_NUM_LOCK_ON = 2097152; // This mask is used to check whether the SCROLL LOCK meta key is on. static const int32_t META_SCROLL_LOCK_ON = 4194304; // This mask is used to check whether the left SHIFT meta key is pressed. static const int32_t META_SHIFT_LEFT_ON = 64; // This mask is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON and META_SHIFT_RIGHT_ON. static const int32_t META_SHIFT_MASK = 193; // This mask is used to check whether one of the SHIFT meta keys is pressed. static const int32_t META_SHIFT_ON = 1; // This mask is used to check whether the right SHIFT meta key is pressed. static const int32_t META_SHIFT_RIGHT_ON = 128; // This mask is used to check whether the SYM meta key is pressed. static const int32_t META_SYM_ON = 4; // Create a new key event. ANDROID_EXPORT KeyEvent(int32_t action, int32_t code); ANDROID_EXPORT KeyEvent(std::chrono::milliseconds downTime, std::chrono::milliseconds eventTime, int32_t action, int32_t code, int32_t repeat); ANDROID_EXPORT KeyEvent(std::chrono::milliseconds downTime, std::chrono::milliseconds eventTime, int32_t action, int32_t code, int32_t repeat, int32_t metaState); ANDROID_EXPORT KeyEvent(std::chrono::milliseconds downTime, std::chrono::milliseconds eventTime, int32_t action, int32_t code, int32_t repeat, int32_t metaState, int32_t deviceId, int32_t scancode); ANDROID_EXPORT KeyEvent(std::chrono::milliseconds downTime, std::chrono::milliseconds eventTime, int32_t action, int32_t code, int32_t repeat, int32_t metaState, int32_t deviceId, int32_t scancode, int32_t flags); ANDROID_EXPORT KeyEvent(std::chrono::milliseconds downTime, std::chrono::milliseconds eventTime, int32_t action, int32_t code, int32_t repeat, int32_t metaState, int32_t deviceId, int32_t scancode, int32_t flags, int32_t source); // Create a new key event for a string of characters. ANDROID_EXPORT KeyEvent(std::chrono::milliseconds time, String& characters, int32_t deviceId, int32_t flags); // Make an exact copy of an existing key event. ANDROID_EXPORT KeyEvent(const KeyEvent& origEvent); ANDROID_EXPORT KeyEvent(KeyEvent&& origEvent); ANDROID_EXPORT virtual ~KeyEvent() = default; // Retrieve the action of this key event. ANDROID_EXPORT int32_t getAction(); // Get the character that is produced by putting accent on the character c. ANDROID_EXPORT static int32_t getDeadChar(int32_t accent, int32_t c); // Retrieve the time of the most recent key down event, in the uptimeMillis(); time base. ANDROID_EXPORT std::chrono::milliseconds getDownTime(); // Retrieve the time this event occurred, in the uptimeMillis(); time base. ANDROID_EXPORT std::chrono::milliseconds getEventTime() override; // Returns the flags for this key event. ANDROID_EXPORT int32_t getFlags(); // Retrieve the key code of the key event. ANDROID_EXPORT int32_t getKeyCode(); // Returns the state of the meta keys. ANDROID_EXPORT int32_t getMetaState(); // Gets a mask that includes all valid modifier key meta state bits. ANDROID_EXPORT static int32_t getModifierMetaStateMask(); // Returns the state of the modifier keys. ANDROID_EXPORT int32_t getModifiers(); // Gets the number or symbol associated with the key. ANDROID_EXPORT virtual char getNumber(); // Retrieve the repeat count of the event. ANDROID_EXPORT int32_t getRepeatCount(); // Retrieve the hardware key id of this key event.These values are not reliable and vary from device to device. ANDROID_EXPORT int32_t getScanCode(); // Gets the source of the event. ANDROID_EXPORT int32_t getSource() override; // Gets the Unicode character generated by the specified key and meta key state combination. ANDROID_EXPORT virtual int32_t getUnicodeChar(int32_t metaState); // Gets the Unicode character generated by the specified key and meta key state combination. ANDROID_EXPORT virtual int32_t getUnicodeChar(); // Returns true if only the specified modifiers keys are pressed. ANDROID_EXPORT bool hasModifiers(int32_t modifiers); // Returns true if no modifier keys are pressed. ANDROID_EXPORT bool hasNoModifiers(); // Returns the pressed state of the ALT meta key. ANDROID_EXPORT bool isAltPressed(); // For ACTION_UP events, indicates that the event has been canceled as per FLAG_CANCELED. ANDROID_EXPORT bool isCanceled(); // Returns the locked state of the CAPS LOCK meta key. ANDROID_EXPORT bool isCapsLockOn(); // Returns the pressed state of the CTRL meta key. ANDROID_EXPORT bool isCtrlPressed(); // Returns the pressed state of the FUNCTION meta key. ANDROID_EXPORT bool isFunctionPressed(); // Returns true if the specified keycode is a gamepad button. ANDROID_EXPORT static bool isGamepadButton(int32_t keyCode); // For ACTION_DOWN events, indicates that the event has been canceled as per FLAG_LONG_PRESS. ANDROID_EXPORT bool isLongPress(); // Returns the pressed state of the META meta key. ANDROID_EXPORT bool isMetaPressed(); // Returns true if this key code is a modifier key. ANDROID_EXPORT static bool isModifierKey(int32_t keyCode); // Returns the locked state of the NUM LOCK meta key. ANDROID_EXPORT bool isNumLockOn(); // Returns true if this key produces a glyph. ANDROID_EXPORT virtual bool isPrintingKey(); // Returns the locked state of the SCROLL LOCK meta key. ANDROID_EXPORT bool isScrollLockOn(); // Returns the pressed state of the SHIFT meta key. ANDROID_EXPORT bool isShiftPressed(); // Returns the pressed state of the SYM meta key. ANDROID_EXPORT bool isSymPressed(); // Is this a system key? System keys can not be used for menu shortcuts. ANDROID_EXPORT bool isSystem(); // For ACTION_UP events, indicates that the event is still being tracked from its initial down event as per FLAG_TRACKING. ANDROID_EXPORT bool isTracking(); // Gets a keycode by its symbolic name such as "KEYCODE_A" or an equivalent numeric constant such as "1001". ANDROID_EXPORT static int32_t keyCodeFromString(String& symbolicName); // Returns a string that represents the symbolic name of the specified keycode such as "KEYCODE_A", "KEYCODE_DPAD_UP", or an equivalent numeric constant such as "1001" if unknown. ANDROID_EXPORT static String& keyCodeToString(int32_t keyCode); // Returns true if only the specified modifier keys are pressed according to the specified meta state. ANDROID_EXPORT static bool metaStateHasModifiers(int32_t metaState, int32_t modifiers); // Returns true if no modifiers keys are pressed according to the specified meta state. ANDROID_EXPORT static bool metaStateHasNoModifiers(int32_t metaState); // Normalizes the specified meta state. ANDROID_EXPORT static int32_t normalizeMetaState(int32_t metaState); // Modifies the source of the event. ANDROID_EXPORT void setSource(int32_t source); // Call this during onKeyDown(int32_t, KeyEvent); to have the system track the key through its up (possibly including a std::chrono::milliseconds press);. ANDROID_EXPORT void startTracking(); private: std::chrono::milliseconds m_eventTime { 0 }; std::chrono::milliseconds m_downTime { 0 }; int32_t m_action { 0 }; int32_t m_code { -1 }; int32_t m_repeat { 0 }; int32_t m_metaState { 0 }; int32_t m_scancode { 0 }; int32_t m_flags { 0 }; int32_t m_source { 0 }; int32_t m_nativeKeyCode { 0 }; int32_t m_virtualKeyCode { 0 }; bool m_isSystemKey { false }; }; } // namespace view } // namespace android using KeyEvent = android::view::KeyEvent;
49.88806
233
0.716978
[ "3d" ]
a9dd8effbb9764fd5c2833d0f1056d890bf0fce2
3,056
h
C
Triangulation_2/doc/Triangulation_2/Concepts/ConstrainedTriangulationTraits_2.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Triangulation_2/doc/Triangulation_2/Concepts/ConstrainedTriangulationTraits_2.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Triangulation_2/doc/Triangulation_2/Concepts/ConstrainedTriangulationTraits_2.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
/*! \ingroup PkgTriangulation2Concepts \cgalConcept The concept `ConstrainedTriangulationTraits_2` defines the requirements for the geometric traits class of a constrained triangulation ( `CGAL::Constrained_triangulation_2<Traits,Tds,Itag>`) that supports intersections of input constraints (i. e. when the template parameter `Itag` is instantiated by one of the tag classes `CGAL::Exact_intersections_tag` or `CGAL::Exact_predicates_tag`). This concept refines the concept `TriangulationTraits_2`, adding requirements for function objects to compute the intersection points of two constraints. When `CGAL::Exact_predicates_tag` is used, the traits class is also required to provide additional types to compute the squared distance between a point and a line \cgalRefines `TriangulationTraits_2` \cgalHasModel All \cgal Kernels \cgalHasModel `CGAL::Projection_traits_3<K>` \cgalHasModel `CGAL::Projection_traits_xy_3<K>` \cgalHasModel `CGAL::Projection_traits_yz_3<K>` \cgalHasModel `CGAL::Projection_traits_xz_3<K>` \sa `TriangulationTraits_2` \sa `ConstrainedDelaunayTriangulationTraits_2` \sa `CGAL::Constrained_triangulation_2<Traits,Tds,Itag>` */ class ConstrainedTriangulationTraits_2 { public: /// \name Types /// @{ /*! A function object whose `operator()` computes the intersection of two segments. `boost::optional<boost::variant<Point_2,Segment_2> > operator()(Segment_2 s1, Segment_2 s2);` Returns the intersection of `s1` and `s2`. */ typedef unspecified_type Intersect_2; ///@} /// \name Types required with Exact_predicates_tag /// When the constrained triangulation is instantiated with the intersection tag `CGAL::Exact_predicates_tag`, the used algorithm needs to be able to compare some distances between points and lines and the following types are further required. /// @{ /*! A number type supporting the comparison operator `<`. */ typedef unspecified_type RT; /*! The line type. */ typedef unspecified_type Line_2; /*! A function object whose `operator()` constructs a line from two points. `Line_2 operator()(Point_2 p1, Point_2 p2)`. */ typedef unspecified_type Construct_line_2; /*! A function object whose `operator()` computes the squared distance between a line and a point. `RT operator()(Line_2 l, Point_2 p);` Returns the squared distance between `p` and `l`. */ typedef unspecified_type Compute_squared_distance_2; /*! A function object whose `operator()` computes the bounding box of a point. CGAL::Bbox_2 operator()(Point_2 p);` Returns the bounding box of `p`. The result type is `CGAL::Bbox_2` (even for projection traits classes). */ typedef unspecified_type Compute_bounding_box_2; /// @} /// \name Access to Constructor Objects /// @{ /*! */ Intersect_2 intersect_2_object(); /*! required when the intersection tag is `CGAL::Exact_predicates_tag`. */ Construct_line_2 construct_line_2_object(); /*! required when the intersection tag is `CGAL::Exact_predicates_tag`. */ Compute_squared_distance_2 compute_squared_distance_2_object(); /// @} }; /* end ConstrainedTriangulationTraits_2 */
26.119658
243
0.777814
[ "object" ]
a9ded966547da82310bcfa6618f520d435bf0c02
4,753
h
C
applications/plugins/SofaHAPI/SofaHAPIHapticsDevice.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/SofaHAPI/SofaHAPIHapticsDevice.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/SofaHAPI/SofaHAPIHapticsDevice.h
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFAHAPI_SOFAHAPIHAPTICSDEVICE_H #define SOFAHAPI_SOFAHAPIHAPTICSDEVICE_H #include <SofaHAPI/config.h> #include <cstddef> //HAPI include #include <H3DUtil/AutoRef.h> #include <HAPI/HAPIHapticsDevice.h> #include <HAPI/HapticSpring.h> #include "SofaHAPIForceFeedbackEffect.h" #include <sofa/defaulttype/RigidTypes.h> #include <sofa/defaulttype/SolidTypes.h> #include <sofa/core/behavior/MechanicalState.h> #include <sofa/core/behavior/BaseController.h> #include <SofaUserInteraction/Controller.h> #include <SofaHaptics/ForceFeedback.h> namespace sofa { namespace component { using sofa::helper::vector; using sofa::defaulttype::Vec3d; using sofa::defaulttype::Quat; using sofa::defaulttype::Rigid3dTypes; typedef sofa::defaulttype::SolidTypes<double>::Transform Transform; using sofa::core::objectmodel::Data; using sofa::core::objectmodel::BaseLink; using sofa::core::objectmodel::MultiLink; using sofa::core::objectmodel::KeypressedEvent; using sofa::core::objectmodel::KeyreleasedEvent; using sofa::core::behavior::MechanicalState; using sofa::component::controller::Controller; using sofa::component::controller::ForceFeedback; /** * HAPI Haptics Device */ class SOFA_SOFAHAPI_API SofaHAPIHapticsDevice : public Controller { public: SOFA_CLASS(SofaHAPIHapticsDevice, Controller); Data<double> scale; Data<double> forceScale; Data<Vec3d> positionBase; Data<Quat> orientationBase; Data<Vec3d> positionTool; Data<Quat> orientationTool; Data<bool> permanent; Data<bool> toolSelector; Data<int> toolCount; Data<int> toolIndex; Data<double> toolTransitionSpringStiffness; Data<std::string> driverName; Data<bool> drawDevice; Data<float> drawHandleSize; Data<float> drawForceScale; //SofaHAPIHapticsDeviceData data; ForceFeedbackTransform data; SofaHAPIHapticsDevice(); virtual ~SofaHAPIHapticsDevice(); virtual void init(); virtual void bwdInit(); virtual void reset(); void reinit(); bool initDevice(); void releaseDevice(); void cleanup(); virtual void draw(const sofa::core::visual::VisualParams* vparams); void setForceFeedbacks(vector<ForceFeedback*> ffs); void onKeyPressedEvent(KeypressedEvent *); void onKeyReleasedEvent(KeyreleasedEvent *); void onBeginAnimationStep(const double /*dt*/); void onEndAnimationStep(const double /*dt*/); void setDataValue(); protected: std::auto_ptr<HAPI::HAPIHapticsDevice> device; MultiLink<SofaHAPIHapticsDevice, SofaHAPIForceFeedbackEffect, BaseLink::FLAG_STRONGLINK> feedbackEffects; H3DUtil::AutoRef<HAPI::HapticSpring> transitionEffect; sofa::core::behavior::MechanicalState<sofa::defaulttype::Rigid3dTypes> *mState; ///< Controlled MechanicalState. bool isToolControlled; int fakeButtonState; int lastButtonState; Transform lastToolPosition; void setToolFeedback(int indice, bool enable = true, bool transfer = true); void sendHapticDeviceEvent(); }; } // namespace SofaHAPI } #endif // SOFAHAPI_SOFAHAPIHAPTICSDEVICE_H
35.736842
115
0.632232
[ "vector", "transform" ]
a9df76b56bc308dcee57f42a6aeb1b77900b3f97
6,087
h
C
GNSS_INS_ZUPT/3rdparty/RobustGNSS/gtsam/gtsam/geometry/EssentialMatrix.h
wvu-navLab/gnss-ins-zupt
1104dcece2493b572fb7d7ab3488c25c1840bc6b
[ "MIT" ]
8
2022-01-02T05:43:46.000Z
2022-03-30T10:45:21.000Z
GNSS_INS_ZUPT/3rdparty/RobustGNSS/gtsam/gtsam/geometry/EssentialMatrix.h
wvu-navLab/gnss-ins-zupt
1104dcece2493b572fb7d7ab3488c25c1840bc6b
[ "MIT" ]
null
null
null
GNSS_INS_ZUPT/3rdparty/RobustGNSS/gtsam/gtsam/geometry/EssentialMatrix.h
wvu-navLab/gnss-ins-zupt
1104dcece2493b572fb7d7ab3488c25c1840bc6b
[ "MIT" ]
3
2022-03-26T14:47:17.000Z
2022-03-27T07:29:58.000Z
/* * @file EssentialMatrix.h * @brief EssentialMatrix class * @author Frank Dellaert * @date December 17, 2013 */ #pragma once #include <gtsam/geometry/Pose3.h> #include <gtsam/geometry/Unit3.h> #include <gtsam/geometry/Point2.h> #include <gtsam/base/Manifold.h> #include <iosfwd> #include <iostream> namespace gtsam { /** * An essential matrix is like a Pose3, except with translation up to scale * It is named after the 3*3 matrix aEb = [aTb]x aRb from computer vision, * but here we choose instead to parameterize it as a (Rot3,Unit3) pair. * We can then non-linearly optimize immediately on this 5-dimensional manifold. */ class GTSAM_EXPORT EssentialMatrix : private ProductManifold<Rot3, Unit3> { private: typedef ProductManifold<Rot3, Unit3> Base; Matrix3 E_; ///< Essential matrix /// Construct from Base EssentialMatrix(const Base& base) : Base(base), E_(direction().skew() * rotation().matrix()) { } public: /// Static function to convert Point2 to homogeneous coordinates static Vector3 Homogeneous(const Point2& p) { return Vector3(p.x(), p.y(), 1); } /// @name Constructors and named constructors /// @{ /// Default constructor EssentialMatrix() : Base(Rot3(), Unit3(1, 0, 0)), E_(direction().skew()) { } /// Construct from rotation and translation EssentialMatrix(const Rot3& aRb, const Unit3& aTb) : Base(aRb, aTb), E_(direction().skew() * rotation().matrix()) { } /// Named constructor with derivatives static EssentialMatrix FromRotationAndDirection(const Rot3& aRb, const Unit3& aTb, OptionalJacobian<5, 3> H1 = boost::none, OptionalJacobian<5, 2> H2 = boost::none); /// Named constructor converting a Pose3 with scale to EssentialMatrix (no scale) static EssentialMatrix FromPose3(const Pose3& _1P2_, OptionalJacobian<5, 6> H = boost::none); /// Random, using Rot3::Random and Unit3::Random template<typename Engine> static EssentialMatrix Random(Engine & rng) { return EssentialMatrix(Rot3::Random(rng), Unit3::Random(rng)); } virtual ~EssentialMatrix() {} /// @} /// @name Testable /// @{ /// print with optional string void print(const std::string& s = "") const; /// assert equality up to a tolerance bool equals(const EssentialMatrix& other, double tol = 1e-8) const { return rotation().equals(other.rotation(), tol) && direction().equals(other.direction(), tol); } /// @} /// @name Manifold /// @{ using Base::dimension; using Base::dim; using Base::Dim; /// Retract delta to manifold EssentialMatrix retract(const TangentVector& v) const { return Base::retract(v); } /// Compute the coordinates in the tangent space TangentVector localCoordinates(const EssentialMatrix& other) const { return Base::localCoordinates(other); } /// @} /// @name Essential matrix methods /// @{ /// Rotation inline const Rot3& rotation() const { return this->first; } /// Direction inline const Unit3& direction() const { return this->second; } /// Return 3*3 matrix representation inline const Matrix3& matrix() const { return E_; } /// Return epipole in image_a , as Unit3 to allow for infinity inline const Unit3& epipole_a() const { return direction(); } /// Return epipole in image_b, as Unit3 to allow for infinity inline Unit3 epipole_b() const { return rotation().unrotate(direction()); } /** * @brief takes point in world coordinates and transforms it to pose with |t|==1 * @param p point in world coordinates * @param DE optional 3*5 Jacobian wrpt to E * @param Dpoint optional 3*3 Jacobian wrpt point * @return point in pose coordinates */ Point3 transform_to(const Point3& p, OptionalJacobian<3,5> DE = boost::none, OptionalJacobian<3,3> Dpoint = boost::none) const; /** * Given essential matrix E in camera frame B, convert to body frame C * @param cRb rotation from body frame to camera frame * @param E essential matrix E in camera frame C */ EssentialMatrix rotate(const Rot3& cRb, OptionalJacobian<5, 5> HE = boost::none, OptionalJacobian<5, 3> HR = boost::none) const; /** * Given essential matrix E in camera frame B, convert to body frame C * @param cRb rotation from body frame to camera frame * @param E essential matrix E in camera frame C */ friend EssentialMatrix operator*(const Rot3& cRb, const EssentialMatrix& E) { return E.rotate(cRb); } /// epipolar error, algebraic double error(const Vector3& vA, const Vector3& vB, // OptionalJacobian<1,5> H = boost::none) const; /// @} /// @name Streaming operators /// @{ /// stream to stream GTSAM_EXPORT friend std::ostream& operator <<(std::ostream& os, const EssentialMatrix& E); /// stream from stream GTSAM_EXPORT friend std::istream& operator >>(std::istream& is, EssentialMatrix& E); /// @} private: /// @name Advanced Interface /// @{ /** Serialization function */ friend class boost::serialization::access; template<class ARCHIVE> void serialize(ARCHIVE & ar, const unsigned int /*version*/) { ar & BOOST_SERIALIZATION_NVP(first); ar & BOOST_SERIALIZATION_NVP(second); ar & boost::serialization::make_nvp("E11", E_(0,0)); ar & boost::serialization::make_nvp("E12", E_(0,1)); ar & boost::serialization::make_nvp("E13", E_(0,2)); ar & boost::serialization::make_nvp("E21", E_(1,0)); ar & boost::serialization::make_nvp("E22", E_(1,1)); ar & boost::serialization::make_nvp("E23", E_(1,2)); ar & boost::serialization::make_nvp("E31", E_(2,0)); ar & boost::serialization::make_nvp("E32", E_(2,1)); ar & boost::serialization::make_nvp("E33", E_(2,2)); } /// @} }; template<> struct traits<EssentialMatrix> : public internal::Manifold<EssentialMatrix> {}; template<> struct traits<const EssentialMatrix> : public internal::Manifold<EssentialMatrix> {}; } // gtsam
28.577465
92
0.66026
[ "geometry" ]
a9e311d2f8a4fef657a88d136b80b8e06ee41c19
2,880
c
C
ext/mvc/controller.c
quasipickle/cphalcon
a9069f1afc6c4a7fd4edd705afb61cfe25389d68
[ "BSD-3-Clause" ]
1
2019-06-12T19:54:14.000Z
2019-06-12T19:54:14.000Z
ext/mvc/controller.c
quasipickle/cphalcon
a9069f1afc6c4a7fd4edd705afb61cfe25389d68
[ "BSD-3-Clause" ]
null
null
null
ext/mvc/controller.c
quasipickle/cphalcon
a9069f1afc6c4a7fd4edd705afb61cfe25389d68
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/fcall.h" /** * Phalcon\Mvc\Controller * * Every application controller should extend this class that encapsulates all the controller functionality * * The controllers provide the “flow” between models and views. Controllers are responsible * for processing the incoming requests from the web browser, interrogating the models for data, * and passing that data on to the views for presentation. * *<code> * *class PeopleController extends \Phalcon\Mvc\Controller *{ * * //This action will be executed by default * public function indexAction() * { * * } * * public function findAction() * { * * } * * public function saveAction() * { * //Forwards flow to the index action * return $this->dispatcher->forward(array('controller' => 'people', 'action' => 'index')); * } * *} * *</code> */ /** * Phalcon\Mvc\Controller initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Controller){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc, Controller, mvc_controller, "phalcon\\di\\injectable", phalcon_mvc_controller_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); return SUCCESS; } /** * Phalcon\Mvc\Controller constructor * */ PHP_METHOD(Phalcon_Mvc_Controller, __construct){ PHALCON_MM_GROW(); if (phalcon_method_exists_ex(this_ptr, SS("onconstruct") TSRMLS_CC) == SUCCESS) { phalcon_call_method_noret(this_ptr, "onconstruct"); } PHALCON_MM_RESTORE(); }
28.514851
167
0.561458
[ "object" ]
a9e58e9e6789a92a087af41c9a3061aa16fa7c17
2,948
h
C
VTK/Graphics/vtkExtractSelection.h
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
VTK/Graphics/vtkExtractSelection.h
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
VTK/Graphics/vtkExtractSelection.h
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkExtractSelection.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkExtractSelection - extract a subset from a vtkDataSet. // .SECTION Description // vtkExtractSelection extracts some subset of cells and points from // its input dataset. The subset is described by the contents of the // vtkSelection on its first input port. The dataset is given on its // second input port. Depending on the content of the vtkSelection, // this will use either a vtkExtractSelectedIds, vtkExtractSelectedFrustum // vtkExtractSelectedLocations or a vtkExtractSelectedThreshold to perform // the extraction. // .SECTION See Also // vtkSelection vtkExtractSelectedIds vtkExtractSelectedFrustum // vtkExtractSelectedLocations vtkExtractSelectedThresholds #ifndef __vtkExtractSelection_h #define __vtkExtractSelection_h #include "vtkDataSetAlgorithm.h" class vtkExtractSelectedIds; class vtkExtractSelectedFrustum; class vtkExtractSelectedLocations; class vtkExtractSelectedThresholds; class vtkSelection; class VTK_GRAPHICS_EXPORT vtkExtractSelection : public vtkDataSetAlgorithm { public: vtkTypeRevisionMacro(vtkExtractSelection,vtkDataSetAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Construct object with NULL extractfilter static vtkExtractSelection *New(); // Description: // Convenience method to specify the selection connection (2nd input // port) void SetSelectionConnection(vtkAlgorithmOutput* algOutput) { this->SetInputConnection(1, algOutput); } protected: vtkExtractSelection(); ~vtkExtractSelection(); //sets up empty output dataset virtual int RequestDataObject(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); //runs the algorithm and fills the output with results virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int port, vtkInformation* info); vtkExtractSelectedIds* IdsFilter; vtkExtractSelectedFrustum* FrustumFilter; vtkExtractSelectedLocations* LocationsFilter; vtkExtractSelectedThresholds* ThresholdsFilter; private: vtkExtractSelection(const vtkExtractSelection&); // Not implemented. void operator=(const vtkExtractSelection&); // Not implemented. }; #endif
35.095238
75
0.730326
[ "object" ]
a9e8220a29174b735f8744f39743bf5ca2357fe9
165,071
h
C
src/physfs.h
jopadan/physfs
158b38ecb58644febd236e6c060db3b5851690f5
[ "Zlib" ]
null
null
null
src/physfs.h
jopadan/physfs
158b38ecb58644febd236e6c060db3b5851690f5
[ "Zlib" ]
null
null
null
src/physfs.h
jopadan/physfs
158b38ecb58644febd236e6c060db3b5851690f5
[ "Zlib" ]
null
null
null
/** * \file physfs.h * * Main header file for PhysicsFS. */ /** * \mainpage PhysicsFS * * The latest version of PhysicsFS can be found at: * https://icculus.org/physfs/ * * PhysicsFS; a portable, flexible file i/o abstraction. * * This API gives you access to a system file system in ways superior to the * stdio or system i/o calls. The brief benefits: * * - It's portable. * - It's safe. No file access is permitted outside the specified dirs. * - It's flexible. Archives (.ZIP files) can be used transparently as * directory structures. * * With PhysicsFS, you have a single writing directory and multiple * directories (the "search path") for reading. You can think of this as a * filesystem within a filesystem. If (on Windows) you were to set the * writing directory to "C:\MyGame\MyWritingDirectory", then no PHYSFS calls * could touch anything above this directory, including the "C:\MyGame" and * "C:\" directories. This prevents an application's internal scripting * language from piddling over c:\\config.sys, for example. If you'd rather * give PHYSFS full access to the system's REAL file system, set the writing * dir to "C:\", but that's generally A Bad Thing for several reasons. * * Drive letters are hidden in PhysicsFS once you set up your initial paths. * The search path creates a single, hierarchical directory structure. * Not only does this lend itself well to general abstraction with archives, * it also gives better support to operating systems like MacOS and Unix. * Generally speaking, you shouldn't ever hardcode a drive letter; not only * does this hurt portability to non-Microsoft OSes, but it limits your win32 * users to a single drive, too. Use the PhysicsFS abstraction functions and * allow user-defined configuration options, too. When opening a file, you * specify it like it was on a Unix filesystem: if you want to write to * "C:\MyGame\MyConfigFiles\game.cfg", then you might set the write dir to * "C:\MyGame" and then open "MyConfigFiles/game.cfg". This gives an * abstraction across all platforms. Specifying a file in this way is termed * "platform-independent notation" in this documentation. Specifying a * a filename in a form such as "C:\mydir\myfile" or * "MacOS hard drive:My Directory:My File" is termed "platform-dependent * notation". The only time you use platform-dependent notation is when * setting up your write directory and search path; after that, all file * access into those directories are done with platform-independent notation. * * All files opened for writing are opened in relation to the write directory, * which is the root of the writable filesystem. When opening a file for * reading, PhysicsFS goes through the search path. This is NOT the * same thing as the PATH environment variable. An application using * PhysicsFS specifies directories to be searched which may be actual * directories, or archive files that contain files and subdirectories of * their own. See the end of these docs for currently supported archive * formats. * * Once the search path is defined, you may open files for reading. If you've * got the following search path defined (to use a win32 example again): * * - C:\\mygame * - C:\\mygame\\myuserfiles * - D:\\mygamescdromdatafiles * - C:\\mygame\\installeddatafiles.zip * * Then a call to PHYSFS_openRead("textfiles/myfile.txt") (note the directory * separator, lack of drive letter, and lack of dir separator at the start of * the string; this is platform-independent notation) will check for * C:\\mygame\\textfiles\\myfile.txt, then * C:\\mygame\\myuserfiles\\textfiles\\myfile.txt, then * D:\\mygamescdromdatafiles\\textfiles\\myfile.txt, then, finally, for * textfiles\\myfile.txt inside of C:\\mygame\\installeddatafiles.zip. * Remember that most archive types and platform filesystems store their * filenames in a case-sensitive manner, so you should be careful to specify * it correctly. * * Files opened through PhysicsFS may NOT contain "." or ".." or ":" as dir * elements. Not only are these meaningless on MacOS Classic and/or Unix, * they are a security hole. Also, symbolic links (which can be found in * some archive types and directly in the filesystem on Unix platforms) are * NOT followed until you call PHYSFS_permitSymbolicLinks(). That's left to * your own discretion, as following a symlink can allow for access outside * the write dir and search paths. For portability, there is no mechanism for * creating new symlinks in PhysicsFS. * * The write dir is not included in the search path unless you specifically * add it. While you CAN change the write dir as many times as you like, * you should probably set it once and stick to it. Remember that your * program will not have permission to write in every directory on Unix and * NT systems. * * All files are opened in binary mode; there is no endline conversion for * textfiles. Other than that, PhysicsFS has some convenience functions for * platform-independence. There is a function to tell you the current * platform's dir separator ("\\" on windows, "/" on Unix, ":" on MacOS), * which is needed only to set up your search/write paths. There is a * function to tell you what CD-ROM drives contain accessible discs, and a * function to recommend a good search path, etc. * * A recommended order for the search path is the write dir, then the base dir, * then the cdrom dir, then any archives discovered. Quake 3 does something * like this, but moves the archives to the start of the search path. Build * Engine games, like Duke Nukem 3D and Blood, place the archives last, and * use the base dir for both searching and writing. There is a helper * function (PHYSFS_setSaneConfig()) that puts together a basic configuration * for you, based on a few parameters. Also see the comments on * PHYSFS_getBaseDir(), and PHYSFS_getPrefDir() for info on what those * are and how they can help you determine an optimal search path. * * PhysicsFS 2.0 adds the concept of "mounting" archives to arbitrary points * in the search path. If a zipfile contains "maps/level.map" and you mount * that archive at "mods/mymod", then you would have to open * "mods/mymod/maps/level.map" to access the file, even though "mods/mymod" * isn't actually specified in the .zip file. Unlike the Unix mentality of * mounting a filesystem, "mods/mymod" doesn't actually have to exist when * mounting the zipfile. It's a "virtual" directory. The mounting mechanism * allows the developer to seperate archives in the tree and avoid trampling * over files when added new archives, such as including mod support in a * game...keeping external content on a tight leash in this manner can be of * utmost importance to some applications. * * PhysicsFS is mostly thread safe. The errors returned by * PHYSFS_getLastErrorCode() are unique by thread, and library-state-setting * functions are mutex'd. For efficiency, individual file accesses are * not locked, so you can not safely read/write/seek/close/etc the same * file from two threads at the same time. Other race conditions are bugs * that should be reported/patched. * * While you CAN use stdio/syscall file access in a program that has PHYSFS_* * calls, doing so is not recommended, and you can not directly use system * filehandles with PhysicsFS and vice versa (but as of PhysicsFS 2.1, you * can wrap them in a PHYSFS_Io interface yourself if you wanted to). * * Note that archives need not be named as such: if you have a ZIP file and * rename it with a .PKG extension, the file will still be recognized as a * ZIP archive by PhysicsFS; the file's contents are used to determine its * type where possible. * * Currently supported archive types: * - .ZIP (pkZip/WinZip/Info-ZIP compatible) * - .7Z (7zip archives) * - .ISO (ISO9660 files, CD-ROM images) * - .GRP (Build Engine groupfile archives) * - .PAK (Quake I/II archive format) * - .HOG (Descent I/II/III HOG file archives) * - .MVL (Descent II movielib archives) * - .WAD (DOOM engine archives) * - .VDF (Gothic I/II engine archives) * - .POD (Terminal Velocity POD archives) * - .SLB (Independence War archives) * - .RES (F-22 Lightning 2 / Comanche 3 RES RESOURCE2xxx archives) * * String policy for PhysicsFS 2.0 and later: * * PhysicsFS 1.0 could only deal with null-terminated ASCII strings. All high * ASCII chars resulted in undefined behaviour, and there was no Unicode * support at all. PhysicsFS 2.0 supports Unicode without breaking binary * compatibility with the 1.0 API by using UTF-8 encoding of all strings * passed in and out of the library. * * All strings passed through PhysicsFS are in null-terminated UTF-8 format. * This means that if all you care about is English (ASCII characters <= 127) * then you just use regular C strings. If you care about Unicode (and you * should!) then you need to figure out what your platform wants, needs, and * offers. If you are on Windows before Win2000 and build with Unicode * support, your TCHAR strings are two bytes per character (this is called * "UCS-2 encoding"). Any modern Windows uses UTF-16, which is two bytes * per character for most characters, but some characters are four. You * should convert them to UTF-8 before handing them to PhysicsFS with * PHYSFS_utf8FromUtf16(), which handles both UTF-16 and UCS-2. If you're * using Unix or Mac OS X, your wchar_t strings are four bytes per character * ("UCS-4 encoding", sometimes called "UTF-32"). Use PHYSFS_utf8FromUcs4(). * Mac OS X can give you UTF-8 directly from a CFString or NSString, and many * Unixes generally give you C strings in UTF-8 format everywhere. If you * have a single-byte high ASCII charset, like so-many European "codepages" * you may be out of luck. We'll convert from "Latin1" to UTF-8 only, and * never back to Latin1. If you're above ASCII 127, all bets are off: move * to Unicode or use your platform's facilities. Passing a C string with * high-ASCII data that isn't UTF-8 encoded will NOT do what you expect! * * Naturally, there's also PHYSFS_utf8ToUcs2(), PHYSFS_utf8ToUtf16(), and * PHYSFS_utf8ToUcs4() to get data back into a format you like. Behind the * scenes, PhysicsFS will use Unicode where possible: the UTF-8 strings on * Windows will be converted and used with the multibyte Windows APIs, for * example. * * PhysicsFS offers basic encoding conversion support, but not a whole string * library. Get your stuff into whatever format you can work with. * * Most platforms supported by PhysicsFS 2.1 and later fully support Unicode. * Some older platforms have been dropped (Windows 95, Mac OS 9). Some, like * OS/2, might be able to convert to a local codepage or will just fail to * open/create the file. Modern OSes (macOS, Linux, Windows, etc) should all * be fine. * * Many game-specific archivers are seriously unprepared for Unicode (the * Descent HOG/MVL and Build Engine GRP archivers, for example, only offer a * DOS 8.3 filename, for example). Nothing can be done for these, but they * tend to be legacy formats for existing content that was all ASCII (and * thus, valid UTF-8) anyhow. Other formats, like .ZIP, don't explicitly * offer Unicode support, but unofficially expect filenames to be UTF-8 * encoded, and thus Just Work. Most everything does the right thing without * bothering you, but it's good to be aware of these nuances in case they * don't. * * * Other stuff: * * Please see the file LICENSE.txt in the source's root directory for * licensing and redistribution rights. * * Please see the file CREDITS.txt in the source's "docs" directory for * a more or less complete list of who's responsible for this. * * \author Ryan C. Gordon. */ #ifndef _INCLUDE_PHYSFS_H_ #define _INCLUDE_PHYSFS_H_ #ifdef __cplusplus extern "C" { #endif #if defined(PHYSFS_DECL) /* do nothing. */ #elif defined(_MSC_VER) #define PHYSFS_DECL __declspec(dllexport) #elif defined(__SUNPRO_C) #define PHYSFS_DECL __global #elif ((__GNUC__ >= 3) && (!defined(__EMX__)) && (!defined(sun))) #define PHYSFS_DECL __attribute__((visibility("default"))) #else #define PHYSFS_DECL #endif #if defined(PHYSFS_DEPRECATED) /* do nothing. */ #elif (__GNUC__ >= 4) /* technically, this arrived in gcc 3.1, but oh well. */ #define PHYSFS_DEPRECATED __attribute__((deprecated)) #else #define PHYSFS_DEPRECATED #endif #if 0 /* !!! FIXME: look into this later. */ #if defined(PHYSFS_CALL) /* do nothing. */ #elif defined(__WIN32__) && !defined(__GNUC__) #define PHYSFS_CALL __cdecl #elif defined(__OS2__) || defined(OS2) /* should work across all compilers. */ #define PHYSFS_CALL _System #else #define PHYSFS_CALL #endif #endif /** * \typedef PHYSFS_uint8 * \brief An unsigned, 8-bit integer type. */ typedef unsigned char PHYSFS_uint8; /** * \typedef PHYSFS_sint8 * \brief A signed, 8-bit integer type. */ typedef signed char PHYSFS_sint8; /** * \typedef PHYSFS_uint16 * \brief An unsigned, 16-bit integer type. */ typedef unsigned short PHYSFS_uint16; /** * \typedef PHYSFS_sint16 * \brief A signed, 16-bit integer type. */ typedef signed short PHYSFS_sint16; /** * \typedef PHYSFS_uint32 * \brief An unsigned, 32-bit integer type. */ typedef unsigned int PHYSFS_uint32; /** * \typedef PHYSFS_sint32 * \brief A signed, 32-bit integer type. */ typedef signed int PHYSFS_sint32; /** * \typedef PHYSFS_uint64 * \brief An unsigned, 64-bit integer type. * \warning on platforms without any sort of 64-bit datatype, this is * equivalent to PHYSFS_uint32! */ /** * \typedef PHYSFS_sint64 * \brief A signed, 64-bit integer type. * \warning on platforms without any sort of 64-bit datatype, this is * equivalent to PHYSFS_sint32! */ #if (defined PHYSFS_NO_64BIT_SUPPORT) /* oh well. */ typedef PHYSFS_uint32 PHYSFS_uint64; typedef PHYSFS_sint32 PHYSFS_sint64; #elif (defined _MSC_VER) typedef signed __int64 PHYSFS_sint64; typedef unsigned __int64 PHYSFS_uint64; #else typedef unsigned long long PHYSFS_uint64; typedef signed long long PHYSFS_sint64; #endif #ifndef DOXYGEN_SHOULD_IGNORE_THIS /* Make sure the types really have the right sizes */ #define PHYSFS_COMPILE_TIME_ASSERT(name, x) \ typedef int PHYSFS_compile_time_assert_##name[(x) * 2 - 1] PHYSFS_COMPILE_TIME_ASSERT(uint8IsOneByte, sizeof(PHYSFS_uint8) == 1); PHYSFS_COMPILE_TIME_ASSERT(sint8IsOneByte, sizeof(PHYSFS_sint8) == 1); PHYSFS_COMPILE_TIME_ASSERT(uint16IsTwoBytes, sizeof(PHYSFS_uint16) == 2); PHYSFS_COMPILE_TIME_ASSERT(sint16IsTwoBytes, sizeof(PHYSFS_sint16) == 2); PHYSFS_COMPILE_TIME_ASSERT(uint32IsFourBytes, sizeof(PHYSFS_uint32) == 4); PHYSFS_COMPILE_TIME_ASSERT(sint32IsFourBytes, sizeof(PHYSFS_sint32) == 4); #ifndef PHYSFS_NO_64BIT_SUPPORT PHYSFS_COMPILE_TIME_ASSERT(uint64IsEightBytes, sizeof(PHYSFS_uint64) == 8); PHYSFS_COMPILE_TIME_ASSERT(sint64IsEightBytes, sizeof(PHYSFS_sint64) == 8); #endif #undef PHYSFS_COMPILE_TIME_ASSERT #endif /* DOXYGEN_SHOULD_IGNORE_THIS */ /** * \struct PHYSFS_File * \brief A PhysicsFS file handle. * * You get a pointer to one of these when you open a file for reading, * writing, or appending via PhysicsFS. * * As you can see from the lack of meaningful fields, you should treat this * as opaque data. Don't try to manipulate the file handle, just pass the * pointer you got, unmolested, to various PhysicsFS APIs. * * \sa PHYSFS_openRead * \sa PHYSFS_openWrite * \sa PHYSFS_openAppend * \sa PHYSFS_close * \sa PHYSFS_read * \sa PHYSFS_write * \sa PHYSFS_seek * \sa PHYSFS_tell * \sa PHYSFS_eof * \sa PHYSFS_setBuffer * \sa PHYSFS_flush */ typedef struct PHYSFS_File { void *opaque; /**< That's all you get. Don't touch. */ } PHYSFS_File; /** * \def PHYSFS_file * \brief 1.0 API compatibility define. * * PHYSFS_file is identical to PHYSFS_File. This #define is here for backwards * compatibility with the 1.0 API, which had an inconsistent capitalization * convention in this case. New code should use PHYSFS_File, as this #define * may go away someday. * * \sa PHYSFS_File */ #define PHYSFS_file PHYSFS_File /** * \struct PHYSFS_ArchiveInfo * \brief Information on various PhysicsFS-supported archives. * * This structure gives you details on what sort of archives are supported * by this implementation of PhysicsFS. Archives tend to be things like * ZIP files and such. * * \warning Not all binaries are created equal! PhysicsFS can be built with * or without support for various archives. You can check with * PHYSFS_supportedArchiveTypes() to see if your archive type is * supported. * * \sa PHYSFS_supportedArchiveTypes * \sa PHYSFS_registerArchiver * \sa PHYSFS_deregisterArchiver */ typedef struct PHYSFS_ArchiveInfo { const char *extension; /**< Archive file extension: "ZIP", for example. */ const char *description; /**< Human-readable archive description. */ const char *author; /**< Person who did support for this archive. */ const char *url; /**< URL related to this archive */ int supportsSymlinks; /**< non-zero if archive offers symbolic links. */ } PHYSFS_ArchiveInfo; /** * \struct PHYSFS_Version * \brief Information the version of PhysicsFS in use. * * Represents the library's version as three levels: major revision * (increments with massive changes, additions, and enhancements), * minor revision (increments with backwards-compatible changes to the * major revision), and patchlevel (increments with fixes to the minor * revision). * * \sa PHYSFS_VERSION * \sa PHYSFS_getLinkedVersion */ typedef struct PHYSFS_Version { PHYSFS_uint8 major; /**< major revision */ PHYSFS_uint8 minor; /**< minor revision */ PHYSFS_uint8 patch; /**< patchlevel */ } PHYSFS_Version; #ifndef DOXYGEN_SHOULD_IGNORE_THIS #define PHYSFS_VER_MAJOR 3 #define PHYSFS_VER_MINOR 1 #define PHYSFS_VER_PATCH 0 #endif /* DOXYGEN_SHOULD_IGNORE_THIS */ /* PhysicsFS state stuff ... */ /** * \def PHYSFS_VERSION(x) * \brief Macro to determine PhysicsFS version program was compiled against. * * This macro fills in a PHYSFS_Version structure with the version of the * library you compiled against. This is determined by what header the * compiler uses. Note that if you dynamically linked the library, you might * have a slightly newer or older version at runtime. That version can be * determined with PHYSFS_getLinkedVersion(), which, unlike PHYSFS_VERSION, * is not a macro. * * \param x A pointer to a PHYSFS_Version struct to initialize. * * \sa PHYSFS_Version * \sa PHYSFS_getLinkedVersion */ #define PHYSFS_VERSION(x) \ { \ (x)->major = PHYSFS_VER_MAJOR; \ (x)->minor = PHYSFS_VER_MINOR; \ (x)->patch = PHYSFS_VER_PATCH; \ } /** * \fn void PHYSFS_getLinkedVersion(PHYSFS_Version *ver) * \brief Get the version of PhysicsFS that is linked against your program. * * If you are using a shared library (DLL) version of PhysFS, then it is * possible that it will be different than the version you compiled against. * * This is a real function; the macro PHYSFS_VERSION tells you what version * of PhysFS you compiled against: * * \code * PHYSFS_Version compiled; * PHYSFS_Version linked; * * PHYSFS_VERSION(&compiled); * PHYSFS_getLinkedVersion(&linked); * printf("We compiled against PhysFS version %d.%d.%d ...\n", * compiled.major, compiled.minor, compiled.patch); * printf("But we linked against PhysFS version %d.%d.%d.\n", * linked.major, linked.minor, linked.patch); * \endcode * * This function may be called safely at any time, even before PHYSFS_init(). * * \sa PHYSFS_VERSION */ PHYSFS_DECL void PHYSFS_getLinkedVersion(PHYSFS_Version *ver); #ifdef __ANDROID__ typedef struct PHYSFS_AndroidInit { void *jnienv; void *context; } PHYSFS_AndroidInit; #endif /** * \fn int PHYSFS_init(const char *argv0) * \brief Initialize the PhysicsFS library. * * This must be called before any other PhysicsFS function. * * This should be called prior to any attempts to change your process's * current working directory. * * \warning On Android, argv0 should be a non-NULL pointer to a * PHYSFS_AndroidInit struct. This struct must hold a valid JNIEnv * * and a JNI jobject of a Context (either the application context or * the current Activity is fine). Both are cast to a void * so we * don't need jni.h included wherever physfs.h is. PhysicsFS * uses these objects to query some system details. PhysicsFS does * not hold a reference to the JNIEnv or Context past the call to * PHYSFS_init(). If you pass a NULL here, PHYSFS_init can still * succeed, but PHYSFS_getBaseDir() and PHYSFS_getPrefDir() will be * incorrect. * * \param argv0 the argv[0] string passed to your program's mainline. * This may be NULL on most platforms (such as ones without a * standard main() function), but you should always try to pass * something in here. Many Unix-like systems _need_ to pass argv[0] * from main() in here. See warning about Android, too! * \return nonzero on success, zero on error. Specifics of the error can be * gleaned from PHYSFS_getLastError(). * * \sa PHYSFS_deinit * \sa PHYSFS_isInit */ PHYSFS_DECL int PHYSFS_init(const char *argv0); /** * \fn int PHYSFS_deinit(void) * \brief Deinitialize the PhysicsFS library. * * This closes any files opened via PhysicsFS, blanks the search/write paths, * frees memory, and invalidates all of your file handles. * * Note that this call can FAIL if there's a file open for writing that * refuses to close (for example, the underlying operating system was * buffering writes to network filesystem, and the fileserver has crashed, * or a hard drive has failed, etc). It is usually best to close all write * handles yourself before calling this function, so that you can gracefully * handle a specific failure. * * Once successfully deinitialized, PHYSFS_init() can be called again to * restart the subsystem. All default API states are restored at this * point, with the exception of any custom allocator you might have * specified, which survives between initializations. * * \return nonzero on success, zero on error. Specifics of the error can be * gleaned from PHYSFS_getLastError(). If failure, state of PhysFS is * undefined, and probably badly screwed up. * * \sa PHYSFS_init * \sa PHYSFS_isInit */ PHYSFS_DECL int PHYSFS_deinit(void); /** * \fn const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void) * \brief Get a list of supported archive types. * * Get a list of archive types supported by this implementation of PhysicFS. * These are the file formats usable for search path entries. This is for * informational purposes only. Note that the extension listed is merely * convention: if we list "ZIP", you can open a PkZip-compatible archive * with an extension of "XYZ", if you like. * * The returned value is an array of pointers to PHYSFS_ArchiveInfo structures, * with a NULL entry to signify the end of the list: * * \code * PHYSFS_ArchiveInfo **i; * * for (i = PHYSFS_supportedArchiveTypes(); *i != NULL; i++) * { * printf("Supported archive: [%s], which is [%s].\n", * (*i)->extension, (*i)->description); * } * \endcode * * The return values are pointers to internal memory, and should * be considered READ ONLY, and never freed. The returned values are * valid until the next call to PHYSFS_deinit(), PHYSFS_registerArchiver(), * or PHYSFS_deregisterArchiver(). * * \return READ ONLY Null-terminated array of READ ONLY structures. * * \sa PHYSFS_registerArchiver * \sa PHYSFS_deregisterArchiver */ PHYSFS_DECL const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void); /** * \fn void PHYSFS_freeList(void *listVar) * \brief Deallocate resources of lists returned by PhysicsFS. * * Certain PhysicsFS functions return lists of information that are * dynamically allocated. Use this function to free those resources. * * It is safe to pass a NULL here, but doing so will cause a crash in versions * before PhysicsFS 2.1.0. * * \param listVar List of information specified as freeable by this function. * Passing NULL is safe; it is a valid no-op. * * \sa PHYSFS_getCdRomDirs * \sa PHYSFS_enumerateFiles * \sa PHYSFS_getSearchPath */ PHYSFS_DECL void PHYSFS_freeList(void *listVar); /** * \fn const char *PHYSFS_getLastError(void) * \brief Get human-readable error information. * * \deprecated Use PHYSFS_getLastErrorCode() and PHYSFS_getErrorByCode() instead. * * \warning As of PhysicsFS 2.1, this function has been nerfed. * Before PhysicsFS 2.1, this function was the only way to get * error details beyond a given function's basic return value. * This was meant to be a human-readable string in one of several * languages, and was not useful for application parsing. This was * a problem, because the developer and not the user chose the * language at compile time, and the PhysicsFS maintainers had * to (poorly) maintain a significant amount of localization work. * The app couldn't parse the strings, even if they counted on a * specific language, since some were dynamically generated. * In 2.1 and later, this always returns a static string in * English; you may use it as a key string for your own * localizations if you like, as we'll promise not to change * existing error strings. Also, if your application wants to * look at specific errors, we now offer a better option: * use PHYSFS_getLastErrorCode() instead. * * Get the last PhysicsFS error message as a human-readable, null-terminated * string. This will return NULL if there's been no error since the last call * to this function. The pointer returned by this call points to an internal * buffer. Each thread has a unique error state associated with it, but each * time a new error message is set, it will overwrite the previous one * associated with that thread. It is safe to call this function at anytime, * even before PHYSFS_init(). * * PHYSFS_getLastError() and PHYSFS_getLastErrorCode() both reset the same * thread-specific error state. Calling one will wipe out the other's * data. If you need both, call PHYSFS_getLastErrorCode(), then pass that * value to PHYSFS_getErrorByCode(). * * As of PhysicsFS 2.1, this function only presents text in the English * language, but the strings are static, so you can use them as keys into * your own localization dictionary. These strings are meant to be passed on * directly to the user. * * Generally, applications should only concern themselves with whether a * given function failed; however, if your code require more specifics, you * should use PHYSFS_getLastErrorCode() instead of this function. * * \return READ ONLY string of last error message. * * \sa PHYSFS_getLastErrorCode * \sa PHYSFS_getErrorByCode */ PHYSFS_DECL const char *PHYSFS_getLastError(void) PHYSFS_DEPRECATED; /** * \fn const char *PHYSFS_getDirSeparator(void) * \brief Get platform-dependent dir separator string. * * This returns "\\" on win32, "/" on Unix, and ":" on MacOS. It may be more * than one character, depending on the platform, and your code should take * that into account. Note that this is only useful for setting up the * search/write paths, since access into those dirs always use '/' * (platform-independent notation) to separate directories. This is also * handy for getting platform-independent access when using stdio calls. * * \return READ ONLY null-terminated string of platform's dir separator. */ PHYSFS_DECL const char *PHYSFS_getDirSeparator(void); /** * \fn void PHYSFS_permitSymbolicLinks(int allow) * \brief Enable or disable following of symbolic links. * * Some physical filesystems and archives contain files that are just pointers * to other files. On the physical filesystem, opening such a link will * (transparently) open the file that is pointed to. * * By default, PhysicsFS will check if a file is really a symlink during open * calls and fail if it is. Otherwise, the link could take you outside the * write and search paths, and compromise security. * * If you want to take that risk, call this function with a non-zero parameter. * Note that this is more for sandboxing a program's scripting language, in * case untrusted scripts try to compromise the system. Generally speaking, * a user could very well have a legitimate reason to set up a symlink, so * unless you feel there's a specific danger in allowing them, you should * permit them. * * Symlinks are only explicitly checked when dealing with filenames * in platform-independent notation. That is, when setting up your * search and write paths, etc, symlinks are never checked for. * * Please note that PHYSFS_stat() will always check the path specified; if * that path is a symlink, it will not be followed in any case. If symlinks * aren't permitted through this function, PHYSFS_stat() ignores them, and * would treat the query as if the path didn't exist at all. * * Symbolic link permission can be enabled or disabled at any time after * you've called PHYSFS_init(), and is disabled by default. * * \param allow nonzero to permit symlinks, zero to deny linking. * * \sa PHYSFS_symbolicLinksPermitted */ PHYSFS_DECL void PHYSFS_permitSymbolicLinks(int allow); /** * \fn char **PHYSFS_getCdRomDirs(void) * \brief Get an array of paths to available CD-ROM drives. * * The dirs returned are platform-dependent ("D:\" on Win32, "/cdrom" or * whatnot on Unix). Dirs are only returned if there is a disc ready and * accessible in the drive. So if you've got two drives (D: and E:), and only * E: has a disc in it, then that's all you get. If the user inserts a disc * in D: and you call this function again, you get both drives. If, on a * Unix box, the user unmounts a disc and remounts it elsewhere, the next * call to this function will reflect that change. * * This function refers to "CD-ROM" media, but it really means "inserted disc * media," such as DVD-ROM, HD-DVD, CDRW, and Blu-Ray discs. It looks for * filesystems, and as such won't report an audio CD, unless there's a * mounted filesystem track on it. * * The returned value is an array of strings, with a NULL entry to signify the * end of the list: * * \code * char **cds = PHYSFS_getCdRomDirs(); * char **i; * * for (i = cds; *i != NULL; i++) * printf("cdrom dir [%s] is available.\n", *i); * * PHYSFS_freeList(cds); * \endcode * * This call may block while drives spin up. Be forewarned. * * When you are done with the returned information, you may dispose of the * resources by calling PHYSFS_freeList() with the returned pointer. * * \return Null-terminated array of null-terminated strings. * * \sa PHYSFS_getCdRomDirsCallback */ PHYSFS_DECL char **PHYSFS_getCdRomDirs(void); /** * \fn const char *PHYSFS_getBaseDir(void) * \brief Get the path where the application resides. * * Helper function. * * Get the "base dir". This is the directory where the application was run * from, which is probably the installation directory, and may or may not * be the process's current working directory. * * You should probably use the base dir in your search path. * * \warning On most platforms, this is a directory; on Android, this gives * you the path to the app's package (APK) file. As APK files are * just .zip files, you can mount them in PhysicsFS like regular * directories. You'll probably want to call * PHYSFS_setRoot(basedir, "/assets") after mounting to make your * app's actual data available directly without all the Android * metadata and directory offset. Note that if you passed a NULL to * PHYSFS_init(), you will not get the APK file here. * * \return READ ONLY string of base dir in platform-dependent notation. * * \sa PHYSFS_getPrefDir */ PHYSFS_DECL const char *PHYSFS_getBaseDir(void); /** * \fn const char *PHYSFS_getUserDir(void) * \brief Get the path where user's home directory resides. * * \deprecated As of PhysicsFS 2.1, you probably want PHYSFS_getPrefDir(). * * Helper function. * * Get the "user dir". This is meant to be a suggestion of where a specific * user of the system can store files. On Unix, this is her home directory. * On systems with no concept of multiple home directories (MacOS, win95), * this will default to something like "C:\mybasedir\users\username" * where "username" will either be the login name, or "default" if the * platform doesn't support multiple users, either. * * \return READ ONLY string of user dir in platform-dependent notation. * * \sa PHYSFS_getBaseDir * \sa PHYSFS_getPrefDir */ PHYSFS_DECL const char *PHYSFS_getUserDir(void) PHYSFS_DEPRECATED; /** * \fn const char *PHYSFS_getWriteDir(void) * \brief Get path where PhysicsFS will allow file writing. * * Get the current write dir. The default write dir is NULL. * * \return READ ONLY string of write dir in platform-dependent notation, * OR NULL IF NO WRITE PATH IS CURRENTLY SET. * * \sa PHYSFS_setWriteDir */ PHYSFS_DECL const char *PHYSFS_getWriteDir(void); /** * \fn int PHYSFS_setWriteDir(const char *newDir) * \brief Tell PhysicsFS where it may write files. * * Set a new write dir. This will override the previous setting. * * This call will fail (and fail to change the write dir) if the current * write dir still has files open in it. * * \param newDir The new directory to be the root of the write dir, * specified in platform-dependent notation. Setting to NULL * disables the write dir, so no files can be opened for * writing via PhysicsFS. * \return non-zero on success, zero on failure. All attempts to open a file * for writing via PhysicsFS will fail until this call succeeds. * Use PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_getWriteDir */ PHYSFS_DECL int PHYSFS_setWriteDir(const char *newDir); /** * \fn int PHYSFS_addToSearchPath(const char *newDir, int appendToPath) * \brief Add an archive or directory to the search path. * * \deprecated As of PhysicsFS 2.0, use PHYSFS_mount() instead. This * function just wraps it anyhow. * * This function is equivalent to: * * \code * PHYSFS_mount(newDir, NULL, appendToPath); * \endcode * * You must use this and not PHYSFS_mount if binary compatibility with * PhysicsFS 1.0 is important (which it may not be for many people). * * \sa PHYSFS_mount * \sa PHYSFS_removeFromSearchPath * \sa PHYSFS_getSearchPath */ PHYSFS_DECL int PHYSFS_addToSearchPath(const char *newDir, int appendToPath) PHYSFS_DEPRECATED; /** * \fn int PHYSFS_removeFromSearchPath(const char *oldDir) * \brief Remove a directory or archive from the search path. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_unmount() instead. This * function just wraps it anyhow. There's no functional difference * except the vocabulary changed from "adding to the search path" * to "mounting" when that functionality was extended, and thus * the preferred way to accomplish this function's work is now * called "unmounting." * * This function is equivalent to: * * \code * PHYSFS_unmount(oldDir); * \endcode * * You must use this and not PHYSFS_unmount if binary compatibility with * PhysicsFS 1.0 is important (which it may not be for many people). * * \sa PHYSFS_addToSearchPath * \sa PHYSFS_getSearchPath * \sa PHYSFS_unmount */ PHYSFS_DECL int PHYSFS_removeFromSearchPath(const char *oldDir) PHYSFS_DEPRECATED; /** * \fn char **PHYSFS_getSearchPath(void) * \brief Get the current search path. * * The default search path is an empty list. * * The returned value is an array of strings, with a NULL entry to signify the * end of the list: * * \code * char **i; * * for (i = PHYSFS_getSearchPath(); *i != NULL; i++) * printf("[%s] is in the search path.\n", *i); * \endcode * * When you are done with the returned information, you may dispose of the * resources by calling PHYSFS_freeList() with the returned pointer. * * \return Null-terminated array of null-terminated strings. NULL if there * was a problem (read: OUT OF MEMORY). * * \sa PHYSFS_getSearchPathCallback * \sa PHYSFS_addToSearchPath * \sa PHYSFS_removeFromSearchPath */ PHYSFS_DECL char **PHYSFS_getSearchPath(void); /** * \fn int PHYSFS_setSaneConfig(const char *organization, const char *appName, const char *archiveExt, int includeCdRoms, int archivesFirst) * \brief Set up sane, default paths. * * Helper function. * * The write dir will be set to the pref dir returned by * \code PHYSFS_getPrefDir(organization, appName) \endcode, which is * created if it doesn't exist. * * The above is sufficient to make sure your program's configuration directory * is separated from other clutter, and platform-independent. * * The search path will be: * * - The Write Dir (created if it doesn't exist) * - The Base Dir (PHYSFS_getBaseDir()) * - All found CD-ROM dirs (optionally) * * These directories are then searched for files ending with the extension * (archiveExt), which, if they are valid and supported archives, will also * be added to the search path. If you specified "PKG" for (archiveExt), and * there's a file named data.PKG in the base dir, it'll be checked. Archives * can either be appended or prepended to the search path in alphabetical * order, regardless of which directories they were found in. All archives * are mounted in the root of the virtual file system ("/"). * * All of this can be accomplished from the application, but this just does it * all for you. Feel free to add more to the search path manually, too. * * \param organization Name of your company/group/etc to be used as a * dirname, so keep it small, and no-frills. * * \param appName Program-specific name of your program, to separate it * from other programs using PhysicsFS. * * \param archiveExt File extension used by your program to specify an * archive. For example, Quake 3 uses "pk3", even though * they are just zipfiles. Specify NULL to not dig out * archives automatically. Do not specify the '.' char; * If you want to look for ZIP files, specify "ZIP" and * not ".ZIP" ... the archive search is case-insensitive. * * \param includeCdRoms Non-zero to include CD-ROMs in the search path, and * (if (archiveExt) != NULL) search them for archives. * This may cause a significant amount of blocking * while discs are accessed, and if there are no discs * in the drive (or even not mounted on Unix systems), * then they may not be made available anyhow. You may * want to specify zero and handle the disc setup * yourself. * * \param archivesFirst Non-zero to prepend the archives to the search path. * Zero to append them. Ignored if !(archiveExt). * * \return nonzero on success, zero on error. Use PHYSFS_getLastErrorCode() * to obtain the specific error. */ PHYSFS_DECL int PHYSFS_setSaneConfig(const char *organization, const char *appName, const char *archiveExt, int includeCdRoms, int archivesFirst); /* Directory management stuff ... */ /** * \fn int PHYSFS_mkdir(const char *dirName) * \brief Create a directory. * * This is specified in platform-independent notation in relation to the * write dir. All missing parent directories are also created if they * don't exist. * * So if you've got the write dir set to "C:\mygame\writedir" and call * PHYSFS_mkdir("downloads/maps") then the directories * "C:\mygame\writedir\downloads" and "C:\mygame\writedir\downloads\maps" * will be created if possible. If the creation of "maps" fails after we * have successfully created "downloads", then the function leaves the * created directory behind and reports failure. * * \param dirName New dir to create. * \return nonzero on success, zero on error. Use * PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_delete */ PHYSFS_DECL int PHYSFS_mkdir(const char *dirName); /** * \fn int PHYSFS_delete(const char *filename) * \brief Delete a file or directory. * * (filename) is specified in platform-independent notation in relation to the * write dir. * * A directory must be empty before this call can delete it. * * Deleting a symlink will remove the link, not what it points to, regardless * of whether you "permitSymLinks" or not. * * So if you've got the write dir set to "C:\mygame\writedir" and call * PHYSFS_delete("downloads/maps/level1.map") then the file * "C:\mygame\writedir\downloads\maps\level1.map" is removed from the * physical filesystem, if it exists and the operating system permits the * deletion. * * Note that on Unix systems, deleting a file may be successful, but the * actual file won't be removed until all processes that have an open * filehandle to it (including your program) close their handles. * * Chances are, the bits that make up the file still exist, they are just * made available to be written over at a later point. Don't consider this * a security method or anything. :) * * \param filename Filename to delete. * \return nonzero on success, zero on error. Use PHYSFS_getLastErrorCode() * to obtain the specific error. */ PHYSFS_DECL int PHYSFS_delete(const char *filename); /** * \fn const char *PHYSFS_getRealDir(const char *filename) * \brief Figure out where in the search path a file resides. * * The file is specified in platform-independent notation. The returned * filename will be the element of the search path where the file was found, * which may be a directory, or an archive. Even if there are multiple * matches in different parts of the search path, only the first one found * is used, just like when opening a file. * * So, if you look for "maps/level1.map", and C:\\mygame is in your search * path and C:\\mygame\\maps\\level1.map exists, then "C:\mygame" is returned. * * If a any part of a match is a symbolic link, and you've not explicitly * permitted symlinks, then it will be ignored, and the search for a match * will continue. * * If you specify a fake directory that only exists as a mount point, it'll * be associated with the first archive mounted there, even though that * directory isn't necessarily contained in a real archive. * * \warning This will return NULL if there is no real directory associated * with (filename). Specifically, PHYSFS_mountIo(), * PHYSFS_mountMemory(), and PHYSFS_mountHandle() will return NULL * even if the filename is found in the search path. Plan accordingly. * * \param filename file to look for. * \return READ ONLY string of element of search path containing the * the file in question. NULL if not found. */ PHYSFS_DECL const char *PHYSFS_getRealDir(const char *filename); /** * \fn char **PHYSFS_enumerateFiles(const char *dir) * \brief Get a file listing of a search path's directory. * * \warning In PhysicsFS versions prior to 2.1, this function would return * as many items as it could in the face of a failure condition * (out of memory, disk i/o error, etc). Since this meant apps * couldn't distinguish between complete success and partial failure, * and since the function could always return NULL to report * catastrophic failures anyway, in PhysicsFS 2.1 this function's * policy changed: it will either return a list of complete results * or it will return NULL for any failure of any kind, so we can * guarantee that the enumeration ran to completion and has no gaps * in its results. * * Matching directories are interpolated. That is, if "C:\mydir" is in the * search path and contains a directory "savegames" that contains "x.sav", * "y.sav", and "z.sav", and there is also a "C:\userdir" in the search path * that has a "savegames" subdirectory with "w.sav", then the following code: * * \code * char **rc = PHYSFS_enumerateFiles("savegames"); * char **i; * * for (i = rc; *i != NULL; i++) * printf(" * We've got [%s].\n", *i); * * PHYSFS_freeList(rc); * \endcode * * \...will print: * * \verbatim * We've got [x.sav]. * We've got [y.sav]. * We've got [z.sav]. * We've got [w.sav].\endverbatim * * Feel free to sort the list however you like. However, the returned data * will always contain no duplicates, and will be always sorted in alphabetic * (rather: case-sensitive Unicode) order for you. * * Don't forget to call PHYSFS_freeList() with the return value from this * function when you are done with it. * * \param dir directory in platform-independent notation to enumerate. * \return Null-terminated array of null-terminated strings, or NULL for * failure cases. * * \sa PHYSFS_enumerate */ PHYSFS_DECL char **PHYSFS_enumerateFiles(const char *dir); /** * \fn int PHYSFS_exists(const char *fname) * \brief Determine if a file exists in the search path. * * Reports true if there is an entry anywhere in the search path by the * name of (fname). * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, so you * might end up further down in the search path than expected. * * \param fname filename in platform-independent notation. * \return non-zero if filename exists. zero otherwise. */ PHYSFS_DECL int PHYSFS_exists(const char *fname); /** * \fn int PHYSFS_isDirectory(const char *fname) * \brief Determine if a file in the search path is really a directory. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_stat() instead. This * function just wraps it anyhow. * * Determine if the first occurence of (fname) in the search path is * really a directory entry. * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, so you * might end up further down in the search path than expected. * * \param fname filename in platform-independent notation. * \return non-zero if filename exists and is a directory. zero otherwise. * * \sa PHYSFS_stat * \sa PHYSFS_exists */ PHYSFS_DECL int PHYSFS_isDirectory(const char *fname) PHYSFS_DEPRECATED; /** * \fn int PHYSFS_isSymbolicLink(const char *fname) * \brief Determine if a file in the search path is really a symbolic link. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_stat() instead. This * function just wraps it anyhow. * * Determine if the first occurence of (fname) in the search path is * really a symbolic link. * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, and as such, * this function will always return 0 in that case. * * \param fname filename in platform-independent notation. * \return non-zero if filename exists and is a symlink. zero otherwise. * * \sa PHYSFS_stat * \sa PHYSFS_exists */ PHYSFS_DECL int PHYSFS_isSymbolicLink(const char *fname) PHYSFS_DEPRECATED; /** * \fn PHYSFS_sint64 PHYSFS_getLastModTime(const char *filename) * \brief Get the last modification time of a file. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_stat() instead. This * function just wraps it anyhow. * * The modtime is returned as a number of seconds since the Unix epoch * (midnight, Jan 1, 1970). The exact derivation and accuracy of this time * depends on the particular archiver. If there is no reasonable way to * obtain this information for a particular archiver, or there was some sort * of error, this function returns (-1). * * You must use this and not PHYSFS_stat() if binary compatibility with * PhysicsFS 2.0 is important (which it may not be for many people). * * \param filename filename to check, in platform-independent notation. * \return last modified time of the file. -1 if it can't be determined. * * \sa PHYSFS_stat */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_getLastModTime(const char *filename) PHYSFS_DEPRECATED; /* i/o stuff... */ /** * \fn PHYSFS_File *PHYSFS_openWrite(const char *filename) * \brief Open a file for writing. * * Open a file for writing, in platform-independent notation and in relation * to the write dir as the root of the writable filesystem. The specified * file is created if it doesn't exist. If it does exist, it is truncated to * zero bytes, and the writing offset is set to the start. * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, and opening a * symlink with this function will fail in such a case. * * \param filename File to open. * \return A valid PhysicsFS filehandle on success, NULL on error. Use * PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_openRead * \sa PHYSFS_openAppend * \sa PHYSFS_write * \sa PHYSFS_close */ PHYSFS_DECL PHYSFS_File *PHYSFS_openWrite(const char *filename); /** * \fn PHYSFS_File *PHYSFS_openAppend(const char *filename) * \brief Open a file for appending. * * Open a file for writing, in platform-independent notation and in relation * to the write dir as the root of the writable filesystem. The specified * file is created if it doesn't exist. If it does exist, the writing offset * is set to the end of the file, so the first write will be the byte after * the end. * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, and opening a * symlink with this function will fail in such a case. * * \param filename File to open. * \return A valid PhysicsFS filehandle on success, NULL on error. Use * PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_openRead * \sa PHYSFS_openWrite * \sa PHYSFS_write * \sa PHYSFS_close */ PHYSFS_DECL PHYSFS_File *PHYSFS_openAppend(const char *filename); /** * \fn PHYSFS_File *PHYSFS_openRead(const char *filename) * \brief Open a file for reading. * * Open a file for reading, in platform-independent notation. The search path * is checked one at a time until a matching file is found, in which case an * abstract filehandle is associated with it, and reading may be done. * The reading offset is set to the first byte of the file. * * Note that entries that are symlinks are ignored if * PHYSFS_permitSymbolicLinks(1) hasn't been called, and opening a * symlink with this function will fail in such a case. * * \param filename File to open. * \return A valid PhysicsFS filehandle on success, NULL on error. * Use PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_openWrite * \sa PHYSFS_openAppend * \sa PHYSFS_read * \sa PHYSFS_close */ PHYSFS_DECL PHYSFS_File *PHYSFS_openRead(const char *filename); /** * \fn int PHYSFS_close(PHYSFS_File *handle) * \brief Close a PhysicsFS filehandle. * * This call is capable of failing if the operating system was buffering * writes to the physical media, and, now forced to write those changes to * physical media, can not store the data for some reason. In such a case, * the filehandle stays open. A well-written program should ALWAYS check the * return value from the close call in addition to every writing call! * * \param handle handle returned from PHYSFS_open*(). * \return nonzero on success, zero on error. Use PHYSFS_getLastErrorCode() * to obtain the specific error. * * \sa PHYSFS_openRead * \sa PHYSFS_openWrite * \sa PHYSFS_openAppend */ PHYSFS_DECL int PHYSFS_close(PHYSFS_File *handle); /** * \fn PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer, PHYSFS_uint32 objSize, PHYSFS_uint32 objCount) * \brief Read data from a PhysicsFS filehandle * * The file must be opened for reading. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_readBytes() instead. This * function just wraps it anyhow. This function never clarified * what would happen if you managed to read a partial object, so * working at the byte level makes this cleaner for everyone, * especially now that PHYSFS_Io interfaces can be supplied by the * application. * * \param handle handle returned from PHYSFS_openRead(). * \param buffer buffer to store read data into. * \param objSize size in bytes of objects being read from (handle). * \param objCount number of (objSize) objects to read from (handle). * \return number of objects read. PHYSFS_getLastErrorCode() can shed light * on the reason this might be < (objCount), as can PHYSFS_eof(). * -1 if complete failure. * * \sa PHYSFS_readBytes * \sa PHYSFS_eof */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer, PHYSFS_uint32 objSize, PHYSFS_uint32 objCount) PHYSFS_DEPRECATED; /** * \fn PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer, PHYSFS_uint32 objSize, PHYSFS_uint32 objCount) * \brief Write data to a PhysicsFS filehandle * * The file must be opened for writing. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_writeBytes() instead. This * function just wraps it anyhow. This function never clarified * what would happen if you managed to write a partial object, so * working at the byte level makes this cleaner for everyone, * especially now that PHYSFS_Io interfaces can be supplied by the * application. * * \param handle retval from PHYSFS_openWrite() or PHYSFS_openAppend(). * \param buffer buffer of bytes to write to (handle). * \param objSize size in bytes of objects being written to (handle). * \param objCount number of (objSize) objects to write to (handle). * \return number of objects written. PHYSFS_getLastErrorCode() can shed * light on the reason this might be < (objCount). -1 if complete * failure. * * \sa PHYSFS_writeBytes */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer, PHYSFS_uint32 objSize, PHYSFS_uint32 objCount) PHYSFS_DEPRECATED; /* File position stuff... */ /** * \fn int PHYSFS_eof(PHYSFS_File *handle) * \brief Check for end-of-file state on a PhysicsFS filehandle. * * Determine if the end of file has been reached in a PhysicsFS filehandle. * * \param handle handle returned from PHYSFS_openRead(). * \return nonzero if EOF, zero if not. * * \sa PHYSFS_read * \sa PHYSFS_tell */ PHYSFS_DECL int PHYSFS_eof(PHYSFS_File *handle); /** * \fn PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle) * \brief Determine current position within a PhysicsFS filehandle. * * \param handle handle returned from PHYSFS_open*(). * \return offset in bytes from start of file. -1 if error occurred. * Use PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_seek */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle); /** * \fn int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos) * \brief Seek to a new position within a PhysicsFS filehandle. * * The next read or write will occur at that place. Seeking past the * beginning or end of the file is not allowed, and causes an error. * * \param handle handle returned from PHYSFS_open*(). * \param pos number of bytes from start of file to seek to. * \return nonzero on success, zero on error. Use PHYSFS_getLastErrorCode() * to obtain the specific error. * * \sa PHYSFS_tell */ PHYSFS_DECL int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos); /** * \fn PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle) * \brief Get total length of a file in bytes. * * Note that if another process/thread is writing to this file at the same * time, then the information this function supplies could be incorrect * before you get it. Use with caution, or better yet, don't use at all. * * \param handle handle returned from PHYSFS_open*(). * \return size in bytes of the file. -1 if can't be determined. * * \sa PHYSFS_tell * \sa PHYSFS_seek */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle); /* Buffering stuff... */ /** * \fn int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 bufsize) * \brief Set up buffering for a PhysicsFS file handle. * * Define an i/o buffer for a file handle. A memory block of (bufsize) bytes * will be allocated and associated with (handle). * * For files opened for reading, up to (bufsize) bytes are read from (handle) * and stored in the internal buffer. Calls to PHYSFS_read() will pull * from this buffer until it is empty, and then refill it for more reading. * Note that compressed files, like ZIP archives, will decompress while * buffering, so this can be handy for offsetting CPU-intensive operations. * The buffer isn't filled until you do your next read. * * For files opened for writing, data will be buffered to memory until the * buffer is full or the buffer is flushed. Closing a handle implicitly * causes a flush...check your return values! * * Seeking, etc transparently accounts for buffering. * * You can resize an existing buffer by calling this function more than once * on the same file. Setting the buffer size to zero will free an existing * buffer. * * PhysicsFS file handles are unbuffered by default. * * Please check the return value of this function! Failures can include * not being able to seek backwards in a read-only file when removing the * buffer, not being able to allocate the buffer, and not being able to * flush the buffer to disk, among other unexpected problems. * * \param handle handle returned from PHYSFS_open*(). * \param bufsize size, in bytes, of buffer to allocate. * \return nonzero if successful, zero on error. * * \sa PHYSFS_flush * \sa PHYSFS_read * \sa PHYSFS_write * \sa PHYSFS_close */ PHYSFS_DECL int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 bufsize); /** * \fn int PHYSFS_flush(PHYSFS_File *handle) * \brief Flush a buffered PhysicsFS file handle. * * For buffered files opened for writing, this will put the current contents * of the buffer to disk and flag the buffer as empty if possible. * * For buffered files opened for reading or unbuffered files, this is a safe * no-op, and will report success. * * \param handle handle returned from PHYSFS_open*(). * \return nonzero if successful, zero on error. * * \sa PHYSFS_setBuffer * \sa PHYSFS_close */ PHYSFS_DECL int PHYSFS_flush(PHYSFS_File *handle); /* Byteorder stuff... */ /** * \fn PHYSFS_sint16 PHYSFS_swapSLE16(PHYSFS_sint16 val) * \brief Swap littleendian signed 16 to platform's native byte order. * * Take a 16-bit signed value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_sint16 PHYSFS_swapSLE16(PHYSFS_sint16 val); /** * \fn PHYSFS_uint16 PHYSFS_swapULE16(PHYSFS_uint16 val) * \brief Swap littleendian unsigned 16 to platform's native byte order. * * Take a 16-bit unsigned value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_uint16 PHYSFS_swapULE16(PHYSFS_uint16 val); /** * \fn PHYSFS_sint32 PHYSFS_swapSLE32(PHYSFS_sint32 val) * \brief Swap littleendian signed 32 to platform's native byte order. * * Take a 32-bit signed value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_sint32 PHYSFS_swapSLE32(PHYSFS_sint32 val); /** * \fn PHYSFS_uint32 PHYSFS_swapULE32(PHYSFS_uint32 val) * \brief Swap littleendian unsigned 32 to platform's native byte order. * * Take a 32-bit unsigned value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_uint32 PHYSFS_swapULE32(PHYSFS_uint32 val); /** * \fn PHYSFS_sint64 PHYSFS_swapSLE64(PHYSFS_sint64 val) * \brief Swap littleendian signed 64 to platform's native byte order. * * Take a 64-bit signed value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_swapSLE64(PHYSFS_sint64 val); /** * \fn PHYSFS_uint64 PHYSFS_swapULE64(PHYSFS_uint64 val) * \brief Swap littleendian unsigned 64 to platform's native byte order. * * Take a 64-bit unsigned value in littleendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL PHYSFS_uint64 PHYSFS_swapULE64(PHYSFS_uint64 val); /** * \fn PHYSFS_sint16 PHYSFS_swapSBE16(PHYSFS_sint16 val) * \brief Swap bigendian signed 16 to platform's native byte order. * * Take a 16-bit signed value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_sint16 PHYSFS_swapSBE16(PHYSFS_sint16 val); /** * \fn PHYSFS_uint16 PHYSFS_swapUBE16(PHYSFS_uint16 val) * \brief Swap bigendian unsigned 16 to platform's native byte order. * * Take a 16-bit unsigned value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_uint16 PHYSFS_swapUBE16(PHYSFS_uint16 val); /** * \fn PHYSFS_sint32 PHYSFS_swapSBE32(PHYSFS_sint32 val) * \brief Swap bigendian signed 32 to platform's native byte order. * * Take a 32-bit signed value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_sint32 PHYSFS_swapSBE32(PHYSFS_sint32 val); /** * \fn PHYSFS_uint32 PHYSFS_swapUBE32(PHYSFS_uint32 val) * \brief Swap bigendian unsigned 32 to platform's native byte order. * * Take a 32-bit unsigned value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. */ PHYSFS_DECL PHYSFS_uint32 PHYSFS_swapUBE32(PHYSFS_uint32 val); /** * \fn PHYSFS_sint64 PHYSFS_swapSBE64(PHYSFS_sint64 val) * \brief Swap bigendian signed 64 to platform's native byte order. * * Take a 64-bit signed value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_swapSBE64(PHYSFS_sint64 val); /** * \fn PHYSFS_uint64 PHYSFS_swapUBE64(PHYSFS_uint64 val) * \brief Swap bigendian unsigned 64 to platform's native byte order. * * Take a 64-bit unsigned value in bigendian format and convert it to * the platform's native byte order. * * \param val value to convert * \return converted value. * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL PHYSFS_uint64 PHYSFS_swapUBE64(PHYSFS_uint64 val); /** * \fn int PHYSFS_readSLE16(PHYSFS_File *file, PHYSFS_sint16 *val) * \brief Read and convert a signed 16-bit littleendian value. * * Convenience function. Read a signed 16-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_readSLE16(PHYSFS_File *file, PHYSFS_sint16 *val); /** * \fn int PHYSFS_readULE16(PHYSFS_File *file, PHYSFS_uint16 *val) * \brief Read and convert an unsigned 16-bit littleendian value. * * Convenience function. Read an unsigned 16-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * */ PHYSFS_DECL int PHYSFS_readULE16(PHYSFS_File *file, PHYSFS_uint16 *val); /** * \fn int PHYSFS_readSBE16(PHYSFS_File *file, PHYSFS_sint16 *val) * \brief Read and convert a signed 16-bit bigendian value. * * Convenience function. Read a signed 16-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_readSBE16(PHYSFS_File *file, PHYSFS_sint16 *val); /** * \fn int PHYSFS_readUBE16(PHYSFS_File *file, PHYSFS_uint16 *val) * \brief Read and convert an unsigned 16-bit bigendian value. * * Convenience function. Read an unsigned 16-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * */ PHYSFS_DECL int PHYSFS_readUBE16(PHYSFS_File *file, PHYSFS_uint16 *val); /** * \fn int PHYSFS_readSLE32(PHYSFS_File *file, PHYSFS_sint32 *val) * \brief Read and convert a signed 32-bit littleendian value. * * Convenience function. Read a signed 32-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_readSLE32(PHYSFS_File *file, PHYSFS_sint32 *val); /** * \fn int PHYSFS_readULE32(PHYSFS_File *file, PHYSFS_uint32 *val) * \brief Read and convert an unsigned 32-bit littleendian value. * * Convenience function. Read an unsigned 32-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * */ PHYSFS_DECL int PHYSFS_readULE32(PHYSFS_File *file, PHYSFS_uint32 *val); /** * \fn int PHYSFS_readSBE32(PHYSFS_File *file, PHYSFS_sint32 *val) * \brief Read and convert a signed 32-bit bigendian value. * * Convenience function. Read a signed 32-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_readSBE32(PHYSFS_File *file, PHYSFS_sint32 *val); /** * \fn int PHYSFS_readUBE32(PHYSFS_File *file, PHYSFS_uint32 *val) * \brief Read and convert an unsigned 32-bit bigendian value. * * Convenience function. Read an unsigned 32-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * */ PHYSFS_DECL int PHYSFS_readUBE32(PHYSFS_File *file, PHYSFS_uint32 *val); /** * \fn int PHYSFS_readSLE64(PHYSFS_File *file, PHYSFS_sint64 *val) * \brief Read and convert a signed 64-bit littleendian value. * * Convenience function. Read a signed 64-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_readSLE64(PHYSFS_File *file, PHYSFS_sint64 *val); /** * \fn int PHYSFS_readULE64(PHYSFS_File *file, PHYSFS_uint64 *val) * \brief Read and convert an unsigned 64-bit littleendian value. * * Convenience function. Read an unsigned 64-bit littleendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_readULE64(PHYSFS_File *file, PHYSFS_uint64 *val); /** * \fn int PHYSFS_readSBE64(PHYSFS_File *file, PHYSFS_sint64 *val) * \brief Read and convert a signed 64-bit bigendian value. * * Convenience function. Read a signed 64-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_readSBE64(PHYSFS_File *file, PHYSFS_sint64 *val); /** * \fn int PHYSFS_readUBE64(PHYSFS_File *file, PHYSFS_uint64 *val) * \brief Read and convert an unsigned 64-bit bigendian value. * * Convenience function. Read an unsigned 64-bit bigendian value from a * file and convert it to the platform's native byte order. * * \param file PhysicsFS file handle from which to read. * \param val pointer to where value should be stored. * \return zero on failure, non-zero on success. If successful, (*val) will * store the result. On failure, you can find out what went wrong * from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_readUBE64(PHYSFS_File *file, PHYSFS_uint64 *val); /** * \fn int PHYSFS_writeSLE16(PHYSFS_File *file, PHYSFS_sint16 val) * \brief Convert and write a signed 16-bit littleendian value. * * Convenience function. Convert a signed 16-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeSLE16(PHYSFS_File *file, PHYSFS_sint16 val); /** * \fn int PHYSFS_writeULE16(PHYSFS_File *file, PHYSFS_uint16 val) * \brief Convert and write an unsigned 16-bit littleendian value. * * Convenience function. Convert an unsigned 16-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeULE16(PHYSFS_File *file, PHYSFS_uint16 val); /** * \fn int PHYSFS_writeSBE16(PHYSFS_File *file, PHYSFS_sint16 val) * \brief Convert and write a signed 16-bit bigendian value. * * Convenience function. Convert a signed 16-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeSBE16(PHYSFS_File *file, PHYSFS_sint16 val); /** * \fn int PHYSFS_writeUBE16(PHYSFS_File *file, PHYSFS_uint16 val) * \brief Convert and write an unsigned 16-bit bigendian value. * * Convenience function. Convert an unsigned 16-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeUBE16(PHYSFS_File *file, PHYSFS_uint16 val); /** * \fn int PHYSFS_writeSLE32(PHYSFS_File *file, PHYSFS_sint32 val) * \brief Convert and write a signed 32-bit littleendian value. * * Convenience function. Convert a signed 32-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeSLE32(PHYSFS_File *file, PHYSFS_sint32 val); /** * \fn int PHYSFS_writeULE32(PHYSFS_File *file, PHYSFS_uint32 val) * \brief Convert and write an unsigned 32-bit littleendian value. * * Convenience function. Convert an unsigned 32-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeULE32(PHYSFS_File *file, PHYSFS_uint32 val); /** * \fn int PHYSFS_writeSBE32(PHYSFS_File *file, PHYSFS_sint32 val) * \brief Convert and write a signed 32-bit bigendian value. * * Convenience function. Convert a signed 32-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeSBE32(PHYSFS_File *file, PHYSFS_sint32 val); /** * \fn int PHYSFS_writeUBE32(PHYSFS_File *file, PHYSFS_uint32 val) * \brief Convert and write an unsigned 32-bit bigendian value. * * Convenience function. Convert an unsigned 32-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). */ PHYSFS_DECL int PHYSFS_writeUBE32(PHYSFS_File *file, PHYSFS_uint32 val); /** * \fn int PHYSFS_writeSLE64(PHYSFS_File *file, PHYSFS_sint64 val) * \brief Convert and write a signed 64-bit littleendian value. * * Convenience function. Convert a signed 64-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_writeSLE64(PHYSFS_File *file, PHYSFS_sint64 val); /** * \fn int PHYSFS_writeULE64(PHYSFS_File *file, PHYSFS_uint64 val) * \brief Convert and write an unsigned 64-bit littleendian value. * * Convenience function. Convert an unsigned 64-bit value from the platform's * native byte order to littleendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_writeULE64(PHYSFS_File *file, PHYSFS_uint64 val); /** * \fn int PHYSFS_writeSBE64(PHYSFS_File *file, PHYSFS_sint64 val) * \brief Convert and write a signed 64-bit bigending value. * * Convenience function. Convert a signed 64-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_sint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_writeSBE64(PHYSFS_File *file, PHYSFS_sint64 val); /** * \fn int PHYSFS_writeUBE64(PHYSFS_File *file, PHYSFS_uint64 val) * \brief Convert and write an unsigned 64-bit bigendian value. * * Convenience function. Convert an unsigned 64-bit value from the platform's * native byte order to bigendian and write it to a file. * * \param file PhysicsFS file handle to which to write. * \param val Value to convert and write. * \return zero on failure, non-zero on success. On failure, you can * find out what went wrong from PHYSFS_getLastErrorCode(). * * \warning Remember, PHYSFS_uint64 is only 32 bits on platforms without * any sort of 64-bit support. */ PHYSFS_DECL int PHYSFS_writeUBE64(PHYSFS_File *file, PHYSFS_uint64 val); /* Everything above this line is part of the PhysicsFS 1.0 API. */ /** * \fn int PHYSFS_isInit(void) * \brief Determine if the PhysicsFS library is initialized. * * Once PHYSFS_init() returns successfully, this will return non-zero. * Before a successful PHYSFS_init() and after PHYSFS_deinit() returns * successfully, this will return zero. This function is safe to call at * any time. * * \return non-zero if library is initialized, zero if library is not. * * \sa PHYSFS_init * \sa PHYSFS_deinit */ PHYSFS_DECL int PHYSFS_isInit(void); /** * \fn int PHYSFS_symbolicLinksPermitted(void) * \brief Determine if the symbolic links are permitted. * * This reports the setting from the last call to PHYSFS_permitSymbolicLinks(). * If PHYSFS_permitSymbolicLinks() hasn't been called since the library was * last initialized, symbolic links are implicitly disabled. * * \return non-zero if symlinks are permitted, zero if not. * * \sa PHYSFS_permitSymbolicLinks */ PHYSFS_DECL int PHYSFS_symbolicLinksPermitted(void); /** * \struct PHYSFS_Allocator * \brief PhysicsFS allocation function pointers. * * (This is for limited, hardcore use. If you don't immediately see a need * for it, you can probably ignore this forever.) * * You create one of these structures for use with PHYSFS_setAllocator. * Allocators are assumed to be reentrant by the caller; please mutex * accordingly. * * Allocations are always discussed in 64-bits, for future expansion...we're * on the cusp of a 64-bit transition, and we'll probably be allocating 6 * gigabytes like it's nothing sooner or later, and I don't want to change * this again at that point. If you're on a 32-bit platform and have to * downcast, it's okay to return NULL if the allocation is greater than * 4 gigabytes, since you'd have to do so anyhow. * * \sa PHYSFS_setAllocator */ typedef struct PHYSFS_Allocator { int (*Init)(void); /**< Initialize. Can be NULL. Zero on failure. */ void (*Deinit)(void); /**< Deinitialize your allocator. Can be NULL. */ void *(*Malloc)(PHYSFS_uint64); /**< Allocate like malloc(). */ void *(*Realloc)(void *, PHYSFS_uint64); /**< Reallocate like realloc(). */ void (*Free)(void *); /**< Free memory from Malloc or Realloc. */ } PHYSFS_Allocator; /** * \fn int PHYSFS_setAllocator(const PHYSFS_Allocator *allocator) * \brief Hook your own allocation routines into PhysicsFS. * * (This is for limited, hardcore use. If you don't immediately see a need * for it, you can probably ignore this forever.) * * By default, PhysicsFS will use whatever is reasonable for a platform * to manage dynamic memory (usually ANSI C malloc/realloc/free, but * some platforms might use something else), but in some uncommon cases, the * app might want more control over the library's memory management. This * lets you redirect PhysicsFS to use your own allocation routines instead. * You can only call this function before PHYSFS_init(); if the library is * initialized, it'll reject your efforts to change the allocator mid-stream. * You may call this function after PHYSFS_deinit() if you are willing to * shut down the library and restart it with a new allocator; this is a safe * and supported operation. The allocator remains intact between deinit/init * calls. If you want to return to the platform's default allocator, pass a * NULL in here. * * If you aren't immediately sure what to do with this function, you can * safely ignore it altogether. * * \param allocator Structure containing your allocator's entry points. * \return zero on failure, non-zero on success. This call only fails * when used between PHYSFS_init() and PHYSFS_deinit() calls. */ PHYSFS_DECL int PHYSFS_setAllocator(const PHYSFS_Allocator *allocator); /** * \fn int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath) * \brief Add an archive or directory to the search path. * * If this is a duplicate, the entry is not added again, even though the * function succeeds. You may not add the same archive to two different * mountpoints: duplicate checking is done against the archive and not the * mountpoint. * * When you mount an archive, it is added to a virtual file system...all files * in all of the archives are interpolated into a single hierachical file * tree. Two archives mounted at the same place (or an archive with files * overlapping another mountpoint) may have overlapping files: in such a case, * the file earliest in the search path is selected, and the other files are * inaccessible to the application. This allows archives to be used to * override previous revisions; you can use the mounting mechanism to place * archives at a specific point in the file tree and prevent overlap; this * is useful for downloadable mods that might trample over application data * or each other, for example. * * The mountpoint does not need to exist prior to mounting, which is different * than those familiar with the Unix concept of "mounting" may expect. * As well, more than one archive can be mounted to the same mountpoint, or * mountpoints and archive contents can overlap...the interpolation mechanism * still functions as usual. * * Specifying a symbolic link to an archive or directory is allowed here, * regardless of the state of PHYSFS_permitSymbolicLinks(). That function * only deals with symlinks inside the mounted directory or archive. * * \param newDir directory or archive to add to the path, in * platform-dependent notation. * \param mountPoint Location in the interpolated tree that this archive * will be "mounted", in platform-independent notation. * NULL or "" is equivalent to "/". * \param appendToPath nonzero to append to search path, zero to prepend. * \return nonzero if added to path, zero on failure (bogus archive, dir * missing, etc). Use PHYSFS_getLastErrorCode() to obtain * the specific error. * * \sa PHYSFS_removeFromSearchPath * \sa PHYSFS_getSearchPath * \sa PHYSFS_getMountPoint * \sa PHYSFS_mountIo */ PHYSFS_DECL int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath); /** * \fn int PHYSFS_getMountPoint(const char *dir) * \brief Determine a mounted archive's mountpoint. * * You give this function the name of an archive or dir you successfully * added to the search path, and it reports the location in the interpolated * tree where it is mounted. Files mounted with a NULL mountpoint or through * PHYSFS_addToSearchPath() will report "/". The return value is READ ONLY * and valid until the archive is removed from the search path. * * \param dir directory or archive previously added to the path, in * platform-dependent notation. This must match the string * used when adding, even if your string would also reference * the same file with a different string of characters. * \return READ-ONLY string of mount point if added to path, NULL on failure * (bogus archive, etc). Use PHYSFS_getLastErrorCode() to obtain the * specific error. * * \sa PHYSFS_removeFromSearchPath * \sa PHYSFS_getSearchPath * \sa PHYSFS_getMountPoint */ PHYSFS_DECL const char *PHYSFS_getMountPoint(const char *dir); /** * \typedef PHYSFS_StringCallback * \brief Function signature for callbacks that report strings. * * These are used to report a list of strings to an original caller, one * string per callback. All strings are UTF-8 encoded. Functions should not * try to modify or free the string's memory. * * These callbacks are used, starting in PhysicsFS 1.1, as an alternative to * functions that would return lists that need to be cleaned up with * PHYSFS_freeList(). The callback means that the library doesn't need to * allocate an entire list and all the strings up front. * * Be aware that promises data ordering in the list versions are not * necessarily so in the callback versions. Check the documentation on * specific APIs, but strings may not be sorted as you expect. * * \param data User-defined data pointer, passed through from the API * that eventually called the callback. * \param str The string data about which the callback is meant to inform. * * \sa PHYSFS_getCdRomDirsCallback * \sa PHYSFS_getSearchPathCallback */ typedef void (*PHYSFS_StringCallback)(void *data, const char *str); /** * \typedef PHYSFS_EnumFilesCallback * \brief Function signature for callbacks that enumerate files. * * \warning As of PhysicsFS 2.1, Use PHYSFS_EnumerateCallback with * PHYSFS_enumerate() instead; it gives you more control over the process. * * These are used to report a list of directory entries to an original caller, * one file/dir/symlink per callback. All strings are UTF-8 encoded. * Functions should not try to modify or free any string's memory. * * These callbacks are used, starting in PhysicsFS 1.1, as an alternative to * functions that would return lists that need to be cleaned up with * PHYSFS_freeList(). The callback means that the library doesn't need to * allocate an entire list and all the strings up front. * * Be aware that promised data ordering in the list versions are not * necessarily so in the callback versions. Check the documentation on * specific APIs, but strings may not be sorted as you expect and you might * get duplicate strings. * * \param data User-defined data pointer, passed through from the API * that eventually called the callback. * \param origdir A string containing the full path, in platform-independent * notation, of the directory containing this file. In most * cases, this is the directory on which you requested * enumeration, passed in the callback for your convenience. * \param fname The filename that is being enumerated. It may not be in * alphabetical order compared to other callbacks that have * fired, and it will not contain the full path. You can * recreate the fullpath with $origdir/$fname ... The file * can be a subdirectory, a file, a symlink, etc. * * \sa PHYSFS_enumerateFilesCallback */ typedef void (*PHYSFS_EnumFilesCallback)(void *data, const char *origdir, const char *fname); /** * \fn void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback c, void *d) * \brief Enumerate CD-ROM directories, using an application-defined callback. * * Internally, PHYSFS_getCdRomDirs() just calls this function and then builds * a list before returning to the application, so functionality is identical * except for how the information is represented to the application. * * Unlike PHYSFS_getCdRomDirs(), this function does not return an array. * Rather, it calls a function specified by the application once per * detected disc: * * \code * * static void foundDisc(void *data, const char *cddir) * { * printf("cdrom dir [%s] is available.\n", cddir); * } * * // ... * PHYSFS_getCdRomDirsCallback(foundDisc, NULL); * \endcode * * This call may block while drives spin up. Be forewarned. * * \param c Callback function to notify about detected drives. * \param d Application-defined data passed to callback. Can be NULL. * * \sa PHYSFS_StringCallback * \sa PHYSFS_getCdRomDirs */ PHYSFS_DECL void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback c, void *d); /** * \fn void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback c, void *d) * \brief Enumerate the search path, using an application-defined callback. * * Internally, PHYSFS_getSearchPath() just calls this function and then builds * a list before returning to the application, so functionality is identical * except for how the information is represented to the application. * * Unlike PHYSFS_getSearchPath(), this function does not return an array. * Rather, it calls a function specified by the application once per * element of the search path: * * \code * * static void printSearchPath(void *data, const char *pathItem) * { * printf("[%s] is in the search path.\n", pathItem); * } * * // ... * PHYSFS_getSearchPathCallback(printSearchPath, NULL); * \endcode * * Elements of the search path are reported in order search priority, so the * first archive/dir that would be examined when looking for a file is the * first element passed through the callback. * * \param c Callback function to notify about search path elements. * \param d Application-defined data passed to callback. Can be NULL. * * \sa PHYSFS_StringCallback * \sa PHYSFS_getSearchPath */ PHYSFS_DECL void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback c, void *d); /** * \fn void PHYSFS_enumerateFilesCallback(const char *dir, PHYSFS_EnumFilesCallback c, void *d) * \brief Get a file listing of a search path's directory, using an application-defined callback. * * \deprecated As of PhysicsFS 2.1, use PHYSFS_enumerate() instead. This * function has no way to report errors (or to have the callback signal an * error or request a stop), so if data will be lost, your callback has no * way to direct the process, and your calling app has no way to know. * * As of PhysicsFS 2.1, this function just wraps PHYSFS_enumerate() and * ignores errors. Consider using PHYSFS_enumerate() or * PHYSFS_enumerateFiles() instead. * * \sa PHYSFS_enumerate * \sa PHYSFS_enumerateFiles * \sa PHYSFS_EnumFilesCallback */ PHYSFS_DECL void PHYSFS_enumerateFilesCallback(const char *dir, PHYSFS_EnumFilesCallback c, void *d) PHYSFS_DEPRECATED; /** * \fn void PHYSFS_utf8FromUcs4(const PHYSFS_uint32 *src, char *dst, PHYSFS_uint64 len) * \brief Convert a UCS-4 string to a UTF-8 string. * * \warning This function will not report an error if there are invalid UCS-4 * values in the source string. It will replace them with a '?' * character and continue on. * * UCS-4 (aka UTF-32) strings are 32-bits per character: \c wchar_t on Unix. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is the same size as the source buffer. UTF-8 * never uses more than 32-bits per character, so while it may shrink a UCS-4 * string, it will never expand it. * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UTF-8 * sequence at the end. If the buffer length is 0, this function does nothing. * * \param src Null-terminated source string in UCS-4 format. * \param dst Buffer to store converted UTF-8 string. * \param len Size, in bytes, of destination buffer. */ PHYSFS_DECL void PHYSFS_utf8FromUcs4(const PHYSFS_uint32 *src, char *dst, PHYSFS_uint64 len); /** * \fn void PHYSFS_utf8ToUcs4(const char *src, PHYSFS_uint32 *dst, PHYSFS_uint64 len) * \brief Convert a UTF-8 string to a UCS-4 string. * * \warning This function will not report an error if there are invalid UTF-8 * sequences in the source string. It will replace them with a '?' * character and continue on. * * UCS-4 (aka UTF-32) strings are 32-bits per character: \c wchar_t on Unix. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is four times the size of the source buffer. * UTF-8 uses from one to four bytes per character, but UCS-4 always uses * four, so an entirely low-ASCII string will quadruple in size! * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UCS-4 * sequence at the end. If the buffer length is 0, this function does nothing. * * \param src Null-terminated source string in UTF-8 format. * \param dst Buffer to store converted UCS-4 string. * \param len Size, in bytes, of destination buffer. */ PHYSFS_DECL void PHYSFS_utf8ToUcs4(const char *src, PHYSFS_uint32 *dst, PHYSFS_uint64 len); /** * \fn void PHYSFS_utf8FromUcs2(const PHYSFS_uint16 *src, char *dst, PHYSFS_uint64 len) * \brief Convert a UCS-2 string to a UTF-8 string. * * \warning you almost certainly should use PHYSFS_utf8FromUtf16(), which * became available in PhysicsFS 2.1, unless you know what you're doing. * * \warning This function will not report an error if there are invalid UCS-2 * values in the source string. It will replace them with a '?' * character and continue on. * * UCS-2 strings are 16-bits per character: \c TCHAR on Windows, when building * with Unicode support. Please note that modern versions of Windows use * UTF-16, which is an extended form of UCS-2, and not UCS-2 itself. You * almost certainly want PHYSFS_utf8FromUtf16() instead. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is double the size of the source buffer. * UTF-8 never uses more than 32-bits per character, so while it may shrink * a UCS-2 string, it may also expand it. * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UTF-8 * sequence at the end. If the buffer length is 0, this function does nothing. * * \param src Null-terminated source string in UCS-2 format. * \param dst Buffer to store converted UTF-8 string. * \param len Size, in bytes, of destination buffer. * * \sa PHYSFS_utf8FromUtf16 */ PHYSFS_DECL void PHYSFS_utf8FromUcs2(const PHYSFS_uint16 *src, char *dst, PHYSFS_uint64 len); /** * \fn PHYSFS_utf8ToUcs2(const char *src, PHYSFS_uint16 *dst, PHYSFS_uint64 len) * \brief Convert a UTF-8 string to a UCS-2 string. * * \warning you almost certainly should use PHYSFS_utf8ToUtf16(), which * became available in PhysicsFS 2.1, unless you know what you're doing. * * \warning This function will not report an error if there are invalid UTF-8 * sequences in the source string. It will replace them with a '?' * character and continue on. * * UCS-2 strings are 16-bits per character: \c TCHAR on Windows, when building * with Unicode support. Please note that modern versions of Windows use * UTF-16, which is an extended form of UCS-2, and not UCS-2 itself. You * almost certainly want PHYSFS_utf8ToUtf16() instead, but you need to * understand how that changes things, too. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is double the size of the source buffer. * UTF-8 uses from one to four bytes per character, but UCS-2 always uses * two, so an entirely low-ASCII string will double in size! * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UCS-2 * sequence at the end. If the buffer length is 0, this function does nothing. * * \param src Null-terminated source string in UTF-8 format. * \param dst Buffer to store converted UCS-2 string. * \param len Size, in bytes, of destination buffer. * * \sa PHYSFS_utf8ToUtf16 */ PHYSFS_DECL void PHYSFS_utf8ToUcs2(const char *src, PHYSFS_uint16 *dst, PHYSFS_uint64 len); /** * \fn void PHYSFS_utf8FromLatin1(const char *src, char *dst, PHYSFS_uint64 len) * \brief Convert a UTF-8 string to a Latin1 string. * * Latin1 strings are 8-bits per character: a popular "high ASCII" encoding. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is double the size of the source buffer. * UTF-8 expands latin1 codepoints over 127 from 1 to 2 bytes, so the string * may grow in some cases. * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UTF-8 * sequence at the end. If the buffer length is 0, this function does nothing. * * Please note that we do not supply a UTF-8 to Latin1 converter, since Latin1 * can't express most Unicode codepoints. It's a legacy encoding; you should * be converting away from it at all times. * * \param src Null-terminated source string in Latin1 format. * \param dst Buffer to store converted UTF-8 string. * \param len Size, in bytes, of destination buffer. */ PHYSFS_DECL void PHYSFS_utf8FromLatin1(const char *src, char *dst, PHYSFS_uint64 len); /* Everything above this line is part of the PhysicsFS 2.0 API. */ /** * \fn int PHYSFS_caseFold(const PHYSFS_uint32 from, PHYSFS_uint32 *to) * \brief "Fold" a Unicode codepoint to a lowercase equivalent. * * (This is for limited, hardcore use. If you don't immediately see a need * for it, you can probably ignore this forever.) * * This will convert a Unicode codepoint into its lowercase equivalent. * Bogus codepoints and codepoints without a lowercase equivalent will * be returned unconverted. * * Note that you might get multiple codepoints in return! The German Eszett, * for example, will fold down to two lowercase latin 's' codepoints. The * theory is that if you fold two strings, one with an Eszett and one with * "SS" down, they will match. * * \warning Anyone that is a student of Unicode knows about the "Turkish I" * problem. This API does not handle it. Assume this one letter * in all of Unicode will definitely fold sort of incorrectly. If * you don't know what this is about, you can probably ignore this * problem for most of the planet, but perfection is impossible. * * \param from The codepoint to fold. * \param to Buffer to store the folded codepoint values into. This should * point to space for at least 3 PHYSFS_uint32 slots. * \return The number of codepoints the folding produced. Between 1 and 3. */ PHYSFS_DECL int PHYSFS_caseFold(const PHYSFS_uint32 from, PHYSFS_uint32 *to); /** * \fn int PHYSFS_utf8stricmp(const char *str1, const char *str2) * \brief Case-insensitive compare of two UTF-8 strings. * * This is a strcasecmp/stricmp replacement that expects both strings * to be in UTF-8 encoding. It will do "case folding" to decide if the * Unicode codepoints in the strings match. * * If both strings are exclusively low-ASCII characters, this will do the * right thing, as that is also valid UTF-8. If there are any high-ASCII * chars, this will not do what you expect! * * It will report which string is "greater than" the other, but be aware that * this doesn't necessarily mean anything: 'a' may be "less than" 'b', but * a Japanese kuten has no meaningful alphabetically relationship to * a Greek lambda, but being able to assign a reliable "value" makes sorting * algorithms possible, if not entirely sane. Most cases should treat the * return value as "equal" or "not equal". * * Like stricmp, this expects both strings to be NULL-terminated. * * \param str1 First string to compare. * \param str2 Second string to compare. * \return -1 if str1 is "less than" str2, 1 if "greater than", 0 if equal. */ PHYSFS_DECL int PHYSFS_utf8stricmp(const char *str1, const char *str2); /** * \fn int PHYSFS_utf16stricmp(const PHYSFS_uint16 *str1, const PHYSFS_uint16 *str2) * \brief Case-insensitive compare of two UTF-16 strings. * * This is a strcasecmp/stricmp replacement that expects both strings * to be in UTF-16 encoding. It will do "case folding" to decide if the * Unicode codepoints in the strings match. * * It will report which string is "greater than" the other, but be aware that * this doesn't necessarily mean anything: 'a' may be "less than" 'b', but * a Japanese kuten has no meaningful alphabetically relationship to * a Greek lambda, but being able to assign a reliable "value" makes sorting * algorithms possible, if not entirely sane. Most cases should treat the * return value as "equal" or "not equal". * * Like stricmp, this expects both strings to be NULL-terminated. * * \param str1 First string to compare. * \param str2 Second string to compare. * \return -1 if str1 is "less than" str2, 1 if "greater than", 0 if equal. */ PHYSFS_DECL int PHYSFS_utf16stricmp(const PHYSFS_uint16 *str1, const PHYSFS_uint16 *str2); /** * \fn int PHYSFS_ucs4stricmp(const PHYSFS_uint32 *str1, const PHYSFS_uint32 *str2) * \brief Case-insensitive compare of two UCS-4 strings. * * This is a strcasecmp/stricmp replacement that expects both strings * to be in UCS-4 (aka UTF-32) encoding. It will do "case folding" to decide * if the Unicode codepoints in the strings match. * * It will report which string is "greater than" the other, but be aware that * this doesn't necessarily mean anything: 'a' may be "less than" 'b', but * a Japanese kuten has no meaningful alphabetically relationship to * a Greek lambda, but being able to assign a reliable "value" makes sorting * algorithms possible, if not entirely sane. Most cases should treat the * return value as "equal" or "not equal". * * Like stricmp, this expects both strings to be NULL-terminated. * * \param str1 First string to compare. * \param str2 Second string to compare. * \return -1 if str1 is "less than" str2, 1 if "greater than", 0 if equal. */ PHYSFS_DECL int PHYSFS_ucs4stricmp(const PHYSFS_uint32 *str1, const PHYSFS_uint32 *str2); /** * \typedef PHYSFS_EnumerateCallback * \brief Possible return values from PHYSFS_EnumerateCallback. * * These values dictate if an enumeration callback should continue to fire, * or stop (and why it is stopping). * * \sa PHYSFS_EnumerateCallback * \sa PHYSFS_enumerate */ typedef enum PHYSFS_EnumerateCallbackResult { PHYSFS_ENUM_ERROR = -1, /**< Stop enumerating, report error to app. */ PHYSFS_ENUM_STOP = 0, /**< Stop enumerating, report success to app. */ PHYSFS_ENUM_OK = 1 /**< Keep enumerating, no problems */ } PHYSFS_EnumerateCallbackResult; /** * \typedef PHYSFS_EnumerateCallback * \brief Function signature for callbacks that enumerate and return results. * * This is the same thing as PHYSFS_EnumFilesCallback from PhysicsFS 2.0, * except it can return a result from the callback: namely: if you're looking * for something specific, once you find it, you can tell PhysicsFS to stop * enumerating further. This is used with PHYSFS_enumerate(), which we * hopefully got right this time. :) * * \param data User-defined data pointer, passed through from the API * that eventually called the callback. * \param origdir A string containing the full path, in platform-independent * notation, of the directory containing this file. In most * cases, this is the directory on which you requested * enumeration, passed in the callback for your convenience. * \param fname The filename that is being enumerated. It may not be in * alphabetical order compared to other callbacks that have * fired, and it will not contain the full path. You can * recreate the fullpath with $origdir/$fname ... The file * can be a subdirectory, a file, a symlink, etc. * \return A value from PHYSFS_EnumerateCallbackResult. * All other values are (currently) undefined; don't use them. * * \sa PHYSFS_enumerate * \sa PHYSFS_EnumerateCallbackResult */ typedef PHYSFS_EnumerateCallbackResult (*PHYSFS_EnumerateCallback)(void *data, const char *origdir, const char *fname); /** * \fn int PHYSFS_enumerate(const char *dir, PHYSFS_EnumerateCallback c, void *d) * \brief Get a file listing of a search path's directory, using an application-defined callback, with errors reported. * * Internally, PHYSFS_enumerateFiles() just calls this function and then builds * a list before returning to the application, so functionality is identical * except for how the information is represented to the application. * * Unlike PHYSFS_enumerateFiles(), this function does not return an array. * Rather, it calls a function specified by the application once per * element of the search path: * * \code * * static PHYSFS_EnumerateCallbackResult printDir(void *data, const char *origdir, const char *fname) * { * printf(" * We've got [%s] in [%s].\n", fname, origdir); * return PHYSFS_ENUM_OK; // give me more data, please. * } * * // ... * PHYSFS_enumerate("/some/path", printDir, NULL); * \endcode * * Items sent to the callback are not guaranteed to be in any order whatsoever. * There is no sorting done at this level, and if you need that, you should * probably use PHYSFS_enumerateFiles() instead, which guarantees * alphabetical sorting. This form reports whatever is discovered in each * archive before moving on to the next. Even within one archive, we can't * guarantee what order it will discover data. <em>Any sorting you find in * these callbacks is just pure luck. Do not rely on it.</em> As this walks * the entire list of archives, you may receive duplicate filenames. * * This API and the callbacks themselves are capable of reporting errors. * Prior to this API, callbacks had to accept every enumerated item, even if * they were only looking for a specific thing and wanted to stop after that, * or had a serious error and couldn't alert anyone. Furthermore, if * PhysicsFS itself had a problem (disk error or whatnot), it couldn't report * it to the calling app, it would just have to skip items or stop * enumerating outright, and the caller wouldn't know it had lost some data * along the way. * * Now the caller can be sure it got a complete data set, and its callback has * control if it wants enumeration to stop early. See the documentation for * PHYSFS_EnumerateCallback for details on how your callback should behave. * * \param dir Directory, in platform-independent notation, to enumerate. * \param c Callback function to notify about search path elements. * \param d Application-defined data passed to callback. Can be NULL. * \return non-zero on success, zero on failure. Use * PHYSFS_getLastErrorCode() to obtain the specific error. If the * callback returns PHYSFS_ENUM_STOP to stop early, this will be * considered success. Callbacks returning PHYSFS_ENUM_ERROR will * make this function return zero and set the error code to * PHYSFS_ERR_APP_CALLBACK. * * \sa PHYSFS_EnumerateCallback * \sa PHYSFS_enumerateFiles */ PHYSFS_DECL int PHYSFS_enumerate(const char *dir, PHYSFS_EnumerateCallback c, void *d); /** * \fn int PHYSFS_unmount(const char *oldDir) * \brief Remove a directory or archive from the search path. * * This is functionally equivalent to PHYSFS_removeFromSearchPath(), but that * function is deprecated to keep the vocabulary paired with PHYSFS_mount(). * * This must be a (case-sensitive) match to a dir or archive already in the * search path, specified in platform-dependent notation. * * This call will fail (and fail to remove from the path) if the element still * has files open in it. * * \warning This function wants the path to the archive or directory that was * mounted (the same string used for the "newDir" argument of * PHYSFS_addToSearchPath or any of the mount functions), not the * path where it is mounted in the tree (the "mountPoint" argument * to any of the mount functions). * * \param oldDir dir/archive to remove. * \return nonzero on success, zero on failure. Use * PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_getSearchPath * \sa PHYSFS_mount */ PHYSFS_DECL int PHYSFS_unmount(const char *oldDir); /** * \fn const PHYSFS_Allocator *PHYSFS_getAllocator(void) * \brief Discover the current allocator. * * (This is for limited, hardcore use. If you don't immediately see a need * for it, you can probably ignore this forever.) * * This function exposes the function pointers that make up the currently used * allocator. This can be useful for apps that want to access PhysicsFS's * internal, default allocation routines, as well as for external code that * wants to share the same allocator, even if the application specified their * own. * * This call is only valid between PHYSFS_init() and PHYSFS_deinit() calls; * it will return NULL if the library isn't initialized. As we can't * guarantee the state of the internal allocators unless the library is * initialized, you shouldn't use any allocator returned here after a call * to PHYSFS_deinit(). * * Do not call the returned allocator's Init() or Deinit() methods under any * circumstances. * * If you aren't immediately sure what to do with this function, you can * safely ignore it altogether. * * \return Current allocator, as set by PHYSFS_setAllocator(), or PhysicsFS's * internal, default allocator if no application defined allocator * is currently set. Will return NULL if the library is not * initialized. * * \sa PHYSFS_Allocator * \sa PHYSFS_setAllocator */ PHYSFS_DECL const PHYSFS_Allocator *PHYSFS_getAllocator(void); /** * \enum PHYSFS_FileType * \brief Type of a File * * Possible types of a file. * * \sa PHYSFS_stat */ typedef enum PHYSFS_FileType { PHYSFS_FILETYPE_REGULAR, /**< a normal file */ PHYSFS_FILETYPE_DIRECTORY, /**< a directory */ PHYSFS_FILETYPE_SYMLINK, /**< a symlink */ PHYSFS_FILETYPE_OTHER /**< something completely different like a device */ } PHYSFS_FileType; /** * \struct PHYSFS_Stat * \brief Meta data for a file or directory * * Container for various meta data about a file in the virtual file system. * PHYSFS_stat() uses this structure for returning the information. The time * data will be either the number of seconds since the Unix epoch (midnight, * Jan 1, 1970), or -1 if the information isn't available or applicable. * The (filesize) field is measured in bytes. * The (readonly) field tells you whether the archive thinks a file is * not writable, but tends to be only an estimate (for example, your write * dir might overlap with a .zip file, meaning you _can_ successfully open * that path for writing, as it gets created elsewhere. * * \sa PHYSFS_stat * \sa PHYSFS_FileType */ typedef struct PHYSFS_Stat { PHYSFS_sint64 filesize; /**< size in bytes, -1 for non-files and unknown */ PHYSFS_sint64 modtime; /**< last modification time */ PHYSFS_sint64 createtime; /**< like modtime, but for file creation time */ PHYSFS_sint64 accesstime; /**< like modtime, but for file access time */ PHYSFS_FileType filetype; /**< File? Directory? Symlink? */ int readonly; /**< non-zero if read only, zero if writable. */ } PHYSFS_Stat; /** * \fn int PHYSFS_stat(const char *fname, PHYSFS_Stat *stat) * \brief Get various information about a directory or a file. * * Obtain various information about a file or directory from the meta data. * * This function will never follow symbolic links. If you haven't enabled * symlinks with PHYSFS_permitSymbolicLinks(), stat'ing a symlink will be * treated like stat'ing a non-existant file. If symlinks are enabled, * stat'ing a symlink will give you information on the link itself and not * what it points to. * * \param fname filename to check, in platform-indepedent notation. * \param stat pointer to structure to fill in with data about (fname). * \return non-zero on success, zero on failure. On failure, (stat)'s * contents are undefined. * * \sa PHYSFS_Stat */ PHYSFS_DECL int PHYSFS_stat(const char *fname, PHYSFS_Stat *stat); /** * \fn void PHYSFS_utf8FromUtf16(const PHYSFS_uint16 *src, char *dst, PHYSFS_uint64 len) * \brief Convert a UTF-16 string to a UTF-8 string. * * \warning This function will not report an error if there are invalid UTF-16 * sequences in the source string. It will replace them with a '?' * character and continue on. * * UTF-16 strings are 16-bits per character (except some chars, which are * 32-bits): \c TCHAR on Windows, when building with Unicode support. Modern * Windows releases use UTF-16. Windows releases before 2000 used TCHAR, but * only handled UCS-2. UTF-16 _is_ UCS-2, except for the characters that * are 4 bytes, which aren't representable in UCS-2 at all anyhow. If you * aren't sure, you should be using UTF-16 at this point on Windows. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is double the size of the source buffer. * UTF-8 never uses more than 32-bits per character, so while it may shrink * a UTF-16 string, it may also expand it. * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UTF-8 * sequence at the end. If the buffer length is 0, this function does nothing. * * \param src Null-terminated source string in UTF-16 format. * \param dst Buffer to store converted UTF-8 string. * \param len Size, in bytes, of destination buffer. */ PHYSFS_DECL void PHYSFS_utf8FromUtf16(const PHYSFS_uint16 *src, char *dst, PHYSFS_uint64 len); /** * \fn PHYSFS_utf8ToUtf16(const char *src, PHYSFS_uint16 *dst, PHYSFS_uint64 len) * \brief Convert a UTF-8 string to a UTF-16 string. * * \warning This function will not report an error if there are invalid UTF-8 * sequences in the source string. It will replace them with a '?' * character and continue on. * * UTF-16 strings are 16-bits per character (except some chars, which are * 32-bits): \c TCHAR on Windows, when building with Unicode support. Modern * Windows releases use UTF-16. Windows releases before 2000 used TCHAR, but * only handled UCS-2. UTF-16 _is_ UCS-2, except for the characters that * are 4 bytes, which aren't representable in UCS-2 at all anyhow. If you * aren't sure, you should be using UTF-16 at this point on Windows. * * To ensure that the destination buffer is large enough for the conversion, * please allocate a buffer that is double the size of the source buffer. * UTF-8 uses from one to four bytes per character, but UTF-16 always uses * two to four, so an entirely low-ASCII string will double in size! The * UTF-16 characters that would take four bytes also take four bytes in UTF-8, * so you don't need to allocate 4x the space just in case: double will do. * * Strings that don't fit in the destination buffer will be truncated, but * will always be null-terminated and never have an incomplete UTF-16 * surrogate pair at the end. If the buffer length is 0, this function does * nothing. * * \param src Null-terminated source string in UTF-8 format. * \param dst Buffer to store converted UTF-16 string. * \param len Size, in bytes, of destination buffer. * * \sa PHYSFS_utf8ToUtf16 */ PHYSFS_DECL void PHYSFS_utf8ToUtf16(const char *src, PHYSFS_uint16 *dst, PHYSFS_uint64 len); /** * \fn PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer, PHYSFS_uint64 len) * \brief Read bytes from a PhysicsFS filehandle * * The file must be opened for reading. * * \param handle handle returned from PHYSFS_openRead(). * \param buffer buffer of at least (len) bytes to store read data into. * \param len number of bytes being read from (handle). * \return number of bytes read. This may be less than (len); this does not * signify an error, necessarily (a short read may mean EOF). * PHYSFS_getLastErrorCode() can shed light on the reason this might * be < (len), as can PHYSFS_eof(). -1 if complete failure. * * \sa PHYSFS_eof */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer, PHYSFS_uint64 len); /** * \fn PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer, PHYSFS_uint64 len) * \brief Write data to a PhysicsFS filehandle * * The file must be opened for writing. * * Please note that while (len) is an unsigned 64-bit integer, you are limited * to 63 bits (9223372036854775807 bytes), so we can return a negative value * on error. If length is greater than 0x7FFFFFFFFFFFFFFF, this function will * immediately fail. For systems without a 64-bit datatype, you are limited * to 31 bits (0x7FFFFFFF, or 2147483647 bytes). We trust most things won't * need to do multiple gigabytes of i/o in one call anyhow, but why limit * things? * * \param handle retval from PHYSFS_openWrite() or PHYSFS_openAppend(). * \param buffer buffer of (len) bytes to write to (handle). * \param len number of bytes being written to (handle). * \return number of bytes written. This may be less than (len); in the case * of an error, the system may try to write as many bytes as possible, * so an incomplete write might occur. PHYSFS_getLastErrorCode() can * shed light on the reason this might be < (len). -1 if complete * failure. */ PHYSFS_DECL PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer, PHYSFS_uint64 len); /** * \struct PHYSFS_Io * \brief An abstract i/o interface. * * \warning This is advanced, hardcore stuff. You don't need this unless you * really know what you're doing. Most apps will not need this. * * Historically, PhysicsFS provided access to the physical filesystem and * archives within that filesystem. However, sometimes you need more power * than this. Perhaps you need to provide an archive that is entirely * contained in RAM, or you need to bridge some other file i/o API to * PhysicsFS, or you need to translate the bits (perhaps you have a * a standard .zip file that's encrypted, and you need to decrypt on the fly * for the unsuspecting zip archiver). * * A PHYSFS_Io is the interface that Archivers use to get archive data. * Historically, this has mapped to file i/o to the physical filesystem, but * as of PhysicsFS 2.1, applications can provide their own i/o implementations * at runtime. * * This interface isn't necessarily a good universal fit for i/o. There are a * few requirements of note: * * - They only do blocking i/o (at least, for now). * - They need to be able to duplicate. If you have a file handle from * fopen(), you need to be able to create a unique clone of it (so we * have two handles to the same file that can both seek/read/etc without * stepping on each other). * - They need to know the size of their entire data set. * - They need to be able to seek and rewind on demand. * * ...in short, you're probably not going to write an HTTP implementation. * * Thread safety: PHYSFS_Io implementations are not guaranteed to be thread * safe in themselves. Under the hood where PhysicsFS uses them, the library * provides its own locks. If you plan to use them directly from separate * threads, you should either use mutexes to protect them, or don't use the * same PHYSFS_Io from two threads at the same time. * * \sa PHYSFS_mountIo */ typedef struct PHYSFS_Io { /** * \brief Binary compatibility information. * * This must be set to zero at this time. Future versions of this * struct will increment this field, so we know what a given * implementation supports. We'll presumably keep supporting older * versions as we offer new features, though. */ PHYSFS_uint32 version; /** * \brief Instance data for this struct. * * Each instance has a pointer associated with it that can be used to * store anything it likes. This pointer is per-instance of the stream, * so presumably it will change when calling duplicate(). This can be * deallocated during the destroy() method. */ void *opaque; /** * \brief Read more data. * * Read (len) bytes from the interface, at the current i/o position, and * store them in (buffer). The current i/o position should move ahead * by the number of bytes successfully read. * * You don't have to implement this; set it to NULL if not implemented. * This will only be used if the file is opened for reading. If set to * NULL, a default implementation that immediately reports failure will * be used. * * \param io The i/o instance to read from. * \param buf The buffer to store data into. It must be at least * (len) bytes long and can't be NULL. * \param len The number of bytes to read from the interface. * \return number of bytes read from file, 0 on EOF, -1 if complete * failure. */ PHYSFS_sint64 (*read)(struct PHYSFS_Io *io, void *buf, PHYSFS_uint64 len); /** * \brief Write more data. * * Write (len) bytes from (buffer) to the interface at the current i/o * position. The current i/o position should move ahead by the number of * bytes successfully written. * * You don't have to implement this; set it to NULL if not implemented. * This will only be used if the file is opened for writing. If set to * NULL, a default implementation that immediately reports failure will * be used. * * You are allowed to buffer; a write can succeed here and then later * fail when flushing. Note that PHYSFS_setBuffer() may be operating a * level above your i/o, so you should usually not implement your * own buffering routines. * * \param io The i/o instance to write to. * \param buffer The buffer to read data from. It must be at least * (len) bytes long and can't be NULL. * \param len The number of bytes to read from (buffer). * \return number of bytes written to file, -1 if complete failure. */ PHYSFS_sint64 (*write)(struct PHYSFS_Io *io, const void *buffer, PHYSFS_uint64 len); /** * \brief Move i/o position to a given byte offset from start. * * This method moves the i/o position, so the next read/write will * be of the byte at (offset) offset. Seeks past the end of file should * be treated as an error condition. * * \param io The i/o instance to seek. * \param offset The new byte offset for the i/o position. * \return non-zero on success, zero on error. */ int (*seek)(struct PHYSFS_Io *io, PHYSFS_uint64 offset); /** * \brief Report current i/o position. * * Return bytes offset, or -1 if you aren't able to determine. A failure * will almost certainly be fatal to further use of this stream, so you * may not leave this unimplemented. * * \param io The i/o instance to query. * \return The current byte offset for the i/o position, -1 if unknown. */ PHYSFS_sint64 (*tell)(struct PHYSFS_Io *io); /** * \brief Determine size of the i/o instance's dataset. * * Return number of bytes available in the file, or -1 if you * aren't able to determine. A failure will almost certainly be fatal * to further use of this stream, so you may not leave this unimplemented. * * \param io The i/o instance to query. * \return Total size, in bytes, of the dataset. */ PHYSFS_sint64 (*length)(struct PHYSFS_Io *io); /** * \brief Duplicate this i/o instance. * * This needs to result in a full copy of this PHYSFS_Io, that can live * completely independently. The copy needs to be able to perform all * its operations without altering the original, including either object * being destroyed separately (so, for example: they can't share a file * handle; they each need their own). * * If you can't duplicate a handle, it's legal to return NULL, but you * almost certainly need this functionality if you want to use this to * PHYSFS_Io to back an archive. * * \param io The i/o instance to duplicate. * \return A new value for a stream's (opaque) field, or NULL on error. */ struct PHYSFS_Io *(*duplicate)(struct PHYSFS_Io *io); /** * \brief Flush resources to media, or wherever. * * This is the chance to report failure for writes that had claimed * success earlier, but still had a chance to actually fail. This method * can be NULL if flushing isn't necessary. * * This function may be called before destroy(), as it can report failure * and destroy() can not. It may be called at other times, too. * * \param io The i/o instance to flush. * \return Zero on error, non-zero on success. */ int (*flush)(struct PHYSFS_Io *io); /** * \brief Cleanup and deallocate i/o instance. * * Free associated resources, including (opaque) if applicable. * * This function must always succeed: as such, it returns void. The * system may call your flush() method before this. You may report * failure there if necessary. This method may still be called if * flush() fails, in which case you'll have to abandon unflushed data * and other failing conditions and clean up. * * Once this method is called for a given instance, the system will assume * it is unsafe to touch that instance again and will discard any * references to it. * * \param s The i/o instance to destroy. */ void (*destroy)(struct PHYSFS_Io *io); } PHYSFS_Io; /** * \fn int PHYSFS_mountIo(PHYSFS_Io *io, const char *newDir, const char *mountPoint, int appendToPath) * \brief Add an archive, built on a PHYSFS_Io, to the search path. * * \warning Unless you have some special, low-level need, you should be using * PHYSFS_mount() instead of this. * * This function operates just like PHYSFS_mount(), but takes a PHYSFS_Io * instead of a pathname. Behind the scenes, PHYSFS_mount() calls this * function with a physical-filesystem-based PHYSFS_Io. * * (newDir) must be a unique string to identify this archive. It is used * to optimize archiver selection (if you name it XXXXX.zip, we might try * the ZIP archiver first, for example, or directly choose an archiver that * can only trust the data is valid by filename extension). It doesn't * need to refer to a real file at all. If the filename extension isn't * helpful, the system will try every archiver until one works or none * of them do. This filename must be unique, as the system won't allow you * to have two archives with the same name. * * (io) must remain until the archive is unmounted. When the archive is * unmounted, the system will call (io)->destroy(io), which will give you * a chance to free your resources. * * If this function fails, (io)->destroy(io) is not called. * * \param io i/o instance for archive to add to the path. * \param newDir Filename that can represent this stream. * \param mountPoint Location in the interpolated tree that this archive * will be "mounted", in platform-independent notation. * NULL or "" is equivalent to "/". * \param appendToPath nonzero to append to search path, zero to prepend. * \return nonzero if added to path, zero on failure (bogus archive, stream * i/o issue, etc). Use PHYSFS_getLastErrorCode() to obtain * the specific error. * * \sa PHYSFS_unmount * \sa PHYSFS_getSearchPath * \sa PHYSFS_getMountPoint */ PHYSFS_DECL int PHYSFS_mountIo(PHYSFS_Io *io, const char *newDir, const char *mountPoint, int appendToPath); /** * \fn int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *), const char *newDir, const char *mountPoint, int appendToPath) * \brief Add an archive, contained in a memory buffer, to the search path. * * \warning Unless you have some special, low-level need, you should be using * PHYSFS_mount() instead of this. * * This function operates just like PHYSFS_mount(), but takes a memory buffer * instead of a pathname. This buffer contains all the data of the archive, * and is used instead of a real file in the physical filesystem. * * (newDir) must be a unique string to identify this archive. It is used * to optimize archiver selection (if you name it XXXXX.zip, we might try * the ZIP archiver first, for example, or directly choose an archiver that * can only trust the data is valid by filename extension). It doesn't * need to refer to a real file at all. If the filename extension isn't * helpful, the system will try every archiver until one works or none * of them do. This filename must be unique, as the system won't allow you * to have two archives with the same name. * * (ptr) must remain until the archive is unmounted. When the archive is * unmounted, the system will call (del)(ptr), which will notify you that * the system is done with the buffer, and give you a chance to free your * resources. (del) can be NULL, in which case the system will make no * attempt to free the buffer. * * If this function fails, (del) is not called. * * \param buf Address of the memory buffer containing the archive data. * \param len Size of memory buffer, in bytes. * \param del A callback that triggers upon unmount. Can be NULL. * \param newDir Filename that can represent this stream. * \param mountPoint Location in the interpolated tree that this archive * will be "mounted", in platform-independent notation. * NULL or "" is equivalent to "/". * \param appendToPath nonzero to append to search path, zero to prepend. * \return nonzero if added to path, zero on failure (bogus archive, etc). * Use PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_unmount * \sa PHYSFS_getSearchPath * \sa PHYSFS_getMountPoint */ PHYSFS_DECL int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *), const char *newDir, const char *mountPoint, int appendToPath); /** * \fn int PHYSFS_mountHandle(PHYSFS_File *file, const char *newDir, const char *mountPoint, int appendToPath) * \brief Add an archive, contained in a PHYSFS_File handle, to the search path. * * \warning Unless you have some special, low-level need, you should be using * PHYSFS_mount() instead of this. * * \warning Archives-in-archives may be very slow! While a PHYSFS_File can * seek even when the data is compressed, it may do so by rewinding * to the start and decompressing everything before the seek point. * Normal archive usage may do a lot of seeking behind the scenes. * As such, you might find normal archive usage extremely painful * if mounted this way. Plan accordingly: if you, say, have a * self-extracting .zip file, and want to mount something in it, * compress the contents of the inner archive and make sure the outer * .zip file doesn't compress the inner archive too. * * This function operates just like PHYSFS_mount(), but takes a PHYSFS_File * handle instead of a pathname. This handle contains all the data of the * archive, and is used instead of a real file in the physical filesystem. * The PHYSFS_File may be backed by a real file in the physical filesystem, * but isn't necessarily. The most popular use for this is likely to mount * archives stored inside other archives. * * (newDir) must be a unique string to identify this archive. It is used * to optimize archiver selection (if you name it XXXXX.zip, we might try * the ZIP archiver first, for example, or directly choose an archiver that * can only trust the data is valid by filename extension). It doesn't * need to refer to a real file at all. If the filename extension isn't * helpful, the system will try every archiver until one works or none * of them do. This filename must be unique, as the system won't allow you * to have two archives with the same name. * * (file) must remain until the archive is unmounted. When the archive is * unmounted, the system will call PHYSFS_close(file). If you need this * handle to survive, you will have to wrap this in a PHYSFS_Io and use * PHYSFS_mountIo() instead. * * If this function fails, PHYSFS_close(file) is not called. * * \param file The PHYSFS_File handle containing archive data. * \param newDir Filename that can represent this stream. * \param mountPoint Location in the interpolated tree that this archive * will be "mounted", in platform-independent notation. * NULL or "" is equivalent to "/". * \param appendToPath nonzero to append to search path, zero to prepend. * \return nonzero if added to path, zero on failure (bogus archive, etc). * Use PHYSFS_getLastErrorCode() to obtain the specific error. * * \sa PHYSFS_unmount * \sa PHYSFS_getSearchPath * \sa PHYSFS_getMountPoint */ PHYSFS_DECL int PHYSFS_mountHandle(PHYSFS_File *file, const char *newDir, const char *mountPoint, int appendToPath); /** * \enum PHYSFS_ErrorCode * \brief Values that represent specific causes of failure. * * Most of the time, you should only concern yourself with whether a given * operation failed or not, but there may be occasions where you plan to * handle a specific failure case gracefully, so we provide specific error * codes. * * Most of these errors are a little vague, and most aren't things you can * fix...if there's a permission error, for example, all you can really do * is pass that information on to the user and let them figure out how to * handle it. In most these cases, your program should only care that it * failed to accomplish its goals, and not care specifically why. * * \sa PHYSFS_getLastErrorCode * \sa PHYSFS_getErrorByCode */ typedef enum PHYSFS_ErrorCode { PHYSFS_ERR_OK, /**< Success; no error. */ PHYSFS_ERR_OTHER_ERROR, /**< Error not otherwise covered here. */ PHYSFS_ERR_OUT_OF_MEMORY, /**< Memory allocation failed. */ PHYSFS_ERR_NOT_INITIALIZED, /**< PhysicsFS is not initialized. */ PHYSFS_ERR_IS_INITIALIZED, /**< PhysicsFS is already initialized. */ PHYSFS_ERR_ARGV0_IS_NULL, /**< Needed argv[0], but it is NULL. */ PHYSFS_ERR_UNSUPPORTED, /**< Operation or feature unsupported. */ PHYSFS_ERR_PAST_EOF, /**< Attempted to access past end of file. */ PHYSFS_ERR_FILES_STILL_OPEN, /**< Files still open. */ PHYSFS_ERR_INVALID_ARGUMENT, /**< Bad parameter passed to an function. */ PHYSFS_ERR_NOT_MOUNTED, /**< Requested archive/dir not mounted. */ PHYSFS_ERR_NOT_FOUND, /**< File (or whatever) not found. */ PHYSFS_ERR_SYMLINK_FORBIDDEN,/**< Symlink seen when not permitted. */ PHYSFS_ERR_NO_WRITE_DIR, /**< No write dir has been specified. */ PHYSFS_ERR_OPEN_FOR_READING, /**< Wrote to a file opened for reading. */ PHYSFS_ERR_OPEN_FOR_WRITING, /**< Read from a file opened for writing. */ PHYSFS_ERR_NOT_A_FILE, /**< Needed a file, got a directory (etc). */ PHYSFS_ERR_READ_ONLY, /**< Wrote to a read-only filesystem. */ PHYSFS_ERR_CORRUPT, /**< Corrupted data encountered. */ PHYSFS_ERR_SYMLINK_LOOP, /**< Infinite symbolic link loop. */ PHYSFS_ERR_IO, /**< i/o error (hardware failure, etc). */ PHYSFS_ERR_PERMISSION, /**< Permission denied. */ PHYSFS_ERR_NO_SPACE, /**< No space (disk full, over quota, etc) */ PHYSFS_ERR_BAD_FILENAME, /**< Filename is bogus/insecure. */ PHYSFS_ERR_BUSY, /**< Tried to modify a file the OS needs. */ PHYSFS_ERR_DIR_NOT_EMPTY, /**< Tried to delete dir with files in it. */ PHYSFS_ERR_OS_ERROR, /**< Unspecified OS-level error. */ PHYSFS_ERR_DUPLICATE, /**< Duplicate entry. */ PHYSFS_ERR_BAD_PASSWORD, /**< Bad password. */ PHYSFS_ERR_APP_CALLBACK /**< Application callback reported error. */ } PHYSFS_ErrorCode; /** * \fn PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void) * \brief Get machine-readable error information. * * Get the last PhysicsFS error message as an integer value. This will return * PHYSFS_ERR_OK if there's been no error since the last call to this * function. Each thread has a unique error state associated with it, but * each time a new error message is set, it will overwrite the previous one * associated with that thread. It is safe to call this function at anytime, * even before PHYSFS_init(). * * PHYSFS_getLastError() and PHYSFS_getLastErrorCode() both reset the same * thread-specific error state. Calling one will wipe out the other's * data. If you need both, call PHYSFS_getLastErrorCode(), then pass that * value to PHYSFS_getErrorByCode(). * * Generally, applications should only concern themselves with whether a * given function failed; however, if you require more specifics, you can * try this function to glean information, if there's some specific problem * you're expecting and plan to handle. But with most things that involve * file systems, the best course of action is usually to give up, report the * problem to the user, and let them figure out what should be done about it. * For that, you might prefer PHYSFS_getErrorByCode() instead. * * \return Enumeration value that represents last reported error. * * \sa PHYSFS_getErrorByCode */ PHYSFS_DECL PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void); /** * \fn const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code) * \brief Get human-readable description string for a given error code. * * Get a static string, in UTF-8 format, that represents an English * description of a given error code. * * This string is guaranteed to never change (although we may add new strings * for new error codes in later versions of PhysicsFS), so you can use it * for keying a localization dictionary. * * It is safe to call this function at anytime, even before PHYSFS_init(). * * These strings are meant to be passed on directly to the user. * Generally, applications should only concern themselves with whether a * given function failed, but not care about the specifics much. * * Do not attempt to free the returned strings; they are read-only and you * don't own their memory pages. * * \param code Error code to convert to a string. * \return READ ONLY string of requested error message, NULL if this * is not a valid PhysicsFS error code. Always check for NULL if * you might be looking up an error code that didn't exist in an * earlier version of PhysicsFS. * * \sa PHYSFS_getLastErrorCode */ PHYSFS_DECL const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code); /** * \fn void PHYSFS_setErrorCode(PHYSFS_ErrorCode code) * \brief Set the current thread's error code. * * This lets you set the value that will be returned by the next call to * PHYSFS_getLastErrorCode(). This will replace any existing error code, * whether set by your application or internally by PhysicsFS. * * Error codes are stored per-thread; what you set here will not be * accessible to another thread. * * Any call into PhysicsFS may change the current error code, so any code you * set here is somewhat fragile, and thus you shouldn't build any serious * error reporting framework on this function. The primary goal of this * function is to allow PHYSFS_Io implementations to set the error state, * which generally will be passed back to your application when PhysicsFS * makes a PHYSFS_Io call that fails internally. * * This function doesn't care if the error code is a value known to PhysicsFS * or not (but PHYSFS_getErrorByCode() will return NULL for unknown values). * The value will be reported unmolested by PHYSFS_getLastErrorCode(). * * \param code Error code to become the current thread's new error state. * * \sa PHYSFS_getLastErrorCode * \sa PHYSFS_getErrorByCode */ PHYSFS_DECL void PHYSFS_setErrorCode(PHYSFS_ErrorCode code); /** * \fn const char *PHYSFS_getPrefDir(const char *org, const char *app) * \brief Get the user-and-app-specific path where files can be written. * * Helper function. * * Get the "pref dir". This is meant to be where users can write personal * files (preferences and save games, etc) that are specific to your * application. This directory is unique per user, per application. * * This function will decide the appropriate location in the native filesystem, * create the directory if necessary, and return a string in * platform-dependent notation, suitable for passing to PHYSFS_setWriteDir(). * * On Windows, this might look like: * "C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name" * * On Linux, this might look like: * "/home/bob/.local/share/My Program Name" * * On Mac OS X, this might look like: * "/Users/bob/Library/Application Support/My Program Name" * * (etc.) * * You should probably use the pref dir for your write dir, and also put it * near the beginning of your search path. Older versions of PhysicsFS * offered only PHYSFS_getUserDir() and left you to figure out where the * files should go under that tree. This finds the correct location * for whatever platform, which not only changes between operating systems, * but also versions of the same operating system. * * You specify the name of your organization (if it's not a real organization, * your name or an Internet domain you own might do) and the name of your * application. These should be proper names. * * Both the (org) and (app) strings may become part of a directory name, so * please follow these rules: * * - Try to use the same org string (including case-sensitivity) for * all your applications that use this function. * - Always use a unique app string for each one, and make sure it never * changes for an app once you've decided on it. * - Unicode characters are legal, as long as it's UTF-8 encoded, but... * - ...only use letters, numbers, and spaces. Avoid punctuation like * "Game Name 2: Bad Guy's Revenge!" ... "Game Name 2" is sufficient. * * The pointer returned by this function remains valid until you call this * function again, or call PHYSFS_deinit(). This is not necessarily a fast * call, though, so you should call this once at startup and copy the string * if you need it. * * You should assume the path returned by this function is the only safe * place to write files (and that PHYSFS_getUserDir() and PHYSFS_getBaseDir(), * while they might be writable, or even parents of the returned path, aren't * where you should be writing things). * * \param org The name of your organization. * \param app The name of your application. * \return READ ONLY string of user dir in platform-dependent notation. NULL * if there's a problem (creating directory failed, etc). * * \sa PHYSFS_getBaseDir * \sa PHYSFS_getUserDir */ PHYSFS_DECL const char *PHYSFS_getPrefDir(const char *org, const char *app); /** * \struct PHYSFS_Archiver * \brief Abstract interface to provide support for user-defined archives. * * \warning This is advanced, hardcore stuff. You don't need this unless you * really know what you're doing. Most apps will not need this. * * Historically, PhysicsFS provided a means to mount various archive file * formats, and physical directories in the native filesystem. However, * applications have been limited to the file formats provided by the * library. This interface allows an application to provide their own * archive file types. * * Conceptually, a PHYSFS_Archiver provides directory entries, while * PHYSFS_Io provides data streams for those directory entries. The most * obvious use of PHYSFS_Archiver is to provide support for an archive * file type that isn't provided by PhysicsFS directly: perhaps some * proprietary format that only your application needs to understand. * * Internally, all the built-in archive support uses this interface, so the * best examples for building a PHYSFS_Archiver is the source code to * PhysicsFS itself. * * An archiver is added to the system with PHYSFS_registerArchiver(), and then * it will be available for use automatically with PHYSFS_mount(); if a * given archive can be handled with your archiver, it will be given control * as appropriate. * * These methods deal with dir handles. You have one instance of your * archiver, and it generates a unique, opaque handle for each opened * archive in its openArchive() method. Since the lifetime of an Archiver * (not an archive) is generally the entire lifetime of the process, and it's * assumed to be a singleton, we do not provide any instance data for the * archiver itself; the app can just use some static variables if necessary. * * Symlinks should always be followed (except in stat()); PhysicsFS will * use the stat() method to check for symlinks and make a judgement on * whether to continue to call other methods based on that. * * Archivers, when necessary, should set the PhysicsFS error state with * PHYSFS_setErrorCode() before returning. PhysicsFS will pass these errors * back to the application unmolested in most cases. * * Thread safety: PHYSFS_Archiver implementations are not guaranteed to be * thread safe in themselves. PhysicsFS provides thread safety when it calls * into a given archiver inside the library, but it does not promise that * using the same PHYSFS_File from two threads at once is thread-safe; as * such, your PHYSFS_Archiver can assume that locking is handled for you * so long as the PHYSFS_Io you return from PHYSFS_open* doesn't change any * of your Archiver state, as the PHYSFS_Io won't be as aggressively * protected. * * \sa PHYSFS_registerArchiver * \sa PHYSFS_deregisterArchiver * \sa PHYSFS_supportedArchiveTypes */ typedef struct PHYSFS_Archiver { /** * \brief Binary compatibility information. * * This must be set to zero at this time. Future versions of this * struct will increment this field, so we know what a given * implementation supports. We'll presumably keep supporting older * versions as we offer new features, though. */ PHYSFS_uint32 version; /** * \brief Basic info about this archiver. * * This is used to identify your archive, and is returned in * PHYSFS_supportedArchiveTypes(). */ PHYSFS_ArchiveInfo info; /** * \brief Open an archive provided by (io). * * This is where resources are allocated and data is parsed when mounting * an archive. * (name) is a filename associated with (io), but doesn't necessarily * map to anything, let alone a real filename. This possibly- * meaningless name is in platform-dependent notation. * (forWrite) is non-zero if this is to be used for * the write directory, and zero if this is to be used for an * element of the search path. * (claimed) should be set to 1 if this is definitely an archive your * archiver implementation can handle, even if it fails. We use to * decide if we should stop trying other archivers if you fail to open * it. For example: the .zip archiver will set this to 1 for something * that's got a .zip file signature, even if it failed because the file * was also truncated. No sense in trying other archivers here, we * already tried to handle it with the appropriate implementation!. * Return NULL on failure and set (claimed) appropriately. If no archiver * opened the archive or set (claimed), PHYSFS_mount() will report * PHYSFS_ERR_UNSUPPORTED. Otherwise, it will report the error from the * archiver that claimed the data through (claimed). * Return non-NULL on success. The pointer returned will be * passed as the "opaque" parameter for later calls. */ void *(*openArchive)(PHYSFS_Io *io, const char *name, int forWrite, int *claimed); /** * \brief List all files in (dirname). * * Each file is passed to (cb), where a copy is made if appropriate, so * you can dispose of it upon return from the callback. (dirname) is in * platform-independent notation. * If you have a failure, call PHYSFS_SetErrorCode() with whatever code * seem appropriate and return PHYSFS_ENUM_ERROR. * If the callback returns PHYSFS_ENUM_ERROR, please call * PHYSFS_SetErrorCode(PHYSFS_ERR_APP_CALLBACK) and then return * PHYSFS_ENUM_ERROR as well. Don't call the callback again in any * circumstances. * If the callback returns PHYSFS_ENUM_STOP, stop enumerating and return * PHYSFS_ENUM_STOP as well. Don't call the callback again in any * circumstances. Don't set an error code in this case. * Callbacks are only supposed to return a value from * PHYSFS_EnumerateCallbackResult. Any other result has undefined * behavior. * As long as the callback returned PHYSFS_ENUM_OK and you haven't * experienced any errors of your own, keep enumerating until you're done * and then return PHYSFS_ENUM_OK without setting an error code. * * \warning PHYSFS_enumerate returns zero or non-zero (success or failure), * so be aware this function pointer returns different values! */ PHYSFS_EnumerateCallbackResult (*enumerate)(void *opaque, const char *dirname, PHYSFS_EnumerateCallback cb, const char *origdir, void *callbackdata); /** * \brief Open a file in this archive for reading. * * This filename, (fnm), is in platform-independent notation. * Fail if the file does not exist. * Returns NULL on failure, and calls PHYSFS_setErrorCode(). * Returns non-NULL on success. The pointer returned will be * passed as the "opaque" parameter for later file calls. */ PHYSFS_Io *(*openRead)(void *opaque, const char *fnm); /** * \brief Open a file in this archive for writing. * * If the file does not exist, it should be created. If it exists, * it should be truncated to zero bytes. The writing offset should * be the start of the file. * If the archive is read-only, this operation should fail. * This filename is in platform-independent notation. * Returns NULL on failure, and calls PHYSFS_setErrorCode(). * Returns non-NULL on success. The pointer returned will be * passed as the "opaque" parameter for later file calls. */ PHYSFS_Io *(*openWrite)(void *opaque, const char *filename); /** * \brief Open a file in this archive for appending. * * If the file does not exist, it should be created. The writing * offset should be the end of the file. * If the archive is read-only, this operation should fail. * This filename is in platform-independent notation. * Returns NULL on failure, and calls PHYSFS_setErrorCode(). * Returns non-NULL on success. The pointer returned will be * passed as the "opaque" parameter for later file calls. */ PHYSFS_Io *(*openAppend)(void *opaque, const char *filename); /** * \brief Delete a file or directory in the archive. * * This same call is used for both files and directories; there is not a * separate rmdir() call. Directories are only meant to be removed if * they are empty. * If the archive is read-only, this operation should fail. * * Return non-zero on success, zero on failure. * This filename is in platform-independent notation. * On failure, call PHYSFS_setErrorCode(). */ int (*remove)(void *opaque, const char *filename); /** * \brief Create a directory in the archive. * * If the application is trying to make multiple dirs, PhysicsFS * will split them up into multiple calls before passing them to * your driver. * If the archive is read-only, this operation should fail. * Return non-zero on success, zero on failure. * This filename is in platform-independent notation. * On failure, call PHYSFS_setErrorCode(). */ int (*mkdir)(void *opaque, const char *filename); /** * \brief Obtain basic file metadata. * * On success, fill in all the fields in (stat), using * reasonable defaults for fields that apply to your archive. * * Returns non-zero on success, zero on failure. * This filename is in platform-independent notation. * On failure, call PHYSFS_setErrorCode(). */ int (*stat)(void *opaque, const char *fn, PHYSFS_Stat *stat); /** * \brief Destruct a previously-opened archive. * * Close this archive, and free any associated memory, * including the original PHYSFS_Io and (opaque) itself, if * applicable. Implementation can assume that it won't be called if * there are still files open from this archive. */ void (*closeArchive)(void *opaque); } PHYSFS_Archiver; /** * \fn int PHYSFS_registerArchiver(const PHYSFS_Archiver *archiver) * \brief Add a new archiver to the system. * * \warning This is advanced, hardcore stuff. You don't need this unless you * really know what you're doing. Most apps will not need this. * * If you want to provide your own archiver (for example, a custom archive * file format, or some virtual thing you want to make look like a filesystem * that you can access through the usual PhysicsFS APIs), this is where you * start. Once an archiver is successfully registered, then you can use * PHYSFS_mount() to add archives that your archiver supports to the * search path, or perhaps use it as the write dir. Internally, PhysicsFS * uses this function to register its own built-in archivers, like .zip * support, etc. * * You may not have two archivers that handle the same extension. If you are * going to have a clash, you can deregister the other archiver (including * built-in ones) with PHYSFS_deregisterArchiver(). * * The data in (archiver) is copied; you may free this pointer when this * function returns. * * Once this function returns successfully, PhysicsFS will be able to support * archives of this type until you deregister the archiver again. * * \param archiver The archiver to register. * \return Zero on error, non-zero on success. * * \sa PHYSFS_Archiver * \sa PHYSFS_deregisterArchiver */ PHYSFS_DECL int PHYSFS_registerArchiver(const PHYSFS_Archiver *archiver); /** * \fn int PHYSFS_deregisterArchiver(const char *ext) * \brief Remove an archiver from the system. * * If for some reason, you only need your previously-registered archiver to * live for a portion of your app's lifetime, you can remove it from the * system once you're done with it through this function. * * This fails if there are any archives still open that use this archiver. * * This function can also remove internally-supplied archivers, like .zip * support or whatnot. This could be useful in some situations, like * disabling support for them outright or overriding them with your own * implementation. Once an internal archiver is disabled like this, * PhysicsFS provides no mechanism to recover them, short of calling * PHYSFS_deinit() and PHYSFS_init() again. * * PHYSFS_deinit() will automatically deregister all archivers, so you don't * need to explicitly deregister yours if you otherwise shut down cleanly. * * \param ext Filename extension that the archiver handles. * \return Zero on error, non-zero on success. * * \sa PHYSFS_Archiver * \sa PHYSFS_registerArchiver */ PHYSFS_DECL int PHYSFS_deregisterArchiver(const char *ext); /* Everything above this line is part of the PhysicsFS 2.1 API. */ /** * \fn int PHYSFS_setRoot(const char *archive, const char *subdir) * \brief Make a subdirectory of an archive its root directory. * * This lets you narrow down the accessible files in a specific archive. For * example, if you have x.zip with a file in y/z.txt, mounted to /a, if you * call PHYSFS_setRoot("x.zip", "/y"), then the call * PHYSFS_openRead("/a/z.txt") will succeed. * * You can change an archive's root at any time, altering the interpolated * file tree (depending on where paths shift, a different archive may be * providing various files). If you set the root to NULL or "/", the * archive will be treated as if no special root was set (as if the archive * was just mounted normally). * * Changing the root only affects future operations on pathnames; a file * that was opened from a path that changed due to a setRoot will not be * affected. * * Setting a new root is not limited to archives in the search path; you may * set one on the write dir, too, which might be useful if you have files * open for write and thus can't change the write dir at the moment. * * It is not an error to set a subdirectory that does not exist to be the * root of an archive; however, no files will be visible in this case. If * the missing directories end up getting created (a mkdir to the physical * filesystem, etc) then this will be reflected in the interpolated tree. * * \param archive dir/archive on which to change root. * \param subdir new subdirectory to make the root of this archive. * \return nonzero on success, zero on failure. Use * PHYSFS_getLastErrorCode() to obtain the specific error. */ PHYSFS_DECL int PHYSFS_setRoot(const char *archive, const char *subdir); /* Everything above this line is part of the PhysicsFS 3.1 API. */ #ifdef __cplusplus } #endif #endif /* !defined _INCLUDE_PHYSFS_H_ */ /* end of physfs.h ... */
42.056306
148
0.70772
[ "object", "3d" ]
a9f7073cb0836fab31c1dcc36ce4fa6afecc9cdf
2,284
h
C
2006/utils/amodeler/inc/enums.h
kevinzhwl/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
12
2015-10-05T07:11:57.000Z
2021-11-20T10:22:38.000Z
2006/utils/amodeler/inc/enums.h
HelloWangQi/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
null
null
null
2006/utils/amodeler/inc/enums.h
HelloWangQi/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
14
2015-12-04T08:42:08.000Z
2022-01-08T02:09:23.000Z
#ifndef AMODELER_INC_ENUMS_H #define AMODELER_INC_ENUMS_H /////////////////////////////////////////////////////////////////////////////// // // (C) Copyright 2002 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // DESCRIPTION: // // Some popular enums. // /////////////////////////////////////////////////////////////////////////////// #include "global.h" AMODELER_NAMESPACE_BEGIN enum BoolOperType { kBoolOperUnite, kBoolOperSubtract, kBoolOperIntersect }; enum BodyInterferenceType { kBodiesDoNotInterfere, kBodiesTouch, kBodiesInterfere }; enum PointInBodyLocation { kPointOutsideBody, kPointAtVertex, kPointOnEdge, kPointInFace, kPointInsideBody }; enum HiddenLinesDisplay { kHiddenLinesInvisible, kHiddenLinesDashed, kHiddenLinesVisible }; enum HiddenLineDrawingImprove { kNoDrawingImprove, kConnectDrawingImprove, kArcReconstructDrawingImprove }; enum TriangulationType { kGenerateTriangles, kGenerateQuadrilaterals, kGenerateTriStrips, kGenerateTriStripsPerSurface }; enum RayBodyIntersection { kRayDoesNotIntersect, kRayPointAtVertex, kRayPointOnEdge, kRayPointInFace, kRayIntersectsVertex, kRayIntersectsEdge, kRayIntersectsFace }; AMODELER_NAMESPACE_END #endif
23.546392
80
0.66944
[ "object" ]
a9fc5c3f1b4e0729c8c550f034db84e2f53ebbb2
11,735
c
C
src/thirdparty/stlsoft/pantheios/src/util/init_code_strings.c
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
44
2015-09-27T09:17:38.000Z
2022-02-10T12:58:40.000Z
src/thirdparty/stlsoft/pantheios/src/util/init_code_strings.c
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
3
2017-03-08T06:54:59.000Z
2020-07-05T05:31:50.000Z
src/thirdparty/stlsoft/pantheios/src/util/init_code_strings.c
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
16
2015-10-22T07:39:47.000Z
2022-01-08T23:46:07.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: src/util/init_code_strings.c * * Purpose: Initialisation code strings for Pantheios API * * Created: 27th September 2007 * Updated: 29th June 2016 * * Home: http://www.pantheios.org/ * * Copyright (c) 2007-2016, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the * names of any 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. * * ////////////////////////////////////////////////////////////////////// */ #include <pantheios/pantheios.h> #include <pantheios/init_codes.h> #include <pantheios/quality/contract.h> /* ///////////////////////////////////////////////////////////////////////// * namespace */ #if !defined(PANTHEIOS_NO_NAMESPACE) namespace pantheios { #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * macros */ #define pan_init_char_t_ char #define PANTHEIOS_INIT_CODE_STRING(x) x /* ///////////////////////////////////////////////////////////////////////// * API */ #ifdef PANTHEIOS_DOCUMENTATION_SKIP_SECTION struct InitCodeString #else /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */ # define InitCodeString pantheios_src_util_InitCodeString typedef struct InitCodeString InitCodeString; struct InitCodeString #endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */ { int code; /*!< The status code. */ pan_init_char_t_ const* str; /*!< The string. */ size_t len; /*!< The string length. */ }; #define INIT_ERR_STR_DECL(rc, desc) \ \ static const pan_init_char_t_ s_str##rc[] = desc; \ static const InitCodeString s_rct##rc = { rc, s_str##rc, STLSOFT_NUM_ELEMENTS(s_str##rc) - 1 } #define INIT_ERR_STR_ENTRY(rc) \ \ &s_rct##rc static pan_init_char_t_ const* pantheios_LookupCodeA_(int code, InitCodeString const** mappings, size_t cMappings, size_t* len) { /* Use Null Object (Variable) here for len, so do not need to check * elsewhere. */ size_t len_; if(NULL == len) { len = &len_; } /* Linear search. */ { size_t i; for(i = 0; i < cMappings; ++i) { if(code == mappings[i]->code) { return (*len = mappings[i]->len, mappings[i]->str); } }} return (*len = 0, PANTHEIOS_INIT_CODE_STRING("unrecognised status code")); } static pan_init_char_t_ const* pantheios_LookupInitCodeStringA_(int code, size_t* len) { INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_SUCCESS , PANTHEIOS_INIT_CODE_STRING("operation completed successfully") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_OUT_OF_MEMORY , PANTHEIOS_INIT_CODE_STRING("out of memory") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_UNSPECIFIED_EXCEPTION , PANTHEIOS_INIT_CODE_STRING("general exception") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_UNKNOWN_FAILURE , PANTHEIOS_INIT_CODE_STRING("unknown failure") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE , PANTHEIOS_INIT_CODE_STRING("unspecified failure") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_NOT_IMPLEMENTED , PANTHEIOS_INIT_CODE_STRING("feature not implemented, or not supported by host environment") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_CANNOT_CREATE_TSS_INDEX , PANTHEIOS_INIT_CODE_STRING("cannot create TSS index") ); INIT_ERR_STR_DECL(PANTHEIOS_INIT_RC_CANNOT_CREATE_THREAD , PANTHEIOS_INIT_CODE_STRING("cannot create thread") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_NO_BACKENDS_SPECIFIED , PANTHEIOS_INIT_CODE_STRING("no backends specified") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_ALL_BACKEND_INITS_FAILED , PANTHEIOS_INIT_CODE_STRING("all backends failed") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_INVALID_PROCESSID , PANTHEIOS_INIT_CODE_STRING("invalid process identifier") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_API_MUTEX_INIT_FAILED , PANTHEIOS_INIT_CODE_STRING("API mutex initialisation failed") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_INTENDED_FAILURE , PANTHEIOS_INIT_CODE_STRING("feature intentionally failed") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_INIT_PARAM_REQUIRED , PANTHEIOS_INIT_CODE_STRING("backend requires initialisation parameter") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_INIT_CONFIG_REQUIRED , PANTHEIOS_INIT_CODE_STRING("backend requires initialisation configuration information") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_INVALID_ARGUMENT , PANTHEIOS_INIT_CODE_STRING("an invalid argument was passed to the backend") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_ARGUMENT_TOO_LONG , PANTHEIOS_INIT_CODE_STRING("an argument was too long") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_ARGUMENT_OUT_OF_RANGE , PANTHEIOS_INIT_CODE_STRING("an argument was out of range") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_PERMISSION_DENIED , PANTHEIOS_INIT_CODE_STRING("permission to access a required resource was denied") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_RESOURCE_BUSY , PANTHEIOS_INIT_CODE_STRING("required resource is already is use") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_FUTURE_VERSION_REQUESTED , PANTHEIOS_INIT_CODE_STRING("a version was requested of a later version of Pantheios than was used to create the back-end") ); INIT_ERR_STR_DECL(PANTHEIOS_BE_INIT_RC_OLD_VERSION_NOT_SUPPORTED , PANTHEIOS_INIT_CODE_STRING("a version was requested of a previous version of Pantheios that is no longer supported by the back-end") ); INIT_ERR_STR_DECL(PANTHEIOS_FE_INIT_RC_INTENDED_FAILURE , PANTHEIOS_INIT_CODE_STRING("feature intentionally failed") ); INIT_ERR_STR_DECL(PANTHEIOS_FE_INIT_RC_SYSTEM_NOT_CONFIGURED , PANTHEIOS_INIT_CODE_STRING("system not configured for frontend") ); INIT_ERR_STR_DECL(PANTHEIOS_FE_INIT_RC_INIT_CONFIG_REQUIRED , PANTHEIOS_INIT_CODE_STRING("frontend requires initialisation configuration information") ); static const InitCodeString* s_strings[] = { INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_SUCCESS ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_OUT_OF_MEMORY ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_UNSPECIFIED_EXCEPTION ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_UNKNOWN_FAILURE ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_NOT_IMPLEMENTED ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_CANNOT_CREATE_TSS_INDEX ), INIT_ERR_STR_ENTRY(PANTHEIOS_INIT_RC_CANNOT_CREATE_THREAD ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_NO_BACKENDS_SPECIFIED ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_ALL_BACKEND_INITS_FAILED), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_INVALID_PROCESSID ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_API_MUTEX_INIT_FAILED ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_INTENDED_FAILURE ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_INIT_PARAM_REQUIRED ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_INIT_CONFIG_REQUIRED ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_INVALID_ARGUMENT ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_ARGUMENT_TOO_LONG ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_ARGUMENT_OUT_OF_RANGE ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_PERMISSION_DENIED ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_RESOURCE_BUSY ), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_FUTURE_VERSION_REQUESTED), INIT_ERR_STR_ENTRY(PANTHEIOS_BE_INIT_RC_OLD_VERSION_NOT_SUPPORTED), INIT_ERR_STR_ENTRY(PANTHEIOS_FE_INIT_RC_INTENDED_FAILURE ), INIT_ERR_STR_ENTRY(PANTHEIOS_FE_INIT_RC_SYSTEM_NOT_CONFIGURED ), INIT_ERR_STR_ENTRY(PANTHEIOS_FE_INIT_RC_INIT_CONFIG_REQUIRED ), }; return pantheios_LookupCodeA_(code, s_strings, STLSOFT_NUM_ELEMENTS(s_strings), len); } PANTHEIOS_CALL(pan_init_char_t_ const*) pantheios_getInitCodeString(int code) { return pantheios_LookupInitCodeStringA_((int)code, NULL); } PANTHEIOS_CALL(size_t) pantheios_getInitCodeStringLength(int code) { size_t len; return (pantheios_LookupInitCodeStringA_((int)code, &len), len); } /* deprecated */ PANTHEIOS_CALL(pan_init_char_t_ const*) pantheios_getInitErrorString(int code) { return pantheios_LookupInitCodeStringA_((int)code, NULL); } /* deprecated */ PANTHEIOS_CALL(size_t) pantheios_getInitErrorStringLength(int code) { size_t len; return (pantheios_LookupInitCodeStringA_((int)code, &len), len); } /* ///////////////////////////////////////////////////////////////////////// * namespace */ #if !defined(PANTHEIOS_NO_NAMESPACE) } /* namespace pantheios */ #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////// end of file //////////////////////////// */
54.078341
216
0.638773
[ "object" ]
a9fd37b088503fbf2b289848248aaf4381c9b8a5
6,635
h
C
arccore/src/base/arccore/base/Array3View.h
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
arccore/src/base/arccore/base/Array3View.h
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
arccore/src/base/arccore/base/Array3View.h
grospelliergilles/framework
9cb9bc9ad723e2af626267e59dd531cdb7a4df44
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* Array3View.h (C) 2000-2022 */ /* */ /* Vue d'un tableau 3D. */ /*---------------------------------------------------------------------------*/ #ifndef ARCCORE_BASE_ARRAY3VIEW_H #define ARCCORE_BASE_ARRAY3VIEW_H /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arccore/base/Array2View.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arccore { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \ingroup Collection * \brief Vue pour un tableau 3D. * * Une vue 3D peut être créée à partir d'un tableau classique (Array) * comme suit: \code UniqueArray<Int32> a(5*7*9); Array3View<Int32> view(a.unguardedBasePointer(),5,7,9); view[3][4][5] = 2; view.setItem(4,5,6, 1); // Met la valeur 1 a l'élément view[4][5][6]. \endcode Pour des raisons de performance, il est préférable d'accéder aux éléments via operator()() */ template<class DataType> class Array3View { public: constexpr Array3View(DataType* ptr,Integer dim1_size,Integer dim2_size,Integer dim3_size) : m_ptr(ptr), m_dim1_size(dim1_size), m_dim2_size(dim2_size), m_dim3_size(dim3_size), m_dim23_size(dim2_size*dim3_size) { } constexpr Array3View() : m_ptr(0), m_dim1_size(0), m_dim2_size(0), m_dim3_size(0), m_dim23_size(0) { } public: constexpr Integer dim1Size() const { return m_dim1_size; } constexpr Integer dim2Size() const { return m_dim2_size; } constexpr Integer dim3Size() const { return m_dim3_size; } constexpr Integer totalNbElement() const { return m_dim1_size*m_dim23_size; } public: constexpr Array2View<DataType> operator[](Integer i) { ARCCORE_CHECK_AT(i,m_dim1_size); return Array2View<DataType>(m_ptr + (m_dim23_size*i),m_dim2_size,m_dim3_size); } constexpr ConstArray2View<DataType> operator[](Integer i) const { ARCCORE_CHECK_AT(i,m_dim1_size); return ConstArray2View<DataType>(m_ptr + (m_dim23_size*i),m_dim2_size,m_dim3_size); } constexpr DataType item(Integer i,Integer j,Integer k) const { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); return m_ptr[(m_dim23_size*i) + m_dim3_size*j + k]; } constexpr const DataType& operator()(Integer i,Integer j,Integer k) const { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); return m_ptr[(m_dim23_size*i) + m_dim3_size*j + k]; } constexpr DataType& operator()(Integer i,Integer j,Integer k) { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); return m_ptr[(m_dim23_size*i) + m_dim3_size*j + k]; } constexpr DataType setItem(Integer i,Integer j,Integer k,const DataType& value) { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); m_ptr[(m_dim23_size*i) + m_dim3_size*j + k] = value; } public: /*! * \brief Pointeur sur la mémoire allouée. */ inline DataType* unguardedBasePointer() { return m_ptr; } private: DataType* m_ptr; Integer m_dim1_size; //!< Taille de la 1ere dimension Integer m_dim2_size; //!< Taille de la 2eme dimension Integer m_dim3_size; //!< Taille de la 3eme dimension Integer m_dim23_size; //!< dim2 * dim3 }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \ingroup Collection * \brief Vue pour un tableau 3D constant. */ template<class DataType> class ConstArray3View { public: constexpr ConstArray3View(const DataType* ptr,Integer dim1_size,Integer dim2_size,Integer dim3_size) : m_ptr(ptr), m_dim1_size(dim1_size), m_dim2_size(dim2_size), m_dim3_size(dim3_size), m_dim23_size(dim2_size*dim3_size) { } constexpr ConstArray3View() : m_ptr(0), m_dim1_size(0), m_dim2_size(0), m_dim3_size(0), m_dim23_size(0) { } public: constexpr Integer dim1Size() const { return m_dim1_size; } constexpr Integer dim2Size() const { return m_dim2_size; } constexpr Integer dim3Size() const { return m_dim3_size; } constexpr Integer totalNbElement() const { return m_dim1_size*m_dim23_size; } public: constexpr ConstArray2View<DataType> operator[](Integer i) const { ARCCORE_CHECK_AT(i,m_dim1_size); return ConstArray2View<DataType>(m_ptr + (m_dim23_size*i),m_dim2_size,m_dim3_size); } constexpr DataType item(Integer i,Integer j,Integer k) const { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); return m_ptr[(m_dim23_size*i) + m_dim3_size*j + k]; } constexpr const DataType& operator()(Integer i,Integer j,Integer k) const { ARCCORE_CHECK_AT(i,m_dim1_size); ARCCORE_CHECK_AT(j,m_dim2_size); ARCCORE_CHECK_AT(k,m_dim3_size); return m_ptr[(m_dim23_size*i) + m_dim3_size*j + k]; } public: /*! * \brief Pointeur sur la mémoire allouée. */ constexpr inline const DataType* unguardedBasePointer() const { return m_ptr; } private: const DataType* m_ptr; Integer m_dim1_size; //!< Taille de la 1ere dimension Integer m_dim2_size; //!< Taille de la 2eme dimension Integer m_dim3_size; //!< Taille de la 3eme dimension Integer m_dim23_size; //!< dim2 * dim3 }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arccore /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #endif
36.861111
102
0.563828
[ "3d" ]
a9fd71f7113b01d9f609d17a194d6a6930d1b90a
515
h
C
Code/Engine/RendererFoundation/Resources/Implementation/RenderTargetSetup_inl.h
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Code/Engine/RendererFoundation/Resources/Implementation/RenderTargetSetup_inl.h
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Code/Engine/RendererFoundation/Resources/Implementation/RenderTargetSetup_inl.h
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
1
2020-03-08T04:55:16.000Z
2020-03-08T04:55:16.000Z
#pragma once bool ezGALRenderTagetSetup::HasRenderTargets() const { return m_uiMaxRTIndex != 0xFFu; } ezUInt8 ezGALRenderTagetSetup::GetMaxRenderTargetIndex() const { return m_uiMaxRTIndex; } ezGALRenderTargetViewHandle ezGALRenderTagetSetup::GetRenderTarget( ezUInt8 uiIndex ) const { EZ_ASSERT_DEBUG( uiIndex <= m_uiMaxRTIndex, "Render target index out of range" ); return m_hRTs[uiIndex]; } ezGALRenderTargetViewHandle ezGALRenderTagetSetup::GetDepthStencilTarget() const { return m_hDSTarget; }
20.6
91
0.8
[ "render" ]
e70bb74167e768a29e54cd7c6ae7a8989c65c05a
1,205
h
C
copasi/sbml/unittests/test000099.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/sbml/unittests/test000099.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/sbml/unittests/test000099.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #ifndef TEST_000099_H__ #define TEST_000099_H__ #include <cppunit/TestFixture.h> #include <cppunit/TestSuite.h> #include <cppunit/TestResult.h> #include <cppunit/extensions/HelperMacros.h> /** * Tests for dealing with notes on different model elements */ class CDataModel; class test000099 : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test000099); CPPUNIT_TEST(test_bug1675); CPPUNIT_TEST_SUITE_END(); protected: // incorrect SBML model static const char* SBML_MODEL_BAD; // correct SBML model with same name as incorrect model static const char* SBML_MODEL_GOOD; CDataModel* pDataModel; public: void setUp(); void tearDown(); // test for bug 1675 // After an import failed, the model that was created during import should be gone void test_bug1675(); }; #endif /* TEST000099_H__ */
23.627451
84
0.749378
[ "model" ]
e716685d7c2b6c9221d47b0e2ca254ef98e118aa
2,503
h
C
Ornate_cpp/Aggregations/Ordered_tree_view.h
pkolodziej13/Ornate_cpp
9774b71b2a3a9f9a970cc236a0b49729d7369017
[ "MIT" ]
null
null
null
Ornate_cpp/Aggregations/Ordered_tree_view.h
pkolodziej13/Ornate_cpp
9774b71b2a3a9f9a970cc236a0b49729d7369017
[ "MIT" ]
null
null
null
Ornate_cpp/Aggregations/Ordered_tree_view.h
pkolodziej13/Ornate_cpp
9774b71b2a3a9f9a970cc236a0b49729d7369017
[ "MIT" ]
null
null
null
#pragma once #include <Utilities/containing_shared_ptr.h> #include "Ordered_tree.h" namespace agg { template<class Suggested> struct Ordered_tree_view { using this_type = Ordered_tree_view<Suggested>; using decayed_type = std::decay_t<Suggested>; struct Sugested_node_base { virtual uti::containing_shared_ptr<Sugested_node_base> add_child() = 0; virtual Suggested get() = 0; }; template<class T_specific, class = std::enable_if_t<std::is_convertible_v<T_specific&, Suggested>>> Ordered_tree_view(Ordered_tree<T_specific>& to_manipulate) :node_manipulator(std::make_shared<Sugested_node_concrete<T_specific>>(to_manipulate)) , object(to_manipulate.get()) { } Ordered_tree_view(uti::containing_shared_ptr<Sugested_node_base> child) :node_manipulator(child), object(child->get()) { } template<class T_specific, class = std::enable_if_t<std::is_convertible_v<T_specific&, Suggested>>> Ordered_tree_view(Ordered_tree_view<T_specific>& manipulated) : node_manipulator(std::make_shared<Sugested_node_proxy<T_specific>>(manipulated)) , object(manipulated.get()) { } Ordered_tree_view(Ordered_tree_view<Suggested>& manipulated) : node_manipulator(manipulated.node_manipulator) , object(manipulated.object) { } this_type add_child() { return this_type(node_manipulator->add_child()); } Suggested& get() { return object; }; decayed_type* operator->() { return &get(); } private: template< class Realized> struct Sugested_node_concrete :Sugested_node_base { using this_type = Sugested_node_concrete< Realized>; Sugested_node_concrete(Ordered_tree<Realized>& node) :node(node) { } virtual Suggested get() { return node.get(); } Ordered_tree<Realized>& node; uti::containing_shared_ptr<Sugested_node_base> add_child() { auto& added = node.add_child(); return std::make_shared<this_type>(added); } }; template< class Realized> struct Sugested_node_proxy :Sugested_node_base { using this_type = Sugested_node_proxy< Realized>; Sugested_node_proxy(Ordered_tree_view<Realized>& node) :node(node) { } virtual Suggested get() { return node.get(); } Ordered_tree_view<Realized> node; uti::containing_shared_ptr<Sugested_node_base> add_child() { auto added = node.add_child(); return std::make_shared<this_type>(added); } }; Suggested object; uti::containing_shared_ptr<Sugested_node_base> node_manipulator; }; }
25.540816
101
0.729125
[ "object" ]
e7170fd26b664b09e91dfffd3545dacaf0066f0e
20,848
c
C
os/arch/arm/src/tiva/tiva_gpioirq.c
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
511
2017-03-29T09:14:09.000Z
2022-03-30T23:10:29.000Z
os/arch/arm/src/tiva/tiva_gpioirq.c
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
4,673
2017-03-29T10:43:43.000Z
2022-03-31T08:33:44.000Z
os/arch/arm/src/tiva/tiva_gpioirq.c
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
642
2017-03-30T20:45:33.000Z
2022-03-24T17:07:33.000Z
/**************************************************************************** * * Copyright 2017 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /**************************************************************************** * arch/arm/src/tiva/tiva_gpioirq.c * * Copyright (C) 2009-2010, 2012, 2014-2015 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * 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 NuttX 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <tinyara/arch.h> #include <tinyara/irq.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <debug.h> #include <arch/irq.h> #include <arch/board/board.h> #include "chip.h" #include "up_internal.h" #include "up_arch.h" #include "irq/irq.h" #include "tiva_gpio.h" #ifdef CONFIG_TIVA_GPIO_IRQS /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define TIVA_NPINS 8 #define TIVA_NIRQ_PINS (TIVA_NPORTS * TIVA_NPINS) #define TIVA_GPIO_IRQ_IDX(port, pin) ((port * TIVA_NPINS) + (pin)) /**************************************************************************** * Private types ****************************************************************************/ struct gpio_handler_s { xcpt_t isr; /* Interrupt service routine entry point */ void *arg; /* The argument that accompanies the interrupt */ }; /**************************************************************************** * Private Data ****************************************************************************/ /* A table of handlers for each GPIO port interrupt */ static struct gpio_handler_s g_gpioportirqvector[TIVA_NIRQ_PINS]; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: gpioport2irq * * Description: * Translates from GPIO port to GPIO IRQ. * ****************************************************************************/ static int gpioport2irq(uint8_t port) { int irq = -1; switch (port) { #ifdef CONFIG_TIVA_GPIOA_IRQS case (GPIO_PORTA >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOA; } break; #endif #ifdef CONFIG_TIVA_GPIOB_IRQS case (GPIO_PORTB >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOB; } break; #endif #ifdef CONFIG_TIVA_GPIOC_IRQS case (GPIO_PORTC >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOC; } break; #endif #ifdef CONFIG_TIVA_GPIOD_IRQS case (GPIO_PORTD >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOD; } break; #endif #ifdef CONFIG_TIVA_GPIOE_IRQS case (GPIO_PORTE >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOE; } break; #endif #ifdef CONFIG_TIVA_GPIOF_IRQS case (GPIO_PORTF >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOF; } break; #endif #ifdef CONFIG_TIVA_GPIOG_IRQS case (GPIO_PORTG >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOG; } break; #endif #ifdef CONFIG_TIVA_GPIOH_IRQS case (GPIO_PORTH >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOH; } break; #endif #ifdef CONFIG_TIVA_GPIOJ_IRQS case (GPIO_PORTJ >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOJ; } break; #endif #ifdef CONFIG_TIVA_GPIOK_IRQS case (GPIO_PORTK >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOK; } break; #endif #ifdef CONFIG_TIVA_GPIOL_IRQS case (GPIO_PORTL >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOL; } break; #endif #ifdef CONFIG_TIVA_GPIOM_IRQS case (GPIO_PORTM >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOM; } break; #endif #ifdef CONFIG_TIVA_GPION_IRQS case (GPIO_PORTN >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPION; } break; #endif #ifdef CONFIG_TIVA_GPIOP_IRQS case (GPIO_PORTP >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOP; } break; #endif #ifdef CONFIG_TIVA_GPIOQ_IRQS case (GPIO_PORTQ >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOQ; } break; #endif #ifdef CONFIG_TIVA_GPIOR_IRQS case (GPIO_PORTR >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOR; } break; #endif #ifdef CONFIG_TIVA_GPIOS_IRQS case (GPIO_PORTS >> GPIO_PORT_SHIFT): { irq = TIVA_IRQ_GPIOS; } break; #endif } return irq; } /**************************************************************************** * Name: tiva_gpioirqstatus * * Description: * Returns raw or masked interrupt status. * ****************************************************************************/ uint32_t tiva_gpioirqstatus(uint8_t port, bool masked) { uintptr_t base = tiva_gpiobaseaddress(port); if (masked) { return getreg32(base + TIVA_GPIO_MIS_OFFSET); } else { return getreg32(base + TIVA_GPIO_RIS_OFFSET); } } /**************************************************************************** * Name: tiva_gpioirqclear * * Description: * Clears the interrupt status of the input base * ****************************************************************************/ void tiva_gpioirqclear(uint8_t port, uint32_t pinmask) { uintptr_t base = tiva_gpiobaseaddress(port); /* "The GPIOICR register is the interrupt clear register. Writing a 1 to a bit * in this register clears the corresponding interrupt edge detection logic * register. Writing a 0 has no effect." */ modifyreg32(base + TIVA_GPIO_ICR_OFFSET, 0, pinmask); } /**************************************************************************** * Name: tiva_gpioporthandler * * Description: * Handle interrupts on each enabled GPIO port * ****************************************************************************/ static int tiva_gpioporthandler(uint8_t port, void *context) { int irq = gpioport2irq(port); /* GPIO port interrupt vector */ uint32_t mis = tiva_gpioirqstatus(port, true); /* Masked Interrupt Status */ uint8_t pin; /* Pin number */ tiva_gpioirqclear(port, 0xff); llvdbg("mis=0b%08b\n", mis & 0xff); /* Now process each IRQ pending in the MIS */ if (mis != 0) { for (pin = 0; pin < TIVA_NPINS; ++pin) { if (((mis >> pin) & 1) != 0) { int index = TIVA_GPIO_IRQ_IDX(port, pin); FAR struct gpio_handler_s *handler = &g_gpioportirqvector[index]; llvdbg("port=%d pin=%d isr=%p arg=%p index=%d\n", port, pin, handler->isr, handler->arg, index); handler->isr(irq, context, handler->arg); } } } return OK; } #ifdef CONFIG_TIVA_GPIOA_IRQS static int tiva_gpioahandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTA >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOB_IRQS static int tiva_gpiobhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTB >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOC_IRQS static int tiva_gpiochandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTC >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOD_IRQS static int tiva_gpiodhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTD >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOE_IRQS static int tiva_gpioehandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTE >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOF_IRQS static int tiva_gpiofhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTF >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOG_IRQS static int tiva_gpioghandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTG >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOH_IRQS static int tiva_gpiohhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTH >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOJ_IRQS static int tiva_gpiojhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTJ >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOK_IRQS static int tiva_gpiokhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTK >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOL_IRQS static int tiva_gpiolhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTL >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOM_IRQS static int tiva_gpiomhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTM >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPION_IRQS static int tiva_gpionhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTN >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOP_IRQS static int tiva_gpiophandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTP >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOQ_IRQS static int tiva_gpioqhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTQ >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOR_IRQS static int tiva_gpiorhandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTR >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif #ifdef CONFIG_TIVA_GPIOS_IRQS static int tiva_gpioshandler(int irq, FAR void *context, FAR void *arg) { irqstate_t flags; flags = irqsave(); up_disable_irq(irq); int ret = tiva_gpioporthandler((GPIO_PORTS >> GPIO_PORT_SHIFT), context); up_enable_irq(irq); irqrestore(flags); return ret; } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: tiva_gpioirqinitialize * * Description: * Initialize all vectors to the unexpected interrupt handler * ****************************************************************************/ int tiva_gpioirqinitialize(void) { int i; /* Point all interrupt vectors to the unexpected interrupt */ for (i = 0; i < TIVA_NIRQ_PINS; ++i) { g_gpioportirqvector[i].isr = irq_unexpected_isr; g_gpioportirqvector[i].arg = NULL; } vdbg("tiva_gpioirqinitialize isr=%d/%d irq_unexpected_isr=%p\n", i, TIVA_NIRQ_PINS, irq_unexpected_isr); /* Then attach each GPIO interrupt handlers and enable corresponding GPIO * interrupts */ #ifdef CONFIG_TIVA_GPIOA_IRQS irq_attach(TIVA_IRQ_GPIOA, tiva_gpioahandler, NULL); up_enable_irq(TIVA_IRQ_GPIOA); #endif #ifdef CONFIG_TIVA_GPIOB_IRQS irq_attach(TIVA_IRQ_GPIOB, tiva_gpiobhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOB); #endif #ifdef CONFIG_TIVA_GPIOC_IRQS irq_attach(TIVA_IRQ_GPIOC, tiva_gpiochandler, NULL); up_enable_irq(TIVA_IRQ_GPIOC); #endif #ifdef CONFIG_TIVA_GPIOD_IRQS irq_attach(TIVA_IRQ_GPIOD, tiva_gpiodhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOD); #endif #ifdef CONFIG_TIVA_GPIOE_IRQS irq_attach(TIVA_IRQ_GPIOE, tiva_gpioehandler, NULL); up_enable_irq(TIVA_IRQ_GPIOE); #endif #ifdef CONFIG_TIVA_GPIOF_IRQS irq_attach(TIVA_IRQ_GPIOF, tiva_gpiofhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOF); #endif #ifdef CONFIG_TIVA_GPIOG_IRQS irq_attach(TIVA_IRQ_GPIOG, tiva_gpioghandler, NULL); up_enable_irq(TIVA_IRQ_GPIOG); #endif #ifdef CONFIG_TIVA_GPIOH_IRQS irq_attach(TIVA_IRQ_GPIOH, tiva_gpiohhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOH); #endif #ifdef CONFIG_TIVA_GPIOJ_IRQS irq_attach(TIVA_IRQ_GPIOJ, tiva_gpiojhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOJ); #endif #ifdef CONFIG_TIVA_GPIOK_IRQS irq_attach(TIVA_IRQ_GPIOK, tiva_gpiokhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOK); #endif #ifdef CONFIG_TIVA_GPIOL_IRQS irq_attach(TIVA_IRQ_GPIOL, tiva_gpiolhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOL); #endif #ifdef CONFIG_TIVA_GPIOM_IRQS irq_attach(TIVA_IRQ_GPIOM, tiva_gpiomhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOM); #endif #ifdef CONFIG_TIVA_GPION_IRQS irq_attach(TIVA_IRQ_GPION, tiva_gpionhandler, NULL); up_enable_irq(TIVA_IRQ_GPION); #endif #ifdef CONFIG_TIVA_GPIOP_IRQS irq_attach(TIVA_IRQ_GPIOP, tiva_gpiophandler, NULL); up_enable_irq(TIVA_IRQ_GPIOP); #endif #ifdef CONFIG_TIVA_GPIOQ_IRQS irq_attach(TIVA_IRQ_GPIOQ, tiva_gpioqhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOQ); #endif #ifdef CONFIG_TIVA_GPIOR_IRQS irq_attach(TIVA_IRQ_GPIOR, tiva_gpiorhandler, NULL); up_enable_irq(TIVA_IRQ_GPIOR); #endif #ifdef CONFIG_TIVA_GPIOS_IRQS irq_attach(TIVA_IRQ_GPIOS, tiva_gpioshandler, NULL); up_enable_irq(TIVA_IRQ_GPIOS); #endif return OK; } /**************************************************************************** * Name: tiva_gpioirqattach * * Description: * Attach in GPIO interrupt to the provided 'isr'. If isr==NULL, then the * irq_unexpected_isr handler is assigned and the pin's interrupt mask is * disabled to stop further interrupts. Otherwise, the new isr is linked * and the pin's interrupt mask is set. * * Returns: * Zero (OK) is returned on success. Otherwise a negated errno value is * return to indicate the nature of the failure. * ****************************************************************************/ int tiva_gpioirqattach(uint32_t pinset, xcpt_t isr, void *arg) { FAR struct gpio_handler_s *handler; irqstate_t flags; uint8_t port = (pinset & GPIO_PORT_MASK) >> GPIO_PORT_SHIFT; uint8_t pinno = (pinset & GPIO_PIN_MASK); uint8_t pin = 1 << pinno; /* Assign per-pin interrupt handlers */ if (port < TIVA_NPORTS) { flags = irqsave(); /* If the new ISR is NULL, then the ISR is being detached. * In this case, disable the ISR and direct any interrupts * to the unexpected interrupt handler. */ vdbg("assign port=%d pin=%d function=%p to idx=%d\n", port, pinno, isr, TIVA_GPIO_IRQ_IDX(port, pinno)); handler = &g_gpioportirqvector[TIVA_GPIO_IRQ_IDX(port, pinno)]; if (isr == NULL) { tiva_gpioirqdisable(port, pin); handler->isr = irq_unexpected_isr; handler->arg = NULL; } else { handler->isr = isr; handler->arg = arg; tiva_gpioirqenable(port, pin); } irqrestore(flags); } return OK; } /**************************************************************************** * Name: tiva_gpioportirqattach * * Description: * Attach 'isr' to the GPIO port. Only use this if you want to handle * the entire ports interrupts explicitly. * ****************************************************************************/ void tiva_gpioportirqattach(uint8_t port, xcpt_t isr) { irqstate_t flags; int irq = gpioport2irq(port); /* assign port interrupt handler */ if (port < TIVA_NPORTS) { flags = irqsave(); /* If the new ISR is NULL, then the ISR is being detached. * In this case, disable the ISR and direct any interrupts * to the unexpected interrupt handler. */ vdbg("assign function=%p to port=%d\n", isr, port); if (isr == NULL) { tiva_gpioirqdisable(port, 0xff); irq_attach(irq, irq_unexpected_isr, NULL); } else { irq_attach(irq, isr, NULL); tiva_gpioirqenable(port, 0xff); } irqrestore(flags); } } /**************************************************************************** * Name: tiva_gpioirqenable * * Description: * Enable the GPIO port IRQ * ****************************************************************************/ void tiva_gpioirqenable(uint8_t port, uint8_t pin) { uintptr_t base = tiva_gpiobaseaddress(port); /* Enable the GPIO interrupt. "The GPIO IM register is the interrupt * mask register. Bits set to High in GPIO IM allow the corresponding * pins to trigger their individual interrupts and the combined GPIO INTR * line. Clearing a bit disables interrupt triggering on that pin. All * bits are cleared by a reset. */ modifyreg32(base + TIVA_GPIO_IM_OFFSET, 0, pin); } /**************************************************************************** * Name: tiva_gpioirqdisable * * Description: * Disable the GPIO port IRQ * ****************************************************************************/ void tiva_gpioirqdisable(uint8_t port, uint8_t pin) { uintptr_t base = tiva_gpiobaseaddress(port); /* Disable the GPIO interrupt. "The GPIO IM register is the interrupt * mask register. Bits set to High in GPIO IM allow the corresponding * pins to trigger their individual interrupts and the combined GPIO INTR * line. Clearing a bit disables interrupt triggering on that pin. All * bits are cleared by a reset. */ modifyreg32(base + TIVA_GPIO_IM_OFFSET, pin, 0); } #endif /* CONFIG_TIVA_GPIO_IRQS */
26.356511
106
0.648935
[ "vector" ]
e718b7ffa325203cbe1e60609911e029bd2708a0
16,535
h
C
src/public/TracingAPI.h
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
149
2018-12-23T09:08:00.000Z
2022-02-02T09:18:38.000Z
src/public/TracingAPI.h
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
null
null
null
src/public/TracingAPI.h
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
56
2018-12-23T18:11:40.000Z
2021-11-30T13:18:17.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef js_TracingAPI_h #define js_TracingAPI_h #include "js/AllocPolicy.h" #include "js/HashTable.h" #include "js/HeapAPI.h" #include "js/TraceKind.h" class JS_PUBLIC_API(JSTracer); namespace JS { class JS_PUBLIC_API(CallbackTracer); template <typename T> class Heap; template <typename T> class TenuredHeap; /** Returns a static string equivalent of |kind|. */ JS_FRIEND_API(const char*) GCTraceKindToAscii(JS::TraceKind kind); } // namespace JS enum WeakMapTraceKind { /** * Do not trace into weak map keys or values during traversal. Users must * handle weak maps manually. */ DoNotTraceWeakMaps, /** * Do true ephemeron marking with a weak key lookup marking phase. This is * the default for GCMarker. */ ExpandWeakMaps, /** * Trace through to all values, irrespective of whether the keys are live * or not. Used for non-marking tracers. */ TraceWeakMapValues, /** * Trace through to all keys and values, irrespective of whether the keys * are live or not. Used for non-marking tracers. */ TraceWeakMapKeysValues }; class JS_PUBLIC_API(JSTracer) { public: // Return the runtime set on the tracer. JSRuntime* runtime() const { return runtime_; } // Return the weak map tracing behavior currently set on this tracer. WeakMapTraceKind weakMapAction() const { return weakMapAction_; } enum class TracerKindTag { // Marking path: a tracer used only for marking liveness of cells, not // for moving them. The kind will transition to WeakMarking after // everything reachable by regular edges has been marked. Marking, // Same as Marking, except we have now moved on to the "weak marking // phase", in which every marked obj/script is immediately looked up to // see if it is a weak map key (and therefore might require marking its // weak map value). WeakMarking, // A tracer that traverses the graph for the purposes of moving objects // from the nursery to the tenured area. Tenuring, // General-purpose traversal that invokes a callback on each cell. // Traversing children is the responsibility of the callback. Callback }; bool isMarkingTracer() const { return tag_ == TracerKindTag::Marking || tag_ == TracerKindTag::WeakMarking; } bool isWeakMarkingTracer() const { return tag_ == TracerKindTag::WeakMarking; } bool isTenuringTracer() const { return tag_ == TracerKindTag::Tenuring; } bool isCallbackTracer() const { return tag_ == TracerKindTag::Callback; } inline JS::CallbackTracer* asCallbackTracer(); bool traceWeakEdges() const { return traceWeakEdges_; } bool canSkipJsids() const { return canSkipJsids_; } #ifdef DEBUG bool checkEdges() { return checkEdges_; } #endif // Get the current GC number. Only call this method if |isMarkingTracer()| // is true. uint32_t gcNumberForMarking() const; protected: JSTracer(JSRuntime* rt, TracerKindTag tag, WeakMapTraceKind weakTraceKind = TraceWeakMapValues) : runtime_(rt) , weakMapAction_(weakTraceKind) #ifdef DEBUG , checkEdges_(true) #endif , tag_(tag) , traceWeakEdges_(true) , canSkipJsids_(false) {} #ifdef DEBUG // Set whether to check edges are valid in debug builds. void setCheckEdges(bool check) { checkEdges_ = check; } #endif private: JSRuntime* runtime_; WeakMapTraceKind weakMapAction_; #ifdef DEBUG bool checkEdges_; #endif protected: TracerKindTag tag_; bool traceWeakEdges_; bool canSkipJsids_; }; namespace JS { class AutoTracingName; class AutoTracingIndex; class AutoTracingCallback; class JS_PUBLIC_API(CallbackTracer) : public JSTracer { public: CallbackTracer(JSRuntime* rt, WeakMapTraceKind weakTraceKind = TraceWeakMapValues) : JSTracer(rt, JSTracer::TracerKindTag::Callback, weakTraceKind), contextName_(nullptr), contextIndex_(InvalidIndex), contextFunctor_(nullptr) {} CallbackTracer(JSContext* cx, WeakMapTraceKind weakTraceKind = TraceWeakMapValues); // Override these methods to receive notification when an edge is visited // with the type contained in the callback. The default implementation // dispatches to the fully-generic onChild implementation, so for cases that // do not care about boxing overhead and do not need the actual edges, // just override the generic onChild. virtual void onObjectEdge(JSObject** objp) { onChild(JS::GCCellPtr(*objp)); } virtual void onStringEdge(JSString** strp) { onChild(JS::GCCellPtr(*strp)); } virtual void onSymbolEdge(JS::Symbol** symp) { onChild(JS::GCCellPtr(*symp)); } #ifdef ENABLE_BIGINT virtual void onBigIntEdge(JS::BigInt** bip) { onChild(JS::GCCellPtr(*bip)); } #endif virtual void onScriptEdge(JSScript** scriptp) { onChild(JS::GCCellPtr(*scriptp)); } virtual void onShapeEdge(js::Shape** shapep) { onChild(JS::GCCellPtr(*shapep, JS::TraceKind::Shape)); } virtual void onObjectGroupEdge(js::ObjectGroup** groupp) { onChild(JS::GCCellPtr(*groupp, JS::TraceKind::ObjectGroup)); } virtual void onBaseShapeEdge(js::BaseShape** basep) { onChild(JS::GCCellPtr(*basep, JS::TraceKind::BaseShape)); } virtual void onJitCodeEdge(js::jit::JitCode** codep) { onChild(JS::GCCellPtr(*codep, JS::TraceKind::JitCode)); } virtual void onLazyScriptEdge(js::LazyScript** lazyp) { onChild(JS::GCCellPtr(*lazyp, JS::TraceKind::LazyScript)); } virtual void onScopeEdge(js::Scope** scopep) { onChild(JS::GCCellPtr(*scopep, JS::TraceKind::Scope)); } virtual void onRegExpSharedEdge(js::RegExpShared** sharedp) { onChild(JS::GCCellPtr(*sharedp, JS::TraceKind::RegExpShared)); } // Override this method to receive notification when a node in the GC // heap graph is visited. virtual void onChild(const JS::GCCellPtr& thing) = 0; // Access to the tracing context: // When tracing with a JS::CallbackTracer, we invoke the callback with the // edge location and the type of target. This is useful for operating on // the edge in the abstract or on the target thing, satisfying most common // use cases. However, some tracers need additional detail about the // specific edge that is being traced in order to be useful. Unfortunately, // the raw pointer to the edge that we provide is not enough information to // infer much of anything useful about that edge. // // In order to better support use cases that care in particular about edges // -- as opposed to the target thing -- tracing implementations are // responsible for providing extra context information about each edge they // trace, as it is traced. This contains, at a minimum, an edge name and, // when tracing an array, the index. Further specialization can be achived // (with some complexity), by associating a functor with the tracer so // that, when requested, the user can generate totally custom edge // descriptions. // Returns the current edge's name. It is only valid to call this when // inside the trace callback, however, the edge name will always be set. const char* contextName() const { MOZ_ASSERT(contextName_); return contextName_; } // Returns the current edge's index, if marked as part of an array of edges. // This must be called only inside the trace callback. When not tracing an // array, the value will be InvalidIndex. const static size_t InvalidIndex = size_t(-1); size_t contextIndex() const { return contextIndex_; } // Build a description of this edge in the heap graph. This call may invoke // the context functor, if set, which may inspect arbitrary areas of the // heap. On the other hand, the description provided by this method may be // substantially more accurate and useful than those provided by only the // contextName and contextIndex. void getTracingEdgeName(char* buffer, size_t bufferSize); // The trace implementation may associate a callback with one or more edges // using AutoTracingDetails. This functor is called by getTracingEdgeName // and is responsible for providing a textual representation of the // currently being traced edge. The callback has access to the full heap, // including the currently set tracing context. class ContextFunctor { public: virtual void operator()(CallbackTracer* trc, char* buf, size_t bufsize) = 0; }; #ifdef DEBUG enum class TracerKind { DoNotCare, Moving, GrayBuffering, VerifyTraceProtoAndIface, ClearEdges, UnmarkGray }; virtual TracerKind getTracerKind() const { return TracerKind::DoNotCare; } #endif // In C++, overriding a method hides all methods in the base class with // that name, not just methods with that signature. Thus, the typed edge // methods have to have distinct names to allow us to override them // individually, which is freqently useful if, for example, we only want to // process only one type of edge. void dispatchToOnEdge(JSObject** objp) { onObjectEdge(objp); } void dispatchToOnEdge(JSString** strp) { onStringEdge(strp); } void dispatchToOnEdge(JS::Symbol** symp) { onSymbolEdge(symp); } #ifdef ENABLE_BIGINT void dispatchToOnEdge(JS::BigInt** bip) { onBigIntEdge(bip); } #endif void dispatchToOnEdge(JSScript** scriptp) { onScriptEdge(scriptp); } void dispatchToOnEdge(js::Shape** shapep) { onShapeEdge(shapep); } void dispatchToOnEdge(js::ObjectGroup** groupp) { onObjectGroupEdge(groupp); } void dispatchToOnEdge(js::BaseShape** basep) { onBaseShapeEdge(basep); } void dispatchToOnEdge(js::jit::JitCode** codep) { onJitCodeEdge(codep); } void dispatchToOnEdge(js::LazyScript** lazyp) { onLazyScriptEdge(lazyp); } void dispatchToOnEdge(js::Scope** scopep) { onScopeEdge(scopep); } void dispatchToOnEdge(js::RegExpShared** sharedp) { onRegExpSharedEdge(sharedp); } protected: void setTraceWeakEdges(bool value) { traceWeakEdges_ = value; } // If this is set to false, then the tracer will skip some jsids // to improve performance. This is needed for the cycle collector. void setCanSkipJsids(bool value) { canSkipJsids_ = value; } private: friend class AutoTracingName; const char* contextName_; friend class AutoTracingIndex; size_t contextIndex_; friend class AutoTracingDetails; ContextFunctor* contextFunctor_; }; // Set the name portion of the tracer's context for the current edge. class MOZ_RAII AutoTracingName { CallbackTracer* trc_; const char* prior_; public: AutoTracingName(CallbackTracer* trc, const char* name) : trc_(trc), prior_(trc->contextName_) { MOZ_ASSERT(name); trc->contextName_ = name; } ~AutoTracingName() { MOZ_ASSERT(trc_->contextName_); trc_->contextName_ = prior_; } }; // Set the index portion of the tracer's context for the current range. class MOZ_RAII AutoTracingIndex { CallbackTracer* trc_; public: explicit AutoTracingIndex(JSTracer* trc, size_t initial = 0) : trc_(nullptr) { if (trc->isCallbackTracer()) { trc_ = trc->asCallbackTracer(); MOZ_ASSERT(trc_->contextIndex_ == CallbackTracer::InvalidIndex); trc_->contextIndex_ = initial; } } ~AutoTracingIndex() { if (trc_) { MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); trc_->contextIndex_ = CallbackTracer::InvalidIndex; } } void operator++() { if (trc_) { MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); ++trc_->contextIndex_; } } }; // Set a context callback for the trace callback to use, if it needs a detailed // edge description. class MOZ_RAII AutoTracingDetails { CallbackTracer* trc_; public: AutoTracingDetails(JSTracer* trc, CallbackTracer::ContextFunctor& func) : trc_(nullptr) { if (trc->isCallbackTracer()) { trc_ = trc->asCallbackTracer(); MOZ_ASSERT(trc_->contextFunctor_ == nullptr); trc_->contextFunctor_ = &func; } } ~AutoTracingDetails() { if (trc_) { MOZ_ASSERT(trc_->contextFunctor_); trc_->contextFunctor_ = nullptr; } } }; } // namespace JS JS::CallbackTracer* JSTracer::asCallbackTracer() { MOZ_ASSERT(isCallbackTracer()); return static_cast<JS::CallbackTracer*>(this); } namespace js { namespace gc { template <typename T> JS_PUBLIC_API(void) TraceExternalEdge(JSTracer* trc, T* thingp, const char* name); } // namespace gc } // namespace js namespace JS { // The JS::TraceEdge family of functions traces the given GC thing reference. // This performs the tracing action configured on the given JSTracer: typically // calling the JSTracer::callback or marking the thing as live. // // The argument to JS::TraceEdge is an in-out param: when the function returns, // the garbage collector might have moved the GC thing. In this case, the // reference passed to JS::TraceEdge will be updated to the thing's new // location. Callers of this method are responsible for updating any state that // is dependent on the object's address. For example, if the object's address // is used as a key in a hashtable, then the object must be removed and // re-inserted with the correct hash. // // Note that while |edgep| must never be null, it is fine for |*edgep| to be // nullptr. template <typename T> inline void TraceEdge(JSTracer* trc, JS::Heap<T>* thingp, const char* name) { MOZ_ASSERT(thingp); if (*thingp) { js::gc::TraceExternalEdge(trc, thingp->unsafeGet(), name); } } template <typename T> inline void TraceEdge(JSTracer* trc, JS::TenuredHeap<T>* thingp, const char* name) { MOZ_ASSERT(thingp); if (T ptr = thingp->unbarrieredGetPtr()) { js::gc::TraceExternalEdge(trc, &ptr, name); thingp->setPtr(ptr); } } // Edges that are always traced as part of root marking do not require // incremental barriers. This function allows for marking non-barriered // pointers, but asserts that this happens during root marking. // // Note that while |edgep| must never be null, it is fine for |*edgep| to be // nullptr. template <typename T> extern JS_PUBLIC_API(void) UnsafeTraceRoot(JSTracer* trc, T* edgep, const char* name); extern JS_PUBLIC_API(void) TraceChildren(JSTracer* trc, GCCellPtr thing); using ZoneSet = js::HashSet<Zone*, js::DefaultHasher<Zone*>, js::SystemAllocPolicy>; using CompartmentSet = js::HashSet<JS::Compartment*, js::DefaultHasher<JS::Compartment*>, js::SystemAllocPolicy>; /** * Trace every value within |compartments| that is wrapped by a * cross-compartment wrapper from a compartment that is not an element of * |compartments|. */ extern JS_PUBLIC_API(void) TraceIncomingCCWs(JSTracer* trc, const JS::CompartmentSet& compartments); } // namespace JS extern JS_PUBLIC_API(void) JS_GetTraceThingInfo(char* buf, size_t bufsize, JSTracer* trc, void* thing, JS::TraceKind kind, bool includeDetails); namespace js { // Trace an edge that is not a GC root and is not wrapped in a barriered // wrapper for some reason. // // This method does not check if |*edgep| is non-null before tracing through // it, so callers must check any nullable pointer before calling this method. template <typename T> extern JS_PUBLIC_API(void) UnsafeTraceManuallyBarrieredEdge(JSTracer* trc, T* edgep, const char* name); namespace gc { // Return true if the given edge is not live and is about to be swept. template <typename T> extern JS_PUBLIC_API(bool) EdgeNeedsSweep(JS::Heap<T>* edgep); // Not part of the public API, but declared here so we can use it in GCPolicy // which is. template <typename T> bool IsAboutToBeFinalizedUnbarriered(T* thingp); } // namespace gc } // namespace js #endif /* js_TracingAPI_h */
35.712743
113
0.695494
[ "object", "shape" ]
e719ae769d9f72cc813c0dce4b98d6395a09ba74
18,735
h
C
mainWindow/kpMainWindow.h
mikefncu/ikPaint
ee787809c5df0a1b78995962ced4ec3870cc139c
[ "BSD-2-Clause" ]
null
null
null
mainWindow/kpMainWindow.h
mikefncu/ikPaint
ee787809c5df0a1b78995962ced4ec3870cc139c
[ "BSD-2-Clause" ]
null
null
null
mainWindow/kpMainWindow.h
mikefncu/ikPaint
ee787809c5df0a1b78995962ced4ec3870cc139c
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2003-2007 Clarence Dang <dang@kde.org> Modified by Maikel Diaz <ariguanabosoft@gmail.com> Copyright (c) 2015-2018 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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. */ #ifndef KP_MAIN_WINDOW_H #define KP_MAIN_WINDOW_H #include <qmainwindow.h> #include <qurl.h> #include <kpDefs.h> #include <kpPixmapFX.h> #include <kpImage.h> #include <qaction.h> class KActionCollection; class QActionGroup; class QDragEnterEvent; class QDropEvent; class QMenu; class QMoveEvent; class QPoint; class QRect; class QSize; class QStringList; class KConfigGroup; class KFontAction; class KFontSizeAction; class KSelectAction; class KToggleAction; class KToolBar; class QPrinter; class KRecentFilesAction; class KScanDialog; class KToggleFullScreenAction; class kpColor; class kpColorCells; class kpColorToolBar; class kpCommand; class kpCommandEnvironment; class kpCommandHistory; class kpDocument; class kpDocumentEnvironment; class kpDocumentMetaInfo; class kpViewManager; class kpViewScrollableContainer; class kpImageSelectionTransparency; class kpSqueezedTextLabel; class kpTextStyle; class kpThumbnail; class kpThumbnailView; class kpTool; class kpToolEnvironment; class kpToolSelectionEnvironment; class kpToolText; class kpToolToolBar; class kpTransformDialogEnvironment; class kpZoomedView; class kpMainWindow : public QMainWindow { Q_OBJECT public: // Opens a new window with a blank document. kpMainWindow (); // Opens a new window with the document specified by <url> // or creates a blank document if <url> could not be opened. kpMainWindow (const QString &url); // Opens a new window with the document <newDoc> // (<newDoc> can be 0 although this would result in a new // window without a document at all). kpMainWindow (kpDocument *newDoc); //virtual void finalizeGUI(KXMLGUIClient *client); private: void readGeneralSettings (); void init (); void saveSettings (); public: ~kpMainWindow (); public: kpDocument *document () const; kpDocumentEnvironment *documentEnvironment (); kpViewManager *viewManager () const; kpColorToolBar *colorToolBar () const; kpColorCells *colorCells () const; kpToolToolBar *toolToolBar () const; kpCommandHistory *commandHistory () const; kpCommandEnvironment *commandEnvironment (); private: void setupActions (); void enableDocumentActions (bool enable = true); void setDocument (kpDocument *newDoc); virtual void dragEnterEvent (QDragEnterEvent *e); virtual void dropEvent (QDropEvent *e); virtual void moveEvent (QMoveEvent *e); private slots: void slotScrollViewAfterScroll (); void slotUpdateCaption (); void slotDocumentRestored (); // // ActionCollection // public: KActionCollection *actionCollection (); // // Tools // private: kpToolSelectionEnvironment *toolSelectionEnvironment (); kpToolEnvironment *toolEnvironment (); void setupToolActions (); void createToolBox (); void enableToolsDocumentActions (bool enable = true); private slots: void updateToolOptionPrevNextActionsEnabled (); void updateActionDrawOpaqueChecked (); private: void updateActionDrawOpaqueEnabled (); public: QActionGroup *toolsActionGroup (); kpTool *tool () const; bool toolHasBegunShape () const; bool toolIsASelectionTool (bool includingTextTool = true) const; bool toolIsTextTool () const; private: // Ends the current shape. If there is no shape currently being drawn, // it does nothing. // // In general, call this at the start of every kpMainWindow slot, // directly invoked by the _user_ (by activating an action or via another // way), so that: // // 1. The document contains the pixels of that shape: // // Most tools have the shape, currently being drawn, layered above the // document as a kpTempImage. In other words, the document does not // yet contain the pixels of that shape. By ending the shape, the layer // is pushed down onto the document so that it now contains those // pixels. Your slot can now safely read the document as it's now // consistent with what's on the screen. // // For example, consider the case where a line is being dragged out and // CTRL+I is pressed to invert the image, while the mouse is still held // down. The CTRL+I invert code (kpMainWindow::slotInvertColors()) must // push the line kpTempImage onto the document before the invert can // meaningfully proceed (else the invert will see the state of the document // before the line was dragged out). // // Note that selection layers are not pushed down by this method. // This is a feature, not a bug. The user would be annoyed if e.g. // slotSave() happened to push down the selection. Use // kpDocument::imageWithSelection() to get around this problem. You // should still call toolEndShape() even if a selection is active // -- this ends selection "shapes", which are actually things like // selection moves or smearing operations, rather than the selections // themselves. // // AND/OR: // // 2. The current tool is no longer in a drawing state: // // If your slot is going to bring up a new main window or modal dialog // or at least some widget that acquires mouse or keyboard focus, this // could confuse the tool if the tool is in the middle of a drawing // operation. // // Do not call this in slots not invoked by the user. For instance, // calling this method in response to an internal timer tick would be // wrong. The user's drawing operation would unexpectedly finish and // this would bewilder and irritate the user. // // TODO: Help / KolourPaint Handbook does not call this. I'm sure there // are a few other actions that don't call this but should. void toolEndShape (); public: kpImageSelectionTransparency imageSelectionTransparency () const; // The drawing background color is set to <transparency>.transparentColor() // if the <transparency> is in Transparent mode or if <forceColorChange> // is true (not the default). [x] // // If <transparency> is in Opaque mode and <forceColorChange> is false, // the background color is not changed because: // // 1. It is ignored by the selection in Opaque mode anyway. // 2. This avoids irritating the user with an unnecessary background // color change. // // The only case where you should set <forceColorChange> to true is in // kpToolImageSelectionTransparencyCommand to ensure that the state // is identical to when the command was constructed. // Later: I don't think setting it to true is ever necessary since: // // 1. The background color only counts in Transparent mode. // // 2. Any kpToolImageSelectionTransparencyCommand that switches to // Transparent mode will automatically set the background // color due to the first part of [x] anyway. // // The other fields of <transparency> are copied into the main window // as expected. void setImageSelectionTransparency (const kpImageSelectionTransparency &transparency, bool forceColorChange = false); int settingImageSelectionTransparency () const; private slots: void slotToolSelected (kpTool *tool); private: void readLastTool (); int toolNumber () const; void saveLastTool (); private: bool maybeDragScrollingMainView () const; private slots: bool slotDragScroll (const QPoint &docPoint, const QPoint &docLastPoint, int zoomLevel, bool *didSomething); bool slotEndDragScroll (); private slots: void slotBeganDocResize (); void slotContinuedDocResize (const QSize &size); void slotCancelledDocResize (); void slotEndedDocResize (const QSize &size); void slotDocResizeMessageChanged (const QString &string); private slots: void slotActionPrevToolOptionGroup1 (); void slotActionNextToolOptionGroup1 (); void slotActionPrevToolOptionGroup2 (); void slotActionNextToolOptionGroup2 (); void slotActionDrawOpaqueToggled (); void slotActionDrawColorSimilarity (); public slots: void slotToolRectSelection(); void slotToolEllipticalSelection(); void slotToolFreeFormSelection(); void slotToolText(); // // File Menu // private: void setupFileMenuActions (); void enableFileMenuDocumentActions (bool enable = true); void addRecentURL (const QString &url); private slots: void slotNew (); private: QSize defaultDocSize () const; void saveDefaultDocSize (const QSize &size); private: bool shouldOpen (); void setDocumentChoosingWindow (kpDocument *doc); private: kpDocument *openInternal (const QString &url, const QSize &fallbackDocSize, bool newDocSameNameIfNotExist); // Same as above except that it: // // 1. Assumes a default fallback document size. // 2. If the URL is successfully opened (with the special exception of // the "kolourpaint doesnotexist.png" case), it is bubbled up to the // top in the Recent Files Action. // // As a result of this behavior, this should only be called in response // to a user open request e.g. File / Open or "kolourpaint doesexist.png". // It should not be used for session restore - in that case, it does not // make sense to bubble the Recent Files list. bool open (const QString &url, bool newDocSameNameIfNotExist = false); QList<QString> askForOpenURLs(const QString &caption, bool allowMultipleURLs = true); private slots: void slotOpen (); void slotOpenRecent (const QString &url); void slotScreenshot(); void slotMakeScreenshot(); void slotProperties (); bool save (bool localOnly = false); bool slotSave (); private: QString askForSaveURL (const QString &caption, const QString &startURL, const kpImage &imageToBeSaved, const QString &startSaveOptions, const kpDocumentMetaInfo &docMetaInfo, const QString &forcedSaveOptionsGroup, bool localOnly, QString *chosenSaveOptions, bool isSavingForFirstTime, bool *allowOverwritePrompt, bool *allowLossyPrompt); private slots: bool saveAs (bool localOnly = false); bool slotSaveAs (); bool slotExport (); void slotEnableReload (); bool slotReload (); private: void sendDocumentNameToPrinter (QPrinter *printer); void sendImageToPrinter (QPrinter *printer, bool showPrinterSetupDialog); private slots: void slotPrint (); void slotPrintPreview (); void slotPrintPreviewRequest(QPrinter * printer); bool queryCloseDocument (); bool queryClose (); void closeEvent(QCloseEvent *event); void slotClose (); void slotQuit (); // // Edit Menu // private: void setupEditMenuActions (); void enableEditMenuDocumentActions (bool enable = true); public: QMenu *selectionToolRMBMenu (); private slots: void slotCut (); void slotCopy (); void slotEnablePaste (); private: QRect calcUsefulPasteRect (int imageWidth, int imageHeight); // (it is possible to paste a selection border i.e. a selection with no content) void paste (const kpAbstractSelection &sel, bool forceTopLeft = false); public: // (<forceNewTextSelection> is ignored if <text> is empty) void pasteText (const QString &text, bool forceNewTextSelection = false, const QPoint &newTextSelectionTopLeft = KP_INVALID_POINT); void pasteTextAt (const QString &text, const QPoint &point, // Allow tiny adjustment of <point> so that mouse // pointer is not exactly on top of the topLeft of // any new text selection (so that it doesn't look // weird by being on top of a resize handle just after // a paste). bool allowNewTextSelectionPointShift = false); public slots: void slotPaste (); private slots: void slotPasteInNewWindow (); public slots: void slotDelete (); void slotSelectAll (); private: void addDeselectFirstCommand (kpCommand *cmd); public slots: void slotDeselect (); private slots: void slotCopyToFile (); void slotPasteFromFile (); // // View Menu // private: void setupViewMenuActions (); bool viewMenuDocumentActionsEnabled () const; void enableViewMenuDocumentActions (bool enable = true); QRect mapToGlobal (const QRect &rect) const; QRect mapFromGlobal (const QRect &rect) const; // // View Menu - Zoom // private: void setupViewMenuZoomActions (); void enableViewMenuZoomDocumentActions (bool enable); void sendZoomListToActionZoom (); void zoomToPre (int zoomLevel); void zoomToPost (); public: void zoomTo (int zoomLevel, bool centerUnderCursor = false); void zoomToRect (const QRect &normalizedDocRect, bool accountForGrips, bool careAboutWidth, bool careAboutHeight); public slots: void slotActualSize (); void slotFitToPage (); void slotFitToWidth (); void slotFitToHeight (); public: void zoomIn (bool centerUnderCursor = false); void zoomOut (bool centerUnderCursor = false); public slots: void slotZoomIn (); void slotZoomOut (); private: void zoomAccordingToZoomAction (bool centerUnderCursor = false); private slots: void slotZoom (); // // Image Menu // private: kpTransformDialogEnvironment *transformDialogEnvironment (); bool isSelectionActive () const; bool isTextSelection () const; QString autoCropText () const; void setupImageMenuActions (); void enableImageMenuDocumentActions (bool enable = true); private slots: void slotImageMenuUpdateDueToSelection (); public: kpColor backgroundColor (bool ofSelection = false) const; void addImageOrSelectionCommand (kpCommand *cmd, bool addSelCreateCmdIfSelAvail = true, bool addSelContentCmdIfSelAvail = true); private slots: void slotResizeScale (); public slots: void slotCrop (); private slots: void slotAutoCrop (); void slotFlip (); void slotMirror (); void slotRotate (); void slotRotate270 (); void slotRotate90 (); void slotSkew (); void slotConvertToBlackAndWhite (); void slotConvertToGrayscale (); void slotInvertColors (); void slotClear (); void slotMoreEffects (); // // Colors Menu // private: void setupColorsMenuActions (); void createColorBox (); void enableColorsMenuDocumentActions (bool enable); private slots: void slotUpdateColorsAppendDeleteColumnActionEnabled (); private: bool queryCloseColors (); private slots: void slotColorsDefault (); void slotColorsReload (); bool slotColorsSave (); void slotColorsAppendColumn (); void slotColorsDeleteColumn (); // // Settings Menu // private: void setupSettingsMenuActions (); void enableSettingsMenuDocumentActions (bool enable = true); private slots: void slotFullScreen (); void slotEnableSettingsShowPath (); void slotShowPathToggled (); // // Help Menu // private slots: void slotAbout (); // // Status Bar // private: enum { StatusBarItemShapePoints, StatusBarItemShapeSize, StatusBarItemDocSize, StatusBarItemDocDepth, StatusBarItemZoom, StatusBarItemColor }; void createStatusBar (); void setStatusBarDocDepth (int depth = 0); private slots: void setStatusBarMessage (const QString &message = QString()); void setStatusBarShapePoints (const QPoint &startPoint = KP_INVALID_POINT, const QPoint &endPoint = KP_INVALID_POINT); void setStatusBarShapeSize (const QSize &size = KP_INVALID_SIZE); void setStatusBarDocSize (const QSize &size = KP_INVALID_SIZE); void setStatusBarZoom (int zoom = 0); void setStatusBarPixelColor (const QColor &color = QColor()); void recalculateStatusBarMessage (); void recalculateStatusBarShape (); void recalculateStatusBar (); // // Status Bar // private: void createGUI (); // // Text ToolBar // private: void setupTextToolBarActions (); void readAndApplyTextSettings (); public: void enableTextToolBarActions (bool enable = true); private slots: void slotTextFontFamilyChanged (); void slotTextFontSizeChanged (); void slotTextBoldChanged (); void slotTextItalicChanged (); void slotTextUnderlineChanged (); void slotTextStrikeThruChanged (); public: QToolBar *textToolBar (); bool isTextStyleBackgroundOpaque () const; kpTextStyle textStyle () const; void setTextStyle (const kpTextStyle &textStyle_); int settingTextStyle () const; private: struct kpMainWindowPrivate *d; }; #endif // KP_MAIN_WINDOW_H
28.559451
89
0.687056
[ "shape" ]
e71d383dcb176af843a1ddc4d61ac87a6e1e3f41
12,625
h
C
include/vkfw_core/gfx/vk/rt/AccelerationStructureGeometry.h
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
include/vkfw_core/gfx/vk/rt/AccelerationStructureGeometry.h
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
include/vkfw_core/gfx/vk/rt/AccelerationStructureGeometry.h
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
/** * @file AccelerationStructureGeometry.h * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2020.11.20 * * @brief Declaration of the acceleration structure geometry class. */ #pragma once #include "main.h" #include "gfx/meshes/MeshInfo.h" #include "gfx/vk/rt/BottomLevelAccelerationStructure.h" #include "gfx/vk/rt/TopLevelAccelerationStructure.h" #include "gfx/vk/rt/AccelerationStructure.h" #include "gfx/Material.h" #include "gfx/vk/memory/MemoryGroup.h" #include "core/concepts.h" #include <glm/mat4x4.hpp> #include "rt/ray_tracing_host_interface.h" #include "gfx/Texture2D.h" namespace vkfw_core::gfx { class DescriptorSetLayout; class LogicalDevice; class DeviceBuffer; class MeshInfo; class SceneMeshNode; class SubMesh; class DeviceBuffer; class PipelineBarrier; struct BufferRange; struct AccelerationStructureInfo; } namespace vkfw_core::gfx::rt { class AccelerationStructureGeometry { public: AccelerationStructureGeometry(LogicalDevice* device, std::string_view name, const std::vector<std::uint32_t>& queueFamilyIndices); ~AccelerationStructureGeometry(); void AddTriangleGeometry(const glm::mat4& transform, const MaterialInfo& materialInfo, const std::vector<std::uint32_t>& materialSBTMapping, std::size_t primitiveCount, std::size_t vertexCount, std::size_t vertexSize, DeviceBuffer* vbo, std::size_t vboOffset = 0, DeviceBuffer* ibo = nullptr, std::size_t iboOffset = 0); void AddMeshGeometry(const MeshInfo& mesh, const glm::mat4& transform); struct AccelerationStructureBufferInfo { std::size_t geometryBufferSize = 0; std::vector<std::vector<std::uint32_t>> indices; std::vector<std::vector<std::uint8_t>> vertices; std::vector<std::vector<std::uint8_t>> materials; std::vector<std::size_t> materialBufferOffsets; }; template<Vertex VertexType> void FinalizeGeometry(AccelerationStructureBufferInfo& bufferInfo); template<vkfw_core::Material MaterialType> void FinalizeMaterial(AccelerationStructureBufferInfo& bufferInfo); void FinalizeBuffer(const AccelerationStructureBufferInfo& bufferInfo, const std::vector<std::uint32_t>& materialSBTMapping); void BuildAccelerationStructure(); void AddDescriptorLayoutBindingAS(DescriptorSetLayout& layout, vk::ShaderStageFlags shaderFlags, std::uint32_t bindingAS); void AddDescriptorLayoutBindingBuffers(DescriptorSetLayout& layout, vk::ShaderStageFlags shaderFlags, std::uint32_t bindingVBO, std::uint32_t bindingIBO, std::uint32_t bindingInstanceBuffer, std::uint32_t bindingTextures); [[nodiscard]] vk::AccelerationStructureKHR GetTopLevelAccelerationStructure(vk::AccessFlags2KHR access, vk::PipelineStageFlags2KHR pipelineStages, PipelineBarrier& barrier) const; void FillGeometryInfo(std::vector<BufferRange>& vbos, std::vector<BufferRange>& ibos, BufferRange& instanceBuffer); template<vkfw_core::Material MaterialType> void FillMaterialInfo(BufferRange& materialBuffer); void FillTextureInfo(std::vector<Texture*>& textures); void CreateResourceUseBarriers(vk::AccessFlags2KHR access, vk::PipelineStageFlags2KHR pipelineStage, vk::ImageLayout newLayout, PipelineBarrier& barrier); private: struct MeshGeometryInfo { std::size_t index = 0; const MeshInfo* mesh = nullptr; glm::mat4 transform = glm::mat4{1.0f}; std::size_t vertexSize = 0; std::size_t vboOffset = 0; std::size_t vboRange = 0; std::size_t iboOffset = 0; std::size_t iboRange = 0; }; struct TriangleGeometryInfo { std::size_t index = 0; Buffer* vboBuffer; std::size_t vboOffset = 0; std::size_t vboRange = 0; Buffer* iboBuffer; std::size_t iboOffset = 0; std::size_t iboRange = 0; }; void TransferMemGroup(); [[nodiscard]] std::size_t AddBottomLevelAccelerationStructure(std::uint32_t bufferIndex, std::uint32_t sbtInstanceOffset, const glm::mat3x4& transform); void AddInstanceInfo(std::uint32_t vertexSize, std::uint32_t bufferIndex, std::uint32_t materialType, std::uint32_t materialIndex, const glm::mat4& transform, std::uint32_t indexOffset = 0); void AddMeshNodeInstance(const MeshGeometryInfo& mesh, const SceneMeshNode* node, const glm::mat4& transform, const std::vector<std::pair<std::uint32_t, std::uint32_t>>& materialMapping); void AddMeshNodeGeometry(const MeshGeometryInfo& mesh, const SceneMeshNode* node, const glm::mat4& transform, const std::vector<std::uint32_t>& materialSBTMapping); void AddSubMeshGeometry(const MeshGeometryInfo& mesh, const SubMesh& subMesh, const glm::mat4& transform, const std::vector<std::uint32_t>& materialSBTMapping); std::pair<std::uint32_t, std::uint32_t> AddMaterial(const MaterialInfo& materialInfo); /** The device to create the acceleration structures in. */ LogicalDevice* m_device; /** The structures name. */ std::string m_name; /** The queue family indices used. */ std::vector<std::uint32_t> m_queueFamilyIndices; /** The bottom level acceleration structure for the scene. */ std::vector<BottomLevelAccelerationStructure> m_BLAS; /** The transformations for the bottom level acceleration structures. */ std::vector<glm::mat3x4> m_BLASTransforms; /** The top level acceleration structure for the scene. */ TopLevelAccelerationStructure m_TLAS; /** The sampler for the materials textures. */ // Sampler m_textureSampler; /** Holds the memory for geometry and instance buffers. */ MemoryGroup m_bufferMemGroup; /** Holds the memory for textures. */ MemoryGroup m_textureMemGroup; /** Holds the information for the the meshes vertex and index buffers. */ std::vector<MeshGeometryInfo> m_meshGeometryInfos; /** The information about triangle geometries. */ std::vector<TriangleGeometryInfo> m_triangleGeometryInfos; /** An internal counter for the current geometry index. */ std::size_t m_geometryIndex = 0; /** Contains for each geometry index an index to a vbo/ibo pair. */ std::vector<std::uint32_t> m_bufferIndices; std::uint32_t m_bufferIndex = MemoryGroup::INVALID_INDEX; /** Contains for each geometry index a SBT offset */ std::vector<std::uint32_t> m_sbtInstanceOffsets; /** Contains further information about each instance like material indices. */ std::vector<InstanceDesc> m_instanceInfos; /** The offset and range of the instances buffer. */ std::size_t m_instanceBufferOffset = 0; std::size_t m_instanceBufferRange = 0; /** Holds the materials. */ std::vector<std::vector<Material>> m_materials; // std::vector<std::vector<std::uint8_t>> m_materialInfos; std::vector<Texture*> m_textures; /** The offset and range of the material buffer. */ std::vector<std::size_t> m_materialBuffersOffset; std::vector<std::size_t> m_materialBuffersRange; }; template<Vertex VertexType> void AccelerationStructureGeometry::FinalizeGeometry(AccelerationStructureBufferInfo& bufferInfo) { bufferInfo.indices.resize(m_meshGeometryInfos.size()); bufferInfo.vertices.resize(m_meshGeometryInfos.size()); for (std::size_t i_mesh = 0; i_mesh < m_meshGeometryInfos.size(); ++i_mesh) { std::vector<VertexType> vertices; auto& meshInfo = m_meshGeometryInfos[i_mesh]; meshInfo.mesh->GetVertices<VertexType>(vertices); bufferInfo.indices[i_mesh] = meshInfo.mesh->GetIndices(); bufferInfo.vertices[i_mesh].resize(byteSizeOf(vertices)); memcpy(bufferInfo.vertices[i_mesh].data(), vertices.data(), bufferInfo.vertices[i_mesh].size()); meshInfo.vertexSize = sizeof(VertexType); meshInfo.vboRange = byteSizeOf(vertices); meshInfo.vboOffset = m_device->CalculateStorageBufferAlignment(bufferInfo.geometryBufferSize); meshInfo.iboRange = byteSizeOf(bufferInfo.indices[i_mesh]); meshInfo.iboOffset = m_device->CalculateStorageBufferAlignment(meshInfo.vboOffset + meshInfo.vboRange); bufferInfo.geometryBufferSize = meshInfo.iboOffset + meshInfo.iboRange; std::vector<std::pair<std::uint32_t, std::uint32_t>> materialMapping; for (const auto& mat : meshInfo.mesh->GetMaterials()) { materialMapping.emplace_back(AddMaterial(*mat)); } AddMeshNodeInstance(meshInfo, meshInfo.mesh->GetRootNode(), meshInfo.transform, materialMapping); } m_instanceBufferRange = byteSizeOf(m_instanceInfos); m_instanceBufferOffset = m_device->CalculateStorageBufferAlignment(bufferInfo.geometryBufferSize); bufferInfo.geometryBufferSize = m_instanceBufferOffset + m_instanceBufferRange; } template<vkfw_core::Material MaterialType> void AccelerationStructureGeometry::FinalizeMaterial(AccelerationStructureBufferInfo& bufferInfo) { if (bufferInfo.materials.size() <= MaterialType::MATERIAL_ID) { bufferInfo.materials.resize(MaterialType::MATERIAL_ID + 1); m_materialBuffersRange.resize(MaterialType::MATERIAL_ID + 1, 0); m_materialBuffersOffset.resize(MaterialType::MATERIAL_ID + 1, 0); } constexpr std::size_t iType = MaterialType::MATERIAL_ID; const std::size_t materialGPUSize = MaterialType::GetGPUSize(); bufferInfo.materials[iType].resize(m_materials[iType].size() * materialGPUSize); std::size_t materialStart = 0; for (std::size_t i = 0; i < m_materials[iType].size(); ++i) { auto texturesOffset = m_textures.size(); auto materialBuffer = std::span{&bufferInfo.materials[iType][materialStart], materialGPUSize}; MaterialType::FillGPUInfo(*static_cast<const MaterialType*>(m_materials[iType][i].m_materialInfo), materialBuffer, static_cast<std::uint32_t>(texturesOffset)); m_textures.resize(texturesOffset + m_materials[iType][i].m_materialInfo->GetTextureCount()); for (std::size_t iTex = 0; iTex < m_materials[iType][i].m_materialInfo->GetTextureCount(); ++iTex) { m_textures[texturesOffset + iTex] = &m_materials[iType][i].m_textures[iTex]->GetTexture(); } // // if (m_materials[iType][i].m_diffuseTexture) { // m_materialInfos[iType][i].diffuseTextureIndex = // static_cast<std::uint32_t>(m_diffuseTextures.size()); // m_diffuseTextures.emplace_back(nullptr); // } // if (m_materials[iType][i].m_bumpMap) { // m_materialInfos[iType][i].bumpTextureIndex = static_cast<std::uint32_t>(m_bumpMaps.size()); // m_bumpMaps.emplace_back(nullptr); // } // m_materialInfos[iType][i].diffuseColor = // glm::vec4{m_materials[iType][i].m_materialInfo->m_diffuse, 1.0f}; } m_materialBuffersRange[iType] = byteSizeOf(bufferInfo.materials[iType]); } template<vkfw_core::Material MaterialType> void AccelerationStructureGeometry::FillMaterialInfo(BufferRange& materialBuffer) { materialBuffer.m_buffer = m_bufferMemGroup.GetBuffer(m_bufferIndex); materialBuffer.m_offset = m_materialBuffersOffset[MaterialType::MATERIAL_ID]; materialBuffer.m_range = m_materialBuffersRange[MaterialType::MATERIAL_ID]; } }
50.907258
118
0.648713
[ "mesh", "geometry", "vector", "transform" ]
e71dc762e23e7314b1d18e5ee8744338771d876d
4,170
c
C
testsuite/systemtest/bintools/Scheduler/tests/DSPstone/fixed_point/lms/src/lms.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
74
2015-10-22T15:34:10.000Z
2022-03-25T07:57:23.000Z
testsuite/systemtest/bintools/Scheduler/tests/DSPstone/fixed_point/lms/src/lms.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
79
2015-11-19T09:23:08.000Z
2022-01-12T14:15:16.000Z
testsuite/systemtest/bintools/Scheduler/tests/DSPstone/fixed_point/lms/src/lms.c
kanishkan/tce
430e764b4d43f46bd1dc754aeb1d5632fc742110
[ "MIT" ]
38
2015-11-17T10:12:23.000Z
2022-03-25T07:57:24.000Z
/* * benchmark program: lms.c * * benchmark suite: DSP-kernel * * description: lms - filter benchmarking * * * x(n-0) ---- x(n-1) ----- x(n-i) ----- x(n-N+1) * x(n) --->---------| 1/z|-------| 1/z|-.....-| 1/z|---- * | ----- | ------ | ------ | * h0 h1 hi hN-1 * \________ |____ _____| _________/ * \______(+)_______/ * | * |---------> y(n) * v * d(n) -------------------->(+)--------> e(n) * - * * * Notation and symbols: * x(n) - Input sample at time n. * d(n) - Desired signal at time n. * y(n) - FIR filter output at time n. * H(n) - Filter coefficient vector at time n. H={h0,h1,..,hN-1} * X(n) - Filter state variable vector at time N. * X={x(0),x(n-1),...,x(n-N+1)} * delta - Adaptation gain. * N - Number of coefficient taps in the filter. * * PROCESSING: * * True LMS Algorithm * ------------------ * Get input sample * Save input sample * Do FIR * Shift vector X * Get d(n), calculate e(n) * Update coefficients * Output y(n) * * * System equations: * * e(n) = d(n) - H(n) X(n) (FIR filter and error) * H(n+1)= H(n) + delta X(n) e(n) (Coefficient update) * * References: * "Adaptive Digital Filters and Signal Analysis", Maurice G. Bellanger * Marcel Dekker, Inc. New York and Basel * * "The DLMS Algorithm Suitable for the Pipelined Realization of Adaptive * Filters", Proc. IEEE ASSP Workshop, Academia Sinica, Beijing, 1986 * * * * reference code: target assembly * * f. verification: none * * organization: Aachen University of Technology - IS2 * DSP Tools Group * phone: +49(241)807887 * fax: +49(241)8888195 * e-mail: zivojnov@ert.rwth-aachen.de * * author: Juan Martinez Velarde * * history: 29-3-94 creation (Martinez Velarde) * 03-4-94 first revision, optimized (Martinez Velarde) * * $Author: schraut $ * $Date: 1995/01/30 07:48:50 $ * $Revision: 1.2 $ */ #include "scheduler_tester_macros.h" #define STORAGE_CLASS register #define TYPE int #define N 16 /* number of coefficient taps */ volatile TYPE init_7 = 7, init_8 = 8, init_1 = 1; void pin_down(TYPE *d, TYPE *x, TYPE *delta, TYPE *p_H, TYPE *p_X) { int f ; OUTPUT_VAR(*d); *d = init_7 ; OUTPUT_VAR(*x); *x = init_8 ; OUTPUT_VAR(*delta); *delta = init_1 ; for (f = 0 ; f < N ; f++) { OUTPUT_VAR(*p_H); *p_H++ = init_1 ; OUTPUT_VAR(*p_X); *p_X++ = init_1 ; } } int main() { static TYPE H[N] ; /* Filter Coefficient Vector */ static TYPE X[N] ; /* Filter State Variable Vector */ TYPE delta = 0; /* Adaption Gain */ TYPE d = 0; /* Desired signal */ TYPE x = 0; /* Input Sample */ TYPE y = 0; /* FIR LMS Filter Output */ STORAGE_CLASS TYPE error ; /* FIR error */ int f ; STORAGE_CLASS TYPE *p_H, *p_X, *p_X2 ; pin_down(&d,&x,&delta,&H[0],&X[0]) ; p_H = &H[N-1] ; p_X = &X[N-1] ; p_X2= &X[N-2] ; START_PROFILING; y = 0 ; /* FIR filtering and State Variable Update */ for (f = 1 ; f < N ; f++) y += *p_H-- * (*p_X-- = *p_X2--) ; /* last convolution tap, get input sample */ y += *p_H * (*p_X = x) ; /* * error as the weighted difference * between desired and calculated signal * */ error = (d - y) * delta ; for (f = 0; f < N ; f++) *p_H++ += error * *p_X++ ; /* update the coefficients */ END_PROFILING; pin_down(&d,&x,&y,&H[0],&X[0]) ; return(0) ; }
25.120482
76
0.452038
[ "vector" ]
e71f7e546bd2dc7fc3d9b05bd20c4a51e65cf01e
18,826
h
C
dnn/src/common/cv/filter.h
jonrzhang/MegEngine
94b72022156a068d3e87bceed7e1c7ae77dada16
[ "Apache-2.0" ]
3
2020-10-23T06:33:57.000Z
2020-10-23T06:34:06.000Z
dnn/src/common/cv/filter.h
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
null
null
null
dnn/src/common/cv/filter.h
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
1
2020-11-09T06:29:51.000Z
2020-11-09T06:29:51.000Z
/** * By downloading, copying, installing or using the software you agree to this license. * If you do not agree to this license, do not download, install, * copy or use the software. * * * License Agreement * For Open Source Computer Vision Library * (3-clause BSD License) * * Copyright (C) 2000-2020, Intel Corporation, all rights reserved. * Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. * Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved. * Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. * Copyright (C) 2015-2016, OpenCV Foundation, all rights reserved. * Copyright (C) 2015-2016, Itseez Inc., all rights reserved. * Copyright (C) 2019-2020, Xperience AI, all rights reserved. * Third party copyrights are property of their respective owners. * * 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 names of the copyright holders nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * This software is provided by the copyright holders and contributors "as is" and * any express or implied warranties, including, but not limited to, the implied * warranties of merchantability and fitness for a particular purpose are disclaimed. * In no event shall copyright holders or contributors be liable for any direct, * indirect, incidental, special, exemplary, or consequential damages * (including, but not limited to, procurement of substitute goods or services; * loss of use, data, or profits; or business interruption) however caused * and on any theory of liability, whether in contract, strict liability, * or tort (including negligence or otherwise) arising in any way out of * the use of this software, even if advised of the possibility of such damage. * * --------------------------------------------------------------------------- * \file dnn/src/common/cv/filter.h * * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * This file has been modified by Megvii ("Megvii Modifications"). * All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. * * --------------------------------------------------------------------------- */ #pragma once #include "src/common/cv/common.h" #include "src/common/cv/helper.h" #include "src/common/utils.h" #include <type_traits> namespace megdnn { namespace megcv { namespace filter_common { using BorderMode = param::WarpPerspective::BorderMode; /* ============================ vecOp ============================== */ /*! * \struct RowNoVec * \brief Filter a row using the kernel. */ struct RowNoVec { RowNoVec() {} /*! * \param kernel The filter kernel * \param ksize The size of the kernel */ RowNoVec(const uchar* /*kernel*/, int /*ksize*/) {} /*! * \param src The src data * \param dst The dst data * \param width The width of the src * \param cn The channel size */ int operator()(const uchar* /*src*/, uchar* /*dst*/, int /*width*/, int /*cn*/) const { return 0; } }; /*! * \struct ColumnNoVec * \brief Filter a column using the kernel. */ struct ColumnNoVec { ColumnNoVec() {} /*! * \param kernel The filter kernel * \param ksize The size of the kernel * \param bits The bits shift, Used only if the type is \c uint8_t */ ColumnNoVec(const uchar* /*kernel*/, int /*ksize*/, int /*bits*/) {} /*! * \param src The src data * \param dst The dst data * \param count The count of rows that this column kernel processed. * \param width The width of the src */ int operator()(const uchar** /*src*/, uchar* /*dst*/, int& /*count*/, int /*width*/) const { return 0; } }; /*! * \struct SymmRowSmallFilter * \brief Filter a row using the kernel, used if the kernel is symmetry. */ struct SymmRowSmallNoVec { SymmRowSmallNoVec() {} SymmRowSmallNoVec(const uchar*, int) {} int operator()(const uchar*, uchar*, int, int) const { return 0; } }; struct SymmColumnSmallNoVec { SymmColumnSmallNoVec() {} SymmColumnSmallNoVec(const uchar*, int, int) {} int operator()(const uchar**, uchar*, int&, int) const { return 0; } }; /* ============================ Filters ============================== */ class BaseRowFilter { public: BaseRowFilter() { ksize = anchor = -1; } virtual ~BaseRowFilter() {} //! the filtering operator. Must be overridden in the derived classes. The //! horizontal border interpolation is done outside of the class. virtual void operator()(const uchar* src, uchar* dst, int width, int cn) = 0; //! The size of the kernel int ksize; //! The center of the filter, e.g. gaussian blur, anchor is ksize / 2 int anchor; }; class BaseColumnFilter { public: BaseColumnFilter() { ksize = anchor = -1; } virtual ~BaseColumnFilter() {} //! the filtering operator. Must be overridden in the derived classes. The //! vertical border interpolation is done outside of the class. virtual void operator()(const uchar** src, uchar* dst, int dststep, int dstcount, int width) = 0; //! resets the internal buffers, if any virtual void reset() {} //! The size of the kernel int ksize; //! The center of the filter, e.g. gaussian blur, anchor is ksize / 2 int anchor; }; /*! * \struct RowFilter * \brief The filter of the row * \tparam ST the type of src * \tparam DT the type of dst * \tparam VecOp process the element using vectorized operator. */ template <typename ST, typename DT, class VecOp> struct RowFilter : public BaseRowFilter { RowFilter(const Mat<DT>& kernel_, int anchor_, const VecOp& vec_op_ = VecOp()) { anchor = anchor_; kernel = kernel_.clone(); ksize = kernel.cols(); vec_op = vec_op_; } void operator()(const uchar* src, uchar* dst, int width, int cn) { const DT* kx = kernel.ptr(); const ST* S; DT* D = reinterpret_cast<DT*>(dst); int i, k; i = vec_op(src, dst, width, cn); width *= cn; #if MEGCV_ENABLE_UNROLLED for (; i <= width - 4; i += 4) { S = reinterpret_cast<const ST*>(src) + i; DT f = kx[0]; DT s0 = f * S[0], s1 = f * S[1], s2 = f * S[2], s3 = f * S[3]; for (k = 1; k < ksize; k++) { S += cn; f = kx[k]; s0 += f * S[0]; s1 += f * S[1]; s2 += f * S[2]; s3 += f * S[3]; } D[i] = s0; D[i + 1] = s1; D[i + 2] = s2; D[i + 3] = s3; } #endif for (; i < width; i++) { S = reinterpret_cast<const ST*>(src) + i; DT s0 = kx[0] * S[0]; for (k = 1; k < ksize; k++) { S += cn; s0 += kx[k] * S[0]; } D[i] = s0; } } //! The kernel used in RowFilter Mat<DT> kernel; //! The vectorized operator used in RowFilter VecOp vec_op; }; template <typename ST, typename DT, class VecOp> struct SymmRowSmallFilter : public RowFilter<ST, DT, VecOp> { SymmRowSmallFilter(const Mat<DT>& kernel_, int anchor_, const VecOp& vec_op_ = VecOp()) : RowFilter<ST, DT, VecOp>(kernel_, anchor_, vec_op_) {} void operator()(const uchar* src, uchar* dst, int width, int cn) { int ksize2 = this->ksize / 2, ksize2n = ksize2 * cn; const DT* kx = this->kernel.ptr() + ksize2; DT* D = reinterpret_cast<DT*>(dst); int i = this->vec_op(src, dst, width, cn), j, k; //! The center const ST* S = reinterpret_cast<const ST*>(src) + i + ksize2n; width *= cn; if (this->ksize == 1 && kx[0] == 1) { for (; i <= width - 2; i += 2) { DT s0 = S[i], s1 = S[i + 1]; D[i] = s0; D[i + 1] = s1; } S += i; } else if (this->ksize == 3) { DT k0 = kx[0], k1 = kx[1]; for (; i <= width - 2; i += 2, S += 2) { DT s0 = S[0] * k0 + (S[-cn] + S[cn]) * k1, s1 = S[1] * k0 + (S[1 - cn] + S[1 + cn]) * k1; D[i] = s0; D[i + 1] = s1; } } else if (this->ksize == 5) { DT k0 = kx[0], k1 = kx[1], k2 = kx[2]; for (; i <= width - 2; i += 2, S += 2) { DT s0 = S[0] * k0 + (S[-cn] + S[cn]) * k1 + (S[-cn * 2] + S[cn * 2]) * k2; DT s1 = S[1] * k0 + (S[1 - cn] + S[1 + cn]) * k1 + (S[1 - cn * 2] + S[1 + cn * 2]) * k2; D[i] = s0; D[i + 1] = s1; } } for (; i < width; i++, S++) { DT s0 = kx[0] * S[0]; for (k = 1, j = cn; k <= ksize2; k++, j += cn) s0 += kx[k] * (S[j] + S[-j]); D[i] = s0; } } }; template <class CastOp, class VecOp> struct ColumnFilter : public BaseColumnFilter { typedef typename CastOp::type1 ST; typedef typename CastOp::rtype DT; ColumnFilter(const Mat<ST>& kernel_, int anchor_, const CastOp& cast_op_ = CastOp(), const VecOp& vec_op_ = VecOp()) { kernel = kernel_.clone(); anchor = anchor_; ksize = kernel.cols(); cast_op = cast_op_; vec_op = vec_op_; } void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) { const ST* ky = this->kernel.ptr(); int i = 0, k; CastOp castOp = this->cast_op; { for( ; count > 0; count--, dst += dststep, src++ ) { DT* D = (DT*)dst; i = (this->vec_op)(src, dst, count, width); #if MEGCV_ENABLE_UNROLLED for( ; i <= width - 4; i += 4 ) { ST f = ky[0]; const ST* S = (const ST*)src[0] + i; ST s0 = f*S[0], s1 = f*S[1], s2 = f*S[2], s3 = f*S[3]; for( k = 1; k < ksize; k++ ) { S = (const ST*)src[k] + i; f = ky[k]; s0 += f*S[0]; s1 += f*S[1]; s2 += f*S[2]; s3 += f*S[3]; } D[i] = castOp(s0); D[i+1] = castOp(s1); D[i+2] = castOp(s2); D[i+3] = castOp(s3); } #endif for( ; i < width; i++ ) { ST s0 = 0; for( k = 0; k < ksize; k++ ) { s0 += ky[k]* ((const ST*)src[k])[i]; } D[i] = castOp(s0); } } } } Mat<ST> kernel; CastOp cast_op; VecOp vec_op; }; template <class CastOp, class VecOp> struct SymmColumnFilter : public ColumnFilter<CastOp, VecOp> { typedef typename CastOp::type1 ST; typedef typename CastOp::rtype DT; SymmColumnFilter(const Mat<ST>& kernel_, int anchor_, const CastOp& cast_op_ = CastOp(), const VecOp& vec_op_ = VecOp()) : ColumnFilter<CastOp, VecOp>(kernel_, anchor_, cast_op_, vec_op_) { } void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) { int ksize2 = this->ksize / 2; const ST* ky = this->kernel.ptr() + ksize2; int i, k; src += ksize2; for (; count > 0; count--, dst += dststep, src++) { DT* D = (DT*)dst; i = (this->vec_op)(src, dst, count, width); #if MEGCV_ENABLE_UNROLLED for (; i <= width - 4; i += 4) { ST f = ky[0]; const ST *S = (const ST*)src[0] + i, *S2; ST s0 = f * S[0], s1 = f * S[1], s2 = f * S[2], s3 = f * S[3]; for (k = 1; k <= ksize2; k++) { S = (const ST*)src[k] + i; S2 = (const ST*)src[-k] + i; f = ky[k]; s0 += f * (S[0] + S2[0]); s1 += f * (S[1] + S2[1]); s2 += f * (S[2] + S2[2]); s3 += f * (S[3] + S2[3]); } D[i] = this->cast_op(s0); D[i + 1] = this->cast_op(s1); D[i + 2] = this->cast_op(s2); D[i + 3] = this->cast_op(s3); } #endif for (; i < width; i++) { ST s0 = ky[0] * ((const ST*)src[0])[i]; for (k = 1; k <= ksize2; k++) { s0 += ky[k] * (((const ST*)src[k])[i] + ((const ST*)src[-k])[i]); } D[i] = this->cast_op(s0); } } } }; template <class CastOp, class VecOp> struct SymmColumnSmallFilter : public SymmColumnFilter<CastOp, VecOp> { typedef typename CastOp::type1 ST; typedef typename CastOp::rtype DT; SymmColumnSmallFilter(const Mat<ST>& kernel_, int anchor_, const CastOp& cast_op_ = CastOp(), const VecOp& vec_op_ = VecOp()) : SymmColumnFilter<CastOp, VecOp>(kernel_, anchor_, cast_op_, vec_op_) { //! \warning Only process if the kernel size is 3 megdnn_assert(this->ksize == 3); } void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) { int ksize2 = this->ksize / 2; const ST* ky = this->kernel.ptr() + ksize2; int i; ST f0 = ky[0], f1 = ky[1]; src += ksize2; if (std::is_same<ST, int>::value && std::is_same<DT, uchar>::value) { (this->vec_op)(src, dst, count, width); } for (; count > 0; count--, dst += dststep, src++) { DT* D = (DT*)dst; i = (this->vec_op)(src, dst, count, width); if (count == 0) break; const ST* S0 = (const ST*)src[-1]; const ST* S1 = (const ST*)src[0]; const ST* S2 = (const ST*)src[1]; { #if MEGCV_ENABLE_UNROLLED for (; i <= width - 4; i += 4) { ST s0 = (S0[i] + S2[i]) * f1 + S1[i] * f0; ST s1 = (S0[i + 1] + S2[i + 1]) * f1 + S1[i + 1] * f0; D[i] = this->cast_op(s0); D[i + 1] = this->cast_op(s1); s0 = (S0[i + 2] + S2[i + 2]) * f1 + S1[i + 2] * f0; s1 = (S0[i + 3] + S2[i + 3]) * f1 + S1[i + 3] * f0; D[i + 2] = this->cast_op(s0); D[i + 3] = this->cast_op(s1); } #endif for (; i < width; i++) { ST s0 = (S0[i] + S2[i]) * f1 + S1[i] * f0; D[i] = this->cast_op(s0); } } } } }; /* ============================ Filter Engine ========================= */ /*! * \brief The common class for filtering the image. First filter the image using * row filter and store in buffer data, and then using column filter. * \tparam ST The image data type * \tparam FT The inner buffer data type. * * \note As for uint8_t type, we may use int to store the buffer, which calc the * product of the image and the filter kernel. */ template <typename ST, typename FT> class FilterEngine { public: FilterEngine() = default; /*! * \brief Init the filter and border. * \warning row_filter and column_filter must be non-null */ FilterEngine(BaseRowFilter* row_filter, BaseColumnFilter* column_filter, size_t ch, const ST* border_value, BorderMode bmode); //! the destructor ~FilterEngine(); //! applies filter to the the whole image. void apply(const Mat<ST>& src, Mat<ST>& dst); private: //! starts filtering of the src image. void start(const Mat<ST>& src); //! processes the next srcCount rows of the image. int proceed(const uchar* src, int srcStep, int srcCount, uchar* dst, int dstStep); //! row filter filter BaseRowFilter* m_row_filter; //! column filter filter BaseColumnFilter* m_column_filter; //! the channel of the image size_t m_ch; BorderMode m_bmode; //! the size of the kernel Size m_ksize; //! the center of kernel, e.g GuassianBlur m_anchor is (kernel_row/2, //! kernel_column/2) Point<size_t> m_anchor; //! the whole size. Size m_whole_size; //! store the border value, if sizeof(src_type) >= 4, std::vector<int> m_border_table; //! nr of border value int m_border_elem_size; //! the step of the buffer data. int m_buf_step; //! store the border value, The size is ksize.cols - 1 std::vector<uchar> m_const_border_value; //! store the total row if the border is BORDER_CONSTANT, the size is //! image_width + kernel_width - 1, which include the row and the border. std::vector<uchar> m_const_border_row; //! store the total row if the border is not BORDER_CONSTANT std::vector<uchar> m_src_row; //! store the kernel_height rows data. std::vector<uchar> m_ring_buf; //! the border left width, equal to m_anchor.x int m_left_width; //! equal to m_ksize.width() - m_left_width - 1 int m_right_width; }; } // namespace filter_common } // namespace megcv } // namespace megdnn // vim: filetype=cpp.doxygen
34.0434
89
0.513014
[ "vector" ]
e71fb5fd85378d7835e3288974fe866a415ab26e
11,147
h
C
src/db/v4/DefsV4.h
BerryTrucks/keepassb
0f3545337db72523f4c6e5b37c818b3b73bab3ae
[ "MIT" ]
3
2016-01-01T20:12:09.000Z
2021-04-25T11:28:55.000Z
src/db/v4/DefsV4.h
BerryTrucks/keepassb
0f3545337db72523f4c6e5b37c818b3b73bab3ae
[ "MIT" ]
2
2021-04-23T00:18:55.000Z
2021-04-23T00:19:53.000Z
src/db/v4/DefsV4.h
BerryTrucks/keepassb
0f3545337db72523f4c6e5b37c818b3b73bab3ae
[ "MIT" ]
3
2016-01-31T16:53:28.000Z
2021-04-17T11:02:26.000Z
/* * DefsV4.h * * Copyright (c) 2014-2016 Andrei Popleteev. * Licensed under the MIT license. */ #ifndef DEFSV4_H_ #define DEFSV4_H_ #include "db/PwDatabase.h" // KeePass2 XML tag names const QString XML_META = QString("Meta"); const QString XML_ROOT = QString("Root"); const QString XML_GROUP = QString("Group"); const QString XML_ENTRY = QString("Entry"); const QString XML_KEEPASS_FILE = QString("KeePassFile"); const QString XML_GENERATOR = QString("Generator"); const QString XML_HEADER_HASH = QString("HeaderHash"); const QString XML_DATABASE_NAME = QString("DatabaseName"); const QString XML_DATABASE_NAME_CHANGED = QString("DatabaseNameChanged"); const QString XML_DATABASE_DESCRIPTION = QString("DatabaseDescription"); const QString XML_DATABASE_DESCRIPTION_CHANGED = QString("DatabaseDescriptionChanged"); const QString XML_DEFAULT_USERNAME = QString("DefaultUserName"); const QString XML_DEFAULT_USERNAME_CHANGED = QString("DefaultUserNameChanged"); const QString XML_MAINTENANCE_HISTORY_DAYS = QString("MaintenanceHistoryDays"); const QString XML_COLOR = QString("Color"); const QString XML_MASTER_KEY_CHANGED = QString("MasterKeyChanged"); const QString XML_MASTER_KEY_CHANGE_REC = QString("MasterKeyChangeRec"); const QString XML_MASTER_KEY_CHANGE_FORCE = QString("MasterKeyChangeForce"); const QString XML_MEMORY_PROTECTION = QString("MemoryProtection"); const QString XML_MEMORY_PROTECTION_PROTECT_TITLE = QString("ProtectTitle"); const QString XML_MEMORY_PROTECTION_PROTECT_USERNAME = QString("ProtectUserName"); const QString XML_MEMORY_PROTECTION_PROTECT_PASSWORD = QString("ProtectPassword"); const QString XML_MEMORY_PROTECTION_PROTECT_URL = QString("ProtectURL"); const QString XML_MEMORY_PROTECTION_PROTECT_NOTES = QString("ProtectNotes"); const QString XML_RECYCLE_BIN_ENABLED = QString("RecycleBinEnabled"); const QString XML_RECYCLE_BIN_UUID = QString("RecycleBinUUID"); const QString XML_RECYCLE_BIN_CHANGED = QString("RecycleBinChanged"); const QString XML_ENTRY_TEMPLATES_GROUP = QString("EntryTemplatesGroup"); const QString XML_ENTRY_TEMPLATES_GROUP_CHANGED = QString("EntryTemplatesGroupChanged"); const QString XML_HISTORY_MAX_ITEMS = QString("HistoryMaxItems"); const QString XML_HISTORY_MAX_SIZE = QString("HistoryMaxSize"); const QString XML_LAST_SELECTED_GROUP = QString("LastSelectedGroup"); const QString XML_LAST_TOP_VISIBLE_GROUP = QString("LastTopVisibleGroup"); const QString XML_CUSTOM_ICONS = QString("CustomIcons"); const QString XML_CUSTOM_ICON_ITEM = QString("Icon"); const QString XML_CUSTOM_ICON_ITEM_ID = QString("UUID"); const QString XML_CUSTOM_ICON_ITEM_DATA = QString("Data"); const QString XML_BINARIES = QString("Binaries"); const QString XML_BINARY_ID = QString("ID"); const QString XML_BINARY_COMPRESSED = QString("Compressed"); const QString XML_CUSTOM_DATA = QString("CustomData"); const QString XML_CUSTOM_DATA_ITEM = QString("Item"); const QString XML_BINARY = QString("Binary"); const QString XML_TITLE = QString("Title"); const QString XML_USERNAME = QString("UserName"); const QString XML_PASSWORD = QString("Password"); const QString XML_URL = QString("URL"); const QString XML_NOTES = QString("Notes"); const QString XML_UUID = QString("UUID"); const QString XML_NAME = QString("Name"); const QString XML_ICON_ID = QString("IconID"); const QString XML_CUSTOM_ICON_UUID = QString("CustomIconUUID"); const QString XML_STRING = QString("String"); const QString XML_HISTORY = QString("History"); const QString XML_KEY = QString("Key"); const QString XML_VALUE = QString("Value"); const QString XML_PROTECTED = QString("Protected"); const QString XML_TRUE = QString("True"); // Since Qt/Cascades does not have string-to-bool (and vice versa) conversion, we need this const QString XML_FALSE = QString("False"); // Since Qt/Cascades does not have string-to-bool (and vice versa) conversion, we need this const QString XML_REF = QString("Ref"); const QString XML_IS_EXPANDED = QString("IsExpanded"); const QString XML_DEFAULT_AUTO_TYPE_SEQUENCE = QString("DefaultAutoTypeSequence"); const QString XML_ENABLE_AUTO_TYPE = QString("EnableAutoType"); const QString XML_ENABLE_SEARCHING = QString("EnableSearching"); const QString XML_LAST_TOP_VISIBLE_ENTRY = QString("LastTopVisibleEntry"); const QString XML_USAGE_COUNT = QString("UsageCount"); const QString XML_LOCATION_CHANGED_TIME = QString("LocationChanged"); const QString XML_FOREGROUND_COLOR = QString("ForegroundColor"); const QString XML_BACKGROUND_COLOR = QString("BackgroundColor"); const QString XML_OVERRIDE_URL = QString("OverrideURL"); const QString XML_TAGS = QString("Tags"); const QString XML_AUTO_TYPE = QString("AutoType"); const QString XML_AUTO_TYPE_ENABLED = QString("Enabled"); const QString XML_AUTO_TYPE_OBFUSCATION = QString("DataTransferObfuscation"); const QString XML_AUTO_TYPE_DEFAULT_SEQUENCE = QString("DefaultSequence"); const QString XML_AUTO_TYPE_ITEM = QString("Association"); const QString XML_AUTO_TYPE_WINDOW = QString("Window"); const QString XML_AUTO_TYPE_KEYSTROKE_SEQUENCE = QString("KeystrokeSequence"); const QString XML_TIMES = QString("Times"); const QString XML_LAST_MODIFICATION_TIME = QString("LastModificationTime"); const QString XML_CREATION_TIME = QString("CreationTime"); const QString XML_LAST_ACCESS_TIME = QString("LastAccessTime"); const QString XML_EXPIRY_TIME = QString("ExpiryTime"); const QString XML_EXPIRES = QString("Expires"); const QString XML_DELETED_OBJECTS = QString("DeletedObjects"); const QString XML_DELETED_OBJECT_ITEM = QString("DeletedObject"); const QString XML_DELETION_TIME = QString("DeletionTime"); // Tag names for XML-formatted key files const QString XML_KEYFILE = "KeyFile"; const QString XML_KEYFILE_META = "Meta"; const QString XML_KEYFILE_KEY = "Key"; const QString XML_KEYFILE_DATA = "Data"; /** * Common error codes for V4-related methods. */ class ErrorCodesV4 { public: enum ErrorCode { SUCCESS = PwDatabase::SUCCESS, // key transform errors KEY_TRANSFORM_INIT_ERROR = 0x20, KEY_TRANSFORM_ERROR_1 = 0x21, KEY_TRANSFORM_ERROR_2 = 0x22, KEY_TRANSFORM_ERROR_3 = 0x23, KEY_TRANSFORM_END_ERROR = 0x24, // 0x25..0x2F are reserved for future use // loading errors CANNOT_DECRYPT_DB = 0x30, CANNOT_INIT_SALSA20 = 0x31, WRONG_BLOCK_ID = 0x32, BLOCK_HASH_NON_ZERO = 0x33, BLOCK_HASH_MISMATCH = 0x34, CANNOT_REMOVE_PADDING = 0x35, // 0x36..0x3F are reserved for future use // xml parsing errors XML_PARSING_ERROR_GENERIC = 0x40, XML_DOCUMENT_PARSING_ERROR_NOT_KEEPASS = 0x41, XML_DOCUMENT_PARSING_ERROR_GENERIC = 0x42, XML_DOCUMENT_PARSING_ERROR_TAG = 0x43, XML_ROOT_PARSING_ERROR_GENERIC = 0x44, XML_ROOT_PARSING_ERROR_TAG = 0x45, XML_DELETED_OBJECTS_PARSING_ERROR_GENERIC = 0x46, XML_DELETED_OBJECTS_PARSING_ERROR_TAG = 0x47, XML_DELETED_OBJECT_ITEM_PARSING_ERROR_GENERIC = 0x48, XML_DELETED_OBJECT_ITEM_PARSING_ERROR_TAG = 0x49, XML_DELETED_OBJECT_ITEM_PARSING_ERROR_1 = 0x4A, // 0x4B..0x4F are reserved for future use XML_META_PARSING_ERROR_GENERIC = 0x50, XML_META_BINARIES_PARSING_ERROR_GENERIC = 0x51, XML_META_BINARIES_PARSING_ERROR_TAG = 0x52, XML_META_MEMORY_PROTECTION_PARSING_ERROR_GENERIC = 0x53, XML_META_MEMORY_PROTECTION_PARSING_ERROR_TAG = 0x54, XML_META_BINARY_PARSING_ERROR_GENERIC = 0x55, XML_META_BINARY_PARSING_ERROR_TAG = 0x56, XML_META_BINARY_PARSING_ERROR_1 = 0x57, XML_META_CUSTOM_DATA_PARSING_ERROR_GENERIC = 0x58, XML_META_CUSTOM_DATA_PARSING_ERROR_TAG = 0x59, XML_META_CUSTOM_DATA_ITEM_PARSING_ERROR_GENERIC = 0x5A, XML_META_CUSTOM_DATA_ITEM_PARSING_ERROR_TAG = 0x5B, XML_META_CUSTOM_ICONS_PARSING_ERROR_GENERIC = 0x5C, XML_META_CUSTOM_ICONS_PARSING_ERROR_TAG = 0x5D, XML_META_CUSTOM_ICON_ITEM_PARSING_ERROR_GENERIC = 0x5E, XML_META_CUSTOM_ICON_ITEM_PARSING_ERROR_TAG = 0x5F, XML_META_CUSTOM_ICON_ITEM_PARSING_ERROR_1 = 0x60, XML_META_PARSING_ERROR_TAG = 0x61, XML_META_HEADER_HASH_MISMATCH = 0x62, // 0x63..0x6F are reserved for future use XML_GROUP_PARSING_ERROR_GENERIC = 0x70, XML_GROUP_PARSING_ERROR_TAG = 0x71, XML_GROUP_TIMES_PARSING_ERROR_GENERIC = 0x72, XML_GROUP_TIMES_PARSING_ERROR_TAG = 0x73, XML_GROUP_TIMES_PARSING_ERROR_1 = 0x74, XML_GROUP_TIMES_PARSING_ERROR_2 = 0x75, XML_GROUP_TIMES_PARSING_ERROR_3 = 0x76, XML_GROUP_TIMES_PARSING_ERROR_4 = 0x77, // 0x78..0x7F are reserved for future use XML_ENTRY_PARSING_ERROR_GENERIC = 0x80, XML_ENTRY_TIMES_PARSING_ERROR_GENERIC = 0x81, XML_ENTRY_TIMES_PARSING_ERROR_TAG = 0x82, XML_ENTRY_TIMES_PARSING_ERROR_1 = 0x83, XML_ENTRY_TIMES_PARSING_ERROR_2 = 0x84, XML_ENTRY_TIMES_PARSING_ERROR_3 = 0x85, XML_ENTRY_TIMES_PARSING_ERROR_4 = 0x86, XML_ENTRY_TIMES_PARSING_ERROR_5 = 0x87, XML_ENTRY_AUTO_TYPE_PARSING_ERROR_GENERIC = 0x88, XML_ENTRY_AUTO_TYPE_PARSING_ERROR_TAG = 0x89, XML_ENTRY_AUTO_TYPE_ASSOCIATION_PARSING_ERROR_GENERIC = 0x8A, XML_ENTRY_AUTO_TYPE_ASSOCIATION_PARSING_ERROR_TAG = 0x8B, XML_ENTRY_HISTORY_PARSING_ERROR_GENERIC = 0x8C, XML_ENTRY_FIELD_PARSING_ERROR_GENERIC = 0x8D, XML_ENTRY_FIELD_PARSING_ERROR_TAG = 0x8E, XML_ENTRY_ATTACHMENT_PARSING_ERROR_GENERIC = 0x8F, // 0x90..0x9F are reserved for future use INVALID_ATTACHMENT_REFERENCE_1 = 0xA0, INVALID_ATTACHMENT_REFERENCE_2 = 0xA1, // saving errors BLOCK_HASHING_ERROR = 0xC0, GZIP_COMPRESS_ERROR = 0xC1, CANNOT_ENCRYPT_DB = 0xC2, RNG_ERROR_1 = 0xC3, }; }; typedef QPair<QString, QString> QStringPair; #endif /* DEFSV4_H_ */
51.368664
135
0.688526
[ "transform" ]
e72711f9e08c021f841bfb25c7d85f576d53f199
1,191
h
C
src/State_Title.h
VictorieeMan/PianoGame_Compilable
da441618227c84a46eed9fed723ffded5f200dea
[ "MIT" ]
54
2016-05-25T07:39:10.000Z
2022-03-06T01:11:00.000Z
src/State_Title.h
VictorieeMan/PianoGame_Compilable
da441618227c84a46eed9fed723ffded5f200dea
[ "MIT" ]
null
null
null
src/State_Title.h
VictorieeMan/PianoGame_Compilable
da441618227c84a46eed9fed723ffded5f200dea
[ "MIT" ]
18
2018-03-09T12:50:19.000Z
2022-03-22T06:11:19.000Z
// Copyright (c)2007 Nicholas Piegdon // See license.txt for license information #ifndef __STATE_TITLE_H #define __STATE_TITLE_H #include "SharedState.h" #include "GameState.h" #include "MenuLayout.h" #include "libmidi/MidiTypes.h" #include "DeviceTile.h" #include "StringTile.h" #include <vector> class Midi; class MidiCommOut; class Tga; class TitleState : public GameState { public: // You can pass 0 in for state.midi_out to have the title // screen pick a device for you. TitleState(const SharedState &state) : m_state(state), m_output_tile(0), m_input_tile(0), m_file_tile(0), m_skip_next_mouse_up(false) { } ~TitleState(); protected: virtual void Init(); virtual void Update(); virtual void Draw(Renderer &renderer) const; private: void PlayDevicePreview(microseconds_t delta_microseconds); ButtonState m_continue_button; ButtonState m_back_button; SharedState m_state; std::string m_last_input_note_name; std::wstring m_tooltip; DeviceTile *m_output_tile; DeviceTile *m_input_tile; StringTile *m_file_tile; bool m_skip_next_mouse_up; }; #endif
20.894737
62
0.701931
[ "vector" ]
e7271cabb0752a992e0d474067dbd1dc333ec9a8
6,842
h
C
pandas/src/parser/tokenizer.h
sandbox/pandas
fd5471208244ae1cb9cb426d6aa02ab408cfacba
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
pandas/src/parser/tokenizer.h
sandbox/pandas
fd5471208244ae1cb9cb426d6aa02ab408cfacba
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
pandas/src/parser/tokenizer.h
sandbox/pandas
fd5471208244ae1cb9cb426d6aa02ab408cfacba
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
1
2020-11-14T00:18:18.000Z
2020-11-14T00:18:18.000Z
/* Copyright (c) 2012, Lambda Foundry, Inc., except where noted Incorporates components of WarrenWeckesser/textreader, licensed under 3-clause BSD See LICENSE for the license */ #ifndef PANDAS_SRC_PARSER_TOKENIZER_H_ #define PANDAS_SRC_PARSER_TOKENIZER_H_ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "Python.h" #include <ctype.h> #define ERROR_OK 0 #define ERROR_NO_DIGITS 1 #define ERROR_OVERFLOW 2 #define ERROR_INVALID_CHARS 3 #include "../headers/stdint.h" #include "khash.h" #define CHUNKSIZE 1024 * 256 #define KB 1024 #define MB 1024 * KB #define STREAM_INIT_SIZE 32 #define REACHED_EOF 1 #define CALLING_READ_FAILED 2 #ifndef P_INLINE #if defined(__GNUC__) #define P_INLINE static __inline__ #elif defined(_MSC_VER) #define P_INLINE #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define P_INLINE static inline #else #define P_INLINE #endif #endif #if defined(_MSC_VER) #define strtoll _strtoi64 #endif /* C flat file parsing low level code for pandas / NumPy */ #define FALSE 0 #define TRUE 1 // Maximum number of columns in a file. #define MAX_NUM_COLUMNS 2000 // Maximum number of characters in single field. #define FIELD_BUFFER_SIZE 2000 /* * Common set of error types for the read_rows() and tokenize() * functions. */ #define ERROR_OUT_OF_MEMORY 1 #define ERROR_INVALID_COLUMN_INDEX 10 #define ERROR_CHANGED_NUMBER_OF_FIELDS 12 #define ERROR_TOO_MANY_CHARS 21 #define ERROR_TOO_MANY_FIELDS 22 #define ERROR_NO_DATA 23 // #define VERBOSE #if defined(VERBOSE) #define TRACE(X) printf X; #else #define TRACE(X) #endif #define PARSER_OUT_OF_MEMORY -1 /* * XXX Might want to couple count_rows() with read_rows() to avoid duplication * of some file I/O. */ /* * WORD_BUFFER_SIZE determines the maximum amount of non-delimiter * text in a row. */ #define WORD_BUFFER_SIZE 4000 typedef enum { START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, EAT_CRNL, EAT_CRNL_NOP, EAT_WHITESPACE, EAT_COMMENT, EAT_LINE_COMMENT, WHITESPACE_LINE, START_FIELD_IN_SKIP_LINE, IN_FIELD_IN_SKIP_LINE, IN_QUOTED_FIELD_IN_SKIP_LINE, QUOTE_IN_QUOTED_FIELD_IN_SKIP_LINE, FINISHED } ParserState; typedef enum { QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE } QuoteStyle; typedef void *(*io_callback)(void *src, size_t nbytes, size_t *bytes_read, int *status); typedef int (*io_cleanup)(void *src); typedef struct parser_t { void *source; io_callback cb_io; io_cleanup cb_cleanup; int chunksize; // Number of bytes to prepare for each chunk char *data; // pointer to data to be processed int datalen; // amount of data available int datapos; // where to write out tokenized data char *stream; int stream_len; int stream_cap; // Store words in (potentially ragged) matrix for now, hmm char **words; int *word_starts; // where we are in the stream int words_len; int words_cap; char *pword_start; // pointer to stream start of current field int word_start; // position start of current field int *line_start; // position in words for start of line int *line_fields; // Number of fields in each line int lines; // Number of (good) lines observed int file_lines; // Number of file lines observed (including bad or skipped) int lines_cap; // Vector capacity // Tokenizing stuff ParserState state; int doublequote; /* is " represented by ""? */ char delimiter; /* field separator */ int delim_whitespace; /* delimit by consuming space/tabs instead */ char quotechar; /* quote character */ char escapechar; /* escape character */ char lineterminator; int skipinitialspace; /* ignore spaces following delimiter? */ int quoting; /* style of quoting to write */ // krufty, hmm =/ int numeric_field; char commentchar; int allow_embedded_newline; int strict; /* raise exception on bad CSV */ int usecols; // Boolean: 1: usecols provided, 0: none provided int expected_fields; int error_bad_lines; int warn_bad_lines; // floating point options char decimal; char sci; // thousands separator (comma, period) char thousands; int header; // Boolean: 1: has header, 0: no header int header_start; // header row start int header_end; // header row end void *skipset; PyObject *skipfunc; int64_t skip_first_N_rows; int skip_footer; double (*converter)(const char *, char **, char, char, char, int); // error handling char *warn_msg; char *error_msg; int skip_empty_lines; } parser_t; typedef struct coliter_t { char **words; int *line_start; int col; } coliter_t; void coliter_setup(coliter_t *self, parser_t *parser, int i, int start); coliter_t *coliter_new(parser_t *self, int i); #define COLITER_NEXT(iter, word) \ do { \ const int i = *iter.line_start++ + iter.col; \ word = i < *iter.line_start ? iter.words[i] : ""; \ } while (0) parser_t *parser_new(void); int parser_init(parser_t *self); int parser_consume_rows(parser_t *self, size_t nrows); int parser_trim_buffers(parser_t *self); int parser_add_skiprow(parser_t *self, int64_t row); int parser_set_skipfirstnrows(parser_t *self, int64_t nrows); void parser_free(parser_t *self); void parser_set_default_options(parser_t *self); void debug_print_parser(parser_t *self); int tokenize_nrows(parser_t *self, size_t nrows); int tokenize_all_rows(parser_t *self); // Have parsed / type-converted a chunk of data // and want to free memory from the token stream typedef struct uint_state { int seen_sint; int seen_uint; int seen_null; } uint_state; void uint_state_init(uint_state *self); int uint64_conflict(uint_state *self); uint64_t str_to_uint64(uint_state *state, const char *p_item, int64_t int_max, uint64_t uint_max, int *error, char tsep); int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, int *error, char tsep); double xstrtod(const char *p, char **q, char decimal, char sci, char tsep, int skip_trailing); double precise_xstrtod(const char *p, char **q, char decimal, char sci, char tsep, int skip_trailing); double round_trip(const char *p, char **q, char decimal, char sci, char tsep, int skip_trailing); int to_boolean(const char *item, uint8_t *val); #endif // PANDAS_SRC_PARSER_TOKENIZER_H_
24.789855
80
0.691464
[ "vector" ]
e72788ae4f1e4fd82c3bdf34884f868a442b4a57
4,187
h
C
include/inviwo/core/datastructures/light/baselightsource.h
BioDataAnalysis/inviwo
6ca6fdd28837229ec1fdfa38d7ab35f3f07dd75b
[ "BSD-2-Clause" ]
null
null
null
include/inviwo/core/datastructures/light/baselightsource.h
BioDataAnalysis/inviwo
6ca6fdd28837229ec1fdfa38d7ab35f3f07dd75b
[ "BSD-2-Clause" ]
null
null
null
include/inviwo/core/datastructures/light/baselightsource.h
BioDataAnalysis/inviwo
6ca6fdd28837229ec1fdfa38d7ab35f3f07dd75b
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 IVW_BASELIGHT_H #define IVW_BASELIGHT_H #include <inviwo/core/common/inviwocoredefine.h> #include <inviwo/core/common/inviwo.h> #include <inviwo/core/datastructures/spatialdata.h> #include <inviwo/core/util/document.h> namespace inviwo { enum class LightSourceType { area = 0, cone, point, directional }; class IVW_CORE_API LightSource : public SpatialEntity<3> { public: LightSource(); virtual ~LightSource() = default; virtual float getArea() const = 0; /** * Get radiant flux (color) of light source. * @return Radiant flux in watt. */ virtual vec3 getPower() const = 0; /** * Get the intensity (color) from the light source given in watt per steradian (flux density per * solid angle, W*s*r^-1). * @return Flux density per solid angle, W*s*r^-1 */ const vec3 getIntensity() const; /** * Set the intensity (color) from the light source given in watt per steradian (flux density per * solid angle, W*s*r^-1). * @param intensity */ void setIntensity(const vec3& intensity); virtual LightSourceType getLightSourceType() const = 0; /** * Return field of view in radians. * @return Field of view in radians */ float getFieldOfView() const; void setFieldOfView(float FOVInRadians); /** * Get width and height in world space. */ const vec2& getSize() const; /** * Set width and height in texture space. */ void setSize(const vec2& newSize); /** * Get is enabled. */ bool isEnabled() const; /** * Set if enabled. */ void setEnabled(bool enable); virtual Document getInfo() const; static const uvec3 colorCode; static const std::string classIdentifier; static const std::string dataName; protected: vec3 intensity_; // Color of light source, flux density per solid angle (given in watt per // steradian W*s*r^-1) float fieldOfView_; // Field of view in radians vec2 size_; // width, height in world space bool enabled_; }; /** * \brief Encodes the position and direction in a matrix. * * Light source position is extracted using: * `p = M * vec4(0, 0, 0, 1)` * And the light source direction using: * `d = normalize(M * vec4(0, 0, 1, 0))` * @param pos Light source position. * @param dir Light source direction. * @return Transformation from light source model space to world space. */ IVW_CORE_API mat4 getLightTransformationMatrix(vec3 pos, vec3 dir); } // namespace inviwo #endif // IVW_BASELIGHT_H
32.457364
100
0.667065
[ "model", "solid" ]
e728c78b9c0d3bceee6e05c60ac0a3101ca3139b
44,054
h
C
apps/mysql-5.1.65/storage/innodb_plugin/include/dict0dict.h
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
3
2021-04-29T07:59:16.000Z
2021-12-10T02:23:05.000Z
apps/mysql-5.1.65/storage/innodb_plugin/include/dict0dict.h
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
apps/mysql-5.1.65/storage/innodb_plugin/include/dict0dict.h
vusec/firestarter
2048c1f731b8f3c5570a920757f9d7730d5f716a
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** Copyright (c) 1996, 2012, Oracle and/or its affiliates. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file include/dict0dict.h Data dictionary system Created 1/8/1996 Heikki Tuuri *******************************************************/ #ifndef dict0dict_h #define dict0dict_h #include "univ.i" #include "dict0types.h" #include "dict0mem.h" #include "data0type.h" #include "data0data.h" #include "mem0mem.h" #include "rem0types.h" #include "ut0mem.h" #include "ut0lst.h" #include "hash0hash.h" #include "ut0rnd.h" #include "ut0byte.h" #include "trx0types.h" #ifndef UNIV_HOTBACKUP # include "sync0sync.h" # include "sync0rw.h" /******************************************************************//** Makes all characters in a NUL-terminated UTF-8 string lower case. */ UNIV_INTERN void dict_casedn_str( /*============*/ char* a); /*!< in/out: string to put in lower case */ /********************************************************************//** Get the database name length in a table name. @return database name length */ UNIV_INTERN ulint dict_get_db_name_len( /*=================*/ const char* name); /*!< in: table name in the form dbname '/' tablename */ /********************************************************************//** Return the end of table name where we have removed dbname and '/'. @return table name */ const char* dict_remove_db_name( /*================*/ const char* name); /*!< in: table name in the form dbname '/' tablename */ /**********************************************************************//** Returns a table object based on table id. @return table, NULL if does not exist */ UNIV_INTERN dict_table_t* dict_table_get_on_id( /*=================*/ dulint table_id, /*!< in: table id */ trx_t* trx); /*!< in: transaction handle */ /********************************************************************//** Decrements the count of open MySQL handles to a table. */ UNIV_INTERN void dict_table_decrement_handle_count( /*==============================*/ dict_table_t* table, /*!< in/out: table */ ibool dict_locked); /*!< in: TRUE=data dictionary locked */ /**********************************************************************//** Inits the data dictionary module. */ UNIV_INTERN void dict_init(void); /*===========*/ /********************************************************************//** Gets the space id of every table of the data dictionary and makes a linear list and a hash table of them to the data dictionary cache. This function can be called at database startup if we did not need to do a crash recovery. In crash recovery we must scan the space id's from the .ibd files in MySQL database directories. */ UNIV_INTERN void dict_load_space_id_list(void); /*=========================*/ /*********************************************************************//** Gets the column data type. */ UNIV_INLINE void dict_col_copy_type( /*===============*/ const dict_col_t* col, /*!< in: column */ dtype_t* type); /*!< out: data type */ #endif /* !UNIV_HOTBACKUP */ #ifdef UNIV_DEBUG /*********************************************************************//** Assert that a column and a data type match. @return TRUE */ UNIV_INLINE ibool dict_col_type_assert_equal( /*=======================*/ const dict_col_t* col, /*!< in: column */ const dtype_t* type); /*!< in: data type */ #endif /* UNIV_DEBUG */ #ifndef UNIV_HOTBACKUP /***********************************************************************//** Returns the minimum size of the column. @return minimum size */ UNIV_INLINE ulint dict_col_get_min_size( /*==================*/ const dict_col_t* col); /*!< in: column */ /***********************************************************************//** Returns the maximum size of the column. @return maximum size */ UNIV_INLINE ulint dict_col_get_max_size( /*==================*/ const dict_col_t* col); /*!< in: column */ /***********************************************************************//** Returns the size of a fixed size column, 0 if not a fixed size column. @return fixed size, or 0 */ UNIV_INLINE ulint dict_col_get_fixed_size( /*====================*/ const dict_col_t* col, /*!< in: column */ ulint comp); /*!< in: nonzero=ROW_FORMAT=COMPACT */ /***********************************************************************//** Returns the ROW_FORMAT=REDUNDANT stored SQL NULL size of a column. For fixed length types it is the fixed length of the type, otherwise 0. @return SQL null storage size in ROW_FORMAT=REDUNDANT */ UNIV_INLINE ulint dict_col_get_sql_null_size( /*=======================*/ const dict_col_t* col, /*!< in: column */ ulint comp); /*!< in: nonzero=ROW_FORMAT=COMPACT */ /*********************************************************************//** Gets the column number. @return col->ind, table column position (starting from 0) */ UNIV_INLINE ulint dict_col_get_no( /*============*/ const dict_col_t* col); /*!< in: column */ /*********************************************************************//** Gets the column position in the clustered index. */ UNIV_INLINE ulint dict_col_get_clust_pos( /*===================*/ const dict_col_t* col, /*!< in: table column */ const dict_index_t* clust_index); /*!< in: clustered index */ /****************************************************************//** If the given column name is reserved for InnoDB system columns, return TRUE. @return TRUE if name is reserved */ UNIV_INTERN ibool dict_col_name_is_reserved( /*======================*/ const char* name); /*!< in: column name */ /********************************************************************//** Acquire the autoinc lock. */ UNIV_INTERN void dict_table_autoinc_lock( /*====================*/ dict_table_t* table); /*!< in/out: table */ /********************************************************************//** Unconditionally set the autoinc counter. */ UNIV_INTERN void dict_table_autoinc_initialize( /*==========================*/ dict_table_t* table, /*!< in/out: table */ ib_uint64_t value); /*!< in: next value to assign to a row */ /********************************************************************//** Reads the next autoinc value (== autoinc counter value), 0 if not yet initialized. @return value for a new row, or 0 */ UNIV_INTERN ib_uint64_t dict_table_autoinc_read( /*====================*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Updates the autoinc counter if the value supplied is greater than the current value. */ UNIV_INTERN void dict_table_autoinc_update_if_greater( /*=================================*/ dict_table_t* table, /*!< in/out: table */ ib_uint64_t value); /*!< in: value which was assigned to a row */ /********************************************************************//** Release the autoinc lock. */ UNIV_INTERN void dict_table_autoinc_unlock( /*======================*/ dict_table_t* table); /*!< in/out: table */ #endif /* !UNIV_HOTBACKUP */ /**********************************************************************//** Adds system columns to a table object. */ UNIV_INTERN void dict_table_add_system_columns( /*==========================*/ dict_table_t* table, /*!< in/out: table */ mem_heap_t* heap); /*!< in: temporary heap */ #ifndef UNIV_HOTBACKUP /**********************************************************************//** Adds a table object to the dictionary cache. */ UNIV_INTERN void dict_table_add_to_cache( /*====================*/ dict_table_t* table, /*!< in: table */ mem_heap_t* heap); /*!< in: temporary heap */ /**********************************************************************//** Removes a table object from the dictionary cache. */ UNIV_INTERN void dict_table_remove_from_cache( /*=========================*/ dict_table_t* table); /*!< in, own: table */ /**********************************************************************//** Renames a table object. @return TRUE if success */ UNIV_INTERN ibool dict_table_rename_in_cache( /*=======================*/ dict_table_t* table, /*!< in/out: table */ const char* new_name, /*!< in: new name */ ibool rename_also_foreigns);/*!< in: in ALTER TABLE we want to preserve the original table name in constraints which reference it */ /**********************************************************************//** Removes an index from the dictionary cache. */ UNIV_INTERN void dict_index_remove_from_cache( /*=========================*/ dict_table_t* table, /*!< in/out: table */ dict_index_t* index); /*!< in, own: index */ /**********************************************************************//** Change the id of a table object in the dictionary cache. This is used in DISCARD TABLESPACE. */ UNIV_INTERN void dict_table_change_id_in_cache( /*==========================*/ dict_table_t* table, /*!< in/out: table object already in cache */ dulint new_id);/*!< in: new id to set */ /**********************************************************************//** Adds a foreign key constraint object to the dictionary cache. May free the object if there already is an object with the same identifier in. At least one of foreign table or referenced table must already be in the dictionary cache! @return DB_SUCCESS or error code */ UNIV_INTERN ulint dict_foreign_add_to_cache( /*======================*/ dict_foreign_t* foreign, /*!< in, own: foreign key constraint */ ibool check_charsets);/*!< in: TRUE=check charset compatibility */ /*********************************************************************//** Check if the index is referenced by a foreign key, if TRUE return the matching instance NULL otherwise. @return pointer to foreign key struct if index is defined for foreign key, otherwise NULL */ UNIV_INTERN dict_foreign_t* dict_table_get_referenced_constraint( /*=================================*/ dict_table_t* table, /*!< in: InnoDB table */ dict_index_t* index); /*!< in: InnoDB index */ /*********************************************************************//** Checks if a table is referenced by foreign keys. @return TRUE if table is referenced by a foreign key */ UNIV_INTERN ibool dict_table_is_referenced_by_foreign_key( /*====================================*/ const dict_table_t* table); /*!< in: InnoDB table */ /**********************************************************************//** Replace the index in the foreign key list that matches this index's definition with an equivalent index. */ UNIV_INTERN void dict_table_replace_index_in_foreign_list( /*=====================================*/ dict_table_t* table, /*!< in/out: table */ dict_index_t* index, /*!< in: index to be replaced */ const trx_t* trx); /*!< in: transaction handle */ /*********************************************************************//** Checks if a index is defined for a foreign key constraint. Index is a part of a foreign key constraint if the index is referenced by foreign key or index is a foreign key index @return pointer to foreign key struct if index is defined for foreign key, otherwise NULL */ UNIV_INTERN dict_foreign_t* dict_table_get_foreign_constraint( /*==============================*/ dict_table_t* table, /*!< in: InnoDB table */ dict_index_t* index); /*!< in: InnoDB index */ /*********************************************************************//** Scans a table create SQL string and adds to the data dictionary the foreign key constraints declared in the string. This function should be called after the indexes for a table have been created. Each foreign key constraint must be accompanied with indexes in bot participating tables. The indexes are allowed to contain more fields than mentioned in the constraint. @return error code or DB_SUCCESS */ UNIV_INTERN ulint dict_create_foreign_constraints( /*============================*/ trx_t* trx, /*!< in: transaction */ const char* sql_string, /*!< in: table create statement where foreign keys are declared like: FOREIGN KEY (a, b) REFERENCES table2(c, d), table2 can be written also with the database name before it: test.table2; the default database id the database of parameter name */ size_t sql_length, /*!< in: length of sql_string */ const char* name, /*!< in: table full name in the normalized form database_name/table_name */ ibool reject_fks); /*!< in: if TRUE, fail with error code DB_CANNOT_ADD_CONSTRAINT if any foreign keys are found. */ /**********************************************************************//** Parses the CONSTRAINT id's to be dropped in an ALTER TABLE statement. @return DB_SUCCESS or DB_CANNOT_DROP_CONSTRAINT if syntax error or the constraint id does not match */ UNIV_INTERN ulint dict_foreign_parse_drop_constraints( /*================================*/ mem_heap_t* heap, /*!< in: heap from which we can allocate memory */ trx_t* trx, /*!< in: transaction */ dict_table_t* table, /*!< in: table */ ulint* n, /*!< out: number of constraints to drop */ const char*** constraints_to_drop); /*!< out: id's of the constraints to drop */ /**********************************************************************//** Returns a table object and optionally increment its MySQL open handle count. NOTE! This is a high-level function to be used mainly from outside the 'dict' directory. Inside this directory dict_table_get_low is usually the appropriate function. @return table, NULL if does not exist */ UNIV_INTERN dict_table_t* dict_table_get( /*===========*/ const char* table_name, /*!< in: table name */ ibool inc_mysql_count); /*!< in: whether to increment the open handle count on the table */ /**********************************************************************//** Returns a index object, based on table and index id, and memoryfixes it. @return index, NULL if does not exist */ UNIV_INTERN dict_index_t* dict_index_get_on_id_low( /*=====================*/ dict_table_t* table, /*!< in: table */ dulint index_id); /*!< in: index id */ /**********************************************************************//** Checks if a table is in the dictionary cache. @return table, NULL if not found */ UNIV_INLINE dict_table_t* dict_table_check_if_in_cache_low( /*=============================*/ const char* table_name); /*!< in: table name */ /**********************************************************************//** Gets a table; loads it to the dictionary cache if necessary. A low-level function. @return table, NULL if not found */ UNIV_INLINE dict_table_t* dict_table_get_low( /*===============*/ const char* table_name); /*!< in: table name */ /**********************************************************************//** Returns a table object based on table id. @return table, NULL if does not exist */ UNIV_INLINE dict_table_t* dict_table_get_on_id_low( /*=====================*/ dulint table_id); /*!< in: table id */ /**********************************************************************//** Find an index that is equivalent to the one passed in and is not marked for deletion. @return index equivalent to foreign->foreign_index, or NULL */ UNIV_INTERN dict_index_t* dict_foreign_find_equiv_index( /*==========================*/ dict_foreign_t* foreign);/*!< in: foreign key */ /**********************************************************************//** Returns an index object by matching on the name and column names and if more than one index matches return the index with the max id @return matching index, NULL if not found */ UNIV_INTERN dict_index_t* dict_table_get_index_by_max_id( /*===========================*/ dict_table_t* table, /*!< in: table */ const char* name, /*!< in: the index name to find */ const char** columns,/*!< in: array of column names */ ulint n_cols);/*!< in: number of columns */ /**********************************************************************//** Returns a column's name. @return column name. NOTE: not guaranteed to stay valid if table is modified in any way (columns added, etc.). */ UNIV_INTERN const char* dict_table_get_col_name( /*====================*/ const dict_table_t* table, /*!< in: table */ ulint col_nr);/*!< in: column number */ /**********************************************************************//** Prints a table definition. */ UNIV_INTERN void dict_table_print( /*=============*/ dict_table_t* table); /*!< in: table */ /**********************************************************************//** Prints a table data. */ UNIV_INTERN void dict_table_print_low( /*=================*/ dict_table_t* table); /*!< in: table */ /**********************************************************************//** Prints a table data when we know the table name. */ UNIV_INTERN void dict_table_print_by_name( /*=====================*/ const char* name); /*!< in: table name */ /**********************************************************************//** Outputs info on foreign keys of a table. */ UNIV_INTERN void dict_print_info_on_foreign_keys( /*============================*/ ibool create_table_format, /*!< in: if TRUE then print in a format suitable to be inserted into a CREATE TABLE, otherwise in the format of SHOW TABLE STATUS */ FILE* file, /*!< in: file where to print */ trx_t* trx, /*!< in: transaction */ dict_table_t* table); /*!< in: table */ /**********************************************************************//** Outputs info on a foreign key of a table in a format suitable for CREATE TABLE. */ UNIV_INTERN void dict_print_info_on_foreign_key_in_create_format( /*============================================*/ FILE* file, /*!< in: file where to print */ trx_t* trx, /*!< in: transaction */ dict_foreign_t* foreign, /*!< in: foreign key constraint */ ibool add_newline); /*!< in: whether to add a newline */ /********************************************************************//** Displays the names of the index and the table. */ UNIV_INTERN void dict_index_name_print( /*==================*/ FILE* file, /*!< in: output stream */ trx_t* trx, /*!< in: transaction */ const dict_index_t* index); /*!< in: index to print */ #ifdef UNIV_DEBUG /********************************************************************//** Gets the first index on the table (the clustered index). @return index, NULL if none exists */ UNIV_INLINE dict_index_t* dict_table_get_first_index( /*=======================*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Gets the next index on the table. @return index, NULL if none left */ UNIV_INLINE dict_index_t* dict_table_get_next_index( /*======================*/ const dict_index_t* index); /*!< in: index */ #else /* UNIV_DEBUG */ # define dict_table_get_first_index(table) UT_LIST_GET_FIRST((table)->indexes) # define dict_table_get_next_index(index) UT_LIST_GET_NEXT(indexes, index) #endif /* UNIV_DEBUG */ #endif /* !UNIV_HOTBACKUP */ /********************************************************************//** Check whether the index is the clustered index. @return nonzero for clustered index, zero for other indexes */ UNIV_INLINE ulint dict_index_is_clust( /*================*/ const dict_index_t* index) /*!< in: index */ __attribute__((pure)); /********************************************************************//** Check whether the index is unique. @return nonzero for unique index, zero for other indexes */ UNIV_INLINE ulint dict_index_is_unique( /*=================*/ const dict_index_t* index) /*!< in: index */ __attribute__((pure)); /********************************************************************//** Check whether the index is the insert buffer tree. @return nonzero for insert buffer, zero for other indexes */ UNIV_INLINE ulint dict_index_is_ibuf( /*===============*/ const dict_index_t* index) /*!< in: index */ __attribute__((pure)); /********************************************************************//** Check whether the index is a secondary index or the insert buffer tree. @return nonzero for insert buffer, zero for other indexes */ UNIV_INLINE ulint dict_index_is_sec_or_ibuf( /*======================*/ const dict_index_t* index) /*!< in: index */ __attribute__((pure)); /********************************************************************//** Gets the number of user-defined columns in a table in the dictionary cache. @return number of user-defined (e.g., not ROW_ID) columns of a table */ UNIV_INLINE ulint dict_table_get_n_user_cols( /*=======================*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Gets the number of system columns in a table in the dictionary cache. @return number of system (e.g., ROW_ID) columns of a table */ UNIV_INLINE ulint dict_table_get_n_sys_cols( /*======================*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Gets the number of all columns (also system) in a table in the dictionary cache. @return number of columns of a table */ UNIV_INLINE ulint dict_table_get_n_cols( /*==================*/ const dict_table_t* table); /*!< in: table */ #ifdef UNIV_DEBUG /********************************************************************//** Gets the nth column of a table. @return pointer to column object */ UNIV_INLINE dict_col_t* dict_table_get_nth_col( /*===================*/ const dict_table_t* table, /*!< in: table */ ulint pos); /*!< in: position of column */ /********************************************************************//** Gets the given system column of a table. @return pointer to column object */ UNIV_INLINE dict_col_t* dict_table_get_sys_col( /*===================*/ const dict_table_t* table, /*!< in: table */ ulint sys); /*!< in: DATA_ROW_ID, ... */ #else /* UNIV_DEBUG */ #define dict_table_get_nth_col(table, pos) \ ((table)->cols + (pos)) #define dict_table_get_sys_col(table, sys) \ ((table)->cols + (table)->n_cols + (sys) - DATA_N_SYS_COLS) #endif /* UNIV_DEBUG */ /********************************************************************//** Gets the given system column number of a table. @return column number */ UNIV_INLINE ulint dict_table_get_sys_col_no( /*======================*/ const dict_table_t* table, /*!< in: table */ ulint sys); /*!< in: DATA_ROW_ID, ... */ #ifndef UNIV_HOTBACKUP /********************************************************************//** Returns the minimum data size of an index record. @return minimum data size in bytes */ UNIV_INLINE ulint dict_index_get_min_size( /*====================*/ const dict_index_t* index); /*!< in: index */ #endif /* !UNIV_HOTBACKUP */ /********************************************************************//** Check whether the table uses the compact page format. @return TRUE if table uses the compact page format */ UNIV_INLINE ibool dict_table_is_comp( /*===============*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Determine the file format of a table. @return file format version */ UNIV_INLINE ulint dict_table_get_format( /*==================*/ const dict_table_t* table); /*!< in: table */ /********************************************************************//** Set the file format of a table. */ UNIV_INLINE void dict_table_set_format( /*==================*/ dict_table_t* table, /*!< in/out: table */ ulint format);/*!< in: file format version */ /********************************************************************//** Extract the compressed page size from table flags. @return compressed page size, or 0 if not compressed */ UNIV_INLINE ulint dict_table_flags_to_zip_size( /*=========================*/ ulint flags) /*!< in: flags */ __attribute__((const)); /********************************************************************//** Check whether the table uses the compressed compact page format. @return compressed page size, or 0 if not compressed */ UNIV_INLINE ulint dict_table_zip_size( /*================*/ const dict_table_t* table); /*!< in: table */ /*********************************************************************//** Obtain exclusive locks on all index trees of the table. This is to prevent accessing index trees while InnoDB is updating internal metadata for operations such as truncate tables. */ UNIV_INLINE void dict_table_x_lock_indexes( /*======================*/ dict_table_t* table); /*!< in: table */ /*********************************************************************//** Release the exclusive locks on all index tree. */ UNIV_INLINE void dict_table_x_unlock_indexes( /*========================*/ dict_table_t* table); /*!< in: table */ /********************************************************************//** Checks if a column is in the ordering columns of the clustered index of a table. Column prefixes are treated like whole columns. @return TRUE if the column, or its prefix, is in the clustered key */ UNIV_INTERN ibool dict_table_col_in_clustered_key( /*============================*/ const dict_table_t* table, /*!< in: table */ ulint n); /*!< in: column number */ #ifndef UNIV_HOTBACKUP /*******************************************************************//** Copies types of columns contained in table to tuple and sets all fields of the tuple to the SQL NULL value. This function should be called right after dtuple_create(). */ UNIV_INTERN void dict_table_copy_types( /*==================*/ dtuple_t* tuple, /*!< in/out: data tuple */ const dict_table_t* table); /*!< in: table */ /**********************************************************************//** Looks for an index with the given id. NOTE that we do not reserve the dictionary mutex: this function is for emergency purposes like printing info of a corrupt database page! @return index or NULL if not found from cache */ UNIV_INTERN dict_index_t* dict_index_find_on_id_low( /*======================*/ dulint id); /*!< in: index id */ /**********************************************************************//** Adds an index to the dictionary cache. @return DB_SUCCESS, DB_TOO_BIG_RECORD, or DB_CORRUPTION */ UNIV_INTERN ulint dict_index_add_to_cache( /*====================*/ dict_table_t* table, /*!< in: table on which the index is */ dict_index_t* index, /*!< in, own: index; NOTE! The index memory object is freed in this function! */ ulint page_no,/*!< in: root page number of the index */ ibool strict);/*!< in: TRUE=refuse to create the index if records could be too big to fit in an B-tree page */ /**********************************************************************//** Removes an index from the dictionary cache. */ UNIV_INTERN void dict_index_remove_from_cache( /*=========================*/ dict_table_t* table, /*!< in/out: table */ dict_index_t* index); /*!< in, own: index */ #endif /* !UNIV_HOTBACKUP */ /********************************************************************//** Gets the number of fields in the internal representation of an index, including fields added by the dictionary system. @return number of fields */ UNIV_INLINE ulint dict_index_get_n_fields( /*====================*/ const dict_index_t* index); /*!< in: an internal representation of index (in the dictionary cache) */ /********************************************************************//** Gets the number of fields in the internal representation of an index that uniquely determine the position of an index entry in the index, if we do not take multiversioning into account: in the B-tree use the value returned by dict_index_get_n_unique_in_tree. @return number of fields */ UNIV_INLINE ulint dict_index_get_n_unique( /*====================*/ const dict_index_t* index); /*!< in: an internal representation of index (in the dictionary cache) */ /********************************************************************//** Gets the number of fields in the internal representation of an index which uniquely determine the position of an index entry in the index, if we also take multiversioning into account. @return number of fields */ UNIV_INLINE ulint dict_index_get_n_unique_in_tree( /*============================*/ const dict_index_t* index); /*!< in: an internal representation of index (in the dictionary cache) */ /********************************************************************//** Gets the number of user-defined ordering fields in the index. In the internal representation we add the row id to the ordering fields to make all indexes unique, but this function returns the number of fields the user defined in the index as ordering fields. @return number of fields */ UNIV_INLINE ulint dict_index_get_n_ordering_defined_by_user( /*======================================*/ const dict_index_t* index); /*!< in: an internal representation of index (in the dictionary cache) */ #ifdef UNIV_DEBUG /********************************************************************//** Gets the nth field of an index. @return pointer to field object */ UNIV_INLINE dict_field_t* dict_index_get_nth_field( /*=====================*/ const dict_index_t* index, /*!< in: index */ ulint pos); /*!< in: position of field */ #else /* UNIV_DEBUG */ # define dict_index_get_nth_field(index, pos) ((index)->fields + (pos)) #endif /* UNIV_DEBUG */ /********************************************************************//** Gets pointer to the nth column in an index. @return column */ UNIV_INLINE const dict_col_t* dict_index_get_nth_col( /*===================*/ const dict_index_t* index, /*!< in: index */ ulint pos); /*!< in: position of the field */ /********************************************************************//** Gets the column number of the nth field in an index. @return column number */ UNIV_INLINE ulint dict_index_get_nth_col_no( /*======================*/ const dict_index_t* index, /*!< in: index */ ulint pos); /*!< in: position of the field */ /********************************************************************//** Looks for column n in an index. @return position in internal representation of the index; ULINT_UNDEFINED if not contained */ UNIV_INTERN ulint dict_index_get_nth_col_pos( /*=======================*/ const dict_index_t* index, /*!< in: index */ ulint n); /*!< in: column number */ /********************************************************************//** Returns TRUE if the index contains a column or a prefix of that column. @return TRUE if contains the column or its prefix */ UNIV_INTERN ibool dict_index_contains_col_or_prefix( /*==============================*/ const dict_index_t* index, /*!< in: index */ ulint n); /*!< in: column number */ /********************************************************************//** Looks for a matching field in an index. The column has to be the same. The column in index must be complete, or must contain a prefix longer than the column in index2. That is, we must be able to construct the prefix in index2 from the prefix in index. @return position in internal representation of the index; ULINT_UNDEFINED if not contained */ UNIV_INTERN ulint dict_index_get_nth_field_pos( /*=========================*/ const dict_index_t* index, /*!< in: index from which to search */ const dict_index_t* index2, /*!< in: index */ ulint n); /*!< in: field number in index2 */ /********************************************************************//** Looks for column n position in the clustered index. @return position in internal representation of the clustered index */ UNIV_INTERN ulint dict_table_get_nth_col_pos( /*=======================*/ const dict_table_t* table, /*!< in: table */ ulint n); /*!< in: column number */ /********************************************************************//** Returns the position of a system column in an index. @return position, ULINT_UNDEFINED if not contained */ UNIV_INLINE ulint dict_index_get_sys_col_pos( /*=======================*/ const dict_index_t* index, /*!< in: index */ ulint type); /*!< in: DATA_ROW_ID, ... */ /*******************************************************************//** Adds a column to index. */ UNIV_INTERN void dict_index_add_col( /*===============*/ dict_index_t* index, /*!< in/out: index */ const dict_table_t* table, /*!< in: table */ dict_col_t* col, /*!< in: column */ ulint prefix_len); /*!< in: column prefix length */ #ifndef UNIV_HOTBACKUP /*******************************************************************//** Copies types of fields contained in index to tuple. */ UNIV_INTERN void dict_index_copy_types( /*==================*/ dtuple_t* tuple, /*!< in/out: data tuple */ const dict_index_t* index, /*!< in: index */ ulint n_fields); /*!< in: number of field types to copy */ #endif /* !UNIV_HOTBACKUP */ /*********************************************************************//** Gets the field column. @return field->col, pointer to the table column */ UNIV_INLINE const dict_col_t* dict_field_get_col( /*===============*/ const dict_field_t* field); /*!< in: index field */ #ifndef UNIV_HOTBACKUP /**********************************************************************//** Returns an index object if it is found in the dictionary cache. Assumes that dict_sys->mutex is already being held. @return index, NULL if not found */ UNIV_INTERN dict_index_t* dict_index_get_if_in_cache_low( /*===========================*/ dulint index_id); /*!< in: index id */ #if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG /**********************************************************************//** Returns an index object if it is found in the dictionary cache. @return index, NULL if not found */ UNIV_INTERN dict_index_t* dict_index_get_if_in_cache( /*=======================*/ dulint index_id); /*!< in: index id */ #endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */ #ifdef UNIV_DEBUG /**********************************************************************//** Checks that a tuple has n_fields_cmp value in a sensible range, so that no comparison can occur with the page number field in a node pointer. @return TRUE if ok */ UNIV_INTERN ibool dict_index_check_search_tuple( /*==========================*/ const dict_index_t* index, /*!< in: index tree */ const dtuple_t* tuple); /*!< in: tuple used in a search */ /**********************************************************************//** Check for duplicate index entries in a table [using the index name] */ UNIV_INTERN void dict_table_check_for_dup_indexes( /*=============================*/ const dict_table_t* table, /*!< in: Check for dup indexes in this table */ ibool tmp_ok);/*!< in: TRUE=allow temporary index names */ #endif /* UNIV_DEBUG */ /**********************************************************************//** Builds a node pointer out of a physical record and a page number. @return own: node pointer */ UNIV_INTERN dtuple_t* dict_index_build_node_ptr( /*======================*/ const dict_index_t* index, /*!< in: index */ const rec_t* rec, /*!< in: record for which to build node pointer */ ulint page_no,/*!< in: page number to put in node pointer */ mem_heap_t* heap, /*!< in: memory heap where pointer created */ ulint level); /*!< in: level of rec in tree: 0 means leaf level */ /**********************************************************************//** Copies an initial segment of a physical record, long enough to specify an index entry uniquely. @return pointer to the prefix record */ UNIV_INTERN rec_t* dict_index_copy_rec_order_prefix( /*=============================*/ const dict_index_t* index, /*!< in: index */ const rec_t* rec, /*!< in: record for which to copy prefix */ ulint* n_fields,/*!< out: number of fields copied */ byte** buf, /*!< in/out: memory buffer for the copied prefix, or NULL */ ulint* buf_size);/*!< in/out: buffer size */ /**********************************************************************//** Builds a typed data tuple out of a physical record. @return own: data tuple */ UNIV_INTERN dtuple_t* dict_index_build_data_tuple( /*========================*/ dict_index_t* index, /*!< in: index */ rec_t* rec, /*!< in: record for which to build data tuple */ ulint n_fields,/*!< in: number of data fields */ mem_heap_t* heap); /*!< in: memory heap where tuple created */ /*********************************************************************//** Gets the space id of the root of the index tree. @return space id */ UNIV_INLINE ulint dict_index_get_space( /*=================*/ const dict_index_t* index); /*!< in: index */ /*********************************************************************//** Sets the space id of the root of the index tree. */ UNIV_INLINE void dict_index_set_space( /*=================*/ dict_index_t* index, /*!< in/out: index */ ulint space); /*!< in: space id */ /*********************************************************************//** Gets the page number of the root of the index tree. @return page number */ UNIV_INLINE ulint dict_index_get_page( /*================*/ const dict_index_t* tree); /*!< in: index */ /*********************************************************************//** Gets the read-write lock of the index tree. @return read-write lock */ UNIV_INLINE rw_lock_t* dict_index_get_lock( /*================*/ dict_index_t* index); /*!< in: index */ /********************************************************************//** Returns free space reserved for future updates of records. This is relevant only in the case of many consecutive inserts, as updates which make the records bigger might fragment the index. @return number of free bytes on page, reserved for updates */ UNIV_INLINE ulint dict_index_get_space_reserve(void); /*==============================*/ /*********************************************************************//** Calculates the minimum record length in an index. */ UNIV_INTERN ulint dict_index_calc_min_rec_len( /*========================*/ const dict_index_t* index); /*!< in: index */ /*********************************************************************//** Calculates new estimates for table and index statistics. The statistics are used in query optimization. */ UNIV_INTERN void dict_update_statistics( /*===================*/ dict_table_t* table, /*!< in/out: table */ ibool only_calc_if_missing_stats);/*!< in: only update/recalc the stats if they have not been initialized yet, otherwise do nothing */ /********************************************************************//** Reserves the dictionary system mutex for MySQL. */ UNIV_INTERN void dict_mutex_enter_for_mysql(void); /*============================*/ /********************************************************************//** Releases the dictionary system mutex for MySQL. */ UNIV_INTERN void dict_mutex_exit_for_mysql(void); /*===========================*/ /**********************************************************************//** Lock the appropriate latch to protect a given table's statistics. table->id is used to pick the corresponding latch from a global array of latches. */ UNIV_INTERN void dict_table_stats_lock( /*==================*/ const dict_table_t* table, /*!< in: table */ ulint latch_mode); /*!< in: RW_S_LATCH or RW_X_LATCH */ /**********************************************************************//** Unlock the latch that has been locked by dict_table_stats_lock() */ UNIV_INTERN void dict_table_stats_unlock( /*====================*/ const dict_table_t* table, /*!< in: table */ ulint latch_mode); /*!< in: RW_S_LATCH or RW_X_LATCH */ /********************************************************************//** Checks if the database name in two table names is the same. @return TRUE if same db name */ UNIV_INTERN ibool dict_tables_have_same_db( /*=====================*/ const char* name1, /*!< in: table name in the form dbname '/' tablename */ const char* name2); /*!< in: table name in the form dbname '/' tablename */ /*********************************************************************//** Removes an index from the cache */ UNIV_INTERN void dict_index_remove_from_cache( /*=========================*/ dict_table_t* table, /*!< in/out: table */ dict_index_t* index); /*!< in, own: index */ /**********************************************************************//** Get index by name @return index, NULL if does not exist */ UNIV_INTERN dict_index_t* dict_table_get_index_on_name( /*=========================*/ dict_table_t* table, /*!< in: table */ const char* name); /*!< in: name of the index to find */ /**********************************************************************//** In case there is more than one index with the same name return the index with the min(id). @return index, NULL if does not exist */ UNIV_INTERN dict_index_t* dict_table_get_index_on_name_and_min_id( /*====================================*/ dict_table_t* table, /*!< in: table */ const char* name); /*!< in: name of the index to find */ /* Buffers for storing detailed information about the latest foreign key and unique key errors */ extern FILE* dict_foreign_err_file; extern mutex_t dict_foreign_err_mutex; /* mutex protecting the buffers */ /** the dictionary system */ extern dict_sys_t* dict_sys; /** the data dictionary rw-latch protecting dict_sys */ extern rw_lock_t dict_operation_lock; /* Dictionary system struct */ struct dict_sys_struct{ mutex_t mutex; /*!< mutex protecting the data dictionary; protects also the disk-based dictionary system tables; this mutex serializes CREATE TABLE and DROP TABLE, as well as reading the dictionary data for a table from system tables */ dulint row_id; /*!< the next row id to assign; NOTE that at a checkpoint this must be written to the dict system header and flushed to a file; in recovery this must be derived from the log records */ hash_table_t* table_hash; /*!< hash table of the tables, based on name */ hash_table_t* table_id_hash; /*!< hash table of the tables, based on id */ UT_LIST_BASE_NODE_T(dict_table_t) table_LRU; /*!< LRU list of tables */ ulint size; /*!< varying space in bytes occupied by the data dictionary table and index objects */ dict_table_t* sys_tables; /*!< SYS_TABLES table */ dict_table_t* sys_columns; /*!< SYS_COLUMNS table */ dict_table_t* sys_indexes; /*!< SYS_INDEXES table */ dict_table_t* sys_fields; /*!< SYS_FIELDS table */ }; #endif /* !UNIV_HOTBACKUP */ /** dummy index for ROW_FORMAT=REDUNDANT supremum and infimum records */ extern dict_index_t* dict_ind_redundant; /** dummy index for ROW_FORMAT=COMPACT supremum and infimum records */ extern dict_index_t* dict_ind_compact; /**********************************************************************//** Inits dict_ind_redundant and dict_ind_compact. */ UNIV_INTERN void dict_ind_init(void); /*===============*/ /**********************************************************************//** Closes the data dictionary module. */ UNIV_INTERN void dict_close(void); /*============*/ #ifndef UNIV_NONINL #include "dict0dict.ic" #endif #endif
36.989085
78
0.544218
[ "object" ]
e72a64ef49f16d1af3dcb47d07fec26004036d7a
31,679
c
C
src/mon-blows.c
ryandesign/angband
04c19f81c717cde52b53ea30058e44ef00cba49a
[ "CC-BY-3.0" ]
null
null
null
src/mon-blows.c
ryandesign/angband
04c19f81c717cde52b53ea30058e44ef00cba49a
[ "CC-BY-3.0" ]
null
null
null
src/mon-blows.c
ryandesign/angband
04c19f81c717cde52b53ea30058e44ef00cba49a
[ "CC-BY-3.0" ]
null
null
null
/** * \file mon-blows.c * \brief Monster melee module. * * Copyright (c) 1997 Ben Harrison, David Reeve Sward, Keldon Jones. * 2013 Ben Semmler * 2016 Nick McConnell * * This work is free software; you can redistribute it and/or modify it * under the terms of either: * * a) the GNU General Public License as published by the Free Software * Foundation, version 2, or * * b) the "Angband licence": * This software may be copied and distributed for educational, research, * and not for profit purposes provided that this copyright and statement * are included in all such copies. Other copyrights may also apply. */ #include "angband.h" #include "effects.h" #include "init.h" #include "monster.h" #include "mon-attack.h" #include "mon-blows.h" #include "mon-desc.h" #include "mon-lore.h" #include "mon-make.h" #include "mon-msg.h" #include "mon-util.h" #include "obj-desc.h" #include "obj-gear.h" #include "obj-make.h" #include "obj-pile.h" #include "obj-slays.h" #include "obj-tval.h" #include "obj-util.h" #include "player-calcs.h" #include "player-timed.h" #include "player-util.h" #include "project.h" /** * ------------------------------------------------------------------------ * Monster blow methods * ------------------------------------------------------------------------ */ typedef enum { BLOW_TAG_NONE, BLOW_TAG_TARGET, BLOW_TAG_OF_TARGET, BLOW_TAG_HAS } blow_tag_t; static blow_tag_t blow_tag_lookup(const char *tag) { if (strncmp(tag, "target", 6) == 0) return BLOW_TAG_TARGET; else if (strncmp(tag, "oftarget", 8) == 0) return BLOW_TAG_OF_TARGET; else if (strncmp(tag, "has", 3) == 0) return BLOW_TAG_HAS; else return BLOW_TAG_NONE; } /** * Print a monster blow message. * * We fill in the monster name and/or pronoun where necessary in * the message to replace instances of {name} or {pronoun}. */ char *monster_blow_method_action(struct blow_method *method, int midx) { char buf[1024] = "\0"; const char *next; const char *s; const char *tag; const char *in_cursor; size_t end = 0; struct monster *t_mon = NULL; int choice = randint0(method->num_messages); struct blow_message *msg = method->messages; /* Get the target monster, if any */ if (midx > 0) { t_mon = cave_monster(cave, midx); } /* Pick a message */ while (choice--) { msg = msg->next; } in_cursor = msg->act_msg; /* Add info to the message */ next = strchr(in_cursor, '{'); while (next) { /* Copy the text leading up to this { */ strnfcat(buf, 1024, &end, "%.*s", next - in_cursor, in_cursor); s = next + 1; while (*s && isalpha((unsigned char) *s)) s++; /* Valid tag */ if (*s == '}') { /* Start the tag after the { */ tag = next + 1; in_cursor = s + 1; switch (blow_tag_lookup(tag)) { case BLOW_TAG_TARGET: { char m_name[80]; if (midx > 0) { monster_desc(m_name, sizeof(m_name), t_mon, MDESC_TARG); strnfcat(buf, sizeof(buf), &end, m_name); } else { strnfcat(buf, sizeof(buf), &end, "you"); } break; } case BLOW_TAG_OF_TARGET: { char m_name[80]; if (midx > 0) { monster_desc(m_name, sizeof(m_name), t_mon, MDESC_TARG); strnfcat(buf, sizeof(buf), &end, m_name); strnfcat(buf, sizeof(buf), &end, "'s"); } else { strnfcat(buf, sizeof(buf), &end, "your"); } break; } case BLOW_TAG_HAS: { if (midx > 0) { strnfcat(buf, sizeof(buf), &end, "has"); } else { strnfcat(buf, sizeof(buf), &end, "have"); } break; } default: { break; } } } else { /* An invalid tag, skip it */ in_cursor = next + 1; } next = strchr(in_cursor, '{'); } strnfcat(buf, 1024, &end, in_cursor); return string_make(buf); } /** * ------------------------------------------------------------------------ * Monster blow effect helper functions * ------------------------------------------------------------------------ */ int blow_index(const char *name) { int i; for (i = 1; i < z_info->blow_effects_max; i++) { struct blow_effect *effect = &blow_effects[i]; if (my_stricmp(name, effect->name) == 0) return i; } return 0; } /** * Monster steals an item from the player */ static void steal_player_item(melee_effect_handler_context_t *context) { int tries; /* Find an item */ for (tries = 0; tries < 10; tries++) { struct object *obj, *stolen; char o_name[80]; bool split = false; bool none_left = false; /* Pick an item */ int index = randint0(z_info->pack_size); /* Obtain the item */ obj = context->p->upkeep->inven[index]; /* Skip non-objects */ if (obj == NULL) continue; /* Skip artifacts */ if (obj->artifact) continue; /* Get a description */ object_desc(o_name, sizeof(o_name), obj, ODESC_FULL); /* Is it one of a stack being stolen? */ if (obj->number > 1) split = true; /* Try to steal */ if (react_to_slay(obj, context->mon)) { /* React to objects that hurt the monster */ char m_name[80]; /* Get the monster names (or "it") */ monster_desc(m_name, sizeof(m_name), context->mon, MDESC_STANDARD); /* Fail to steal */ msg("%s tries to steal %s %s, but fails.", m_name, (split ? "one of your" : "your"), o_name); } else { /* Message */ msg("%s %s (%c) was stolen!", (split ? "One of your" : "Your"), o_name, I2A(index)); /* Steal and carry */ stolen = gear_object_for_use(obj, 1, false, &none_left); (void)monster_carry(cave, context->mon, stolen); } /* Obvious */ context->obvious = true; /* Blink away */ context->blinked = true; /* Done */ break; } } /** * Get the elemental damage taken by a monster from another monster's melee */ static int monster_elemental_damage(melee_effect_handler_context_t *context, int type, enum mon_messages *hurt_msg, enum mon_messages *die_msg) { struct monster_lore *lore = get_lore(context->t_mon->race); int hurt_flag = RF_NONE; int imm_flag = RF_NONE; int damage = 0; /* Deal with elemental types */ switch (type) { case PROJ_ACID: { imm_flag = RF_IM_ACID; break; } case PROJ_ELEC: { imm_flag = RF_IM_ELEC; break; } case PROJ_FIRE: { imm_flag = RF_IM_FIRE; hurt_flag = RF_HURT_FIRE; *hurt_msg = MON_MSG_CATCH_FIRE; *die_msg = MON_MSG_DISINTEGRATES; break; } case PROJ_COLD: { imm_flag = RF_IM_COLD; hurt_flag = RF_HURT_FIRE; *hurt_msg = MON_MSG_BADLY_FROZEN; *die_msg = MON_MSG_FREEZE_SHATTER; break; } case PROJ_POIS: { imm_flag = RF_IM_POIS; break; } default: return 0; } rf_on(lore->flags, imm_flag); rf_on(lore->flags, hurt_flag); if (rf_has(context->t_mon->race->flags, imm_flag)) { *hurt_msg = MON_MSG_RESIST_A_LOT; damage = context->damage / 9; } else if (rf_has(context->t_mon->race->flags, hurt_flag)) { damage = context->damage * 2; } return damage; } /** * Deal damage to a monster from another monster. * * This is a helper for melee handlers. It is very similar to mon_take_hit(), * but eliminates the player-oriented stuff of that function. * * \param context is the project_m context. * \param hurt_msg is the message if the monster is hurt (if any). * \return true if the monster died, false if it is still alive. */ static bool monster_melee_monster(melee_effect_handler_context_t *context, enum mon_messages hurt_msg, enum mon_messages die_msg) { int dam = context->damage; struct monster *t_mon = context->t_mon; /* "Unique" monsters can only be "killed" by the player */ if (rf_has(t_mon->race->flags, RF_UNIQUE)) { /* Reduce monster hp to zero, but don't kill it. */ if (dam > t_mon->hp) dam = t_mon->hp; } /* Redraw (later) if needed */ if (player->upkeep->health_who == t_mon) player->upkeep->redraw |= (PR_HEALTH); /* Wake the monster up */ mon_clear_timed(t_mon, MON_TMD_SLEEP, MON_TMD_FLG_NOMESSAGE, false); /* Hurt the monster */ t_mon->hp -= dam; /* Dead or damaged monster */ if (t_mon->hp < 0) { /* Death message */ add_monster_message(t_mon, die_msg, false); /* Generate treasure, etc */ monster_death(t_mon, false); /* Delete the monster */ delete_monster_idx(t_mon->midx); return true; } else if (!monster_is_mimicking(t_mon)) { /* Give detailed messages if visible */ if (hurt_msg != MON_MSG_NONE) { add_monster_message(t_mon, hurt_msg, false); } else if (dam > 0) { message_pain(t_mon, dam); } } /* Sometimes a monster gets scared by damage */ if (!t_mon->m_timed[MON_TMD_FEAR] && !rf_has(t_mon->race->flags, RF_NO_FEAR) && dam > 0) { int percentage; /* Percentage of fully healthy */ percentage = (100L * t_mon->hp) / t_mon->maxhp; /* Run (sometimes) if at 10% or less of max hit points, * or (usually) when hit for half its current hit points */ if ((randint1(10) >= percentage) || ((dam >= t_mon->hp) && (randint0(100) < 80))) { int timer = randint1(10) + (((dam >= t_mon->hp) && (percentage > 7)) ? 20 : ((11 - percentage) * 5)); mon_inc_timed(t_mon, MON_TMD_FEAR, timer, MON_TMD_FLG_NOMESSAGE | MON_TMD_FLG_NOFAIL, false); } } return false; } /** * Deal the actual melee damage from a monster to a target player or monster * * This function is used in handlers where there is no further processing of * a monster after damage, so we always return true for monster targets */ static bool monster_damage_target(melee_effect_handler_context_t *context, bool no_further_monster_effect) { /* Take damage */ if (context->p) { take_hit(context->p, context->damage, context->ddesc); if (context->p->is_dead) return true; } else { bool dead = false; assert(context->t_mon); dead = monster_melee_monster(context, MON_MSG_NONE, MON_MSG_DIE); return (dead || no_further_monster_effect); } return false; } /** * ------------------------------------------------------------------------ * Monster blow multi-effect handlers * These are each called by several individual effect handlers * ------------------------------------------------------------------------ */ /** * Do damage as the result of a melee attack that has an elemental aspect. * * \param context is information for the current attack. * \param type is the PROJ_ constant for the element. * \param pure_element should be true if no side effects (mostly a hack * for poison). */ static void melee_effect_elemental(melee_effect_handler_context_t *context, int type, bool pure_element) { int physical_dam, elemental_dam; enum mon_messages hurt_msg = MON_MSG_NONE; enum mon_messages die_msg = MON_MSG_DIE; if (pure_element) /* Obvious */ context->obvious = true; if (context->p) { switch (type) { case PROJ_ACID: msg("You are covered in acid!"); break; case PROJ_ELEC: msg("You are struck by electricity!"); break; case PROJ_FIRE: msg("You are enveloped in flames!"); break; case PROJ_COLD: msg("You are covered with frost!"); break; } } /* Give a small bonus to ac for elemental attacks */ physical_dam = adjust_dam_armor(context->damage, context->ac + 50); /* Some attacks do no physical damage */ if (!context->method->phys) physical_dam = 0; if (context->p) { elemental_dam = adjust_dam(context->p, type, context->damage, RANDOMISE, 0, true); } else { assert(context->t_mon); elemental_dam = monster_elemental_damage(context, type, &hurt_msg, &die_msg); } /* Take the larger of physical or elemental damage */ context->damage = (physical_dam > elemental_dam) ? physical_dam : elemental_dam; if (context->p && elemental_dam > 0) inven_damage(context->p, type, MIN(elemental_dam * 5, 300)); if (context->damage > 0) { if (context->p) { take_hit(context->p, context->damage, context->ddesc); } else { assert(context->t_mon); (void) monster_melee_monster(context, hurt_msg, die_msg); } } /* Learn about the player */ if (pure_element && context->p) { update_smart_learn(context->mon, context->p, 0, 0, type); } } /** * Do damage as the result of a melee attack that has a status effect. * * \param context is the information for the current attack. * \param type is the TMD_ constant for the effect. * \param amount is the amount that the timer should be increased by. * \param of_flag is the OF_ flag that is passed on to monster learning for * this effect. * \param attempt_save indicates if a saving throw should be attempted for * this effect. * \param save_msg is the message that is displayed if the saving throw is * successful. */ static void melee_effect_timed(melee_effect_handler_context_t *context, int type, int amount, int of_flag, bool save, const char *save_msg) { /* Take damage */ if (monster_damage_target(context, false)) return; /* Handle status */ if (context->t_mon) { /* Translate to monster timed effect */ int mon_tmd_effect = -1; /* Will do until monster and player timed effects are fused */ switch (type) { case TMD_CONFUSED: { mon_tmd_effect = MON_TMD_CONF; break; } case TMD_PARALYZED: { mon_tmd_effect = MON_TMD_HOLD; break; } case TMD_BLIND: { mon_tmd_effect = MON_TMD_STUN; break; } case TMD_AFRAID: { mon_tmd_effect = MON_TMD_FEAR; break; } default: { break; } } if (mon_tmd_effect >= 0) { mon_inc_timed(context->t_mon, mon_tmd_effect, amount, 0, false); context->obvious = true; } } else if (save && randint0(100) < context->p->state.skills[SKILL_SAVE]) { /* Attempt a saving throw if desired. */ if (save_msg != NULL) { msg("%s", save_msg); } context->obvious = true; } else { /* Increase timer for type. */ if (player_inc_timed(context->p, type, amount, true, true)) { context->obvious = true; } /* Learn about the player */ update_smart_learn(context->mon, context->p, of_flag, 0, -1); } } /** * Do damage as the result of a melee attack that drains a stat. * * \param context is the information for the current attack. * \param stat is the STAT_ constant for the desired stat. */ static void melee_effect_stat(melee_effect_handler_context_t *context, int stat) { /* Take damage */ if (monster_damage_target(context, true)) return; /* Damage (stat) */ effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", stat, 0, 0, 0, 0, &context->obvious); } /** * Do damage as the result of an experience draining melee attack. * * \param context is the information for the current attack. * \param chance is the player's chance of resisting drain if they have * OF_HOLD_LIFE. * \param drain_amount is the base amount of experience to drain. */ static void melee_effect_experience(melee_effect_handler_context_t *context, int chance, int drain_amount) { /* Take damage */ if (context->p) { take_hit(context->p, context->damage, context->ddesc); context->obvious = true; update_smart_learn(context->mon, context->p, OF_HOLD_LIFE, 0, -1); if (context->p->is_dead) return; } else { assert(context->t_mon); (void) monster_melee_monster(context, MON_MSG_NONE, MON_MSG_DIE); return; } if (player_of_has(context->p, OF_HOLD_LIFE) && (randint0(100) < chance)) { msg("You keep hold of your life force!"); } else { s32b d = drain_amount + (context->p->exp/100) * z_info->life_drain_percent; if (player_of_has(context->p, OF_HOLD_LIFE)) { msg("You feel your life slipping away!"); player_exp_lose(context->p, d / 10, false); } else { msg("You feel your life draining away!"); player_exp_lose(context->p, d, false); } } } /** * ------------------------------------------------------------------------ * Monster blow effect handlers * ------------------------------------------------------------------------ */ /** * Melee effect handler: Hit the player, but don't do any damage. */ static void melee_effect_handler_NONE(melee_effect_handler_context_t *context) { context->obvious = true; context->damage = 0; } /** * Melee effect handler: Hurt the player with no side effects. */ static void melee_effect_handler_HURT(melee_effect_handler_context_t *context) { /* Obvious */ context->obvious = true; /* Armor reduces total damage */ context->damage = adjust_dam_armor(context->damage, context->ac); /* Take damage */ (void) monster_damage_target(context, true); } /** * Melee effect handler: Poison the player. * * We can't use melee_effect_timed(), because this is both and elemental attack * and a status attack. Note the false value for pure_element for * melee_effect_elemental(). */ static void melee_effect_handler_POISON(melee_effect_handler_context_t *context) { melee_effect_elemental(context, PROJ_POIS, false); /* Player is dead or not attacked */ if (!context->p || context->p->is_dead) return; /* Take "poison" effect */ if (player_inc_timed(context->p, TMD_POISONED, 5 + randint1(context->rlev), true, true)) context->obvious = true; /* Learn about the player */ update_smart_learn(context->mon, context->p, 0, 0, ELEM_POIS); } /** * Melee effect handler: Disenchant the player. */ static void melee_effect_handler_DISENCHANT(melee_effect_handler_context_t *context) { /* Take damage */ if (monster_damage_target(context, true)) return; /* Apply disenchantment if no resist */ if (!player_resists(context->p, ELEM_DISEN)) effect_simple(EF_DISENCHANT, source_monster(context->mon->midx), "0", 0, 0, 0, 0, 0, &context->obvious); /* Learn about the player */ update_smart_learn(context->mon, context->p, 0, 0, ELEM_DISEN); } /** * Melee effect handler: Drain charges from the player's inventory. */ static void melee_effect_handler_DRAIN_CHARGES(melee_effect_handler_context_t *context) { struct object *obj; struct monster *monster = context->mon; struct player *current_player = context->p; int tries; int unpower = 0, newcharge; /* Take damage */ if (monster_damage_target(context, true)) return; /* Find an item */ for (tries = 0; tries < 10; tries++) { /* Pick an item */ obj = context->p->upkeep->inven[randint0(z_info->pack_size)]; /* Skip non-objects */ if (obj == NULL) continue; /* Drain charged wands/staves */ if (tval_can_have_charges(obj)) { /* Charged? */ if (obj->pval) { /* Get number of charge to drain */ unpower = (context->rlev / (obj->kind->level + 2)) + 1; /* Get new charge value, don't allow negative */ newcharge = MAX((obj->pval - unpower),0); /* Remove the charges */ obj->pval = newcharge; } } if (unpower) { int heal = context->rlev * unpower; msg("Energy drains from your pack!"); context->obvious = true; /* Don't heal more than max hp */ heal = MIN(heal, monster->maxhp - monster->hp); /* Heal */ monster->hp += heal; /* Redraw (later) if needed */ if (current_player->upkeep->health_who == monster) current_player->upkeep->redraw |= (PR_HEALTH); /* Combine the pack */ current_player->upkeep->notice |= (PN_COMBINE); /* Redraw stuff */ current_player->upkeep->redraw |= (PR_INVEN); /* Affect only a single inventory slot */ break; } } } /** * Melee effect handler: Take the player's gold. */ static void melee_effect_handler_EAT_GOLD(melee_effect_handler_context_t *context) { struct player *current_player = context->p; /* Take damage */ if (monster_damage_target(context, true)) return; /* Obvious */ context->obvious = true; /* Attempt saving throw (unless paralyzed) based on dex and level */ if (!current_player->timed[TMD_PARALYZED] && (randint0(100) < (adj_dex_safe[current_player->state.stat_ind[STAT_DEX]] + current_player->lev))) { /* Saving throw message */ msg("You quickly protect your money pouch!"); /* Occasional blink anyway */ if (randint0(3)) context->blinked = true; } else { s32b gold = (current_player->au / 10) + randint1(25); if (gold < 2) gold = 2; if (gold > 5000) gold = (current_player->au / 20) + randint1(3000); if (gold > current_player->au) gold = current_player->au; current_player->au -= gold; if (gold <= 0) { msg("Nothing was stolen."); return; } /* Let the player know they were robbed */ msg("Your purse feels lighter."); if (current_player->au) msg("%d coins were stolen!", gold); else msg("All of your coins were stolen!"); /* While we have gold, put it in objects */ while (gold > 0) { int amt; /* Create a new temporary object */ struct object *obj = object_new(); object_prep(obj, money_kind("gold", gold), 0, MINIMISE); /* Amount of gold to put in this object */ amt = gold > MAX_PVAL ? MAX_PVAL : gold; obj->pval = amt; gold -= amt; /* Set origin to stolen, so it is not confused with * dropped treasure in monster_death */ obj->origin = ORIGIN_STOLEN; obj->origin_depth = current_player->depth; /* Give the gold to the monster */ monster_carry(cave, context->mon, obj); } /* Redraw gold */ current_player->upkeep->redraw |= (PR_GOLD); /* Blink away */ context->blinked = true; } } /** * Melee effect handler: Take something from the player's inventory. */ static void melee_effect_handler_EAT_ITEM(melee_effect_handler_context_t *context) { /* Take damage */ if (monster_damage_target(context, false)) return; /* Steal from player or monster */ if (context->p) { int chance = adj_dex_safe[context->p->state.stat_ind[STAT_DEX]] + context->p->lev; /* Saving throw (unless paralyzed) based on dex and level */ if (!context->p->timed[TMD_PARALYZED] && (randint0(100) < chance)) { /* Saving throw message */ msg("You grab hold of your backpack!"); /* Occasional "blink" anyway */ context->blinked = true; /* Obvious */ context->obvious = true; /* Done */ return; } /* Try to steal an item */ steal_player_item(context); } else { assert(context->t_mon); steal_monster_item(context->t_mon, context->mon->midx); context->obvious = true; } } /** * Melee effect handler: Eat the player's food. */ static void melee_effect_handler_EAT_FOOD(melee_effect_handler_context_t *context) { int tries; /* Take damage */ if (monster_damage_target(context, true)) return; /* Steal some food */ for (tries = 0; tries < 10; tries++) { /* Pick an item from the pack */ int index = randint0(z_info->pack_size); struct object *obj, *eaten; char o_name[80]; bool none_left = false; /* Get the item */ obj = context->p->upkeep->inven[index]; /* Skip non-objects */ if (obj == NULL) continue; /* Skip non-food objects */ if (!tval_is_edible(obj)) continue; if (obj->number == 1) { object_desc(o_name, sizeof(o_name), obj, ODESC_BASE); msg("Your %s (%c) was eaten!", o_name, I2A(index)); } else { object_desc(o_name, sizeof(o_name), obj, ODESC_PREFIX | ODESC_BASE); msg("One of your %s (%c) was eaten!", o_name, I2A(index)); } /* Steal and eat */ eaten = gear_object_for_use(obj, 1, false, &none_left); if (eaten->known) object_delete(&eaten->known); object_delete(&eaten); /* Obvious */ context->obvious = true; /* Done */ break; } } /** * Melee effect handler: Absorb the player's light. */ static void melee_effect_handler_EAT_LIGHT(melee_effect_handler_context_t *context) { /* Take damage */ if (monster_damage_target(context, true)) return; /* Drain the light source */ effect_simple(EF_DRAIN_LIGHT, source_monster(context->mon->midx), "250+1d250", 0, 0, 0, 0, 0, &context->obvious); } /** * Melee effect handler: Attack the player with acid. */ static void melee_effect_handler_ACID(melee_effect_handler_context_t *context) { melee_effect_elemental(context, PROJ_ACID, true); } /** * Melee effect handler: Attack the player with electricity. */ static void melee_effect_handler_ELEC(melee_effect_handler_context_t *context) { melee_effect_elemental(context, PROJ_ELEC, true); } /** * Melee effect handler: Attack the player with fire. */ static void melee_effect_handler_FIRE(melee_effect_handler_context_t *context) { melee_effect_elemental(context, PROJ_FIRE, true); } /** * Melee effect handler: Attack the player with cold. */ static void melee_effect_handler_COLD(melee_effect_handler_context_t *context) { melee_effect_elemental(context, PROJ_COLD, true); } /** * Melee effect handler: Blind the player. */ static void melee_effect_handler_BLIND(melee_effect_handler_context_t *context) { melee_effect_timed(context, TMD_BLIND, 10 + randint1(context->rlev), OF_PROT_BLIND, false, NULL); } /** * Melee effect handler: Confuse the player. */ static void melee_effect_handler_CONFUSE(melee_effect_handler_context_t *context) { melee_effect_timed(context, TMD_CONFUSED, 3 + randint1(context->rlev), OF_PROT_CONF, false, NULL); } /** * Melee effect handler: Terrify the player. */ static void melee_effect_handler_TERRIFY(melee_effect_handler_context_t *context) { melee_effect_timed(context, TMD_AFRAID, 3 + randint1(context->rlev), OF_PROT_FEAR, true, "You stand your ground!"); } /** * Melee effect handler: Paralyze the player. */ static void melee_effect_handler_PARALYZE(melee_effect_handler_context_t *context) { /* Hack -- Prevent perma-paralysis via damage */ if (context->p->timed[TMD_PARALYZED] && (context->damage < 1)) context->damage = 1; melee_effect_timed(context, TMD_PARALYZED, 3 + randint1(context->rlev), OF_FREE_ACT, true, "You resist the effects!"); } /** * Melee effect handler: Drain the player's strength. */ static void melee_effect_handler_LOSE_STR(melee_effect_handler_context_t *context) { melee_effect_stat(context, STAT_STR); } /** * Melee effect handler: Drain the player's intelligence. */ static void melee_effect_handler_LOSE_INT(melee_effect_handler_context_t *context) { melee_effect_stat(context, STAT_INT); } /** * Melee effect handler: Drain the player's wisdom. */ static void melee_effect_handler_LOSE_WIS(melee_effect_handler_context_t *context) { melee_effect_stat(context, STAT_WIS); } /** * Melee effect handler: Drain the player's dexterity. */ static void melee_effect_handler_LOSE_DEX(melee_effect_handler_context_t *context) { melee_effect_stat(context, STAT_DEX); } /** * Melee effect handler: Drain the player's constitution. */ static void melee_effect_handler_LOSE_CON(melee_effect_handler_context_t *context) { melee_effect_stat(context, STAT_CON); } /** * Melee effect handler: Drain all of the player's stats. */ static void melee_effect_handler_LOSE_ALL(melee_effect_handler_context_t *context) { /* Take damage */ if (monster_damage_target(context, true)) return; /* Damage (stats) */ effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", STAT_STR, 0, 0, 0, 0, &context->obvious); effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", STAT_DEX, 0, 0, 0, 0, &context->obvious); effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", STAT_CON, 0, 0, 0, 0, &context->obvious); effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", STAT_INT, 0, 0, 0, 0, &context->obvious); effect_simple(EF_DRAIN_STAT, source_monster(context->mon->midx), "0", STAT_WIS, 0, 0, 0, 0, &context->obvious); } /** * Melee effect handler: Cause an earthquake around the player. */ static void melee_effect_handler_SHATTER(melee_effect_handler_context_t *context) { /* Obvious */ context->obvious = true; /* Hack -- Reduce damage based on the player armor class */ context->damage = adjust_dam_armor(context->damage, context->ac); /* Take damage */ if (monster_damage_target(context, false)) return; /* Radius 8 earthquake centered at the monster */ if (context->damage > 23) { effect_simple(EF_EARTHQUAKE, source_monster(context->mon->midx), "0", 0, 8, 0, 0, 0, NULL); } } /** * Melee effect handler: Drain the player's experience. */ static void melee_effect_handler_EXP_10(melee_effect_handler_context_t *context) { melee_effect_experience(context, 95, damroll(10, 6)); } /** * Melee effect handler: Drain the player's experience. */ static void melee_effect_handler_EXP_20(melee_effect_handler_context_t *context) { melee_effect_experience(context, 90, damroll(20, 6)); } /** * Melee effect handler: Drain the player's experience. */ static void melee_effect_handler_EXP_40(melee_effect_handler_context_t *context) { melee_effect_experience(context, 75, damroll(40, 6)); } /** * Melee effect handler: Drain the player's experience. */ static void melee_effect_handler_EXP_80(melee_effect_handler_context_t *context) { melee_effect_experience(context, 50, damroll(80, 6)); } /** * Melee effect handler: Make the player hallucinate. * * Note that we don't use melee_effect_timed(), due to the different monster * learning function. */ static void melee_effect_handler_HALLU(melee_effect_handler_context_t *context) { /* Take damage */ if (monster_damage_target(context, true)) return; /* Increase "image" */ if (player_inc_timed(context->p, TMD_IMAGE, 3 + randint1(context->rlev / 2), true, true)) context->obvious = true; /* Learn about the player */ update_smart_learn(context->mon, context->p, 0, 0, ELEM_CHAOS); } /** * ------------------------------------------------------------------------ * Monster blow melee handler selection * ------------------------------------------------------------------------ */ melee_effect_handler_f melee_handler_for_blow_effect(const char *name) { static const struct effect_handler_s { const char *name; melee_effect_handler_f function; } effect_handlers[] = { { "NONE", melee_effect_handler_NONE }, { "HURT", melee_effect_handler_HURT }, { "POISON", melee_effect_handler_POISON }, { "DISENCHANT", melee_effect_handler_DISENCHANT }, { "DRAIN_CHARGES", melee_effect_handler_DRAIN_CHARGES }, { "EAT_GOLD", melee_effect_handler_EAT_GOLD }, { "EAT_ITEM", melee_effect_handler_EAT_ITEM }, { "EAT_FOOD", melee_effect_handler_EAT_FOOD }, { "EAT_LIGHT", melee_effect_handler_EAT_LIGHT }, { "ACID", melee_effect_handler_ACID }, { "ELEC", melee_effect_handler_ELEC }, { "FIRE", melee_effect_handler_FIRE }, { "COLD", melee_effect_handler_COLD }, { "BLIND", melee_effect_handler_BLIND }, { "CONFUSE", melee_effect_handler_CONFUSE }, { "TERRIFY", melee_effect_handler_TERRIFY }, { "PARALYZE", melee_effect_handler_PARALYZE }, { "LOSE_STR", melee_effect_handler_LOSE_STR }, { "LOSE_INT", melee_effect_handler_LOSE_INT }, { "LOSE_WIS", melee_effect_handler_LOSE_WIS }, { "LOSE_DEX", melee_effect_handler_LOSE_DEX }, { "LOSE_CON", melee_effect_handler_LOSE_CON }, { "LOSE_ALL", melee_effect_handler_LOSE_ALL }, { "SHATTER", melee_effect_handler_SHATTER }, { "EXP_10", melee_effect_handler_EXP_10 }, { "EXP_20", melee_effect_handler_EXP_20 }, { "EXP_40", melee_effect_handler_EXP_40 }, { "EXP_80", melee_effect_handler_EXP_80 }, { "HALLU", melee_effect_handler_HALLU }, { NULL, NULL }, }; const struct effect_handler_s *current = effect_handlers; while (current->name != NULL && current->function != NULL) { if (my_stricmp(name, current->name) == 0) return current->function; current++; } return NULL; }
27.28596
112
0.657944
[ "object" ]
e72ae7087bdd4c7b2939bd16b437d4593af791ee
21,462
c
C
test_conformance/compatibility/test_conformance/basic/test_bufferreadwriterect.c
svenvh/OpenCL-CTS
509172b7805aca2514081e259b6f26cb74a3445a
[ "Apache-2.0" ]
1
2020-06-05T04:01:03.000Z
2020-06-05T04:01:03.000Z
test_conformance/compatibility/test_conformance/basic/test_bufferreadwriterect.c
svenvh/OpenCL-CTS
509172b7805aca2514081e259b6f26cb74a3445a
[ "Apache-2.0" ]
null
null
null
test_conformance/compatibility/test_conformance/basic/test_bufferreadwriterect.c
svenvh/OpenCL-CTS
509172b7805aca2514081e259b6f26cb74a3445a
[ "Apache-2.0" ]
3
2020-10-26T02:53:08.000Z
2021-02-12T14:59:41.000Z
// // Copyright (c) 2017 The Khronos Group Inc. // // 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 "../../test_common/harness/compat.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "procs.h" #define CL_EXIT_ERROR(cmd,format,...) \ { \ if ((cmd) != CL_SUCCESS) { \ log_error("CL ERROR: %s %u: ", __FILE__,__LINE__); \ log_error(format,## __VA_ARGS__ ); \ log_error("\n"); \ /*abort();*/ \ } \ } typedef unsigned char BufferType; // Globals for test cl_command_queue queue; // Width and height of each pair of images. enum { TotalImages = 8 }; size_t width [TotalImages]; size_t height [TotalImages]; size_t depth [TotalImages]; // cl buffer and host buffer. cl_mem buffer [TotalImages]; BufferType* verify[TotalImages]; BufferType* backing[TotalImages]; // Temporary buffer used for read and write operations. BufferType* tmp_buffer; size_t tmp_buffer_size; size_t num_tries = 50; // Number of randomly selected operations to perform. size_t alloc_scale = 2; // Scale term applied buffer allocation size. MTdata mt; // Initialize a buffer in host memory containing random values of the specified size. static void initialize_image(BufferType* ptr, size_t w, size_t h, size_t d, MTdata mt) { enum { ElementSize = sizeof(BufferType)/sizeof(unsigned char) }; unsigned char* buf = (unsigned char*)ptr; size_t size = w*h*d*ElementSize; for (size_t i = 0; i != size; i++) { buf[i] = (unsigned char)(genrand_int32(mt) % 0xff); } } // This function prints the contents of a buffer to standard error. void print_buffer(BufferType* buf, size_t w, size_t h, size_t d) { log_error("Size = %lux%lux%lu (%lu total)\n",w,h,d,w*h*d); for (unsigned k=0; k!=d;++k) { log_error("Slice: %u\n",k); for (unsigned j=0; j!=h;++j) { for (unsigned i=0;i!=w;++i) { log_error("%02x",buf[k*(w*h)+j*w+i]); } log_error("\n"); } log_error("\n"); } } // Returns true if the two specified regions overlap. bool check_overlap(const size_t src_offset[3], const size_t dst_offset[3], const size_t region[3]) { const size_t src_min[] = {src_offset[0], src_offset[1], src_offset[2]}; const size_t src_max[] = {src_offset[0]+region[0], src_offset[1]+region[1], src_offset[2]+region[2]}; const size_t dst_min[] = {dst_offset[0], dst_offset[1], dst_offset[2]}; const size_t dst_max[] = {dst_offset[0]+region[0], dst_offset[1]+region[1], dst_offset[2]+region[2]}; // Check for overlap, using the span space formulation. bool overlap = true; unsigned i; for (i=0; i != 3; ++i) { overlap = overlap && (src_min[i] < dst_max[i]) && (src_max[i] > dst_min[i]); } return overlap; } // This function invokes the CopyBufferRect CL command and then mirrors the operation on the host side verify buffers. int copy_region(size_t src, size_t soffset[3], size_t sregion[3], size_t dst, size_t doffset[3], size_t dregion[3]) { // Copy between cl buffers. size_t src_slice_pitch = (width[src]*height[src] != 1) ? width[src]*height[src] : 0; size_t dst_slice_pitch = (width[dst]*height[dst] != 1) ? width[dst]*height[dst] : 0; cl_int err; if (check_overlap(soffset,doffset,sregion)) { log_info( "Copy overlap reported, skipping copy buffer rect\n" ); return CL_SUCCESS; } else { if ((err = clEnqueueCopyBufferRect(queue, buffer[src],buffer[dst], soffset, doffset, sregion,/*dregion,*/ width[src], src_slice_pitch, width[dst], dst_slice_pitch, 0, NULL, NULL)) != CL_SUCCESS) { CL_EXIT_ERROR(err, "clEnqueueCopyBufferRect failed between %u and %u",(unsigned)src,(unsigned)dst); } } // Copy between host buffers. size_t total = sregion[0] * sregion[1] * sregion[2]; size_t spitch = width[src]; size_t sslice = width[src]*height[src]; size_t dpitch = width[dst]; size_t dslice = width[dst]*height[dst]; for (size_t i = 0; i != total; ++i) { // Compute the coordinates of the element within the source and destination regions. size_t rslice = sregion[0]*sregion[1]; size_t sz = i / rslice; size_t sy = (i % rslice) / sregion[0]; size_t sx = (i % rslice) % sregion[0]; size_t dz = sz; size_t dy = sy; size_t dx = sx; // Compute the offset in bytes of the source and destination. size_t s_idx = (soffset[2]+sz)*sslice + (soffset[1]+sy)*spitch + soffset[0]+sx; size_t d_idx = (doffset[2]+dz)*dslice + (doffset[1]+dy)*dpitch + doffset[0]+dx; verify[dst][d_idx] = verify[src][s_idx]; } return 0; } // This function compares the destination region in the buffer pointed // to by device, to the source region of the specified verify buffer. int verify_region(BufferType* device, size_t src, size_t soffset[3], size_t sregion[3], size_t dst, size_t doffset[3]) { // Copy between host buffers. size_t spitch = width[src]; size_t sslice = width[src]*height[src]; size_t dpitch = width[dst]; size_t dslice = width[dst]*height[dst]; size_t total = sregion[0] * sregion[1] * sregion[2]; for (size_t i = 0; i != total; ++i) { // Compute the coordinates of the element within the source and destination regions. size_t rslice = sregion[0]*sregion[1]; size_t sz = i / rslice; size_t sy = (i % rslice) / sregion[0]; size_t sx = (i % rslice) % sregion[0]; // Compute the offset in bytes of the source and destination. size_t s_idx = (soffset[2]+sz)*sslice + (soffset[1]+sy)*spitch + soffset[0]+sx; size_t d_idx = (doffset[2]+sz)*dslice + (doffset[1]+sy)*dpitch + doffset[0]+sx; if (device[d_idx] != verify[src][s_idx]) { log_error("Verify failed on comparsion %lu: coordinate (%lu, %lu, %lu) of region\n",i,sx,sy,sz); log_error("0x%02x != 0x%02x\n", device[d_idx], verify[src][s_idx]); #if 0 // Uncomment this section to print buffers. log_error("Device (copy): [%lu]\n",dst); print_buffer(device,width[dst],height[dst],depth[dst]); log_error("\n"); log_error("Verify: [%lu]\n",src); print_buffer(verify[src],width[src],height[src],depth[src]); log_error("\n"); abort(); #endif return -1; } } return 0; } // This function invokes ReadBufferRect to read a region from the // specified source buffer into a temporary destination buffer. The // contents of the temporary buffer are then compared to the source // region of the corresponding verify buffer. int read_verify_region(size_t src, size_t soffset[3], size_t sregion[3], size_t dst, size_t doffset[3], size_t dregion[3]) { // Clear the temporary destination host buffer. memset(tmp_buffer, 0xff, tmp_buffer_size); size_t src_slice_pitch = (width[src]*height[src] != 1) ? width[src]*height[src] : 0; size_t dst_slice_pitch = (width[dst]*height[dst] != 1) ? width[dst]*height[dst] : 0; // Copy the source region of the cl buffer, to the destination region of the temporary buffer. CL_EXIT_ERROR(clEnqueueReadBufferRect(queue, buffer[src], CL_TRUE, soffset,doffset, sregion, width[src], src_slice_pitch, width[dst], dst_slice_pitch, tmp_buffer, 0, NULL, NULL), "clEnqueueCopyBufferRect failed between %u and %u",(unsigned)src,(unsigned)dst); return verify_region(tmp_buffer,src,soffset,sregion,dst,doffset); } // This function performs the same verification check as // read_verify_region, except a MapBuffer command is used to access the // device buffer data instead of a ReadBufferRect, and the whole // buffer is checked. int map_verify_region(size_t src) { size_t size_bytes = width[src]*height[src]*depth[src]*sizeof(BufferType); // Copy the source region of the cl buffer, to the destination region of the temporary buffer. cl_int err; BufferType* mapped = (BufferType*)clEnqueueMapBuffer(queue,buffer[src],CL_TRUE,CL_MAP_READ,0,size_bytes,0,NULL,NULL,&err); CL_EXIT_ERROR(err, "clEnqueueMapBuffer failed for buffer %u",(unsigned)src); size_t soffset[] = { 0, 0, 0 }; size_t sregion[] = { width[src], height[src], depth[src] }; int ret = verify_region(mapped,src,soffset,sregion,src,soffset); CL_EXIT_ERROR(clEnqueueUnmapMemObject(queue,buffer[src],mapped,0,NULL,NULL), "clEnqueueUnmapMemObject failed for buffer %u",(unsigned)src); return ret; } // This function generates a new temporary buffer and then writes a // region of it to a region in the specified destination buffer. int write_region(size_t src, size_t soffset[3], size_t sregion[3], size_t dst, size_t doffset[3], size_t dregion[3]) { initialize_image(tmp_buffer, tmp_buffer_size, 1, 1, mt); // memset(tmp_buffer, 0xf0, tmp_buffer_size); size_t src_slice_pitch = (width[src]*height[src] != 1) ? width[src]*height[src] : 0; size_t dst_slice_pitch = (width[dst]*height[dst] != 1) ? width[dst]*height[dst] : 0; // Copy the source region of the cl buffer, to the destination region of the temporary buffer. CL_EXIT_ERROR(clEnqueueWriteBufferRect(queue, buffer[dst], CL_TRUE, doffset,soffset, /*sregion,*/dregion, width[dst], dst_slice_pitch, width[src], src_slice_pitch, tmp_buffer, 0, NULL, NULL), "clEnqueueWriteBufferRect failed between %u and %u",(unsigned)src,(unsigned)dst); // Copy from the temporary buffer to the host buffer. size_t spitch = width[src]; size_t sslice = width[src]*height[src]; size_t dpitch = width[dst]; size_t dslice = width[dst]*height[dst]; size_t total = sregion[0] * sregion[1] * sregion[2]; for (size_t i = 0; i != total; ++i) { // Compute the coordinates of the element within the source and destination regions. size_t rslice = sregion[0]*sregion[1]; size_t sz = i / rslice; size_t sy = (i % rslice) / sregion[0]; size_t sx = (i % rslice) % sregion[0]; size_t dz = sz; size_t dy = sy; size_t dx = sx; // Compute the offset in bytes of the source and destination. size_t s_idx = (soffset[2]+sz)*sslice + (soffset[1]+sy)*spitch + soffset[0]+sx; size_t d_idx = (doffset[2]+dz)*dslice + (doffset[1]+dy)*dpitch + doffset[0]+dx; verify[dst][d_idx] = tmp_buffer[s_idx]; } return 0; } void CL_CALLBACK mem_obj_destructor_callback( cl_mem, void *data ) { free( data ); } // This is the main test function for the conformance test. int test_bufferreadwriterect(cl_device_id device, cl_context context, cl_command_queue queue_, int num_elements) { queue = queue_; cl_int err; // Initialize the random number generator. mt = init_genrand( gRandomSeed ); // Compute a maximum buffer size based on the number of test images and the device maximum. cl_ulong max_mem_alloc_size = 0; CL_EXIT_ERROR(clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_mem_alloc_size, NULL),"Could not get device info"); log_info("CL_DEVICE_MAX_MEM_ALLOC_SIZE = %llu bytes.\n", max_mem_alloc_size); // Confirm that the maximum allocation size is not zero. if (max_mem_alloc_size == 0) { log_error("Error: CL_DEVICE_MAX_MEM_ALLOC_SIZE is zero bytes\n"); return -1; } // Guess at a reasonable maximum dimension. size_t max_mem_alloc_dim = (size_t)cbrt((double)(max_mem_alloc_size/sizeof(BufferType)))/alloc_scale; if (max_mem_alloc_dim == 0) { max_mem_alloc_dim = max_mem_alloc_size; } log_info("Using maximum dimension = %lu.\n", max_mem_alloc_dim); // Create pairs of cl buffers and host buffers on which operations will be mirrored. log_info("Creating %u pairs of random sized host and cl buffers.\n", TotalImages); size_t max_size = 0; size_t total_bytes = 0; for (unsigned i=0; i != TotalImages; ++i) { // Determine a width and height for this buffer. size_t size_bytes; size_t tries = 0; size_t max_tries = 1048576; do { width[i] = get_random_size_t(1, max_mem_alloc_dim, mt); height[i] = get_random_size_t(1, max_mem_alloc_dim, mt); depth[i] = get_random_size_t(1, max_mem_alloc_dim, mt); ++tries; } while ((tries < max_tries) && (size_bytes = width[i]*height[i]*depth[i]*sizeof(BufferType)) > max_mem_alloc_size); // Check to see if adequately sized buffers were found. if (tries >= max_tries) { log_error("Error: Could not find random buffer sized less than %llu bytes in %lu tries.\n", max_mem_alloc_size, max_tries); return -1; } // Keep track of the dimensions of the largest buffer. max_size = (size_bytes > max_size) ? size_bytes : max_size; total_bytes += size_bytes; log_info("Buffer[%u] is (%lu,%lu,%lu) = %lu MB (truncated)\n",i,width[i],height[i],depth[i],(size_bytes)/1048576); } log_info( "Total size: %lu MB (truncated)\n", total_bytes/1048576 ); // Allocate a temporary buffer for read and write operations. tmp_buffer_size = max_size; tmp_buffer = (BufferType*)malloc(tmp_buffer_size); // Initialize cl buffers log_info( "Initializing buffers\n" ); for (unsigned i=0; i != TotalImages; ++i) { size_t size_bytes = width[i]*height[i]*depth[i]*sizeof(BufferType); // Allocate a host copy of the buffer for verification. verify[i] = (BufferType*)malloc(size_bytes); CL_EXIT_ERROR(verify[i] ? CL_SUCCESS : -1, "malloc of host buffer failed for buffer %u", i); // Allocate the buffer in host memory. backing[i] = (BufferType*)malloc(size_bytes); CL_EXIT_ERROR(backing[i] ? CL_SUCCESS : -1, "malloc of backing buffer failed for buffer %u", i); // Generate a random buffer. log_info( "Initializing buffer %u\n", i ); initialize_image(verify[i], width[i], height[i], depth[i], mt); // Copy the image into a buffer which will passed to CL. memcpy(backing[i], verify[i], size_bytes); // Create the CL buffer. buffer[i] = clCreateBuffer (context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, size_bytes, backing[i], &err); CL_EXIT_ERROR(err,"clCreateBuffer failed for buffer %u", i); // Make sure buffer is cleaned up appropriately if we encounter an error in the rest of the calls. err = clSetMemObjectDestructorCallback( buffer[i], mem_obj_destructor_callback, backing[i] ); CL_EXIT_ERROR(err, "Unable to set mem object destructor callback" ); } // Main test loop, run num_tries times. log_info( "Executing %u test operations selected at random.\n", (unsigned)num_tries ); for (size_t iter = 0; iter < num_tries; ++iter) { // Determine a source and a destination. size_t src = get_random_size_t(0,TotalImages,mt); size_t dst = get_random_size_t(0,TotalImages,mt); // Determine the minimum dimensions. size_t min_width = width[src] < width[dst] ? width[src] : width[dst]; size_t min_height = height[src] < height[dst] ? height[src] : height[dst]; size_t min_depth = depth[src] < depth[dst] ? depth[src] : depth[dst]; // Generate a random source rectangle within the minimum dimensions. size_t mx = get_random_size_t(0, min_width-1, mt); size_t my = get_random_size_t(0, min_height-1, mt); size_t mz = get_random_size_t(0, min_depth-1, mt); size_t sw = get_random_size_t(1, (min_width - mx), mt); size_t sh = get_random_size_t(1, (min_height - my), mt); size_t sd = get_random_size_t(1, (min_depth - mz), mt); size_t sx = get_random_size_t(0, width[src]-sw, mt); size_t sy = get_random_size_t(0, height[src]-sh, mt); size_t sz = get_random_size_t(0, depth[src]-sd, mt); size_t soffset[] = { sx, sy, sz }; size_t sregion[] = { sw, sh, sd }; // Generate a destination rectangle of the same size. size_t dw = sw; size_t dh = sh; size_t dd = sd; // Generate a random destination offset within the buffer. size_t dx = get_random_size_t(0, (width[dst] - dw), mt); size_t dy = get_random_size_t(0, (height[dst] - dh), mt); size_t dz = get_random_size_t(0, (depth[dst] - dd), mt); size_t doffset[] = { dx, dy, dz }; size_t dregion[] = { dw, dh, dd }; // Execute one of three operations: // - Copy: Copies between src and dst within each set of host, buffer, and images. // - Read & verify: Reads src region from buffer and image, and compares to host. // - Write: Generates new buffer with src dimensions, and writes to cl buffer and image. enum { TotalOperations = 3 }; size_t operation = get_random_size_t(0,TotalOperations,mt); switch (operation) { case 0: log_info("%lu Copy %lu offset (%lu,%lu,%lu) -> %lu offset (%lu,%lu,%lu) region (%lux%lux%lu = %lu)\n", iter, src, soffset[0], soffset[1], soffset[2], dst, doffset[0], doffset[1], doffset[2], sregion[0], sregion[1], sregion[2], sregion[0]*sregion[1]*sregion[2]); if ((err = copy_region(src, soffset, sregion, dst, doffset, dregion))) return err; break; case 1: log_info("%lu Read %lu offset (%lu,%lu,%lu) -> %lu offset (%lu,%lu,%lu) region (%lux%lux%lu = %lu)\n", iter, src, soffset[0], soffset[1], soffset[2], dst, doffset[0], doffset[1], doffset[2], sregion[0], sregion[1], sregion[2], sregion[0]*sregion[1]*sregion[2]); if ((err = read_verify_region(src, soffset, sregion, dst, doffset, dregion))) return err; break; case 2: log_info("%lu Write %lu offset (%lu,%lu,%lu) -> %lu offset (%lu,%lu,%lu) region (%lux%lux%lu = %lu)\n", iter, src, soffset[0], soffset[1], soffset[2], dst, doffset[0], doffset[1], doffset[2], sregion[0], sregion[1], sregion[2], sregion[0]*sregion[1]*sregion[2]); if ((err = write_region(src, soffset, sregion, dst, doffset, dregion))) return err; break; } #if 0 // Uncomment this section to verify each operation. // If commented out, verification won't occur until the end of the // test, and it will not be possible to determine which operation failed. log_info("Verify src %lu offset (%u,%u,%u) region (%lux%lux%lu)\n", src, 0, 0, 0, width[src], height[src], depth[src]); if (err = map_verify_region(src)) return err; log_info("Verify dst %lu offset (%u,%u,%u) region (%lux%lux%lu)\n", dst, 0, 0, 0, width[dst], height[dst], depth[dst]); if (err = map_verify_region(dst)) return err; #endif } // end main for loop. for (unsigned i=0;i<TotalImages;++i) { log_info("Verify %u offset (%u,%u,%u) region (%lux%lux%lu)\n", i, 0, 0, 0, width[i], height[i], depth[i]); if ((err = map_verify_region(i))) return err; } // Clean-up. free_mtdata(mt); for (unsigned i=0;i<TotalImages;++i) { free( verify[i] ); clReleaseMemObject( buffer[i] ); } free( tmp_buffer ); if (!err) { log_info("RECT read, write test passed\n"); } return err; }
40.49434
146
0.599012
[ "object" ]
e72b55e5c087d2f67fef60b64b472f9d6c4f6f20
6,383
h
C
src/rcl/event.h
cndabai/micro_ros
56676e56ceed07af4dedf1f92b8a4f4768691921
[ "Apache-2.0" ]
4
2021-07-29T03:01:04.000Z
2021-12-21T09:12:39.000Z
src/rcl/event.h
cndabai/micro_ros
56676e56ceed07af4dedf1f92b8a4f4768691921
[ "Apache-2.0" ]
null
null
null
src/rcl/event.h
cndabai/micro_ros
56676e56ceed07af4dedf1f92b8a4f4768691921
[ "Apache-2.0" ]
6
2021-06-14T15:55:19.000Z
2021-11-19T01:18:10.000Z
// Copyright 2019 Open Source Robotics Foundation, Inc. // // 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 #ifndef RCL__EVENT_H_ #define RCL__EVENT_H_ #ifdef __cplusplus extern "C" { #endif #include "rcl/client.h" #include "rcl/macros.h" #include "rcl/publisher.h" #include "rcl/service.h" #include "rcl/subscription.h" #include "rcl/visibility_control.h" /// Enumeration of all of the publisher events that may fire. typedef enum rcl_publisher_event_type_t { RCL_PUBLISHER_OFFERED_DEADLINE_MISSED, RCL_PUBLISHER_LIVELINESS_LOST, RCL_PUBLISHER_OFFERED_INCOMPATIBLE_QOS, } rcl_publisher_event_type_t; /// Enumeration of all of the subscription events that may fire. typedef enum rcl_subscription_event_type_t { RCL_SUBSCRIPTION_REQUESTED_DEADLINE_MISSED, RCL_SUBSCRIPTION_LIVELINESS_CHANGED, RCL_SUBSCRIPTION_REQUESTED_INCOMPATIBLE_QOS, RCL_SUBSCRIPTION_MESSAGE_LOST, } rcl_subscription_event_type_t; /// rmw struct. typedef struct rmw_event_t rmw_event_t; /// Internal rcl implementation struct. struct rcl_event_impl_t; /// Structure which encapsulates a ROS QoS event handle. typedef struct rcl_event_t { /// Pointer to the event implementation struct rcl_event_impl_t * impl; } rcl_event_t; /// Return a rcl_event_t struct with members set to `NULL`. /** * Should be called to get a null rcl_event_t before passing to * rcl_event_init(). * * \return Zero initialized rcl_event_t. */ RCL_PUBLIC RCL_WARN_UNUSED rcl_event_t rcl_get_zero_initialized_event(void); /// Initialize an rcl_event_t with a publisher. /** * Fill the rcl_event_t with the publisher and desired event_type. * * \param[in,out] event pointer to fill * \param[in] publisher to get events from * \param[in] event_type to listen for * \return #RCL_RET_OK if the rcl_event_t is filled, or * \return #RCL_RET_INVALID_ARGUMENT if any arguments are invalid, or * \return #RCL_RET_BAD_ALLOC if allocating memory fails, or * \return #RCL_RET_UNSUPPORTED if event_type is not supported, or * \return #RCL_RET_ERROR if an unspecified error occurs. */ RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_publisher_event_init( rcl_event_t * event, const rcl_publisher_t * publisher, const rcl_publisher_event_type_t event_type); /// Initialize an rcl_event_t with a subscription. /** * Fill the rcl_event_t with the subscription and desired event_type. * * \param[in,out] event pointer to fill * \param[in] subscription to get events from * \param[in] event_type to listen for * \return #RCL_RET_OK if the rcl_event_t is filled, or * \return #RCL_RET_INVALID_ARGUMENT if any arguments are invalid, or * \return #RCL_RET_BAD_ALLOC if allocating memory fails, or * \return #RCL_RET_UNSUPPORTED if event_type is not supported, or * \return #RCL_RET_ERROR if an unspecified error occurs. */ RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_subscription_event_init( rcl_event_t * event, const rcl_subscription_t * subscription, const rcl_subscription_event_type_t event_type); // Take event using the event handle. /** * Take an event from the event handle. * * \param[in] event event object to take from * \param[in, out] event_info event info object to write taken data into * \return #RCL_RET_OK if successful, or * \return #RCL_RET_INVALID_ARGUMENT if any arguments are invalid, or * \return #RCL_RET_BAD_ALLOC if memory allocation failed, or * \return #RCL_RET_EVENT_TAKE_FAILED if the take event failed, or * \return #RCL_RET_ERROR if an unexpected error occurs. */ RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_take_event( const rcl_event_t * event, void * event_info); // Finalize an event. /** * Finalize an event. * * \param[in] event to finalize * \return #RCL_RET_OK if successful, or * \return #RCL_RET_EVENT_INVALID if event is null, or * \return #RCL_RET_ERROR if an unexpected error occurs. */ RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_event_fini(rcl_event_t * event); /// Return the rmw event handle. /** * The handle returned is a pointer to the internally held rmw handle. * This function can fail, and therefore return `NULL`, if the: * - event is `NULL` * - event is invalid (never called init, called fini, or invalid node) * * The returned handle is made invalid if the event is finalized or if * rcl_shutdown() is called. * The returned handle is not guaranteed to be valid for the life time of the * event as it may be finalized and recreated itself. * Therefore it is recommended to get the handle from the event using * this function each time it is needed and avoid use of the handle * concurrently with functions that might change it. * * <hr> * Attribute | Adherence * ------------------ | ------------- * Allocates Memory | Yes * Thread-Safe | No * Uses Atomics | No * Lock-Free | Yes * * \param[in] event pointer to the rcl event * \return rmw event handle if successful, otherwise `NULL` */ RCL_PUBLIC RCL_WARN_UNUSED rmw_event_t * rcl_event_get_rmw_handle(const rcl_event_t * event); /// Check that the event is valid. /** * The bool returned is `false` if `event` is invalid. * The bool returned is `true` otherwise. * In the case where `false` is to be returned, an error message is set. * This function cannot fail. * * <hr> * Attribute | Adherence * ------------------ | ------------- * Allocates Memory | No * Thread-Safe | No * Uses Atomics | No * Lock-Free | Yes * * \param[in] event pointer to the rcl event * \return `true` if `event` is valid, otherwise `false` */ RCL_PUBLIC bool rcl_event_is_valid(const rcl_event_t * event); #ifdef __cplusplus } #endif #endif // RCL__EVENT_H_
30.835749
78
0.715808
[ "object" ]
30adf78a0f2a788c28d31a58983000b7063c68ab
3,295
h
C
src/main/cpp/xmlmechdata/MechDataDefn.h
Team302/2020InfiniteRecharge
c6355fdc7fcfd1f62b4f0ed5d077f026d3ace8f4
[ "MIT" ]
5
2020-01-11T14:49:32.000Z
2020-01-30T01:10:00.000Z
src/main/cpp/xmlmechdata/MechDataDefn.h
Team302/2020InfiniteRecharge
c6355fdc7fcfd1f62b4f0ed5d077f026d3ace8f4
[ "MIT" ]
117
2020-01-11T14:48:09.000Z
2020-03-04T01:38:43.000Z
src/main/cpp/xmlmechdata/MechDataDefn.h
Team302/2020InfiniteRecharge
c6355fdc7fcfd1f62b4f0ed5d077f026d3ace8f4
[ "MIT" ]
null
null
null
//==================================================================================================================================================== /// Copyright 2019 Lake Orion Robotics FIRST Team 302 /// /// 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 /** // C++ Includes #include <cstring> #include <string> #include <utility> #include <vector> // FRC includes // Team 302 includes #include <subsys/IMechanism.h> #include <subsys/MechParamData.h> // Third Party Includes //======================================================================================================== /// MechDataDefn.h //======================================================================================================== /// /// File Description: /// Top-level XML parsing file for defining the key mechanism parameter values. Examples include /// set points, min/max values, etc. /// This parsing leverages the 3rd party Open Source Pugixml library (https://pugixml.org/). /// /// This parsing code will call the classes/methods to parse the lower-level objects. When the parsing /// has been completed, the mechanism parameters will be defined. /// /// The robot definition XML file is: /home/lvuser/config/mechdata/xxx.xml where xxx is the class name /// that will be reading the file. /// //======================================================================================================== class MechDataDefn { public: MechDataDefn() = delete; virtual ~MechDataDefn() = delete; //================================================================================================ /// Method: ParseXML /// Description: Parse a robot.xml file /// Returns: void //================================================================================================ static void ParseXML ( std::string& leaf, /// <I> - the file name (without the path) to parse mechParameters& params /// <O> - the parameter data ); }; **/
47.753623
151
0.513505
[ "vector" ]
30b44627e0362f7ab14ca6740f2fa7c38f99f6be
2,948
h
C
chrome/browser/dom_distiller/lazy_dom_distiller_service.h
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
chrome/browser/dom_distiller/lazy_dom_distiller_service.h
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/dom_distiller/lazy_dom_distiller_service.h
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-03-15T13:21:38.000Z
2017-03-15T13:21:38.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DOM_DISTILLER_LAZY_DOM_DISTILLER_SERVICE_H_ #define CHROME_BROWSER_DOM_DISTILLER_LAZY_DOM_DISTILLER_SERVICE_H_ #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/dom_distiller/core/task_tracker.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" namespace content { class NotificationSource; class NotificationDetails; } // namespace content class Profile; namespace dom_distiller { class DomDistillerServiceFactory; // A class which helps with lazy instantiation of the DomDistillerService, using // the BrowserContextKeyedServiceFactory for it. This class will delete itself // when the profile is destroyed. class LazyDomDistillerService : public DomDistillerServiceInterface, public content::NotificationObserver { public: LazyDomDistillerService(Profile* profile, const DomDistillerServiceFactory* service_factory); virtual ~LazyDomDistillerService(); public: // DomDistillerServiceInterface implementation: virtual syncer::SyncableService* GetSyncableService() const OVERRIDE; virtual const std::string AddToList( const GURL& url, const ArticleAvailableCallback& article_cb) OVERRIDE; virtual std::vector<ArticleEntry> GetEntries() const OVERRIDE; virtual scoped_ptr<ArticleEntry> RemoveEntry(const std::string& entry_id) OVERRIDE; virtual scoped_ptr<ViewerHandle> ViewEntry(ViewRequestDelegate* delegate, const std::string& entry_id) OVERRIDE; virtual scoped_ptr<ViewerHandle> ViewUrl(ViewRequestDelegate* delegate, const GURL& url) OVERRIDE; virtual void AddObserver(DomDistillerObserver* observer) OVERRIDE; virtual void RemoveObserver(DomDistillerObserver* observer) OVERRIDE; private: // Accessor method for the backing service instance. DomDistillerServiceInterface* instance() const; // content::NotificationObserver implementation: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // The Profile to use when retrieving the DomDistillerService and also the // profile to listen for destruction of. Profile* profile_; // A BrowserContextKeyedServiceFactory for the DomDistillerService. const DomDistillerServiceFactory* service_factory_; // Used to track when the profile is shut down. content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(LazyDomDistillerService); }; } // namespace dom_distiller #endif // CHROME_BROWSER_DOM_DISTILLER_LAZY_DOM_DISTILLER_SERVICE_H_
38.789474
80
0.759837
[ "vector" ]
30b9549e3b729b1f6a651200843eeb989e562b05
38,689
c
C
release/src/linux/linux/fs/nfsd/vfs.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src/linux/linux/fs/nfsd/vfs.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src/linux/linux/fs/nfsd/vfs.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
#define MSNFS /* HACK HACK */ /* * linux/fs/nfsd/vfs.c * * File operations used by nfsd. Some of these have been ripped from * other parts of the kernel because they weren't in ksyms.c, others * are partial duplicates with added or changed functionality. * * Note that several functions dget() the dentry upon which they want * to act, most notably those that create directory entries. Response * dentry's are dput()'d if necessary in the release callback. * So if you notice code paths that apparently fail to dput() the * dentry, don't worry--they have been taken care of. * * Copyright (C) 1995-1999 Olaf Kirch <okir@monad.swb.de> */ #include <linux/config.h> #include <linux/version.h> #include <linux/string.h> #include <linux/sched.h> #include <linux/errno.h> #include <linux/locks.h> #include <linux/fs.h> #include <linux/major.h> #include <linux/ext2_fs.h> #include <linux/proc_fs.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/net.h> #include <linux/unistd.h> #include <linux/slab.h> #include <linux/in.h> #define __NO_VERSION__ #include <linux/module.h> #include <linux/sunrpc/svc.h> #include <linux/nfsd/nfsd.h> #ifdef CONFIG_NFSD_V3 #include <linux/nfs3.h> #include <linux/nfsd/xdr3.h> #endif /* CONFIG_NFSD_V3 */ #include <linux/nfsd/nfsfh.h> #include <linux/quotaops.h> #include <asm/uaccess.h> #define NFSDDBG_FACILITY NFSDDBG_FILEOP #define NFSD_PARANOIA /* We must ignore files (but only files) which might have mandatory * locks on them because there is no way to know if the accesser has * the lock. */ #define IS_ISMNDLK(i) (S_ISREG((i)->i_mode) && MANDATORY_LOCK(i)) /* * This is a cache of readahead params that help us choose the proper * readahead strategy. Initially, we set all readahead parameters to 0 * and let the VFS handle things. * If you increase the number of cached files very much, you'll need to * add a hash table here. */ struct raparms { struct raparms *p_next; unsigned int p_count; ino_t p_ino; dev_t p_dev; unsigned long p_reada, p_ramax, p_raend, p_ralen, p_rawin; }; static struct raparms * raparml; static struct raparms * raparm_cache; /* * Look up one component of a pathname. * N.B. After this call _both_ fhp and resfh need an fh_put * * If the lookup would cross a mountpoint, and the mounted filesystem * is exported to the client with NFSEXP_NOHIDE, then the lookup is * accepted as it stands and the mounted directory is * returned. Otherwise the covered directory is returned. * NOTE: this mountpoint crossing is not supported properly by all * clients and is explicitly disallowed for NFSv3 * NeilBrown <neilb@cse.unsw.edu.au> */ int nfsd_lookup(struct svc_rqst *rqstp, struct svc_fh *fhp, const char *name, int len, struct svc_fh *resfh) { struct svc_export *exp; struct dentry *dparent; struct dentry *dentry; int err; dprintk("nfsd: nfsd_lookup(fh %s, %.*s)\n", SVCFH_fmt(fhp), len,name); /* Obtain dentry and export. */ err = fh_verify(rqstp, fhp, S_IFDIR, MAY_EXEC); if (err) goto out; dparent = fhp->fh_dentry; exp = fhp->fh_export; err = nfserr_acces; /* Lookup the name, but don't follow links */ if (isdotent(name, len)) { if (len==1) dentry = dget(dparent); else if (dparent != exp->ex_dentry) dentry = dget(dparent->d_parent); else if (!EX_NOHIDE(exp)) dentry = dget(dparent); /* .. == . just like at / */ else { /* checking mountpoint crossing is very different when stepping up */ struct svc_export *exp2 = NULL; struct dentry *dp; struct vfsmount *mnt = mntget(exp->ex_mnt); dentry = dget(dparent); while(follow_up(&mnt, &dentry)) ; dp = dget(dentry->d_parent); dput(dentry); dentry = dp; for ( ; exp2 == NULL && dp->d_parent != dp; dp=dp->d_parent) exp2 = exp_get(exp->ex_client, dp->d_inode->i_dev, dp->d_inode->i_ino); if (exp2==NULL) { dput(dentry); dentry = dget(dparent); } else { exp = exp2; } mntput(mnt); } } else { fh_lock(fhp); dentry = lookup_one_len(name, dparent, len); err = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_nfserr; /* * check if we have crossed a mount point ... */ if (d_mountpoint(dentry)) { struct svc_export *exp2 = NULL; struct vfsmount *mnt = mntget(exp->ex_mnt); struct dentry *mounts = dget(dentry); while (follow_down(&mnt,&mounts)&&d_mountpoint(mounts)) ; exp2 = exp_get(rqstp->rq_client, mounts->d_inode->i_dev, mounts->d_inode->i_ino); if (exp2 && EX_NOHIDE(exp2)) { /* successfully crossed mount point */ exp = exp2; dput(dentry); dentry = mounts; } else dput(mounts); mntput(mnt); } } if (dentry->d_inode && dentry->d_inode->i_op && dentry->d_inode->i_op->revalidate && dentry->d_inode->i_op->revalidate(dentry)) err = nfserr_noent; else err = fh_compose(resfh, exp, dentry, fhp); if (!err && !dentry->d_inode) err = nfserr_noent; out: return err; out_nfserr: err = nfserrno(err); goto out; } /* * Set various file attributes. * N.B. After this call fhp needs an fh_put */ int nfsd_setattr(struct svc_rqst *rqstp, struct svc_fh *fhp, struct iattr *iap, int check_guard, time_t guardtime) { struct dentry *dentry; struct inode *inode; int accmode = MAY_SATTR; int ftype = 0; int imode; int err; int size_change = 0; if (iap->ia_valid & (ATTR_ATIME | ATTR_MTIME | ATTR_SIZE)) accmode |= MAY_WRITE|MAY_OWNER_OVERRIDE; if (iap->ia_valid & ATTR_SIZE) ftype = S_IFREG; /* Get inode */ err = fh_verify(rqstp, fhp, ftype, accmode); if (err || !iap->ia_valid) goto out; dentry = fhp->fh_dentry; inode = dentry->d_inode; /* NFSv2 does not differentiate between "set-[ac]time-to-now" * which only requires access, and "set-[ac]time-to-X" which * requires ownership. * So if it looks like it might be "set both to the same time which * is close to now", and if inode_change_ok fails, then we * convert to "set to now" instead of "set to explicit time" * * We only call inode_change_ok as the last test as technically * it is not an interface that we should be using. It is only * valid if the filesystem does not define it's own i_op->setattr. */ #define BOTH_TIME_SET (ATTR_ATIME_SET | ATTR_MTIME_SET) #define MAX_TOUCH_TIME_ERROR (30*60) if ((iap->ia_valid & BOTH_TIME_SET) == BOTH_TIME_SET && iap->ia_mtime == iap->ia_atime ) { /* Looks probable. Now just make sure time is in the right ballpark. * Solaris, at least, doesn't seem to care what the time request is. * We require it be within 30 minutes of now. */ time_t delta = iap->ia_atime - CURRENT_TIME; if (delta<0) delta = -delta; if (delta < MAX_TOUCH_TIME_ERROR && inode_change_ok(inode, iap) != 0) { /* turn off ATTR_[AM]TIME_SET but leave ATTR_[AM]TIME * this will cause notify_change to set these times to "now" */ iap->ia_valid &= ~BOTH_TIME_SET; } } /* The size case is special. It changes the file as well as the attributes. */ if (iap->ia_valid & ATTR_SIZE) { if (iap->ia_size < inode->i_size) { err = nfsd_permission(fhp->fh_export, dentry, MAY_TRUNC|MAY_OWNER_OVERRIDE); if (err) goto out; } /* * If we are changing the size of the file, then * we need to break all leases. */ err = get_lease(inode, FMODE_WRITE); if (err) goto out_nfserr; err = get_write_access(inode); if (err) goto out_nfserr; err = locks_verify_truncate(inode, NULL, iap->ia_size); if (err) { put_write_access(inode); goto out_nfserr; } DQUOT_INIT(inode); } imode = inode->i_mode; if (iap->ia_valid & ATTR_MODE) { iap->ia_mode &= S_IALLUGO; imode = iap->ia_mode |= (imode & ~S_IALLUGO); } /* Revoke setuid/setgid bit on chown/chgrp */ if ((iap->ia_valid & ATTR_UID) && (imode & S_ISUID) && !S_ISDIR(imode) && iap->ia_uid != inode->i_uid) { iap->ia_valid |= ATTR_MODE; iap->ia_mode = imode &= ~S_ISUID; } if ((iap->ia_valid & ATTR_GID) && (imode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) && !S_ISDIR(imode) && iap->ia_gid != inode->i_gid) { iap->ia_valid |= ATTR_MODE; iap->ia_mode = imode &= ~S_ISGID; } /* Change the attributes. */ iap->ia_valid |= ATTR_CTIME; if (iap->ia_valid & ATTR_SIZE) { down_write(&inode->i_alloc_sem); fh_lock(fhp); size_change = 1; } err = nfserr_notsync; if (!check_guard || guardtime == inode->i_ctime) { err = notify_change(dentry, iap); err = nfserrno(err); } if (size_change) { fh_unlock(fhp); up_write(&inode->i_alloc_sem); put_write_access(inode); } if (!err) if (EX_ISSYNC(fhp->fh_export)) write_inode_now(inode, 1); out: return err; out_nfserr: err = nfserrno(err); goto out; } #ifdef CONFIG_NFSD_V3 /* * Check server access rights to a file system object */ struct accessmap { u32 access; int how; }; static struct accessmap nfs3_regaccess[] = { { NFS3_ACCESS_READ, MAY_READ }, { NFS3_ACCESS_EXECUTE, MAY_EXEC }, { NFS3_ACCESS_MODIFY, MAY_WRITE|MAY_TRUNC }, { NFS3_ACCESS_EXTEND, MAY_WRITE }, { 0, 0 } }; static struct accessmap nfs3_diraccess[] = { { NFS3_ACCESS_READ, MAY_READ }, { NFS3_ACCESS_LOOKUP, MAY_EXEC }, { NFS3_ACCESS_MODIFY, MAY_EXEC|MAY_WRITE|MAY_TRUNC }, { NFS3_ACCESS_EXTEND, MAY_EXEC|MAY_WRITE }, { NFS3_ACCESS_DELETE, MAY_REMOVE }, { 0, 0 } }; static struct accessmap nfs3_anyaccess[] = { /* Some clients - Solaris 2.6 at least, make an access call * to the server to check for access for things like /dev/null * (which really, the server doesn't care about). So * We provide simple access checking for them, looking * mainly at mode bits */ { NFS3_ACCESS_READ, MAY_READ }, { NFS3_ACCESS_EXECUTE, MAY_EXEC }, { NFS3_ACCESS_MODIFY, MAY_WRITE }, { NFS3_ACCESS_EXTEND, MAY_WRITE }, { 0, 0 } }; int nfsd_access(struct svc_rqst *rqstp, struct svc_fh *fhp, u32 *access) { struct accessmap *map; struct svc_export *export; struct dentry *dentry; u32 query, result = 0; unsigned int error; error = fh_verify(rqstp, fhp, 0, MAY_NOP); if (error) goto out; export = fhp->fh_export; dentry = fhp->fh_dentry; if (S_ISREG(dentry->d_inode->i_mode)) map = nfs3_regaccess; else if (S_ISDIR(dentry->d_inode->i_mode)) map = nfs3_diraccess; else map = nfs3_anyaccess; query = *access; for (; map->access; map++) { if (map->access & query) { unsigned int err2; err2 = nfsd_permission(export, dentry, map->how); switch (err2) { case nfs_ok: result |= map->access; break; /* the following error codes just mean the access was not allowed, * rather than an error occurred */ case nfserr_rofs: case nfserr_acces: case nfserr_perm: /* simply don't "or" in the access bit. */ break; default: error = err2; goto out; } } } *access = result; out: return error; } #endif /* CONFIG_NFSD_V3 */ /* * Open an existing file or directory. * The access argument indicates the type of open (read/write/lock) * N.B. After this call fhp needs an fh_put */ int nfsd_open(struct svc_rqst *rqstp, struct svc_fh *fhp, int type, int access, struct file *filp) { struct dentry *dentry; struct inode *inode; int err; /* If we get here, then the client has already done an "open", and (hopefully) * checked permission - so allow OWNER_OVERRIDE in case a chmod has now revoked * permission */ err = fh_verify(rqstp, fhp, type, access | MAY_OWNER_OVERRIDE); if (err) goto out; dentry = fhp->fh_dentry; inode = dentry->d_inode; /* Disallow access to files with the append-only bit set or * with mandatory locking enabled */ err = nfserr_perm; if (IS_APPEND(inode) || IS_ISMNDLK(inode)) goto out; if (!inode->i_fop) goto out; /* * Check to see if there are any leases on this file. * This may block while leases are broken. */ err = get_lease(inode, (access & MAY_WRITE) ? FMODE_WRITE : 0); if (err) goto out_nfserr; if ((access & MAY_WRITE) && (err = get_write_access(inode)) != 0) goto out_nfserr; memset(filp, 0, sizeof(*filp)); filp->f_op = fops_get(inode->i_fop); atomic_set(&filp->f_count, 1); filp->f_dentry = dentry; filp->f_vfsmnt = fhp->fh_export->ex_mnt; filp->f_maxcount = INT_MAX; if (access & MAY_WRITE) { filp->f_flags = O_WRONLY|O_LARGEFILE; filp->f_mode = FMODE_WRITE; DQUOT_INIT(inode); } else { filp->f_flags = O_RDONLY|O_LARGEFILE; filp->f_mode = FMODE_READ; } err = 0; if (filp->f_op && filp->f_op->open) { err = filp->f_op->open(inode, filp); if (err) { fops_put(filp->f_op); if (access & MAY_WRITE) put_write_access(inode); /* I nearly added put_filp() call here, but this filp * is really on callers stack frame. -DaveM */ atomic_dec(&filp->f_count); } } out_nfserr: if (err) err = nfserrno(err); out: return err; } /* * Close a file. */ void nfsd_close(struct file *filp) { struct dentry *dentry = filp->f_dentry; struct inode *inode = dentry->d_inode; if (filp->f_op && filp->f_op->release) filp->f_op->release(inode, filp); fops_put(filp->f_op); if (filp->f_mode & FMODE_WRITE) put_write_access(inode); } /* * Sync a file * As this calls fsync (not fdatasync) there is no need for a write_inode * after it. */ inline void nfsd_dosync(struct file *filp, struct dentry *dp, struct file_operations *fop) { struct inode *inode = dp->d_inode; int (*fsync) (struct file *, struct dentry *, int); filemap_fdatasync(inode->i_mapping); if (fop && (fsync = fop->fsync)) fsync(filp, dp, 0); filemap_fdatawait(inode->i_mapping); } void nfsd_sync(struct file *filp) { struct inode *inode = filp->f_dentry->d_inode; dprintk("nfsd: sync file %s\n", filp->f_dentry->d_name.name); down(&inode->i_sem); nfsd_dosync(filp, filp->f_dentry, filp->f_op); up(&inode->i_sem); } void nfsd_sync_dir(struct dentry *dp) { nfsd_dosync(NULL, dp, dp->d_inode->i_fop); } /* * Obtain the readahead parameters for the file * specified by (dev, ino). */ static inline struct raparms * nfsd_get_raparms(dev_t dev, ino_t ino) { struct raparms *ra, **rap, **frap = NULL; int depth = 0; for (rap = &raparm_cache; (ra = *rap); rap = &ra->p_next) { if (ra->p_ino == ino && ra->p_dev == dev) goto found; depth++; if (ra->p_count == 0) frap = rap; } depth = nfsdstats.ra_size*11/10; if (!frap) return NULL; rap = frap; ra = *frap; ra->p_dev = dev; ra->p_ino = ino; ra->p_reada = 0; ra->p_ramax = 0; ra->p_raend = 0; ra->p_ralen = 0; ra->p_rawin = 0; found: if (rap != &raparm_cache) { *rap = ra->p_next; ra->p_next = raparm_cache; raparm_cache = ra; } ra->p_count++; nfsdstats.ra_depth[depth*10/nfsdstats.ra_size]++; return ra; } /* copied from fs/read_write.c */ static inline loff_t llseek(struct file *file, loff_t offset, int origin) { loff_t (*fn)(struct file *, loff_t, int); loff_t retval; fn = default_llseek; if (file->f_op && file->f_op->llseek) fn = file->f_op->llseek; lock_kernel(); retval = fn(file, offset, origin); unlock_kernel(); return retval; } /* * Read data from a file. count must contain the requested read count * on entry. On return, *count contains the number of bytes actually read. * N.B. After this call fhp needs an fh_put */ int nfsd_read(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t offset, char *buf, unsigned long *count) { struct raparms *ra; mm_segment_t oldfs; int err; struct file file; err = nfsd_open(rqstp, fhp, S_IFREG, MAY_READ, &file); if (err) goto out; err = nfserr_perm; if (!file.f_op->read) goto out_close; #ifdef MSNFS if ((fhp->fh_export->ex_flags & NFSEXP_MSNFS) && (!lock_may_read(file.f_dentry->d_inode, offset, *count))) goto out_close; #endif /* Get readahead parameters */ ra = nfsd_get_raparms(fhp->fh_export->ex_dev, fhp->fh_dentry->d_inode->i_ino); if (ra) { file.f_reada = ra->p_reada; file.f_ramax = ra->p_ramax; file.f_raend = ra->p_raend; file.f_ralen = ra->p_ralen; file.f_rawin = ra->p_rawin; } llseek(&file, offset, 0); oldfs = get_fs(); set_fs(KERNEL_DS); err = file.f_op->read(&file, buf, *count, &file.f_pos); set_fs(oldfs); /* Write back readahead params */ if (ra != NULL) { dprintk("nfsd: raparms %ld %ld %ld %ld %ld\n", file.f_reada, file.f_ramax, file.f_raend, file.f_ralen, file.f_rawin); ra->p_reada = file.f_reada; ra->p_ramax = file.f_ramax; ra->p_raend = file.f_raend; ra->p_ralen = file.f_ralen; ra->p_rawin = file.f_rawin; ra->p_count -= 1; } if (err >= 0) { nfsdstats.io_read += err; *count = err; err = 0; } else err = nfserrno(err); out_close: nfsd_close(&file); out: return err; } /* * Write data to a file. * The stable flag requests synchronous writes. * N.B. After this call fhp needs an fh_put */ int nfsd_write(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t offset, char *buf, unsigned long cnt, int *stablep) { struct svc_export *exp; struct file file; struct dentry *dentry; struct inode *inode; mm_segment_t oldfs; int err = 0; int stable = *stablep; err = nfsd_open(rqstp, fhp, S_IFREG, MAY_WRITE, &file); if (err) goto out; if (!cnt) goto out_close; err = nfserr_perm; if (!file.f_op->write) goto out_close; #ifdef MSNFS if ((fhp->fh_export->ex_flags & NFSEXP_MSNFS) && (!lock_may_write(file.f_dentry->d_inode, offset, cnt))) goto out_close; #endif dentry = file.f_dentry; inode = dentry->d_inode; exp = fhp->fh_export; /* * Request sync writes if * - the sync export option has been set, or * - the client requested O_SYNC behavior (NFSv3 feature). * - The file system doesn't support fsync(). * When gathered writes have been configured for this volume, * flushing the data to disk is handled separately below. */ if (file.f_op->fsync == 0) {/* COMMIT3 cannot work */ stable = 2; *stablep = 2; /* FILE_SYNC */ } if (!EX_ISSYNC(exp)) stable = 0; if (stable && !EX_WGATHER(exp)) file.f_flags |= O_SYNC; llseek(&file, offset, 0); /* Write the data. */ oldfs = get_fs(); set_fs(KERNEL_DS); err = file.f_op->write(&file, buf, cnt, &file.f_pos); if (err >= 0) nfsdstats.io_write += cnt; set_fs(oldfs); /* clear setuid/setgid flag after write */ if (err >= 0 && (inode->i_mode & (S_ISUID | S_ISGID))) { struct iattr ia; ia.ia_valid = ATTR_MODE; ia.ia_mode = inode->i_mode & ~(S_ISUID | S_ISGID); notify_change(dentry, &ia); } if (err >= 0 && stable) { static unsigned long last_ino; static kdev_t last_dev = NODEV; /* * Gathered writes: If another process is currently * writing to the file, there's a high chance * this is another nfsd (triggered by a bulk write * from a client's biod). Rather than syncing the * file with each write request, we sleep for 10 msec. * * I don't know if this roughly approximates * C. Juszak's idea of gathered writes, but it's a * nice and simple solution (IMHO), and it seems to * work:-) */ if (EX_WGATHER(exp)) { if (atomic_read(&inode->i_writecount) > 1 || (last_ino == inode->i_ino && last_dev == inode->i_dev)) { dprintk("nfsd: write defer %d\n", current->pid); set_current_state(TASK_UNINTERRUPTIBLE); schedule_timeout((HZ+99)/100); current->state = TASK_RUNNING; dprintk("nfsd: write resume %d\n", current->pid); } if (inode->i_state & I_DIRTY) { dprintk("nfsd: write sync %d\n", current->pid); nfsd_sync(&file); } #if 0 wake_up(&inode->i_wait); #endif } last_ino = inode->i_ino; last_dev = inode->i_dev; } dprintk("nfsd: write complete err=%d\n", err); if (err >= 0) err = 0; else err = nfserrno(err); out_close: nfsd_close(&file); out: return err; } #ifdef CONFIG_NFSD_V3 /* * Commit all pending writes to stable storage. * Strictly speaking, we could sync just the indicated file region here, * but there's currently no way we can ask the VFS to do so. * * Unfortunately we cannot lock the file to make sure we return full WCC * data to the client, as locking happens lower down in the filesystem. */ int nfsd_commit(struct svc_rqst *rqstp, struct svc_fh *fhp, off_t offset, unsigned long count) { struct file file; int err; if ((err = nfsd_open(rqstp, fhp, S_IFREG, MAY_WRITE, &file)) != 0) return err; if (EX_ISSYNC(fhp->fh_export)) { if (file.f_op && file.f_op->fsync) { nfsd_sync(&file); } else { err = nfserr_notsupp; } } nfsd_close(&file); return err; } #endif /* CONFIG_NFSD_V3 */ /* * Create a file (regular, directory, device, fifo); UNIX sockets * not yet implemented. * If the response fh has been verified, the parent directory should * already be locked. Note that the parent directory is left locked. * * N.B. Every call to nfsd_create needs an fh_put for _both_ fhp and resfhp */ int nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp, char *fname, int flen, struct iattr *iap, int type, dev_t rdev, struct svc_fh *resfhp) { struct dentry *dentry, *dchild; struct inode *dirp; int err; err = nfserr_perm; if (!flen) goto out; err = nfserr_exist; if (isdotent(fname, flen)) goto out; err = fh_verify(rqstp, fhp, S_IFDIR, MAY_CREATE); if (err) goto out; dentry = fhp->fh_dentry; dirp = dentry->d_inode; err = nfserr_notdir; if(!dirp->i_op || !dirp->i_op->lookup) goto out; /* * Check whether the response file handle has been verified yet. * If it has, the parent directory should already be locked. */ if (!resfhp->fh_dentry) { /* called from nfsd_proc_mkdir, or possibly nfsd3_proc_create */ fh_lock(fhp); dchild = lookup_one_len(fname, dentry, flen); err = PTR_ERR(dchild); if (IS_ERR(dchild)) goto out_nfserr; err = fh_compose(resfhp, fhp->fh_export, dchild, fhp); if (err) goto out; } else { /* called from nfsd_proc_create */ dchild = resfhp->fh_dentry; if (!fhp->fh_locked) { /* not actually possible */ printk(KERN_ERR "nfsd_create: parent %s/%s not locked!\n", dentry->d_parent->d_name.name, dentry->d_name.name); err = -EIO; goto out; } } /* * Make sure the child dentry is still negative ... */ err = nfserr_exist; if (dchild->d_inode) { dprintk("nfsd_create: dentry %s/%s not negative!\n", dentry->d_name.name, dchild->d_name.name); goto out; } if (!(iap->ia_valid & ATTR_MODE)) iap->ia_mode = 0; iap->ia_mode = (iap->ia_mode & S_IALLUGO) | type; /* * Get the dir op function pointer. */ err = nfserr_perm; switch (type) { case S_IFREG: err = vfs_create(dirp, dchild, iap->ia_mode); break; case S_IFDIR: err = vfs_mkdir(dirp, dchild, iap->ia_mode); break; case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: err = vfs_mknod(dirp, dchild, iap->ia_mode, rdev); break; default: printk("nfsd: bad file type %o in nfsd_create\n", type); err = -EINVAL; } if (err < 0) goto out_nfserr; if (EX_ISSYNC(fhp->fh_export)) { nfsd_sync_dir(dentry); write_inode_now(dchild->d_inode, 1); } /* Set file attributes. Mode has already been set and * setting uid/gid works only for root. Irix appears to * send along the gid when it tries to implement setgid * directories via NFS. */ err = 0; if ((iap->ia_valid &= ~(ATTR_UID|ATTR_GID|ATTR_MODE)) != 0) err = nfsd_setattr(rqstp, resfhp, iap, 0, (time_t)0); /* * Update the file handle to get the new inode info. */ if (!err) err = fh_update(resfhp); out: return err; out_nfserr: err = nfserrno(err); goto out; } #ifdef CONFIG_NFSD_V3 /* * NFSv3 version of nfsd_create */ int nfsd_create_v3(struct svc_rqst *rqstp, struct svc_fh *fhp, char *fname, int flen, struct iattr *iap, struct svc_fh *resfhp, int createmode, u32 *verifier) { struct dentry *dentry, *dchild; struct inode *dirp; int err; __u32 v_mtime=0, v_atime=0; int v_mode=0; err = nfserr_perm; if (!flen) goto out; err = nfserr_exist; if (isdotent(fname, flen)) goto out; if (!(iap->ia_valid & ATTR_MODE)) iap->ia_mode = 0; err = fh_verify(rqstp, fhp, S_IFDIR, MAY_CREATE); if (err) goto out; dentry = fhp->fh_dentry; dirp = dentry->d_inode; /* Get all the sanity checks out of the way before * we lock the parent. */ err = nfserr_notdir; if(!dirp->i_op || !dirp->i_op->lookup) goto out; fh_lock(fhp); /* * Compose the response file handle. */ dchild = lookup_one_len(fname, dentry, flen); err = PTR_ERR(dchild); if (IS_ERR(dchild)) goto out_nfserr; err = fh_compose(resfhp, fhp->fh_export, dchild, fhp); if (err) goto out; if (createmode == NFS3_CREATE_EXCLUSIVE) { /* while the verifier would fit in mtime+atime, * solaris7 gets confused (bugid 4218508) if these have * the high bit set, so we use the mode as well */ v_mtime = verifier[0]&0x7fffffff; v_atime = verifier[1]&0x7fffffff; v_mode = S_IFREG | ((verifier[0]&0x80000000) >> (32-7)) /* u+x */ | ((verifier[1]&0x80000000) >> (32-9)) /* u+r */ ; } if (dchild->d_inode) { err = 0; switch (createmode) { case NFS3_CREATE_UNCHECKED: if (! S_ISREG(dchild->d_inode->i_mode)) err = nfserr_exist; else { iap->ia_valid &= ATTR_SIZE; goto set_attr; } break; case NFS3_CREATE_EXCLUSIVE: if ( dchild->d_inode->i_mtime == v_mtime && dchild->d_inode->i_atime == v_atime && dchild->d_inode->i_mode == v_mode && dchild->d_inode->i_size == 0 ) break; /* fallthru */ case NFS3_CREATE_GUARDED: err = nfserr_exist; } goto out; } err = vfs_create(dirp, dchild, iap->ia_mode); if (err < 0) goto out_nfserr; if (EX_ISSYNC(fhp->fh_export)) { nfsd_sync_dir(dentry); /* setattr will sync the child (or not) */ } /* * Update the filehandle to get the new inode info. */ err = fh_update(resfhp); if (err) goto out; if (createmode == NFS3_CREATE_EXCLUSIVE) { /* Cram the verifier into atime/mtime/mode */ iap->ia_valid = ATTR_MTIME|ATTR_ATIME | ATTR_MTIME_SET|ATTR_ATIME_SET | ATTR_MODE; iap->ia_mtime = v_mtime; iap->ia_atime = v_atime; iap->ia_mode = v_mode; } /* Set file attributes. * Mode has already been set but we might need to reset it * for CREATE_EXCLUSIVE * Irix appears to send along the gid when it tries to * implement setgid directories via NFS. Clear out all that cruft. */ set_attr: if ((iap->ia_valid &= ~(ATTR_UID|ATTR_GID)) != 0) err = nfsd_setattr(rqstp, resfhp, iap, 0, (time_t)0); out: fh_unlock(fhp); return err; out_nfserr: err = nfserrno(err); goto out; } #endif /* CONFIG_NFSD_V3 */ /* * Read a symlink. On entry, *lenp must contain the maximum path length that * fits into the buffer. On return, it contains the true length. * N.B. After this call fhp needs an fh_put */ int nfsd_readlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *buf, int *lenp) { struct dentry *dentry; struct inode *inode; mm_segment_t oldfs; int err; err = fh_verify(rqstp, fhp, S_IFLNK, MAY_NOP); if (err) goto out; dentry = fhp->fh_dentry; inode = dentry->d_inode; err = nfserr_inval; if (!inode->i_op || !inode->i_op->readlink) goto out; UPDATE_ATIME(inode); /* N.B. Why does this call need a get_fs()?? * Remove the set_fs and watch the fireworks:-) --okir */ oldfs = get_fs(); set_fs(KERNEL_DS); err = inode->i_op->readlink(dentry, buf, *lenp); set_fs(oldfs); if (err < 0) goto out_nfserr; *lenp = err; err = 0; out: return err; out_nfserr: err = nfserrno(err); goto out; } /* * Create a symlink and look up its inode * N.B. After this call _both_ fhp and resfhp need an fh_put */ int nfsd_symlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *fname, int flen, char *path, int plen, struct svc_fh *resfhp, struct iattr *iap) { struct dentry *dentry, *dnew; int err, cerr; err = nfserr_noent; if (!flen || !plen) goto out; err = nfserr_exist; if (isdotent(fname, flen)) goto out; err = fh_verify(rqstp, fhp, S_IFDIR, MAY_CREATE); if (err) goto out; fh_lock(fhp); dentry = fhp->fh_dentry; dnew = lookup_one_len(fname, dentry, flen); err = PTR_ERR(dnew); if (IS_ERR(dnew)) goto out_nfserr; err = vfs_symlink(dentry->d_inode, dnew, path); if (!err) { if (EX_ISSYNC(fhp->fh_export)) nfsd_sync_dir(dentry); if (iap) { iap->ia_valid &= ATTR_MODE /* ~(ATTR_MODE|ATTR_UID|ATTR_GID)*/; if (iap->ia_valid) { iap->ia_valid |= ATTR_CTIME; iap->ia_mode = (iap->ia_mode&S_IALLUGO) | S_IFLNK; err = notify_change(dnew, iap); if (err) err = nfserrno(err); else if (EX_ISSYNC(fhp->fh_export)) write_inode_now(dentry->d_inode, 1); } } } else err = nfserrno(err); fh_unlock(fhp); /* Compose the fh so the dentry will be freed ... */ cerr = fh_compose(resfhp, fhp->fh_export, dnew, fhp); if (err==0) err = cerr; out: return err; out_nfserr: err = nfserrno(err); goto out; } /* * Create a hardlink * N.B. After this call _both_ ffhp and tfhp need an fh_put */ int nfsd_link(struct svc_rqst *rqstp, struct svc_fh *ffhp, char *name, int len, struct svc_fh *tfhp) { struct dentry *ddir, *dnew, *dold; struct inode *dirp, *dest; int err; err = fh_verify(rqstp, ffhp, S_IFDIR, MAY_CREATE); if (err) goto out; err = fh_verify(rqstp, tfhp, -S_IFDIR, MAY_NOP); if (err) goto out; err = nfserr_perm; if (!len) goto out; err = nfserr_exist; if (isdotent(name, len)) goto out; fh_lock(ffhp); ddir = ffhp->fh_dentry; dirp = ddir->d_inode; dnew = lookup_one_len(name, ddir, len); err = PTR_ERR(dnew); if (IS_ERR(dnew)) goto out_nfserr; dold = tfhp->fh_dentry; dest = dold->d_inode; err = vfs_link(dold, dirp, dnew); if (!err) { if (EX_ISSYNC(ffhp->fh_export)) { nfsd_sync_dir(ddir); write_inode_now(dest, 1); } } else { if (err == -EXDEV && rqstp->rq_vers == 2) err = nfserr_acces; else err = nfserrno(err); } fh_unlock(ffhp); dput(dnew); out: return err; out_nfserr: err = nfserrno(err); goto out; } /* * Rename a file * N.B. After this call _both_ ffhp and tfhp need an fh_put */ int nfsd_rename(struct svc_rqst *rqstp, struct svc_fh *ffhp, char *fname, int flen, struct svc_fh *tfhp, char *tname, int tlen) { struct dentry *fdentry, *tdentry, *odentry, *ndentry; struct inode *fdir, *tdir; int err; err = fh_verify(rqstp, ffhp, S_IFDIR, MAY_REMOVE); if (err) goto out; err = fh_verify(rqstp, tfhp, S_IFDIR, MAY_CREATE); if (err) goto out; fdentry = ffhp->fh_dentry; fdir = fdentry->d_inode; tdentry = tfhp->fh_dentry; tdir = tdentry->d_inode; err = (rqstp->rq_vers == 2) ? nfserr_acces : nfserr_xdev; if (fdir->i_dev != tdir->i_dev) goto out; err = nfserr_perm; if (!flen || isdotent(fname, flen) || !tlen || isdotent(tname, tlen)) goto out; /* cannot use fh_lock as we need deadlock protective ordering * so do it by hand */ double_down(&tdir->i_sem, &fdir->i_sem); ffhp->fh_locked = tfhp->fh_locked = 1; fill_pre_wcc(ffhp); fill_pre_wcc(tfhp); odentry = lookup_one_len(fname, fdentry, flen); err = PTR_ERR(odentry); if (IS_ERR(odentry)) goto out_nfserr; err = -ENOENT; if (!odentry->d_inode) goto out_dput_old; ndentry = lookup_one_len(tname, tdentry, tlen); err = PTR_ERR(ndentry); if (IS_ERR(ndentry)) goto out_dput_old; #ifdef MSNFS if ((ffhp->fh_export->ex_flags & NFSEXP_MSNFS) && ((atomic_read(&odentry->d_count) > 1) || (atomic_read(&ndentry->d_count) > 1))) { err = nfserr_perm; } else #endif err = vfs_rename(fdir, odentry, tdir, ndentry); if (!err && EX_ISSYNC(tfhp->fh_export)) { nfsd_sync_dir(tdentry); nfsd_sync_dir(fdentry); } dput(ndentry); out_dput_old: dput(odentry); out_nfserr: if (err) err = nfserrno(err); /* we cannot reply on fh_unlock on the two filehandles, * as that would do the wrong thing if the two directories * were the same, so again we do it by hand */ fill_post_wcc(ffhp); fill_post_wcc(tfhp); double_up(&tdir->i_sem, &fdir->i_sem); ffhp->fh_locked = tfhp->fh_locked = 0; out: return err; } /* * Unlink a file or directory * N.B. After this call fhp needs an fh_put */ int nfsd_unlink(struct svc_rqst *rqstp, struct svc_fh *fhp, int type, char *fname, int flen) { struct dentry *dentry, *rdentry; struct inode *dirp; int err; err = nfserr_acces; if (!flen || isdotent(fname, flen)) goto out; err = fh_verify(rqstp, fhp, S_IFDIR, MAY_REMOVE); if (err) goto out; fh_lock(fhp); dentry = fhp->fh_dentry; dirp = dentry->d_inode; rdentry = lookup_one_len(fname, dentry, flen); err = PTR_ERR(rdentry); if (IS_ERR(rdentry)) goto out_nfserr; if (!rdentry->d_inode) { dput(rdentry); err = nfserr_noent; goto out; } if (type != S_IFDIR) { /* It's UNLINK */ #ifdef MSNFS if ((fhp->fh_export->ex_flags & NFSEXP_MSNFS) && (atomic_read(&rdentry->d_count) > 1)) { err = nfserr_perm; } else #endif err = vfs_unlink(dirp, rdentry); } else { /* It's RMDIR */ err = vfs_rmdir(dirp, rdentry); } dput(rdentry); if (err) goto out_nfserr; if (EX_ISSYNC(fhp->fh_export)) nfsd_sync_dir(dentry); out: return err; out_nfserr: err = nfserrno(err); goto out; } /* * Read entries from a directory. * The verifier is an NFSv3 thing we ignore for now. */ int nfsd_readdir(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t offset, encode_dent_fn func, u32 *buffer, int *countp, u32 *verf) { u32 *p; int oldlen, eof, err; struct file file; struct readdir_cd cd; err = nfsd_open(rqstp, fhp, S_IFDIR, MAY_READ, &file); if (err) goto out; offset = llseek(&file, offset, 0); if (offset < 0) { err = nfserrno((int)offset); goto out_close; } /* Set up the readdir context */ memset(&cd, 0, sizeof(cd)); cd.rqstp = rqstp; cd.buffer = buffer; cd.buflen = *countp; /* count of words */ cd.dirfh = fhp; /* * Read the directory entries. This silly loop is necessary because * readdir() is not guaranteed to fill up the entire buffer, but * may choose to do less. */ do { oldlen = cd.buflen; err = vfs_readdir(&file, (filldir_t) func, &cd); if (err < 0) goto out_nfserr; } while (oldlen != cd.buflen && !cd.eob); /* If we didn't fill the buffer completely, we're at EOF */ eof = !cd.eob; offset = llseek(&file, 0LL, 1); if (cd.offset) { if (rqstp->rq_vers == 3) (void)xdr_encode_hyper(cd.offset, offset); else *cd.offset = htonl(offset); } p = cd.buffer; *p++ = 0; /* no more entries */ *p++ = htonl(eof); /* end of directory */ *countp = (caddr_t) p - (caddr_t) buffer; dprintk("nfsd: readdir result %d bytes, eof %d offset %d\n", *countp, eof, cd.offset? ntohl(*cd.offset) : -1); err = 0; out_close: nfsd_close(&file); out: return err; out_nfserr: err = nfserrno(err); goto out_close; } /* * Get file system stats * N.B. After this call fhp needs an fh_put */ int nfsd_statfs(struct svc_rqst *rqstp, struct svc_fh *fhp, struct statfs *stat) { int err = fh_verify(rqstp, fhp, 0, MAY_NOP); if (!err && vfs_statfs(fhp->fh_dentry->d_inode->i_sb,stat)) err = nfserr_io; return err; } /* * Check for a user's access permissions to this inode. */ int nfsd_permission(struct svc_export *exp, struct dentry *dentry, int acc) { struct inode *inode = dentry->d_inode; int err; if (acc == MAY_NOP) return 0; #if 0 dprintk("nfsd: permission 0x%x%s%s%s%s%s%s%s mode 0%o%s%s%s\n", acc, (acc & MAY_READ)? " read" : "", (acc & MAY_WRITE)? " write" : "", (acc & MAY_EXEC)? " exec" : "", (acc & MAY_SATTR)? " sattr" : "", (acc & MAY_TRUNC)? " trunc" : "", (acc & MAY_LOCK)? " lock" : "", (acc & MAY_OWNER_OVERRIDE)? " owneroverride" : "", inode->i_mode, IS_IMMUTABLE(inode)? " immut" : "", IS_APPEND(inode)? " append" : "", IS_RDONLY(inode)? " ro" : ""); dprintk(" owner %d/%d user %d/%d\n", inode->i_uid, inode->i_gid, current->fsuid, current->fsgid); #endif /* The following code is here to make IRIX happy, which * does a permission check every time a user does * echo yaddayadda > special-file * by sending a CREATE request. * The original code would check read-only export status * only for regular files and directories, allowing * clients to chown/chmod device files and fifos even * on volumes exported read-only. */ if (!(acc & _NFSD_IRIX_BOGOSITY) && (acc & (MAY_WRITE | MAY_SATTR | MAY_TRUNC))) { if (EX_RDONLY(exp) || IS_RDONLY(inode)) return nfserr_rofs; if (/* (acc & MAY_WRITE) && */ IS_IMMUTABLE(inode)) return nfserr_perm; } if ((acc & MAY_TRUNC) && IS_APPEND(inode)) return nfserr_perm; if (acc & MAY_LOCK) { /* If we cannot rely on authentication in NLM requests, * just allow locks, otherwise require read permission, or * ownership */ if (exp->ex_flags & NFSEXP_NOAUTHNLM) return 0; else acc = MAY_READ | MAY_OWNER_OVERRIDE; } /* * The file owner always gets access permission for accesses that * would normally be checked at open time. This is to make * file access work even when the client has done a fchmod(fd, 0). * * However, `cp foo bar' should fail nevertheless when bar is * readonly. A sensible way to do this might be to reject all * attempts to truncate a read-only file, because a creat() call * always implies file truncation. * ... but this isn't really fair. A process may reasonably call * ftruncate on an open file descriptor on a file with perm 000. * We must trust the client to do permission checking - using "ACCESS" * with NFSv3. */ if ((acc & MAY_OWNER_OVERRIDE) && inode->i_uid == current->fsuid) return 0; err = permission(inode, acc & (MAY_READ|MAY_WRITE|MAY_EXEC)); /* Allow read access to binaries even when mode 111 */ if (err == -EACCES && S_ISREG(inode->i_mode) && acc == (MAY_READ | MAY_OWNER_OVERRIDE)) err = permission(inode, MAY_EXEC); return err? nfserrno(err) : 0; } void nfsd_racache_shutdown(void) { if (!raparm_cache) return; dprintk("nfsd: freeing readahead buffers.\n"); kfree(raparml); raparm_cache = raparml = NULL; } /* * Initialize readahead param cache */ int nfsd_racache_init(int cache_size) { int i; if (raparm_cache) return 0; raparml = kmalloc(sizeof(struct raparms) * cache_size, GFP_KERNEL); if (raparml != NULL) { dprintk("nfsd: allocating %d readahead buffers.\n", cache_size); memset(raparml, 0, sizeof(struct raparms) * cache_size); for (i = 0; i < cache_size - 1; i++) { raparml[i].p_next = raparml + i + 1; } raparm_cache = raparml; } else { printk(KERN_WARNING "nfsd: Could not allocate memory read-ahead cache.\n"); return -ENOMEM; } nfsdstats.ra_size = cache_size; return 0; }
23.852651
80
0.661558
[ "object" ]
30c0997fd01aed705e817cc909f55abba89236e2
9,182
c
C
Openharmony v1.0/vendor/hisi/hi35xx/third_party/uboot/arch/x86/lib/bios.c
clkbit123/TheOpenHarmony
0e6bcd9dee9f1a2481d762966b8bbd24baad6159
[ "MIT" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.1/device/hisilicon/third_party/uboot/u-boot-2020.01/arch/x86/lib/bios.c
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.1/device/hisilicon/third_party/uboot/u-boot-2020.01/arch/x86/lib/bios.c
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: GPL-2.0 /* * From Coreboot file device/oprom/realmode/x86.c * * Copyright (C) 2007 Advanced Micro Devices, Inc. * Copyright (C) 2009-2010 coresystems GmbH */ #include <common.h> #include <bios_emul.h> #include <irq_func.h> #include <vbe.h> #include <linux/linkage.h> #include <asm/cache.h> #include <asm/processor.h> #include <asm/i8259.h> #include <asm/io.h> #include <asm/post.h> #include "bios.h" /* Interrupt handlers for each interrupt the ROM can call */ static int (*int_handler[256])(void); /* to have a common register file for interrupt handlers */ X86EMU_sysEnv _X86EMU_env; asmlinkage void (*realmode_call)(u32 addr, u32 eax, u32 ebx, u32 ecx, u32 edx, u32 esi, u32 edi); asmlinkage void (*realmode_interrupt)(u32 intno, u32 eax, u32 ebx, u32 ecx, u32 edx, u32 esi, u32 edi); static void setup_realmode_code(void) { memcpy((void *)REALMODE_BASE, &asm_realmode_code, asm_realmode_code_size); /* Ensure the global pointers are relocated properly. */ realmode_call = PTR_TO_REAL_MODE(asm_realmode_call); realmode_interrupt = PTR_TO_REAL_MODE(__realmode_interrupt); debug("Real mode stub @%x: %d bytes\n", REALMODE_BASE, asm_realmode_code_size); } static void setup_rombios(void) { const char date[] = "06/11/99"; memcpy((void *)0xffff5, &date, 8); const char ident[] = "PCI_ISA"; memcpy((void *)0xfffd9, &ident, 7); /* system model: IBM-AT */ writeb(0xfc, 0xffffe); } static int int_exception_handler(void) { /* compatibility shim */ struct eregs reg_info = { .eax = M.x86.R_EAX, .ecx = M.x86.R_ECX, .edx = M.x86.R_EDX, .ebx = M.x86.R_EBX, .esp = M.x86.R_ESP, .ebp = M.x86.R_EBP, .esi = M.x86.R_ESI, .edi = M.x86.R_EDI, .vector = M.x86.intno, .error_code = 0, .eip = M.x86.R_EIP, .cs = M.x86.R_CS, .eflags = M.x86.R_EFLG }; struct eregs *regs = &reg_info; debug("Oops, exception %d while executing option rom\n", regs->vector); cpu_hlt(); return 0; } static int int_unknown_handler(void) { debug("Unsupported software interrupt #0x%x eax 0x%x\n", M.x86.intno, M.x86.R_EAX); return -1; } /* setup interrupt handlers for mainboard */ void bios_set_interrupt_handler(int intnum, int (*int_func)(void)) { int_handler[intnum] = int_func; } static void setup_interrupt_handlers(void) { int i; /* * The first 16 int_handler functions are not BIOS services, * but the CPU-generated exceptions ("hardware interrupts") */ for (i = 0; i < 0x10; i++) int_handler[i] = &int_exception_handler; /* Mark all other int_handler calls as unknown first */ for (i = 0x10; i < 0x100; i++) { /* Skip if bios_set_interrupt_handler() isn't called first */ if (int_handler[i]) continue; /* * Now set the default functions that are actually needed * to initialize the option roms. The board may override * these with bios_set_interrupt_handler() */ switch (i) { case 0x10: int_handler[0x10] = &int10_handler; break; case 0x12: int_handler[0x12] = &int12_handler; break; case 0x16: int_handler[0x16] = &int16_handler; break; case 0x1a: int_handler[0x1a] = &int1a_handler; break; default: int_handler[i] = &int_unknown_handler; break; } } } static void write_idt_stub(void *target, u8 intnum) { unsigned char *codeptr; codeptr = (unsigned char *)target; memcpy(codeptr, &__idt_handler, __idt_handler_size); codeptr[3] = intnum; /* modify int# in the code stub. */ } static void setup_realmode_idt(void) { struct realmode_idt *idts = NULL; int i; /* * Copy IDT stub code for each interrupt. This might seem wasteful * but it is really simple */ for (i = 0; i < 256; i++) { idts[i].cs = 0; idts[i].offset = 0x1000 + (i * __idt_handler_size); write_idt_stub((void *)((ulong)idts[i].offset), i); } /* * Many option ROMs use the hard coded interrupt entry points in the * system bios. So install them at the known locations. */ /* int42 is the relocated int10 */ write_idt_stub((void *)0xff065, 0x42); /* BIOS Int 11 Handler F000:F84D */ write_idt_stub((void *)0xff84d, 0x11); /* BIOS Int 12 Handler F000:F841 */ write_idt_stub((void *)0xff841, 0x12); /* BIOS Int 13 Handler F000:EC59 */ write_idt_stub((void *)0xfec59, 0x13); /* BIOS Int 14 Handler F000:E739 */ write_idt_stub((void *)0xfe739, 0x14); /* BIOS Int 15 Handler F000:F859 */ write_idt_stub((void *)0xff859, 0x15); /* BIOS Int 16 Handler F000:E82E */ write_idt_stub((void *)0xfe82e, 0x16); /* BIOS Int 17 Handler F000:EFD2 */ write_idt_stub((void *)0xfefd2, 0x17); /* ROM BIOS Int 1A Handler F000:FE6E */ write_idt_stub((void *)0xffe6e, 0x1a); } #ifdef CONFIG_FRAMEBUFFER_SET_VESA_MODE static u8 vbe_get_mode_info(struct vbe_mode_info *mi) { u16 buffer_seg; u16 buffer_adr; char *buffer; debug("VBE: Getting information about VESA mode %04x\n", mi->video_mode); buffer = PTR_TO_REAL_MODE(asm_realmode_buffer); buffer_seg = (((unsigned long)buffer) >> 4) & 0xff00; buffer_adr = ((unsigned long)buffer) & 0xffff; realmode_interrupt(0x10, VESA_GET_MODE_INFO, 0x0000, mi->video_mode, 0x0000, buffer_seg, buffer_adr); memcpy(mi->mode_info_block, buffer, sizeof(struct vbe_mode_info)); mi->valid = true; return 0; } static u8 vbe_set_mode(struct vbe_mode_info *mi) { int video_mode = mi->video_mode; debug("VBE: Setting VESA mode %#04x\n", video_mode); /* request linear framebuffer mode */ video_mode |= (1 << 14); /* don't clear the framebuffer, we do that later */ video_mode |= (1 << 15); realmode_interrupt(0x10, VESA_SET_MODE, video_mode, 0x0000, 0x0000, 0x0000, 0x0000); return 0; } static void vbe_set_graphics(int vesa_mode, struct vbe_mode_info *mode_info) { unsigned char *framebuffer; mode_info->video_mode = (1 << 14) | vesa_mode; vbe_get_mode_info(mode_info); framebuffer = (unsigned char *)(ulong)mode_info->vesa.phys_base_ptr; debug("VBE: resolution: %dx%d@%d\n", le16_to_cpu(mode_info->vesa.x_resolution), le16_to_cpu(mode_info->vesa.y_resolution), mode_info->vesa.bits_per_pixel); debug("VBE: framebuffer: %p\n", framebuffer); if (!framebuffer) { debug("VBE: Mode does not support linear framebuffer\n"); return; } mode_info->video_mode &= 0x3ff; vbe_set_mode(mode_info); } #endif /* CONFIG_FRAMEBUFFER_SET_VESA_MODE */ void bios_run_on_x86(struct udevice *dev, unsigned long addr, int vesa_mode, struct vbe_mode_info *mode_info) { pci_dev_t pcidev = dm_pci_get_bdf(dev); u32 num_dev; num_dev = PCI_BUS(pcidev) << 8 | PCI_DEV(pcidev) << 3 | PCI_FUNC(pcidev); /* Needed to avoid exceptions in some ROMs */ interrupt_init(); /* Set up some legacy information in the F segment */ setup_rombios(); /* Set up C interrupt handlers */ setup_interrupt_handlers(); /* Set up real-mode IDT */ setup_realmode_idt(); /* Make sure the code is placed. */ setup_realmode_code(); debug("Calling Option ROM at %lx, pci device %#x...", addr, num_dev); /* Option ROM entry point is at OPROM start + 3 */ realmode_call(addr + 0x0003, num_dev, 0xffff, 0x0000, 0xffff, 0x0, 0x0); debug("done\n"); #ifdef CONFIG_FRAMEBUFFER_SET_VESA_MODE if (vesa_mode != -1) vbe_set_graphics(vesa_mode, mode_info); #endif } asmlinkage int interrupt_handler(u32 intnumber, u32 gsfs, u32 dses, u32 edi, u32 esi, u32 ebp, u32 esp, u32 ebx, u32 edx, u32 ecx, u32 eax, u32 cs_ip, u16 stackflags) { u32 ip; u32 cs; u32 flags; int ret = 0; ip = cs_ip & 0xffff; cs = cs_ip >> 16; flags = stackflags; #ifdef CONFIG_REALMODE_DEBUG debug("oprom: INT# 0x%x\n", intnumber); debug("oprom: eax: %08x ebx: %08x ecx: %08x edx: %08x\n", eax, ebx, ecx, edx); debug("oprom: ebp: %08x esp: %08x edi: %08x esi: %08x\n", ebp, esp, edi, esi); debug("oprom: ip: %04x cs: %04x flags: %08x\n", ip, cs, flags); debug("oprom: stackflags = %04x\n", stackflags); #endif /* * Fetch arguments from the stack and put them to a place * suitable for the interrupt handlers */ M.x86.R_EAX = eax; M.x86.R_ECX = ecx; M.x86.R_EDX = edx; M.x86.R_EBX = ebx; M.x86.R_ESP = esp; M.x86.R_EBP = ebp; M.x86.R_ESI = esi; M.x86.R_EDI = edi; M.x86.intno = intnumber; M.x86.R_EIP = ip; M.x86.R_CS = cs; M.x86.R_EFLG = flags; /* Call the interrupt handler for this interrupt number */ ret = int_handler[intnumber](); /* * This code is quite strange... * * Put registers back on the stack. The assembler code will pop them * later. We force (volatile!) changing the values of the parameters * of this function. We know that they stay alive on the stack after * we leave this function. */ *(volatile u32 *)&eax = M.x86.R_EAX; *(volatile u32 *)&ecx = M.x86.R_ECX; *(volatile u32 *)&edx = M.x86.R_EDX; *(volatile u32 *)&ebx = M.x86.R_EBX; *(volatile u32 *)&esi = M.x86.R_ESI; *(volatile u32 *)&edi = M.x86.R_EDI; flags = M.x86.R_EFLG; /* Pass success or error back to our caller via the CARRY flag */ if (ret) { flags &= ~1; /* no error: clear carry */ } else { debug("int%02x call returned error\n", intnumber); flags |= 1; /* error: set carry */ } *(volatile u16 *)&stackflags = flags; return ret; }
25.792135
78
0.680462
[ "vector", "model" ]
30c48c40c62a90c87133ee541de75c65944e3789
1,191
h
C
tcpip-cpp/core/TcpipBase.h
robamu-org/tcpip-demo
9240cdf0171c3b8f6b86839661afb090459a2677
[ "Apache-2.0" ]
1
2021-05-15T23:07:12.000Z
2021-05-15T23:07:12.000Z
tcpip-cpp/core/TcpipBase.h
spacefisch/tcpip-demo
9240cdf0171c3b8f6b86839661afb090459a2677
[ "Apache-2.0" ]
null
null
null
tcpip-cpp/core/TcpipBase.h
spacefisch/tcpip-demo
9240cdf0171c3b8f6b86839661afb090459a2677
[ "Apache-2.0" ]
null
null
null
#pragma once #include "tcpipCommon.h" #include <demoConfig.h> #include <vector> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #elif defined(__unix__) #include <netdb.h> #endif /** * Generic base class for TCPIP classes like. Encapsulates common components to reduce * boilerplate and duplicate code. */ class TcpipBase { public: TcpipBase() = delete; TcpipBase(tcpip::DemoConfig& cfg, size_t reception_buf_size); virtual~ TcpipBase(); virtual int performOperation() = 0; protected: #ifdef _WIN32 static constexpr int SHUT_RECV = SD_RECEIVE; static constexpr int SHUT_SEND = SD_SEND; static constexpr int SHUT_BOTH = SD_BOTH; #elif defined(__unix__) static constexpr int INVALID_SOCKET = -1; static constexpr int SOCKET_ERROR = -1; static constexpr int SHUT_RECV = SHUT_RD; static constexpr int SHUT_SEND = SHUT_WR; static constexpr int SHUT_BOTH = SHUT_RDWR; #endif virtual int setup(struct addrinfo& hints) = 0; tcpip::DemoProtocols prot; tcpip::DemoTypes type; tcpip::DemoModes mode; std::string server_address; std::string server_port; std::vector<uint8_t> reception_buffer; };
19.85
86
0.715365
[ "vector" ]
30c6b24240772ae86f6858f744c20396716cd0b9
875
h
C
XCDYouTubeKit Demo/iOS Demo/MPMoviePlayerController+BackgroundPlayback.h
BreeeZe/XCDYouTubeKit
7b4c57a8bf1fa521c382b069889b3a56c1c44107
[ "MIT" ]
18
2018-06-03T19:50:48.000Z
2021-11-09T10:16:42.000Z
XCDYouTubeKit Demo/iOS Demo/MPMoviePlayerController+BackgroundPlayback.h
BreeeZe/XCDYouTubeKit
7b4c57a8bf1fa521c382b069889b3a56c1c44107
[ "MIT" ]
1
2018-06-03T19:01:15.000Z
2018-06-03T19:55:55.000Z
XCDYouTubeKit Demo/iOS Demo/MPMoviePlayerController+BackgroundPlayback.h
BreeeZe/XCDYouTubeKit
7b4c57a8bf1fa521c382b069889b3a56c1c44107
[ "MIT" ]
2
2018-06-03T17:15:40.000Z
2019-12-13T19:46:43.000Z
// // Copyright (c) 2013-2016 Cédric Luthi. All rights reserved. // @import MediaPlayer; @interface MPMoviePlayerController (BackgroundPlayback) /** * When enabling background playback: * - The `UIBackgroundModes` array (Required background modes) in the application Info.plist file must contain the `audio` element (App plays audio or streams audio/video using AirPlay). * - The audio session category must be set to `AVAudioSessionCategoryPlayback`. * * @discussion On iOS < 7, the `backgroundPlaybackEnabled` property does nothing. Instead, you must set the `PlayVideoInBackground` boolean user default used by the MediaPlayer framework. The `PlayVideoInBackground` user default must be set before a `MPMoviePlayerController` object is created. */ @property (nonatomic, assign, getter = isBackgroundPlaybackEnabled) BOOL backgroundPlaybackEnabled; @end
46.052632
295
0.779429
[ "object" ]
30cea893a72cd8be1ed750bb50e2a6a0d3302127
6,171
c
C
kernels/c/dft7c_c.c
spiral-software/spiral-package-ffte
19f751776c117e28bdbcc3d2530c895ad554d855
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
kernels/c/dft7c_c.c
spiral-software/spiral-package-ffte
19f751776c117e28bdbcc3d2530c895ad554d855
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
kernels/c/dft7c_c.c
spiral-software/spiral-package-ffte
19f751776c117e28bdbcc3d2530c895ad554d855
[ "BSD-2-Clause-FreeBSD" ]
1
2021-06-15T12:41:51.000Z
2021-06-15T12:41:51.000Z
/* FFTE: A FAST FOURIER TRANSFORM PACKAGE (C) COPYRIGHT SOFTWARE, 2000-2004, 2008-2014, ALL RIGHTS RESERVED BY DAISUKE TAKAHASHI FACULTY OF ENGINEERING, INFORMATION AND SYSTEMS UNIVERSITY OF TSUKUBA 1-1-1 TENNODAI, TSUKUBA, IBARAKI 305-8573, JAPAN E-MAIL: daisuke@cs.tsukuba.ac.jp WRITTEN BY DAISUKE TAKAHASHI THIS KERNEL WAS GENERATED BY SPIRAL 8.2.0a03 */ void dft7c_(double *Y, double *X, int *lp1, int *mp1) { double s670, s671, s672, s673, s674, s675, s676, s677, s678, s679, s680, s681, s682, s683, s684, s685, s686, s687, s688, s689, s690, s691, s692, s693, s694, s695, s696, s697, s698, s699, s700, s701, s702, s703, s704, s705, s706, s707, s708, s709, t1798, t1799, t1800, t1801, t1802, t1803, t1804, t1805, t1806, t1807, t1808, t1809, t1810, t1811, t1812, t1813, t1814, t1815, t1816, t1817, t1818, t1819, t1820, t1821, t1822, t1823, t1824, t1825, t1826, t1827, t1828, t1829, t1830, t1831, t1832, t1833, t1834, t1835, t1836, t1837, t1838, t1839, t1840, t1841, t1842, t1843, t1844, t1845, t1846, t1847, t1848, t1849; int a903, a904, a905, a906, a907, a908, a909, a910, a911, a912, a913, a914, a915, a916, b31, l1, m1; l1 = *(lp1); m1 = *(mp1); for(int k1 = 0; k1 < m1; k1++) { a903 = (2*k1); s670 = X[a903]; a904 = (a903 + 1); s671 = X[a904]; b31 = (l1*m1); a905 = (a903 + (2*b31)); s672 = X[a905]; s673 = X[(a905 + 1)]; a906 = (a903 + (4*b31)); s674 = X[a906]; s675 = X[(a906 + 1)]; a907 = (a903 + (6*b31)); s676 = X[a907]; s677 = X[(a907 + 1)]; a908 = (a903 + (8*b31)); s678 = X[a908]; s679 = X[(a908 + 1)]; a909 = (a903 + (10*b31)); s680 = X[a909]; s681 = X[(a909 + 1)]; a910 = (a903 + (12*b31)); s682 = X[a910]; s683 = X[(a910 + 1)]; t1798 = (s674 + s678); t1799 = (s675 + s679); t1800 = (s672 + t1798); t1801 = (s673 + t1799); t1802 = (s672 - (0.5*t1798)); t1803 = (s673 - (0.5*t1799)); s684 = (0.8660254037844386*(s675 - s679)); s685 = (0.8660254037844386*(s674 - s678)); t1804 = (t1802 + s684); t1805 = (t1803 - s685); t1806 = (t1802 - s684); t1807 = (t1803 + s685); t1808 = (s682 + s680); t1809 = (s683 + s681); t1810 = (s676 + t1808); t1811 = (s677 + t1809); t1812 = (s676 - (0.5*t1808)); t1813 = (s677 - (0.5*t1809)); s686 = (0.8660254037844386*(s683 - s681)); s687 = (0.8660254037844386*(s682 - s680)); t1814 = (t1812 + s686); t1815 = (t1813 - s687); t1816 = (t1812 - s686); t1817 = (t1813 + s687); s688 = ((0.5*t1814) + (0.8660254037844386*t1815)); s689 = ((0.5*t1815) - (0.8660254037844386*t1814)); s690 = ((0.8660254037844386*t1817) - (0.5*t1816)); s691 = ((0.8660254037844386*t1816) + (0.5*t1817)); t1818 = (t1800 + t1810); t1819 = (t1801 + t1811); t1820 = (t1804 + s688); t1821 = (t1805 + s689); t1822 = (t1804 - s688); t1823 = (t1805 - s689); t1824 = (t1806 + s690); t1825 = (t1807 - s691); t1826 = (t1806 - s690); t1827 = (t1807 + s691); t1828 = (s670 - (0.16666666666666666*t1818)); t1829 = (s671 - (0.16666666666666666*t1819)); s692 = ((0.4066888930575896*t1820) + (0.17043646531196571*t1821)); s693 = ((0.4066888930575896*t1821) - (0.17043646531196571*t1820)); s694 = ((0.39507823426270006*t1824) + (0.1958510486474645*t1825)); s695 = ((0.39507823426270006*t1825) - (0.1958510486474645*t1824)); s696 = (0.44095855184409843*(t1801 - t1811)); s697 = (0.44095855184409843*(t1800 - t1810)); s698 = ((0.39507823426270006*t1822) - (0.1958510486474645*t1823)); s699 = ((0.1958510486474645*t1822) + (0.39507823426270006*t1823)); s700 = ((0.17043646531196566*t1827) - (0.4066888930575896*t1826)); s701 = ((0.17043646531196566*t1826) + (0.4066888930575896*t1827)); t1830 = (s694 + s698); t1831 = (s695 + s699); t1832 = (t1828 + t1830); t1833 = (t1829 + t1831); t1834 = (t1828 - (0.5*t1830)); t1835 = (t1829 - (0.5*t1831)); s702 = (0.8660254037844386*(s695 - s699)); s703 = (0.8660254037844386*(s694 - s698)); t1836 = (t1834 + s702); t1837 = (t1835 - s703); t1838 = (t1834 - s702); t1839 = (t1835 + s703); t1840 = (s696 + s700); t1841 = (s697 + s701); t1842 = (s692 + t1840); t1843 = (s693 - t1841); t1844 = (s692 - (0.5*t1840)); t1845 = (s693 + (0.5*t1841)); s704 = (0.8660254037844386*(s701 - s697)); s705 = (0.8660254037844386*(s696 - s700)); t1846 = (t1844 + s704); t1847 = (t1845 - s705); t1848 = (t1844 - s704); t1849 = (t1845 + s705); s706 = ((0.5*t1846) + (0.8660254037844386*t1847)); s707 = ((0.5*t1847) - (0.8660254037844386*t1846)); s708 = ((0.8660254037844386*t1849) - (0.5*t1848)); s709 = ((0.8660254037844386*t1848) + (0.5*t1849)); Y[a903] = (s670 + t1818); Y[a904] = (s671 + t1819); a911 = (a903 + (2*m1)); Y[a911] = (t1832 + t1842); Y[(a911 + 1)] = (t1833 + t1843); a912 = (a903 + (4*m1)); Y[a912] = (t1838 + s708); Y[(a912 + 1)] = (t1839 - s709); a913 = (a903 + (6*m1)); Y[a913] = (t1836 + s706); Y[(a913 + 1)] = (t1837 + s707); a914 = (a903 + (8*m1)); Y[a914] = (t1836 - s706); Y[(a914 + 1)] = (t1837 - s707); a915 = (a903 + (10*m1)); Y[a915] = (t1838 - s708); Y[(a915 + 1)] = (t1839 + s709); a916 = (a903 + (12*m1)); Y[a916] = (t1832 - t1842); Y[(a916 + 1)] = (t1833 - t1843); } }
38.092593
74
0.497488
[ "transform" ]
30d68c3a1d96484a63cc18b0d53b8b650b25f0df
4,718
h
C
include/ozz/animation/runtime/skeleton_utils.h
elix22/ozz-animation
5a00ca8cc799abc50a5e82089b57c8cbe8970e0c
[ "MIT" ]
1,666
2015-08-17T18:48:06.000Z
2022-03-31T05:13:15.000Z
include/ozz/animation/runtime/skeleton_utils.h
elix22/ozz-animation
5a00ca8cc799abc50a5e82089b57c8cbe8970e0c
[ "MIT" ]
126
2015-08-25T18:18:07.000Z
2022-03-31T19:32:32.000Z
include/ozz/animation/runtime/skeleton_utils.h
elix22/ozz-animation
5a00ca8cc799abc50a5e82089b57c8cbe8970e0c
[ "MIT" ]
244
2015-08-27T05:31:43.000Z
2022-03-29T09:03:00.000Z
//----------------------------------------------------------------------------// // // // ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation // // and distributed under the MIT License (MIT). // // // // Copyright (c) Guillaume Blanc // // // // 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 OZZ_OZZ_ANIMATION_RUNTIME_SKELETON_UTILS_H_ #define OZZ_OZZ_ANIMATION_RUNTIME_SKELETON_UTILS_H_ #include "ozz/animation/runtime/skeleton.h" #include "ozz/base/maths/transform.h" #include <cassert> namespace ozz { namespace animation { // Get bind-pose of a skeleton joint. ozz::math::Transform GetJointLocalBindPose(const Skeleton& _skeleton, int _joint); // Test if a joint is a leaf. _joint number must be in range [0, num joints]. // "_joint" is a leaf if it's the last joint, or next joint's parent isn't // "_joint". inline bool IsLeaf(const Skeleton& _skeleton, int _joint) { const int num_joints = _skeleton.num_joints(); assert(_joint >= 0 && _joint < num_joints && "_joint index out of range"); const span<const int16_t>& parents = _skeleton.joint_parents(); const int next = _joint + 1; return next == num_joints || parents[next] != _joint; } // Applies a specified functor to each joint in a depth-first order. // _Fct is of type void(int _current, int _parent) where the first argument is // the child of the second argument. _parent is kNoParent if the // _current joint is a root. _from indicates the joint from which the joint // hierarchy traversal begins. Use Skeleton::kNoParent to traverse the // whole hierarchy, in case there are multiple roots. template <typename _Fct> inline _Fct IterateJointsDF(const Skeleton& _skeleton, _Fct _fct, int _from = Skeleton::kNoParent) { const span<const int16_t>& parents = _skeleton.joint_parents(); const int num_joints = _skeleton.num_joints(); // // parents[i] >= _from is true as long as "i" is a child of "_from". static_assert(Skeleton::kNoParent < 0, "Algorithm relies on kNoParent being negative"); for (int i = _from < 0 ? 0 : _from, process = i < num_joints; process; ++i, process = i < num_joints && parents[i] >= _from) { _fct(i, parents[i]); } return _fct; } // Applies a specified functor to each joint in a reverse (from leaves to root) // depth-first order. _Fct is of type void(int _current, int _parent) where the // first argument is the child of the second argument. _parent is kNoParent if // the _current joint is a root. template <typename _Fct> inline _Fct IterateJointsDFReverse(const Skeleton& _skeleton, _Fct _fct) { const span<const int16_t>& parents = _skeleton.joint_parents(); for (int i = _skeleton.num_joints() - 1; i >= 0; --i) { _fct(i, parents[i]); } return _fct; } } // namespace animation } // namespace ozz #endif // OZZ_OZZ_ANIMATION_RUNTIME_SKELETON_UTILS_H_
51.846154
80
0.590716
[ "transform" ]
30d8add8c6df26b688dc2548058065ebcbcb591c
9,781
h
C
trunk/third_party/webrtc/voice_engine/include/voe_rtp_rtcp.h
goddino/libjingle
9516bee51c73af4c3082e74b88ed1198a0eb2bb1
[ "BSL-1.0", "BSD-3-Clause" ]
7
2015-08-06T01:46:07.000Z
2020-10-20T09:14:58.000Z
trunk/third_party/webrtc/voice_engine/include/voe_rtp_rtcp.h
goddino/libjingle
9516bee51c73af4c3082e74b88ed1198a0eb2bb1
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
trunk/third_party/webrtc/voice_engine/include/voe_rtp_rtcp.h
goddino/libjingle
9516bee51c73af4c3082e74b88ed1198a0eb2bb1
[ "BSL-1.0", "BSD-3-Clause" ]
16
2015-01-08T01:47:24.000Z
2022-02-25T06:06:06.000Z
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // This sub-API supports the following functionalities: // // - Callbacks for RTP and RTCP events such as modified SSRC or CSRC. // - SSRC handling. // - Transmission of RTCP sender reports. // - Obtaining RTCP data from incoming RTCP sender reports. // - RTP and RTCP statistics (jitter, packet loss, RTT etc.). // - Forward Error Correction (FEC). // - Writing RTP and RTCP packets to binary files for off-line analysis of // the call quality. // - Inserting extra RTP packets into active audio stream. // // Usage example, omitting error checking: // // using namespace webrtc; // VoiceEngine* voe = VoiceEngine::Create(); // VoEBase* base = VoEBase::GetInterface(voe); // VoERTP_RTCP* rtp_rtcp = VoERTP_RTCP::GetInterface(voe); // base->Init(); // int ch = base->CreateChannel(); // ... // rtp_rtcp->SetLocalSSRC(ch, 12345); // ... // base->DeleteChannel(ch); // base->Terminate(); // base->Release(); // rtp_rtcp->Release(); // VoiceEngine::Delete(voe); // #ifndef WEBRTC_VOICE_ENGINE_VOE_RTP_RTCP_H #define WEBRTC_VOICE_ENGINE_VOE_RTP_RTCP_H #include <vector> #include "webrtc/common_types.h" namespace webrtc { class VoiceEngine; // VoERTPObserver class WEBRTC_DLLEXPORT VoERTPObserver { public: virtual void OnIncomingCSRCChanged( int channel, unsigned int CSRC, bool added) = 0; virtual void OnIncomingSSRCChanged( int channel, unsigned int SSRC) = 0; protected: virtual ~VoERTPObserver() {} }; // VoERTCPObserver class WEBRTC_DLLEXPORT VoERTCPObserver { public: virtual void OnApplicationDataReceived( int channel, unsigned char subType, unsigned int name, const unsigned char* data, unsigned short dataLengthInBytes) = 0; protected: virtual ~VoERTCPObserver() {} }; // CallStatistics struct CallStatistics { unsigned short fractionLost; unsigned int cumulativeLost; unsigned int extendedMax; unsigned int jitterSamples; int rttMs; int bytesSent; int packetsSent; int bytesReceived; int packetsReceived; }; // See section 6.4.1 in http://www.ietf.org/rfc/rfc3550.txt for details. struct SenderInfo { uint32_t NTP_timestamp_high; uint32_t NTP_timestamp_low; uint32_t RTP_timestamp; uint32_t sender_packet_count; uint32_t sender_octet_count; }; // See section 6.4.2 in http://www.ietf.org/rfc/rfc3550.txt for details. struct ReportBlock { uint32_t sender_SSRC; // SSRC of sender uint32_t source_SSRC; uint8_t fraction_lost; uint32_t cumulative_num_packets_lost; uint32_t extended_highest_sequence_number; uint32_t interarrival_jitter; uint32_t last_SR_timestamp; uint32_t delay_since_last_SR; }; // VoERTP_RTCP class WEBRTC_DLLEXPORT VoERTP_RTCP { public: // Factory for the VoERTP_RTCP sub-API. Increases an internal // reference counter if successful. Returns NULL if the API is not // supported or if construction fails. static VoERTP_RTCP* GetInterface(VoiceEngine* voiceEngine); // Releases the VoERTP_RTCP sub-API and decreases an internal // reference counter. Returns the new reference count. This value should // be zero for all sub-API:s before the VoiceEngine object can be safely // deleted. virtual int Release() = 0; // Registers an instance of a VoERTPObserver derived class for a specified // |channel|. It will allow the user to observe callbacks related to the // RTP protocol such as changes in the incoming SSRC. virtual int RegisterRTPObserver(int channel, VoERTPObserver& observer) = 0; // Deregisters an instance of a VoERTPObserver derived class for a // specified |channel|. virtual int DeRegisterRTPObserver(int channel) = 0; // Registers an instance of a VoERTCPObserver derived class for a specified // |channel|. virtual int RegisterRTCPObserver( int channel, VoERTCPObserver& observer) = 0; // Deregisters an instance of a VoERTCPObserver derived class for a // specified |channel|. virtual int DeRegisterRTCPObserver(int channel) = 0; // Sets the local RTP synchronization source identifier (SSRC) explicitly. virtual int SetLocalSSRC(int channel, unsigned int ssrc) = 0; // Gets the local RTP SSRC of a specified |channel|. virtual int GetLocalSSRC(int channel, unsigned int& ssrc) = 0; // Gets the SSRC of the incoming RTP packets. virtual int GetRemoteSSRC(int channel, unsigned int& ssrc) = 0; // Sets the status of rtp-audio-level-indication on a specific |channel|. virtual int SetRTPAudioLevelIndicationStatus( int channel, bool enable, unsigned char ID = 1) = 0; // Sets the status of rtp-audio-level-indication on a specific |channel|. virtual int GetRTPAudioLevelIndicationStatus( int channel, bool& enabled, unsigned char& ID) = 0; // Gets the CSRCs of the incoming RTP packets. virtual int GetRemoteCSRCs(int channel, unsigned int arrCSRC[15]) = 0; // Sets the RTCP status on a specific |channel|. virtual int SetRTCPStatus(int channel, bool enable) = 0; // Gets the RTCP status on a specific |channel|. virtual int GetRTCPStatus(int channel, bool& enabled) = 0; // Sets the canonical name (CNAME) parameter for RTCP reports on a // specific |channel|. virtual int SetRTCP_CNAME(int channel, const char cName[256]) = 0; // Gets the canonical name (CNAME) parameter for RTCP reports on a // specific |channel|. virtual int GetRTCP_CNAME(int channel, char cName[256]) = 0; // Gets the canonical name (CNAME) parameter for incoming RTCP reports // on a specific channel. virtual int GetRemoteRTCP_CNAME(int channel, char cName[256]) = 0; // Gets RTCP data from incoming RTCP Sender Reports. virtual int GetRemoteRTCPData( int channel, unsigned int& NTPHigh, unsigned int& NTPLow, unsigned int& timestamp, unsigned int& playoutTimestamp, unsigned int* jitter = NULL, unsigned short* fractionLost = NULL) = 0; // Gets RTP statistics for a specific |channel|. virtual int GetRTPStatistics( int channel, unsigned int& averageJitterMs, unsigned int& maxJitterMs, unsigned int& discardedPackets) = 0; // Gets RTCP statistics for a specific |channel|. virtual int GetRTCPStatistics(int channel, CallStatistics& stats) = 0; // Gets the sender info part of the last received RTCP Sender Report (SR) // on a specified |channel|. virtual int GetRemoteRTCPSenderInfo( int channel, SenderInfo* sender_info) = 0; // Gets the report block parts of the last received RTCP Sender Report (SR), // or RTCP Receiver Report (RR) on a specified |channel|. Each vector // element also contains the SSRC of the sender in addition to a report // block. virtual int GetRemoteRTCPReportBlocks( int channel, std::vector<ReportBlock>* receive_blocks) = 0; // Sends an RTCP APP packet on a specific |channel|. virtual int SendApplicationDefinedRTCPPacket( int channel, unsigned char subType, unsigned int name, const char* data, unsigned short dataLengthInBytes) = 0; // Sets the Forward Error Correction (FEC) status on a specific |channel|. virtual int SetFECStatus( int channel, bool enable, int redPayloadtype = -1) = 0; // Gets the FEC status on a specific |channel|. virtual int GetFECStatus( int channel, bool& enabled, int& redPayloadtype) = 0; // This function enables Negative Acknowledgment (NACK) using RTCP, // implemented based on RFC 4585. NACK retransmits RTP packets if lost on // the network. This creates a lossless transport at the expense of delay. // If using NACK, NACK should be enabled on both endpoints in a call. virtual int SetNACKStatus(int channel, bool enable, int maxNoPackets) = 0; // Enables capturing of RTP packets to a binary file on a specific // |channel| and for a given |direction|. The file can later be replayed // using e.g. RTP Tools rtpplay since the binary file format is // compatible with the rtpdump format. virtual int StartRTPDump( int channel, const char fileNameUTF8[1024], RTPDirections direction = kRtpIncoming) = 0; // Disables capturing of RTP packets to a binary file on a specific // |channel| and for a given |direction|. virtual int StopRTPDump( int channel, RTPDirections direction = kRtpIncoming) = 0; // Gets the the current RTP capturing state for the specified // |channel| and |direction|. virtual int RTPDumpIsActive( int channel, RTPDirections direction = kRtpIncoming) = 0; // Sends an extra RTP packet using an existing/active RTP session. // It is possible to set the payload type, marker bit and payload // of the extra RTP virtual int InsertExtraRTPPacket( int channel, unsigned char payloadType, bool markerBit, const char* payloadData, unsigned short payloadSize) = 0; // Gets the timestamp of the last RTP packet received by |channel|. virtual int GetLastRemoteTimeStamp(int channel, uint32_t* lastRemoteTimeStamp) = 0; protected: VoERTP_RTCP() {} virtual ~VoERTP_RTCP() {} }; } // namespace webrtc #endif // #ifndef WEBRTC_VOICE_ENGINE_VOE_RTP_RTCP_H
36.496269
80
0.705347
[ "object", "vector" ]
30df8ba0f3d132be3ff5a1222cbb666e201e9ebd
36,132
h
C
implementations/ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashGrid.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashGrid.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/ball/src/include/BALL/DATATYPE/hashGrid.h
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #ifndef BALL_DATATYPE_HASHGRID_H #define BALL_DATATYPE_HASHGRID_H #ifndef BALL_COMMON_H # include <BALL/common.h> #endif #ifndef BALL_CONCEPT_FORWARDITERATOR_H # include <BALL/CONCEPT/forwardIterator.h> #endif #ifndef BALL_CONCEPT_VISITOR_H # include <BALL/CONCEPT/visitor.h> #endif #ifndef BALL_CONCEPT_PROCESSOR_H # include <BALL/CONCEPT/processor.h> #endif #ifndef BALL_MATHS_VECTOR3_H # include <BALL/MATHS/vector3.h> #endif #ifdef BALL_HAS_GNU_SLIST #include <ext/slist> #else #include <list> #endif #include <algorithm> namespace BALL { namespace __private { extern const char BALL_EXPORT neighbour_table_[27][3]; } template <typename Item> class HashGrid3; /** \defgroup GenericHash3D Three-dimensional Hash Grid \ingroup GenericHash */ //@{ /** Grid Box Class. These boxes represent the buckets of a threedimensional hash grid. Every such box contains a linear list of the objects that are contained in this box. This list is accessible through a DataIterator. \par \ingroup GenericHash3D */ template <typename Item> class HashGridBox3 { public: /** @name Constructors and Destructors */ //@{ /// Default constructor HashGridBox3(HashGrid3<Item>* parent); /// Clears the grid box void clear(); /** Clears the grid box. Same as clear. */ void destroy(); //@} /** @name Assignment */ //@{ //@} /** @name Accessors */ //@{ void setParent(HashGrid3<Item>* p); /** * Return the indices of this box in the parent HashGrid */ void getIndices(Position& x, Position& y, Position& z); /** Find an item in the item list of this grid box. @param item the item to be searched for @return a pointer to the desired item or a NULL pointer, if the item could not be found. */ Item* find(const Item &item); /// The const version of find() const Item* find(const Item& item) const; /** Counts all items in the data item list. @return the size of the data item list. */ Size getSize() const; /** Insert an item into the data item list of a grid box. @param item the item to be inserted */ void insert(const Item& item); /** Remove the first occurrence of a certain item from the data item list. @param item the item to be removed @return bool - <tt>true</tt>, if the item could be removed, <tt>false</tt> otherwise. */ bool remove(const Item& item); /** Remove all occurences of a certain item from the data item list. @param item the item to be removed @return bool - <tt>true</tt>, if the item could be removed, <tt>false</tt> otherwise. */ bool removeAll(const Item& item); //@} /** @name Miscellaneous */ //@{ /// Host method void host(Visitor<HashGridBox3> &visitor); //@} /** @name Predicates */ //@{ /// Equality operator bool operator == (const HashGridBox3& box) const; /// Inequality operator bool operator != (const HashGridBox3& box) const; /** Test whether an item is in the data item list @param item @return bool - <tt>true</tt> if instance has <tt>item</tt>, <tt>false</tt> otherwise. */ bool has(const Item& item) const; /** Test, whether this box is empty, i. e. the data item list contains nothing @return bool - <tt>true</tt>, if <tt>this</tt> is empty. <tt>false</tt> otherwise. */ bool isEmpty() const; //@} /** @name Debugging and Diagnostics */ //@{ /// bool isValid() const; /// void dump(std::ostream& s = std::cout, Size depth = 0) const; //@} /** @name Internal Iterators */ //@{ /// bool apply(UnaryProcessor<Item>& processor); /// bool apply(UnaryProcessor< HashGridBox3<Item> >& processor); //@} /** @name External Iterators */ //@{ typedef Position BoxIteratorPosition; class BoxIteratorTraits { public: BALL_CREATE_DEEP(BoxIteratorTraits) virtual ~BoxIteratorTraits() {} BoxIteratorTraits() : bound_(0), position_(0), x_(0), y_(0), z_(0) { } BoxIteratorTraits(const HashGridBox3& box) : bound_((HashGridBox3 *)&box), position_(0) { bound_->getIndices(x_, y_, z_); } BoxIteratorTraits(const BoxIteratorTraits& traits, bool /* deep */ = true) : bound_(traits.bound_), position_(traits.position_) { } HashGridBox3* getContainer() { return bound_; } const HashGridBox3* getContainer() const { return bound_; } bool isSingular() const { return (bound_ == 0); } BoxIteratorPosition& getPosition() { return position_; } const BoxIteratorPosition& getPosition() const { return position_; } bool operator == (const BoxIteratorTraits& traits) const { return (position_ == traits.position_); } bool operator != (const BoxIteratorTraits& traits) const { return (position_ != traits.position_); } bool isValid() const { return (bound_ != 0 && position_ < 27); } void invalidate() { bound_ = 0; position_ = 100; } void toBegin() { position_ = 0; cur_box_ = bound_; } bool isBegin() const { return (position_ == 0); } void toEnd() { position_ = 27; cur_box_ = 0; } bool isEnd() const { return (position_ == 27); } HashGridBox3<Item>& getData() { return *cur_box_; } const HashGridBox3<Item>& getData() const { return *cur_box_; } void forward() { ++position_; // iterate to the next existing box while ( position_ < 27 && !(cur_box_ = bound_->parent->getBox(x_ + __private::neighbour_table_[position_][0], y_ + __private::neighbour_table_[position_][1], z_ + __private::neighbour_table_[position_][2]))) { ++position_; } } private: HashGridBox3<Item> *bound_; HashGridBox3<Item> *cur_box_; BoxIteratorPosition position_; Position x_, y_, z_; }; friend class BoxIteratorTraits; /** BoxIterators iterate over all boxes that lie in the direct neighborhood to a box, and over the box itself. Such an iterator traverses over 27 boxes. */ typedef ForwardIterator <HashGridBox3<Item>, HashGridBox3<Item>, BoxIteratorPosition, BoxIteratorTraits> BoxIterator; /// get the first box BoxIterator beginBox() { return BoxIterator::begin(*this); } /// get the last box BoxIterator endBox() { return BoxIterator::end(*this); } /// This is the const version of \link BoxIterator BoxIterator \endlink typedef ConstForwardIterator <HashGridBox3<Item>, HashGridBox3<Item>, BoxIteratorPosition, BoxIteratorTraits> ConstBoxIterator; /// get the first box ConstBoxIterator beginBox() const { return ConstBoxIterator::begin(*this); } /// get the last box ConstBoxIterator endBox() const { return ConstBoxIterator::end(*this); } #ifdef BALL_HAS_GNU_SLIST typedef typename __gnu_cxx::slist<Item> DataContainer; #else typedef typename std::list<Item> DataContainer; #endif typedef typename DataContainer::iterator DataIteratorPosition; class DataIteratorTraits { public: BALL_CREATE_DEEP(DataIteratorTraits) virtual ~DataIteratorTraits() {} DataIteratorTraits() : bound_(0), position_() { } DataIteratorTraits(const HashGridBox3& box) : bound_((HashGridBox3 *)&box), position_(bound_->data.begin()) { } DataIteratorTraits(const DataIteratorTraits& traits, bool /* deep */ = true) : bound_(traits.bound_), position_(traits.position_) { } const DataIteratorTraits& operator = (const DataIteratorTraits &traits) { bound_ = traits.bound_; position_ = traits.position_; return *this; } HashGridBox3* getContainer() { return bound_; } const HashGridBox3* getContainer() const { return bound_; } bool isSingular() const { return (bound_ == 0); } DataIteratorPosition& getPosition() { return position_; } const DataIteratorPosition& getPosition() const { return position_; } bool operator == (const DataIteratorTraits &traits) const { return (position_ == traits.position_); } bool operator != (const DataIteratorTraits &traits) const { return (position_ != traits.position_); } bool isValid() const { return (bound_ != 0 && position_ != bound_->data.end()); } void invalidate() { bound_ = 0; position_ = bound_->data.end(); } void toBegin() { position_ = bound_->data.begin(); } bool isBegin() const { return (position_ == bound_->data.begin()); } void toEnd() { position_ = bound_->data.end(); } bool isEnd() const { return (position_ == bound_->data.end()); } Item& getData() { return *position_; } const Item& getData() const { return *position_; } void forward() { ++position_; } private: HashGridBox3<Item>* bound_; DataIteratorPosition position_; }; friend class DataIteratorTraits; /** Data iterator for grid boxes. This iterator traverses the list of data items store in a \link HashGridBox3 HashGridBox3 \endlink . */ typedef ForwardIterator <HashGridBox3<Item>, Item, DataIteratorPosition, DataIteratorTraits> DataIterator; /// DataIterator beginData() { return DataIterator::begin(*this); } /// DataIterator endData() { return DataIterator::end(*this); } /** Const data iterator for grid boxes. This is the const version of \link DataIterator DataIterator \endlink */ typedef ConstForwardIterator <HashGridBox3<Item>, Item, DataIteratorPosition, DataIteratorTraits> ConstDataIterator; /// ConstDataIterator beginData() const { return ConstDataIterator::begin(*this); } /// ConstDataIterator endData() const { return ConstDataIterator::end(*this); } //@} HashGrid3<Item>* parent; DataContainer data; }; template<typename Item> HashGridBox3<Item>::HashGridBox3(HashGrid3<Item>* p) : parent(p) { } template<typename Item> void HashGridBox3<Item>::clear() { data.clear(); } template<typename Item> BALL_INLINE void HashGridBox3<Item>::destroy() { clear(); } template<typename Item> BALL_INLINE void HashGridBox3<Item>::setParent(HashGrid3<Item>* p) { parent = p; } template<typename Item> BALL_INLINE void HashGridBox3<Item>::getIndices(Position& x, Position& y, Position& z) { parent->getIndices(*this, x, y, z); } template<typename Item> Item* HashGridBox3<Item>::find(const Item& item) { typename DataContainer::iterator found = std::find(data.begin(), data.end(), item); if (found != data.end()) { return &(*found); } return 0; } template<typename Item> BALL_INLINE const Item* HashGridBox3<Item>::find(const Item& item) const { return const_cast<HashGridBox3*>(this)->find(item); } template<typename Item> Size HashGridBox3<Item>::getSize() const { return data.size(); } template<typename Item> BALL_INLINE void HashGridBox3<Item>::insert(const Item& item) { data.push_front(item); } template<typename Item> bool HashGridBox3<Item>::remove(const Item& item) { #ifdef BALL_HAS_GNU_SLIST if(data.empty()) { return false; } if(*data.begin() == item) { data.pop_front(); return true; } DataIteratorPosition prev = data.begin(); DataIteratorPosition pos = prev; for(++pos; pos != data.end(); ++pos) { if(*pos == item) { data.erase_after(prev); return true; } prev = pos; } return false; #else DataIteratorPosition pos = std::find(data.begin(), data.end(), item); if (pos != data.end()) { data.erase(pos); return true; } return false; #endif } template<typename Item> bool HashGridBox3<Item>::removeAll(const Item& item) { data.remove(item); return true; } template <typename Item> BALL_INLINE void HashGridBox3<Item>::host(Visitor< HashGridBox3<Item> >& visitor) { visitor.visit(*this); } template<typename Item> bool HashGridBox3<Item>::operator == (const HashGridBox3<Item>& box) const { return (data == box.data); } template<typename Item> BALL_INLINE bool HashGridBox3<Item>::operator != (const HashGridBox3<Item>& box) const { return !(*this == box); } template<typename Item> BALL_INLINE bool HashGridBox3<Item>::has(const Item& item) const { return (std::find(data.begin(), data.end(), item) != data.end()); } template<typename Item> BALL_INLINE bool HashGridBox3<Item>::isEmpty() const { return data.empty(); } template<typename Item> bool HashGridBox3<Item>::isValid() const { // this is no longer required... return true; } template<typename Item> void HashGridBox3<Item>::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " size: " << getSize() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " data:" << std::endl; for (typename DataContainer::const_iterator d_it = data.begin(); d_it != data.end(); ++d_it) { BALL_DUMP_DEPTH(s, depth); s << " " << *d_it << std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template <typename Item> bool HashGridBox3<Item>::apply(UnaryProcessor<Item>& processor) { if (processor.start() == false) { return false; } Processor::Result result; for (typename DataContainer::iterator d_it = data.begin(); d_it != data.end(); ++d_it) { result = processor(*d_it); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor.finish(); } template <typename Item> bool HashGridBox3<Item>::apply(UnaryProcessor< HashGridBox3<Item> >& processor) { if (processor.start() == false) { return false; } Processor::Result result; for (BoxIterator it = beginBox(); +it; ++it) { result = processor(*it); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor.finish(); } /** Three-dimensional Hash Grid Class. ????? \par */ template <typename Item> class HashGrid3 { public: BALL_CREATE(HashGrid3) /** @name Constructors and destructor */ //@{ /// Default constructor HashGrid3(); /** Constructor using origin, dimensions, and spacings of the grid. It creates a hashgrid at <tt>origin</tt> with axis-dependant spacings. @param origin @param dimension_x @param dimension_y @param dimension_z @param spacing_x @param spacing_y @param spacing_z */ HashGrid3(const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing_x, float spacing_y, float spacing_z); /** Constructor using origin, dimensions, and a single spacing (only cubic grids) */ HashGrid3(const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing); /** Constructor using two vectors and a single spacing. This constructor creates a hash grid at <tt>origin</tt> with spacing <tt>spacing</tt>. The vector <tt>size</tt> has to be relative to <tt>origin</tt> and defines the opposite corner of the grid, thereby setting the size of the grid. @param origin a vector defining the origin of our cubic hash grid @param size a vector defining the opposite corner of the cubic grid @param spacing this float will be used as spacing in all three dimensions */ HashGrid3(const Vector3& origin, const Vector3& size, float spacing); /// Copy constructor HashGrid3(const HashGrid3& grid, bool deep = true); /// Destructor virtual ~HashGrid3(); /// Clears the whole grid virtual void clear(); /// Clears the HashGridBox3 at position (x, y, z) void clear(Position x, Position y, Position z); /// Clears the HashGridBox3 at position <tt>vector</tt> void clear(const Vector3 &vector); /// Destroys the grid (obsolete, only calls clear()) void destroy(); /// Destroys a box of the grid (obsolete, only calls clear()) void destroy(Position x, Position y, Position z); /// Destroys a box of the grid (obsolete, only calls clear()) void destroy(const Vector3& vector); //@} /** @name Assignment */ //@{ /// assigns the content of a hash grid (obsolete) void set(const Vector3& origin, const Vector3& unit, Size dimension_x, Size dimension_y, Size dimension_z); /// assigns the content of a hash grid (obsolete) void set(const Vector3& origin, float unit, Size size); /// assigns the content of a hash grid (obsolete) void set(const HashGrid3& grid, bool deep = true); /// Assignment operator const HashGrid3& operator = (const HashGrid3& grid); /// void get(Vector3& origin, Vector3& unit, Size& dimension_x, Size& dimension_y, Size& dimension_z) const; /// void get(HashGrid3& grid, bool deep = true) const; //@} /** @name Accessors */ //@{ /// Counts the non-empty boxes of a grid. Size countNonEmptyBoxes() const; /// Returns the size of a grid, i. e. ????? Size getSize() const; /// Returns the origin of the grid Vector3& getOrigin(); /// Returns a const reference of the grid origin const Vector3& getOrigin() const; /// Returns the unit of the grid Vector3& getUnit(); /// Returns the unit of the grid (const version) const Vector3& getUnit() const; /// Get the x dimension of the grid Size getSizeX() const; /// Get the y dimension of the grid Size getSizeY() const; /// Get the z dimension of the grid Size getSizeZ() const; /// Return the HashGridBox3 at position (x, y, z) HashGridBox3<Item>* getBox(Position x, Position y, Position z); /// Return the HashGridBox3 at position (x, y, z) (const version) const HashGridBox3<Item>* getBox(Position x, Position y, Position z) const; /// Return the HashGridBox3 at position vector HashGridBox3<Item>* getBox(const Vector3& vector); /// Return the HashGridBox3 at position vector (const version) const HashGridBox3<Item>* getBox(const Vector3 &vector) const; /// Get the position indices of a HashGridBox3 bool getIndices(const HashGridBox3<Item>& box, Position& x, Position& y, Position& z) const; /// Insert an item at position (x, y, z) void insert(Position x, Position y, Position z, const Item& item); /// Insert an item at position <tt>vector</tt> void insert(const Vector3& vector, const Item& item); /// Remove an item from position (x, y ,z) bool remove(Position x, Position y, Position z, const Item& item); /// Remove an item from position <tt>vector</tt> bool remove(const Vector3& vector, const Item& item); //@} /** @name Miscellaneous */ //@{ /// void host(Visitor<HashGrid3>& visitor); //@} /** @name Predicates */ //@{ /// Equality operator bool operator == (const HashGrid3& grid) const; /// Inequality operator bool operator != (const HashGrid3& grid) const; /// Tests, whether <tt>this</tt> is empty bool isEmpty() const; //@} /** @name Debugging and Diagnostics */ //@{ /// Validity check virtual bool isValid() const; /// Dump the contents of a HashGrid3 to a stream virtual void dump(std::ostream& s = std::cout, Size depth = 0) const; //@} /** @name Internal Iterators */ //@{ /// bool apply(UnaryProcessor<Item> &processor); /// bool apply(UnaryProcessor< HashGridBox3<Item> > &processor); /** Get the nearest item for a point @param distance number of adjacted boxes in each direction to search in */ const Item* getClosestItem(const Vector3& point, Size distance) const; /** Calculate the minimum required spacing to build a HashGrid3 with the given size and less than the given memory consumption. @param memory the amount of memory in bytes @param size the diagonal of the grid @return the minimal needed spacing */ static float calculateMinSpacing(LongIndex memory, const Vector3& size); //@} /** @name External Iterators */ //@{ typedef Position BoxIteratorPosition; class BoxIteratorTraits { public: BALL_CREATE_DEEP(BoxIteratorTraits) virtual ~BoxIteratorTraits() {} BoxIteratorTraits() : bound_(0), position_(0) { } BoxIteratorTraits(const HashGrid3 &grid) : bound_((HashGrid3 *)&grid), position_(0) { } BoxIteratorTraits(const BoxIteratorTraits& traits, bool /* deep */ = true) : bound_(traits.bound_), position_(traits.position_) { } const BoxIteratorTraits& operator = (const BoxIteratorTraits& traits) { bound_ = traits.bound_; position_ = traits.position_; return *this; } HashGrid3* getContainer() { return bound_; } const HashGrid3* getContainer() const { return bound_; } bool isSingular() const { return (bound_ == 0); } BoxIteratorPosition& getPosition() { return position_; } const BoxIteratorPosition& getPosition() const { return position_; } bool operator == (const BoxIteratorTraits& traits) const { return (position_ == traits.position_); } bool operator != (const BoxIteratorTraits& traits) const { return (position_ != traits.position_); } bool isValid() const { return (bound_ != 0 && position_ < bound_->getSize()); } void invalidate() { bound_ = 0; position_ = bound_->getSize()+1; } void toBegin() { position_ = 0; } bool isBegin() const { return (position_ == 0); } void toEnd() { position_ = bound_->getSize(); } bool isEnd() const { return (position_ == bound_->getSize()); } HashGridBox3<Item>& getData() { return bound_->box_[position_]; } const HashGridBox3<Item>& getData() const { return bound_->box_[position_]; } void forward() { ++position_; } private: HashGrid3<Item>* bound_; BoxIteratorPosition position_; }; friend class BoxIteratorTraits; /// typedef ForwardIterator <HashGrid3<Item>, HashGridBox3<Item>, BoxIteratorPosition, BoxIteratorTraits> BoxIterator; /// BoxIterator beginBox() { return BoxIterator::begin(*this); } /// BoxIterator endBox() { return BoxIterator::end(*this); } /// typedef ConstForwardIterator <HashGrid3<Item>, HashGridBox3<Item>, BoxIteratorPosition, BoxIteratorTraits> ConstBoxIterator; /// ConstBoxIterator beginBox() const { return ConstBoxIterator::begin(*this); } /// ConstBoxIterator endBox() const { return ConstBoxIterator::end(*this); } //@} private: //_ Index getIndex_(const HashGridBox3<Item>& box) const; //_ Vector3 origin_; //_ Vector3 unit_; //_ Size dimension_x_; //_ Size dimension_y_; //_ Size dimension_z_; //_ vector<HashGridBox3<Item> > box_; }; //@} template <typename Item> HashGrid3<Item>::HashGrid3() : origin_(0,0,0), unit_(0,0,0), dimension_x_(0), dimension_y_(0), dimension_z_(0) { } template <typename Item> HashGrid3<Item>::HashGrid3 (const Vector3 &originvector, Size dimension_x, Size dimension_y, Size dimension_z, float spacing_x, float spacing_y, float spacing_z) : origin_(originvector), unit_(spacing_x, spacing_y, spacing_z), dimension_x_(dimension_x), dimension_y_(dimension_y), dimension_z_(dimension_z), box_(dimension_x * dimension_y * dimension_z, HashGridBox3<Item>(this)) { } template <typename Item> HashGrid3<Item>::HashGrid3 (const Vector3& origin, Size dimension_x, Size dimension_y, Size dimension_z, float spacing) : origin_(origin), unit_(spacing, spacing, spacing), dimension_x_(dimension_x), dimension_y_(dimension_y), dimension_z_(dimension_z), box_(dimension_x * dimension_y * dimension_z, HashGridBox3<Item>(this)) { } // this constructor creates a linear array of HashGridBox3 objects. template <typename Item> HashGrid3<Item>::HashGrid3(const Vector3& origin, const Vector3& size, float spacing) : origin_(origin), unit_(spacing, spacing, spacing), dimension_x_((Size)(size.x / spacing + 1.0)), dimension_y_((Size)(size.y / spacing + 1.0)), dimension_z_((Size)(size.z / spacing + 1.0)), box_(dimension_x_ * dimension_y_ * dimension_z_, HashGridBox3<Item>(this)) { } template <typename Item> HashGrid3<Item>::HashGrid3(const HashGrid3<Item>& grid, bool deep) { set(grid, deep); } template <typename Item> HashGrid3<Item>::~HashGrid3() { } template <typename Item> void HashGrid3<Item>::clear() { Size size = dimension_x_ * dimension_y_ * dimension_z_; for (Position index = 0; index < (Position)size; ++index) { box_[index].clear(); } } template <typename Item> BALL_INLINE void HashGrid3<Item>::clear(Position x, Position y, Position z) { HashGridBox3<Item>* box = getBox(x, y, z); if (box != 0) { box->clear(); } } template <typename Item> BALL_INLINE void HashGrid3<Item>::clear(const Vector3& vector) { HashGridBox3<Item>* box = getBox(vector); if (box != 0) { box->clear(); } } template <typename Item> BALL_INLINE void HashGrid3<Item>::destroy() { clear(); } template <typename Item> BALL_INLINE void HashGrid3<Item>::destroy(Position x, Position y, Position z) { clear(x, y, z); } template <typename Item> BALL_INLINE void HashGrid3<Item>::destroy(const Vector3 &vector) { clear(vector); } template <typename Item> void HashGrid3<Item>::set (const Vector3& origin, const Vector3& unit, Size dimension_x, Size dimension_y, Size dimension_z) { origin_.set(origin); unit_.set(unit); dimension_x_ = dimension_x; dimension_y_ = dimension_y; dimension_z_ = dimension_z; box_.assign(getSize(), HashGridBox3<Item>(this)); } template <typename Item> void HashGrid3<Item>::set(const Vector3& origin, float unit, Size size) { origin_.set(origin); unit_.set(unit, unit, unit); dimension_x_ = size; dimension_y_ = size; dimension_z_ = size; box_.assign(getSize(), HashGridBox3<Item>(this)); } template <typename Item> void HashGrid3<Item>::set(const HashGrid3<Item>& grid, bool /* deep */) { origin_.set(grid.origin_); unit_.set(grid.unit_); dimension_x_ = grid.dimension_x_; dimension_y_ = grid.dimension_y_; dimension_z_ = grid.dimension_z_; box_ = grid.box_; for(Position i = 0; i < box_.size(); ++i) { box_[i].setParent(this); } } template <typename Item> BALL_INLINE const HashGrid3<Item>& HashGrid3<Item>::operator = (const HashGrid3<Item> &grid) { set(grid); return *this; } template <typename Item> BALL_INLINE void HashGrid3<Item>::get(Vector3 &origin, Vector3 &unit, Size& dimension_x, Size& dimension_y, Size& dimension_z) const { origin.set(origin_); unit.set(unit_); dimension_x = dimension_x_; dimension_y = dimension_y_; dimension_z = dimension_z_; } template <typename Item> BALL_INLINE void HashGrid3<Item>::get(HashGrid3<Item> &grid, bool deep) const { grid.set(*this, deep); } template <typename Item> Size HashGrid3<Item>::countNonEmptyBoxes() const { Size size = 0; for (Position i=0; i<27; ++i) { if (!box_[i].isEmpty()) ++size; } return size; } template <typename Item> BALL_INLINE Size HashGrid3<Item>::getSize() const { return (dimension_x_ * dimension_y_ * dimension_z_); } template <typename Item> BALL_INLINE Vector3& HashGrid3<Item>::getOrigin() { return origin_; } template <typename Item> BALL_INLINE const Vector3& HashGrid3<Item>::getOrigin() const { return origin_; } template <typename Item> BALL_INLINE Vector3& HashGrid3<Item>::getUnit() { return unit_; } template <typename Item> BALL_INLINE const Vector3& HashGrid3<Item>::getUnit() const { return unit_; } template <typename Item> BALL_INLINE Size HashGrid3<Item>::getSizeX() const { return dimension_x_; } template <typename Item> BALL_INLINE Size HashGrid3<Item>::getSizeY() const { return dimension_y_; } template <typename Item> BALL_INLINE Size HashGrid3<Item>::getSizeZ() const { return dimension_z_; } template <typename Item> const Item* HashGrid3<Item>::getClosestItem(const Vector3& point, Size dist) const { const HashGridBox3<Item>* box = getBox(point); if (!box) return 0; Position x, y, z; getIndices(*box, x, y, z); const Item* item = 0; float distance = FLT_MAX; // iterator over neighbour boxes for (Index xi = -(Index)dist; xi <= (Index)dist; xi++) { const Index xn = x + xi; for (Index yi = -(Index)dist; yi <= (Index)dist; yi++) { const Index yn = y + yi; for (Index zi = -(Index)dist; zi <= (Index)dist; zi++) { // iterate over all data items const HashGridBox3<Item>* const box_ptr = getBox(xn, yn, z+zi); if (box_ptr != 0 && !box_ptr->isEmpty()) { typename HashGridBox3<Item>::ConstDataIterator hit = box_ptr->beginData(); for (;hit != box_ptr->endData(); hit++) { const float new_dist = ((*hit)->getPosition() - point).getSquareLength(); if (new_dist < distance) { item = &*hit; distance = new_dist; } } } } } } return item; } template <typename Item> BALL_INLINE float HashGrid3<Item>::calculateMinSpacing(LongIndex memory, const Vector3& size) { LongSize memory_for_box = sizeof(HashGridBox3<Item>) + sizeof(HashGridBox3<Item>*); LongSize nr_boxes =(LongSize)floor((float)(memory / memory_for_box)); return pow((double)((size.x * size.y * size.z) / nr_boxes), (double)(1.0 / 3.0)); } template <typename Item> BALL_INLINE HashGridBox3<Item>* HashGrid3<Item>::getBox(Position x, Position y, Position z) { if (x >= (Position)dimension_x_ || y >= (Position)dimension_y_ || z >= (Position)dimension_z_) { return 0; } else { return &(box_[x * dimension_y_ * dimension_z_ + y * dimension_z_ + z]); } } template <typename Item> BALL_INLINE const HashGridBox3<Item>* HashGrid3<Item>::getBox(Position x, Position y, Position z) const { return ((HashGrid3*)this)->getBox(x, y, z); } template <typename Item> BALL_INLINE HashGridBox3<Item>* HashGrid3<Item>::getBox(const Vector3& vector) { float x = (vector.x - origin_.x) / unit_.x; float y = (vector.y - origin_.y) / unit_.y; float z = (vector.z - origin_.z) / unit_.z; // workaround for MSVC 7, dont change this !!! Index x1 = (Index) Maths::floor(x); Index y1 = (Index) Maths::floor(y); Index z1 = (Index) Maths::floor(z); return getBox(x1, y1, z1); } template <typename Item> BALL_INLINE const HashGridBox3<Item>* HashGrid3<Item>::getBox(const Vector3& vector) const { return ((HashGrid3 *)this)->getBox(vector); } template <typename Item> BALL_INLINE bool HashGrid3<Item>::getIndices (const HashGridBox3<Item>& box, Position& x, Position& y, Position& z) const { Index index = getIndex_(box); if (index == INVALID_INDEX) { x = y = z = INVALID_POSITION; return false; } x = index / (dimension_y_ * dimension_z_); index -= x * dimension_y_ * dimension_z_; y = index / dimension_z_; z = index - y * dimension_z_; return true; } template <typename Item> BALL_INLINE void HashGrid3<Item>::insert (Position x, Position y, Position z, const Item& item) { HashGridBox3<Item>* box = getBox(x, y, z); if (box != 0) { box->insert(item); } } template <typename Item> BALL_INLINE void HashGrid3<Item>::insert(const Vector3& vector, const Item& item) { HashGridBox3<Item> *box = getBox(vector); if (box != 0) { box->insert(item); } } template <typename Item> BALL_INLINE bool HashGrid3<Item>::remove(Position x, Position y, Position z, const Item& item) { HashGridBox3<Item>* box = getBox(x, y, z); if (box != 0) { return box->remove(item); } return false; } template <typename Item> BALL_INLINE bool HashGrid3<Item>::remove(const Vector3& vector, const Item& item) { HashGridBox3<Item>* box = getBox(vector); if (box != 0) { return box->remove(item); } return false; } template <typename Item> BALL_INLINE void HashGrid3<Item>::host(Visitor< HashGrid3<Item> >& visitor) { visitor.visit(*this); } template <typename Item> BALL_INLINE bool HashGrid3<Item>::operator == (const HashGrid3<Item>& grid) const { if (getSize() != grid.getSize() || origin_ != grid.origin_ || unit_ != grid.unit_ || dimension_x_ != grid.dimension_x_ || dimension_y_ != grid.dimension_y_ || dimension_z_ != grid.dimension_z_) { return false; } return box_ == grid.box_; } template <typename Item> BALL_INLINE bool HashGrid3<Item>::operator != (const HashGrid3<Item>& grid) const { return !(*this == grid); } template <typename Item> BALL_INLINE bool HashGrid3<Item>::isEmpty() const { return (getSize() == 0); } template <typename Item> bool HashGrid3<Item>::isValid() const { Size size = getSize(); for (Position index = 0; index < (Position)size; ++index) { if (box_[index].isValid() == false) { return false; } } return true; } template <typename Item> void HashGrid3<Item>::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_DEPTH(s, depth); s << " origin: " << origin_ << std::endl; BALL_DUMP_DEPTH(s, depth); s << " unit: " << unit_.z << std::endl; BALL_DUMP_DEPTH(s, depth); s << " dimension: " << dimension_x_ << " " << dimension_y_ << " " << dimension_z_ << std::endl; Size size = getSize(); BALL_DUMP_DEPTH(s, depth); s << " size: " << size << std::endl; BALL_DUMP_DEPTH(s, depth); s << " non empty boxes: " << countNonEmptyBoxes() << std::endl; BALL_DUMP_DEPTH(s, depth); s << " boxes:" << std::endl; Position x, y, z; for (Position index = 0; index < (Position)size; ++index) { BALL_DUMP_DEPTH(s, depth); getIndices(box_[index], x, y, z); s << " " << index << ". box: (" << x << ',' << y << ',' << z << ')' << std::endl; box_[index].dump(s, 1); } BALL_DUMP_DEPTH(s, depth); s << " non-empty boxes:" << std::endl; for (Position i=0; i<27; ++i) { if (!box_[i].isEmpty()) s << " " << getIndex_(box_[i]) << std::endl; } BALL_DUMP_STREAM_SUFFIX(s); } template <typename Item> bool HashGrid3<Item>::apply(UnaryProcessor<Item>& processor) { if (processor.start() == false) { return false; } Processor::Result result; for (Position i=0; i<27; ++i) { HashGridBox3<Item>* box = &box_[i]; for (typename HashGridBox3<Item>::DataIterator *item = box->beginData(); +item; ++item) { result = processor(*item); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } } return processor->finish(); } template <typename Item> bool HashGrid3<Item>::apply(UnaryProcessor< HashGridBox3<Item> >& processor) { if (processor.start() == false) { return false; } Processor::Result result; for (Position i=0; i<27; ++i) { HashGridBox3<Item>* box = &box_[i]; result = processor(*box); if (result <= Processor::BREAK) { return (result == Processor::BREAK) ? true : false; } } return processor->finish(); } template <typename Item> BALL_INLINE Index HashGrid3<Item>::getIndex_(const HashGridBox3<Item>& box) const { if ((&box < &box_[0]) || (&box - &box_[0] >= getSize())) { return INVALID_INDEX; } else { return (Index)(&box - &box_[0]); } } } // namespace BALL #endif // BALL_DATATYPE_HASHGRID_H
20.541217
107
0.645079
[ "vector" ]
30e52fa456edb3980dbe500137509cac5205708b
2,355
h
C
src/modules/AnalysisTelescope/AnalysisTelescope.h
simonspa/corryvreckan
ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436
[ "MIT" ]
null
null
null
src/modules/AnalysisTelescope/AnalysisTelescope.h
simonspa/corryvreckan
ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436
[ "MIT" ]
null
null
null
src/modules/AnalysisTelescope/AnalysisTelescope.h
simonspa/corryvreckan
ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436
[ "MIT" ]
null
null
null
/** * @file * @brief Definition of module AnalysisTelescope * * @copyright Copyright (c) 2017-2020 CERN and the Corryvreckan authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #ifndef AnalysisTelescope_H #define AnalysisTelescope_H 1 #include <TH1F.h> #include <TH2F.h> #include <iostream> #include "core/module/Module.hpp" #include "objects/MCParticle.hpp" #include "objects/Track.hpp" namespace corryvreckan { /** @ingroup Modules */ class AnalysisTelescope : public Module { public: // Constructors and destructors AnalysisTelescope(Configuration& config, std::vector<std::shared_ptr<Detector>> detectors); // Functions void initialize() override; StatusCode run(const std::shared_ptr<Clipboard>& clipboard) override; private: ROOT::Math::XYZPoint closestApproach(ROOT::Math::XYZPoint position, const MCParticleVector& particles); // Histograms for each of the devices std::map<std::string, TH1F*> telescopeMCresidualsLocalX; std::map<std::string, TH1F*> telescopeMCresidualsLocalY; std::map<std::string, TH1F*> telescopeMCresidualsX; std::map<std::string, TH1F*> telescopeMCresidualsY; std::map<std::string, TH1F*> telescopeResidualsLocalX; std::map<std::string, TH1F*> telescopeResidualsLocalY; std::map<std::string, TH1F*> telescopeResidualsX; std::map<std::string, TH1F*> telescopeResidualsY; // Histograms at the position of the DUT std::map<std::string, TH1F*> telescopeResolutionX; std::map<std::string, TH1F*> telescopeResolutionY; std::map<std::string, TH1F*> pxTimeMinusSeedTime; std::map<std::string, TH2F*> pxTimeMinusSeedTime_vs_pxCharge; std::map<std::string, TH2F*> pxTimeMinusSeedTime_vs_pxCharge_2px; std::map<std::string, TH2F*> pxTimeMinusSeedTime_vs_pxCharge_3px; std::map<std::string, TH2F*> pxTimeMinusSeedTime_vs_pxCharge_4px; // Parameters double chi2ndofCut; }; } // namespace corryvreckan #endif // AnalysisTelescope_H
37.380952
122
0.70276
[ "vector" ]
30e62d33e2755bc2e5fb67f0c54adcc6a155966b
1,464
c
C
src/platform/pc/led_process.c
NakedSolidSnake/Raspberry_IPC_Socket_UDP
6aff45ff6f1ea5d44e9682f3e61602e7cea2daed
[ "MIT" ]
null
null
null
src/platform/pc/led_process.c
NakedSolidSnake/Raspberry_IPC_Socket_UDP
6aff45ff6f1ea5d44e9682f3e61602e7cea2daed
[ "MIT" ]
null
null
null
src/platform/pc/led_process.c
NakedSolidSnake/Raspberry_IPC_Socket_UDP
6aff45ff6f1ea5d44e9682f3e61602e7cea2daed
[ "MIT" ]
1
2021-06-14T12:16:21.000Z
2021-06-14T12:16:21.000Z
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <syslog.h> #include <led_interface.h> #define BUFFER_SIZE 1024 void on_receive_message(const char *buffer, size_t buffer_size, void *data); bool Init(void *object); bool Set(void *object, uint8_t state); int main(int argc, char *argv[]) { char server_buffer[BUFFER_SIZE]; LED_Interface led_interface = { .Init = Init, .Set = Set }; UDP_Server server = { .buffer = server_buffer, .buffer_size = BUFFER_SIZE, .port = 1234, .on_receive_message = on_receive_message }; LED_Data led = { .object = NULL, .interface = &led_interface }; LED_Run(&server, &led); return 0; } bool Init(void *object) { (void)object; return true; } bool Set(void *object, uint8_t state) { (void)object; openlog("LED UDP", LOG_PID | LOG_CONS , LOG_USER); syslog(LOG_INFO, "LED Status: %s", state ? "On": "Off"); closelog(); return true; } void on_receive_message(const char *buffer, size_t buffer_size, void *data) { LED_Data *led = (LED_Data *)data; if(strncmp("LED ON", buffer, strlen("LED ON")) == 0) led->interface->Set(led->object, 1); else if(strncmp("LED OFF", buffer, strlen("LED OFF")) == 0) led->interface->Set(led->object, 0); }
20.914286
76
0.608607
[ "object" ]
30e98bf25dc02dddc2ddb030bf9bbb3279feb834
952
h
C
Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Engine/Classes/Materials/MaterialExpressionTextureSampleParameter2D.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "Materials/MaterialExpressionTextureSampleParameter.h" #include "MaterialExpressionTextureSampleParameter2D.generated.h" class UTexture; UCLASS(collapsecategories, hidecategories=Object) class ENGINE_API UMaterialExpressionTextureSampleParameter2D : public UMaterialExpressionTextureSampleParameter { GENERATED_UCLASS_BODY() //~ Begin UMaterialExpression Interface #if WITH_EDITOR virtual void GetCaption(TArray<FString>& OutCaptions) const override; #endif // WITH_EDITOR //~ End UMaterialExpression Interface //~ Begin UMaterialExpressionTextureSampleParameter Interface virtual bool TextureIsValid( UTexture* InTexture ) override; virtual const TCHAR* GetRequirements() override; virtual void SetDefaultTexture() override; //~ End UMaterialExpressionTextureSampleParameter Interface };
28
111
0.82563
[ "object" ]
30eb221e68a9793f5762b54b1af0b0837d36c848
14,106
h
C
API/SketchUpAPI/length_formatter.h
TonyHuangYJ/SketchUpNET
af165847c1817daa2aa91852bb92738218a064be
[ "MIT" ]
69
2015-11-08T07:11:00.000Z
2022-02-02T20:30:58.000Z
API/SketchUpAPI/length_formatter.h
TonyHuangYJ/SketchUpNET
af165847c1817daa2aa91852bb92738218a064be
[ "MIT" ]
34
2015-11-08T17:07:46.000Z
2022-03-12T19:10:09.000Z
API/SketchUpAPI/length_formatter.h
TonyHuangYJ/SketchUpNET
af165847c1817daa2aa91852bb92738218a064be
[ "MIT" ]
28
2016-12-10T01:02:14.000Z
2022-03-16T23:17:08.000Z
// Copyright 2017 Trimble Inc. All Rights Reserved. #ifndef SKETCHUP_LENGTH_FORMATTER_H_ #define SKETCHUP_LENGTH_FORMATTER_H_ #include <SketchUpAPI/defs.h> #ifdef __cplusplus extern "C" { #endif /** @struct SULengthFormatterRef @brief References a length formatter object. Length formatters are used to generate formatted strings (optionally with units) from length, area, and volume values. Additionally length formatters can be used to translate a formatted length/area/volume string into a value. Accessors and setters are exposed for some of the key formatting properties, facilitating customization of the formater. In cases when users want the formatter to reflect the properties of a model, SUModelGetLengthFormatter should be used to more efficiently extract/copy the relevant properties from the model to the formatter. @since SketchUp 2018, API 6.0 */ /** @enum SULengthFormatType @brief Indicates the different supported length string formatting types @since SketchUp 2018, API 6.0 */ enum SULengthFormatType { SU_LFORMAT_DECIMAL, SU_LFORMAT_ARCHITECTURAL, SU_LFORMAT_ENGINEERING, SU_LFORMAT_FRACTIONAL }; /** @enum SULengthUnitType @brief Indicates the different supported length string formatting units @since SketchUp 2018, API 6.0 Added in SketchUp 2020, API 8.0 - SU_LUNIT_YARD */ enum SULengthUnitType { SU_LUNIT_INCHES, SU_LUNIT_FEET, SU_LUNIT_MILLIMETER, SU_LUNIT_CENTIMETER, SU_LUNIT_METER, SU_LUNIT_YARD }; /** @enum SUAreaUnitType @brief Indicates the different supported area string formatting units @since SketchUp 2019.2, API 7.1 Added in SketchUp 2020, API 8.0 - SU_AUNIT_SQUARE_YARD */ enum SUAreaUnitType { SU_AUNIT_SQUARE_INCHES, SU_AUNIT_SQUARE_FEET, SU_AUNIT_SQUARE_MILLIMETER, SU_AUNIT_SQUARE_CENTIMETER, SU_AUNIT_SQUARE_METER, SU_AUNIT_SQUARE_YARD }; /** @enum SUVolumeUnitType @brief Indicates the different supported volume string formatting units @since SketchUp 2019.2, API 7.1 Added in SketchUp 2020, API 8.0 - SU_VUNIT_CUBIC_YARD - SU_VUNIT_LITER - SU_VUNIT_US_GALLON */ enum SUVolumeUnitType { SU_VUNIT_CUBIC_INCHES, SU_VUNIT_CUBIC_FEET, SU_VUNIT_CUBIC_MILLIMETER, SU_VUNIT_CUBIC_CENTIMETER, SU_VUNIT_CUBIC_METER, SU_VUNIT_CUBIC_YARD, SU_VUNIT_LITER, SU_VUNIT_US_GALLON }; /** @brief Creates a new length formatter with default properties. @since SketchUp 2018, API 6.0 @param[out] formatter The formatter object created. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_NULL_POINTER_OUTPUT if formatter is NULL - \ref SU_ERROR_OVERWRITE_VALID if formatter already references a valid object */ SU_RESULT SULengthFormatterCreate(SULengthFormatterRef* formatter); /** @brief Releases a length formatter object. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is an invalid object - \ref SU_ERROR_NULL_POINTER_INPUT if formatter is NULL */ SU_RESULT SULengthFormatterRelease(SULengthFormatterRef* formatter); /** @brief Retrieves the precision of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[out] precision The precision retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if precision is NULL */ SU_RESULT SULengthFormatterGetPrecision(SULengthFormatterRef formatter, size_t* precision); /** @brief Sets the precision of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] precision The precision to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object */ SU_RESULT SULengthFormatterSetPrecision(SULengthFormatterRef formatter, size_t precision); /** @brief Retrieves the area precision of a length formatter. @since Sketchup 2020, API 8.0 @param[in] formatter The formatter object. @param[out] precision The precision retrieved. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if precision is NULL */ SU_RESULT SULengthFormatterGetAreaPrecision(SULengthFormatterRef formatter, size_t* precision); /** @brief Sets the area precision of a length formatter. @since Sketchup 2020, API 8.0 @param[in] formatter The formatter object. @param[in] precision The precision to be set. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object */ SU_RESULT SULengthFormatterSetAreaPrecision(SULengthFormatterRef formatter, size_t precision); /** @brief Retrieves the volume precision of a length formatter. @since Sketchup 2020, API 8.0 @param[in] formatter The formatter object. @param[out] precision The precision retrieved. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if precision is NULL */ SU_RESULT SULengthFormatterGetVolumePrecision(SULengthFormatterRef formatter, size_t* precision); /** @brief Sets the volume precision of a length formatter. @since Sketchup 2020, API 8.0 @param[in] formatter The formatter object. @param[in] precision The precision to be set. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object */ SU_RESULT SULengthFormatterSetVolumePrecision(SULengthFormatterRef formatter, size_t precision); /** @brief Retrieves the format of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[out] format The format retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if format is NULL */ SU_RESULT SULengthFormatterGetFormat(SULengthFormatterRef formatter, enum SULengthFormatType* format); /** @brief Sets the format of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] format The format to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_OUT_OF_RANGE if format is not a supported option */ SU_RESULT SULengthFormatterSetFormat(SULengthFormatterRef formatter, enum SULengthFormatType format); /** @brief Retrieves the units of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[out] units The unit type retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if units is NULL */ SU_RESULT SULengthFormatterGetUnits(SULengthFormatterRef formatter, enum SULengthUnitType* units); /** @brief Retrieves the area units of a length formatter. @since SketchUp 2019.2, API 7.1 @param[in] formatter The formatter object. @param[out] units The unit type retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if units is NULL */ SU_RESULT SULengthFormatterGetAreaUnits(SULengthFormatterRef formatter, enum SUAreaUnitType* units); /** @brief Retrieves the volume units of a length formatter. @since SketchUp 2019.2, API 7.1 @param[in] formatter The formatter object. @param[out] units The unit type retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if units is NULL */ SU_RESULT SULengthFormatterGetVolumeUnits(SULengthFormatterRef formatter, enum SUVolumeUnitType* units); /** @brief Sets the units of a length formatter. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] units The unit type to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_OUT_OF_RANGE if units is not a supported option */ SU_RESULT SULengthFormatterSetUnits(SULengthFormatterRef formatter, enum SULengthUnitType units); /** @brief Sets the area units of a length formatter. @since SketchUp 2019.2, API 7.1 @param[in] formatter The formatter object. @param[in] units The unit type to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_OUT_OF_RANGE if units is not a supported option */ SU_RESULT SULengthFormatterSetAreaUnits(SULengthFormatterRef formatter, enum SUAreaUnitType units); /** @brief Sets the volume units of a length formatter. @since SketchUp 2019.2, API 7.1 @param[in] formatter The formatter object. @param[in] units The unit type to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_OUT_OF_RANGE if units is not a supported option */ SU_RESULT SULengthFormatterSetVolumeUnits(SULengthFormatterRef formatter, enum SUVolumeUnitType units); /** @brief Retrieves whether units are suppressed. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[out] suppress The unit suppression flag retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if suppress is NULL */ SU_RESULT SULengthFormatterGetSuppressUnits(SULengthFormatterRef formatter, bool* suppress); /** @brief Sets whether units are suppressed. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] suppress The unit suppression flag to be set. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object */ SU_RESULT SULengthFormatterSetSuppressUnits(SULengthFormatterRef formatter, bool suppress); /** @brief Retrieves a formatted length string from the provided length value. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] length The length value. @param[in] strip Whether to strip trailing zeros, leading ~, and decimal point if it is the last character. @param[out] string The formatted string retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if suppress is string - \ref SU_ERROR_INVALID_OUTPUT if *string is not a valid object */ SU_RESULT SULengthFormatterGetLengthString(SULengthFormatterRef formatter, double length, bool strip, SUStringRef* string); /** @brief Retrieves a formatted area string from the provided area value. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] area The area value. @param[out] string The formatted string retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if suppress is string - \ref SU_ERROR_INVALID_OUTPUT if *string is not a valid object */ SU_RESULT SULengthFormatterGetAreaString(SULengthFormatterRef formatter, double area, SUStringRef* string); /** @brief Retrieves a formatted volume string from the provided volume value. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] volume The volume value. @param[out] string The formatted string retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if suppress is string - \ref SU_ERROR_INVALID_OUTPUT if *string is not a valid object */ SU_RESULT SULengthFormatterGetVolumeString(SULengthFormatterRef formatter, double volume, SUStringRef* string); /** @brief Parses a formatted length string getting the numeric value. @since SketchUp 2018, API 6.0 @param[in] formatter The formatter object. @param[in] string The formatted string. @param[out] value The numeric value retrieved. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter or string are not a valid objects - \ref SU_ERROR_NULL_POINTER_OUTPUT if value is NULL - \ref SU_ERROR_INVALID_ARGUMENT if the string could not be parsed */ SU_RESULT SULengthFormatterParseString(SULengthFormatterRef formatter, SUStringRef string, double* value); /** @brief Force the display of Architectural inches even if the value is zero. @since SketchUp 2019, API 7.0 @param[in] formatter The formatter object. @param[in] force_inch The boolean value to force inch display. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object */ SU_RESULT SULengthFormatterSetForceInchDisplay(SULengthFormatterRef formatter, bool force_inch); /** @brief Determine if Architectural inches will display even if the value is zero. @since SketchUp 2019, API 7.0 @param[in] formatter The formatter object. @param[out] force_inch The boolean value to force inch display. @related SULengthFormatterRef @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if formatter is not a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if value is NULL */ SU_RESULT SULengthFormatterGetForceInchDisplay(SULengthFormatterRef formatter, bool* force_inch); #ifdef __cplusplus } // extern "C" #endif #endif // SKETCHUP_LENGTH_FORMATTER_H_
32.804651
80
0.792074
[ "object", "model" ]
30f3d46965c8e6191a15838b17b5c67ec7c9a208
134,140
h
C
windows_sysroot/include/winrt/windows.devices.enumeration.pnp.h
ci-fuzz/bazel-toolchain
4f42c70f17fd1a64bff2aa53a1a3d97a0b55dcdd
[ "Apache-2.0" ]
5
2020-05-29T06:22:17.000Z
2021-11-28T08:21:38.000Z
windows_sysroot/include/winrt/windows.devices.enumeration.pnp.h
ci-fuzz/bazel-toolchain
4f42c70f17fd1a64bff2aa53a1a3d97a0b55dcdd
[ "Apache-2.0" ]
null
null
null
windows_sysroot/include/winrt/windows.devices.enumeration.pnp.h
ci-fuzz/bazel-toolchain
4f42c70f17fd1a64bff2aa53a1a3d97a0b55dcdd
[ "Apache-2.0" ]
5
2020-05-30T04:15:11.000Z
2021-11-28T08:48:56.000Z
#pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include <rpc.h> #include <rpcndr.h> #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include <windows.h> #include <ole2.h> #endif /*COM_NO_WINDOWS_H*/ #ifndef __windows2Edevices2Eenumeration2Epnp_h__ #define __windows2Edevices2Eenumeration2Epnp_h__ #ifndef __windows2Edevices2Eenumeration2Epnp_p_h__ #define __windows2Edevices2Eenumeration2Epnp_p_h__ #pragma once // // Deprecated attribute support // #pragma push_macro("DEPRECATED") #undef DEPRECATED #if !defined(DISABLE_WINRT_DEPRECATION) #if defined(__cplusplus) #if __cplusplus >= 201402 #define DEPRECATED(x) [[deprecated(x)]] #define DEPRECATEDENUMERATOR(x) [[deprecated(x)]] #elif defined(_MSC_VER) #if _MSC_VER >= 1900 #define DEPRECATED(x) [[deprecated(x)]] #define DEPRECATEDENUMERATOR(x) [[deprecated(x)]] #else #define DEPRECATED(x) __declspec(deprecated(x)) #define DEPRECATEDENUMERATOR(x) #endif // _MSC_VER >= 1900 #else // Not Standard C++ or MSVC, ignore the construct. #define DEPRECATED(x) #define DEPRECATEDENUMERATOR(x) #endif // C++ deprecation #else // C - disable deprecation #define DEPRECATED(x) #define DEPRECATEDENUMERATOR(x) #endif #else // Deprecation is disabled #define DEPRECATED(x) #define DEPRECATEDENUMERATOR(x) #endif /* DEPRECATED */ // Disable Deprecation for this header, MIDL verifies that cross-type access is acceptable #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #else #pragma warning(push) #pragma warning(disable: 4996) #endif // Ensure that the setting of the /ns_prefix command line switch is consistent for all headers. // If you get an error from the compiler indicating "warning C4005: 'CHECK_NS_PREFIX_STATE': macro redefinition", this // indicates that you have included two different headers with different settings for the /ns_prefix MIDL command line switch #if !defined(DISABLE_NS_PREFIX_CHECKS) #define CHECK_NS_PREFIX_STATE "always" #endif // !defined(DISABLE_NS_PREFIX_CHECKS) #pragma push_macro("MIDL_CONST_ID") #undef MIDL_CONST_ID #define MIDL_CONST_ID const __declspec(selectany) // API Contract Inclusion Definitions #if !defined(SPECIFIC_API_CONTRACT_DEFINITIONS) #if !defined(WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION) #define WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION 0x40000 #endif // defined(WINDOWS_FOUNDATION_FOUNDATIONCONTRACT_VERSION) #if !defined(WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION) #define WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION 0xa0000 #endif // defined(WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION) #endif // defined(SPECIFIC_API_CONTRACT_DEFINITIONS) // Header files for imported files #include "inspectable.h" #include "AsyncInfo.h" #include "EventToken.h" #include "windowscontracts.h" #include "Windows.Foundation.h" #include "Windows.Devices.Enumeration.h" // Importing Collections header #include <windows.foundation.collections.h> #if defined(__cplusplus) && !defined(CINTERFACE) /* Forward Declarations */ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { interface IPnpObject; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject ABI::Windows::Devices::Enumeration::Pnp::IPnpObject #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { interface IPnpObjectStatics; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectStatics #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { interface IPnpObjectUpdate; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectUpdate #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { interface IPnpObjectWatcher; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ // Parameterized interface forward declarations (C++) // Collection interface definitions namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { class PnpObject; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("22b0fb93-30e6-501a-bd3b-9fa3063e9c16")) IAsyncOperation<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : IAsyncOperation_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.IAsyncOperation`1<Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IAsyncOperation<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("9d615463-6879-521f-8e97-e66d3ddbc95e")) IAsyncOperationCompletedHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : IAsyncOperationCompletedHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IAsyncOperationCompletedHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { class PnpObjectCollection; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("6bb6d2f1-b5fb-57f0-8251-f20cde5a6871")) IIterator<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : IIterator_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterator<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::Collections::__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("30b50092-36ee-53ff-9450-029004436c60")) IIterable<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : IIterable_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterable<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::Collections::__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("cce5a798-d269-5fce-99ce-ef0ae3cd0569")) IVectorView<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : IVectorView_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IVectorView`1<Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IVectorView<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::Collections::__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE #define DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("f383c2cc-f326-5bbe-95d1-cbc24714ef86")) IAsyncOperation<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*> : IAsyncOperation_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*, __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.IAsyncOperation`1<Windows.Devices.Enumeration.Pnp.PnpObjectCollection>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IAsyncOperation<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*> __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_t; #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection ABI::Windows::Foundation::__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE #define DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("811d834c-a15e-5522-b7f4-e53004fc58ff")) IAsyncOperationCompletedHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*> : IAsyncOperationCompletedHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*, __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Devices.Enumeration.Pnp.PnpObjectCollection>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IAsyncOperationCompletedHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectCollection*> __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_t; #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FIIterator_1_HSTRING_USE #define DEF___FIIterator_1_HSTRING_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) IIterator<HSTRING> : IIterator_impl<HSTRING> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<String>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterator<HSTRING> __FIIterator_1_HSTRING_t; #define __FIIterator_1_HSTRING ABI::Windows::Foundation::Collections::__FIIterator_1_HSTRING_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterator_1_HSTRING_USE */ #ifndef DEF___FIIterable_1_HSTRING_USE #define DEF___FIIterable_1_HSTRING_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) IIterable<HSTRING> : IIterable_impl<HSTRING> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<String>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterable<HSTRING> __FIIterable_1_HSTRING_t; #define __FIIterable_1_HSTRING ABI::Windows::Foundation::Collections::__FIIterable_1_HSTRING_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterable_1_HSTRING_USE */ #ifndef DEF___FIKeyValuePair_2_HSTRING_IInspectable_USE #define DEF___FIKeyValuePair_2_HSTRING_IInspectable_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("09335560-6c6b-5a26-9348-97b781132b20")) IKeyValuePair<HSTRING, IInspectable*> : IKeyValuePair_impl<HSTRING, IInspectable*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IKeyValuePair`2<String, Object>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IKeyValuePair<HSTRING, IInspectable*> __FIKeyValuePair_2_HSTRING_IInspectable_t; #define __FIKeyValuePair_2_HSTRING_IInspectable ABI::Windows::Foundation::Collections::__FIKeyValuePair_2_HSTRING_IInspectable_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIKeyValuePair_2_HSTRING_IInspectable_USE */ #ifndef DEF___FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_USE #define DEF___FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("5db5fa32-707c-5849-a06b-91c8eb9d10e8")) IIterator<__FIKeyValuePair_2_HSTRING_IInspectable*> : IIterator_impl<__FIKeyValuePair_2_HSTRING_IInspectable*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<Windows.Foundation.Collections.IKeyValuePair`2<String, Object>>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterator<__FIKeyValuePair_2_HSTRING_IInspectable*> __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_t; #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable ABI::Windows::Foundation::Collections::__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_USE */ #ifndef DEF___FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_USE #define DEF___FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("fe2f3d47-5d47-5499-8374-430c7cda0204")) IIterable<__FIKeyValuePair_2_HSTRING_IInspectable*> : IIterable_impl<__FIKeyValuePair_2_HSTRING_IInspectable*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<Windows.Foundation.Collections.IKeyValuePair`2<String, Object>>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IIterable<__FIKeyValuePair_2_HSTRING_IInspectable*> __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_t; #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable ABI::Windows::Foundation::Collections::__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_USE */ #ifndef DEF___FIMapView_2_HSTRING_IInspectable_USE #define DEF___FIMapView_2_HSTRING_IInspectable_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("bb78502a-f79d-54fa-92c9-90c5039fdf7e")) IMapView<HSTRING, IInspectable*> : IMapView_impl<HSTRING, IInspectable*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IMapView`2<String, Object>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef IMapView<HSTRING, IInspectable*> __FIMapView_2_HSTRING_IInspectable_t; #define __FIMapView_2_HSTRING_IInspectable ABI::Windows::Foundation::Collections::__FIMapView_2_HSTRING_IInspectable_t /* Collections */ } /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FIMapView_2_HSTRING_IInspectable_USE */ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { class PnpObjectWatcher; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_USE #define DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("2ee2b4c9-b696-5ecc-b29b-f1e0ef5fe1f7")) ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, IInspectable*> : ITypedEventHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher*>, IInspectable*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.Pnp.PnpObjectWatcher, Object>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, IInspectable*> __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_t; #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable ABI::Windows::Foundation::__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #define DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("d578eed2-58e5-5825-8af2-12f89387b656")) ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> : ITypedEventHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher*>, ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObject*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObject*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.Pnp.PnpObjectWatcher, Windows.Devices.Enumeration.Pnp.PnpObject>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::PnpObject*> __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t; #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject ABI::Windows::Foundation::__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { class PnpObjectUpdate; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_USE #define DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_USE #if !defined(RO_NO_TEMPLATE_NAME) namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("af8f929d-8058-5c38-a3d8-30aa7a08b588")) ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::PnpObjectUpdate*> : ITypedEventHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher*>, ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectUpdate*, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectUpdate*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.Pnp.PnpObjectWatcher, Windows.Devices.Enumeration.Pnp.PnpObjectUpdate>"; } }; // Define a typedef for the parameterized interface specialization's mangled name. // This allows code which uses the mangled name for the parameterized interface to access the // correct parameterized interface specialization. typedef ITypedEventHandler<ABI::Windows::Devices::Enumeration::Pnp::PnpObjectWatcher*, ABI::Windows::Devices::Enumeration::Pnp::PnpObjectUpdate*> __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_t; #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate ABI::Windows::Foundation::__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_t /* Foundation */ } /* Windows */ } /* ABI */ } #endif // !defined(RO_NO_TEMPLATE_NAME) #endif /* DEF___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_USE */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { typedef enum DeviceWatcherStatus : int DeviceWatcherStatus; } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { typedef enum PnpObjectType : int PnpObjectType; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ /* * * Struct Windows.Devices.Enumeration.Pnp.PnpObjectType * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { enum PnpObjectType : int { PnpObjectType_Unknown = 0, PnpObjectType_DeviceInterface = 1, PnpObjectType_DeviceContainer = 2, PnpObjectType_Device = 3, PnpObjectType_DeviceInterfaceClass = 4, PnpObjectType_AssociationEndpoint = 5, PnpObjectType_AssociationEndpointContainer = 6, PnpObjectType_AssociationEndpointService = 7, #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x70000 PnpObjectType_DevicePanel = 8, #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x70000 }; } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObject * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObject * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObject[] = L"Windows.Devices.Enumeration.Pnp.IPnpObject"; namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { MIDL_INTERFACE("95c66258-733b-4a8f-93a3-db078ac870c1") IPnpObject : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE get_Type( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType* value ) = 0; virtual HRESULT STDMETHODCALLTYPE get_Id( HSTRING* value ) = 0; virtual HRESULT STDMETHODCALLTYPE get_Properties( __FIMapView_2_HSTRING_IInspectable** value ) = 0; virtual HRESULT STDMETHODCALLTYPE Update( ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectUpdate* updateInfo ) = 0; }; extern MIDL_CONST_ID IID& IID_IPnpObject = _uuidof(IPnpObject); } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectStatics * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObject * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectStatics[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectStatics"; namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { MIDL_INTERFACE("b3c32a3d-d168-4660-bbf3-a733b14b6e01") IPnpObjectStatics : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE CreateFromIdAsync( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType type, HSTRING id, __FIIterable_1_HSTRING* requestedProperties, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject** asyncOp ) = 0; virtual HRESULT STDMETHODCALLTYPE FindAllAsync( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection** asyncOp ) = 0; virtual HRESULT STDMETHODCALLTYPE FindAllAsyncAqsFilter( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, HSTRING aqsFilter, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection** asyncOp ) = 0; virtual HRESULT STDMETHODCALLTYPE CreateWatcher( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher** watcher ) = 0; virtual HRESULT STDMETHODCALLTYPE CreateWatcherAqsFilter( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, HSTRING aqsFilter, ABI::Windows::Devices::Enumeration::Pnp::IPnpObjectWatcher** watcher ) = 0; }; extern MIDL_CONST_ID IID& IID_IPnpObjectStatics = _uuidof(IPnpObjectStatics); } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObjectUpdate * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectUpdate[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate"; namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { MIDL_INTERFACE("6f59e812-001e-4844-bcc6-432886856a17") IPnpObjectUpdate : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE get_Type( ABI::Windows::Devices::Enumeration::Pnp::PnpObjectType* value ) = 0; virtual HRESULT STDMETHODCALLTYPE get_Id( HSTRING* value ) = 0; virtual HRESULT STDMETHODCALLTYPE get_Properties( __FIMapView_2_HSTRING_IInspectable** value ) = 0; }; extern MIDL_CONST_ID IID& IID_IPnpObjectUpdate = _uuidof(IPnpObjectUpdate); } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObjectWatcher * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectWatcher[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher"; namespace ABI { namespace Windows { namespace Devices { namespace Enumeration { namespace Pnp { MIDL_INTERFACE("83c95ca8-4772-4a7a-aca8-e48c42a89c44") IPnpObjectWatcher : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE add_Added( __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* handler, EventRegistrationToken* token ) = 0; virtual HRESULT STDMETHODCALLTYPE remove_Added( EventRegistrationToken token ) = 0; virtual HRESULT STDMETHODCALLTYPE add_Updated( __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* handler, EventRegistrationToken* token ) = 0; virtual HRESULT STDMETHODCALLTYPE remove_Updated( EventRegistrationToken token ) = 0; virtual HRESULT STDMETHODCALLTYPE add_Removed( __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* handler, EventRegistrationToken* token ) = 0; virtual HRESULT STDMETHODCALLTYPE remove_Removed( EventRegistrationToken token ) = 0; virtual HRESULT STDMETHODCALLTYPE add_EnumerationCompleted( __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* handler, EventRegistrationToken* token ) = 0; virtual HRESULT STDMETHODCALLTYPE remove_EnumerationCompleted( EventRegistrationToken token ) = 0; virtual HRESULT STDMETHODCALLTYPE add_Stopped( __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* handler, EventRegistrationToken* token ) = 0; virtual HRESULT STDMETHODCALLTYPE remove_Stopped( EventRegistrationToken token ) = 0; virtual HRESULT STDMETHODCALLTYPE get_Status( ABI::Windows::Devices::Enumeration::DeviceWatcherStatus* status ) = 0; virtual HRESULT STDMETHODCALLTYPE Start(void) = 0; virtual HRESULT STDMETHODCALLTYPE Stop(void) = 0; }; extern MIDL_CONST_ID IID& IID_IPnpObjectWatcher = _uuidof(IPnpObjectWatcher); } /* Pnp */ } /* Enumeration */ } /* Devices */ } /* Windows */ } /* ABI */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObject * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * RuntimeClass contains static methods. * Static Methods exist on the Windows.Devices.Enumeration.Pnp.IPnpObjectStatics interface starting with version 1.0 of the Windows.Foundation.UniversalApiContract API contract * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObject ** Default Interface ** * * Class Threading Model: Both Single and Multi Threaded Apartment * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObject_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObject_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObject[] = L"Windows.Devices.Enumeration.Pnp.PnpObject"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectCollection * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Foundation.Collections.IVectorView`1<Windows.Devices.Enumeration.Pnp.PnpObject> ** Default Interface ** * Windows.Foundation.Collections.IIterable`1<Windows.Devices.Enumeration.Pnp.PnpObject> * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectCollection_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectCollection_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectCollection[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectCollection"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectUpdate * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate ** Default Interface ** * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectUpdate"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectWatcher * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher ** Default Interface ** * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectWatcher"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #else // !defined(__cplusplus) /* Forward Declarations */ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject; #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics; #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate; #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_FWD_DEFINED__ #ifndef ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher; #endif // ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_FWD_DEFINED__ // Parameterized interface forward declarations (C) // Collection interface definitions typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* put_Completed)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* handler); HRESULT (STDMETHODCALLTYPE* get_Completed)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject** result); HRESULT (STDMETHODCALLTYPE* GetResults)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject** result); END_INTERFACE } __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_put_Completed(This, handler) \ ((This)->lpVtbl->put_Completed(This, handler)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_get_Completed(This, result) \ ((This)->lpVtbl->get_Completed(This, result)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetResults(This, result) \ ((This)->lpVtbl->GetResults(This, result)) #endif /* COBJMACROS */ #endif // ____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* Invoke)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* asyncInfo, AsyncStatus asyncStatus); END_INTERFACE } __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Invoke(This, asyncInfo, asyncStatus) \ ((This)->lpVtbl->Invoke(This, asyncInfo, asyncStatus)) #endif /* COBJMACROS */ #endif // ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Current)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject** result); HRESULT (STDMETHODCALLTYPE* get_HasCurrent)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, boolean* result); HRESULT (STDMETHODCALLTYPE* MoveNext)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, boolean* result); HRESULT (STDMETHODCALLTYPE* GetMany)(__FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, UINT32 itemsLength, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject** items, UINT32* result); END_INTERFACE } __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_get_Current(This, result) \ ((This)->lpVtbl->get_Current(This, result)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_get_HasCurrent(This, result) \ ((This)->lpVtbl->get_HasCurrent(This, result)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_MoveNext(This, result) \ ((This)->lpVtbl->MoveNext(This, result)) #define __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetMany(This, itemsLength, items, result) \ ((This)->lpVtbl->GetMany(This, itemsLength, items, result)) #endif /* COBJMACROS */ #endif // ____FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* First)(__FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __FIIterator_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject** result); END_INTERFACE } __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_First(This, result) \ ((This)->lpVtbl->First(This, result)) #endif /* COBJMACROS */ #endif // ____FIIterable_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* GetAt)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, UINT32 index, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject** result); HRESULT (STDMETHODCALLTYPE* get_Size)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, UINT32* result); HRESULT (STDMETHODCALLTYPE* IndexOf)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* value, UINT32* index, boolean* result); HRESULT (STDMETHODCALLTYPE* GetMany)(__FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, UINT32 startIndex, UINT32 itemsLength, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject** items, UINT32* result); END_INTERFACE } __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetAt(This, index, result) \ ((This)->lpVtbl->GetAt(This, index, result)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_get_Size(This, result) \ ((This)->lpVtbl->get_Size(This, result)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_IndexOf(This, value, index, result) \ ((This)->lpVtbl->IndexOf(This, value, index, result)) #define __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_GetMany(This, startIndex, itemsLength, items, result) \ ((This)->lpVtbl->GetMany(This, startIndex, itemsLength, items, result)) #endif /* COBJMACROS */ #endif // ____FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection; #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__) #define ____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__ typedef interface __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection; typedef struct __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This); ULONG (STDMETHODCALLTYPE* Release)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* put_Completed)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* handler); HRESULT (STDMETHODCALLTYPE* get_Completed)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection** result); HRESULT (STDMETHODCALLTYPE* GetResults)(__FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, __FIVectorView_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject** result); END_INTERFACE } __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl; interface __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection { CONST_VTBL struct __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_put_Completed(This, handler) \ ((This)->lpVtbl->put_Completed(This, handler)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_get_Completed(This, result) \ ((This)->lpVtbl->get_Completed(This, result)) #define __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_GetResults(This, result) \ ((This)->lpVtbl->GetResults(This, result)) #endif /* COBJMACROS */ #endif // ____FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__) #define ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__ typedef interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection; typedef struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This); ULONG (STDMETHODCALLTYPE* Release)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This); HRESULT (STDMETHODCALLTYPE* Invoke)(__FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* This, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection* asyncInfo, AsyncStatus asyncStatus); END_INTERFACE } __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl; interface __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection { CONST_VTBL struct __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollectionVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_Invoke(This, asyncInfo, asyncStatus) \ ((This)->lpVtbl->Invoke(This, asyncInfo, asyncStatus)) #endif /* COBJMACROS */ #endif // ____FIAsyncOperationCompletedHandler_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FIIterator_1_HSTRING_INTERFACE_DEFINED__) #define ____FIIterator_1_HSTRING_INTERFACE_DEFINED__ typedef interface __FIIterator_1_HSTRING __FIIterator_1_HSTRING; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterator_1_HSTRING; typedef struct __FIIterator_1_HSTRINGVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterator_1_HSTRING* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterator_1_HSTRING* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterator_1_HSTRING* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterator_1_HSTRING* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterator_1_HSTRING* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterator_1_HSTRING* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Current)(__FIIterator_1_HSTRING* This, HSTRING* result); HRESULT (STDMETHODCALLTYPE* get_HasCurrent)(__FIIterator_1_HSTRING* This, boolean* result); HRESULT (STDMETHODCALLTYPE* MoveNext)(__FIIterator_1_HSTRING* This, boolean* result); HRESULT (STDMETHODCALLTYPE* GetMany)(__FIIterator_1_HSTRING* This, UINT32 itemsLength, HSTRING* items, UINT32* result); END_INTERFACE } __FIIterator_1_HSTRINGVtbl; interface __FIIterator_1_HSTRING { CONST_VTBL struct __FIIterator_1_HSTRINGVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterator_1_HSTRING_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterator_1_HSTRING_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterator_1_HSTRING_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterator_1_HSTRING_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterator_1_HSTRING_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterator_1_HSTRING_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterator_1_HSTRING_get_Current(This, result) \ ((This)->lpVtbl->get_Current(This, result)) #define __FIIterator_1_HSTRING_get_HasCurrent(This, result) \ ((This)->lpVtbl->get_HasCurrent(This, result)) #define __FIIterator_1_HSTRING_MoveNext(This, result) \ ((This)->lpVtbl->MoveNext(This, result)) #define __FIIterator_1_HSTRING_GetMany(This, itemsLength, items, result) \ ((This)->lpVtbl->GetMany(This, itemsLength, items, result)) #endif /* COBJMACROS */ #endif // ____FIIterator_1_HSTRING_INTERFACE_DEFINED__ #if !defined(____FIIterable_1_HSTRING_INTERFACE_DEFINED__) #define ____FIIterable_1_HSTRING_INTERFACE_DEFINED__ typedef interface __FIIterable_1_HSTRING __FIIterable_1_HSTRING; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterable_1_HSTRING; typedef struct __FIIterable_1_HSTRINGVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterable_1_HSTRING* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterable_1_HSTRING* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterable_1_HSTRING* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterable_1_HSTRING* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterable_1_HSTRING* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterable_1_HSTRING* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* First)(__FIIterable_1_HSTRING* This, __FIIterator_1_HSTRING** result); END_INTERFACE } __FIIterable_1_HSTRINGVtbl; interface __FIIterable_1_HSTRING { CONST_VTBL struct __FIIterable_1_HSTRINGVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterable_1_HSTRING_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterable_1_HSTRING_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterable_1_HSTRING_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterable_1_HSTRING_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterable_1_HSTRING_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterable_1_HSTRING_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterable_1_HSTRING_First(This, result) \ ((This)->lpVtbl->First(This, result)) #endif /* COBJMACROS */ #endif // ____FIIterable_1_HSTRING_INTERFACE_DEFINED__ #if !defined(____FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__) #define ____FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ typedef interface __FIKeyValuePair_2_HSTRING_IInspectable __FIKeyValuePair_2_HSTRING_IInspectable; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIKeyValuePair_2_HSTRING_IInspectable; typedef struct __FIKeyValuePair_2_HSTRING_IInspectableVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIKeyValuePair_2_HSTRING_IInspectable* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIKeyValuePair_2_HSTRING_IInspectable* This); ULONG (STDMETHODCALLTYPE* Release)(__FIKeyValuePair_2_HSTRING_IInspectable* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIKeyValuePair_2_HSTRING_IInspectable* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIKeyValuePair_2_HSTRING_IInspectable* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIKeyValuePair_2_HSTRING_IInspectable* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Key)(__FIKeyValuePair_2_HSTRING_IInspectable* This, HSTRING* result); HRESULT (STDMETHODCALLTYPE* get_Value)(__FIKeyValuePair_2_HSTRING_IInspectable* This, IInspectable** result); END_INTERFACE } __FIKeyValuePair_2_HSTRING_IInspectableVtbl; interface __FIKeyValuePair_2_HSTRING_IInspectable { CONST_VTBL struct __FIKeyValuePair_2_HSTRING_IInspectableVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIKeyValuePair_2_HSTRING_IInspectable_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIKeyValuePair_2_HSTRING_IInspectable_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIKeyValuePair_2_HSTRING_IInspectable_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIKeyValuePair_2_HSTRING_IInspectable_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIKeyValuePair_2_HSTRING_IInspectable_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIKeyValuePair_2_HSTRING_IInspectable_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIKeyValuePair_2_HSTRING_IInspectable_get_Key(This, result) \ ((This)->lpVtbl->get_Key(This, result)) #define __FIKeyValuePair_2_HSTRING_IInspectable_get_Value(This, result) \ ((This)->lpVtbl->get_Value(This, result)) #endif /* COBJMACROS */ #endif // ____FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ #if !defined(____FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__) #define ____FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ typedef interface __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable; typedef struct __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Current)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, __FIKeyValuePair_2_HSTRING_IInspectable** result); HRESULT (STDMETHODCALLTYPE* get_HasCurrent)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, boolean* result); HRESULT (STDMETHODCALLTYPE* MoveNext)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, boolean* result); HRESULT (STDMETHODCALLTYPE* GetMany)(__FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable* This, UINT32 itemsLength, __FIKeyValuePair_2_HSTRING_IInspectable** items, UINT32* result); END_INTERFACE } __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl; interface __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable { CONST_VTBL struct __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_get_Current(This, result) \ ((This)->lpVtbl->get_Current(This, result)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_get_HasCurrent(This, result) \ ((This)->lpVtbl->get_HasCurrent(This, result)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_MoveNext(This, result) \ ((This)->lpVtbl->MoveNext(This, result)) #define __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_GetMany(This, itemsLength, items, result) \ ((This)->lpVtbl->GetMany(This, itemsLength, items, result)) #endif /* COBJMACROS */ #endif // ____FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ #if !defined(____FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__) #define ____FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ typedef interface __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable; typedef struct __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This); ULONG (STDMETHODCALLTYPE* Release)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* First)(__FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable* This, __FIIterator_1___FIKeyValuePair_2_HSTRING_IInspectable** result); END_INTERFACE } __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl; interface __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable { CONST_VTBL struct __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectableVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_First(This, result) \ ((This)->lpVtbl->First(This, result)) #endif /* COBJMACROS */ #endif // ____FIIterable_1___FIKeyValuePair_2_HSTRING_IInspectable_INTERFACE_DEFINED__ typedef interface __FIMapView_2_HSTRING_IInspectable __FIMapView_2_HSTRING_IInspectable; #if !defined(____FIMapView_2_HSTRING_IInspectable_INTERFACE_DEFINED__) #define ____FIMapView_2_HSTRING_IInspectable_INTERFACE_DEFINED__ typedef interface __FIMapView_2_HSTRING_IInspectable __FIMapView_2_HSTRING_IInspectable; // Declare the parameterized interface IID. EXTERN_C const IID IID___FIMapView_2_HSTRING_IInspectable; typedef struct __FIMapView_2_HSTRING_IInspectableVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FIMapView_2_HSTRING_IInspectable* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FIMapView_2_HSTRING_IInspectable* This); ULONG (STDMETHODCALLTYPE* Release)(__FIMapView_2_HSTRING_IInspectable* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__FIMapView_2_HSTRING_IInspectable* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__FIMapView_2_HSTRING_IInspectable* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__FIMapView_2_HSTRING_IInspectable* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* Lookup)(__FIMapView_2_HSTRING_IInspectable* This, HSTRING key, IInspectable** result); HRESULT (STDMETHODCALLTYPE* get_Size)(__FIMapView_2_HSTRING_IInspectable* This, UINT32* result); HRESULT (STDMETHODCALLTYPE* HasKey)(__FIMapView_2_HSTRING_IInspectable* This, HSTRING key, boolean* result); HRESULT (STDMETHODCALLTYPE* Split)(__FIMapView_2_HSTRING_IInspectable* This, __FIMapView_2_HSTRING_IInspectable** first, __FIMapView_2_HSTRING_IInspectable** second); END_INTERFACE } __FIMapView_2_HSTRING_IInspectableVtbl; interface __FIMapView_2_HSTRING_IInspectable { CONST_VTBL struct __FIMapView_2_HSTRING_IInspectableVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FIMapView_2_HSTRING_IInspectable_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FIMapView_2_HSTRING_IInspectable_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FIMapView_2_HSTRING_IInspectable_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FIMapView_2_HSTRING_IInspectable_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __FIMapView_2_HSTRING_IInspectable_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __FIMapView_2_HSTRING_IInspectable_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __FIMapView_2_HSTRING_IInspectable_Lookup(This, key, result) \ ((This)->lpVtbl->Lookup(This, key, result)) #define __FIMapView_2_HSTRING_IInspectable_get_Size(This, result) \ ((This)->lpVtbl->get_Size(This, result)) #define __FIMapView_2_HSTRING_IInspectable_HasKey(This, key, result) \ ((This)->lpVtbl->HasKey(This, key, result)) #define __FIMapView_2_HSTRING_IInspectable_Split(This, first, second) \ ((This)->lpVtbl->Split(This, first, second)) #endif /* COBJMACROS */ #endif // ____FIMapView_2_HSTRING_IInspectable_INTERFACE_DEFINED__ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_INTERFACE_DEFINED__) #define ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_INTERFACE_DEFINED__ typedef interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable; // Declare the parameterized interface IID. EXTERN_C const IID IID___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable; typedef struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectableVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* This); ULONG (STDMETHODCALLTYPE* Release)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* This); HRESULT (STDMETHODCALLTYPE* Invoke)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* sender, IInspectable* args); END_INTERFACE } __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectableVtbl; interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable { CONST_VTBL struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectableVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_Invoke(This, sender, args) \ ((This)->lpVtbl->Invoke(This, sender, args)) #endif /* COBJMACROS */ #endif // ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__) #define ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ typedef interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject; // Declare the parameterized interface IID. EXTERN_C const IID IID___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject; typedef struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This); HRESULT (STDMETHODCALLTYPE* Invoke)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* sender, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* args); END_INTERFACE } __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl; interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject { CONST_VTBL struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_Invoke(This, sender, args) \ ((This)->lpVtbl->Invoke(This, sender, args)) #endif /* COBJMACROS */ #endif // ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_INTERFACE_DEFINED__) #define ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_INTERFACE_DEFINED__ typedef interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate; // Declare the parameterized interface IID. EXTERN_C const IID IID___FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate; typedef struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdateVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* This); ULONG (STDMETHODCALLTYPE* Release)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* This); HRESULT (STDMETHODCALLTYPE* Invoke)(__FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* sender, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* args); END_INTERFACE } __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdateVtbl; interface __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate { CONST_VTBL struct __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdateVtbl* lpVtbl; }; #ifdef COBJMACROS #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_Release(This) \ ((This)->lpVtbl->Release(This)) #define __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_Invoke(This, sender, args) \ ((This)->lpVtbl->Invoke(This, sender, args)) #endif /* COBJMACROS */ #endif // ____FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate_INTERFACE_DEFINED__ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 typedef enum __x_ABI_CWindows_CDevices_CEnumeration_CDeviceWatcherStatus __x_ABI_CWindows_CDevices_CEnumeration_CDeviceWatcherStatus; typedef enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType; /* * * Struct Windows.Devices.Enumeration.Pnp.PnpObjectType * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType { PnpObjectType_Unknown = 0, PnpObjectType_DeviceInterface = 1, PnpObjectType_DeviceContainer = 2, PnpObjectType_Device = 3, PnpObjectType_DeviceInterfaceClass = 4, PnpObjectType_AssociationEndpoint = 5, PnpObjectType_AssociationEndpointContainer = 6, PnpObjectType_AssociationEndpointService = 7, #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x70000 PnpObjectType_DevicePanel = 8, #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x70000 }; #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObject * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObject * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObject[] = L"Windows.Devices.Enumeration.Pnp.IPnpObject"; typedef struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This); ULONG (STDMETHODCALLTYPE* Release)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Type)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType* value); HRESULT (STDMETHODCALLTYPE* get_Id)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, HSTRING* value); HRESULT (STDMETHODCALLTYPE* get_Properties)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, __FIMapView_2_HSTRING_IInspectable** value); HRESULT (STDMETHODCALLTYPE* Update)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject* This, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* updateInfo); END_INTERFACE } __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectVtbl; interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject { CONST_VTBL struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectVtbl* lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_Release(This) \ ((This)->lpVtbl->Release(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_get_Type(This, value) \ ((This)->lpVtbl->get_Type(This, value)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_get_Id(This, value) \ ((This)->lpVtbl->get_Id(This, value)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_get_Properties(This, value) \ ((This)->lpVtbl->get_Properties(This, value)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_Update(This, updateInfo) \ ((This)->lpVtbl->Update(This, updateInfo)) #endif /* COBJMACROS */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObject_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectStatics * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObject * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectStatics[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectStatics"; typedef struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStaticsVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This); ULONG (STDMETHODCALLTYPE* Release)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* CreateFromIdAsync)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType type, HSTRING id, __FIIterable_1_HSTRING* requestedProperties, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObject** asyncOp); HRESULT (STDMETHODCALLTYPE* FindAllAsync)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection** asyncOp); HRESULT (STDMETHODCALLTYPE* FindAllAsyncAqsFilter)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, HSTRING aqsFilter, __FIAsyncOperation_1_Windows__CDevices__CEnumeration__CPnp__CPnpObjectCollection** asyncOp); HRESULT (STDMETHODCALLTYPE* CreateWatcher)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher** watcher); HRESULT (STDMETHODCALLTYPE* CreateWatcherAqsFilter)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType type, __FIIterable_1_HSTRING* requestedProperties, HSTRING aqsFilter, __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher** watcher); END_INTERFACE } __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStaticsVtbl; interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics { CONST_VTBL struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStaticsVtbl* lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_Release(This) \ ((This)->lpVtbl->Release(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_CreateFromIdAsync(This, type, id, requestedProperties, asyncOp) \ ((This)->lpVtbl->CreateFromIdAsync(This, type, id, requestedProperties, asyncOp)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FindAllAsync(This, type, requestedProperties, asyncOp) \ ((This)->lpVtbl->FindAllAsync(This, type, requestedProperties, asyncOp)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_FindAllAsyncAqsFilter(This, type, requestedProperties, aqsFilter, asyncOp) \ ((This)->lpVtbl->FindAllAsyncAqsFilter(This, type, requestedProperties, aqsFilter, asyncOp)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_CreateWatcher(This, type, requestedProperties, watcher) \ ((This)->lpVtbl->CreateWatcher(This, type, requestedProperties, watcher)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_CreateWatcherAqsFilter(This, type, requestedProperties, aqsFilter, watcher) \ ((This)->lpVtbl->CreateWatcherAqsFilter(This, type, requestedProperties, aqsFilter, watcher)) #endif /* COBJMACROS */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectStatics_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObjectUpdate * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectUpdate[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate"; typedef struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdateVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This); ULONG (STDMETHODCALLTYPE* Release)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* get_Type)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CPnpObjectType* value); HRESULT (STDMETHODCALLTYPE* get_Id)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, HSTRING* value); HRESULT (STDMETHODCALLTYPE* get_Properties)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate* This, __FIMapView_2_HSTRING_IInspectable** value); END_INTERFACE } __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdateVtbl; interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate { CONST_VTBL struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdateVtbl* lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_Release(This) \ ((This)->lpVtbl->Release(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_get_Type(This, value) \ ((This)->lpVtbl->get_Type(This, value)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_get_Id(This, value) \ ((This)->lpVtbl->get_Id(This, value)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_get_Properties(This, value) \ ((This)->lpVtbl->get_Properties(This, value)) #endif /* COBJMACROS */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectUpdate_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Interface Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Interface is a part of the implementation of type Windows.Devices.Enumeration.Pnp.PnpObjectWatcher * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #if !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__) #define ____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__ extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_Devices_Enumeration_Pnp_IPnpObjectWatcher[] = L"Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher"; typedef struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcherVtbl { BEGIN_INTERFACE HRESULT (STDMETHODCALLTYPE* QueryInterface)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, REFIID riid, void** ppvObject); ULONG (STDMETHODCALLTYPE* AddRef)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This); ULONG (STDMETHODCALLTYPE* Release)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This); HRESULT (STDMETHODCALLTYPE* GetIids)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, ULONG* iidCount, IID** iids); HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, HSTRING* className); HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, TrustLevel* trustLevel); HRESULT (STDMETHODCALLTYPE* add_Added)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObject* handler, EventRegistrationToken* token); HRESULT (STDMETHODCALLTYPE* remove_Added)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, EventRegistrationToken token); HRESULT (STDMETHODCALLTYPE* add_Updated)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* handler, EventRegistrationToken* token); HRESULT (STDMETHODCALLTYPE* remove_Updated)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, EventRegistrationToken token); HRESULT (STDMETHODCALLTYPE* add_Removed)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_Windows__CDevices__CEnumeration__CPnp__CPnpObjectUpdate* handler, EventRegistrationToken* token); HRESULT (STDMETHODCALLTYPE* remove_Removed)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, EventRegistrationToken token); HRESULT (STDMETHODCALLTYPE* add_EnumerationCompleted)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* handler, EventRegistrationToken* token); HRESULT (STDMETHODCALLTYPE* remove_EnumerationCompleted)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, EventRegistrationToken token); HRESULT (STDMETHODCALLTYPE* add_Stopped)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, __FITypedEventHandler_2_Windows__CDevices__CEnumeration__CPnp__CPnpObjectWatcher_IInspectable* handler, EventRegistrationToken* token); HRESULT (STDMETHODCALLTYPE* remove_Stopped)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, EventRegistrationToken token); HRESULT (STDMETHODCALLTYPE* get_Status)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This, enum __x_ABI_CWindows_CDevices_CEnumeration_CDeviceWatcherStatus* status); HRESULT (STDMETHODCALLTYPE* Start)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This); HRESULT (STDMETHODCALLTYPE* Stop)(__x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher* This); END_INTERFACE } __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcherVtbl; interface __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher { CONST_VTBL struct __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcherVtbl* lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_QueryInterface(This, riid, ppvObject) \ ((This)->lpVtbl->QueryInterface(This, riid, ppvObject)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_AddRef(This) \ ((This)->lpVtbl->AddRef(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_Release(This) \ ((This)->lpVtbl->Release(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_GetIids(This, iidCount, iids) \ ((This)->lpVtbl->GetIids(This, iidCount, iids)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_GetRuntimeClassName(This, className) \ ((This)->lpVtbl->GetRuntimeClassName(This, className)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_GetTrustLevel(This, trustLevel) \ ((This)->lpVtbl->GetTrustLevel(This, trustLevel)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_add_Added(This, handler, token) \ ((This)->lpVtbl->add_Added(This, handler, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_remove_Added(This, token) \ ((This)->lpVtbl->remove_Added(This, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_add_Updated(This, handler, token) \ ((This)->lpVtbl->add_Updated(This, handler, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_remove_Updated(This, token) \ ((This)->lpVtbl->remove_Updated(This, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_add_Removed(This, handler, token) \ ((This)->lpVtbl->add_Removed(This, handler, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_remove_Removed(This, token) \ ((This)->lpVtbl->remove_Removed(This, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_add_EnumerationCompleted(This, handler, token) \ ((This)->lpVtbl->add_EnumerationCompleted(This, handler, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_remove_EnumerationCompleted(This, token) \ ((This)->lpVtbl->remove_EnumerationCompleted(This, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_add_Stopped(This, handler, token) \ ((This)->lpVtbl->add_Stopped(This, handler, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_remove_Stopped(This, token) \ ((This)->lpVtbl->remove_Stopped(This, token)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_get_Status(This, status) \ ((This)->lpVtbl->get_Status(This, status)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_Start(This) \ ((This)->lpVtbl->Start(This)) #define __x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_Stop(This) \ ((This)->lpVtbl->Stop(This)) #endif /* COBJMACROS */ EXTERN_C const IID IID___x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher; #endif /* !defined(____x_ABI_CWindows_CDevices_CEnumeration_CPnp_CIPnpObjectWatcher_INTERFACE_DEFINED__) */ #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObject * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * RuntimeClass contains static methods. * Static Methods exist on the Windows.Devices.Enumeration.Pnp.IPnpObjectStatics interface starting with version 1.0 of the Windows.Foundation.UniversalApiContract API contract * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObject ** Default Interface ** * * Class Threading Model: Both Single and Multi Threaded Apartment * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObject_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObject_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObject[] = L"Windows.Devices.Enumeration.Pnp.PnpObject"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectCollection * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Foundation.Collections.IVectorView`1<Windows.Devices.Enumeration.Pnp.PnpObject> ** Default Interface ** * Windows.Foundation.Collections.IIterable`1<Windows.Devices.Enumeration.Pnp.PnpObject> * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectCollection_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectCollection_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectCollection[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectCollection"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectUpdate * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObjectUpdate ** Default Interface ** * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectUpdate[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectUpdate"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 /* * * Class Windows.Devices.Enumeration.Pnp.PnpObjectWatcher * * Introduced to Windows.Foundation.UniversalApiContract in version 1.0 * * Class implements the following interfaces: * Windows.Devices.Enumeration.Pnp.IPnpObjectWatcher ** Default Interface ** * * Class Marshaling Behavior: Agile - Class is agile * */ #if WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #ifndef RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher_DEFINED #define RUNTIMECLASS_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_Devices_Enumeration_Pnp_PnpObjectWatcher[] = L"Windows.Devices.Enumeration.Pnp.PnpObjectWatcher"; #endif #endif // WINDOWS_FOUNDATION_UNIVERSALAPICONTRACT_VERSION >= 0x10000 #endif // defined(__cplusplus) #pragma pop_macro("MIDL_CONST_ID") // Restore the original value of the 'DEPRECATED' macro #pragma pop_macro("DEPRECATED") #ifdef __clang__ #pragma clang diagnostic pop // deprecated-declarations #else #pragma warning(pop) #endif #endif // __windows2Edevices2Eenumeration2Epnp_p_h__ #endif // __windows2Edevices2Eenumeration2Epnp_h__
50.907021
505
0.810862
[ "object", "model" ]
a502535ffcfbbbb3a9fe4aeb200d8691c117c3cc
1,631
h
C
src/track/track_editor.h
WilliamLewww/Mustard
c9fc1ea7780e51e78e3362670a08b1764843ed7e
[ "MIT" ]
null
null
null
src/track/track_editor.h
WilliamLewww/Mustard
c9fc1ea7780e51e78e3362670a08b1764843ed7e
[ "MIT" ]
4
2018-01-03T04:51:24.000Z
2018-09-05T03:02:35.000Z
src/track/track_editor.h
WilliamLewww/Mustard
c9fc1ea7780e51e78e3362670a08b1764843ed7e
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "..\core\input.h" #include "..\core\vector2.h" #include "..\core\drawing.h" #include "..\camera.h" class TrackEditor { private: Vector2 visibleRange = Vector2(0, 0); int railSpacingY = 25; bool canPlaceTrack = false; bool enabled = false; bool canChangeMode = false; bool canRemove = false; std::vector<std::vector<Vector2>> railList; int railColor[3] = { 0, 0, 0 }; int currentRailColor[3] = { 255, 0, 0 }; Vector2* boardPosition; int boardWidth, boardHeight; inline Vector2 getBoardCenter() { return Vector2(boardPosition->x + (boardWidth / 2), boardPosition->y + (boardHeight / 2)); }; std::vector<Vector2> getVisibleRail(int side); bool overridePlacement = false; public: bool spec = true; inline Vector2 halfBoardSize() { return Vector2(boardWidth / 2, boardHeight / 2); }; inline bool getSpec() { return spec; }; inline bool getEnabled() { return enabled; }; inline void setEnabled(bool enabled, Vector2* boardPosition, int boardWidth, int boardHeight) { this->enabled = enabled; this->boardPosition = boardPosition; this->boardWidth = boardWidth; this->boardHeight = boardHeight; }; inline void disable() { this->enabled = false; }; inline void enableOverride() { overridePlacement = true; }; inline void disableOverride() { overridePlacement = false; }; inline std::vector<std::vector<Vector2>> getRailList() { return railList; }; inline void clearRailList() { railList.clear(); }; void increaseSpacing(); void decreaseSpacing(); void resetSpacing(); void placeTrack(); void removeTrack(); void update(); void draw(); };
25.888889
128
0.70141
[ "vector" ]
a504714cf5540e89f69db34e113634504960e0d4
11,988
c
C
lib/cfm.c
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
null
null
null
lib/cfm.c
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
null
null
null
lib/cfm.c
salomon42/openvswitch-ovs
7fae5e7bb62af3b8ac74fe20052064eb01feada0
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2010, 2011 Nicira Networks. * * 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 <config.h> #include "cfm.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include "dynamic-string.h" #include "flow.h" #include "hash.h" #include "hmap.h" #include "ofpbuf.h" #include "packets.h" #include "poll-loop.h" #include "timer.h" #include "timeval.h" #include "vlog.h" VLOG_DEFINE_THIS_MODULE(cfm); #define CCM_OPCODE 1 /* CFM message opcode meaning CCM. */ struct cfm_internal { struct cfm cfm; uint32_t seq; /* The sequence number of our last CCM. */ uint8_t ccm_interval; /* The CCM transmission interval. */ int ccm_interval_ms; /* 'ccm_interval' in milliseconds. */ struct timer tx_timer; /* Send CCM when expired. */ struct timer fault_timer; /* Check for faults when expired. */ long long x_recv_time; }; static int ccm_interval_to_ms(uint8_t interval) { switch (interval) { case 0: NOT_REACHED(); /* Explicitly not supported by 802.1ag. */ case 1: return 3; /* Not recommended due to timer resolution. */ case 2: return 10; /* Not recommended due to timer resolution. */ case 3: return 100; case 4: return 1000; case 5: return 10000; case 6: return 60000; case 7: return 600000; default: NOT_REACHED(); /* Explicitly not supported by 802.1ag. */ } NOT_REACHED(); } static long long int cfm_fault_interval(struct cfm_internal *cfmi) { /* According to the 802.1ag specification we should assume every other MP * with the same MAID has the same transmission interval that we have. If * an MP has a different interval, cfm_process_heartbeat will register it * as a fault (likely due to a configuration error). Thus we can check all * MPs at once making this quite a bit simpler. * * According to the specification we should check when (ccm_interval_ms * * 3.5)ms have passed. */ return (cfmi->ccm_interval_ms * 7) / 2; } static uint8_t ms_to_ccm_interval(int interval_ms) { uint8_t i; for (i = 7; i > 0; i--) { if (ccm_interval_to_ms(i) <= interval_ms) { return i; } } return 1; } static struct cfm_internal * cfm_to_internal(const struct cfm *cfm) { return CONTAINER_OF(cfm, struct cfm_internal, cfm); } static uint32_t hash_mpid(uint8_t mpid) { return hash_int(mpid, 0); } static bool cfm_is_valid_mpid(uint32_t mpid) { /* 802.1ag specification requires MPIDs to be within the range [1, 8191] */ return mpid >= 1 && mpid <= 8191; } static struct remote_mp * lookup_remote_mp(const struct hmap *hmap, uint16_t mpid) { struct remote_mp *rmp; HMAP_FOR_EACH_IN_BUCKET (rmp, node, hash_mpid(mpid), hmap) { if (rmp->mpid == mpid) { return rmp; } } return NULL; } /* Allocates a 'cfm' object. This object should have its 'mpid', 'maid', * 'eth_src', and 'interval' filled out. When changes are made to the 'cfm' * object, cfm_configure should be called before using it. */ struct cfm * cfm_create(void) { struct cfm *cfm; struct cfm_internal *cfmi; cfmi = xzalloc(sizeof *cfmi); cfm = &cfmi->cfm; cfmi->x_recv_time = LLONG_MIN; hmap_init(&cfm->remote_mps); return cfm; } void cfm_destroy(struct cfm *cfm) { struct cfm_internal *cfmi = cfm_to_internal(cfm); struct remote_mp *rmp, *rmp_next; if (!cfm) { return; } HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &cfm->remote_mps) { hmap_remove(&cfm->remote_mps, &rmp->node); free(rmp); } hmap_destroy(&cfm->remote_mps); free(cfmi); } /* Should be run periodically to update fault statistics messages. */ void cfm_run(struct cfm *cfm) { long long now = time_msec(); struct cfm_internal *cfmi = cfm_to_internal(cfm); if (timer_expired(&cfmi->fault_timer)) { bool fault; struct remote_mp *rmp; long long int interval; interval = cfm_fault_interval(cfmi); fault = now < cfmi->x_recv_time + interval; HMAP_FOR_EACH (rmp, node, &cfm->remote_mps) { if (rmp->recv_time < timer_enabled_at(&cfmi->fault_timer, interval) || timer_expired_at(&cfmi->fault_timer, rmp->recv_time)) { rmp->fault = true; } if (rmp->fault) { fault = true; } } cfm->fault = fault; timer_set_duration(&cfmi->fault_timer, interval); } } /* Should be run periodically to check if the CFM module has a CCM message it * wishes to send. */ bool cfm_should_send_ccm(struct cfm *cfm) { struct cfm_internal *cfmi = cfm_to_internal(cfm); return timer_expired(&cfmi->tx_timer); } /* Composes a CCM message into 'ccm'. Messages generated with this function * should be sent whenever cfm_should_send_ccm() indicates. */ void cfm_compose_ccm(struct cfm *cfm, struct ccm *ccm) { struct cfm_internal *cfmi = cfm_to_internal(cfm); timer_set_duration(&cfmi->tx_timer, cfmi->ccm_interval_ms); ccm->mdlevel_version = 0; ccm->opcode = CCM_OPCODE; ccm->tlv_offset = 70; ccm->seq = htonl(++cfmi->seq); ccm->mpid = htons(cfmi->cfm.mpid); ccm->flags = cfmi->ccm_interval; memcpy(ccm->maid, cfmi->cfm.maid, sizeof ccm->maid); } void cfm_wait(struct cfm *cfm) { struct cfm_internal *cfmi = cfm_to_internal(cfm); timer_wait(&cfmi->tx_timer); timer_wait(&cfmi->fault_timer); } /* Should be called whenever a client of the cfm library changes the internals * of 'cfm'. Returns true if 'cfm' is valid. */ bool cfm_configure(struct cfm *cfm) { struct cfm_internal *cfmi = cfm_to_internal(cfm); uint8_t interval; if (!cfm_is_valid_mpid(cfm->mpid) || !cfm->interval) { return false; } interval = ms_to_ccm_interval(cfm->interval); if (interval != cfmi->ccm_interval) { cfmi->ccm_interval = interval; cfmi->ccm_interval_ms = ccm_interval_to_ms(interval); timer_set_expired(&cfmi->tx_timer); timer_set_duration(&cfmi->fault_timer, cfm_fault_interval(cfmi)); } return true; } /* Given an array of MPIDs, updates the 'remote_mps' map of 'cfm' to reflect * it. Invalid MPIDs are skipped. */ void cfm_update_remote_mps(struct cfm *cfm, const uint16_t *mpids, size_t n_mpids) { size_t i; struct hmap new_rmps; struct remote_mp *rmp, *rmp_next; hmap_init(&new_rmps); for (i = 0; i < n_mpids; i++) { uint16_t mpid = mpids[i]; if (!cfm_is_valid_mpid(mpid) || lookup_remote_mp(&new_rmps, mpid)) { continue; } if ((rmp = lookup_remote_mp(&cfm->remote_mps, mpid))) { hmap_remove(&cfm->remote_mps, &rmp->node); } else { rmp = xzalloc(sizeof *rmp); rmp->mpid = mpid; } hmap_insert(&new_rmps, &rmp->node, hash_mpid(mpid)); } hmap_swap(&new_rmps, &cfm->remote_mps); HMAP_FOR_EACH_SAFE (rmp, rmp_next, node, &new_rmps) { hmap_remove(&new_rmps, &rmp->node); free(rmp); } hmap_destroy(&new_rmps); } /* Finds a 'remote_mp' with 'mpid' in 'cfm'. If no such 'remote_mp' exists * returns NULL. */ const struct remote_mp * cfm_get_remote_mp(const struct cfm *cfm, uint16_t mpid) { return lookup_remote_mp(&cfm->remote_mps, mpid); } /* Generates 'maid' from 'md_name' and 'ma_name'. A NULL parameter indicates * the default should be used. Returns false if unsuccessful. */ bool cfm_generate_maid(const char *md_name, const char *ma_name, uint8_t maid[CCM_MAID_LEN]) { uint8_t *ma_p; size_t md_len, ma_len; if (!md_name) { md_name = "ovs"; } if (!ma_name) { ma_name = "ovs"; } memset(maid, 0, CCM_MAID_LEN); md_len = strlen(md_name); ma_len = strlen(ma_name); if (!md_len || !ma_len || md_len + ma_len + 4 > CCM_MAID_LEN) { return false; } maid[0] = 4; /* MD name string format. */ maid[1] = md_len; /* MD name size. */ memcpy(&maid[2], md_name, md_len); /* MD name. */ ma_p = maid + 2 + md_len; ma_p[0] = 2; /* MA name string format. */ ma_p[1] = ma_len; /* MA name size. */ memcpy(&ma_p[2], ma_name, ma_len); /* MA name. */ return true; } /* Returns true if the CFM library should process packets from 'flow'. */ bool cfm_should_process_flow(const struct flow *flow) { return (ntohs(flow->dl_type) == ETH_TYPE_CFM && eth_addr_equals(flow->dl_dst, eth_addr_ccm)); } /* Updates internal statistics relevant to packet 'p'. Should be called on * every packet whose flow returned true when passed to * cfm_should_process_flow. */ void cfm_process_heartbeat(struct cfm *cfm, const struct ofpbuf *p) { struct ccm *ccm; uint16_t ccm_mpid; uint8_t ccm_interval; struct remote_mp *rmp; struct eth_header *eth; struct cfm_internal *cfmi = cfm_to_internal(cfm); static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20); eth = p->l2; ccm = ofpbuf_at(p, (uint8_t *)p->l3 - (uint8_t *)p->data, CCM_LEN); if (!ccm) { VLOG_INFO_RL(&rl, "Received an un-parseable 802.1ag CCM heartbeat."); return; } if (ccm->opcode != CCM_OPCODE) { VLOG_INFO_RL(&rl, "Received an unsupported 802.1ag message. " "(opcode %u)", ccm->opcode); return; } if (memcmp(ccm->maid, cfm->maid, sizeof ccm->maid)) { cfmi->x_recv_time = time_msec(); cfm->fault = true; VLOG_WARN_RL(&rl, "Received unexpected remote MAID from MAC " ETH_ADDR_FMT, ETH_ADDR_ARGS(eth->eth_src)); } else { ccm_mpid = ntohs(ccm->mpid); ccm_interval = ccm->flags & 0x7; rmp = lookup_remote_mp(&cfm->remote_mps, ccm_mpid); if (rmp) { rmp->recv_time = time_msec(); rmp->fault = ccm_interval != cfmi->ccm_interval; cfm->fault = rmp->fault || cfm->fault; } else { cfmi->x_recv_time = time_msec(); cfm->fault = true; VLOG_WARN_RL(&rl, "Received unexpected remote MPID %d from MAC " ETH_ADDR_FMT, ccm_mpid, ETH_ADDR_ARGS(eth->eth_src)); } } } void cfm_dump_ds(const struct cfm *cfm, struct ds *ds) { const struct cfm_internal *cfmi = cfm_to_internal(cfm); long long int now = time_msec(); struct remote_mp *rmp; ds_put_format(ds, "MPID %"PRIu16": %s\n", cfm->mpid, cfm->fault ? "fault" : ""); ds_put_format(ds, "\tinterval: %dms\n", cfmi->ccm_interval_ms); ds_put_format(ds, "\tnext CCM tx: %lldms\n", timer_msecs_until_expired(&cfmi->tx_timer)); ds_put_format(ds, "\tnext fault check: %lldms\n", timer_msecs_until_expired(&cfmi->fault_timer)); if (cfmi->x_recv_time != LLONG_MIN) { ds_put_format(ds, "\ttime since bad CCM rx: %lldms\n", now - cfmi->x_recv_time); } ds_put_cstr(ds, "\n"); HMAP_FOR_EACH (rmp, node, &cfm->remote_mps) { ds_put_format(ds, "Remote MPID %"PRIu16": %s\n", rmp->mpid, rmp->fault ? "fault" : ""); ds_put_format(ds, "\ttime since CCM rx: %lldms\n", time_msec() - rmp->recv_time); } }
27.62212
79
0.624208
[ "object" ]
a50872fa696fa1baa02b01df23ca947bd6801718
48
h
C
packages/mccomposite/lib/geometry/primitives/AbstractShape.h
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
5
2017-01-16T03:59:47.000Z
2020-06-23T02:54:19.000Z
packages/mccomposite/lib/geometry/primitives/AbstractShape.h
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
293
2015-10-29T17:45:52.000Z
2022-01-07T16:31:09.000Z
packages/mccomposite/lib/geometry/operations/AbstractShape.h
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
1
2019-05-25T00:53:31.000Z
2019-05-25T00:53:31.000Z
#include "mccomposite/geometry/AbstractShape.h"
24
47
0.833333
[ "geometry" ]
aa13bf5a0fd5f23bac92f28bf8b3904d620e499f
7,037
h
C
src/mongo/db/s/move_primary_source_manager.h
GeertBosch/mongo
884d232473dca72e0872f0e540d4c3108c1e0b3d
[ "Apache-2.0" ]
72
2020-06-12T06:33:41.000Z
2021-03-22T03:15:56.000Z
src/mongo/db/s/move_primary_source_manager.h
GeertBosch/mongo
884d232473dca72e0872f0e540d4c3108c1e0b3d
[ "Apache-2.0" ]
9
2020-07-02T09:36:49.000Z
2021-03-25T23:54:00.000Z
src/mongo/db/s/move_primary_source_manager.h
GeertBosch/mongo
884d232473dca72e0872f0e540d4c3108c1e0b3d
[ "Apache-2.0" ]
14
2020-06-12T03:08:03.000Z
2021-02-03T11:43:09.000Z
/** * Copyright (C) 2018 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #pragma once #include "mongo/base/disallow_copying.h" #include "mongo/db/s/database_sharding_state.h" #include "mongo/s/request_types/move_primary_gen.h" #include "mongo/util/timer.h" namespace mongo { class OperationContext; class Shard; struct ShardingStatistics; class Status; /** * The donor-side movePrimary state machine. This object must be created and owned by a single * thread, which controls its lifetime and should not be passed across threads. Unless explicitly * indicated its methods must not be called from more than one thread and must not be called while * any locks are held. * * The intended workflow is as follows: * - Acquire a distributed lock on the database whose primary is about to be moved. * - Instantiate a MovePrimarySourceManager on the stack. * - Call clone to start and finish cloning of the unsharded collections. * - Call enterCriticalSection to cause the shard to enter in 'read only' mode while the config * server is notified of the new primary. * - Call commitOnConfig to indicate the new primary in the config server metadata. * - Call cleanStaleData to drop now-unused collections (and potentially databases) on the * old primary. * * At any point in time it is safe to let the MovePrimarySourceManager object go out of scope in * which case the destructor will take care of clean up based on how far we have advanced. */ class MovePrimarySourceManager { MONGO_DISALLOW_COPYING(MovePrimarySourceManager); public: /** * Instantiates a new movePrimary source manager. Must be called with the distributed lock * acquired in advance (not asserted). * * May throw any exception. Known exceptions (TODO) are: * - InvalidOptions if the operation context is missing database version * - StaleConfigException if the expected database version does not match what we find it * to be after acquiring the distributed lock. */ MovePrimarySourceManager(OperationContext* opCtx, ShardMovePrimary requestArgs, StringData dbname, ShardId& fromShard, ShardId& toShard); ~MovePrimarySourceManager(); /** * Returns the namespace for which this source manager is active. */ NamespaceString getNss() const; /** * Contacts the recipient shard and tells it to start cloning the specified chunk. This method * will fail if for any reason the recipient shard fails to complete the cloning sequence. * * Expected state: kCreated * Resulting state: kCloning on success, kDone on failure */ Status clone(OperationContext* opCtx); /** * Once this call returns successfully, no writes will be happening on this shard until the * movePrimary is committed. Therefore, commitMovePrimaryMetadata must be called as soon as * possible afterwards. * * Expected state: kCloneCaughtUp * Resulting state: kCriticalSection on success, kDone on failure */ Status enterCriticalSection(OperationContext* opCtx); /** * Persists the updated DatabaseVersion on the config server and leaves the critical section. * * Expected state: kCriticalSection * Resulting state: kNeedCleanStaleData */ Status commitOnConfig(OperationContext* opCtx); /** * Clears stale collections (and potentially databases) on the old primary. * * Expected state: kNeedCleanStaleData * Resulting state: kDone */ Status cleanStaleData(OperationContext* opCtx); /** * May be called at any time. Unregisters the movePrimary source manager from the database and * logs an error in the change log to indicate that the migration has failed. * * Expected state: Any * Resulting state: kDone */ void cleanupOnError(OperationContext* opCtx); private: static BSONObj _buildMoveLogEntry(const std::string& db, const std::string& from, const std::string& to) { BSONObjBuilder details; details.append("database", db); details.append("from", from); details.append("to", to); return details.obj(); } // Used to track the current state of the source manager. See the methods above, which have // comments explaining the various state transitions. enum State { kCreated, kCloning, kCloneCaughtUp, kCriticalSection, kCloneCompleted, kNeedCleanStaleData, kDone }; /** * Called when any of the states fails. May only be called once and will put the migration * manager into the kDone state. */ void _cleanup(OperationContext* opCtx); // The parameters to the movePrimary command const ShardMovePrimary _requestArgs; // The database whose primary we are moving. const StringData _dbname; // The donor shard const ShardId& _fromShard; // The recipient shard const ShardId& _toShard; // Collections that were cloned to the new primary std::vector<NamespaceString> _clonedColls; // Indicates whether sharded collections exist on the old primary. bool _shardedCollectionsExistOnDb; // Times the entire movePrimary operation const Timer _entireOpTimer; // The current state. Used only for diagnostics and validation. State _state{kCreated}; }; } // namespace mongo
37.430851
98
0.693335
[ "object", "vector" ]
aa19d52c340d7100a55924ab37ad6e2974d686ee
8,347
h
C
content/common/gpu/client/content_gl_context.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2016-03-10T09:13:57.000Z
2016-03-10T09:13:57.000Z
content/common/gpu/client/content_gl_context.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
1
2022-03-13T08:39:05.000Z
2022-03-13T08:39:05.000Z
content/common/gpu/client/content_gl_context.h
gavinp/chromium
681563ea0f892a051f4ef3d5e53438e0bb7d2261
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This API is consistent with other OpenGL setup APIs like window's WGL // and pepper's PGL. This API is used to manage OpenGL ContentGLContexts in the // Chrome renderer process in a way that is consistent with other platforms. #ifndef CONTENT_COMMON_GPU_CLIENT_RENDERER_GL_CONTEXT_H_ #define CONTENT_COMMON_GPU_CLIENT_RENDERER_GL_CONTEXT_H_ #pragma once #include <vector> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" #include "build/build_config.h" #include "ui/gfx/gl/gpu_preference.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/size.h" class GpuChannelHost; class CommandBufferProxy; class GURL; struct GpuMemoryAllocationForRenderer; namespace gpu { class TransferBuffer; namespace gles2 { class GLES2CmdHelper; class GLES2Implementation; } } class ContentGLContext : public base::SupportsWeakPtr<ContentGLContext>, public base::NonThreadSafe { public: // These are the same error codes as used by EGL. enum Error { SUCCESS = 0x3000, BAD_ATTRIBUTE = 0x3004, CONTEXT_LOST = 0x300E }; // ContentGLContext configuration attributes. Those in the 16-bit range are // the same as used by EGL. Those outside the 16-bit range are unique to // Chromium. Attributes are matched using a closest fit algorithm. enum Attribute { ALPHA_SIZE = 0x3021, BLUE_SIZE = 0x3022, GREEN_SIZE = 0x3023, RED_SIZE = 0x3024, DEPTH_SIZE = 0x3025, STENCIL_SIZE = 0x3026, SAMPLES = 0x3031, SAMPLE_BUFFERS = 0x3032, HEIGHT = 0x3056, WIDTH = 0x3057, NONE = 0x3038, // Attrib list = terminator SHARE_RESOURCES = 0x10000, BIND_GENERATES_RESOURCES = 0x10001 }; // Reasons that a lost context might have been provoked. enum ContextLostReason { // This context definitely provoked the loss of context. kGuilty, // This context definitely did not provoke the loss of context. kInnocent, // It is unknown whether this context provoked the loss of context. kUnknown }; // Initialize the library. This must have completed before any other // functions are invoked. static bool Initialize(); // Terminate the library. This must be called after any other functions // have completed. static bool Terminate(); ~ContentGLContext(); // Create a ContentGLContext that renders directly to a view. The view and // the associated window must not be destroyed until the returned // ContentGLContext has been destroyed, otherwise the GPU process might // attempt to render to an invalid window handle. // // NOTE: on Mac OS X, this entry point is only used to set up the // accelerated compositor's output. On this platform, we actually pass // a gfx::PluginWindowHandle in place of the gfx::NativeViewId, // because the facility to allocate a fake PluginWindowHandle is // already in place. We could add more entry points and messages to // allocate both fake PluginWindowHandles and NativeViewIds and map // from fake NativeViewIds to PluginWindowHandles, but this seems like // unnecessary complexity at the moment. // // The render_view_id is currently also only used on Mac OS X. // TODO(kbr): clean up the arguments to this function and make them // more cross-platform. static ContentGLContext* CreateViewContext( GpuChannelHost* channel, int32 surface_id, ContentGLContext* share_group, const char* allowed_extensions, const int32* attrib_list, const GURL& active_url, gfx::GpuPreference gpu_preference); // Create a ContentGLContext that renders to an offscreen frame buffer. If // parent is not NULL, that ContentGLContext can access a copy of the created // ContentGLContext's frame buffer that is updated every time SwapBuffers is // called. It is not as general as shared ContentGLContexts in other // implementations of OpenGL. If parent is not NULL, it must be used on the // same thread as the parent. A child ContentGLContext may not outlive its // parent. attrib_list must be NULL or a NONE-terminated list of // attribute/value pairs. static ContentGLContext* CreateOffscreenContext( GpuChannelHost* channel, const gfx::Size& size, ContentGLContext* share_group, const char* allowed_extensions, const int32* attrib_list, const GURL& active_url, gfx::GpuPreference gpu_preference); // Sets the parent context. If any parent textures have been created for // another parent, it is important to delete them before changing the parent. bool SetParent(ContentGLContext* parent); // For an offscreen frame buffer ContentGLContext, return the texture ID with // respect to the parent ContentGLContext. Returns zero if ContentGLContext // does not have a parent. uint32 GetParentTextureId(); // Create a new texture in the parent's ContentGLContext. Returns zero if // ContentGLContext does not have a parent. uint32 CreateParentTexture(const gfx::Size& size); // Deletes a texture in the parent's ContentGLContext. void DeleteParentTexture(uint32 texture); void SetContextLostCallback( const base::Callback<void(ContextLostReason)>& callback); // Set the current ContentGLContext for the calling thread. static bool MakeCurrent(ContentGLContext* context); // For a view ContentGLContext, display everything that has been rendered // since the last call. For an offscreen ContentGLContext, resolve everything // that has been rendered since the last call to a copy that can be accessed // by the parent ContentGLContext. bool SwapBuffers(); // Run the task once the channel has been flushed. Takes care of deleting the // task whether the echo succeeds or not. bool Echo(const base::Closure& task); // Sends an IPC message with the new state of surface visibility bool SetSurfaceVisible(bool visibility); bool DiscardBackbuffer(); bool EnsureBackbuffer(); // Register a callback to invoke whenever we recieve a new memory allocation. void SetMemoryAllocationChangedCallback( const base::Callback<void(const GpuMemoryAllocationForRenderer&)>& callback); // Allows direct access to the GLES2 implementation so a ContentGLContext // can be used without making it current. gpu::gles2::GLES2Implementation* GetImplementation(); // Return the current error. Error GetError(); // Return true if GPU process reported ContentGLContext lost or there was a // problem communicating with the GPU process. bool IsCommandBufferContextLost(); CommandBufferProxy* GetCommandBufferProxy(); // The following 3 IDs let one uniquely identify this context. // Gets the GPU process ID for this context. int GetGPUProcessID(); // Gets the channel ID for this context. int GetChannelID(); // Gets the context ID (relative to the channel). int GetContextID(); private: explicit ContentGLContext(GpuChannelHost* channel); bool Initialize(bool onscreen, int32 surface_id, const gfx::Size& size, ContentGLContext* share_group, const char* allowed_extensions, const int32* attrib_list, const GURL& active_url, gfx::GpuPreference gpu_preference); void Destroy(); void OnContextLost(); scoped_refptr<GpuChannelHost> channel_; base::WeakPtr<ContentGLContext> parent_; base::Callback<void(ContextLostReason)> context_lost_callback_; uint32 parent_texture_id_; CommandBufferProxy* command_buffer_; gpu::gles2::GLES2CmdHelper* gles2_helper_; gpu::TransferBuffer* transfer_buffer_; gpu::gles2::GLES2Implementation* gles2_implementation_; Error last_error_; int frame_number_; DISALLOW_COPY_AND_ASSIGN(ContentGLContext); }; #endif // CONTENT_COMMON_GPU_CLIENT_RENDERER_GL_CONTEXT_H_
36.933628
79
0.718102
[ "render", "vector" ]
aa1b811eb8e388c64dfe61da29083259d8ed4753
616
h
C
src/Renderer/internal/ShaderDefinitions.h
mmha/gravity
5499b77cde89589abefa88618205a0db5f342443
[ "BSL-1.0" ]
null
null
null
src/Renderer/internal/ShaderDefinitions.h
mmha/gravity
5499b77cde89589abefa88618205a0db5f342443
[ "BSL-1.0" ]
null
null
null
src/Renderer/internal/ShaderDefinitions.h
mmha/gravity
5499b77cde89589abefa88618205a0db5f342443
[ "BSL-1.0" ]
null
null
null
#pragma once #include <array> #include <vector> #include <cstdint> #include <experimental/string_view> #include "../../Core/Enum.h" namespace ge::gl4 { enum class UniformLocations : uint32_t { GE_ULOCATION_CAMERA, GE_ULOCATION_MODELINFO, GE_ULOCATION_TECHNIQUE_PARAMETER, COUNT }; extern const std::experimental::string_view shaderDefinitions; extern const Core::EnumArray<std::experimental::string_view, UniformLocations> builtinUniformNames; extern std::vector<std::string> vertexAttributes; //TODO flat_set } //GE_DECLARE_ENUM_STD_HASHER(::ge::gl4::UniformLocations)
23.692308
102
0.743506
[ "vector" ]
aa1e66374f016cbc572c7ef48b44776a81f6fd7e
786
h
C
Concepts/Constructors and Destructors/Constructors and Destructors/Cat.h
nwy140/C-Projects
e1d960f0f08231eb496267ddae37da5fbc9c9de9
[ "MIT" ]
1
2021-02-17T05:44:52.000Z
2021-02-17T05:44:52.000Z
Concepts/Constructors and Destructors/Constructors and Destructors/Cat.h
nwy140/C-Projects
e1d960f0f08231eb496267ddae37da5fbc9c9de9
[ "MIT" ]
null
null
null
Concepts/Constructors and Destructors/Constructors and Destructors/Cat.h
nwy140/C-Projects
e1d960f0f08231eb496267ddae37da5fbc9c9de9
[ "MIT" ]
null
null
null
#pragma once //Creating a class at solution explorer will automatically generate a cpp and header file with the class in header, and declaring methods from class in cpp class Cat // functions in a class are called methods , variables are used to define states/attributes of an object of a class { private: //cannot be accessed outside of class , unless you are accessing from a method declared for this class bool happy; // any variable in class header is not initialized, thus does have a random garbage value // every cat, every seperate object will have its copy of boolean variable when initialized public: // can be accessed outside of class void speak(); Cat(); //constructor // don't have return type ~Cat(); //destructor // destructor has a ~ before classname };
46.235294
155
0.756997
[ "object" ]
aa1eda908adde8741d6af77ad056e7e04bd288ae
12,014
c
C
saneobj-demo.c
ProgerXP/SaneC
75a9b263cdb215796a84c5413187dc1d7905925b
[ "CC0-1.0" ]
14
2020-03-31T12:03:31.000Z
2021-10-21T16:19:22.000Z
saneobj-demo.c
ProgerXP/SaneC
75a9b263cdb215796a84c5413187dc1d7905925b
[ "CC0-1.0" ]
1
2020-04-01T11:35:42.000Z
2020-04-02T09:26:20.000Z
saneobj-demo.c
ProgerXP/SaneC
75a9b263cdb215796a84c5413187dc1d7905925b
[ "CC0-1.0" ]
1
2021-07-09T21:56:25.000Z
2021-07-09T21:56:25.000Z
#include <stdlib.h> #include "saneobj.h" // Use valgrind. /*** Fruit - A Base Class ****************************************************/ // (*) Forward declaration so Fruit's methods can accept Fruit's instances // rather than void*. struct Fruit; typedef struct { Object_vt_; // (*) Abstract method, not defined (resolves to NULL so can't be called). void (*eat)(struct Fruit *o); int (*caloriesPerQuantity)(struct Fruit *o, int qty); } Fruit_vt_; typedef struct { Object_; int calories; } Fruit_; classdef(Fruit, Object); int Fruit_caloriesPerQuantity(Fruit *o, int qty) { return o->calories * qty; } Fruit *Fruit_new(Fruit *o, void *params) { // (*) Abstract class, cannot be instantiated. if (!o->vt) { throw(msgex("Fruit is abstract!")); } initnew(Fruit); return o; } Fruit_vt *vtFruit(void) { linkvt(Fruit, Object) { vt.caloriesPerQuantity = Fruit_caloriesPerQuantity; } return &vt; } /*** Wallnut - A Simple Sub-Class ********************************************/ struct Wallnut; typedef struct { Fruit_vt_; // (*) No introduced methods. } Wallnut_vt_; typedef struct { Fruit_; // (*) No introduced properties. } Wallnut_; classdef(Wallnut, Fruit); Wallnut *Wallnut_new(Wallnut *o, void *params) { initnew(Wallnut); // (*) Setting default value for an inherited property. o->calories = 400; return o; } // (*) Short VT function's definition form. vtdef(Wallnut, Fruit) { } endvtdef /*** Orange - A Sub-Class ****************************************************/ struct Orange; typedef struct { Fruit_vt_; int (*cut)(struct Orange *o, int pieces); } Orange_vt_; typedef struct { Fruit_; char isWhole; } Orange_; classdef(Orange, Fruit); void Orange_eat(Fruit *o) { printf("ate %s", as(o, Orange)->isWhole ? "an orange" : "a piece of orange"); } int Orange_cut(Orange *o, int pieces) { if (pieces > 8) { throw(msgex("No, it's heurestically impossible. Get yourself a melon.")); } else if (pieces < 0) { // (*) Creating a formatted message. throw(sxprintf(newex(), "If your intention is to cheat the Universe by overflowing the counter" " and producing %lu pieces from 1 orange I'm happy to testify that it's" " been made better than our machines.", (unsigned long) pieces)); } o->isWhole = 0; return pieces; } // (*) Overriding an inherited method. int Orange_caloriesPerQuantity(Fruit *o, int qty) { if (qty > 20) { throw(msgex("Buzzt! Buuzt! Explosion danger!")); } // (*) Calling inherited implementation and returning result. inherited(Orange, caloriesPerQuantity) { return inh->caloriesPerQuantity(o, qty); } // We know caloriesPerQuantity() is implemented in Fruit. If fails, indicates // a bug in inherited() implementation. throw(msgex("Should never happen- you know how it happens.")); } Orange *Orange_new(Orange *o, void *params) { initnew(Orange); o->calories = 20; o->isWhole = 1; return o; } Orange_vt *vtOrange(void) { linkvt(Orange, Fruit) { vt.caloriesPerQuantity = Orange_caloriesPerQuantity; vt.eat = Orange_eat; vt.cut = Orange_cut; } return &vt; } /*** YesNo - A Parametrized Singleton ****************************************/ struct YesNo; typedef struct { Autoref_vt_; void (*print)(struct YesNo *o); } YesNo_vt_; typedef struct { Autoref_; char value; } YesNo_; classdef(YesNo, Autoref); YesNo *yesNoes[2]; void YesNo_print(YesNo *o) { puts(o->value ? "yes" : "NO!!!"); } // value can be any sophisticated type the size of a pointer, like to a struct. YesNo *YesNo_new(YesNo *o, void *params) { int value = params ? 1 : 0; if (yesNoes[value]) { // (*) Substituting input object for another one. return yesNoes[value]; } // (*) Using memory allocated by the caller. yesNoes[value] = o; initnew(YesNo); * (char *) &o->value = value; // (*) Prevent this instance from being freed when the caller doesn't need it. o->vt->take(asp(o, Autoref)); return o; } YesNo_vt *vtYesNo(void) { linkvt(YesNo, Autoref) { vt.print = YesNo_print; } return &vt; } /*** Entry Point *************************************************************/ int main () { #ifdef SJ_TRACE_LIFE sjCreating = sjObjectCallbackStdErr; sjDeleting = sjObjectCallbackStdErr; #endif // Here and below "//>" indicates the expected output. Orange_vt *vt = vtOrange(); printf( "Orange's VT function returns %s pointers, with className == %s" " and parent of %s.\n", //> same vt == vtOrange() ? "same" : "different (?!)", //> Orange, Fruit vt->className, vt->parent->className); // (*) Instantiation. Fruit *orange = newobj(Orange); Fruit *wallnut = newobj(Wallnut); // (*) VT (class definition) member access. Instance property access. printf("We got 1 %s (%d cal.) and 1 %s (%d cal.).\n", //> Orange, 20 orange->vt->className, orange->calories, //> Wallnut, 400 wallnut->vt->className, wallnut->calories); printf( "%s: VT's size=%lu, object's size=%lu.\n" "%s: VT's size=%lu, object's size=%lu.\n", //> varies by platform orange->vt->className, orange->vt->size, orange->vt->objectSize, //> smaller than Orange's, smaller wallnut->vt->className, wallnut->vt->size, wallnut->vt->objectSize); // (*) Method calling, including an overriden implementation (of Orange). printf("10 Oranges = %d cal. 10 Wallnuts = %d cal.\n", //> 20*10=200 orange->vt->caloriesPerQuantity(orange, 10), //> 400*10=4000 wallnut->vt->caloriesPerQuantity(wallnut, 10)); printf("Both objects have %s - %s.\n", //> the same parent orange->vt->parent == wallnut->vt->parent ? "the same parent" : "different (?!) parents", //> Fruit orange->vt->parent->className); // (*) Various utility functions. struct SjInheritedMethod eatBase = sjBaseMethod(aspo(orange)->vt, &orange->vt->eat); struct SjInheritedMethod cutBase = sjBaseMethod(aspo(orange)->vt, &as(orange, Orange)->vt->cut); printf("eat() was introduced in %s as %s, cut() - in %s as %s.\n", //> Fruit, abstract eatBase.vt->className, eatBase.method ? "concrete (?!)" : "abstract", //> Orange, concrete cutBase.vt->className, cutBase.method ? "concrete" : "abstract (?!)"); printf("%s is compatible with %s? %s. with %s? %s. with %s? %s.\n", //> Orange orange->vt->className, //> Orange, yes vtOrange()->className, sjHasClass(orange, vtOrange()) ? "yes" : "no (?!)", //> Object, yes vtObject()->className, sjHasClass(orange, vtObject()) ? "yes" : "no (?!)", //> Wallnut, no vtWallnut()->className, sjHasClass(orange, vtWallnut()) ? "yes (?!)" : "no" ); char *list1, *list2; printf("Full class chain: %s,\nbackwards: %s.\n", //> Orange<Fruit<Object list1 = sjJoinClassList(orange->vt, "<", 0), //> Object>Fruit>Orange list2 = sjJoinClassList(orange->vt, ">", 1)); free(list1); free(list2); printf("Got %d parents, 0th = %s, 1st = %s, 2nd = %s, 3rd = %p.\n", //> 2 sjCountParents(orange->vt), //> Object sjNthParent(orange->vt, 0)->className, //> Fruit sjNthParent(orange->vt, 1)->className, //> Orange sjNthParent(orange->vt, 2)->className, //> null sjNthParent(orange->vt, 3)); // (*) Class-cast to a compatible parent class. Resulting class (VT) is // the same, it's just a safety check for runtime. printf("Let's try casting %s to Fruit/Object... got %s/%s.\n", //> Orange orange->vt->className, //> Orange as(orange, Fruit)->vt->className, //> Orange as(orange, Object)->vt->className); // (*) Quick compile-time class-cast. printf("Can do the same with asp()... got %s.\n", //> Orange asp(orange, Fruit)->vt->className); printf("Trying a farther parent... got %s/%s.\n", //> Orange asp(orange, Object)->vt->className, //> Orange aspo(orange)->vt->className); // These shouldn't actually compile - gcc needs to produce // "<Fruit> has no member named <Orange_>". //asp(orange, Orange); // downside cast. //asp(orange, Wallnut); // incompatible class (another branch). // (*) Class-cast in any direction (here - from base class to subclass). printf("Let's try casting %s to Orange... ", wallnut->vt->className); try { as(wallnut, Orange); printf("not good, it worked! Report this bug please!\n"); abort(); } catchall { //> Object of class Wallnut cannot be cast to Orange printf("uh oh, got an exception: %s\n", curex().message); } endtry printf("Trying to instantiate an abstract class of Fruit... "); try { newobj(Fruit); printf("not good, it worked! Report this bug please!\n"); abort(); } catchall { //> Fruit is abstract! printf("uh oh, got an exception: %s\n", curex().message); //sxPrintTrace(); } endtry Orange *or = as(orange, Orange); printf("Cheating Orange to pieces... "); try { or->vt->cut(or, -1); printf("not good, it worked! Report this bug please!\n"); abort(); } catchall { //> a long piece of nonsense (cut because of the SX_MAX_TRACE_STRING limit) printf("uh oh, got an exception: %s\n", curex().message); } endtry //> 5 5 printf("Cutting into %d pieces - got %d back.\n", 5, or->vt->cut(or, 5)); //> 0 printf("isWhole = %d.\n", or->isWhole); // In a real program: // * Objects may be created on the stack (useful for function-local objects). // or be static (global or function) to never go away // * All code between newobj and delobj will be wrapped in try..finally. delobj(orange); delobj(wallnut); // Autorefs. // (*) Parametrized newobj. YesNo *no = newobjx(YesNo, (void *) 0); YesNo *yes1 = newobjx(YesNo, (void *) 1); YesNo *yes2 = newobjx(YesNo, (void *) 2); printf("Got two %s %s's (yes1-2): %p == %p, and %s %s (no).\n", //> same, YesNo, %p, %p yes1 == yes2 ? "same" : "different (?!)", yes1->vt->className, yes1, yes2, //> different, YesNo yes1 == no ? "the same (?!)" : "a different", no->vt->className); printf("yes1 talks: "); //> yes yes1->vt->print(yes1); printf("no talks: "); //> NO!!! no->vt->print(no); printf("yes' refs = %d, no's refs = %d.\n", //> 1, 1 yes1->refs, no->refs); // In production code these would be called as soon as newobj returns // (or at the beginning of a function receiving an object argument). no->vt->take(asp(no, Autoref)); yes1->vt->take(asp(yes1, Autoref)); yes2->vt->take(asp(yes2, Autoref)); //> 3 printf("yes' new refs = %d.\n", yes1->refs); // (*) delobj returning was-deleted flag and NULL'ing the variable. char del1 = delobj(yes1); printf("Now deleting... del yes1 = %d (%p), refs = %d.\n", //> 0, %p, 2 del1, yes1, yes2->refs); yes1 = newobjx(YesNo, (void *) 1); yes1->vt->take(asp(yes1, Autoref)); printf("Got new instance of yes, %s before: %p == %p, refs = %d.\n", //> same yes1 == yes2 ? "same as" : "different (?!) from", //> %p, %p, 3 yes1, yes2, yes1->refs); del1 = delobj(yes1); char del2 = delobj(yes2); // Don't do it at home! Only tests are allowed to del what they haven't taken. char delg = delobj(yesNoes[1]); printf("Now deleting... del yes1 = %d, yes2 = %d, global = %d (%p).\n", //> 0, 0, 1, NULL del1, del2, delg, yesNoes[1]); // (*) On-stack object. newsobj(Orange, os) { os->calories = 50; printf("Got a big orange here, a pair gives us %d cal.\n", //> 50*2=100 os->vt->caloriesPerQuantity(asp(os, Fruit), 2)); } endsobj(os) #ifdef SJ_TRACE_LIFE printf( "The library tells us we have created %d objects and deleted %d of" " them (stack objects not included).\n", //> 4 = Orange, Wallnut, first and second unique YesNo's (yes1, no) sjObjectsCreated, //> 3 = Orange, Wallnut, first YesNo (yes1); no is still kept back in yesNoes[] sjObjectsDeleted); #endif }
28.004662
83
0.606626
[ "object" ]
aa2245e10d97e2eb453e446e93a6555071b6452c
4,634
h
C
logdevice/ops/ldquery/tables/Sequencers.h
Ikhbar-Kebaa/LogDevice
d69d706fb81d665eb94ee844aab94ff4951c9731
[ "BSD-3-Clause" ]
1
2019-01-17T18:53:25.000Z
2019-01-17T18:53:25.000Z
logdevice/ops/ldquery/tables/Sequencers.h
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
logdevice/ops/ldquery/tables/Sequencers.h
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
/** * 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 <map> #include <vector> #include "../Context.h" #include "AdminCommandTable.h" namespace facebook { namespace logdevice { namespace ldquery { namespace tables { class Sequencers : public AdminCommandTable { public: explicit Sequencers(std::shared_ptr<Context> ctx) : AdminCommandTable(ctx) {} static std::string getName() { return "sequencers"; } std::string getDescription() override { return "This table dumps information about all the Sequencer objects in " "the cluster. See \"logdevice/common/Sequencer.h\"."; } TableColumns getFetchableColumns() const override { return { {"log_id", DataType::LOGID, "Log ID this sequencer is for."}, {"metadata_log_id", DataType::TEXT, "ID of the corresponding metadata log."}, {"state", DataType::TEXT, "State of the sequencer. Can be one of: \"UNAVAILABLE\" (Sequencer " "has not yet gotten a valid epoch metadata with an epoch number), " "\"ACTIVATING\" (Sequencer is in the process of getting an epoch " "number and retrieving metadata from the epoch store), \"ACTIVE\" " "(Sequencer is able to replicate), \"PREEMPTED\" (Sequencer has been " "preempted by another sequencer \"preempted_by\", appends to this " "node will be redirected to it), \"PERMANENT_ERROR\" (Permanent " "process-wide error such as running out of ephemera ports)."}, {"epoch", DataType::BIGINT, "Epoch of the sequencer."}, {"next_lsn", DataType::LSN, "Next LSN to be issued to a record by this sequencer."}, {"meta_last_released", DataType::LSN, "Last released LSN of the metadata log."}, {"last_released", DataType::LSN, "Last released LSN for the data log."}, {"last_known_good", DataType::LSN, "Last known good LSN for this data log. This is the highest ESN such " "that all records up to that ESN are known to be fully replicated."}, {"in_flight", DataType::BIGINT, "Number of appends currently in flight."}, {"last_used_ms", DataType::BIGINT, "Timestamp of the last record appended by this sequencer."}, {"state_duration_ms", DataType::BIGINT, "Amount of time in milliseconds the sequencer has been in the current " "\"state\"."}, {"nodeset_state", DataType::TEXT, "Contains debugging information about shards in that epoch's storage " "set. \"H\" means that the shard is healthy. \"L\" means that the " "shard reached the low watermark for space usage. \"O\" means that " "the shard reported being overloaded. \"S\" means that the shard is " "out of space. \"U\" means that the sequencer cannot establish a " "connection to the shard. \"D\" means that the shard's local log " "store is not accepting writes. \"G\" means that the shard is " "greylisting for copyset selection because it is too slow. \"P\" " "means that the sequencer is currently probling the health of this " "shard."}, {"preempted_epoch", DataType::BIGINT, "Epoch of the sequencer that preempted this sequencer (if any)."}, {"preempted_by", DataType::BIGINT, "ID of the sequencer that preempted this sequencer (if any)."}, {"draining", DataType::BIGINT, "Epoch that is draining (if any). Draining means that the sequencer " "stopped accepting new writes but is completing appends curretnly in " "flight."}, {"metadata_log_written", DataType::BIGINT, "Whether the epoch metadata used by this sequencer has been written " "to the metadata log."}, // TODO (T36984535) : deprecate column last_byte_offset {"last_byte_offset", DataType::TEXT, "Offsets of the tail record."}}; } std::string getCommandToSend(QueryContext& ctx) const override { logid_t logid; if (columnHasEqualityConstraintOnLogid(1, ctx, logid)) { return std::string("info sequencers ") + std::to_string(logid.val_) + " --json\n"; } else { return std::string("info sequencers --json\n"); } } }; }}}} // namespace facebook::logdevice::ldquery::tables
41.747748
80
0.628615
[ "vector" ]
aa26e6ca1f9c4818bb9f5103efc793a5be6084ea
88,947
c
C
processors/ARM/gdb-7.10/sim/sh/gencode.c
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
110
2015-01-10T17:54:56.000Z
2021-08-08T05:06:55.000Z
processors/ARM/gdb-7.10/sim/sh/gencode.c
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
36
2015-05-08T07:45:52.000Z
2019-04-30T13:41:12.000Z
processors/ARM/gdb-7.10/sim/sh/gencode.c
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
45
2015-02-26T13:55:13.000Z
2020-11-25T09:17:43.000Z
/* Simulator/Opcode generator for the Renesas (formerly Hitachi) / SuperH Inc. Super-H architecture. Written by Steve Chamberlain of Cygnus Support. sac@cygnus.com This file is part of SH sim. THIS SOFTWARE IS NOT COPYRIGHTED Cygnus offers the following for use in the public domain. Cygnus makes no warranty with regard to the software or it's performance and the user accepts the software "AS IS" with all faults. CYGNUS DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* This program generates the opcode table for the assembler and the simulator code. -t prints a pretty table for the assembler manual -s generates the simulator code jump table -d generates a define table -x generates the simulator code switch statement default used to generate the opcode tables */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MAX_NR_STUFF 42 typedef struct { const char *defs; const char *refs; const char *name; const char *code; const char * const stuff[MAX_NR_STUFF]; int index; } op; static op tab[] = { { "n", "", "add #<imm>,<REG_N>", "0111nnnni8*1....", "R[n] += SEXT (i);", "if (i == 0) {", " UNDEF(n); /* see #ifdef PARANOID */", " break;", "}", }, { "n", "mn", "add <REG_M>,<REG_N>", "0011nnnnmmmm1100", "R[n] += R[m];", }, { "n", "mn", "addc <REG_M>,<REG_N>", "0011nnnnmmmm1110", "ult = R[n] + T;", "SET_SR_T (ult < R[n]);", "R[n] = ult + R[m];", "SET_SR_T (T || (R[n] < ult));", }, { "n", "mn", "addv <REG_M>,<REG_N>", "0011nnnnmmmm1111", "ult = R[n] + R[m];", "SET_SR_T ((~(R[n] ^ R[m]) & (ult ^ R[n])) >> 31);", "R[n] = ult;", }, { "0", "0", "and #<imm>,R0", "11001001i8*1....", "R0 &= i;", }, { "n", "nm", "and <REG_M>,<REG_N>", "0010nnnnmmmm1001", "R[n] &= R[m];", }, { "", "0", "and.b #<imm>,@(R0,GBR)", "11001101i8*1....", "MA (1);", "WBAT (GBR + R0, RBAT (GBR + R0) & i);", }, { "", "", "bf <bdisp8>", "10001011i8p1....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (!T) {", " SET_NIP (PC + 4 + (SEXT (i) * 2));", " cycles += 2;", "}", }, { "", "", "bf.s <bdisp8>", "10001111i8p1....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (!T) {", " SET_NIP (PC + 4 + (SEXT (i) * 2));", " cycles += 2;", " Delay_Slot (PC + 2);", "}", }, { "", "n", "bit32 #imm3,@(disp12,<REG_N>)", "0011nnnni8*11001", "/* 32-bit logical bit-manipulation instructions. */", "int word2 = RIAT (nip);", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "i >>= 4; /* BOGUS: Using only three bits of 'i'. */", "/* MSB of 'i' must be zero. */", "if (i > 7)", " RAISE_EXCEPTION (SIGILL);", "MA (1);", "do_blog_insn (1 << i, (word2 & 0xfff) + R[n], ", " (word2 >> 12) & 0xf, memory, maskb);", "SET_NIP (nip + 2); /* Consume 2 more bytes. */", }, { "", "", "bra <bdisp12>", "1010i12.........", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (PC + 4 + (SEXT12 (i) * 2));", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "n", "braf <REG_N>", "0000nnnn00100011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (PC + 4 + R[n]);", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "", "bsr <bdisp12>", "1011i12.........", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "PR = PH2T (PC + 4);", "SET_NIP (PC + 4 + (SEXT12 (i) * 2));", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "n", "bsrf <REG_N>", "0000nnnn00000011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "PR = PH2T (PC) + 4;", "SET_NIP (PC + 4 + R[n]);", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "", "bt <bdisp8>", "10001001i8p1....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (T) {", " SET_NIP (PC + 4 + (SEXT (i) * 2));", " cycles += 2;", "}", }, { "", "m", "bld/st #<imm>, <REG_M>", "10000111mmmmi4*1", "/* MSB of 'i' is true for load, false for store. */", "if (i <= 7)", " if (T)", " R[m] |= (1 << i);", " else", " R[m] &= ~(1 << i);", "else", " SET_SR_T ((R[m] & (1 << (i - 8))) != 0);", }, { "m", "m", "bset/clr #<imm>, <REG_M>", "10000110mmmmi4*1", "/* MSB of 'i' is true for set, false for clear. */", "if (i <= 7)", " R[m] &= ~(1 << i);", "else", " R[m] |= (1 << (i - 8));", }, { "n", "n", "clips.b <REG_N>", "0100nnnn10010001", "if (R[n] < -128 || R[n] > 127) {", " L (n);", " SET_SR_CS (1);", " if (R[n] > 127)", " R[n] = 127;", " else if (R[n] < -128)", " R[n] = -128;", "}", }, { "n", "n", "clips.w <REG_N>", "0100nnnn10010101", "if (R[n] < -32768 || R[n] > 32767) {", " L (n);", " SET_SR_CS (1);", " if (R[n] > 32767)", " R[n] = 32767;", " else if (R[n] < -32768)", " R[n] = -32768;", "}", }, { "n", "n", "clipu.b <REG_N>", "0100nnnn10000001", "if (R[n] < -256 || R[n] > 255) {", " L (n);", " SET_SR_CS (1);", " R[n] = 255;", "}", }, { "n", "n", "clipu.w <REG_N>", "0100nnnn10000101", "if (R[n] < -65536 || R[n] > 65535) {", " L (n);", " SET_SR_CS (1);", " R[n] = 65535;", "}", }, { "n", "0n", "divs R0,<REG_N>", "0100nnnn10010100", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (R0 == 0)", " R[n] = 0x7fffffff;", "else if (R0 == -1 && R[n] == 0x80000000)", " R[n] = 0x7fffffff;", "else R[n] /= R0;", "L (n);", }, { "n", "0n", "divu R0,<REG_N>", "0100nnnn10000100", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (R0 == 0)", " R[n] = 0xffffffff;", "/* FIXME: The result may be implementation-defined if it is outside */", "/* the range of signed int (i.e. if R[n] was negative and R0 == 1). */", "else R[n] = R[n] / (unsigned int) R0;", "L (n);", }, { "n", "0n", "mulr R0,<REG_N>", "0100nnnn10000000", "R[n] = (R[n] * R0) & 0xffffffff;", "L (n);", }, { "0", "n", "ldbank @<REG_N>,R0", "0100nnnn11100101", "int regn = (R[n] >> 2) & 0x1f;", "int bankn = (R[n] >> 7) & 0x1ff;", "if (regn > 19)", " regn = 19; /* FIXME what should happen? */", "R0 = saved_state.asregs.regstack[bankn].regs[regn];", "L (0);", }, { "", "0n", "stbank R0,@<REG_N>", "0100nnnn11100001", "int regn = (R[n] >> 2) & 0x1f;", "int bankn = (R[n] >> 7) & 0x1ff;", "if (regn > 19)", " regn = 19; /* FIXME what should happen? */", "saved_state.asregs.regstack[bankn].regs[regn] = R0;", }, { "", "", "resbank", "0000000001011011", "int i;", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", /* FIXME: cdef all */ "if (BO) { /* Bank Overflow */", /* FIXME: how do we know when to reset BO? */ " for (i = 0; i <= 14; i++) {", " R[i] = RLAT (R[15]);", " MA (1);", " R[15] += 4;", " }", " PR = RLAT (R[15]);", " R[15] += 4;", " MA (1);", " GBR = RLAT (R[15]);", " R[15] += 4;", " MA (1);", " MACH = RLAT (R[15]);", " R[15] += 4;", " MA (1);", " MACL = RLAT (R[15]);", " R[15] += 4;", " MA (1);", "}", "else if (BANKN == 0) /* Bank Underflow */", " RAISE_EXCEPTION (SIGILL);", /* FIXME: what exception? */ "else {", " SET_BANKN (BANKN - 1);", " for (i = 0; i <= 14; i++)", " R[i] = saved_state.asregs.regstack[BANKN].regs[i];", " MACH = saved_state.asregs.regstack[BANKN].regs[15];", " PR = saved_state.asregs.regstack[BANKN].regs[17];", " GBR = saved_state.asregs.regstack[BANKN].regs[18];", " MACL = saved_state.asregs.regstack[BANKN].regs[19];", "}", }, { "f", "f-", "movml.l <REG_N>,@-R15", "0100nnnn11110001", "/* Push Rn...R0 (if n==15, push pr and R14...R0). */", "do {", " MA (1);", " R[15] -= 4;", " if (n == 15)", " WLAT (R[15], PR);", " else", " WLAT (R[15], R[n]);", "} while (n-- > 0);", }, { "f", "f+", "movml.l @R15+,<REG_N>", "0100nnnn11110101", "/* Pop R0...Rn (if n==15, pop R0...R14 and pr). */", "int i = 0;\n", "do {", " MA (1);", " if (i == 15)", " PR = RLAT (R[15]);", " else", " R[i] = RLAT (R[15]);", " R[15] += 4;", "} while (i++ < n);", }, { "f", "f-", "movmu.l <REG_N>,@-R15", "0100nnnn11110000", "/* Push pr, R14...Rn (if n==15, push pr). */", /* FIXME */ "int i = 15;\n", "do {", " MA (1);", " R[15] -= 4;", " if (i == 15)", " WLAT (R[15], PR);", " else", " WLAT (R[15], R[i]);", "} while (i-- > n);", }, { "f", "f+", "movmu.l @R15+,<REG_N>", "0100nnnn11110100", "/* Pop Rn...R14, pr (if n==15, pop pr). */", /* FIXME */ "do {", " MA (1);", " if (n == 15)", " PR = RLAT (R[15]);", " else", " R[n] = RLAT (R[15]);", " R[15] += 4;", "} while (n++ < 15);", }, { "", "", "nott", "0000000001101000", "SET_SR_T (T == 0);", }, { "", "", "bt.s <bdisp8>", "10001101i8p1....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (T) {", " SET_NIP (PC + 4 + (SEXT (i) * 2));", " cycles += 2;", " Delay_Slot (PC + 2);", "}", }, { "", "", "clrmac", "0000000000101000", "MACH = 0;", "MACL = 0;", }, { "", "", "clrs", "0000000001001000", "SET_SR_S (0);", }, { "", "", "clrt", "0000000000001000", "SET_SR_T (0);", }, /* sh4a */ { "", "", "clrdmxy", "0000000010001000", "saved_state.asregs.cregs.named.sr &= ~(SR_MASK_DMX | SR_MASK_DMY);" }, { "", "0", "cmp/eq #<imm>,R0", "10001000i8*1....", "SET_SR_T (R0 == SEXT (i));", }, { "", "mn", "cmp/eq <REG_M>,<REG_N>", "0011nnnnmmmm0000", "SET_SR_T (R[n] == R[m]);", }, { "", "mn", "cmp/ge <REG_M>,<REG_N>", "0011nnnnmmmm0011", "SET_SR_T (R[n] >= R[m]);", }, { "", "mn", "cmp/gt <REG_M>,<REG_N>", "0011nnnnmmmm0111", "SET_SR_T (R[n] > R[m]);", }, { "", "mn", "cmp/hi <REG_M>,<REG_N>", "0011nnnnmmmm0110", "SET_SR_T (UR[n] > UR[m]);", }, { "", "mn", "cmp/hs <REG_M>,<REG_N>", "0011nnnnmmmm0010", "SET_SR_T (UR[n] >= UR[m]);", }, { "", "n", "cmp/pl <REG_N>", "0100nnnn00010101", "SET_SR_T (R[n] > 0);", }, { "", "n", "cmp/pz <REG_N>", "0100nnnn00010001", "SET_SR_T (R[n] >= 0);", }, { "", "mn", "cmp/str <REG_M>,<REG_N>", "0010nnnnmmmm1100", "ult = R[n] ^ R[m];", "SET_SR_T (((ult & 0xff000000) == 0)", " | ((ult & 0xff0000) == 0)", " | ((ult & 0xff00) == 0)", " | ((ult & 0xff) == 0));", }, { "", "mn", "div0s <REG_M>,<REG_N>", "0010nnnnmmmm0111", "SET_SR_Q ((R[n] & sbit) != 0);", "SET_SR_M ((R[m] & sbit) != 0);", "SET_SR_T (M != Q);", }, { "", "", "div0u", "0000000000011001", "SET_SR_M (0);", "SET_SR_Q (0);", "SET_SR_T (0);", }, { "n", "nm", "div1 <REG_M>,<REG_N>", "0011nnnnmmmm0100", "div1 (&R0, m, n/*, T*/);", }, { "", "nm", "dmuls.l <REG_M>,<REG_N>", "0011nnnnmmmm1101", "dmul (1/*signed*/, R[n], R[m]);", }, { "", "nm", "dmulu.l <REG_M>,<REG_N>", "0011nnnnmmmm0101", "dmul (0/*unsigned*/, R[n], R[m]);", }, { "n", "n", "dt <REG_N>", "0100nnnn00010000", "R[n]--;", "SET_SR_T (R[n] == 0);", }, { "n", "m", "exts.b <REG_M>,<REG_N>", "0110nnnnmmmm1110", "R[n] = SEXT (R[m]);", }, { "n", "m", "exts.w <REG_M>,<REG_N>", "0110nnnnmmmm1111", "R[n] = SEXTW (R[m]);", }, { "n", "m", "extu.b <REG_M>,<REG_N>", "0110nnnnmmmm1100", "R[n] = (R[m] & 0xff);", }, { "n", "m", "extu.w <REG_M>,<REG_N>", "0110nnnnmmmm1101", "R[n] = (R[m] & 0xffff);", }, /* sh2e */ { "", "", "fabs <FREG_N>", "1111nnnn01011101", " union", " {", " unsigned int i;", " float f;", " } u;", " u.f = FR (n);", " u.i &= 0x7fffffff;", " SET_FR (n, u.f);", }, /* sh2e */ { "", "", "fadd <FREG_M>,<FREG_N>", "1111nnnnmmmm0000", "FP_OP (n, +, m);", }, /* sh2e */ { "", "", "fcmp/eq <FREG_M>,<FREG_N>", "1111nnnnmmmm0100", "FP_CMP (n, ==, m);", }, /* sh2e */ { "", "", "fcmp/gt <FREG_M>,<FREG_N>", "1111nnnnmmmm0101", "FP_CMP (n, >, m);", }, /* sh4 */ { "", "", "fcnvds <DR_N>,FPUL", "1111nnnn10111101", "if (! FPSCR_PR || n & 1)", " RAISE_EXCEPTION (SIGILL);", "else", "{", " union", " {", " int i;", " float f;", " } u;", " u.f = DR (n);", " FPUL = u.i;", "}", }, /* sh4 */ { "", "", "fcnvsd FPUL,<DR_N>", "1111nnnn10101101", "if (! FPSCR_PR || n & 1)", " RAISE_EXCEPTION (SIGILL);", "else", "{", " union", " {", " int i;", " float f;", " } u;", " u.i = FPUL;", " SET_DR (n, u.f);", "}", }, /* sh2e */ { "", "", "fdiv <FREG_M>,<FREG_N>", "1111nnnnmmmm0011", "FP_OP (n, /, m);", "/* FIXME: check for DP and (n & 1) == 0? */", }, /* sh4 */ { "", "", "fipr <FV_M>,<FV_N>", "1111vvVV11101101", "if (FPSCR_PR)", " RAISE_EXCEPTION (SIGILL);", "else", "{", " double fsum = 0;", " if (saved_state.asregs.bfd_mach == bfd_mach_sh2a)", " RAISE_EXCEPTION (SIGILL);", " /* FIXME: check for nans and infinities. */", " fsum += FR (v1+0) * FR (v2+0);", " fsum += FR (v1+1) * FR (v2+1);", " fsum += FR (v1+2) * FR (v2+2);", " fsum += FR (v1+3) * FR (v2+3);", " SET_FR (v1+3, fsum);", "}", }, /* sh2e */ { "", "", "fldi0 <FREG_N>", "1111nnnn10001101", "SET_FR (n, (float) 0.0);", "/* FIXME: check for DP and (n & 1) == 0? */", }, /* sh2e */ { "", "", "fldi1 <FREG_N>", "1111nnnn10011101", "SET_FR (n, (float) 1.0);", "/* FIXME: check for DP and (n & 1) == 0? */", }, /* sh2e */ { "", "", "flds <FREG_N>,FPUL", "1111nnnn00011101", " union", " {", " int i;", " float f;", " } u;", " u.f = FR (n);", " FPUL = u.i;", }, /* sh2e */ { "", "", "float FPUL,<FREG_N>", "1111nnnn00101101", /* sh4 */ "if (FPSCR_PR)", " SET_DR (n, (double) FPUL);", "else", "{", " SET_FR (n, (float) FPUL);", "}", }, /* sh2e */ { "", "", "fmac <FREG_0>,<FREG_M>,<FREG_N>", "1111nnnnmmmm1110", "SET_FR (n, FR (m) * FR (0) + FR (n));", "/* FIXME: check for DP and (n & 1) == 0? */", }, /* sh2e */ { "", "", "fmov <FREG_M>,<FREG_N>", "1111nnnnmmmm1100", /* sh4 */ "if (FPSCR_SZ) {", " int ni = XD_TO_XF (n);", " int mi = XD_TO_XF (m);", " SET_XF (ni + 0, XF (mi + 0));", " SET_XF (ni + 1, XF (mi + 1));", "}", "else", "{", " SET_FR (n, FR (m));", "}", }, /* sh2e */ { "", "n", "fmov.s <FREG_M>,@<REG_N>", "1111nnnnmmmm1010", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " WDAT (R[n], m);", "}", "else", "{", " MA (1);", " WLAT (R[n], FI (m));", "}", }, /* sh2e */ { "", "m", "fmov.s @<REG_M>,<FREG_N>", "1111nnnnmmmm1000", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " RDAT (R[m], n);", "}", "else", "{", " MA (1);", " SET_FI (n, RLAT (R[m]));", "}", }, /* sh2a */ { "", "n", "fmov.s @(disp12,<REG_N>), <FREG_M>", "0011nnnnmmmm0001", "/* and fmov.s <FREG_N>, @(disp12,<FREG_M>)", " and mov.bwl <REG_N>, @(disp12,<REG_M>)", " and mov.bwl @(disp12,<REG_N>),<REG_M>", " and movu.bw @(disp12,<REG_N>),<REG_M>. */", "int word2 = RIAT (nip);", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (nip + 2); /* Consume 2 more bytes. */", "MA (1);", "do_long_move_insn (word2 & 0xf000, word2 & 0x0fff, m, n, &thislock);", }, /* sh2e */ { "m", "m", "fmov.s @<REG_M>+,<FREG_N>", "1111nnnnmmmm1001", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " RDAT (R[m], n);", " R[m] += 8;", "}", "else", "{", " MA (1);", " SET_FI (n, RLAT (R[m]));", " R[m] += 4;", "}", }, /* sh2e */ { "n", "n", "fmov.s <FREG_M>,@-<REG_N>", "1111nnnnmmmm1011", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " R[n] -= 8;", " WDAT (R[n], m);", "}", "else", "{", " MA (1);", " R[n] -= 4;", " WLAT (R[n], FI (m));", "}", }, /* sh2e */ { "", "0m", "fmov.s @(R0,<REG_M>),<FREG_N>", "1111nnnnmmmm0110", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " RDAT (R[0]+R[m], n);", "}", "else", "{", " MA (1);", " SET_FI (n, RLAT (R[0] + R[m]));", "}", }, /* sh2e */ { "", "0n", "fmov.s <FREG_M>,@(R0,<REG_N>)", "1111nnnnmmmm0111", /* sh4 */ "if (FPSCR_SZ) {", " MA (2);", " WDAT (R[0]+R[n], m);", "}", "else", "{", " MA (1);", " WLAT ((R[0]+R[n]), FI (m));", "}", }, /* sh4: See fmov instructions above for move to/from extended fp registers. */ /* sh2e */ { "", "", "fmul <FREG_M>,<FREG_N>", "1111nnnnmmmm0010", "FP_OP (n, *, m);", }, /* sh2e */ { "", "", "fneg <FREG_N>", "1111nnnn01001101", " union", " {", " unsigned int i;", " float f;", " } u;", " u.f = FR (n);", " u.i ^= 0x80000000;", " SET_FR (n, u.f);", }, /* sh4a */ { "", "", "fpchg", "1111011111111101", "SET_FPSCR (GET_FPSCR () ^ FPSCR_MASK_PR);", }, /* sh4 */ { "", "", "frchg", "1111101111111101", "if (FPSCR_PR)", " RAISE_EXCEPTION (SIGILL);", "else if (saved_state.asregs.bfd_mach == bfd_mach_sh2a)", " RAISE_EXCEPTION (SIGILL);", "else", " SET_FPSCR (GET_FPSCR () ^ FPSCR_MASK_FR);", }, /* sh4 */ { "", "", "fsca", "1111eeee11111101", "if (FPSCR_PR)", " RAISE_EXCEPTION (SIGILL);", "else if (saved_state.asregs.bfd_mach == bfd_mach_sh2a)", " RAISE_EXCEPTION (SIGILL);", "else", " {", " SET_FR (n, fsca_s (FPUL, &sin));", " SET_FR (n+1, fsca_s (FPUL, &cos));", " }", }, /* sh4 */ { "", "", "fschg", "1111001111111101", "SET_FPSCR (GET_FPSCR () ^ FPSCR_MASK_SZ);", }, /* sh3e */ { "", "", "fsqrt <FREG_N>", "1111nnnn01101101", "FP_UNARY (n, sqrt);", }, /* sh4 */ { "", "", "fsrra <FREG_N>", "1111nnnn01111101", "if (FPSCR_PR)", " RAISE_EXCEPTION (SIGILL);", "else if (saved_state.asregs.bfd_mach == bfd_mach_sh2a)", " RAISE_EXCEPTION (SIGILL);", "else", " SET_FR (n, fsrra_s (FR (n)));", }, /* sh2e */ { "", "", "fsub <FREG_M>,<FREG_N>", "1111nnnnmmmm0001", "FP_OP (n, -, m);", }, /* sh2e */ { "", "", "ftrc <FREG_N>, FPUL", "1111nnnn00111101", /* sh4 */ "if (FPSCR_PR) {", " if (DR (n) != DR (n)) /* NaN */", " FPUL = 0x80000000;", " else", " FPUL = (int) DR (n);", "}", "else", "if (FR (n) != FR (n)) /* NaN */", " FPUL = 0x80000000;", "else", " FPUL = (int) FR (n);", }, /* sh4 */ { "", "", "ftrv <FV_N>", "1111vv0111111101", "if (FPSCR_PR)", " RAISE_EXCEPTION (SIGILL);", "else", "{", " if (saved_state.asregs.bfd_mach == bfd_mach_sh2a)", " RAISE_EXCEPTION (SIGILL);", " /* FIXME not implemented. */", " printf (\"ftrv xmtrx, FV%d\\n\", v1);", "}", }, /* sh2e */ { "", "", "fsts FPUL,<FREG_N>", "1111nnnn00001101", " union", " {", " int i;", " float f;", " } u;", " u.i = FPUL;", " SET_FR (n, u.f);", }, { "", "n", "jmp @<REG_N>", "0100nnnn00101011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (PT2H (R[n]));", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "n", "jsr @<REG_N>", "0100nnnn00001011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "PR = PH2T (PC + 4);", "if (~doprofile)", " gotcall (PR, R[n]);", "SET_NIP (PT2H (R[n]));", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "n", "jsr/n @<REG_N>", "0100nnnn01001011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "PR = PH2T (PC + 2);", "if (~doprofile)", " gotcall (PR, R[n]);", "SET_NIP (PT2H (R[n]));", }, { "", "", "jsr/n @@(<disp>,TBR)", "10000011i8p4....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "PR = PH2T (PC + 2);", "if (~doprofile)", " gotcall (PR, i + TBR);", "SET_NIP (PT2H (i + TBR));", }, { "", "n", "ldc <REG_N>,<CREG_M>", "0100nnnnmmmm1110", "CREG (m) = R[n];", "/* FIXME: user mode */", }, { "", "n", "ldc <REG_N>,SR", "0100nnnn00001110", "SET_SR (R[n]);", "/* FIXME: user mode */", }, { "", "n", "ldc <REG_N>,MOD", "0100nnnn01011110", "SET_MOD (R[n]);", }, { "", "n", "ldc <REG_N>,DBR", "0100nnnn11111010", "if (SR_MD)", " DBR = R[n]; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "", "n", "ldc <REG_N>,SGR", "0100nnnn00111010", "if (SR_MD)", " SGR = R[n]; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "", "n", "ldc <REG_N>,TBR", "0100nnnn01001010", "if (SR_MD)", /* FIXME? */ " TBR = R[n]; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "n", "ldc.l @<REG_N>+,<CREG_M>", "0100nnnnmmmm0111", "MA (1);", "CREG (m) = RLAT (R[n]);", "R[n] += 4;", "/* FIXME: user mode */", }, { "n", "n", "ldc.l @<REG_N>+,SR", "0100nnnn00000111", "MA (1);", "SET_SR (RLAT (R[n]));", "R[n] += 4;", "/* FIXME: user mode */", }, { "n", "n", "ldc.l @<REG_N>+,MOD", "0100nnnn01010111", "MA (1);", "SET_MOD (RLAT (R[n]));", "R[n] += 4;", }, { "n", "n", "ldc.l @<REG_N>+,DBR", "0100nnnn11110110", "if (SR_MD)", "{ /* priv mode */", " MA (1);", " DBR = RLAT (R[n]);", " R[n] += 4;", "}", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "n", "ldc.l @<REG_N>+,SGR", "0100nnnn00110110", "if (SR_MD)", "{ /* priv mode */", " MA (1);", " SGR = RLAT (R[n]);", " R[n] += 4;", "}", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, /* sh-dsp */ { "", "", "ldre @(<disp>,PC)", "10001110i8p1....", "RE = SEXT (i) * 2 + 4 + PH2T (PC);", }, { "", "", "ldrs @(<disp>,PC)", "10001100i8p1....", "RS = SEXT (i) * 2 + 4 + PH2T (PC);", }, /* sh4a */ { "", "n", "ldrc <REG_N>", "0100nnnn00110100", "SET_RC (R[n]);", "loop = get_loop_bounds_ext (RS, RE, memory, mem_end, maskw, endianw);", "CHECK_INSN_PTR (insn_ptr);", "RE |= 1;", }, { "", "", "ldrc #<imm>", "10001010i8*1....", "SET_RC (i);", "loop = get_loop_bounds_ext (RS, RE, memory, mem_end, maskw, endianw);", "CHECK_INSN_PTR (insn_ptr);", "RE |= 1;", }, { "", "n", "lds <REG_N>,<SREG_M>", "0100nnnnssss1010", "SREG (m) = R[n];", }, { "n", "n", "lds.l @<REG_N>+,<SREG_M>", "0100nnnnssss0110", "MA (1);", "SREG (m) = RLAT (R[n]);", "R[n] += 4;", }, /* sh2e / sh-dsp (lds <REG_N>,DSR) */ { "", "n", "lds <REG_N>,FPSCR", "0100nnnn01101010", "SET_FPSCR (R[n]);", }, /* sh2e / sh-dsp (lds.l @<REG_N>+,DSR) */ { "n", "n", "lds.l @<REG_N>+,FPSCR", "0100nnnn01100110", "MA (1);", "SET_FPSCR (RLAT (R[n]));", "R[n] += 4;", }, { "", "", "ldtlb", "0000000000111000", "/* We don't implement cache or tlb, so this is a noop. */", }, { "nm", "nm", "mac.l @<REG_M>+,@<REG_N>+", "0000nnnnmmmm1111", "macl (&R0, memory, n, m);", }, { "nm", "nm", "mac.w @<REG_M>+,@<REG_N>+", "0100nnnnmmmm1111", "macw (&R0, memory, n, m, endianw);", }, { "n", "", "mov #<imm>,<REG_N>", "1110nnnni8*1....", "R[n] = SEXT (i);", }, { "n", "", "movi20 #<imm20>,<REG_N>", "0000nnnni8*10000", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "R[n] = ((i << 24) >> 12) | RIAT (nip);", "SET_NIP (nip + 2); /* Consume 2 more bytes. */", }, { "n", "", "movi20s #<imm20>,<REG_N>", "0000nnnni8*10001", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "R[n] = ((((i & 0xf0) << 24) >> 12) | RIAT (nip)) << 8;", "SET_NIP (nip + 2); /* Consume 2 more bytes. */", }, { "n", "m", "mov <REG_M>,<REG_N>", "0110nnnnmmmm0011", "R[n] = R[m];", }, { "0", "", "mov.b @(<disp>,GBR),R0", "11000100i8*1....", "MA (1);", "R0 = RSBAT (i + GBR);", "L (0);", }, { "0", "m", "mov.b @(<disp>,<REG_M>),R0", "10000100mmmmi4*1", "MA (1);", "R0 = RSBAT (i + R[m]);", "L (0);", }, { "n", "0m", "mov.b @(R0,<REG_M>),<REG_N>", "0000nnnnmmmm1100", "MA (1);", "R[n] = RSBAT (R0 + R[m]);", "L (n);", }, { "nm", "m", "mov.b @<REG_M>+,<REG_N>", "0110nnnnmmmm0100", "MA (1);", "R[n] = RSBAT (R[m]);", "R[m] += 1;", "L (n);", }, { "0n", "n", "mov.b @-<REG_N>,R0", "0100nnnn11001011", "MA (1);", "R[n] -= 1;", "R0 = RSBAT (R[n]);", "L (0);", }, { "", "mn", "mov.b <REG_M>,@<REG_N>", "0010nnnnmmmm0000", "MA (1);", "WBAT (R[n], R[m]);", }, { "", "0", "mov.b R0,@(<disp>,GBR)", "11000000i8*1....", "MA (1);", "WBAT (i + GBR, R0);", }, { "", "m0", "mov.b R0,@(<disp>,<REG_M>)", "10000000mmmmi4*1", "MA (1);", "WBAT (i + R[m], R0);", }, { "", "mn0", "mov.b <REG_M>,@(R0,<REG_N>)", "0000nnnnmmmm0100", "MA (1);", "WBAT (R[n] + R0, R[m]);", }, { "n", "nm", "mov.b <REG_M>,@-<REG_N>", "0010nnnnmmmm0100", /* Allow for the case where m == n. */ "int t = R[m];", "MA (1);", "R[n] -= 1;", "WBAT (R[n], t);", }, { "n", "n0", "mov.b R0,@<REG_N>+", "0100nnnn10001011", "MA (1);", "WBAT (R[n], R0);", "R[n] += 1;", }, { "n", "m", "mov.b @<REG_M>,<REG_N>", "0110nnnnmmmm0000", "MA (1);", "R[n] = RSBAT (R[m]);", "L (n);", }, { "0", "", "mov.l @(<disp>,GBR),R0", "11000110i8*4....", "MA (1);", "R0 = RLAT (i + GBR);", "L (0);", }, { "n", "", "mov.l @(<disp>,PC),<REG_N>", "1101nnnni8p4....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "MA (1);", "R[n] = RLAT ((PH2T (PC) & ~3) + 4 + i);", "L (n);", }, { "n", "m", "mov.l @(<disp>,<REG_M>),<REG_N>", "0101nnnnmmmmi4*4", "MA (1);", "R[n] = RLAT (i + R[m]);", "L (n);", }, { "n", "m0", "mov.l @(R0,<REG_M>),<REG_N>", "0000nnnnmmmm1110", "MA (1);", "R[n] = RLAT (R0 + R[m]);", "L (n);", }, { "nm", "m", "mov.l @<REG_M>+,<REG_N>", "0110nnnnmmmm0110", "MA (1);", "R[n] = RLAT (R[m]);", "R[m] += 4;", "L (n);", }, { "0n", "n", "mov.l @-<REG_N>,R0", "0100nnnn11101011", "MA (1);", "R[n] -= 4;", "R0 = RLAT (R[n]);", "L (0);", }, { "n", "m", "mov.l @<REG_M>,<REG_N>", "0110nnnnmmmm0010", "MA (1);", "R[n] = RLAT (R[m]);", "L (n);", }, { "", "0", "mov.l R0,@(<disp>,GBR)", "11000010i8*4....", "MA (1);", "WLAT (i + GBR, R0);", }, { "", "nm", "mov.l <REG_M>,@(<disp>,<REG_N>)", "0001nnnnmmmmi4*4", "MA (1);", "WLAT (i + R[n], R[m]);", }, { "", "nm0", "mov.l <REG_M>,@(R0,<REG_N>)", "0000nnnnmmmm0110", "MA (1);", "WLAT (R0 + R[n], R[m]);", }, { "n", "nm", "mov.l <REG_M>,@-<REG_N>", "0010nnnnmmmm0110", /* Allow for the case where m == n. */ "int t = R[m];", "MA (1) ;", "R[n] -= 4;", "WLAT (R[n], t);", }, { "n", "n0", "mov.l R0,@<REG_N>+", "0100nnnn10101011", "MA (1) ;", "WLAT (R[n], R0);", "R[n] += 4;", }, { "", "nm", "mov.l <REG_M>,@<REG_N>", "0010nnnnmmmm0010", "MA (1);", "WLAT (R[n], R[m]);", }, { "0", "", "mov.w @(<disp>,GBR),R0", "11000101i8*2....", "MA (1);", "R0 = RSWAT (i + GBR);", "L (0);", }, { "n", "", "mov.w @(<disp>,PC),<REG_N>", "1001nnnni8p2....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "MA (1);", "R[n] = RSWAT (PH2T (PC + 4 + i));", "L (n);", }, { "0", "m", "mov.w @(<disp>,<REG_M>),R0", "10000101mmmmi4*2", "MA (1);", "R0 = RSWAT (i + R[m]);", "L (0);", }, { "n", "m0", "mov.w @(R0,<REG_M>),<REG_N>", "0000nnnnmmmm1101", "MA (1);", "R[n] = RSWAT (R0 + R[m]);", "L (n);", }, { "nm", "n", "mov.w @<REG_M>+,<REG_N>", "0110nnnnmmmm0101", "MA (1);", "R[n] = RSWAT (R[m]);", "R[m] += 2;", "L (n);", }, { "0n", "n", "mov.w @-<REG_N>,R0", "0100nnnn11011011", "MA (1);", "R[n] -= 2;", "R0 = RSWAT (R[n]);", "L (0);", }, { "n", "m", "mov.w @<REG_M>,<REG_N>", "0110nnnnmmmm0001", "MA (1);", "R[n] = RSWAT (R[m]);", "L (n);", }, { "", "0", "mov.w R0,@(<disp>,GBR)", "11000001i8*2....", "MA (1);", "WWAT (i + GBR, R0);", }, { "", "0m", "mov.w R0,@(<disp>,<REG_M>)", "10000001mmmmi4*2", "MA (1);", "WWAT (i + R[m], R0);", }, { "", "m0n", "mov.w <REG_M>,@(R0,<REG_N>)", "0000nnnnmmmm0101", "MA (1);", "WWAT (R0 + R[n], R[m]);", }, { "n", "mn", "mov.w <REG_M>,@-<REG_N>", "0010nnnnmmmm0101", /* Allow for the case where m == n. */ "int t = R[m];", "MA (1);", "R[n] -= 2;", "WWAT (R[n], t);", }, { "n", "0n", "mov.w R0,@<REG_N>+", "0100nnnn10011011", "MA (1);", "WWAT (R[n], R0);", "R[n] += 2;", }, { "", "nm", "mov.w <REG_M>,@<REG_N>", "0010nnnnmmmm0001", "MA (1);", "WWAT (R[n], R[m]);", }, { "0", "", "mova @(<disp>,PC),R0", "11000111i8p4....", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "R0 = ((i + 4 + PH2T (PC)) & ~0x3);", }, { "", "n0", "movca.l R0, @<REG_N>", "0000nnnn11000011", "/* We don't simulate cache, so this insn is identical to mov. */", "MA (1);", "WLAT (R[n], R[0]);", }, { "", "n0", "movco.l R0, @<REG_N>", "0000nnnn01110011", "/* LDST -> T */", "SET_SR_T (LDST);", "/* if (T) R0 -> (Rn) */", "if (T)", " WLAT (R[n], R[0]);", "/* 0 -> LDST */", "SET_LDST (0);", }, { "0", "n", "movli.l @<REG_N>, R0", "0000nnnn01100011", "/* 1 -> LDST */", "SET_LDST (1);", "/* (Rn) -> R0 */", "R[0] = RLAT (R[n]);", "/* if (interrupt/exception) 0 -> LDST */", "/* (we don't simulate asynchronous interrupts/exceptions) */", }, { "n", "", "movt <REG_N>", "0000nnnn00101001", "R[n] = T;", }, { "", "", "movrt <REG_N>", "0000nnnn00111001", "R[n] = (T == 0);", }, { "0", "n", "movua.l @<REG_N>,R0", "0100nnnn10101001", "int regn = R[n];", "int e = target_little_endian ? 3 : 0;", "MA (1);", "R[0] = (RBAT (regn + (0^e)) << 24) + (RBAT (regn + (1^e)) << 16) + ", " (RBAT (regn + (2^e)) << 8) + RBAT (regn + (3^e));", "L (0);", }, { "0n", "n", "movua.l @<REG_N>+,R0", "0100nnnn11101001", "int regn = R[n];", "int e = target_little_endian ? 3 : 0;", "MA (1);", "R[0] = (RBAT (regn + (0^e)) << 24) + (RBAT (regn + (1^e)) << 16) + ", " (RBAT (regn + (2^e)) << 8) + RBAT (regn + (3^e));", "R[n] += 4;", "L (0);", }, { "", "mn", "mul.l <REG_M>,<REG_N>", "0000nnnnmmmm0111", "MACL = ((int) R[n]) * ((int) R[m]);", }, #if 0 /* FIXME: The above cast to int is not really portable. It should be replaced by a SEXT32 macro. */ { "", "nm", "mul.l <REG_M>,<REG_N>", "0000nnnnmmmm0111", "MACL = R[n] * R[m];", }, #endif /* muls.w - see muls */ { "", "mn", "muls <REG_M>,<REG_N>", "0010nnnnmmmm1111", "MACL = ((int) (short) R[n]) * ((int) (short) R[m]);", }, /* mulu.w - see mulu */ { "", "mn", "mulu <REG_M>,<REG_N>", "0010nnnnmmmm1110", "MACL = (((unsigned int) (unsigned short) R[n])", " * ((unsigned int) (unsigned short) R[m]));", }, { "n", "m", "neg <REG_M>,<REG_N>", "0110nnnnmmmm1011", "R[n] = - R[m];", }, { "n", "m", "negc <REG_M>,<REG_N>", "0110nnnnmmmm1010", "ult = -T;", "SET_SR_T (ult > 0);", "R[n] = ult - R[m];", "SET_SR_T (T || (R[n] > ult));", }, { "", "", "nop", "0000000000001001", "/* nop */", }, { "n", "m", "not <REG_M>,<REG_N>", "0110nnnnmmmm0111", "R[n] = ~R[m];", }, /* sh4a */ { "", "n", "icbi @<REG_N>", "0000nnnn11100011", "/* Except for the effect on the cache - which is not simulated -", " this is like a nop. */", }, { "", "n", "ocbi @<REG_N>", "0000nnnn10010011", "RSBAT (R[n]); /* Take exceptions like byte load, otherwise noop. */", "/* FIXME: Cache not implemented */", }, { "", "n", "ocbp @<REG_N>", "0000nnnn10100011", "RSBAT (R[n]); /* Take exceptions like byte load, otherwise noop. */", "/* FIXME: Cache not implemented */", }, { "", "n", "ocbwb @<REG_N>", "0000nnnn10110011", "RSBAT (R[n]); /* Take exceptions like byte load, otherwise noop. */", "/* FIXME: Cache not implemented */", }, { "0", "", "or #<imm>,R0", "11001011i8*1....", "R0 |= i;", }, { "n", "m", "or <REG_M>,<REG_N>", "0010nnnnmmmm1011", "R[n] |= R[m];", }, { "", "0", "or.b #<imm>,@(R0,GBR)", "11001111i8*1....", "MA (1);", "WBAT (R0 + GBR, (RBAT (R0 + GBR) | i));", }, { "", "n", "pref @<REG_N>", "0000nnnn10000011", "/* Except for the effect on the cache - which is not simulated -", " this is like a nop. */", }, /* sh4a */ { "", "n", "prefi @<REG_N>", "0000nnnn11010011", "/* Except for the effect on the cache - which is not simulated -", " this is like a nop. */", }, /* sh4a */ { "", "", "synco", "0000000010101011", "/* Except for the effect on the pipeline - which is not simulated -", " this is like a nop. */", }, { "n", "n", "rotcl <REG_N>", "0100nnnn00100100", "ult = R[n] < 0;", "R[n] = (R[n] << 1) | T;", "SET_SR_T (ult);", }, { "n", "n", "rotcr <REG_N>", "0100nnnn00100101", "ult = R[n] & 1;", "R[n] = (UR[n] >> 1) | (T << 31);", "SET_SR_T (ult);", }, { "n", "n", "rotl <REG_N>", "0100nnnn00000100", "SET_SR_T (R[n] < 0);", "R[n] <<= 1;", "R[n] |= T;", }, { "n", "n", "rotr <REG_N>", "0100nnnn00000101", "SET_SR_T (R[n] & 1);", "R[n] = UR[n] >> 1;", "R[n] |= (T << 31);", }, { "", "", "rte", "0000000000101011", #if 0 /* SH-[12] */ "int tmp = PC;", "SET_NIP (PT2H (RLAT (R[15]) + 2));", "R[15] += 4;", "SET_SR (RLAT (R[15]) & 0x3f3);", "R[15] += 4;", "Delay_Slot (PC + 2);", #else "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_SR (SSR);", "SET_NIP (PT2H (SPC));", "cycles += 2;", "Delay_Slot (PC + 2);", #endif }, { "", "", "rts", "0000000000001011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (PT2H (PR));", "cycles += 2;", "Delay_Slot (PC + 2);", }, { "", "", "rts/n", "0000000001101011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "SET_NIP (PT2H (PR));", }, { "0", "n", "rtv/n <REG_N>", "0000nnnn01111011", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "R0 = R[n];", "L (0);", "SET_NIP (PT2H (PR));", }, /* sh4a */ { "", "", "setdmx", "0000000010011000", "saved_state.asregs.cregs.named.sr |= SR_MASK_DMX;" "saved_state.asregs.cregs.named.sr &= ~SR_MASK_DMY;" }, /* sh4a */ { "", "", "setdmy", "0000000011001000", "saved_state.asregs.cregs.named.sr |= SR_MASK_DMY;" "saved_state.asregs.cregs.named.sr &= ~SR_MASK_DMX;" }, /* sh-dsp */ { "", "n", "setrc <REG_N>", "0100nnnn00010100", "SET_RC (R[n]);", }, { "", "", "setrc #<imm>", "10000010i8*1....", /* It would be more realistic to let loop_start point to some static memory that contains an illegal opcode and then give a bus error when the loop is eventually encountered, but it seems not only simpler, but also more debugging-friendly to just catch the failure here. */ "if (BUSERROR (RS | RE, maskw))", " RAISE_EXCEPTION (SIGILL);", "else {", " SET_RC (i);", " loop = get_loop_bounds (RS, RE, memory, mem_end, maskw, endianw);", " CHECK_INSN_PTR (insn_ptr);", "}", }, { "", "", "sets", "0000000001011000", "SET_SR_S (1);", }, { "", "", "sett", "0000000000011000", "SET_SR_T (1);", }, { "n", "mn", "shad <REG_M>,<REG_N>", "0100nnnnmmmm1100", "R[n] = (R[m] < 0) ? (R[m]&0x1f ? R[n] >> ((-R[m])&0x1f) : R[n] >> 31) : (R[n] << (R[m] & 0x1f));", }, { "n", "n", "shal <REG_N>", "0100nnnn00100000", "SET_SR_T (R[n] < 0);", "R[n] <<= 1;", }, { "n", "n", "shar <REG_N>", "0100nnnn00100001", "SET_SR_T (R[n] & 1);", "R[n] = R[n] >> 1;", }, { "n", "mn", "shld <REG_M>,<REG_N>", "0100nnnnmmmm1101", "R[n] = (R[m] < 0) ? (R[m]&0x1f ? UR[n] >> ((-R[m])&0x1f) : 0): (R[n] << (R[m] & 0x1f));", }, { "n", "n", "shll <REG_N>", "0100nnnn00000000", "SET_SR_T (R[n] < 0);", "R[n] <<= 1;", }, { "n", "n", "shll2 <REG_N>", "0100nnnn00001000", "R[n] <<= 2;", }, { "n", "n", "shll8 <REG_N>", "0100nnnn00011000", "R[n] <<= 8;", }, { "n", "n", "shll16 <REG_N>", "0100nnnn00101000", "R[n] <<= 16;", }, { "n", "n", "shlr <REG_N>", "0100nnnn00000001", "SET_SR_T (R[n] & 1);", "R[n] = UR[n] >> 1;", }, { "n", "n", "shlr2 <REG_N>", "0100nnnn00001001", "R[n] = UR[n] >> 2;", }, { "n", "n", "shlr8 <REG_N>", "0100nnnn00011001", "R[n] = UR[n] >> 8;", }, { "n", "n", "shlr16 <REG_N>", "0100nnnn00101001", "R[n] = UR[n] >> 16;", }, { "", "", "sleep", "0000000000011011", "nip += trap (0xc3, &R0, PC, memory, maskl, maskw, endianw);", }, { "n", "", "stc <CREG_M>,<REG_N>", "0000nnnnmmmm0010", "R[n] = CREG (m);", }, { "n", "", "stc SGR,<REG_N>", "0000nnnn00111010", "if (SR_MD)", " R[n] = SGR; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "", "stc DBR,<REG_N>", "0000nnnn11111010", "if (SR_MD)", " R[n] = DBR; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "", "stc TBR,<REG_N>", "0000nnnn01001010", "if (SR_MD)", /* FIXME? */ " R[n] = TBR; /* priv mode */", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "n", "stc.l <CREG_M>,@-<REG_N>", "0100nnnnmmmm0011", "MA (1);", "R[n] -= 4;", "WLAT (R[n], CREG (m));", }, { "n", "n", "stc.l SGR,@-<REG_N>", "0100nnnn00110010", "if (SR_MD)", "{ /* priv mode */", " MA (1);", " R[n] -= 4;", " WLAT (R[n], SGR);", "}", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "n", "stc.l DBR,@-<REG_N>", "0100nnnn11110010", "if (SR_MD)", "{ /* priv mode */", " MA (1);", " R[n] -= 4;", " WLAT (R[n], DBR);", "}", "else", " RAISE_EXCEPTION (SIGILL); /* user mode */", }, { "n", "", "sts <SREG_M>,<REG_N>", "0000nnnnssss1010", "R[n] = SREG (m);", }, { "n", "n", "sts.l <SREG_M>,@-<REG_N>", "0100nnnnssss0010", "MA (1);", "R[n] -= 4;", "WLAT (R[n], SREG (m));", }, { "n", "nm", "sub <REG_M>,<REG_N>", "0011nnnnmmmm1000", "R[n] -= R[m];", }, { "n", "nm", "subc <REG_M>,<REG_N>", "0011nnnnmmmm1010", "ult = R[n] - T;", "SET_SR_T (ult > R[n]);", "R[n] = ult - R[m];", "SET_SR_T (T || (R[n] > ult));", }, { "n", "nm", "subv <REG_M>,<REG_N>", "0011nnnnmmmm1011", "ult = R[n] - R[m];", "SET_SR_T (((R[n] ^ R[m]) & (ult ^ R[n])) >> 31);", "R[n] = ult;", }, { "n", "nm", "swap.b <REG_M>,<REG_N>", "0110nnnnmmmm1000", "R[n] = ((R[m] & 0xffff0000)", " | ((R[m] << 8) & 0xff00)", " | ((R[m] >> 8) & 0x00ff));", }, { "n", "nm", "swap.w <REG_M>,<REG_N>", "0110nnnnmmmm1001", "R[n] = (((R[m] << 16) & 0xffff0000)", " | ((R[m] >> 16) & 0x00ffff));", }, { "", "n", "tas.b @<REG_N>", "0100nnnn00011011", "MA (1);", "ult = RBAT (R[n]);", "SET_SR_T (ult == 0);", "WBAT (R[n],ult|0x80);", }, { "0", "", "trapa #<imm>", "11000011i8*1....", "long imm = 0xff & i;", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "if (i < 20 || i == 33 || i == 34 || i == 0xc3)", " nip += trap (i, &R0, PC, memory, maskl, maskw, endianw);", #if 0 "else {", /* SH-[12] */ " R[15] -= 4;", " WLAT (R[15], GET_SR ());", " R[15] -= 4;", " WLAT (R[15], PH2T (PC + 2));", #else "else if (!SR_BL) {", " SSR = GET_SR ();", " SPC = PH2T (PC + 2);", " SET_SR (GET_SR () | SR_MASK_MD | SR_MASK_BL | SR_MASK_RB);", " /* FIXME: EXPEVT = 0x00000160; */", #endif " SET_NIP (PT2H (RLAT (VBR + (imm<<2))));", "}", }, { "", "mn", "tst <REG_M>,<REG_N>", "0010nnnnmmmm1000", "SET_SR_T ((R[n] & R[m]) == 0);", }, { "", "0", "tst #<imm>,R0", "11001000i8*1....", "SET_SR_T ((R0 & i) == 0);", }, { "", "0", "tst.b #<imm>,@(R0,GBR)", "11001100i8*1....", "MA (1);", "SET_SR_T ((RBAT (GBR+R0) & i) == 0);", }, { "", "0", "xor #<imm>,R0", "11001010i8*1....", "R0 ^= i;", }, { "n", "mn", "xor <REG_M>,<REG_N>", "0010nnnnmmmm1010", "R[n] ^= R[m];", }, { "", "0", "xor.b #<imm>,@(R0,GBR)", "11001110i8*1....", "MA (1);", "ult = RBAT (GBR+R0);", "ult ^= i;", "WBAT (GBR + R0, ult);", }, { "n", "nm", "xtrct <REG_M>,<REG_N>", "0010nnnnmmmm1101", "R[n] = (((R[n] >> 16) & 0xffff)", " | ((R[m] << 16) & 0xffff0000));", }, #if 0 { "divs.l <REG_M>,<REG_N>", "0100nnnnmmmm1110", "divl (0, R[n], R[m]);", }, { "divu.l <REG_M>,<REG_N>", "0100nnnnmmmm1101", "divl (0, R[n], R[m]);", }, #endif {0, 0}}; op movsxy_tab[] = { /* If this is disabled, the simulator speeds up by about 12% on a 450 MHz PIII - 9% with ACE_FAST. Maybe we should have separate simulator loops? */ #if 1 { "n", "n", "movs.w @-<REG_N>,<DSP_REG_M>", "111101NNMMMM0000", "MA (1);", "R[n] -= 2;", "DSP_R (m) = RSWAT (R[n]) << 16;", "DSP_GRD (m) = SIGN32 (DSP_R (m));", }, { "", "n", "movs.w @<REG_N>,<DSP_REG_M>", "111101NNMMMM0100", "MA (1);", "DSP_R (m) = RSWAT (R[n]) << 16;", "DSP_GRD (m) = SIGN32 (DSP_R (m));", }, { "n", "n", "movs.w @<REG_N>+,<DSP_REG_M>", "111101NNMMMM1000", "MA (1);", "DSP_R (m) = RSWAT (R[n]) << 16;", "DSP_GRD (m) = SIGN32 (DSP_R (m));", "R[n] += 2;", }, { "n", "n8","movs.w @<REG_N>+REG_8,<DSP_REG_M>", "111101NNMMMM1100", "MA (1);", "DSP_R (m) = RSWAT (R[n]) << 16;", "DSP_GRD (m) = SIGN32 (DSP_R (m));", "R[n] += R[8];", }, { "n", "n", "movs.w @-<REG_N>,<DSP_GRD_M>", "111101NNGGGG0000", "MA (1);", "R[n] -= 2;", "DSP_R (m) = RSWAT (R[n]);", }, { "", "n", "movs.w @<REG_N>,<DSP_GRD_M>", "111101NNGGGG0100", "MA (1);", "DSP_R (m) = RSWAT (R[n]);", }, { "n", "n", "movs.w @<REG_N>+,<DSP_GRD_M>", "111101NNGGGG1000", "MA (1);", "DSP_R (m) = RSWAT (R[n]);", "R[n] += 2;", }, { "n", "n8","movs.w @<REG_N>+REG_8,<DSP_GRD_M>", "111101NNGGGG1100", "MA (1);", "DSP_R (m) = RSWAT (R[n]);", "R[n] += R[8];", }, { "n", "n", "movs.w <DSP_REG_M>,@-<REG_N>", "111101NNMMMM0001", "MA (1);", "R[n] -= 2;", "WWAT (R[n], DSP_R (m) >> 16);", }, { "", "n", "movs.w <DSP_REG_M>,@<REG_N>", "111101NNMMMM0101", "MA (1);", "WWAT (R[n], DSP_R (m) >> 16);", }, { "n", "n", "movs.w <DSP_REG_M>,@<REG_N>+", "111101NNMMMM1001", "MA (1);", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += 2;", }, { "n", "n8","movs.w <DSP_REG_M>,@<REG_N>+REG_8", "111101NNMMMM1101", "MA (1);", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += R[8];", }, { "n", "n", "movs.w <DSP_GRD_M>,@-<REG_N>", "111101NNGGGG0001", "MA (1);", "R[n] -= 2;", "WWAT (R[n], SEXT (DSP_R (m)));", }, { "", "n", "movs.w <DSP_GRD_M>,@<REG_N>", "111101NNGGGG0101", "MA (1);", "WWAT (R[n], SEXT (DSP_R (m)));", }, { "n", "n", "movs.w <DSP_GRD_M>,@<REG_N>+", "111101NNGGGG1001", "MA (1);", "WWAT (R[n], SEXT (DSP_R (m)));", "R[n] += 2;", }, { "n", "n8","movs.w <DSP_GRD_M>,@<REG_N>+REG_8", "111101NNGGGG1101", "MA (1);", "WWAT (R[n], SEXT (DSP_R (m)));", "R[n] += R[8];", }, { "n", "n", "movs.l @-<REG_N>,<DSP_REG_M>", "111101NNMMMM0010", "MA (1);", "R[n] -= 4;", "DSP_R (m) = RLAT (R[n]);", "DSP_GRD (m) = SIGN32 (DSP_R (m));", }, { "", "n", "movs.l @<REG_N>,<DSP_REG_M>", "111101NNMMMM0110", "MA (1);", "DSP_R (m) = RLAT (R[n]);", "DSP_GRD (m) = SIGN32 (DSP_R (m));", }, { "n", "n", "movs.l @<REG_N>+,<DSP_REG_M>", "111101NNMMMM1010", "MA (1);", "DSP_R (m) = RLAT (R[n]);", "DSP_GRD (m) = SIGN32 (DSP_R (m));", "R[n] += 4;", }, { "n", "n8","movs.l @<REG_N>+REG_8,<DSP_REG_M>", "111101NNMMMM1110", "MA (1);", "DSP_R (m) = RLAT (R[n]);", "DSP_GRD (m) = SIGN32 (DSP_R (m));", "R[n] += R[8];", }, { "n", "n", "movs.l <DSP_REG_M>,@-<REG_N>", "111101NNMMMM0011", "MA (1);", "R[n] -= 4;", "WLAT (R[n], DSP_R (m));", }, { "", "n", "movs.l <DSP_REG_M>,@<REG_N>", "111101NNMMMM0111", "MA (1);", "WLAT (R[n], DSP_R (m));", }, { "n", "n", "movs.l <DSP_REG_M>,@<REG_N>+", "111101NNMMMM1011", "MA (1);", "WLAT (R[n], DSP_R (m));", "R[n] += 4;", }, { "n", "n8","movs.l <DSP_REG_M>,@<REG_N>+REG_8", "111101NNMMMM1111", "MA (1);", "WLAT (R[n], DSP_R (m));", "R[n] += R[8];", }, { "n", "n", "movs.l <DSP_GRD_M>,@-<REG_N>", "111101NNGGGG0011", "MA (1);", "R[n] -= 4;", "WLAT (R[n], SEXT (DSP_R (m)));", }, { "", "n", "movs.l <DSP_GRD_M>,@<REG_N>", "111101NNGGGG0111", "MA (1);", "WLAT (R[n], SEXT (DSP_R (m)));", }, { "n", "n", "movs.l <DSP_GRD_M>,@<REG_N>+", "111101NNGGGG1011", "MA (1);", "WLAT (R[n], SEXT (DSP_R (m)));", "R[n] += 4;", }, { "n", "n8","movs.l <DSP_GRD_M>,@<REG_N>+REG_8", "111101NNGGGG1111", "MA (1);", "WLAT (R[n], SEXT (DSP_R (m)));", "R[n] += R[8];", }, { "", "n", "movx.w @<REG_xy>,<DSP_XY>", "111100xyXY0001??", "DSP_R (m) = RSWAT (R[n]) << 16;", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "", "n", "movx.l @<REG_xy>,<DSP_XY>", "111100xyXY010100", "DSP_R (m) = RLAT (R[n]);", }, { "n", "n", "movx.w @<REG_xy>+,<DSP_XY>", "111100xyXY0010??", "DSP_R (m) = RSWAT (R[n]) << 16;", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : 2;", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "n", "n", "movx.l @<REG_xy>+,<DSP_XY>", "111100xyXY011000", "DSP_R (m) = RLAT (R[n]);", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : 4;", }, { "n", "n8","movx.w @<REG_xy>+REG_8,<DSP_XY>", "111100xyXY0011??", "DSP_R (m) = RSWAT (R[n]) << 16;", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : R[8];", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "n", "n8","movx.l @<REG_xy>+REG_8,<DSP_XY>", "111100xyXY011100", "DSP_R (m) = RLAT (R[n]);", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : R[8];", }, { "", "n", "movx.w <DSP_Ax>,@<REG_xy>", "111100xyax1001??", "WWAT (R[n], DSP_R (m) >> 16);", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "", "n", "movx.l <DSP_Ax>,@<REG_xy>", "111100xyax110100", "WLAT (R[n], DSP_R (m));", }, { "n", "n", "movx.w <DSP_Ax>,@<REG_xy>+", "111100xyax1010??", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : 2;", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "n", "n", "movx.l <DSP_Ax>,@<REG_xy>+", "111100xyax111000", "WLAT (R[n], DSP_R (m));", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : 4;", }, { "n", "n8","movx.w <DSP_Ax>,@<REG_xy>+REG_8","111100xyax1011??", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : R[8];", "if (iword & 3)", " {", " iword &= 0xfd53; goto top;", " }", }, { "n", "n8","movx.l <DSP_Ax>,@<REG_xy>+REG_8","111100xyax111100", "WLAT (R[n], DSP_R (m));", "R[n] += ((R[n] & 0xffff) == MOD_ME) ? MOD_DELTA : R[8];", }, { "", "n", "movy.w @<REG_yx>,<DSP_YX>", "111100yxYX000001", "DSP_R (m) = RSWAT (R[n]) << 16;", }, { "n", "n", "movy.w @<REG_yx>+,<DSP_YX>", "111100yxYX000010", "DSP_R (m) = RSWAT (R[n]) << 16;", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : 2;", }, { "n", "n9","movy.w @<REG_yx>+REG_9,<DSP_YX>", "111100yxYX000011", "DSP_R (m) = RSWAT (R[n]) << 16;", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : R[9];", }, { "", "n", "movy.w <DSP_Ay>,@<REG_yx>", "111100yxAY010001", "WWAT (R[n], DSP_R (m) >> 16);", }, { "n", "n", "movy.w <DSP_Ay>,@<REG_yx>+", "111100yxAY010010", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : 2;", }, { "n", "n9", "movy.w <DSP_Ay>,@<REG_yx>+REG_9", "111100yxAY010011", "WWAT (R[n], DSP_R (m) >> 16);", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : R[9];", }, { "", "n", "movy.l @<REG_yx>,<DSP_YX>", "111100yxYX100001", "DSP_R (m) = RLAT (R[n]);", }, { "n", "n", "movy.l @<REG_yx>+,<DSP_YX>", "111100yxYX100010", "DSP_R (m) = RLAT (R[n]);", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : 4;", }, { "n", "n9","movy.l @<REG_yx>+REG_9,<DSP_YX>", "111100yxYX100011", "DSP_R (m) = RLAT (R[n]);", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : R[9];", }, { "", "n", "movy.l <DSP_Ay>,@<REG_yx>", "111100yxAY110001", "WLAT (R[n], DSP_R (m));", }, { "n", "n", "movy.l <DSP_Ay>,@<REG_yx>+", "111100yxAY110010", "WLAT (R[n], DSP_R (m));", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : 4;", }, { "n", "n9", "movy.l <DSP_Ay>,@<REG_yx>+REG_9", "111100yxAY110011", "WLAT (R[n], DSP_R (m));", "R[n] += ((R[n] | ~0xffff) == MOD_ME) ? MOD_DELTA : R[9];", }, { "", "", "nopx nopy", "1111000000000000", "/* nop */", }, { "", "", "ppi", "1111100000000000", "RAISE_EXCEPTION_IF_IN_DELAY_SLOT ();", "ppi_insn (RIAT (nip));", "SET_NIP (nip + 2);", "iword &= 0xf7ff; goto top;", }, #endif {0, 0}}; op ppi_tab[] = { { "","", "pshl #<imm>,dz", "00000iiim16.zzzz", "int Sz = DSP_R (z) & 0xffff0000;", "", "if (i <= 16)", " res = Sz << i;", "else if (i >= 128 - 16)", " res = (unsigned) Sz >> 128 - i; /* no sign extension */", "else", " {", " RAISE_EXCEPTION (SIGILL);", " return;", " }", "res &= 0xffff0000;", "res_grd = 0;", "goto logical;", }, { "","", "psha #<imm>,dz", "00010iiim32.zzzz", "int Sz = DSP_R (z);", "int Sz_grd = GET_DSP_GRD (z);", "", "if (i <= 32)", " {", " if (i == 32)", " {", " res = 0;", " res_grd = Sz;", " }", " else", " {", " res = Sz << i;", " res_grd = Sz_grd << i | (unsigned) Sz >> 32 - i;", " }", " res_grd = SEXT (res_grd);", " carry = res_grd & 1;", " }", "else if (i >= 96)", " {", " i = 128 - i;", " if (i == 32)", " {", " res_grd = SIGN32 (Sz_grd);", " res = Sz_grd;", " }", " else", " {", " res = Sz >> i | Sz_grd << 32 - i;", " res_grd = Sz_grd >> i;", " }", " carry = Sz >> (i - 1) & 1;", " }", "else", " {", " RAISE_EXCEPTION (SIGILL);", " return;", " }", "COMPUTE_OVERFLOW;", "greater_equal = 0;", }, { "","", "pmuls Se,Sf,Dg", "0100eeffxxyygguu", "res = (DSP_R (e) >> 16) * (DSP_R (f) >> 16) * 2;", "if (res == 0x80000000)", " res = 0x7fffffff;", "DSP_R (g) = res;", "DSP_GRD (g) = SIGN32 (res);", "return;", }, { "","", "psub Sx,Sy,Du pmuls Se,Sf,Dg", "0110eeffxxyygguu", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = (DSP_R (e) >> 16) * (DSP_R (f) >> 16) * 2;", "if (res == 0x80000000)", " res = 0x7fffffff;", "DSP_R (g) = res;", "DSP_GRD (g) = SIGN32 (res);", "", "z = u;", "res = Sx - Sy;", "carry = (unsigned) res > (unsigned) Sx;", "res_grd = Sx_grd - Sy_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "padd Sx,Sy,Du pmuls Se,Sf,Dg", "0111eeffxxyygguu", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = (DSP_R (e) >> 16) * (DSP_R (f) >> 16) * 2;", "if (res == 0x80000000)", " res = 0x7fffffff;", "DSP_R (g) = res;", "DSP_GRD (g) = SIGN32 (res);", "", "z = u;", "res = Sx + Sy;", "carry = (unsigned) res < (unsigned) Sx;", "res_grd = Sx_grd + Sy_grd + carry;", "COMPUTE_OVERFLOW;", }, { "","", "psubc Sx,Sy,Dz", "10100000xxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sx - Sy - (DSR & 1);", "carry = (unsigned) res > (unsigned) Sx || (res == Sx && Sy);", "res_grd = Sx_grd + Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "DSR &= ~0xf1;\n", "if (res || res_grd)\n", " DSR |= greater_equal | res_grd >> 2 & DSR_MASK_N | overflow;\n", "else\n", " DSR |= DSR_MASK_Z | overflow;\n", "DSR |= carry;\n", "goto assign_z;\n", }, { "","", "paddc Sx,Sy,Dz", "10110000xxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sx + Sy + (DSR & 1);", "carry = (unsigned) res < (unsigned) Sx || (res == Sx && Sy);", "res_grd = Sx_grd + Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "DSR &= ~0xf1;\n", "if (res || res_grd)\n", " DSR |= greater_equal | res_grd >> 2 & DSR_MASK_N | overflow;\n", "else\n", " DSR |= DSR_MASK_Z | overflow;\n", "DSR |= carry;\n", "goto assign_z;\n", }, { "","", "pcmp Sx,Sy", "10000100xxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "z = 17; /* Ignore result. */", "res = Sx - Sy;", "carry = (unsigned) res > (unsigned) Sx;", "res_grd = Sx_grd - Sy_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "pwsb Sx,Sy,Dz", "10100100xxyyzzzz", }, { "","", "pwad Sx,Sy,Dz", "10110100xxyyzzzz", }, { "","", "(if cc) pabs Sx,Dz", "100010ccxx01zzzz", "/* FIXME: duplicate code pabs. */", "res = DSP_R (x);", "res_grd = GET_DSP_GRD (x);", "if (res >= 0)", " carry = 0;", "else", " {", " res = -res;", " carry = (res != 0); /* The manual has a bug here. */", " res_grd = -res_grd - carry;", " }", "COMPUTE_OVERFLOW;", "/* ??? The re-computing of overflow after", " saturation processing is specific to pabs. */", "overflow = res_grd != SIGN32 (res) ? DSR_MASK_V : 0;", "ADD_SUB_GE;", }, { "","", "pabs Sx,Dz", "10001000xx..zzzz", "res = DSP_R (x);", "res_grd = GET_DSP_GRD (x);", "if (res >= 0)", " carry = 0;", "else", " {", " res = -res;", " carry = (res != 0); /* The manual has a bug here. */", " res_grd = -res_grd - carry;", " }", "COMPUTE_OVERFLOW;", "/* ??? The re-computing of overflow after", " saturation processing is specific to pabs. */", "overflow = res_grd != SIGN32 (res) ? DSR_MASK_V : 0;", "ADD_SUB_GE;", }, { "","", "(if cc) prnd Sx,Dz", "100110ccxx01zzzz", "/* FIXME: duplicate code prnd. */", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "", "res = (Sx + 0x8000) & 0xffff0000;", "carry = (unsigned) res < (unsigned) Sx;", "res_grd = Sx_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "prnd Sx,Dz", "10011000xx..zzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "", "res = (Sx + 0x8000) & 0xffff0000;", "carry = (unsigned) res < (unsigned) Sx;", "res_grd = Sx_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pabs Sy,Dz", "101010cc01yyzzzz", "/* FIXME: duplicate code pabs. */", "res = DSP_R (y);", "res_grd = 0;", "overflow = 0;", "greater_equal = DSR_MASK_G;", "if (res >= 0)", " carry = 0;", "else", " {", " res = -res;", " carry = 1;", " if (res < 0)", " {", " if (S)", " res = 0x7fffffff;", " else", " {", " overflow = DSR_MASK_V;", " greater_equal = 0;", " }", " }", " }", }, { "","", "pabs Sy,Dz", "10101000..yyzzzz", "res = DSP_R (y);", "res_grd = 0;", "overflow = 0;", "greater_equal = DSR_MASK_G;", "if (res >= 0)", " carry = 0;", "else", " {", " res = -res;", " carry = 1;", " if (res < 0)", " {", " if (S)", " res = 0x7fffffff;", " else", " {", " overflow = DSR_MASK_V;", " greater_equal = 0;", " }", " }", " }", }, { "","", "(if cc) prnd Sy,Dz", "101110cc01yyzzzz", "/* FIXME: duplicate code prnd. */", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = (Sy + 0x8000) & 0xffff0000;", "carry = (unsigned) res < (unsigned) Sy;", "res_grd = Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "prnd Sy,Dz", "10111000..yyzzzz", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = (Sy + 0x8000) & 0xffff0000;", "carry = (unsigned) res < (unsigned) Sy;", "res_grd = Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pshl Sx,Sy,Dz", "100000ccxxyyzzzz", "int Sx = DSP_R (x) & 0xffff0000;", "int Sy = DSP_R (y) >> 16 & 0x7f;", "", "if (Sy <= 16)", " res = Sx << Sy;", "else if (Sy >= 128 - 16)", " res = (unsigned) Sx >> 128 - Sy; /* no sign extension */", "else", " {", " RAISE_EXCEPTION (SIGILL);", " return;", " }", "goto cond_logical;", }, { "","", "(if cc) psha Sx,Sy,Dz", "100100ccxxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y) >> 16 & 0x7f;", "", "if (Sy <= 32)", " {", " if (Sy == 32)", " {", " res = 0;", " res_grd = Sx;", " }", " else", " {", " res = Sx << Sy;", " res_grd = Sx_grd << Sy | (unsigned) Sx >> 32 - Sy;", " }", " res_grd = SEXT (res_grd);", " carry = res_grd & 1;", " }", "else if (Sy >= 96)", " {", " Sy = 128 - Sy;", " if (Sy == 32)", " {", " res_grd = SIGN32 (Sx_grd);", " res = Sx_grd;", " }", " else", " {", " res = Sx >> Sy | Sx_grd << 32 - Sy;", " res_grd = Sx_grd >> Sy;", " }", " carry = Sx >> (Sy - 1) & 1;", " }", "else", " {", " RAISE_EXCEPTION (SIGILL);", " return;", " }", "COMPUTE_OVERFLOW;", "greater_equal = 0;", }, { "","", "(if cc) psub Sx,Sy,Dz", "101000ccxxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sx - Sy;", "carry = (unsigned) res > (unsigned) Sx;", "res_grd = Sx_grd - Sy_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) psub Sy,Sx,Dz", "100001ccxxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sy - Sx;", "carry = (unsigned) res > (unsigned) Sy;", "res_grd = Sy_grd - Sx_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) padd Sx,Sy,Dz", "101100ccxxyyzzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sx + Sy;", "carry = (unsigned) res < (unsigned) Sx;", "res_grd = Sx_grd + Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pand Sx,Sy,Dz", "100101ccxxyyzzzz", "res = DSP_R (x) & DSP_R (y);", "cond_logical:", "res &= 0xffff0000;", "res_grd = 0;", "if (iword & 0x200)\n", " goto assign_z;\n", "logical:", "carry = 0;", "overflow = 0;", "greater_equal = 0;", "DSR &= ~0xf1;\n", "if (res)\n", " DSR |= res >> 26 & DSR_MASK_N;\n", "else\n", " DSR |= DSR_MASK_Z;\n", "goto assign_dc;\n", }, { "","", "(if cc) pxor Sx,Sy,Dz", "101001ccxxyyzzzz", "res = DSP_R (x) ^ DSP_R (y);", "goto cond_logical;", }, { "","", "(if cc) por Sx,Sy,Dz", "101101ccxxyyzzzz", "res = DSP_R (x) | DSP_R (y);", "goto cond_logical;", }, { "","", "(if cc) pdec Sx,Dz", "100010ccxx..zzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "", "res = Sx - 0x10000;", "carry = res > Sx;", "res_grd = Sx_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "res &= 0xffff0000;", }, { "","", "(if cc) pinc Sx,Dz", "100110ccxx..zzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "", "res = Sx + 0x10000;", "carry = res < Sx;", "res_grd = Sx_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "res &= 0xffff0000;", }, { "","", "(if cc) pdec Sy,Dz", "101010cc..yyzzzz", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sy - 0x10000;", "carry = res > Sy;", "res_grd = Sy_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "res &= 0xffff0000;", }, { "","", "(if cc) pinc Sy,Dz", "101110cc..yyzzzz", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = Sy + 0x10000;", "carry = res < Sy;", "res_grd = Sy_grd + carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", "res &= 0xffff0000;", }, { "","", "(if cc) pclr Dz", "100011cc....zzzz", "res = 0;", "res_grd = 0;", "carry = 0;", "overflow = 0;", "greater_equal = 1;", }, { "","", "pclr Du pmuls Se,Sf,Dg", "0100eeff0001gguu", "/* Do multiply. */", "res = (DSP_R (e) >> 16) * (DSP_R (f) >> 16) * 2;", "if (res == 0x80000000)", " res = 0x7fffffff;", "DSP_R (g) = res;", "DSP_GRD (g) = SIGN32 (res);", "/* FIXME: update DSR based on results of multiply! */", "", "/* Do clr. */", "z = u;", "res = 0;", "res_grd = 0;", "goto assign_z;", }, { "","", "(if cc) pdmsb Sx,Dz", "100111ccxx..zzzz", "unsigned Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "int i = 16;", "", "if (Sx_grd < 0)", " {", " Sx_grd = ~Sx_grd;", " Sx = ~Sx;", " }", "if (Sx_grd)", " {", " Sx = Sx_grd;", " res = -2;", " }", "else if (Sx)", " res = 30;", "else", " res = 31;", "do", " {", " if (Sx & ~0 << i)", " {", " res -= i;", " Sx >>= i;", " }", " }", "while (i >>= 1);", "res <<= 16;", "res_grd = SIGN32 (res);", "carry = 0;", "overflow = 0;", "ADD_SUB_GE;", }, { "","", "(if cc) pdmsb Sy,Dz", "101111cc..yyzzzz", "unsigned Sy = DSP_R (y);", "int i;", "", "if (Sy < 0)", " Sy = ~Sy;", "Sy <<= 1;", "res = 31;", "do", " {", " if (Sy & ~0 << i)", " {", " res -= i;", " Sy >>= i;", " }", " }", "while (i >>= 1);", "res <<= 16;", "res_grd = SIGN32 (res);", "carry = 0;", "overflow = 0;", "ADD_SUB_GE;", }, { "","", "(if cc) pneg Sx,Dz", "110010ccxx..zzzz", "int Sx = DSP_R (x);", "int Sx_grd = GET_DSP_GRD (x);", "", "res = 0 - Sx;", "carry = res != 0;", "res_grd = 0 - Sx_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pcopy Sx,Dz", "110110ccxx..zzzz", "res = DSP_R (x);", "res_grd = GET_DSP_GRD (x);", "carry = 0;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pneg Sy,Dz", "111010cc..yyzzzz", "int Sy = DSP_R (y);", "int Sy_grd = SIGN32 (Sy);", "", "res = 0 - Sy;", "carry = res != 0;", "res_grd = 0 - Sy_grd - carry;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) pcopy Sy,Dz", "111110cc..yyzzzz", "res = DSP_R (y);", "res_grd = SIGN32 (res);", "carry = 0;", "COMPUTE_OVERFLOW;", "ADD_SUB_GE;", }, { "","", "(if cc) psts MACH,Dz", "110011cc....zzzz", "res = MACH;", "res_grd = SIGN32 (res);", "goto assign_z;", }, { "","", "(if cc) psts MACL,Dz", "110111cc....zzzz", "res = MACL;", "res_grd = SIGN32 (res);", "goto assign_z;", }, { "","", "(if cc) plds Dz,MACH", "111011cc....zzzz", "if (0xa05f >> z & 1)", " RAISE_EXCEPTION (SIGILL);", "else", " MACH = DSP_R (z);", "return;", }, { "","", "(if cc) plds Dz,MACL", "111111cc....zzzz", "if (0xa05f >> z & 1)", " RAISE_EXCEPTION (SIGILL);", "else", " MACL = DSP_R (z) = res;", "return;", }, /* sh4a */ { "","", "(if cc) pswap Sx,Dz", "100111ccxx01zzzz", "int Sx = DSP_R (x);", "", "res = ((Sx & 0xffff) * 65536) + ((Sx >> 16) & 0xffff);", "res_grd = GET_DSP_GRD (x);", "carry = 0;", "overflow = 0;", "greater_equal = res & 0x80000000 ? 0 : DSR_MASK_G;", }, /* sh4a */ { "","", "(if cc) pswap Sy,Dz", "101111cc01yyzzzz", "int Sy = DSP_R (y);", "", "res = ((Sy & 0xffff) * 65536) + ((Sy >> 16) & 0xffff);", "res_grd = SIGN32 (Sy);", "carry = 0;", "overflow = 0;", "greater_equal = res & 0x80000000 ? 0 : DSR_MASK_G;", }, {0, 0} }; /* Tables of things to put into enums for sh-opc.h */ static const char * const nibble_type_list[] = { "HEX_0", "HEX_1", "HEX_2", "HEX_3", "HEX_4", "HEX_5", "HEX_6", "HEX_7", "HEX_8", "HEX_9", "HEX_A", "HEX_B", "HEX_C", "HEX_D", "HEX_E", "HEX_F", "REG_N", "REG_M", "BRANCH_12", "BRANCH_8", "DISP_8", "DISP_4", "IMM_4", "IMM_4BY2", "IMM_4BY4", "PCRELIMM_8BY2", "PCRELIMM_8BY4", "IMM_8", "IMM_8BY2", "IMM_8BY4", 0 }; static const char * const arg_type_list[] = { "A_END", "A_BDISP12", "A_BDISP8", "A_DEC_M", "A_DEC_N", "A_DISP_GBR", "A_DISP_PC", "A_DISP_REG_M", "A_DISP_REG_N", "A_GBR", "A_IMM", "A_INC_M", "A_INC_N", "A_IND_M", "A_IND_N", "A_IND_R0_REG_M", "A_IND_R0_REG_N", "A_MACH", "A_MACL", "A_PR", "A_R0", "A_R0_GBR", "A_REG_M", "A_REG_N", "A_SR", "A_VBR", "A_SSR", "A_SPC", 0, }; static int qfunc (const void *va, const void *vb) { const op *a = va; const op *b = vb; char bufa[9]; char bufb[9]; int diff; memcpy (bufa, a->code, 4); memcpy (bufa + 4, a->code + 12, 4); bufa[8] = 0; memcpy (bufb, b->code, 4); memcpy (bufb + 4, b->code + 12, 4); bufb[8] = 0; diff = strcmp (bufa, bufb); /* Stabilize the sort, so that later entries can override more general preceding entries. */ return diff ? diff : a - b; } static void sorttab (void) { op *p = tab; int len = 0; while (p->name) { p++; len++; } qsort (tab, len, sizeof (*p), qfunc); } static void gengastab (void) { op *p; sorttab (); for (p = tab; p->name; p++) { printf ("%s %-30s\n", p->code, p->name); } } static unsigned short table[1 << 16]; static int warn_conflicts = 0; static void conflict_warn (int val, int i) { int ix, key; int j = table[val]; fprintf (stderr, "Warning: opcode table conflict: 0x%04x (idx %d && %d)\n", val, i, table[val]); for (ix = sizeof (tab) / sizeof (tab[0]); ix >= 0; ix--) if (tab[ix].index == i || tab[ix].index == j) { key = ((tab[ix].code[0] - '0') << 3) + ((tab[ix].code[1] - '0') << 2) + ((tab[ix].code[2] - '0') << 1) + ((tab[ix].code[3] - '0')); if (val >> 12 == key) fprintf (stderr, " %s -- %s\n", tab[ix].code, tab[ix].name); } for (ix = sizeof (movsxy_tab) / sizeof (movsxy_tab[0]); ix >= 0; ix--) if (movsxy_tab[ix].index == i || movsxy_tab[ix].index == j) { key = ((movsxy_tab[ix].code[0] - '0') << 3) + ((movsxy_tab[ix].code[1] - '0') << 2) + ((movsxy_tab[ix].code[2] - '0') << 1) + ((movsxy_tab[ix].code[3] - '0')); if (val >> 12 == key) fprintf (stderr, " %s -- %s\n", movsxy_tab[ix].code, movsxy_tab[ix].name); } for (ix = sizeof (ppi_tab) / sizeof (ppi_tab[0]); ix >= 0; ix--) if (ppi_tab[ix].index == i || ppi_tab[ix].index == j) { key = ((ppi_tab[ix].code[0] - '0') << 3) + ((ppi_tab[ix].code[1] - '0') << 2) + ((ppi_tab[ix].code[2] - '0') << 1) + ((ppi_tab[ix].code[3] - '0')); if (val >> 12 == key) fprintf (stderr, " %s -- %s\n", ppi_tab[ix].code, ppi_tab[ix].name); } } /* Take an opcode, expand all varying fields in it out and fill all the right entries in 'table' with the opcode index. */ static void expand_opcode (int val, int i, const char *s) { if (*s == 0) { if (warn_conflicts && table[val] != 0) conflict_warn (val, i); table[val] = i; } else { int j = 0, m = 0; switch (s[0]) { default: fprintf (stderr, "expand_opcode: illegal char '%c'\n", s[0]); exit (1); case '0': case '1': /* Consume an arbitrary number of ones and zeros. */ do { j = (j << 1) + (s[m++] - '0'); } while (s[m] == '0' || s[m] == '1'); expand_opcode ((val << m) | j, i, s + m); break; case 'N': /* NN -- four-way fork */ for (j = 0; j < 4; j++) expand_opcode ((val << 2) | j, i, s + 2); break; case 'x': /* xx or xy -- two-way or four-way fork */ for (j = 0; j < 4; j += (s[1] == 'x' ? 2 : 1)) expand_opcode ((val << 2) | j, i, s + 2); break; case 'y': /* yy or yx -- two-way or four-way fork */ for (j = 0; j < (s[1] == 'x' ? 4 : 2); j++) expand_opcode ((val << 2) | j, i, s + 2); break; case '?': /* Seven-way "wildcard" fork for movxy */ expand_opcode ((val << 2), i, s + 2); for (j = 1; j < 4; j++) { expand_opcode ((val << 2) | j, i, s + 2); expand_opcode ((val << 2) | (j + 16), i, s + 2); } break; case 'i': /* eg. "i8*1" */ case '.': /* "...." is a wildcard */ case 'n': case 'm': /* nnnn, mmmm, i#*#, .... -- 16-way fork. */ for (j = 0; j < 16; j++) expand_opcode ((val << 4) | j, i, s + 4); break; case 'e': /* eeee -- even numbered register: 8 way fork. */ for (j = 0; j < 15; j += 2) expand_opcode ((val << 4) | j, i, s + 4); break; case 'M': /* A0, A1, X0, X1, Y0, Y1, M0, M1, A0G, A1G: MMMM -- 10-way fork */ expand_opcode ((val << 4) | 5, i, s + 4); for (j = 7; j < 16; j++) expand_opcode ((val << 4) | j, i, s + 4); break; case 'G': /* A1G, A0G: GGGG -- two-way fork */ for (j = 13; j <= 15; j +=2) expand_opcode ((val << 4) | j, i, s + 4); break; case 's': /* ssss -- 10-way fork */ /* System registers mach, macl, pr: */ for (j = 0; j < 3; j++) expand_opcode ((val << 4) | j, i, s + 4); /* System registers fpul, fpscr/dsr, a0, x0, x1, y0, y1: */ for (j = 5; j < 12; j++) expand_opcode ((val << 4) | j, i, s + 4); break; case 'X': /* XX/XY -- 2/4 way fork. */ for (j = 0; j < 4; j += (s[1] == 'X' ? 2 : 1)) expand_opcode ((val << 2) | j, i, s + 2); break; case 'a': /* aa/ax -- 2/4 way fork. */ for (j = 0; j < 4; j += (s[1] == 'a' ? 2 : 1)) expand_opcode ((val << 2) | j, i, s + 2); break; case 'Y': /* YY/YX -- 2/4 way fork. */ for (j = 0; j < (s[1] == 'Y' ? 2 : 4); j += 1) expand_opcode ((val << 2) | j, i, s + 2); break; case 'A': /* AA/AY: 2/4 way fork. */ for (j = 0; j < (s[1] == 'A' ? 2 : 4); j += 1) expand_opcode ((val << 2) | j, i, s + 2); break; case 'v': /* vv(VV) -- 4(16) way fork. */ /* Vector register fv0/4/8/12. */ if (s[2] == 'V') { /* 2 vector registers. */ for (j = 0; j < 15; j++) expand_opcode ((val << 4) | j, i, s + 4); } else { /* 1 vector register. */ for (j = 0; j < 4; j += 1) expand_opcode ((val << 2) | j, i, s + 2); } break; } } } /* Print the jump table used to index an opcode into a switch statement entry. */ static void dumptable (const char *name, int size, int start) { int lump = 256; int online = 16; int i = start; printf ("unsigned short %s[%d]={\n", name, size); while (i < start + size) { int j = 0; printf ("/* 0x%x */\n", i); while (j < lump) { int k = 0; while (k < online) { printf ("%2d", table[i + j + k]); if (j + k < lump) printf (","); k++; } j += k; printf ("\n"); } i += j; } printf ("};\n"); } static void filltable (op *p) { static int index = 1; sorttab (); for (; p->name; p++) { p->index = index++; expand_opcode (0, p->index, p->code); } } /* Table already contains all the switch case tags for 16-bit opcode double data transfer (ddt) insns, and the switch case tag for processing parallel processing insns (ppi) for code 0xf800 (ppi nopx nopy). Copy the latter tag to represent all combinations of ppi with ddt. */ static void expand_ppi_movxy (void) { int i; for (i = 0xf000; i < 0xf400; i++) if (table[i]) table[i + 0x800] = table[0xf800]; } static void gensim_caselist (op *p) { for (; p->name; p++) { int j; int sextbit = -1; int needm = 0; int needn = 0; const char *s = p->code; printf (" /* %s %s */\n", p->name, p->code); printf (" case %d: \n", p->index); printf (" {\n"); while (*s) { switch (*s) { default: fprintf (stderr, "gencode/gensim_caselist: illegal char '%c'\n", *s); exit (1); break; case '?': /* Wildcard expansion, nothing to do here. */ s += 2; break; case 'v': printf (" int v1 = ((iword >> 10) & 3) * 4;\n"); s += 2; break; case 'V': printf (" int v2 = ((iword >> 8) & 3) * 4;\n"); s += 2; break; case '0': case '1': s += 2; break; case '.': s += 4; break; case 'n': case 'e': printf (" int n = (iword >> 8) & 0xf;\n"); needn = 1; s += 4; break; case 'N': printf (" int n = (((iword >> 8) - 2) & 0x3) + 2;\n"); s += 2; break; case 'x': if (s[1] == 'y') /* xy */ { printf (" int n = (iword & 3) ? \n"); printf (" ((iword >> 9) & 1) + 4 : \n"); printf (" REG_xy ((iword >> 8) & 3);\n"); } else printf (" int n = ((iword >> 9) & 1) + 4;\n"); needn = 1; s += 2; break; case 'y': if (s[1] == 'x') /* yx */ { printf (" int n = (iword & 0xc) ? \n"); printf (" ((iword >> 8) & 1) + 6 : \n"); printf (" REG_yx ((iword >> 8) & 3);\n"); } else printf (" int n = ((iword >> 8) & 1) + 6;\n"); needn = 1; s += 2; break; case 'm': needm = 1; case 's': case 'M': case 'G': printf (" int m = (iword >> 4) & 0xf;\n"); s += 4; break; case 'X': if (s[1] == 'Y') /* XY */ { printf (" int m = (iword & 3) ? \n"); printf (" ((iword >> 7) & 1) + 8 : \n"); printf (" DSP_xy ((iword >> 6) & 3);\n"); } else printf (" int m = ((iword >> 7) & 1) + 8;\n"); s += 2; break; case 'a': if (s[1] == 'x') /* ax */ { printf (" int m = (iword & 3) ? \n"); printf (" 7 - ((iword >> 6) & 2) : \n"); printf (" DSP_ax ((iword >> 6) & 3);\n"); } else printf (" int m = 7 - ((iword >> 6) & 2);\n"); s += 2; break; case 'Y': if (s[1] == 'X') /* YX */ { printf (" int m = (iword & 0xc) ? \n"); printf (" ((iword >> 6) & 1) + 10 : \n"); printf (" DSP_yx ((iword >> 6) & 3);\n"); } else printf (" int m = ((iword >> 6) & 1) + 10;\n"); s += 2; break; case 'A': if (s[1] == 'Y') /* AY */ { printf (" int m = (iword & 0xc) ? \n"); printf (" 7 - ((iword >> 5) & 2) : \n"); printf (" DSP_ay ((iword >> 6) & 3);\n"); } else printf (" int m = 7 - ((iword >> 5) & 2);\n"); s += 2; break; case 'i': printf (" int i = (iword & 0x"); switch (s[1]) { default: fprintf (stderr, "gensim_caselist: Unknown char '%c' in %s\n", s[1], s); exit (1); break; case '4': printf ("f"); break; case '8': printf ("ff"); break; case '1': sextbit = 12; printf ("fff"); break; } printf (")"); switch (s[3]) { default: fprintf (stderr, "gensim_caselist: Unknown char '%c' in %s\n", s[3], s); exit (1); break; case '.': /* eg. "i12." */ break; case '1': break; case '2': printf (" << 1"); break; case '4': printf (" << 2"); break; } printf (";\n"); s += 4; } } if (sextbit > 0) { printf (" i = (i ^ (1 << %d)) - (1 << %d);\n", sextbit - 1, sextbit - 1); } if (needm && needn) printf (" TB (m,n);\n"); else if (needm) printf (" TL (m);\n"); else if (needn) printf (" TL (n);\n"); { /* Do the refs. */ const char *r; for (r = p->refs; *r; r++) { if (*r == 'f') printf (" CREF (15);\n"); if (*r == '-') { printf (" {\n"); printf (" int i = n;\n"); printf (" do {\n"); printf (" CREF (i);\n"); printf (" } while (i-- > 0);\n"); printf (" }\n"); } if (*r == '+') { printf (" {\n"); printf (" int i = n;\n"); printf (" do {\n"); printf (" CREF (i);\n"); printf (" } while (i++ < 14);\n"); printf (" }\n"); } if (*r == '0') printf (" CREF (0);\n"); if (*r == '8') printf (" CREF (8);\n"); if (*r == '9') printf (" CREF (9);\n"); if (*r == 'n') printf (" CREF (n);\n"); if (*r == 'm') printf (" CREF (m);\n"); } } printf (" {\n"); for (j = 0; j < MAX_NR_STUFF; j++) { if (p->stuff[j]) { printf (" %s\n", p->stuff[j]); } } printf (" }\n"); { /* Do the defs. */ const char *r; for (r = p->defs; *r; r++) { if (*r == 'f') printf (" CDEF (15);\n"); if (*r == '-') { printf (" {\n"); printf (" int i = n;\n"); printf (" do {\n"); printf (" CDEF (i);\n"); printf (" } while (i-- > 0);\n"); printf (" }\n"); } if (*r == '+') { printf (" {\n"); printf (" int i = n;\n"); printf (" do {\n"); printf (" CDEF (i);\n"); printf (" } while (i++ < 14);\n"); printf (" }\n"); } if (*r == '0') printf (" CDEF (0);\n"); if (*r == 'n') printf (" CDEF (n);\n"); if (*r == 'm') printf (" CDEF (m);\n"); } } printf (" break;\n"); printf (" }\n"); } } static void gensim (void) { printf ("{\n"); printf ("/* REG_xy = [r4, r5, r0, r1]. */\n"); printf ("#define REG_xy(R) ((R)==0 ? 4 : (R)==2 ? 5 : (R)==1 ? 0 : 1)\n"); printf ("/* REG_yx = [r6, r7, r2, r3]. */\n"); printf ("#define REG_yx(R) ((R)==0 ? 6 : (R)==1 ? 7 : (R)==2 ? 2 : 3)\n"); printf ("/* DSP_ax = [a0, a1, x0, x1]. */\n"); printf ("#define DSP_ax(R) ((R)==0 ? 7 : (R)==2 ? 5 : (R)==1 ? 8 : 9)\n"); printf ("/* DSP_ay = [a0, a1, y0, y1]. */\n"); printf ("#define DSP_ay(R) ((R)==0 ? 7 : (R)==1 ? 5 : (R)==2 ? 10 : 11)\n"); printf ("/* DSP_xy = [x0, x1, y0, y1]. */\n"); printf ("#define DSP_xy(R) ((R)==0 ? 8 : (R)==2 ? 9 : (R)==1 ? 10 : 11)\n"); printf ("/* DSP_yx = [y0, y1, x0, x1]. */\n"); printf ("#define DSP_yx(R) ((R)==0 ? 10 : (R)==1 ? 11 : (R)==2 ? 8 : 9)\n"); printf (" switch (jump_table[iword]) {\n"); gensim_caselist (tab); gensim_caselist (movsxy_tab); printf (" default:\n"); printf (" {\n"); printf (" RAISE_EXCEPTION (SIGILL);\n"); printf (" }\n"); printf (" }\n"); printf ("}\n"); } static void gendefines (void) { op *p; filltable (tab); for (p = tab; p->name; p++) { const char *s = p->name; printf ("#define OPC_"); while (*s) { if (isalpha (*s)) printf ("%c", tolower (*s)); if (*s == ' ') printf ("_"); if (*s == '@') printf ("ind_"); if (*s == ',') printf ("_"); s++; } printf (" %d\n",p->index); } } static int ppi_index; /* Take a ppi code, expand all varying fields in it and fill all the right entries in 'table' with the opcode index. NOTE: tail recursion optimization removed for simplicity. */ static void expand_ppi_code (int val, int i, const char *s) { int j; switch (s[0]) { default: fprintf (stderr, "gencode/expand_ppi_code: Illegal char '%c'\n", s[0]); exit (2); break; case 'g': case 'z': if (warn_conflicts && table[val] != 0) conflict_warn (val, i); /* The last four bits are disregarded for the switch table. */ table[val] = i; return; case 'm': /* Four-bit expansion. */ for (j = 0; j < 16; j++) expand_ppi_code ((val << 4) + j, i, s + 4); break; case '.': case '0': expand_ppi_code ((val << 1), i, s + 1); break; case '1': expand_ppi_code ((val << 1) + 1, i, s + 1); break; case 'i': case 'e': case 'f': case 'x': case 'y': expand_ppi_code ((val << 1), i, s + 1); expand_ppi_code ((val << 1) + 1, i, s + 1); break; case 'c': expand_ppi_code ((val << 2) + 1, ppi_index++, s + 2); expand_ppi_code ((val << 2) + 2, i, s + 2); expand_ppi_code ((val << 2) + 3, i, s + 2); break; } } static void ppi_filltable (void) { op *p; ppi_index = 1; for (p = ppi_tab; p->name; p++) { p->index = ppi_index++; expand_ppi_code (0, p->index, p->code); } } static void ppi_gensim (void) { op *p = ppi_tab; printf ("#define DSR_MASK_G 0x80\n"); printf ("#define DSR_MASK_Z 0x40\n"); printf ("#define DSR_MASK_N 0x20\n"); printf ("#define DSR_MASK_V 0x10\n"); printf ("\n"); printf ("#define COMPUTE_OVERFLOW do {\\\n"); printf (" overflow = res_grd != SIGN32 (res) ? DSR_MASK_V : 0; \\\n"); printf (" if (overflow && S) \\\n"); printf (" { \\\n"); printf (" if (res_grd & 0x80) \\\n"); printf (" { \\\n"); printf (" res = 0x80000000; \\\n"); printf (" res_grd |= 0xff; \\\n"); printf (" } \\\n"); printf (" else \\\n"); printf (" { \\\n"); printf (" res = 0x7fffffff; \\\n"); printf (" res_grd &= ~0xff; \\\n"); printf (" } \\\n"); printf (" overflow = 0; \\\n"); printf (" } \\\n"); printf ("} while (0)\n"); printf ("\n"); printf ("#define ADD_SUB_GE \\\n"); printf (" (greater_equal = ~(overflow << 3 & res_grd) & DSR_MASK_G)\n"); printf ("\n"); printf ("static void\n"); printf ("ppi_insn (int iword)\n"); printf ("{\n"); printf (" /* 'ee' = [x0, x1, y0, a1] */\n"); printf (" static char e_tab[] = { 8, 9, 10, 5};\n"); printf (" /* 'ff' = [y0, y1, x0, a1] */\n"); printf (" static char f_tab[] = {10, 11, 8, 5};\n"); printf (" /* 'xx' = [x0, x1, a0, a1] */\n"); printf (" static char x_tab[] = { 8, 9, 7, 5};\n"); printf (" /* 'yy' = [y0, y1, m0, m1] */\n"); printf (" static char y_tab[] = {10, 11, 12, 14};\n"); printf (" /* 'gg' = [m0, m1, a0, a1] */\n"); printf (" static char g_tab[] = {12, 14, 7, 5};\n"); printf (" /* 'uu' = [x0, y0, a0, a1] */\n"); printf (" static char u_tab[] = { 8, 10, 7, 5};\n"); printf ("\n"); printf (" int z;\n"); printf (" int res, res_grd;\n"); printf (" int carry, overflow, greater_equal;\n"); printf ("\n"); printf (" switch (ppi_table[iword >> 4]) {\n"); for (; p->name; p++) { int shift, j; int cond = 0; int havedecl = 0; const char *s = p->code; printf (" /* %s %s */\n", p->name, p->code); printf (" case %d: \n", p->index); printf (" {\n"); for (shift = 16; *s; ) { switch (*s) { case 'i': printf (" int i = (iword >> 4) & 0x7f;\n"); s += 6; break; case 'e': case 'f': case 'x': case 'y': case 'g': case 'u': shift -= 2; printf (" int %c = %c_tab[(iword >> %d) & 3];\n", *s, *s, shift); havedecl = 1; s += 2; break; case 'c': printf (" if ((((iword >> 8) ^ DSR) & 1) == 0)\n"); printf ("\treturn;\n"); printf (" }\n"); printf (" case %d: \n", p->index + 1); printf (" {\n"); cond = 1; case '0': case '1': case '.': shift -= 2; s += 2; break; case 'z': if (havedecl) printf ("\n"); printf (" z = iword & 0xf;\n"); havedecl = 2; s += 4; break; } } if (havedecl == 1) printf ("\n"); else if (havedecl == 2) printf (" {\n"); for (j = 0; j < MAX_NR_STUFF; j++) { if (p->stuff[j]) { printf (" %s%s\n", (havedecl == 2 ? " " : ""), p->stuff[j]); } } if (havedecl == 2) printf (" }\n"); if (cond) { printf (" if (iword & 0x200)\n"); printf (" goto assign_z;\n"); } printf (" break;\n"); printf (" }\n"); } printf (" default:\n"); printf (" {\n"); printf (" RAISE_EXCEPTION (SIGILL);\n"); printf (" return;\n"); printf (" }\n"); printf (" }\n"); printf (" DSR &= ~0xf1;\n"); printf (" if (res || res_grd)\n"); printf (" DSR |= greater_equal | res_grd >> 2 & DSR_MASK_N | overflow;\n"); printf (" else\n"); printf (" DSR |= DSR_MASK_Z | overflow;\n"); printf (" assign_dc:\n"); printf (" switch (DSR >> 1 & 7)\n"); printf (" {\n"); printf (" case 0: /* Carry Mode */\n"); printf (" DSR |= carry;\n"); printf (" case 1: /* Negative Value Mode */\n"); printf (" DSR |= res_grd >> 7 & 1;\n"); printf (" case 2: /* Zero Value Mode */\n"); printf (" DSR |= DSR >> 6 & 1;\n"); printf (" case 3: /* Overflow mode */\n"); printf (" DSR |= overflow >> 4;\n"); printf (" case 4: /* Signed Greater Than Mode */\n"); printf (" DSR |= DSR >> 7 & 1;\n"); printf (" case 5: /* Signed Greater Than Or Equal Mode */\n"); printf (" DSR |= greater_equal >> 7;\n"); printf (" }\n"); printf (" assign_z:\n"); printf (" if (0xa05f >> z & 1)\n"); printf (" {\n"); printf (" RAISE_EXCEPTION (SIGILL);\n"); printf (" return;\n"); printf (" }\n"); printf (" DSP_R (z) = res;\n"); printf (" DSP_GRD (z) = res_grd;\n"); printf ("}\n"); } int main (int ac, char *av[]) { /* Verify the table before anything else. */ { op *p; for (p = tab; p->name; p++) { /* Check that the code field contains 16 bits. */ if (strlen (p->code) != 16) { fprintf (stderr, "Code `%s' length wrong (%zu) for `%s'\n", p->code, strlen (p->code), p->name); abort (); } } } /* Now generate the requested data. */ if (ac > 1) { if (ac > 2 && strcmp (av[2], "-w") == 0) { warn_conflicts = 1; } if (strcmp (av[1], "-t") == 0) { gengastab (); } else if (strcmp (av[1], "-d") == 0) { gendefines (); } else if (strcmp (av[1], "-s") == 0) { filltable (tab); dumptable ("sh_jump_table", 1 << 16, 0); memset (table, 0, sizeof table); filltable (movsxy_tab); expand_ppi_movxy (); dumptable ("sh_dsp_table", 1 << 12, 0xf000); memset (table, 0, sizeof table); ppi_filltable (); dumptable ("ppi_table", 1 << 12, 0); } else if (strcmp (av[1], "-x") == 0) { filltable (tab); filltable (movsxy_tab); gensim (); } else if (strcmp (av[1], "-p") == 0) { ppi_filltable (); ppi_gensim (); } } else fprintf (stderr, "Opcode table generation no longer supported.\n"); return 0; }
25.841662
103
0.433494
[ "vector" ]
aa27d2bbe4ffb6ad871dbe501102a52e617cb522
1,765
h
C
src/check_list.h
papillonnette/zetasql-lint
8509877a736c429729240cd055591446ec197359
[ "Apache-2.0" ]
null
null
null
src/check_list.h
papillonnette/zetasql-lint
8509877a736c429729240cd055591446ec197359
[ "Apache-2.0" ]
null
null
null
src/check_list.h
papillonnette/zetasql-lint
8509877a736c429729240cd055591446ec197359
[ "Apache-2.0" ]
null
null
null
// // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef SRC_CHECK_LIST_H_ #define SRC_CHECK_LIST_H_ #include <iostream> #include <map> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "src/linter.h" #include "src/linter_options.h" namespace zetasql::linter { // It is the general list of the linter checks. It can be used to // verify if a place is controlling all of the checks and not missing any. class CheckList { public: // Getter function for the list const std::vector< std::function<LinterResult(absl::string_view, const LinterOptions&)>> GetList(); // Add a linter check to the list void Add(std::function<LinterResult(absl::string_view, const LinterOptions&)> check); private: std::vector< std::function<LinterResult(absl::string_view, const LinterOptions&)>> list_; }; // This function gives all Checks that are using ZetaSQL parser. CheckList GetParserDependantChecks(); // This function is the main function to get all the checks. // Whenever a new check is added this should be // the first place to update. CheckList GetAllChecks(); } // namespace zetasql::linter #endif // SRC_CHECK_LIST_H_
28.467742
79
0.730312
[ "vector" ]
aa288e874199d4121ebc3451277cc2c49aca7ce8
58,647
h
C
seqan/include/seqan/index/index_qgram_openaddressing.3.h
fishlist/linear
e7a19ea372b70e40d636ddec8150ee482e297169
[ "BSD-3-Clause" ]
null
null
null
seqan/include/seqan/index/index_qgram_openaddressing.3.h
fishlist/linear
e7a19ea372b70e40d636ddec8150ee482e297169
[ "BSD-3-Clause" ]
null
null
null
seqan/include/seqan/index/index_qgram_openaddressing.3.h
fishlist/linear
e7a19ea372b70e40d636ddec8150ee482e297169
[ "BSD-3-Clause" ]
null
null
null
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2015, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: David Weese <david.weese@fu-berlin.de> // ========================================================================== #ifndef SEQAN_HEADER_INDEX_QGRAM_OPENADRESSING_H #define SEQAN_HEADER_INDEX_QGRAM_OPENADRESSING_H namespace SEQAN_NAMESPACE_MAIN { struct OpenAddressing_; typedef Tag<OpenAddressing_> OpenAddressing; template <typename THashValue> struct BucketMap { static const THashValue EMPTY; String<THashValue> qgramCode; }; template <typename THashValue> const THashValue BucketMap<THashValue>::EMPTY = (THashValue)-1; // use the index value type as shape value type template < typename TObject, typename TShapeSpec > struct Fibre< Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> >, FibreBucketMap> { typedef typename Fibre< Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> >, FibreShape>::Type TShape; typedef typename Value<TShape>::Type THashValue; typedef BucketMap<THashValue> Type; }; /*! * @class OpenAddressingQGramIndex * @extends IndexQGram * @headerfile <seqan/index.h> * @brief A <i>q</i>-gram that uses open addressing hashing instead of an array. * * @signature template <typename TIndex, typename TShapeSpec> * class Index<TText, IndexQGram<TShapeSpec, OpenAddressing> >; * * @tparam TText The @link TextConcept text type @endlink. * @tparam TShapeSpec The @link Shape @endlink specialization type. * * This index uses a non-trivial hashing for mapping q-gram hash values to buckets. This reduces the sizes of bucket * directories (QGramDir, QGramCountsDir fibres) from &Sigma;<i><sup>q</sup></i> to min(<i>&alpha; &middot; n</i>, * \Sigma<i><sup>q</sup></i>), for a load factor <i>&alpha; &gt; 1</i>. A bucket still stores occurrences (or counts) * of the same <i>q</i>-gram, but in contrast to the @link IndexQGram @endlink index, buckets are in random order due to * the hashing. * * @var double OpenAddressingQGramIndex::alpha * @brief Load factor. Controls space/time-tradeoff and must be greater 1. Default value is 1.6. */ #ifdef PLATFORM_WINDOWS_VS #pragma warning( push ) // Disable warning C4521 locally (multiple copy constructors). #pragma warning( disable: 4521 ) #endif // PLATFORM_WINDOWS_VS template < typename TObject, typename TShapeSpec > class Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> > { private: static const double defaultAlpha; public: typedef typename Member<Index, QGramText>::Type TTextMember; typedef typename Fibre<Index, QGramText>::Type TText; typedef typename Fibre<Index, QGramSA>::Type TSA; typedef typename Fibre<Index, QGramDir>::Type TDir; typedef typename Fibre<Index, QGramCounts>::Type TCounts; typedef typename Fibre<Index, QGramCountsDir>::Type TCountsDir; typedef typename Fibre<Index, QGramShape>::Type TShape; typedef typename Fibre<Index, QGramBucketMap>::Type TBucketMap; typedef typename Cargo<Index>::Type TCargo; typedef typename Size<Index>::Type TSize; TTextMember text; // underlying text TSA sa; // suffix array sorted by the first q chars TDir dir; // bucket directory TCounts counts; // counts each q-gram per sequence TCountsDir countsDir; // directory for count buckets TShape shape; // underlying shape TCargo cargo; // user-defined cargo TBucketMap bucketMap; // bucketMap table (used by open-addressing index) TSize stepSize; // store every <stepSize>'th q-gram in the index double alpha; // for m entries the hash map has at least size alpha*m Index(): stepSize(1), alpha(defaultAlpha) {} Index(Index &other): text(other.text), sa(other.sa), dir(other.dir), counts(other.counts), countsDir(other.countsDir), shape(other.shape), cargo(other.cargo), bucketMap(other.bucketMap), stepSize(1), alpha(defaultAlpha) {} Index(Index const &other): text(other.text), sa(other.sa), dir(other.dir), counts(other.counts), countsDir(other.countsDir), shape(other.shape), cargo(other.cargo), bucketMap(other.bucketMap), stepSize(1), alpha(defaultAlpha) {} template <typename TText_> Index(TText_ &_text): text(_text), stepSize(1), alpha(defaultAlpha) {} template <typename TText_> Index(TText_ const &_text): text(_text), stepSize(1), alpha(defaultAlpha) {} template <typename TText_, typename TShape_> Index(TText_ &_text, TShape_ const &_shape): text(_text), shape(_shape), stepSize(1), alpha(defaultAlpha) {} template <typename TText_, typename TShape_> Index(TText_ const &_text, TShape_ const &_shape): text(_text), shape(_shape), stepSize(1), alpha(defaultAlpha) {} }; #ifdef PLATFORM_WINDOWS_VS // Enable warning C4521 again (multiple copy operators). #pragma warning( pop ) #endif // PLATFORM_WINDOWS_VS //x-begin: min shape open index template < typename TObject, unsigned TSPAN, unsigned TWEIGHT> class Index<TObject, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> > { private: static const double defaultAlpha; public: typedef typename Member<Index, QGramText>::Type TTextMember; typedef typename Fibre<Index, QGramText>::Type TText; typedef typename Fibre<Index, QGramSA>::Type TSA; typedef typename Fibre<Index, QGramDir>::Type TDir; typedef typename Fibre<Index, QGramCounts>::Type TCounts; typedef typename Fibre<Index, QGramCountsDir>::Type TCountsDir; typedef typename Fibre<Index, QGramShape>::Type TShape; typedef typename Fibre<Index, QGramBucketMap>::Type TBucketMap; typedef typename Cargo<Index>::Type TCargo; typedef typename Size<Index>::Type TSize; TTextMember text; // underlying text // TSA sa; // suffix array sorted by the first q chars String<uint64_t> sa; TDir dir; // bucket directory TCounts counts; // counts each q-gram per sequence TCountsDir countsDir; // directory for count buckets TShape shape; // underlying shape TCargo cargo; // user-defined cargo TBucketMap bucketMap; // bucketMap table (used by open-addressing index) TSize stepSize; // store every <stepSize>'th q-gram in the index double alpha; // for m entries the hash map has at least size alpha*m //x-begin// uint64_t start; // uint64_t _Empty_Dir_ = start - 2; //x-end// Index(): stepSize(1), alpha(defaultAlpha) {} Index(Index &other): text(other.text), sa(other.sa), dir(other.dir), counts(other.counts), countsDir(other.countsDir), shape(other.shape), cargo(other.cargo), bucketMap(other.bucketMap), stepSize(1), alpha(defaultAlpha) {} Index(Index const &other): text(other.text), sa(other.sa), dir(other.dir), counts(other.counts), countsDir(other.countsDir), shape(other.shape), cargo(other.cargo), bucketMap(other.bucketMap), stepSize(1), alpha(defaultAlpha) {} template <typename TText_> Index(TText_ &_text): text(_text), stepSize(1), alpha(defaultAlpha) {} template <typename TText_> Index(TText_ const &_text): text(_text), stepSize(1), alpha(defaultAlpha) {} template <typename TText_, typename TShape_> Index(TText_ &_text, TShape_ const &_shape): text(_text), shape(_shape), stepSize(1), alpha(defaultAlpha) {} template <typename TText_, typename TShape_> Index(TText_ const &_text, TShape_ const &_shape): text(_text), shape(_shape), stepSize(1), alpha(defaultAlpha) {} }; //============================================================= // definition of some types for mimizer index struct hPair { uint64_t i1; uint64_t i2; inline hPair & operator = (hPair & b) { i1 = b.i1; i2 = b.i2; return *this; } }; //============================================================== //============================================================= //definition of types of elements in dir (uint64_t) //bodyNode= //length1[4] length2[38] YValue[20] code[2]: code={1} // //headNode= //hvalue(/XValue)[62] code[2]: code={2,3}, 2:head, 3:virtual head // //code 0 empty //code 2 head 10 //code 3 virtual head 11 //code 1 body 01 static const uint64_t _dirEmpty = (uint64_t)1 << 63; static const uint64_t _bitEmpty = 0; static const uint64_t _bitLength = ((uint64_t)1 << 58) - 1; static const uint64_t _bitValue = ((uint64_t)1 << 56) - 1; static const unsigned _bitLength_END = 60; static const unsigned _bitValue_END = 2; //HeadNode(H): //H := (h/X)Value[62]|HeadType[2]: 0:=empty 2:=head 3:=virtual head static const unsigned _HeadValue_bits = 3; static const uint64_t _HeadType_code = 2; static const uint64_t _HeadTypeVtl_code = 3; static const uint64_t _HeadTypeHVl_code = 4; // BodyNode(B): // B := YValue[26]|BodyType[1]: |counth[37] // occ = counth[n+1] - count[n] = (B[n+1] - B[n]) & bit, bit = 00..0011...11 static const unsigned _BodyValue_bits = 38; static const unsigned _BodyType_bits = 37; //static const unsigned _BodyValue_bits = 2; static const uint64_t _BodyType_code = 1; static const uint64_t _BodyTypeEnd_code = 0; static const uint64_t _BodyType_key = ~((uint64_t)1 << _BodyType_bits); static const uint64_t _getBody = ((uint64_t)1 << _BodyType_bits) - 1; static const uint64_t _bitEmptyType = 0; static const uint64_t _bitCode = 3; // node(value) & _bitCode to acquire the type of the node static const uint64_t _bitValue2 = ((uint64_t)1 << 22) - 1; static const uint64_t _bitEmptyCode = 0; static const uint64_t _bitBodyCode = 1; static const uint64_t _bitHeadCode = 2; static const uint64_t _bitVtlHeadCode = 3; //SA node:= seq num i1[40]| base num i2[16] static const uint64_t _BaseNum_bits = 32; static const uint64_t _SeqNum_bits = 30; static const uint64_t _BaseNum_code = ((uint64_t)1 << _BaseNum_bits) - 1; static const uint64_t _Empty_Dir_ = -1; static const unsigned blocklimit = 32; //============================================================== template <typename HValue> inline HValue _makeHeadNode(HValue code) { return (code << _HeadValue_bits) + _HeadType_code; } template <typename HValue> inline HValue _makeVtlHeadNode(HValue code) { return (code << _HeadValue_bits) + _HeadTypeVtl_code; } template <typename HValue> inline HValue _makeHVlHeadNode(HValue code) { return (code << _HeadValue_bits) + _HeadTypeHVl_code; } template <typename HValue> inline void _setHVlHeadNode(HValue & headNode, HValue const & hValue) { headNode = (hValue << _HeadValue_bits) + _HeadTypeHVl_code; } template <typename HValue> inline void _setHeadNode(HValue & headNode, HValue const & hValue) { headNode = (hValue << _HeadValue_bits) + _HeadType_code; } template <typename HValue> inline HValue _makeEmptyNode(HValue code) { return (code << _HeadValue_bits) + _bitEmptyType; } template <typename HValue, unsigned TSPAN, unsigned TWEIGHT> inline HValue _getDirStart(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> > & index) { return index.start; } template <typename HValue> inline void _setBodyType_Begin(HValue & code){ code &= _BodyType_key; } template <typename HValue> inline HValue _ifBodyType(HValue code){ return code & (~_BodyType_key); } template <typename HValue> inline HValue _getHeadValue(HValue code) { return code >> _HeadValue_bits; } template <typename HValue> inline void _setBodyNode(HValue & bodyNode, HValue const & YValue, HValue const & type, HValue const & counth) { bodyNode = (YValue << _BodyValue_bits) + (type << _BodyType_bits) + counth; } template <typename HValue> inline HValue _getBodyValue(HValue code) { return code >> _BodyValue_bits; } template <typename HValue> inline HValue _getBodyCounth(HValue & code) { return code & _getBody; } template <typename HValue> inline HValue _createSANode(HValue const & i1, HValue const & i2) { return (i1 << _BaseNum_bits) + i2; } template <typename HValue> inline void _setSANode(HValue & node, HValue const & i1, HValue const & i2) { node = (i1 << _BaseNum_bits) + i2; } template <typename HValue> inline HValue _getSA_i2(HValue const & node) { return node & _BaseNum_code; } //x-end: min shape open index template < typename TObject, typename TShapeSpec > const double Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> >::defaultAlpha = 1.6; //x-begin template < typename TObject,unsigned TSPAN, unsigned TWEIGHT> const double Index<TObject, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> >::defaultAlpha = 1.6; //x-end ////////////////////////////////////////////////////////////////////////////// // Counting sort - Step 1: Clear directory template < typename TDir, typename THashValue, typename TParallelTag > inline void _qgramClearDir(TDir &dir, BucketMap<THashValue> &bucketMap, Tag<TParallelTag> parallelTag) { typedef BucketMap<THashValue> TBucketMap; if (!empty(dir)) arrayFill(begin(dir, Standard()), end(dir, Standard()), 0, parallelTag); if (!empty(bucketMap.qgramCode)) arrayFill(begin(bucketMap.qgramCode, Standard()), end(bucketMap.qgramCode, Standard()), TBucketMap::EMPTY, parallelTag); } template < typename TBucketMap, typename TValue > inline TValue _hashFunction(TBucketMap const &, TValue val) { // WARNING: // As SSE4.2 is not always available, the bucket order is platform dependent #ifdef __SSE4_2__ return _mm_crc32_u64(0ul, val); #else return ((val * 43) ^ (val >> 20)) + val; #endif } //x1-begin //template <typename TIndex, typename THashValue, typename TParallelTag> /* template<typename TDir, typename THashValue> inline THashValue requestBucket(TDir & dir, THashValue code, unsigned len)//, Tag<TParallelTag> parallelTag) { //std::cout << code << " " << len << std::endl; typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(dir); if (hlen == 0ul) return code; TSize h1 = _hashFunction(dir, code >> _bitValue_END); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif // was the entry empty or occupied by our code? // if not we have a collision -> probe for our code or an empty entry // // do linear probing if we need to save memory (when SEQAN_OPENADDRESSING_COMPACT is defined) // otherwise do quadratic probing to avoid clustering (Cormen 1998) TSize delta = 0; (void)delta; //std::cout << "done\n"; unsigned count = 0; //return h1; for (auto k = 0; k < len; k++) { //if (code == dir[h1 + k]) //{ // std::cout << count<< std::endl; // return h1; //} //std::cout << (dir[h1+k] & _bitCode) << std::endl; switch (dir[h1+k] & _bitCode){ case 1: h1 = (0 + h1 + (dir[h1 + k] >> _bitLength_END) + delta) & hlen ; //std::cout << len << " " << (dir[h1+k] >> _bitLength_END) << std::endl; std::cout << k << std::endl; ++delta; k=0; count++; break; case 2: h1 = (0 + h1 + (dir[h1 + k + 1] >> _bitLength_END) + delta) & hlen ; std::cout << k << std::endl; //std::cout << len << " " << (dir[h1 + k + 1] >> _bitLength_END) << std::endl; ++delta; k=0; count++ ; break; case 3: std::cout << k << std::endl; h1 = (h1 + 1 + delta) & hlen ; ++delta; k=0; count++; break; } } std::cout << len << " count " << count << std::endl; return h1; } */ //x1-end /* template<typename TDir, typename THashValue> inline THashValue requestBucket(TDir & dir, THashValue code, unsigned len)//, Tag<TParallelTag> parallelTag) { //std::cout << code << " " << len << std::endl; typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(dir); if (hlen == 0ul) return code; TSize h1 = _hashFunction(dir, code >> _bitValue_END); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif // was the entry empty or occupied by our code? // if not we have a collision -> probe for our code or an empty entry // // do linear probing if we need to save memory (when SEQAN_OPENADDRESSING_COMPACT is defined) // otherwise do quadratic probing to avoid clustering (Cormen 1998) TSize delta = 0; (void)delta; //std::cout << "done\n"; unsigned count = 0; //return h1; for (auto k = 0; k < len; k++) { switch (dir[h1+k] & _bitCode){ case 1: h1 = (0 + h1 + (dir[h1 + k] >> _bitLength_END) + delta) & hlen ; //std::cout << len << " " << (dir[h1+k] >> _bitLength_END) << std::endl; //std::cout << k << std::endl; ++delta; k=0; count++; break; case 2: h1 = (0 + h1 + (dir[h1 + k + 1] >> _bitLength_END) + delta) & hlen ; std::cout << k << std::endl; //std::cout << len << " " << (dir[h1 + k + 1] >> _bitLength_END) << std::endl; ++delta; k=0; count++ ; break; case 3: //std::cout << k << std::endl; h1 = (h1 + 1 + delta) & hlen ; ++delta; k=0; count++; break; } } std::cout << len << " count " << count << std::endl; return h1; } */ template < typename TBucketMap, typename TValue > inline TValue _hashFunction1(TBucketMap const &, TValue val) { uint64_t key = val; key = (~key) + (key << 21); // key = (key << 21) - key - 1; key = key ^ (key >> 24); key = (key + (key << 3)) + (key << 8); // key * 265 key = key ^ (key >> 14); key = (key + (key << 2)) + (key << 4); // key * 21 key = key ^ (key >> 28); key = key + (key << 31); return key; } template<typename TDir, typename THashValue> inline THashValue requestDir(TDir & dir, THashValue hlen, THashValue code, THashValue code1)//, Tag<TParallelTag> parallelTag) //code:headNode, code1:pointerTobody { //std::cout << code << " " << len << std::endl; typedef unsigned long TSize; //TSize hlen = 536870913 ; //TSize hlen = 2147483649; if (hlen == 0ul) return code; TSize h1 = _hashFunction1(dir, _getHeadValue(code)); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif TSize delta = 0; (void)delta; while(dir[h1] | dir[h1+1]) { switch(code ^ dir[h1]){ case 0: return h1; case 1: return h1; default: h1 = (h1 + delta + 1) & hlen; delta++; } } dir[h1] = code; dir[h1 + 1] = code1; return h1; } /* template < typename THashValue, typename THashValue2, typename TParallelTag > inline THashValue requestBucket(BucketMap<THashValue> &bucketMap, THashValue2 code, Tag<TParallelTag> parallelTag) { //std::cout << "requestBucket "; typedef BucketMap<THashValue> TBucketMap; typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(bucketMap.qgramCode); if (hlen == 0ul) return code; TSize h1 = _hashFunction(bucketMap, code); //TSize h1 = code; #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; //h1 %= hlen; #endif // was the entry empty or occupied by our code? THashValue currentCode = atomicCas(bucketMap.qgramCode[h1], TBucketMap::EMPTY, code, parallelTag); if (currentCode == TBucketMap::EMPTY || currentCode == code) //return h1; return 1; // if not we have a collision -> probe for our code or an empty entry // // do linear probing if we need to save memory (when SEQAN_OPENADDRESSING_COMPACT is defined) // otherwise do quadratic probing to avoid clustering (Cormen 1998) TSize delta = 0; (void)delta; unsigned count = 1; do { #ifdef SEQAN_OPENADDRESSING_COMPACT h1 = (h1 + 1) % hlen; // linear probing guarantees that all entries are visited #else h1 = (h1 + delta + 1) & hlen; // for power2-sized tables the (i*i+i)/2 probing guarantees the same //h1 = (h1 + delta + 1) % hlen; ++delta; #endif currentCode = atomicCas(bucketMap.qgramCode[h1], TBucketMap::EMPTY, code, parallelTag); count++; //std::cout << h1 << " " << bucketMap.qgramCode[h1] << " " << code << std::endl; } while (currentCode != TBucketMap::EMPTY && currentCode != code); //std::cout << code << " " << bucketMap.qgramCode[h1] << std::endl; //std::cout << count << std::endl; //return h1; return count; } */ template < typename THashValue, typename THashValue2, typename TParallelTag > inline THashValue requestBucket(BucketMap<THashValue> &bucketMap, THashValue2 code, Tag<TParallelTag> parallelTag) { typedef BucketMap<THashValue> TBucketMap; typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(bucketMap.qgramCode); if (hlen == 0ul) return code; TSize h1 = _hashFunction(bucketMap, code); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif // was the entry empty or occupied by our code? THashValue currentCode = atomicCas(bucketMap.qgramCode[h1], TBucketMap::EMPTY, code, parallelTag); if (currentCode == TBucketMap::EMPTY || currentCode == code) return h1; // if not we have a collision -> probe for our code or an empty entry // // do linear probing if we need to save memory (when SEQAN_OPENADDRESSING_COMPACT is defined) // otherwise do quadratic probing to avoid clustering (Cormen 1998) TSize delta = 0; (void)delta; do { #ifdef SEQAN_OPENADDRESSING_COMPACT h1 = (h1 + 1) % hlen; // linear probing guarantees that all entries are visited #else h1 = (h1 + delta + 1) & hlen; // for power2-sized tables the (i*i+i)/2 probing guarantees the same ++delta; #endif currentCode = atomicCas(bucketMap.qgramCode[h1], TBucketMap::EMPTY, code, parallelTag); } while (currentCode != TBucketMap::EMPTY && currentCode != code); return h1; } //x-begin2: /* template <typename TDir, typename THashValue> inline THashValue getBucket(TDir const &dir,THashValue v1, THashValue v2, THashValue v3) { typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(dir); if (hlen == 0ul) return v2; TSize h1 = _hashFunction(dir, _getHeadValue(v1)); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif TSize delta = 0; (void)delta; bool flag = false; unsigned k = 1; uint64_t len, start; while(dir[h1] | dir[h1+1]) // if dir[h1]==dir[h+1]==0 then stop; { switch(v1 ^ (dir[h1])){ case 0: //len=_getBlockLength(dir[h1]); start=_getHeadValue(dir[h1]); do { if (v2 == _getBodyValue(dir[start + k])) return start + k; }while(_BlockEnd(dir[h1+k++])) return _EMPTY_NODE; case 1: v1 = v3; h1 = _hashFunction(dir, _getHeadValue(v1)); break; default: h1 = (h1 + delta + 1) & hlen; delta++; } } return _EMPTY_NODE; } */ /* // getBucket(TDir const &dir,THashValue v1, THashValue v2, THashValue v3) // { // typedef unsigned long TSize; // // get size of the index // // // check whether bucket map is disabled and // // where the hash should be found if no collision took place before // TSize hlen = length(dir); // if (hlen == 0ul) return v2; // // TSize h1 = _hashFunction(dir, v1 >> _bitValue_END); //#ifdef SEQAN_OPENADDRESSING_COMPACT // --hlen; // h1 %= hlen; //#else // hlen -= 2; // h1 &= hlen; //#endif // TSize delta = 0; // (void)delta; // // bool flag = false; // unsigned k = 1; // uint64_t len = 1; // while(dir[h1] ^ _bitEmpty) // { // switch(v1 ^ (dir[h1]) & _bitValue_END){ // case 0: // len=dir[h1+1] >> _bitLength; // while(!flag) // { // if(v2 == (dir[h1 + k] & _bitValue2)||(k > len)) // return h1 + k; // k++; // } // return h1 + 1; // case 1: // v1 = v3; // h1 = _hashFunction(dir, v1 >> _bitValue_END); // flag = true; // break; // default: // h1 = (h1 + (dir[h1] >> _bitLength_END) +delta) & hlen; // delta++; // } // } // return h1; // } */ //x-end2: template <typename TObject, unsigned TSPAN, unsigned TWEIGHT, typename TValue, typename TSpec> inline typename Value< Shape<TValue, MinimizerShape<TSPAN, TWEIGHT, TSpec> > >::Type getDir(Index<TObject, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> > const & index, Shape<TValue, MinimizerShape<TSPAN, TWEIGHT, TSpec> > const & shape) { typedef unsigned long TSize; typedef typename Value< Shape<TValue, MinimizerShape<TSPAN, TWEIGHT, TSpec> > >::Type THashValue; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before THashValue key, it; TSize hlen = index.start - 2; TSize h1 = _hashFunction1(index.dir, shape.XValue) & hlen; //if (hlen == 0ul) return index._Empty_Dir_; //#ifdef SEQAN_OPENADDRESSING_COMPACT // --hlen; // h1 %= hlen; //#else //hlen -= 2; //h1 &= hlen; //#endif TSize delta = 0; (void)delta; _setHeadNode(key,shape.XValue); while (index.dir[h1] | index.dir[h1+1]) { switch (index.dir[h1] ^ key) { case 0: it = _getHeadValue(index.dir[h1+1]); do{ if (shape.YValue == _getBodyValue(index.dir[it])) { return it; } }while(_ifBodyType(index.dir[++it])); //until the begin of next block return index._Empty_Dir_ ; case 1: _setHVlHeadNode(key, shape.hValue); h1 = _hashFunction1(index.dir, shape.hValue) & hlen; delta = 0; break; default: h1 = (h1 + delta + 1) & hlen; delta++; } } return index._Empty_Dir_; } template < typename THashValue, typename THashValue2 > inline THashValue getBucket(BucketMap<THashValue> const &bucketMap, THashValue2 code) { typedef BucketMap<THashValue> TBucketMap; typedef unsigned long TSize; // get size of the index // check whether bucket map is disabled and // where the hash should be found if no collision took place before TSize hlen = length(bucketMap.qgramCode); if (hlen == 0ul) return code; TSize h1 = _hashFunction(bucketMap, code); #ifdef SEQAN_OPENADDRESSING_COMPACT --hlen; h1 %= hlen; #else hlen -= 2; h1 &= hlen; #endif // probe for our code or an empty entry // // do linear probing if we need to save memory (when SEQAN_OPENADDRESSING_COMPACT is defined) // otherwise do quadratic probing to avoid clustering (Cormen 1998) TSize delta = 0; (void)delta; while (bucketMap.qgramCode[h1] != code && bucketMap.qgramCode[h1] != TBucketMap::EMPTY) { #ifdef SEQAN_OPENADDRESSING_COMPACT h1 = (h1 + 1) % hlen; // linear probing guarantees that all entries are visited #else h1 = (h1 + delta + 1) & hlen; // for power2-sized tables the (i*i+i)/2 probing guarantees the same ++delta; #endif } return h1; } template <typename TBucketMap> inline bool _emptyBucketMap(TBucketMap const &bucketMap) { return empty(bucketMap); } inline bool _emptyBucketMap(Nothing const &) { return false; } template <typename TObject, typename TShapeSpec> inline __int64 _fullDirLength(Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> > const &index) { typedef Index<TObject, IndexQGram<TShapeSpec, OpenAddressing> > TIndex; typedef typename Fibre<TIndex, QGramDir>::Type TDir; typedef typename Fibre<TIndex, FibreShape>::Type TShape; typedef typename Host<TShape>::Type TTextValue; typedef typename Value<TDir>::Type TDirValue; typedef typename Value<TShape>::Type THashValue; double num_qgrams = _qgramQGramCount(index) * index.alpha; double max_qgrams = pow((double)ValueSize<TTextValue>::VALUE, (double)weight(indexShape(index))); __int64 qgrams; // compare size of open adressing with 1-1 mapping and use the smaller one if (num_qgrams * (sizeof(TDirValue) + sizeof(THashValue)) < max_qgrams * sizeof(TDirValue)) { qgrams = (__int64)ceil(num_qgrams); #ifndef SEQAN_OPENADDRESSING_COMPACT __int64 power2 = 1; while (power2 < qgrams) power2 <<= 1; qgrams = power2; #endif resize(const_cast<TIndex &>(index).bucketMap.qgramCode, qgrams + 1, Exact()); } else { qgrams = (__int64)ceil(max_qgrams); clear(const_cast<TIndex &>(index).bucketMap.qgramCode); // 1-1 mapping, no bucket map needed } return qgrams + 1; } template <typename TObject, unsigned TSPAN, unsigned TWEIGHT> inline __int64 _fullDirLength(Index<TObject, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> > const &index) { typedef Index<TObject, IndexQGram<MinimizerShape<TSPAN, TWEIGHT>, OpenAddressing> > TIndex; typedef typename Fibre<TIndex, FibreShape>::Type TShape; typedef typename Host<TShape>::Type TTextValue; double num_qgrams = _qgramQGramCount(index) * index.alpha; double max_qgrams = 2*pow((double)ValueSize<TTextValue>::VALUE, (double)length(indexShape(index))); __int64 qgrams; qgrams = (__int64)ceil(num_qgrams); #ifndef SEQAN_OPENADDRESSING_COMPACT __int64 power2 = 1; while (power2 < qgrams) power2 <<= 1; qgrams = power2; #endif resize(const_cast<TIndex &>(index).bucketMap.qgramCode, qgrams + 1, Exact()); return qgrams + 1; } template <unsigned TSpan, unsigned TWeight> void _qgramClearDir(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing> > & index) { typedef Shape<Dna, MinimizerShape<TSpan, TWeight> > TM_Shape; typedef typename Value<TM_Shape>::Type HValue; resize (indexDir(index), _fullDirLength(index) + lengthSum(indexText(index)) + 2); index.start = _fullDirLength(index); index._Empty_Dir_ = 0; for (HValue k = 0; k < length(index.dir); k++) { index.dir[k] = _bitEmpty; } std::cout << " _qgramClearDir():" << std::endl; std::cout << " _fullDirLength(index) = " << _fullDirLength(index) << std::endl; std::cout << " lengh(index.dir) = " << length(index.dir) << std::endl; std::cout << " End _qgramClearDir()" << std::endl; } template <unsigned TSpan, unsigned TWeight> void _qgramCountQGrams2(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing > > & index) { typedef Shape<Dna, MinimizerShape<TSpan, TWeight> > TM_Shape; typedef Iterator<String<Dna> >::Type TIter; typedef typename Value<TM_Shape>::Type HValue; typedef std::tuple<HValue, HValue, HValue, HValue> HTuple; typedef String<HTuple> Stringtuple; TM_Shape shape; Stringtuple hs, hs1; HValue m = 0, sum = 0; double time = sysTime(); resize(hs, lengthSum(indexText(index)) - length(indexText(index)) * (shape.span - 1) + 1); std::cout << " _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; std::cout << " lengthSum(StringSet) = " << lengthSum(indexText(index)) << std::endl; for(HValue k = 0; k < length(indexText(index)); k++) { TIter it = begin(indexText(index)[k]); hashInit(shape, it); for (HValue j = 0; j < length(indexText(index)[k]) - shape.span + 1; j++) { hashNext(shape, it + j); hs[m++] = std::make_tuple(shape.XValue, shape.hValue, shape.YValue, _createSANode(k, j)); } } std::cout << " make_tuple sysTime(): " << sysTime() - time << std::endl; //hs[length(hs) - 1] = std::make_tuple((HValue)0, (HValue)0, (HValue)0, (HValue)1); std::sort(begin(hs), end(hs) - 1, [](const HTuple &a, const HTuple &b) {return (std::get<0>(a) > std::get<0>(b)||(std::get<0>(a) == std::get<0>(b) && std::get<1>(a) > std::get<1>(b)));}); hs[length(hs) - 1] = std::make_tuple((HValue)1, (HValue)1, (HValue)0, (HValue)1); std::cout << " sort sysTime(): " << sysTime() - time << " " << std::get<0>(hs[length(hs) - 2]) << " " << std::get<1>(hs[length(hs)- 2]) << std::endl; HValue countx = 1, counth = 1, tmp = 0, countdh = 0, countb = 0, hk = 0; resize(index.sa, length(hs) - 1); for (HValue k = 1; k < length(hs); k++) { index.sa[k - 1] = std::get<3>(hs[k-1]); if (std::get<1>(hs[k]) != std::get<1>(hs[k - 1])) { _setBodyNode(index.dir[index.start + hk], std::get<2>(hs[k-1]), _BodyType_code, tmp); if (std::get<0>(hs[k - 1]) == 0 && std::get<2>(hs[k - 1]) == 441204) std::cout <<"_getBodyValue = " << _getBodyValue(index.dir[index.start + hk]) << std::endl; hk++; countb++; countdh++; tmp = counth; } //else counth++; if (std::get<0>(hs[k]) != std::get<0>(hs[k - 1])) { if (countb < blocklimit) { requestDir(index.dir, index.start, _makeHeadNode(std::get<0>(hs[k-1])), _makeEmptyNode(index.start + hk - countb)); for (HValue j = 0; j < countb; j++) _setBodyType_Begin(index.dir[index.start + hk - countb]); } else { hk -= countb; requestDir(index.dir, index.start, _makeVtlHeadNode(std::get<0>(hs[k-1])), _makeEmptyNode(index.start + hk)); for (HValue j = k - countx; j < k; j++) if (std::get<1>(hs[j]) != std::get<1>(hs[j + 1])) { requestDir(index.dir, index.start, _makeHVlHeadNode(std::get<1>(hs[j])), _makeEmptyNode(index.start+hk)); _setBodyType_Begin(index.dir[index.start + hk]); hk++; } } countb = 0; countx = 1; } else { countx++; } } std::cout << std::endl; std::cout << counth << std::endl; resize(index.dir, index.start + countdh + 10); _setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyType_code, counth - 1); _setBodyType_Begin(index.dir[index.start + countdh]); index._Empty_Dir_ = index.start + countdh + 1; //_setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh]); //index._Empty_Dir_ = index.start + countdh; //_setBodyNode(index.dir[index.start + countdh + 1], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh + 1]); std::cout << " End _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; } template <unsigned TSpan, unsigned TWeight> void _qgramCountQGrams3(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing > > & index) { typedef Shape<Dna, MinimizerShape<TSpan, TWeight> > TM_Shape; typedef Iterator<String<Dna> >::Type TIter; typedef typename Value<TM_Shape>::Type HValue; typedef std::tuple<HValue, HValue, HValue> HTuple; typedef String<HTuple> Stringtuple; TM_Shape shape; Stringtuple hs, hs1; HValue m = 0, sum = 0; double time = sysTime(); resize(hs, lengthSum(indexText(index)) - length(indexText(index)) * (shape.span - 1) + 1); std::cout << " _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; std::cout << " lengthSum(StringSet) = " << lengthSum(indexText(index)) << std::endl; for(HValue k = 0; k < length(indexText(index)); k++) { TIter it = begin(indexText(index)[k]); hashInit(shape, it); for (HValue j = 0; j < length(indexText(index)[k]) - shape.span + 1; j++) { hashNext(shape, it + j); hs[m++] = std::make_tuple(shape.XValue, shape.YValue, _createSANode(k, j)); } } std::cout << " make_tuple sysTime(): " << sysTime() - time << std::endl; //hs[length(hs) - 1] = std::make_tuple((HValue)0, (HValue)0, (HValue)0, (HValue)1); std::sort(begin(hs), end(hs) - 1, [](const HTuple &a, const HTuple &b) {return (std::get<0>(a) < std::get<0>(b)||(std::get<0>(a) == std::get<0>(b) && std::get<1>(a) > std::get<1>(b)));}); hs[length(hs) - 1] = std::make_tuple((HValue)1, (HValue)0, (HValue)1); std::cout << " sort sysTime(): " << sysTime() - time << std::endl; HValue countx = 1, counth = 1, tmp = 0, countdh = 0, countb = 1, hk = 0; resize(index.sa, length(hs) - 1); for (HValue k = 1; k < length(hs); k++) { if (std::get<0>(hs[k]) ^ std::get<0>(hs[k - 1])|std::get<1>(hs[k]) ^ std::get<1>(hs[k - 1])) { _setBodyNode(index.dir[index.start + hk], std::get<1>(hs[k-1]), _BodyType_code, tmp); hk++; countb++; countdh++; tmp = counth; } if (std::get<0>(hs[k]) ^ std::get<0>(hs[k - 1])) { if (countb < blocklimit) { requestDir(index.dir, index.start, _makeHeadNode(std::get<0>(hs[k-1])), _makeEmptyNode(index.start + hk - countb)); for (HValue j = 0; j < countb; j++) _setBodyType_Begin(index.dir[index.start + hk - countb]); } else { hk -= countb; requestDir(index.dir, index.start, _makeVtlHeadNode(std::get<0>(hs[k-1])), _makeEmptyNode(index.start + hk)); for (HValue j = k - countx; j < k; j++) if ((std::get<0>(hs[j]) ^ std::get<0>(hs[j + 1])) | (std::get<1>(hs[j]) ^ std::get<1>(hs[j + 1]))) { requestDir(index.dir, index.start, _makeHVlHeadNode(xy2h(shape, std::get<0>(hs[j]),std::get<1>(hs[j]))), _makeEmptyNode(index.start+hk)); _setBodyType_Begin(index.dir[index.start + hk]); hk++; } } countb = 0; countx = 1; } else { countx++; } index.sa[k - 1] = std::get<2>(hs[k-1]); counth++; } std::cout << std::endl; std::cout << counth << std::endl; resize(index.dir, index.start + countdh + 10); _setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyType_code, counth - 1); _setBodyType_Begin(index.dir[index.start + countdh]); index._Empty_Dir_ = index.start + countdh + 1; //_setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh]); //index._Empty_Dir_ = index.start + countdh; //_setBodyNode(index.dir[index.start + countdh + 1], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh + 1]); std::cout << " End _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; } template <typename TIt> inline void _insertSort(TIt const & begin, TIt const & end ) { Pair<uint64_t, uint64_t> key; for (int j = 1; j < end - begin; j++) { key = *(begin + j); int k = j - 1; while (k >= 0) { if (((begin + k)->i2 < key.i2)) *(begin+k+1) = *(begin+k); else { break; } k--; } *(begin+k+1) = key; } } static String<Pair<unsigned, unsigned> > _SORT_PARA = {std::make_pair(8,4)};//{(8,4),(9,4),(9,4),(8,5),(8,5),(7,6),(8,6),(8,6),(8,6),(9,6)}; //weight:[16,26) inline Pair<unsigned, unsigned> _getSortPara(uint64_t shapeWeight) { return _SORT_PARA[shapeWeight - 16]; } template <typename TIt> inline void _sort3(TIt const & begin, const TIt & end, unsigned const & p_bit, unsigned const & l) { unsigned l_move = 64, r_move = 64 - p_bit; //uint64_t count[1<<p_bit]; uint64_t count[1024]; //int count[1024]; String<Pair<uint64_t, uint64_t> > output; resize(output, end - begin); for (uint64_t j = 0; j < l; j++) { l_move -= p_bit; for (int k = 0; k< (1<<p_bit); k++) count[k]=0; for (int64_t k = 0; k < end - begin; k++) count[(begin + k)->i1 << l_move >> r_move]++; for (int k = 1; k < (1 << p_bit); k++) count[k] += count[k - 1]; for (int64_t k = end - begin - 1; k >=0; k-- ) output[--count[(begin + k)->i1 << l_move >> r_move]] = *(begin + k); for (int64_t k = 0; k < end - begin; k++) *(begin + k) = output[k]; } } template <unsigned TSPAN, unsigned TWEIGHT> void _createValueArray2(StringSet<DnaString> & reads, String<Pair<uint64_t, uint64_t> > & hs, Shape<Dna, MinimizerShape<TSPAN, TWEIGHT> > & shape, int step, int l) { typedef String<Pair<uint64_t, uint64_t> > StringPair; //TShape shape; StringPair tmp; String<uint64_t> tmp3; uint64_t p = 0, q=0, c = 0, n = -1, pre = ~0, count = 0, mask = ((uint64_t)1 << 63); //std::cout << " _createValueArray() " << std::endl; double time = sysTime(); resize(tmp, lengthSum(reads) - length(reads) * (shape.span - 1)); resize(tmp3, lengthSum(reads) - length(reads) * (shape.span - 1)); for(uint64_t j = 0; j < length(reads); j++) { hashInit(shape, begin(reads[j])); for (uint64_t k = 0; k < length(reads[j]) - shape.span + 1; k++) { hashNext(shape, begin(reads[j]) + k); _setBodyNode(tmp3[p], shape.YValue, (uint64_t)1, _createSANode(j, k)); if (pre ^ shape.XValue) { tmp[q].i1 = shape.XValue; tmp[q].i2 = p; pre = shape.XValue; tmp3[p] |= mask; q++; } p++; } } resize(tmp, q); *(end(tmp3)) |= (mask); std::cout << " loading time " << sysTime() - time << std::endl; c = tmp[0].i2; p = q = count = 0; n = -1; //_sort3(begin(tmp), end(tmp), step, l); // sort parameters 1 _sort3(begin(tmp), end(tmp), _getSortPara(shape.weight).i1, _getSortPara(shape.weight).i2); // sort parameters 1 std::cout << " sort xvalue time " << sysTime() - time << std::endl; c = tmp[0].i2; for (uint64_t q = 0; q < length(hs) - 1; q++) { if (tmp3[c] & mask) { c = tmp[++n].i2; } hs[q].i1 = tmp[n].i1; hs[q].i2 = tmp3[c] & (~mask); c++; } std::cout << " xvalue expand " << sysTime() - time << std::endl; hs[length(hs)-1].i2 |= mask; pre = hs[0].i1; for (uint64_t k = 0; k < length(hs); k++) { if (pre ^ hs[k].i1) { pre = hs[k].i1; if (count < 20) // sort parameters _insertSort(begin(hs) + k - count, begin(hs) + k); else std::sort(begin(hs) + k -count, begin(hs) + k, [](Pair<uint64_t, uint64_t> & a, Pair<uint64_t, uint64_t> & b){return a.i2 > b.i2;}); count = 0; } count++; } std::cout << " End sort sysTime(): " << sysTime() - time << std::endl; } template <unsigned TSpan, unsigned TWeight> void _qgramCountQGrams(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing > > & index) { typedef Shape<Dna, MinimizerShape<TSpan, TWeight> > TM_Shape; typedef Iterator<String<Dna> >::Type TIter; typedef typename Value<TM_Shape>::Type HValue; typedef std::tuple<HValue, HValue, HValue> HTuple; typedef Pair<uint64_t, uint64_t> PairH; typedef String<PairH> StringPairH; typedef String<HTuple> StringTuple; StringSet<DnaString> reads; TM_Shape shape; StringPairH hs, hs1; HValue m = 0, sum = 0; double time = sysTime(); resize(hs, lengthSum(indexText(index)) - length(indexText(index)) * (shape.span - 1) + 1); //std::cout << " _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; //std::cout << " lengthSum(StringSet) = " << lengthSum(indexText(index)) << std::endl; _createValueArray2(indexText(index), hs, shape, 9, 5); hs[length(hs) - 1].i1 = 1; _setBodyNode(hs[length(hs) - 1].i2, (HValue)0, (HValue)0, (HValue)1);//std::make_tuple((HValue)1, (HValue)0, (HValue)1); std::cout << " sort sysTime(): " << sysTime() - time << std::endl; HValue countx = 1, counth = 1, tmp = 0, countdh = 0, countb = 0, hk = 0; resize(index.sa, length(hs) - 1); for (HValue k = 1; k < length(hs); k++) { //if (std::get<0>(hs[k]) ^ std::get<0>(hs[k - 1])|std::get<1>(hs[k]) ^ std::get<1>(hs[k - 1])) if ((hs[k].i1 ^ hs[k - 1].i1 )|(_getBodyValue(hs[k].i2 ^ hs[k - 1].i2))) { _setBodyNode(index.dir[index.start + hk], _getBodyValue(hs[k-1].i2), _BodyType_code, tmp); hk++; countb++; countdh++; tmp = counth; } if (hs[k].i1 ^ hs[k - 1].i1) { if (countb < blocklimit) { requestDir(index.dir, index.start, _makeHeadNode(hs[k-1].i1), _makeEmptyNode(index.start + hk - countb)); for (HValue j = 0; j < countb; j++) _setBodyType_Begin(index.dir[index.start + hk - countb]); } else { hk -= countb; requestDir(index.dir, index.start, _makeVtlHeadNode(hs[k-1].i1), _makeEmptyNode(index.start + hk)); for (HValue j = k - countx; j < k; j++) if ((hs[j].i1 ^ hs[j + 1].i1) | _getBodyValue(hs[j].i2 ^ hs[j + 1].i2)) { requestDir(index.dir, index.start, _makeHVlHeadNode(xy2h(shape, hs[j].i1, _getBodyValue(hs[j].i2))), _makeEmptyNode(index.start+hk)); _setBodyType_Begin(index.dir[index.start + hk]); hk++; } } countb = 0; countx = 1; } else { countx++; } index.sa[k - 1] = _getBodyCounth(hs[k-1].i2); counth++; } //std::cout << std::endl; //std::cout << counth << std::endl; resize(index.dir, index.start + countdh + 10); _setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyType_code, counth - 1); _setBodyType_Begin(index.dir[index.start + countdh]); index._Empty_Dir_ = index.start + countdh + 1; //_setBodyNode(index.dir[index.start + countdh], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh]); //index._Empty_Dir_ = index.start + countdh; //_setBodyNode(index.dir[index.start + countdh + 1], _bitEmpty, _BodyTypeEnd_code, counth - 1); //_setBodyType_Begin(index.dir[index.start + countdh + 1]); std::cout << " End _qgramCountQGrams() sysTime(): " << sysTime() - time << std::endl; } template <unsigned TSpan, unsigned TWeight> void createQGramIndexDirOnly(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing > >& index) { double time = sysTime(); //std::cout << " createQGramIndexDirOnly() sysTime(): " << std::endl; _qgramClearDir(index); _qgramCountQGrams(index); //std::cout << " End createQGramIndexDirOnly() sysTime(): " << sysTime() - time << std::endl; std::cout << sysTime() - time << std::endl; } /* template <unsigned TSpan, unsigned TWeight> void createQGramIndexDirOnly2(Index<StringSet<DnaString>, IndexQGram<MinimizerShape<TSpan, TWeight>, OpenAddressing > >& index) { double time = sysTime(); std::cout << " createQGramIndexDirOnly() sysTime(): " << std::endl; _qgramClearDir(index); _qgramCountQGrams2(index); std::cout << " index.dir[index._Empty_Dir_] = " << index.dir[index._Empty_Dir_] << std::endl << " length(index.dir) = " << length(index.dir) << std::endl; std::cout << " End createQGramIndexDirOnly() sysTime(): " << sysTime() - time << std::endl; } */ // ---------------------------------------------------------------------------- // Function open() // ---------------------------------------------------------------------------- template < typename TText, typename TShapeSpec> inline bool open(Index<TText, IndexQGram<TShapeSpec, OpenAddressing> > &index, const char *fileName, int openMode) { String<char> name; name = fileName; append(name, ".txt"); if (!open(getFibre(index, QGramText()), toCString(name), openMode)) return false; name = fileName; append(name, ".sa"); if (!open(getFibre(index, QGramSA()), toCString(name), openMode)) return false; name = fileName; append(name, ".dir"); if (!open(getFibre(index, QGramDir()), toCString(name), openMode)) return false; name = fileName; append(name, ".bkt"); if (!open(getFibre(index, QGramBucketMap()).qgramCode, toCString(name), openMode)) return false; return true; } template <typename TText, typename TShapeSpec> inline bool open(Index<TText, IndexQGram<TShapeSpec, OpenAddressing> > &index, const char *fileName) { return open(index, fileName, OPEN_RDONLY); } // ---------------------------------------------------------------------------- // Function save() // ---------------------------------------------------------------------------- template <typename TText, typename TShapeSpec> inline bool save(Index<TText, IndexQGram<TShapeSpec, OpenAddressing> > &index, const char *fileName, int openMode) { String<char> name; name = fileName; append(name, ".txt"); if (!save(getFibre(index, QGramText()), toCString(name), openMode)) return false; name = fileName; append(name, ".sa"); if (!save(getFibre(index, QGramSA()), toCString(name), openMode)) return false; name = fileName; append(name, ".dir"); if (!save(getFibre(index, QGramDir()), toCString(name), openMode)) return false; name = fileName; append(name, ".bkt"); if (!save(getFibre(index, QGramBucketMap()).qgramCode, toCString(name), openMode)) return false; return true; } template <typename TText, typename TShapeSpec> inline bool save(Index<TText, IndexQGram<TShapeSpec, OpenAddressing> > &index, const char *fileName) { return save(index, fileName, OPEN_WRONLY | OPEN_CREATE); } } #endif //#ifndef SEQAN_HEADER_...
38.532852
172
0.550327
[ "shape" ]
aa3214828c7b18bba681e176d69f32e7d99d59d2
4,573
h
C
board/MK3080B/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
3
2019-04-04T09:29:58.000Z
2019-06-26T10:15:44.000Z
board/MK3080B/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
1
2019-10-28T20:17:19.000Z
2019-10-28T20:17:19.000Z
board/MK3080B/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
2
2019-04-13T02:27:51.000Z
2021-08-01T21:54:21.000Z
/** ****************************************************************************** * @file platform_config.h * @author William Xu * @version V1.0.0 * @date 05-Oct-2016 * @brief This file provides common configuration for current platform. ****************************************************************************** * * The MIT License * Copyright (c) 2014 MXCHIP 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 __MXOS_BOARD_CONF_H__ #define __MXOS_BOARD_CONF_H__ /****************************************************** * Macros ******************************************************/ /****************************************************** * Constants ******************************************************/ #define HARDWARE_REVISION "3080B" #define DEFAULT_NAME "EMW3080B Module" #define MODEL "EMW3080B" /* MXOS RTOS tick rate in Hz */ #define MXOS_DEFAULT_TICK_RATE_HZ (1000) /************************************************************************ * Uncomment to disable watchdog. For debugging only */ #define MXOS_DISABLE_WATCHDOG /************************************************************************ * Uncomment to disable standard IO, i.e. printf(), etc. */ //#define MXOS_DISABLE_STDIO /************************************************************************ * Uncomment to disable MCU powersave API functions */ //#define MXOS_DISABLE_MCU_POWERSAVE /************************************************************************ * Uncomment to enable MCU real time clock */ #define MXOS_ENABLE_MCU_RTC /************************************************************************ * Restore default and start easylink after press down EasyLink button for 3 seconds. */ #define RestoreDefault_TimeOut (3000) /************************************************************************ * CPU clock */ #define MCU_CLOCK_HZ (125000000) /************************************************************************ * How many bits are used in NVIC priority configuration */ #define CORTEX_NVIC_PRIO_BITS (4) /************************************************************************ * Enable write protection to write-disabled embedded flash sectors */ //#define MCU_ENABLE_FLASH_PROTECT /************************************************************************ * Platform provide OTA temporary partition as secondary application partition */ //#define MXOS_ENABLE_SECONDARY_APPLICATION /************************************************************************ * Support Easylink&softap mode */ #define PLATFORM_CONFIG_EASYLINK_SOFTAP_COEXISTENCE 1 /****************************************************** * Enumerations ******************************************************/ /****************************************************** * Type Definitions ******************************************************/ /****************************************************** * Structures ******************************************************/ /****************************************************** * Global Variables ******************************************************/ /****************************************************** * Function Declarations ******************************************************/ #endif
40.830357
88
0.437131
[ "model" ]
aa357c6ae72c92bec1440078362c3d6fa434d94a
2,437
h
C
sources/Include/GCodeController.h
RoboLabHub/RoboDog_v3
fbb5a0af437bcb052eeace2f8dad04a81746972c
[ "MIT" ]
3
2020-10-27T00:18:24.000Z
2021-09-01T18:24:45.000Z
sources/Include/GCodeController.h
RoboLabHub/RoboDog_v3
fbb5a0af437bcb052eeace2f8dad04a81746972c
[ "MIT" ]
null
null
null
sources/Include/GCodeController.h
RoboLabHub/RoboDog_v3
fbb5a0af437bcb052eeace2f8dad04a81746972c
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////// // MIT License // // Copyright (c) 2020 RoboLab19 // // 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 <map> #include <vector> #include <memory> #include "Leg.h" #include "IK.h" #include "Robot.h" #define SET_DEF_PARAM(id, val) if (paramsInt.find(id) == paramsInt.end()) paramsInt[id] = val; class BaseState; class GCodeController // Interface { public: struct MovePoint { int legId; double p[3]; int moveTime; }; typedef std::map<uint8_t, std::shared_ptr<Leg>> RobotLegs; virtual void reset() = 0; virtual bool run(const std::string gcode, bool simulate = false) = 0; virtual bool do_move(bool simulate) = 0; virtual bool run_from_file(const std::string& file) = 0; virtual void say(const std::string& lang, const std::string& text) = 0; virtual bool add_point(int legId, IK::Vector pos, int moveTime) = 0; virtual bool look_at(IK::Vector vec) = 0; virtual int GetSpeedInPercent() = 0; virtual void SetSpeedInPercent(int speed) = 0; virtual RobotLegs GetLegs() = 0; virtual BaseState* GetBaseState() = 0; virtual Robot* GetRobot() = 0; virtual ros::Time GetMoveFinishTime() = 0; virtual IK::Vector get_rot() = 0; };
33.847222
94
0.660648
[ "vector" ]
aa3713c0c673e479c7ee62b8668ed4fb0964fc05
8,953
c
C
Source/OTPersistent.c
cloudr-app/libopenTIDAL
89a1eaa4f842471fe0e0ae194b5976a0c243a9f0
[ "MIT" ]
9
2021-01-29T09:04:36.000Z
2021-11-13T06:44:56.000Z
Source/OTPersistent.c
cloudr-app/libopenTIDAL
89a1eaa4f842471fe0e0ae194b5976a0c243a9f0
[ "MIT" ]
1
2020-12-18T22:40:46.000Z
2020-12-19T11:02:05.000Z
Source/OTPersistent.c
openTIDAL/libopenTIDAL
89a1eaa4f842471fe0e0ae194b5976a0c243a9f0
[ "MIT" ]
null
null
null
/* Copyright (c) 2020-2021 Hugo Melder and openTIDAL contributors 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. */ /* openTIDAL persistent storage helper */ #include <stdio.h> #include <stdlib.h> #include "OTJson.h" #include "openTIDAL.h" /* Predeclare function prototype. */ static char *OTPersistentStream (const struct OTSessionContainer *const session); /* Create a file handle and create the persistent config. */ int OTPersistentCreate (const struct OTSessionContainer *const session, const char *const location) { if (location) { FILE *fp; char *stream; if (session->verboseMode) fprintf (stderr, "* Create file-handle and create config at location.\n"); fp = fopen (location, "w"); if (!fp) return -1; if (session->verboseMode) fprintf (stderr, "* Create json stream.\n"); stream = OTPersistentStream (session); if (!stream) { if (session->verboseMode) fprintf (stderr, "* Failed to create json stream. Aborting...\n"); fclose (fp); return -1; } fprintf (fp, "%s", stream); free (stream); fclose (fp); } else return -1; return 0; } /* Create a stream with the values in the OTSessionContainer. * Returns a heap allocated string, free it after use! */ static char * OTPersistentStream (const struct OTSessionContainer *const session) { char *ptr = NULL; struct OTJsonContainer *authorisation = NULL; struct OTJsonContainer *accessToken = NULL; struct OTJsonContainer *refreshToken = NULL; struct OTJsonContainer *expiresIn = NULL; struct OTJsonContainer *timeFrame = NULL; struct OTJsonContainer *user = NULL; struct OTJsonContainer *id = NULL; struct OTJsonContainer *countryCode = NULL; struct OTJsonContainer *locale = NULL; struct OTJsonContainer *audioQuality = NULL; struct OTJsonContainer *videoQuality = NULL; /* Create json root object. */ struct OTJsonContainer *json = OTJsonCreateObject (); if (!json) goto end; /* Create json objects. */ authorisation = OTJsonCreateObject (); user = OTJsonCreateObject (); if (!authorisation || !user) goto end; /* If successful, the ownership of the pointer is transferred * to the OTJsonContainer */ OTJsonAddItemToObject (json, "authorisation", authorisation); OTJsonAddItemToObject (json, "user", user); /* Create json values. */ if (session->accessToken) { accessToken = OTJsonCreateString (session->accessToken); if (!accessToken) goto end; OTJsonAddItemToObject (authorisation, "accessToken", accessToken); } if (session->refreshToken) { refreshToken = OTJsonCreateString (session->refreshToken); if (!refreshToken) goto end; OTJsonAddItemToObject (authorisation, "refreshToken", refreshToken); } if (session->expiresIn) { expiresIn = OTJsonCreateNumber (session->expiresIn); if (!expiresIn) goto end; OTJsonAddItemToObject (authorisation, "expiresIn", expiresIn); } if (session->timeFrame) { timeFrame = OTJsonCreateNumber (session->timeFrame); if (!timeFrame) goto end; OTJsonAddItemToObject (authorisation, "timeFrame", timeFrame); } if (session->userId) { id = OTJsonCreateString (session->userId); if (!id) goto end; OTJsonAddItemToObject (user, "id", id); } if (session->countryCode) { countryCode = OTJsonCreateString (session->countryCode); if (!countryCode) goto end; OTJsonAddItemToObject (user, "countryCode", countryCode); } if (session->locale) { locale = OTJsonCreateString (session->locale); if (!locale) goto end; OTJsonAddItemToObject (user, "locale", locale); } if (session->audioQuality) { audioQuality = OTJsonCreateString (session->audioQuality); if (!audioQuality) goto end; OTJsonAddItemToObject (user, "audioQuality", audioQuality); } if (session->videoQuality) { videoQuality = OTJsonCreateString (session->videoQuality); if (!videoQuality) goto end; OTJsonAddItemToObject (user, "videoQuality", videoQuality); } /* Allocate json in heap. */ ptr = OTJsonPrint (json); end: OTJsonDelete (json); return ptr; } /* Create a file handle and allocate the contents of * the config file. * Returns a heap allocated string, free it after use! */ char * OTPersistentLoad (const struct OTSessionContainer *const session) { if (session->persistentFileLocation) { FILE *fp; size_t size = 0; char *ptr = NULL; fp = fopen (session->persistentFileLocation, "r"); if (!fp) return NULL; fseek (fp, 0L, SEEK_END); size = ftell (fp); rewind (fp); /* Allocate memory for entire content. */ ptr = malloc (size + 1); if (!ptr) { fclose (fp); return NULL; } if (1 != fread (ptr, size, 1, fp)) { fclose (fp); free (ptr); return NULL; } fclose (fp); return ptr; } return NULL; } /* Points the session->tree value to the * allocated OTJsonContainer. Free it after use! */ int OTPersistentParse (struct OTSessionContainer *const session, const char *stream) { int status = 0; const struct OTJsonContainer *authorisation = NULL; const struct OTJsonContainer *user = NULL; struct OTJsonContainer *json = OTJsonParse (stream); if (!json) { if (session->verboseMode) fprintf (stderr, "* Parsing configuration stream failed.\n"); status = -1; goto end; } /* Parse values. */ authorisation = OTJsonGetObjectItem (json, "authorisation"); user = OTJsonGetObjectItem (json, "user"); if (!authorisation || !user) { status = -1; goto end; } session->accessToken = OTJsonGetObjectItemStringValue (authorisation, "accessToken"); if (!session->accessToken) { status = -1; goto end; } session->refreshToken = OTJsonGetObjectItemStringValue (authorisation, "refreshToken"); if (!session->refreshToken) { status = -1; goto end; } session->expiresIn = OTJsonGetObjectItemNumberValue (authorisation, "expiresIn"); session->timeFrame = OTJsonGetObjectItemNumberValue (authorisation, "timeFrame"); session->userId = OTJsonGetObjectItemStringValue (user, "id"); if (!session->userId) { status = -1; goto end; } session->countryCode = OTJsonGetObjectItemStringValue (user, "countryCode"); if (!session->countryCode) { status = -1; goto end; } session->locale = OTJsonGetObjectItemStringValue (user, "locale"); session->audioQuality = OTJsonGetObjectItemStringValue (user, "audioQuality"); session->videoQuality = OTJsonGetObjectItemStringValue (user, "videoQuality"); /* Delete old tree. */ OTJsonDelete (session->tree); session->tree = json; end: if (status == -1) { OTJsonDelete (json); fprintf (stderr, "* Aborting configuration stream parsing...\n"); } return status; }
33.282528
99
0.605272
[ "object" ]
aa3855c9009d513378c6b6696d80870f0bc20141
53,683
c
C
xgks/src/lib/metafile.c
josborne-noaa/Ferret
ee1e694c5eebafd559b5887930ec4091ef3f4583
[ "Unlicense" ]
48
2016-03-18T22:05:39.000Z
2022-01-29T20:34:09.000Z
xgks/src/lib/metafile.c
josborne-noaa/Ferret
ee1e694c5eebafd559b5887930ec4091ef3f4583
[ "Unlicense" ]
1,974
2017-11-21T20:59:45.000Z
2022-02-08T01:35:30.000Z
xgks/src/lib/metafile.c
josborne-noaa/Ferret
ee1e694c5eebafd559b5887930ec4091ef3f4583
[ "Unlicense" ]
21
2016-03-18T22:28:55.000Z
2021-03-15T10:52:11.000Z
/* * This file contains the interface to the metafile implementations of XGKS. * It is mostly a "switching" interface in that it does little work itself, * but rather calls a specific metafile implementation that does the actual * work. Currently, two types of metafile implementations are available: * GKSM and CGM. For historical reasons, the default is GKSM. * * Copyright (C) 1991 UCAR/Unidata * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose without fee is hereby granted, provided * that the above copyright notice appear in all copies, that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of UCAR/Unidata not be used in * advertising or publicity pertaining to distribution of the software * without specific, written prior permission. UCAR makes no * representations about the suitability of this software for any purpose. * It is provided "as is" without express or implied warranty. It is * provided with no support and without obligation on the part of UCAR or * Unidata, to assist in its use, correction, modification, or enhancement. * */ /* * Mod *jd* 6.15.94 to fix bug in number of metafile ws colors available. * It was 16, now is 256. */ /* Fixed bug below for linux port (received 'warning') *jd* 1.28.97 * define MO_SET_SEG_DETECTmf, num, name, det) <-- original * define MO_SET_SEG_DETECT(mf, num, name, det) <-- fix */ /* * Modified by Joe Sirott, Pacific Marine Environmental Lab * Added support for PostScript and GIF metafile output. * Also, changed prototypes from K&R to ANSI C. * * all macros that call SEL_FUNC must call it with metafile *, not * metafile** *js* 8.97 */ #define MAX_META_WSCOLOURS 256 /*LINTLIBRARY*/ #include <wchar.h> #include <stdlib.h> #include <time.h> /* for time(), localtime(), and strftime() */ #include <sys/types.h> /* for uid_t */ #include <unistd.h> /* for getuid() & getlogin() */ #include <string.h> #include <math.h> #include <ctype.h> #include <assert.h> #include "udposix.h" #include "gks_implem.h" #include "gksm/gksm.h" #include "cgm/cgm.h" #include "ps/ps.h" #include "gif/gif.h" #ifndef lint static char rcsid[] = "$Id$"; static char afsid[] = "$__Header$"; #endif #define NOTSUPPORTED(type) (type==6 || type==16) /* * List of active output Metafiles: */ static int num_cgmo; static int num_gksmo; static int num_psmo; static int num_gifmo; static Metafile active_cgmo[MAX_ACTIVE_WS]; static Metafile active_gksmo[MAX_ACTIVE_WS]; static Metafile active_psmo[MAX_ACTIVE_WS]; static Metafile active_gifmo[MAX_ACTIVE_WS]; typedef int (*INT_PROC)(); /* * Keep in old K&R C to avoid painfu, picky function prototyping requirements * of MIPS c compiler */ static INT_PROC SEL_FUNC(mf, gksm, cgm, ps, gif) Metafile *mf; INT_PROC gksm; INT_PROC cgm; INT_PROC ps; INT_PROC gif; { switch(mf->any->type){ case MF_GKSM: return gksm; case MF_PS: return ps; case MF_CGM: return cgm; case MF_GIF: return gif; default: return 0; } } static INT_PROC emptyProc(void) { return (INT_PROC)0; } /* * The following are macros that expand to the appropriate type of metafile * function (i.e. either GKSM or CGM or PostScript). * * This allows the metafile functions to be chosen at the time of metafile * creation */ #define MO_CELL_ARRAY(mf, num, ll, ur, lr, row, colour, dim) \ SEL_FUNC(mf, (INT_PROC)GMcellArray, (INT_PROC)CGMcellArray, \ (INT_PROC)PScellArray, (INT_PROC)GIFcellArray)\ (mf, num, ll, ur, lr, row, colour, dim) #define MO_CLEAR(mf, num, flag) \ SEL_FUNC(mf, (INT_PROC)GMclear, (INT_PROC)CGMclear, (INT_PROC)PSclear, (INT_PROC)GIFclear)(mf, num, flag) #define MO_CLOSE(mf) \ SEL_FUNC(mf, (INT_PROC)GMmoClose, (INT_PROC)CGMmoClose, (INT_PROC)PSmoClose, (INT_PROC)GIFmoClose)(mf, batmode) #define MO_CLOSE_SEG(mf, num) \ SEL_FUNC(mf, (INT_PROC)GMcloseSeg, (INT_PROC)CGMcloseSeg, (INT_PROC)PScloseSeg, (INT_PROC)GIFcloseSeg)(mf, num) #define MO_DEFER(mf, num, defer_mode, regen_mode) \ SEL_FUNC(mf, (INT_PROC)GMdefer, (INT_PROC)CGMdefer, (INT_PROC)PSdefer, (INT_PROC)GIFdefer)(mf, num, defer_mode, regen_mode) #define MI_GET_NEXT_ITEM(mf) \ SEL_FUNC(mf, (INT_PROC)GMnextItem, (INT_PROC)CGMnextItem, emptyProc, emptyProc)(mf) #define MO_MESSAGE(mf, num, string) \ SEL_FUNC(mf, (INT_PROC)GMmessage, (INT_PROC)CGMmessage, (INT_PROC)PSmessage, (INT_PROC)GIFmessage)(mf, num, string) #define MI_OPEN(mf) \ SEL_FUNC(mf, (INT_PROC)GMmiOpen, (INT_PROC)CGMmiOpen, emptyProc, emptyProc) #define MO_OPEN(mf) \ SEL_FUNC(mf, (INT_PROC)GMmoOpen, (INT_PROC)CGMmoOpen, (INT_PROC)PSmoOpen, (INT_PROC)GIFmoOpen)(mf) #define MI_CLOSE(mf) \ SEL_FUNC(mf, GMmiClose, CGMmiClose(mf), emptyProc, emptyProc)(mf) #define MI_READ_ITEM(mf, record) \ SEL_FUNC(mf, (INT_PROC)GMreadItem, (INT_PROC)CGMreadItem, emptyProc, emptyProc)(mf, record) #define MO_REDRAW_ALL_SEG(mf, num) \ SEL_FUNC(mf, (INT_PROC)GMredrawAllSeg, (INT_PROC)CGMredrawAllSeg, (INT_PROC)PSredrawAllSeg, (INT_PROC)GIFredrawAllSeg)(mf, num) #define MO_RENAME_SEG(mf, num, old, new) \ SEL_FUNC(mf, (INT_PROC)GMrenameSeg, (INT_PROC)CGMrenameSeg, (INT_PROC)PSrenameSeg, (INT_PROC)GIFrenameSeg)(mf, num, old, new) #define MO_SET_ASF(mf, num) \ SEL_FUNC(mf, (INT_PROC)GMsetAsf, (INT_PROC)CGMsetAsf, (INT_PROC)PSsetAsf, (INT_PROC)GIFsetAsf)(mf, num) #define MO_SET_CHAR_UP(mf, num, up, base) \ SEL_FUNC(mf, (INT_PROC)GMsetCharUp, (INT_PROC)CGMsetCharUp, (INT_PROC)PSsetCharUp, (INT_PROC)GIFsetCharUp)(mf, num, up, base) #define MO_SET_CLIPPING(mf, num, rect) \ SEL_FUNC(mf, (INT_PROC)GMsetClip, (INT_PROC)CGMsetClip, (INT_PROC)PSsetClip, (INT_PROC)GIFsetClip)(mf, num, rect) #define MO_SET_COLOUR_REP(mf, num, idx, rep) \ SEL_FUNC(mf, (INT_PROC)GMsetColRep, (INT_PROC)CGMsetColRep, (INT_PROC)PSsetColRep, (INT_PROC)GIFsetColRep)(mf, num, idx, rep) #define MO_SET_FILL_REP(mf, num, idx, rep) \ SEL_FUNC(mf, (INT_PROC)GMsetFillRep, (INT_PROC)CGMsetFillRep, (INT_PROC)PSsetFillRep, (INT_PROC)GIFsetFillRep)(mf, num, idx, rep) #define MO_SET_FILL_STYLE(mf, num, style) \ SEL_FUNC(mf, (INT_PROC)GMsetFillStyle, (INT_PROC)CGMsetFillStyle, (INT_PROC)PSsetFillStyle, (INT_PROC)GIFsetFillStyle)(mf, num, style) #define MO_SET_GRAPH_SIZE(mf, num, code, size) \ SEL_FUNC(mf, (INT_PROC)GMsetGraphSize, (INT_PROC)CGMsetGraphSize, (INT_PROC)PSsetGraphSize, (INT_PROC)GIFsetGraphSize)(mf, num, code, size) #define MO_SET_GRAPH_ATTR(mf, num, code, attr) \ SEL_FUNC(mf, (INT_PROC)GMsetGraphAttr, (INT_PROC)CGMsetGraphAttr, (INT_PROC)PSsetGraphAttr, (INT_PROC)GIFsetGraphAttr)(mf, num, code, attr) #define MO_SET_LIMIT(mf, num, code, rect) \ SEL_FUNC(mf, (INT_PROC)GMsetLimit, (INT_PROC)CGMsetLimit, (INT_PROC)PSsetLimit, (INT_PROC)GIFsetLimit)(mf, num, code, rect) #define MO_SET_LINE_MARKER_REP(mf, num, code, idx, type, size, colour) \ SEL_FUNC(mf, (INT_PROC)GMsetLineMarkRep, (INT_PROC)CGMsetLineMarkRep, (INT_PROC)PSsetLineMarkRep, (INT_PROC)GIFsetLineMarkRep)\ (mf, num, code, idx, type, size, colour) #define MO_SET_PATTERN_REFPT(mf, num) \ SEL_FUNC(mf, (INT_PROC)GMsetPatRefpt, (INT_PROC)CGMsetPatRefpt, (INT_PROC)PSsetPatRefpt, (INT_PROC)GIFsetPatRefpt)(mf, num) #define MO_SET_PATTERN_REP(mf, num, idx, rep) \ SEL_FUNC(mf, (INT_PROC)GMsetPatRep, (INT_PROC)CGMsetPatRep, (INT_PROC)PSsetPatRep, (INT_PROC)GIFsetPatRep)(mf, num, idx, rep) #define MO_SET_PATTERN_SIZE(mf, num) \ SEL_FUNC(mf, (INT_PROC)GMsetPatSize, (INT_PROC)CGMsetPatSize, (INT_PROC)PSsetPatSize, (INT_PROC)GIFsetPatSize)(mf, num) #define MO_SET_SEG_ATTR(mf, num, name, code, attr) \ SEL_FUNC(mf, (INT_PROC)GMsetSegAttr, (INT_PROC)CGMsetSegAttr, (INT_PROC)PSsetSegAttr, (INT_PROC)GIFsetSegAttr)(mf, num, name, code, attr) #define MO_SET_SEG_DETECT(mf, num, name, det) \ SEL_FUNC(mf, (INT_PROC)GMsetSegDetect, (INT_PROC)CGMsetSegDetect, (INT_PROC)PSsetSegDetect, (INT_PROC)GIFsetSegDetect)(mf, num, name, det) #define MO_SET_SEG_HILIGHT(mf, num, name, hilight) \ SEL_FUNC(mf, (INT_PROC)GMsetSegHilight, (INT_PROC)CGMsetSegHilight, (INT_PROC)PSsetSegHilight, (INT_PROC)GIFsetSegHilight\ (mf, num, name, hilight)) #define MO_SET_SEG_PRI(mf, num, name, pri) \ SEL_FUNC(mf, (INT_PROC)GMsetSegPri, (INT_PROC)CGMsetSegPri, (INT_PROC)PSsetSegPri, (INT_PROC)GIFsetSegPri)(mf, num, name, pri) #define MO_SET_SEG_TRANS(mf, num, name, matrix) \ SEL_FUNC(mf, (INT_PROC)GMsetSegTran, (INT_PROC)CGMsetSegTran, (INT_PROC)PSsetSegTran, (INT_PROC)GIFsetSegTran)(mf, num, name, matrix) #define MO_SET_SEG_VIS(mf, num, name, vis) \ SEL_FUNC(mf, (INT_PROC)GMsetSegVis, (INT_PROC)CGMsetSegVis, (INT_PROC)PSsetSegVis, (INT_PROC)GIFsetSegVis)(mf, num, name, vis) #define MO_SET_TEXT_ALIGN(mf, num, align) \ SEL_FUNC(mf, (INT_PROC)GMsetTextAlign, (INT_PROC)CGMsetTextAlign, (INT_PROC)PSsetTextAlign, (INT_PROC)GIFsetTextAlign)(mf, num, align) #define MO_SET_TEXT_FP(mf, num, txfp) \ SEL_FUNC(mf, (INT_PROC)GMsetTextFP, (INT_PROC)CGMsetTextFP, (INT_PROC)PSsetTextFP, (INT_PROC)GIFsetTextFP)(mf, num, txfp) #define MO_SET_TEXT_PATH(mf, num, path) \ SEL_FUNC(mf, (INT_PROC)GMsetTextPath, (INT_PROC)CGMsetTextPath, (INT_PROC)PSsetTextPath, (INT_PROC)GIFsetTextPath)(mf, num, path) #define MO_SET_TEXT_REP(mf, num, idx, rep) \ SEL_FUNC(mf, (INT_PROC)GMsetTextRep, (INT_PROC)CGMsetTextRep, (INT_PROC)PSsetTextRep, (INT_PROC)GIFsetTextRep)(mf, num, idx, rep) #define MO_UPDATE(mf, num, regenflag) \ SEL_FUNC(mf, (INT_PROC)GMupdate, (INT_PROC)CGMupdate, (INT_PROC)PSupdate, (INT_PROC)GIFupdate)(mf, num, regenflag) #define MO_GRAPHIC(mf, num, code, num_pt, pos) \ SEL_FUNC(mf, (INT_PROC)GMoutputGraphic, (INT_PROC)CGMoutputGraphic, (INT_PROC)PSoutputGraphic, (INT_PROC)GIFoutputGraphic)\ (mf, num, code, num_pt, pos) #define MO_WRITE_ITEM(mf, num, type, length, data) \ SEL_FUNC(mf, (INT_PROC)GMwriteItem, (INT_PROC)CGMwriteItem, emptyProc, emptyProc)(mf, num, type, length, data) #define MO_TEXT(mf, num, at, string) \ SEL_FUNC(mf, (INT_PROC)GMtext, (INT_PROC)CGMtext, (INT_PROC)PStext, (INT_PROC)GIFtext)(mf, num, at, string) /* * Execute the data contained in a Metafile item. */ static Gint XgksExecData(Gint type, char *record) { XGKSMONE *ptr1; XGKSMTWO *ptr2; XGKSMMESG *msg; XGKSMGRAPH *graph; XGKSMTEXT *text; XGKSMSIZE *size; XGKSMCHARVEC *vec; XGKSMASF *asf; XGKSMLMREP *lmrep; XGKSMTEXTREP *txrep; XGKSMFILLREP *flrep; XGKSMPATREP *patrep; XGKSMCOLOURREP *corep; XGKSMLIMIT *limit; XGKSMSEGTRAN *tran; XGKSMSEGPRI *pri; XGKSMCELLARRAY *cell; XGKSMPATREF *patref; XGKSMPATSIZ *patsiz; OUT_PRIMI *primi; Gtxpath path; Gflinter inter; Gdefmode defmode; Gtxfp txfp; Gsegattr segattr; Gtxalign txalign; Glnbundl lnrep; Gmkbundl mkrep; Gtxbundl textrep; Gflbundl fillrep; Gptbundl ptrep; Gcobundl colourrep; Gasfs asfs; Gint cnt, i, j; Gpoint *pts; Gpoint siz; Gfloat height; switch (type) { case 0: break; case 2: /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gredrawsegws(xgks_state.activews[cnt].ws_id); } } } break; case 82: /* * only need to call gcloseseg() once, not for each workstation */ (void) gcloseseg(); break; case 1: ptr1 = (XGKSMONE *) record; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { (void) gclearws(xgks_state.activews[cnt].ws_id, (ptr1->flag == 0 ? GCONDITIONALLY : GALWAYS)); } } break; case 3: ptr1 = (XGKSMONE *) record; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gupdatews(xgks_state.activews[cnt].ws_id, (ptr1->flag == 0 ? GPERFORM : GPOSTPONE)); } } } break; case 21: ptr1 = (XGKSMONE *) record; (void) gsetlineind(ptr1->flag); break; case 22: ptr1 = (XGKSMONE *) record; (void) gsetlinetype(ptr1->flag); break; case 24: ptr1 = (XGKSMONE *) record; (void) gsetlinecolourind(ptr1->flag); break; case 25: ptr1 = (XGKSMONE *) record; (void) gsetmarkerind(ptr1->flag); break; case 26: ptr1 = (XGKSMONE *) record; (void) gsetmarkertype(ptr1->flag); break; case 28: ptr1 = (XGKSMONE *) record; (void) gsetmarkercolourind(ptr1->flag); break; case 29: ptr1 = (XGKSMONE *) record; (void) gsettextind(ptr1->flag); break; case 33: ptr1 = (XGKSMONE *) record; (void) gsettextcolourind(ptr1->flag); break; case 35: ptr1 = (XGKSMONE *) record; if (ptr1->flag == 0) path = GTP_RIGHT; else if (ptr1->flag == 1) path = GTP_LEFT; else if (ptr1->flag == 2) path = GTP_UP; else path = GTP_DOWN; (void) gsettextpath(path); break; case 37: ptr1 = (XGKSMONE *) record; (void) gsetfillind(ptr1->flag); break; case 38: ptr1 = (XGKSMONE *) record; if (ptr1->flag == 0) inter = GHOLLOW; else if (ptr1->flag == 1) inter = GSOLID; else if (ptr1->flag == 2) inter = GPATTERN; else inter = GHATCH; (void) gsetfillintstyle(inter); break; case 39: ptr1 = (XGKSMONE *) record; (void) gsetfillstyleind(ptr1->flag); break; case 40: ptr1 = (XGKSMONE *) record; (void) gsetfillcolourind(ptr1->flag); break; case 41: patsiz = (XGKSMPATSIZ *) record; siz.x = patsiz->wid.x; siz.y = patsiz->hgt.y; (void) gsetpatsize(&siz); break; case 42: patref = (XGKSMPATREF *) record; (void) gsetpatrefpt(&patref->ref); break; case 44: ptr1 = (XGKSMONE *) record; (void) gsetpickid(ptr1->flag); break; case 81: ptr1 = (XGKSMONE *) record; (void) gcreateseg(ptr1->flag); break; case 84: ptr1 = (XGKSMONE *) record; (void) gdelseg(ptr1->flag); break; case 4: ptr2 = (XGKSMTWO *) record; if (ptr2->item1 == 0) defmode = GASAP; else if (ptr2->item1 == 1) defmode = GBNIG; else if (ptr2->item1 == 2) defmode = GBNIL; else defmode = GASTI; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetdeferst(xgks_state.activews[cnt].ws_id, defmode, (ptr2->item2 == 0 ? GALLOWED : GSUPPRESSED)); } } } break; case 30: ptr2 = (XGKSMTWO *) record; txfp.font = ptr2->item1; if (ptr2->item2 == 0) txfp.prec = GSTRING; else if (ptr2->item2 == 1) txfp.prec = GCHAR; else txfp.prec = GSTROKE; (void) gsettextfontprec(&txfp); break; case 36: ptr2 = (XGKSMTWO *) record; if (ptr2->item1 == 0) txalign.hor = GTH_NORMAL; else if (ptr2->item1 == 1) txalign.hor = GTH_LEFT; else if (ptr2->item1 == 2) txalign.hor = GTH_CENTRE; else txalign.hor = GTH_RIGHT; if (ptr2->item2 == 0) txalign.ver = GTV_NORMAL; else if (ptr2->item2 == 1) txalign.ver = GTV_TOP; else if (ptr2->item2 == 2) txalign.ver = GTV_CAP; else if (ptr2->item2 == 3) txalign.ver = GTV_HALF; else if (ptr2->item2 == 4) txalign.ver = GTV_BASE; else txalign.ver = GTV_BOTTOM; (void) gsettextalign(&txalign); break; case 83: ptr2 = (XGKSMTWO *) record; (void) grenameseg(ptr2->item1, ptr2->item2); break; case 92: ptr2 = (XGKSMTWO *) record; segattr.seg = ptr2->item1; (void) ginqsegattr(&segattr); segattr.vis = (ptr2->item2 == 0 ? GVISIBLE : GINVISIBLE); (void) gsetsegattr(ptr2->item1, &segattr); break; case 93: ptr2 = (XGKSMTWO *) record; segattr.seg = ptr2->item1; (void) ginqsegattr(&segattr); segattr.hilight = (ptr2->item2 == 0 ? GNORMAL : GHIGHLIGHTED); (void) gsetsegattr(ptr2->item1, &segattr); break; case 95: ptr2 = (XGKSMTWO *) record; segattr.seg = ptr2->item1; (void) ginqsegattr(&segattr); segattr.det = (ptr2->item2 == 0 ? GUNDETECTABLE : GDETECTABLE); (void) gsetsegattr(ptr2->item1, &segattr); break; case 5: msg = (XGKSMMESG *) record; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gmessage(xgks_state.activews[cnt].ws_id, msg->string); } } } break; case 11: graph = (XGKSMGRAPH *) record; GKSERROR(((pts = (Gpoint*)malloc((size_t) (graph->num_pts* sizeof(Gpoint)))) == NULL), 300, errXgksExecData); for (i = 0; i < graph->num_pts; i++) NdcToWc(&(graph->pts[i]), &(pts[i])); (void) gpolyline(graph->num_pts, pts); ufree((voidp)pts); break; case 12: graph = (XGKSMGRAPH *) record; GKSERROR(((pts = (Gpoint *) malloc((size_t) (graph->num_pts * sizeof(Gpoint)))) == NULL), 300, errXgksExecData); for (i = 0; i < graph->num_pts; i++) NdcToWc(&(graph->pts[i]), &(pts[i])); (void) gpolymarker(graph->num_pts, pts); ufree((voidp)pts); break; case 14: graph = (XGKSMGRAPH *) record; GKSERROR(((pts = (Gpoint *) malloc((size_t) (graph->num_pts * sizeof(Gpoint)))) == NULL), 300, errXgksExecData); for (i = 0; i < graph->num_pts; i++) NdcToWc(&(graph->pts[i]), &(pts[i])); (void) gfillarea(graph->num_pts, pts); ufree((voidp)pts); break; case 13: text = (XGKSMTEXT *) record; GKSERROR(((pts = (Gpoint *) malloc(sizeof(Gpoint))) == NULL), 300, errXgksExecData); NdcToWc(&(text->location), pts); (void) gtext(pts, text->string); ufree((voidp)pts); break; case 15: cell = (XGKSMCELLARRAY *) record; GKSERROR(((primi = XgksNewPrimi()) == NULL), 300, errXgksExecData); primi->pid = CELL_ARRAY; primi->primi.cell_array.dim = cell->dim; /* rowsize is equal to cell->dim.x */ primi->primi.cell_array.rowsize = cell->dim.x; j = cell->dim.x * cell->dim.y; GKSERROR(((primi->primi.cell_array.colour = (Gint *) malloc((size_t) (j * sizeof(Gint)))) == NULL), 300, errXgksExecData); primi->primi.cell_array.ll = cell->ll; primi->primi.cell_array.ur = cell->ur; primi->primi.cell_array.lr = cell->lr; primi->primi.cell_array.ul.x = cell->ll.x + (cell->ur.x - cell->lr.x); primi->primi.cell_array.ul.y = cell->ll.y + (cell->ur.y - cell->lr.y); for (i = 0; i < j; i++) primi->primi.cell_array.colour[i] = cell->colour[i]; XgksProcessPrimi(primi); if (MO_OPENED == TRUE) XgksMoCellArray(&(primi->primi.cell_array.ll), &(primi->primi.cell_array.ur), &(primi->primi.cell_array.lr), primi->primi.cell_array.rowsize, primi->primi.cell_array.colour, &(primi->primi.cell_array.dim)); ufree((voidp)primi->primi.cell_array.colour); ufree((voidp)primi); break; case 23: size = (XGKSMSIZE *) record; (void) gsetlinewidth(size->size); break; case 27: size = (XGKSMSIZE *) record; (void) gsetmarkersize(size->size); break; case 31: size = (XGKSMSIZE *) record; (void) gsetcharexpan(size->size); break; case 32: size = (XGKSMSIZE *) record; (void) gsetcharspace(size->size); break; case 34: vec = (XGKSMCHARVEC *) record; VecNdcToWc(&(vec->up), &siz); height = sqrt((siz.x * siz.x) + (siz.y * siz.y)); xgks_state.gks_chattr.up.x = siz.x / height; xgks_state.gks_chattr.up.y = siz.y / height; xgks_state.gks_chattr.height = height; VecNdcToWc(&(vec->base), &siz); height = sqrt((siz.x * siz.x) + (siz.y * siz.y)); xgks_state.gks_chattr.base.x = siz.x / height; xgks_state.gks_chattr.base.y = siz.y / height; xgks_state.gks_chattr.chwidth = height; break; case 43: asf = (XGKSMASF *) record; asfs.ln_type = (asf->asf[0] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.ln_width = (asf->asf[1] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.ln_colour = (asf->asf[2] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.mk_type = (asf->asf[3] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.mk_size = (asf->asf[4] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.mk_colour = (asf->asf[5] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.tx_fp = (asf->asf[6] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.tx_exp = (asf->asf[7] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.tx_space = (asf->asf[8] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.tx_colour = (asf->asf[9] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.fl_inter = (asf->asf[10] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.fl_style = (asf->asf[11] == 0 ? GBUNDLED : GINDIVIDUAL); asfs.fl_colour = (asf->asf[12] == 0 ? GBUNDLED : GINDIVIDUAL); (void) gsetasf(&asfs); break; case 51: lmrep = (XGKSMLMREP *) record; lnrep.type = lmrep->style; lnrep.width = lmrep->size; lnrep.colour = lmrep->colour; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetlinerep(xgks_state.activews[cnt].ws_id, lmrep->idx, &lnrep); } } } break; case 52: lmrep = (XGKSMLMREP *) record; mkrep.type = lmrep->style; mkrep.size = lmrep->size; mkrep.colour = lmrep->colour; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetmarkerrep(xgks_state.activews[cnt].ws_id, lmrep->idx, &mkrep); } } } break; case 53: txrep = (XGKSMTEXTREP *) record; textrep.fp.font = txrep->font; textrep.ch_exp = txrep->tx_exp; textrep.space = txrep->space; textrep.colour = txrep->colour; if (txrep->prec == 0) textrep.fp.prec = GSTRING; else if (txrep->prec == 1) textrep.fp.prec = GCHAR; else textrep.fp.prec = GSTROKE; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsettextrep(xgks_state.activews[cnt].ws_id, txrep->idx, &textrep); } } } break; case 54: flrep = (XGKSMFILLREP *) record; fillrep.style = flrep->style; fillrep.colour = flrep->colour; if (flrep->intstyle == 0) fillrep.inter = GHOLLOW; else if (flrep->intstyle == 1) fillrep.inter = GSOLID; else if (flrep->intstyle == 2) fillrep.inter = GPATTERN; else fillrep.inter = GHATCH; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetfillrep(xgks_state.activews[cnt].ws_id, flrep->idx, &fillrep); } } } break; case 55: patrep = (XGKSMPATREP *) record; ptrep.size.x = patrep->size.x; ptrep.size.y = patrep->size.y; j = ptrep.size.x * ptrep.size.y; GKSERROR(((ptrep.array = (Gint *) malloc((size_t) (j * sizeof(Gint)))) == NULL), 300, errXgksExecData); for (i = 0; i < j; i++) ptrep.array[i] = patrep->array[i]; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetpatrep(xgks_state.activews[cnt].ws_id, patrep->idx, &ptrep); } } } break; case 56: corep = (XGKSMCOLOURREP *) record; colourrep.red = corep->red; colourrep.green = corep->green; colourrep.blue = corep->blue; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetcolourrep(xgks_state.activews[cnt].ws_id, corep->idx, &colourrep); } } } break; case 61: limit = (XGKSMLIMIT *) record; xgks_state.cliprec.rec = limit->rect; XgksProcessClip(&xgks_state.cliprec.rec); break; case 71: limit = (XGKSMLIMIT *) record; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetwswindow(xgks_state.activews[cnt].ws_id, &(limit->rect)); } } } break; case 72: limit = (XGKSMLIMIT *) record; /* Do it on all active ws */ for (cnt = 0; cnt < MAX_ACTIVE_WS; cnt++) { if (xgks_state.activews[cnt].ws_id != INVALID) { /* c1138: don't do this on WISS */ if (xgks_state.activews[cnt].ws->ewstype != WISS) { (void) gsetwsviewport(xgks_state.activews[cnt].ws_id, &(limit->rect)); } } } break; case 91: tran = (XGKSMSEGTRAN *) record; segattr.seg = tran->name; (void) ginqsegattr(&segattr); segattr.segtran[0][0] = tran->matrix[0][0]; segattr.segtran[0][1] = tran->matrix[0][1]; segattr.segtran[0][2] = tran->matrix[0][2]; segattr.segtran[1][0] = tran->matrix[1][0]; segattr.segtran[1][1] = tran->matrix[1][1]; segattr.segtran[1][2] = tran->matrix[1][2]; (void) gsetsegattr(tran->name, &segattr); break; case 94: pri = (XGKSMSEGPRI *) record; segattr.seg = pri->name; (void) ginqsegattr(&segattr); segattr.pri = pri->pri; (void) gsetsegattr(pri->name, &segattr); break; default: return 1; } return 0; } /* * Indicate whether or not a Metafile item of the given type is valid. */ static int XgksValidGksMItem(Gint type) { if (type >= 0 && type <= 6) return OK; if (type >= 11 && type <= 16) return OK; if (type >= 21 && type <= 44) return OK; if (type >= 51 && type <= 56) return OK; if (type == 61) return OK; if (type == 71 || type == 72) return OK; if (type >= 81 && type <= 84) return OK; if (type >= 91 && type <= 95) return OK; if (type > 100) return OK; return INVALID; } /* * WRITE ITEM TO GKSM */ int gwritegksm(Gint ws_id, Gint type, Gint length, Gchar *data) /* workstation identifier */ /* item type */ /* item length */ /* item data-record */ { WS_STATE_PTR ws; Metafile *mf; GKSERROR((xgks_state.gks_state != GWSAC && xgks_state.gks_state != GSGOP), 5, errgwritegksm); GKSERROR((!VALID_WSID(ws_id)), 20, errgwritegksm); /* if it isn't open, it can't be active... */ GKSERROR(((ws = OPEN_WSID(ws_id)) == NULL), 30, errgwritegksm); GKSERROR((ws->wsstate != GACTIVE), 30, errgwritegksm); GKSERROR((WS_CAT(ws) != GMO), 32, errgwritegksm); GKSERROR((type <= 100), 160, errgwritegksm); GKSERROR((length < 0), 161, errgwritegksm); mf = &ws->mf; return MO_WRITE_ITEM(mf, 1, type, length, data); } /* * GET ITEM TYPE FROM GKSM */ int ggetgksm(Gint ws_id, Ggksmit *result) /* workstation identifier */ /* input metafile item information */ { WS_STATE_PTR ws; GKSERROR((xgks_state.gks_state != GWSOP && xgks_state.gks_state != GWSAC && xgks_state.gks_state != GSGOP), 7, errggetgksm); /* check for invalid workstation id */ GKSERROR((!VALID_WSID(ws_id)), 20, errggetgksm); GKSERROR(((ws = OPEN_WSID(ws_id)) == NULL), 25, errggetgksm); GKSERROR((WS_CAT(ws) != GMI), 34, errggetgksm); GKSERROR((ws->mf.any->GksmEmpty == TRUE), 162, errggetgksm); if (XgksValidGksMItem(ws->mf.any->CurItem.type) == INVALID) ws->mf.any->filestat = MF_ITEM_ERR; GKSERROR((ws->mf.any->filestat != METAFILE_OK), 163, errggetgksm); *result = ws->mf.any->CurItem; return OK; } /* * READ ITEM FROM GKSM * * The filestat field has been added to the workstation state structure to * retain MI error information between calls to ggetgksm and greadgksm. The * field has one of four possible integer values (defined in metafile.h): * METAFILE_OK -- no errors so far reading from metafile * MF_DATA_ERR -- type and length of latest item read (current item) are * ok, but XgksReadData couldn't read the data (eg. non- * numeric characters found when trying to read an integer) * The item may be skipped (via greadgksm w/ length 0) and * MI processing can continue. * MF_ITEM_ERR -- something more serious than a data error found in latest * item; eg. type invalid, length invalid, data read ter- * minated prematurely. This error condition can be detected * while going on to the next item, so the current item is * returned correctly, but subsequent attempts to get/read * will fail. Since the exact cause of the error is unknown, * this is not a recoverable condition. * MF_FILE_ERR -- the system reported an I/O error during a read attempt. * This error is not recoverable. * The first function to detect the error will report it, while attempting to * process the item it applies to. In other words, if greadgksm encounters a * file error while trying to go on to the next item after successfully reading * the current item, the error will not be reported until the next get/read * call. After a fatal error has been reported (via GKS error 163, item is * invalid), subsequent get/read attempts will return error 162, no items left * in MI, since the error is unrecoverable and no more reading is allowed. */ int greadgksm(Gint ws_id, Gint length, char *record) /* workstation identifier */ /* maximum item data record length */ /* input metafile item data-record */ { int istat; WS_STATE_PTR ws; GKSERROR((xgks_state.gks_state != GWSOP && xgks_state.gks_state != GWSAC && xgks_state.gks_state != GSGOP), 7, errgreadgksm); /* check for invalid workstation id */ GKSERROR((!VALID_WSID(ws_id)), 20, errgreadgksm); GKSERROR(((ws = OPEN_WSID(ws_id)) == NULL), 25, errgreadgksm); GKSERROR((WS_CAT(ws) != GMI), 34, errgreadgksm); if (ws->mf.any->CurItem.type == 0) ws->mf.any->GksmEmpty = TRUE; GKSERROR((ws->mf.any->GksmEmpty == TRUE), 162, errgreadgksm); if (ws->mf.any->filestat == MF_FILE_ERR) { ws->mf.any->GksmEmpty = TRUE; (void) gerrorhand(162, errgreadgksm, xgks_state.gks_err_file); return 162; } if (XgksValidGksMItem(ws->mf.any->CurItem.type) == INVALID) ws->mf.any->filestat = MF_ITEM_ERR; GKSERROR(((ws->mf.any->filestat == MF_ITEM_ERR) && (length != 0)), MF_ITEM_ERR, errgreadgksm); GKSERROR(((ws->mf.any->filestat == MF_DATA_ERR) && (length != 0)), MF_DATA_ERR, errgreadgksm); GKSERROR((length < 0), 166, errgreadgksm); if ((istat = MI_READ_ITEM(&ws->mf, record)) != 0) return istat; ws->mf.any->filestat = MI_GET_NEXT_ITEM(&ws->mf); return OK; } /* * Return the minimum possible size for the data associated with a GKSM * item-type. * * Note, since this routine is used by ginterpret(), we return the size of the * decoded, binary structures -- not the file-encoded size. */ static int recSize(Gint type) { switch (type) { case 0: case 2: case 82: return 0; case 1: case 3: case 21: case 22: case 24: case 25: case 26: case 28: case 29: case 33: case 35: case 37: case 38: case 39: case 40: case 44: case 81: case 84: return sizeof(XGKSMONE); case 4: case 30: case 36: case 83: case 92: case 93: case 95: return sizeof(XGKSMTWO); case 5: return sizeof(XGKSMONE); case 11: case 12: case 14: return sizeof(XGKSMONE); case 13: return sizeof(XGKSMTEXT); case 15: return sizeof(XGKSMCELLARRAY); case 23: case 27: case 31: case 32: return sizeof(XGKSMSIZE); case 34: return sizeof(XGKSMCHARVEC); case 43: return sizeof(XGKSMASF); case 41: return sizeof(XGKSMPATSIZ); case 42: return sizeof(XGKSMPATREF); case 51: case 52: return sizeof(XGKSMLMREP); case 53: return sizeof(XGKSMTEXTREP); case 54: return sizeof(XGKSMFILLREP); case 55: return sizeof(XGKSMPATREP); case 56: return sizeof(XGKSMCOLOURREP); case 61: case 71: case 72: return sizeof(XGKSMLIMIT); case 91: return sizeof(XGKSMSEGTRAN); case 94: return sizeof(XGKSMSEGPRI); default: return INVALID; } } /* * INTERPRET GKSM ITEM */ int ginterpret(Ggksmit *recInfo, char *data) /* item type and length */ /* item data-record */ { GKSERROR((xgks_state.gks_state != GWSOP && xgks_state.gks_state != GWSAC && xgks_state.gks_state != GSGOP), 7, errginterpret); GKSERROR((recInfo == NULL), 163, errginterpret); GKSERROR(((recInfo->length > 0) && (data == NULL)), 165, errginterpret); /* * We no longer check for invalid size (error 161) because the GKSM * backend returns the length of the formatted data record rather than the * size of the internally-used binary structures. */ #if 0 GKSERROR((recInfo->length < recSize(recInfo->type)), 161, errginterpret); #endif GKSERROR((XgksValidGksMItem(recInfo->type) == INVALID), 164, errginterpret); /* * Can't check for 165 in ginterpret due to file format. * Can't really check for 163, either. */ GKSERROR((recInfo->type > 100), 167, errginterpret); GKSERROR((NOTSUPPORTED(recInfo->type)), 168, errginterpret); GKSERROR((XgksExecData(recInfo->type, data) != 0), 164, errginterpret); return OK; } /* * Open an input Metafile: scan header and get first item. */ int XgksMiOpenWs(ws) WS_STATE_PTR ws; { int status = 26; /* return status = workstation cannot * be opened */ ws->wscolour = MAX_META_WSCOLOURS; ws->set_colour_rep = NULL; if ((strstr(ws->conn, ".cgm") == NULL ? GMmiOpen(&ws->mf, ws->conn) : CGMmiOpen(&ws->mf, ws->conn)) == OK) { ws->mf.any->filestat = MI_GET_NEXT_ITEM(&ws->mf); if (ws->mf.any->filestat == METAFILE_OK) { status = OK; } else { MI_CLOSE(&ws->mf); } } return status; } /* * Open an output Metafile. */ int XgksMoOpenWs(ws) WS_STATE_PTR ws; { Gint status; ws->wscolour = MAX_META_WSCOLOURS; ws->set_colour_rep = NULL; /* Make sure window boundaries are set to zero to avoid */ /* floating point exceptions on DEC OSF *js* 9.97 */ ws->wbound.x = 0; ws->wbound.y = 0; if (strstr(ws->conn, ".cgm") != NULL || strstr(ws->conn, ".CGM") != NULL) { status = CGMmoOpen(ws); } else if (strstr(ws->conn, ".ps") != NULL || strstr(ws->conn, ".PS") != NULL){ status = PSmoOpen(ws); } else if (strstr(ws->conn, ".gif") != NULL || strstr(ws->conn, ".GIF") != NULL){ status = GIFmoOpen(ws); } else { status = GMmoOpen(ws); } return status == OK ? OK :26; } /* * Close an input Metafile. */ int XgksMiCloseWs(WS_STATE_PTR ws) { (void) fclose(ws->mf.any->fp); return OK; } /* * Close an output Metafile. ?batmode */ int XgksMoCloseWs(WS_STATE_PTR ws, int batmode) { return MO_CLOSE(&ws->mf); } /* * Set the clear flag in an output Metafile. */ int XgksMoClearWs(WS_STATE_PTR ws, Gclrflag flag) { Metafile *mf = &ws->mf; return MO_CLEAR(mf, 1, flag); } /* * Redraw all segments in an output Metafile. */ int XgksMoReDrawAllSeg(WS_STATE_PTR ws) { Metafile *mf = &ws->mf; return MO_REDRAW_ALL_SEG(mf, 1); } /* * Set the update flag in an output Metafile. */ int XgksMoUpdateWs(WS_STATE_PTR ws, Gregen regenflag) { Metafile *mf = &ws->mf; return MO_UPDATE(mf, 1, regenflag); } /* * Set the deferal state in an output Metafile. */ int XgksMoDeferWs(WS_STATE_PTR ws, Gdefmode defer_mode, Girgmode regen_mode) { Metafile *mf = &ws->mf; return MO_DEFER(mf, 1, defer_mode, regen_mode); } /* * Write a message to an output Metafile. */ int XgksMoMessage(WS_STATE_PTR ws, Gchar *string) { Metafile *mf = &ws->mf; return MO_MESSAGE(mf, 1, string); } /* * Write a graphic to an output Metafile. */ int XgksMoGraphicOutputToWs(WS_STATE_PTR ws, Gint code, Gint num_pt, Gpoint *pos) { Metafile *mf = &ws->mf; return MO_GRAPHIC(mf, 1, code, num_pt, pos); } /* * Write a graphic to all, appropriate, output Metafiles. */ int XgksMoGraphicOutput(Gint code, Gint num_pt, Gpoint *pos) { if (num_gksmo > 0) GMoutputGraphic(active_gksmo, num_gksmo, code, num_pt, pos); if (num_cgmo > 0) CGMoutputGraphic(active_cgmo, num_cgmo, code, num_pt, pos); if (num_psmo > 0) PSoutputGraphic(active_psmo, num_psmo, code, num_pt, pos); if (num_gifmo > 0) GIFoutputGraphic(active_gifmo, num_gifmo, code, num_pt, pos); return OK; } /* * Write text to an output Metafile. */ int XgksMoTextToWs(WS_STATE_PTR ws, Gpoint *at, Gchar *string) { Metafile *mf = &ws->mf; return MO_TEXT(mf, 1, at, string); } /* * Write text to all, appropriate, output Metafiles. */ int XgksMoText(Gpoint *at, Gchar *string) { if (num_gksmo > 0) GMtext(active_gksmo, num_gksmo, at, string); if (num_cgmo > 0) CGMtext(active_cgmo, num_cgmo, at, string); if (num_psmo > 0) PStext(active_psmo, num_psmo, at, string); if (num_gifmo > 0) GIFtext(active_gifmo, num_gifmo, at, string); return OK; } /* * Write a cell array to an output Metafile. */ int XgksMoCellArrayToWs(WS_STATE_PTR ws, Gpoint *ll, Gpoint *ur, Gpoint *lr, Gint row, Gint *colour, Gipoint *dim) { Metafile *mf = &ws->mf; return MO_CELL_ARRAY(mf, 1, ll, ur, lr, row, colour, dim); } /* * Write a cell array to all, appropriate, output Metafiles. */ int XgksMoCellArray(Gpoint *ll, Gpoint *ur, Gpoint *lr, Gint row, Gint *colour, Gipoint *dim) { if (num_gksmo > 0) GMcellArray(active_gksmo, num_gksmo, ll, ur, lr, row, colour, dim); if (num_cgmo > 0) CGMcellArray(active_cgmo, num_cgmo, ll, ur, lr, row, colour, dim); if (num_psmo > 0) PScellArray(active_psmo, num_psmo, ll, ur, lr, row, colour, dim); if (num_gifmo > 0) GIFcellArray(active_gifmo, num_gifmo, ll, ur, lr, row, colour, dim); return OK; } /* * Set the size of graphics in an output Metafile. */ int XgksMoSetGraphicSizeOnWs(WS_STATE_PTR ws, Gint code, double size) { Metafile *mf = &ws->mf; return MO_SET_GRAPH_SIZE(mf, 1, code, size); } /* * Set the size of graphics in all, appropriate, output Metafiles. */ int XgksMoSetGraphicSize(Gint code, double size) { if (num_gksmo > 0) GMsetGraphSize(active_gksmo, num_gksmo, code, size); if (num_cgmo > 0) CGMsetGraphSize(active_cgmo, num_cgmo, code, size); if (num_psmo > 0) PSsetGraphSize(active_psmo, num_psmo, code, size); if (num_gifmo > 0) GIFsetGraphSize(active_gifmo, num_gifmo, code, size); return OK; } /* * Close the open segment in an output Metafile. */ int XgksMoCloseSegOnWs(WS_STATE_PTR ws) { Metafile *mf = &ws->mf; return MO_CLOSE_SEG(mf, 1); } /* * Close the open segment in all, appropriate, output Metafiles. */ int XgksMoCloseSeg(void) { if (num_gksmo > 0) GMcloseSeg(active_gksmo, num_gksmo); if (num_cgmo > 0) CGMcloseSeg(active_cgmo, num_cgmo); if (num_psmo > 0) PScloseSeg(active_psmo, num_psmo); if (num_gifmo > 0) GIFcloseSeg(active_gifmo, num_gifmo); return OK; } /* * Set the graphic attributes in an output Metafile. */ int XgksMoSetGraphicAttrOnWs(WS_STATE_PTR ws, Gint code, Gint attr) { Metafile *mf = &ws->mf; return MO_SET_GRAPH_ATTR(mf, 1, code, attr); } /* * Set the graphic attributes in all, appropriate, output Metafiles. */ int XgksMoSetGraphicAttr(Gint code, Gint attr) { if (num_gksmo > 0) GMsetGraphAttr(active_gksmo, num_gksmo, code, attr); if (num_cgmo > 0) CGMsetGraphAttr(active_cgmo, num_cgmo, code, attr); if (num_psmo > 0) PSsetGraphAttr(active_psmo, num_psmo, code, attr); if (num_gifmo > 0) GIFsetGraphAttr(active_gifmo, num_gifmo, code, attr); return OK; } /* * Set the font precision in an output Metafile. */ int XgksMoSetTextFPOnWs(WS_STATE_PTR ws, Gtxfp *txfp) { Metafile *mf = &ws->mf; return MO_SET_TEXT_FP(mf, 1, txfp); } /* * Set the font precision in all, appropriate, output Metafiles. */ int XgksMoSetTextFP(Gtxfp *txfp) { if (num_gksmo > 0) GMsetTextFP(active_gksmo, num_gksmo, txfp); if (num_cgmo > 0) CGMsetTextFP(active_cgmo, num_cgmo, txfp); if (num_psmo > 0) PSsetTextFP(active_psmo, num_psmo, txfp); if (num_gifmo > 0) GIFsetTextFP(active_gifmo, num_gifmo, txfp); return OK; } /* * Set the character up-vector in an output Metafile. */ int XgksMoSetCharUpOnWs(WS_STATE_PTR ws, Gpoint *up, Gpoint *base) { Metafile *mf = &ws->mf; return MO_SET_CHAR_UP(mf, 1, up, base); } /* * Set the character up-vector in all, appropriate, output Metafiles. */ int XgksMoSetCharUp(void) { if (num_gksmo > 0) GMsetCharUp(active_gksmo, num_gksmo, (Gpoint*)NULL, (Gpoint*)NULL); if (num_cgmo > 0) CGMsetCharUp(active_cgmo, num_cgmo, (Gpoint*)NULL, (Gpoint*)NULL); if (num_psmo > 0) PSsetCharUp(active_psmo, num_psmo, &xgks_state.gks_chattr.up, &xgks_state.gks_chattr.base); if (num_gifmo > 0) GIFsetCharUp(active_gifmo, num_gifmo, &xgks_state.gks_chattr.up, &xgks_state.gks_chattr.base); return OK; } /* * Set the text-path in an output Metafile. */ int XgksMoSetTextPathOnWs(WS_STATE_PTR ws, Gtxpath path) { Metafile *mf = &ws->mf; return MO_SET_TEXT_PATH(mf, 1, path); } /* * Set the text-path in all, appropriate, output Metafiles. */ int XgksMoSetTextPath(Gtxpath path) { if (num_gksmo > 0) GMsetTextPath(active_gksmo, num_gksmo, path); if (num_cgmo > 0) CGMsetTextPath(active_cgmo, num_cgmo, path); if (num_psmo > 0) PSsetTextPath(active_psmo, num_psmo, path); if (num_gifmo > 0) GIFsetTextPath(active_gifmo, num_gifmo, path); return OK; } /* * Set the text-alignment in an output Metafile. */ int XgksMoSetTextAlignOnWs(WS_STATE_PTR ws, Gtxalign *align) { Metafile *mf = &ws->mf; return MO_SET_TEXT_ALIGN(mf, 1, align); } /* * Set the text-alignment in all, appropriate, output Metafiles. */ int XgksMoSetTextAlign(Gtxalign *align) { if (num_gksmo > 0) GMsetTextAlign(active_gksmo, num_gksmo, align); if (num_cgmo > 0) CGMsetTextAlign(active_cgmo, num_cgmo, align); if (num_psmo > 0) PSsetTextAlign(active_psmo, num_psmo, align); if (num_gifmo > 0) GIFsetTextAlign(active_gifmo, num_gifmo, align); return OK; } /* * Set the interior fill-style in an output Metafile. */ int XgksMoSetFillIntStyleOnWs(WS_STATE_PTR ws, Gflinter style) { Metafile *mf = &ws->mf; return MO_SET_FILL_STYLE(mf, 1, style); } /* * Set the interior fill-style in all, appropriate, output Metafiles. */ int XgksMoSetFillIntStyle(Gflinter style) { if (num_gksmo > 0) GMsetFillStyle(active_gksmo, num_gksmo, style); if (num_cgmo > 0) CGMsetFillStyle(active_cgmo, num_cgmo, style); if (num_psmo > 0) PSsetFillStyle(active_psmo, num_psmo, style); if (num_gifmo > 0) GIFsetFillStyle(active_gifmo, num_gifmo, style); return OK; } /* * Set the pattern size in an output Metafile. */ int XgksMoSetPatSizeOnWs(WS_STATE_PTR ws) { Metafile *mf = &ws->mf; return MO_SET_PATTERN_SIZE(mf, 1); } /* * Set the pattern size in all, appropriate, output Metafiles. */ int XgksMoSetPatSize(void) { if (num_gksmo > 0) GMsetPatSize(active_gksmo, num_gksmo); if (num_cgmo > 0) CGMsetPatSize(active_cgmo, num_cgmo); if (num_psmo > 0) PSsetPatSize(active_psmo, num_psmo); if (num_gifmo > 0) GIFsetPatSize(active_gifmo, num_gifmo); return OK; } /* * Set the pattern reference-point in an output Metafile. */ int XgksMoSetPatRefOnWs(WS_STATE_PTR ws) { Metafile *mf = &ws->mf; return MO_SET_PATTERN_REFPT(mf, 1); } /* * Set the pattern reference-point in all, appropriate, output Metafiles. */ int XgksMoSetPatRef(void) { if (num_gksmo > 0) GMsetPatRefpt(active_gksmo, num_gksmo); if (num_cgmo > 0) CGMsetPatRefpt(active_cgmo, num_cgmo); if (num_psmo > 0) PSsetPatRefpt(active_psmo, num_psmo); if (num_gifmo > 0) GIFsetPatRefpt(active_gifmo, num_gifmo); return OK; } /* * Set the ASF in an output Metafile. */ int XgksMoSetAsfOnWs(WS_STATE_PTR ws) { Metafile *mf = &ws->mf; return MO_SET_ASF(mf, 1); } /* * Set the ASF in all, appropriate, output Metafiles. */ int XgksMoSetAsf(void) { if (num_gksmo > 0) GMsetAsf(active_gksmo, num_gksmo); if (num_cgmo > 0) CGMsetAsf(active_cgmo, num_cgmo); if (num_psmo > 0) PSsetAsf(active_psmo, num_psmo); if (num_gifmo > 0) GIFsetAsf(active_gifmo, num_gifmo); return OK; } /* * Set the line and marker representation in an output Metafile. */ int XgksMoSetLineMarkRep(WS_STATE_PTR ws, Gint code, Gint idx, Gint type, double size, Gint colour) { Metafile *mf = &ws->mf; return MO_SET_LINE_MARKER_REP(mf, 1, code, idx, type, size, colour); } /* * Set the text representation in an output Metafile. */ int XgksMoSetTextRep(WS_STATE_PTR ws, Gint idx, Gtxbundl *rep) { Metafile *mf = &ws->mf; return MO_SET_TEXT_REP(mf, 1, idx, rep); } /* * Set the fill representation in an output Metafile. */ int XgksMoSetFillRep(WS_STATE_PTR ws, Gint idx, Gflbundl *rep) { Metafile *mf = &ws->mf; return MO_SET_FILL_REP(mf, 1, idx, rep); } /* * Set the pattern representation in an output Metafile. */ int XgksMoSetPatRep(WS_STATE_PTR ws, Gint idx, Gptbundl *rep) { Metafile *mf = &ws->mf; return MO_SET_PATTERN_REP(mf, 1, idx, rep); } /* * Set the colour representation in an output Metafile. */ int XgksMoSetColourRep(WS_STATE_PTR ws, Gint idx, Gcobundl *rep) { Metafile *mf = &ws->mf; return MO_SET_COLOUR_REP(mf, 1, idx, rep); } /* * Set the clipping rectangle in an output Metafile. */ int XgksMoSetClipOnWs(WS_STATE_PTR ws, Glimit *rect) { Metafile *mf = &ws->mf; return MO_SET_CLIPPING(mf, 1, rect); } /* * Set the clipping rectangle in all, appropriate, output Metafiles. */ int XgksMoSetClip(Glimit *rect) { if (num_gksmo > 0) GMsetClip(active_gksmo, num_gksmo, rect); if (num_cgmo > 0) CGMsetClip(active_cgmo, num_cgmo, rect); if (num_psmo > 0) PSsetClip(active_psmo, num_psmo, rect); if (num_gifmo > 0) GIFsetClip(active_gifmo, num_gifmo, rect); return OK; } /* * Set the viewport limits in an output Metafile. */ int XgksMoSetLimit(WS_STATE_PTR ws, Gint code, Glimit *rect) { Metafile *mf = &ws->mf; return MO_SET_LIMIT(mf, 1, code, rect); } /* * Rename a segment in all, appropriate, output Metafiles. */ int XgksMoRenameSeg(Gint old, Gint new) { if (num_gksmo > 0) GMrenameSeg(active_gksmo, num_gksmo, old, new); if (num_cgmo > 0) CGMrenameSeg(active_cgmo, num_cgmo, old, new); if (num_psmo > 0) PSrenameSeg(active_psmo, num_psmo, old, new); if (num_gifmo > 0) GIFrenameSeg(active_gifmo, num_gifmo, old, new); return OK; } /* * Set the segment transformation in an output Metafile. */ int XgksMoSetSegTransOnWs(WS_STATE_PTR ws, Gint name, Gfloat (*matrix)[]) { Metafile *mf = &ws->mf; return MO_SET_SEG_TRANS(mf, 1, name, matrix); } /* * Set the segment transformation in all, appropriate, output Metafiles. */ int XgksMoSetSegTrans(Gint name, Gfloat (*matrix)[]) { if (num_gksmo > 0) GMsetSegTran(active_gksmo, num_gksmo, name, matrix); if (num_cgmo > 0) CGMsetSegTran(active_cgmo, num_cgmo, name, matrix); if (num_psmo > 0) PSsetSegTran(active_psmo, num_psmo, name, matrix); if (num_gifmo > 0) GIFsetSegTran(active_gifmo, num_gifmo, name, matrix); return OK; } /* * Set the segment attributes in an output Metafile. */ int XgksMoSetSegAttrOnWs(WS_STATE_PTR ws, Gint name, Gint code, Gint attr) { Metafile *mf = &ws->mf; return MO_SET_SEG_ATTR(mf, 1, name, code, attr); } /* * Set the segment visibility in all, appropriate, output Metafiles. */ int XgksMoSetSegVis(Gint name, Gsegvis vis) { if (num_gksmo > 0) GMsetSegVis(active_gksmo, num_gksmo, name, vis); if (num_cgmo > 0) CGMsetSegVis(active_cgmo, num_cgmo, name, vis); if (num_psmo > 0) PSsetSegVis(active_psmo, num_psmo, name, vis); if (num_gifmo > 0) GIFsetSegVis(active_gifmo, num_gifmo, name, vis); return OK; } /* * Set the segment highlighting in all, appropriate, output Metafiles. */ int XgksMoSetSegHiLight(Gint name, Gseghi hilight) { if (num_gksmo > 0) GMsetSegHilight(active_gksmo, num_gksmo, name, hilight); if (num_cgmo > 0) CGMsetSegHilight(active_cgmo, num_cgmo, name, hilight); if (num_psmo > 0) PSsetSegHilight(active_psmo, num_psmo, name, hilight); if (num_gifmo > 0) GIFsetSegHilight(active_gifmo, num_gifmo, name, hilight); return OK; } /* * Set the segment priority in an output Metafile. */ int XgksMoSetSegPriOnWs(WS_STATE_PTR ws, Gint name, double pri) { Metafile *mf = &ws->mf; return MO_SET_SEG_PRI(mf, 1, name, pri); } /* * Set the segment priority in all, appropriate output Metafiles. */ int XgksMoSetSegPri(Gint name, double pri) { if (num_gksmo > 0) GMsetSegPri(active_gksmo, num_gksmo, name, pri); if (num_cgmo > 0) CGMsetSegPri(active_cgmo, num_cgmo, name, pri); if (num_psmo > 0) PSsetSegPri(active_psmo, num_psmo, name, pri); if (num_gifmo > 0) GIFsetSegPri(active_gifmo, num_gifmo, name, pri); return OK; } /* * Set segment detectability in all, appropriate output Metafiles. */ int XgksMoSetSegDet(Gint name, Gsegdet det) { if (num_gksmo > 0) GMsetSegDetect(active_gksmo, num_gksmo, name, det); if (num_cgmo > 0) CGMsetSegDetect(active_cgmo, num_cgmo, name, det); if (num_psmo > 0) PSsetSegDetect(active_psmo, num_psmo, name, det); if (num_gifmo > 0) GIFsetSegDetect(active_gifmo, num_gifmo, name, det); return OK; } /* * Add an output Metafile to a list of active, output Metafiles. */ static void add_mo(Metafile *mo, Metafile *list, int *num) { assert(*num >= 0); assert(*num < MAX_ACTIVE_WS); list[(*num)++] = *mo; } /* * Remove an output Metafile from a list of active, output Metafiles. */ static void remove_mo(mo, list, num) Metafile *mo; Metafile *list; int *num; { Metafile *outp; assert(*num > 0); assert(*num <= MAX_ACTIVE_WS); /* Find the Metafile to be removed. */ for (outp = list + *num; list < outp; ++list) if (list->any == mo->any) break; assert(list < outp); if (list < outp) { /* Shift the list down over the found Metafile. */ for (--outp; list < outp; ++list) list[0].any = list[1].any; --*num; } } /* * Activate an output Metafile: add it to the list of active, output * Metafiles and write initial output Metafile attributes. */ int XgksMoActivateWs(WS_STATE_PTR ws) { switch(ws->mf.any->type){ case MF_GKSM: add_mo(&ws->mf, active_gksmo, &num_gksmo); break; case MF_PS: add_mo(&ws->mf, active_psmo, &num_psmo); break; case MF_GIF: add_mo(&ws->mf, active_gifmo, &num_gifmo); break; case MF_CGM: default: add_mo(&ws->mf, active_cgmo, &num_cgmo); break; } XgksMoSetClipOnWs(ws, &xgks_state.cliprec.rec); XgksSetLineAttrMo(ws, &xgks_state.gks_lnattr); XgksSetMarkAttrMo(ws, &xgks_state.gks_mkattr); XgksSetTextAttrMo(ws, &xgks_state.gks_txattr, &xgks_state.gks_chattr); XgksMoSetCharUpOnWs(ws, (Gpoint *) NULL, (Gpoint *) NULL); XgksSetFillPatAttrMo(ws, &xgks_state.gks_flattr, &xgks_state.gks_ptattr); XgksMoSetPatSizeOnWs(ws); XgksMoSetPatRefOnWs(ws); XgksMoSetAsfOnWs(ws); XgksMoSetGraphicAttrOnWs(ws, 44, xgks_state.gks_pick_id); return OK; } /* * Deactivate an output Metafile: remove it from the list of active, output * Metafiles. */ int XgksMoDeactivateWs(WS_STATE_PTR ws) { switch(ws->mf.any->type){ case MF_GKSM: remove_mo(&ws->mf, active_gksmo, &num_gksmo); break; case MF_PS: remove_mo(&ws->mf, active_psmo, &num_psmo); break; case MF_GIF: remove_mo(&ws->mf, active_gifmo, &num_gifmo); break; case MF_CGM: default: remove_mo(&ws->mf, active_cgmo, &num_cgmo); break; } return OK; } /* * Initialize the Metafile system. */ int XgksInitGksM(void) { return OK; }
25.587703
144
0.64907
[ "vector" ]
aa3b932c4ef612d7a69de0aa1573ba3945666ed7
5,728
h
C
tensorflow/compiler/xla/service/shaped_buffer.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
384
2017-02-21T18:38:04.000Z
2022-02-22T07:30:25.000Z
tensorflow/compiler/xla/service/shaped_buffer.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
15
2017-03-01T20:18:43.000Z
2020-05-07T10:33:51.000Z
tensorflow/compiler/xla/service/shaped_buffer.h
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
[ "Apache-2.0" ]
81
2017-02-21T19:31:19.000Z
2022-02-22T07:30:24.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_ #include <memory> #include "tensorflow/compiler/xla/service/device_memory_allocator.h" #include "tensorflow/compiler/xla/shape_tree.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/stream_executor_no_cuda.h" #include "tensorflow/core/platform/types.h" namespace xla { // Class which encapsulates a buffer or set of buffers containing data of a // particular XLA shape. Used for zero-copy execution interface for a // XLA client running in the same process as the service (LocalClient), class ShapedBuffer { public: // Creates a ShapedBuffer of arbitrary shape. All buffer pointers // (DeviceMemoryBase) in the returned ShapedBuffer are initialized to null. static StatusOr<std::unique_ptr<ShapedBuffer>> MakeShapedBuffer( const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal); // Convenience method which creates a ShapedBuffer of array shape (not a // tuple). Its single buffer pointer is set to the given value "buffer". The // given buffer must be large enough to store the given shape as given by // ShapeUtil::ByteSizeOf. static StatusOr<std::unique_ptr<ShapedBuffer>> MakeArrayShapedBuffer( const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal, const perftools::gputools::DeviceMemoryBase& buffer); // Convenience method which creates a ShapedBuffer of a non-nested tuple. The // buffer pointers in the return ShapedBuffer are set to the given // "buffers". The size of buffers must match the number of elements in the // tuple shape and be large enough to store their respective shape as given by // ShapeUtil::ByteSizeOf. static StatusOr<std::unique_ptr<ShapedBuffer>> MakeUnnestedTupleShapedBuffer( const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal, const tensorflow::gtl::ArraySlice<perftools::gputools::DeviceMemoryBase> buffers); const Shape& shape() const { return shape_; } const perftools::gputools::Platform* platform() const { return platform_; } int device_ordinal() const { return device_ordinal_; } // Returns the buffer at the given shape index where index is defined as in // ShapeUtil::GetSubshape. const perftools::gputools::DeviceMemoryBase& buffer( const ShapeIndex& index) const; perftools::gputools::DeviceMemoryBase* mutable_buffer( const ShapeIndex& index); // Returns the underlying structure which stores the buffer pointers. const std::vector<perftools::gputools::DeviceMemoryBase>& buffers() const { return buffers_; } std::vector<perftools::gputools::DeviceMemoryBase>* mutable_buffers() { return &buffers_; } // Returns the tree of indices which map to buffer pointers. const ShapeTree<size_t>& shape_index_to_buffer_entry() const { return shape_index_to_buffer_entry_; } ShapeTree<size_t>* mutable_shape_index_to_buffer_entry() { return &shape_index_to_buffer_entry_; } protected: ShapedBuffer(const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal); // The shape of the device buffer with layout. const Shape shape_; // The list of DeviceMemoryBase pointers representing this shape. // Note that there can be a many to one relationship between tuple elements // and buffers. To account for this, shape_index_to_buffer_entry_ allows us // to make from a position in a shape to an index into this list. std::vector<perftools::gputools::DeviceMemoryBase> buffers_; // The tree of indices into buffers_. ShapeTree<size_t> shape_index_to_buffer_entry_; // The platform the memory is allocated on. const perftools::gputools::Platform* platform_; // The device the memory is allocated on. const int device_ordinal_; }; // ShapedBuffer derived class which allocates all internal buffers on // construction and deallocates the memory when the object is // destructed. class ScopedShapedBuffer : public ShapedBuffer { public: // Return a new ScopedShapedBuffer of an arbitrary shape. All buffers in the // ScopedShapedBuffers are automatically allocated to exactly the size of // their respective array shape. static StatusOr<std::unique_ptr<ScopedShapedBuffer>> MakeScopedShapedBuffer( const Shape& shape, DeviceMemoryAllocator* allocator, int device_ordinal); // All buffers in the shape are deallocated on destruction. ~ScopedShapedBuffer(); protected: ScopedShapedBuffer(const Shape& shape, DeviceMemoryAllocator* allocator, int device_ordinal); ScopedShapedBuffer(const ScopedShapedBuffer&) = delete; void operator=(const ScopedShapedBuffer&) = delete; DeviceMemoryAllocator* allocator_; }; } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_
41.507246
80
0.752968
[ "object", "shape", "vector" ]
aa3c34bf464043e4108a6055d3cdc0f0ba6221a2
213,071
h
C
Include/10.0.10586.0/winrt/Windows.ApplicationModel.h
sezero/windows-sdk-headers
e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5
[ "MIT" ]
5
2020-05-29T06:22:17.000Z
2021-11-28T08:21:38.000Z
Include/10.0.10586.0/winrt/Windows.ApplicationModel.h
sezero/windows-sdk-headers
e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5
[ "MIT" ]
null
null
null
Include/10.0.10586.0/winrt/Windows.ApplicationModel.h
sezero/windows-sdk-headers
e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5
[ "MIT" ]
5
2020-05-30T04:15:11.000Z
2021-11-28T08:48:56.000Z
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.00.0613 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __windows2Eapplicationmodel_h__ #define __windows2Eapplicationmodel_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef ____FIIterator_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define ____FIIterator_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ typedef interface __FIIterator_1_Windows__CApplicationModel__CAppInfo __FIIterator_1_Windows__CApplicationModel__CAppInfo; #endif /* ____FIIterator_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ */ #ifndef ____FIIterable_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define ____FIIterable_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ typedef interface __FIIterable_1_Windows__CApplicationModel__CAppInfo __FIIterable_1_Windows__CApplicationModel__CAppInfo; #endif /* ____FIIterable_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ */ #ifndef ____FIIterator_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define ____FIIterator_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ typedef interface __FIIterator_1_Windows__CApplicationModel__CPackage __FIIterator_1_Windows__CApplicationModel__CPackage; #endif /* ____FIIterator_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ */ #ifndef ____FIIterable_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define ____FIIterable_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ typedef interface __FIIterable_1_Windows__CApplicationModel__CPackage __FIIterable_1_Windows__CApplicationModel__CPackage; #endif /* ____FIIterable_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ */ #ifndef ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ typedef interface __FIVectorView_1_Windows__CApplicationModel__CAppInfo __FIVectorView_1_Windows__CApplicationModel__CAppInfo; #endif /* ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ */ #ifndef ____FIVectorView_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define ____FIVectorView_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ typedef interface __FIVectorView_1_Windows__CApplicationModel__CPackage __FIVectorView_1_Windows__CApplicationModel__CPackage; #endif /* ____FIVectorView_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ */ #ifndef ____FIVector_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define ____FIVector_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ typedef interface __FIVector_1_Windows__CApplicationModel__CPackage __FIVector_1_Windows__CApplicationModel__CPackage; #endif /* ____FIVector_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ */ #ifndef ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_FWD_DEFINED__ #define ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_FWD_DEFINED__ typedef interface __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs; #endif /* ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_FWD_DEFINED__ */ #ifndef ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ typedef interface __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo; #endif /* ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ */ #ifndef ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ typedef interface __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo; #endif /* ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IAppDisplayInfo; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIAppInfo_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIAppInfo_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIAppInfo __x_ABI_CWindows_CApplicationModel_CIAppInfo; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IAppInfo; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIAppInfo_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface ISuspendingDeferral; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CISuspendingOperation __x_ABI_CWindows_CApplicationModel_CISuspendingOperation; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface ISuspendingOperation; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface ISuspendingEventArgs; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackageIdWithMetadata; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackageWithMetadata; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackageStatus __x_ABI_CWindows_CApplicationModel_CIPackageStatus; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackageStatus; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageId_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageId_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackageId __x_ABI_CWindows_CApplicationModel_CIPackageId; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackageId; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageId_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackage __x_ABI_CWindows_CApplicationModel_CIPackage; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackage; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage2_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage2_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackage2 __x_ABI_CWindows_CApplicationModel_CIPackage2; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackage2; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage2_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage3_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage3_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackage3 __x_ABI_CWindows_CApplicationModel_CIPackage3; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackage3; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage3_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIPackageStatics __x_ABI_CWindows_CApplicationModel_CIPackageStatics; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackageStatics; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_FWD_DEFINED__ */ #ifndef ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_FWD_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_FWD_DEFINED__ typedef interface __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics; #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IDesignModeStatics; } /* end namespace */ } /* end namespace */ } /* end namespace */ #endif /* __cplusplus */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_FWD_DEFINED__ */ /* header files for imported files */ #include "inspectable.h" #include "AsyncInfo.h" #include "EventToken.h" #include "Windows.Foundation.h" #include "Windows.ApplicationModel.Core.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0000 */ /* [local] */ #ifdef __cplusplus } /*extern "C"*/ #endif #include <windows.foundation.collections.h> #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class AppInfo; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IAppInfo; } /*ApplicationModel*/ } /*Windows*/ } #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0000 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0000_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2523 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2523 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2523_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2523_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0001 */ /* [local] */ #ifndef DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo_USE #define DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("69cec62c-41eb-5d69-a475-29ee22323dd8")) IIterator<ABI::Windows::ApplicationModel::AppInfo*> : IIterator_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::AppInfo*, ABI::Windows::ApplicationModel::IAppInfo*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<Windows.ApplicationModel.AppInfo>"; } }; typedef IIterator<ABI::Windows::ApplicationModel::AppInfo*> __FIIterator_1_Windows__CApplicationModel__CAppInfo_t; #define ____FIIterator_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define __FIIterator_1_Windows__CApplicationModel__CAppInfo ABI::Windows::Foundation::Collections::__FIIterator_1_Windows__CApplicationModel__CAppInfo_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0001 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0001_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0001_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2524 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2524 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2524_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2524_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0002 */ /* [local] */ #ifndef DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo_USE #define DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("63d0bffe-0e34-55b3-83d5-314caff2b137")) IIterable<ABI::Windows::ApplicationModel::AppInfo*> : IIterable_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::AppInfo*, ABI::Windows::ApplicationModel::IAppInfo*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<Windows.ApplicationModel.AppInfo>"; } }; typedef IIterable<ABI::Windows::ApplicationModel::AppInfo*> __FIIterable_1_Windows__CApplicationModel__CAppInfo_t; #define ____FIIterable_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define __FIIterable_1_Windows__CApplicationModel__CAppInfo ABI::Windows::Foundation::Collections::__FIIterable_1_Windows__CApplicationModel__CAppInfo_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo_USE */ #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class Package; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface IPackage; } /*ApplicationModel*/ } /*Windows*/ } #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0002 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0002_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0002_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2525 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2525 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2525_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2525_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0003 */ /* [local] */ #ifndef DEF___FIIterator_1_Windows__CApplicationModel__CPackage_USE #define DEF___FIIterator_1_Windows__CApplicationModel__CPackage_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("0217f069-025c-5ee6-a87f-e782e3b623ae")) IIterator<ABI::Windows::ApplicationModel::Package*> : IIterator_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Package*, ABI::Windows::ApplicationModel::IPackage*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<Windows.ApplicationModel.Package>"; } }; typedef IIterator<ABI::Windows::ApplicationModel::Package*> __FIIterator_1_Windows__CApplicationModel__CPackage_t; #define ____FIIterator_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define __FIIterator_1_Windows__CApplicationModel__CPackage ABI::Windows::Foundation::Collections::__FIIterator_1_Windows__CApplicationModel__CPackage_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterator_1_Windows__CApplicationModel__CPackage_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0003 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0003_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0003_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2526 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2526 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2526_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2526_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0004 */ /* [local] */ #ifndef DEF___FIIterable_1_Windows__CApplicationModel__CPackage_USE #define DEF___FIIterable_1_Windows__CApplicationModel__CPackage_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("69ad6aa7-0c49-5f27-a5eb-ef4d59467b6d")) IIterable<ABI::Windows::ApplicationModel::Package*> : IIterable_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Package*, ABI::Windows::ApplicationModel::IPackage*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<Windows.ApplicationModel.Package>"; } }; typedef IIterable<ABI::Windows::ApplicationModel::Package*> __FIIterable_1_Windows__CApplicationModel__CPackage_t; #define ____FIIterable_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define __FIIterable_1_Windows__CApplicationModel__CPackage ABI::Windows::Foundation::Collections::__FIIterable_1_Windows__CApplicationModel__CPackage_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterable_1_Windows__CApplicationModel__CPackage_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0004 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0004_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0004_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2527 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2527 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2527_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2527_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0005 */ /* [local] */ #ifndef DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #define DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("8246ed12-33e8-52b3-a5c5-19779de9999e")) IVectorView<ABI::Windows::ApplicationModel::AppInfo*> : IVectorView_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::AppInfo*, ABI::Windows::ApplicationModel::IAppInfo*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.AppInfo>"; } }; typedef IVectorView<ABI::Windows::ApplicationModel::AppInfo*> __FIVectorView_1_Windows__CApplicationModel__CAppInfo_t; #define ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo ABI::Windows::Foundation::Collections::__FIVectorView_1_Windows__CApplicationModel__CAppInfo_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0005 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0005_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0005_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2528 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2528 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2528_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2528_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0006 */ /* [local] */ #ifndef DEF___FIVectorView_1_Windows__CApplicationModel__CPackage_USE #define DEF___FIVectorView_1_Windows__CApplicationModel__CPackage_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("0263c4d4-195c-5dc5-a7ca-6806ceca420b")) IVectorView<ABI::Windows::ApplicationModel::Package*> : IVectorView_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Package*, ABI::Windows::ApplicationModel::IPackage*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.Package>"; } }; typedef IVectorView<ABI::Windows::ApplicationModel::Package*> __FIVectorView_1_Windows__CApplicationModel__CPackage_t; #define ____FIVectorView_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define __FIVectorView_1_Windows__CApplicationModel__CPackage ABI::Windows::Foundation::Collections::__FIVectorView_1_Windows__CApplicationModel__CPackage_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIVectorView_1_Windows__CApplicationModel__CPackage_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0006 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0006_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0006_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2529 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2529 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2529_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2529_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0007 */ /* [local] */ #ifndef DEF___FIVector_1_Windows__CApplicationModel__CPackage_USE #define DEF___FIVector_1_Windows__CApplicationModel__CPackage_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("d1bb509e-6989-5c69-b1ff-d1702fe8aca3")) IVector<ABI::Windows::ApplicationModel::Package*> : IVector_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Package*, ABI::Windows::ApplicationModel::IPackage*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IVector`1<Windows.ApplicationModel.Package>"; } }; typedef IVector<ABI::Windows::ApplicationModel::Package*> __FIVector_1_Windows__CApplicationModel__CPackage_t; #define ____FIVector_1_Windows__CApplicationModel__CPackage_FWD_DEFINED__ #define __FIVector_1_Windows__CApplicationModel__CPackage ABI::Windows::Foundation::Collections::__FIVector_1_Windows__CApplicationModel__CPackage_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIVector_1_Windows__CApplicationModel__CPackage_USE */ #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class SuspendingEventArgs; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { interface ISuspendingEventArgs; } /*ApplicationModel*/ } /*Windows*/ } #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0007 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0007_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0007_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2530 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2530 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2530_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2530_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0008 */ /* [local] */ #ifndef DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_USE #define DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("338579bf-1a35-5cc4-a622-a6f384fd892c")) IEventHandler<ABI::Windows::ApplicationModel::SuspendingEventArgs*> : IEventHandler_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::SuspendingEventArgs*, ABI::Windows::ApplicationModel::ISuspendingEventArgs*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.EventHandler`1<Windows.ApplicationModel.SuspendingEventArgs>"; } }; typedef IEventHandler<ABI::Windows::ApplicationModel::SuspendingEventArgs*> __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_t; #define ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_FWD_DEFINED__ #define __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs ABI::Windows::Foundation::__FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_t /* ABI */ } /* Windows */ } /* Foundation */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0008 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0008_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0008_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2531 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2531 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2531_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2531_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0009 */ /* [local] */ #ifndef DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #define DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("07f25b6f-f054-5649-a5ce-b348ddc618b6")) IAsyncOperationCompletedHandler<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> : IAsyncOperationCompletedHandler_impl<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.AppInfo>>"; } }; typedef IAsyncOperationCompletedHandler<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_t; #define ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_t /* ABI */ } /* Windows */ } /* Foundation */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0009 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0009_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0009_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2532 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2532 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2532_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2532_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0010 */ /* [local] */ #ifndef DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #define DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("07543d91-8610-5152-b0e4-43d6e4cdd0cb")) IAsyncOperation<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> : IAsyncOperation_impl<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.IAsyncOperation`1<Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.AppInfo>>"; } }; typedef IAsyncOperation<__FIVectorView_1_Windows__CApplicationModel__CAppInfo*> __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_t; #define ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_FWD_DEFINED__ #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo ABI::Windows::Foundation::__FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_t /* ABI */ } /* Windows */ } /* Foundation */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_USE */ #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { namespace Core { class AppListEntry; } /*Core*/ } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { namespace Core { interface IAppListEntry; } /*Core*/ } /*ApplicationModel*/ } /*Windows*/ } #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0010 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0010_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0010_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2533 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2533 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2533_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2533_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0011 */ /* [local] */ #ifndef DEF___FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #define DEF___FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("b93e2028-50bc-599e-b3d9-427b61d26c01")) IIterator<ABI::Windows::ApplicationModel::Core::AppListEntry*> : IIterator_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Core::AppListEntry*, ABI::Windows::ApplicationModel::Core::IAppListEntry*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterator`1<Windows.ApplicationModel.Core.AppListEntry>"; } }; typedef IIterator<ABI::Windows::ApplicationModel::Core::AppListEntry*> __FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_t; #define ____FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_FWD_DEFINED__ #define __FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry ABI::Windows::Foundation::Collections::__FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterator_1_Windows__CApplicationModel__CCore__CAppListEntry_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0011 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0011_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0011_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2534 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2534 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2534_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2534_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0012 */ /* [local] */ #ifndef DEF___FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #define DEF___FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("86f4d4ef-d8fd-5fb5-807c-72da8fc9e544")) IIterable<ABI::Windows::ApplicationModel::Core::AppListEntry*> : IIterable_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Core::AppListEntry*, ABI::Windows::ApplicationModel::Core::IAppListEntry*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IIterable`1<Windows.ApplicationModel.Core.AppListEntry>"; } }; typedef IIterable<ABI::Windows::ApplicationModel::Core::AppListEntry*> __FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_t; #define ____FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_FWD_DEFINED__ #define __FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry ABI::Windows::Foundation::Collections::__FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIIterable_1_Windows__CApplicationModel__CCore__CAppListEntry_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0012 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0012_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0012_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2535 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2535 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2535_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2535_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0013 */ /* [local] */ #ifndef DEF___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #define DEF___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { namespace Collections { template <> struct __declspec(uuid("920c8b92-d5ef-5899-8776-2ad97aca6e1d")) IVectorView<ABI::Windows::ApplicationModel::Core::AppListEntry*> : IVectorView_impl<ABI::Windows::Foundation::Internal::AggregateType<ABI::Windows::ApplicationModel::Core::AppListEntry*, ABI::Windows::ApplicationModel::Core::IAppListEntry*>> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.Core.AppListEntry>"; } }; typedef IVectorView<ABI::Windows::ApplicationModel::Core::AppListEntry*> __FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t; #define ____FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_FWD_DEFINED__ #define __FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry ABI::Windows::Foundation::Collections::__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t /* ABI */ } /* Windows */ } /* Foundation */ } /* Collections */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0013 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0013_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0013_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2536 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2536 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2536_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2536_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0014 */ /* [local] */ #ifndef DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #define DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("51c74372-9452-57ce-9270-762009fbfe4d")) IAsyncOperationCompletedHandler<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> : IAsyncOperationCompletedHandler_impl<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.AsyncOperationCompletedHandler`1<Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.Core.AppListEntry>>"; } }; typedef IAsyncOperationCompletedHandler<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t; #define ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_FWD_DEFINED__ #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry ABI::Windows::Foundation::__FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t /* ABI */ } /* Windows */ } /* Foundation */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0014 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0014_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0014_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2537 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2537 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2537_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2537_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0015 */ /* [local] */ #ifndef DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #define DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE #if defined(__cplusplus) && !defined(RO_NO_TEMPLATE_NAME) } /*extern "C"*/ namespace ABI { namespace Windows { namespace Foundation { template <> struct __declspec(uuid("d3bcf8a0-3538-5dae-98d7-1f2ab88c3f01")) IAsyncOperation<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> : IAsyncOperation_impl<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> { static const wchar_t* z_get_rc_name_impl() { return L"Windows.Foundation.IAsyncOperation`1<Windows.Foundation.Collections.IVectorView`1<Windows.ApplicationModel.Core.AppListEntry>>"; } }; typedef IAsyncOperation<__FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry*> __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t; #define ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_FWD_DEFINED__ #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry ABI::Windows::Foundation::__FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_t /* ABI */ } /* Windows */ } /* Foundation */ } extern "C" { #endif //__cplusplus #endif /* DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry_USE */ #if defined(__cplusplus) } #endif // defined(__cplusplus) #include <Windows.Foundation.h> #if !defined(__windows2Eapplicationmodel2Ecore_h__) #include <Windows.ApplicationModel.Core.h> #endif // !defined(__windows2Eapplicationmodel2Ecore_h__) #if !defined(__windows2Estorage_h__) #include <Windows.Storage.h> #endif // !defined(__windows2Estorage_h__) #if !defined(__windows2Estorage2Estreams_h__) #include <Windows.Storage.Streams.h> #endif // !defined(__windows2Estorage2Estreams_h__) #if !defined(__windows2Esystem_h__) #include <Windows.System.h> #endif // !defined(__windows2Esystem_h__) #if defined(__cplusplus) extern "C" { #endif // defined(__cplusplus) #if !defined(__cplusplus) typedef struct __x_ABI_CWindows_CFoundation_CDateTime __x_ABI_CWindows_CFoundation_CDateTime; #endif #if !defined(__cplusplus) typedef struct __x_ABI_CWindows_CFoundation_CSize __x_ABI_CWindows_CFoundation_CSize; #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace Foundation { class Uri; } /*Foundation*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace Storage { class StorageFolder; } /*Storage*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace Storage { namespace Streams { class RandomAccessStreamReference; } /*Streams*/ } /*Storage*/ } /*Windows*/ } #endif #if !defined(__cplusplus) #if !defined(__cplusplus) typedef enum __x_ABI_CWindows_CSystem_CProcessorArchitecture __x_ABI_CWindows_CSystem_CProcessorArchitecture; #endif /* end if !defined(__cplusplus) */ #endif #if !defined(__cplusplus) typedef struct __x_ABI_CWindows_CApplicationModel_CPackageVersion __x_ABI_CWindows_CApplicationModel_CPackageVersion; #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class AppDisplayInfo; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class SuspendingDeferral; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class SuspendingOperation; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class PackageStatus; } /*ApplicationModel*/ } /*Windows*/ } #endif #ifdef __cplusplus namespace ABI { namespace Windows { namespace ApplicationModel { class PackageId; } /*ApplicationModel*/ } /*Windows*/ } #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0015 */ /* [local] */ #ifdef __cplusplus } /* end extern "C" */ namespace ABI { namespace Windows { namespace Foundation { typedef struct DateTime DateTime; } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #endif #ifdef __cplusplus } /* end extern "C" */ namespace ABI { namespace Windows { namespace Foundation { typedef struct Size Size; } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #endif #ifdef __cplusplus } /* end extern "C" */ namespace ABI { namespace Windows { namespace System { typedef enum ProcessorArchitecture ProcessorArchitecture; } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #endif #ifdef __cplusplus } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { typedef struct PackageVersion PackageVersion; } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #endif extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0015_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0015_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2538 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2538 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2538_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2538_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0016 */ /* [local] */ #ifndef DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo #define DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0016 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0016_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0016_v0_0_s_ifspec; #ifndef ____FIIterator_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ #define ____FIIterator_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ /* interface __FIIterator_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ /* interface __FIIterator_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIIterator_1_Windows__CApplicationModel__CAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("69cec62c-41eb-5d69-a475-29ee22323dd8") __FIIterator_1_Windows__CApplicationModel__CAppInfo : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Current( /* [retval][out] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IAppInfo **current) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HasCurrent( /* [retval][out] */ __RPC__out boolean *hasCurrent) = 0; virtual HRESULT STDMETHODCALLTYPE MoveNext( /* [retval][out] */ __RPC__out boolean *hasCurrent) = 0; virtual HRESULT STDMETHODCALLTYPE GetMany( /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) ABI::Windows::ApplicationModel::IAppInfo **items, /* [retval][out] */ __RPC__out unsigned int *actual) = 0; }; #else /* C style interface */ typedef struct __FIIterator_1_Windows__CApplicationModel__CAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Current )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIAppInfo **current); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HasCurrent )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__out boolean *hasCurrent); HRESULT ( STDMETHODCALLTYPE *MoveNext )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__out boolean *hasCurrent); HRESULT ( STDMETHODCALLTYPE *GetMany )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CApplicationModel_CIAppInfo **items, /* [retval][out] */ __RPC__out unsigned int *actual); END_INTERFACE } __FIIterator_1_Windows__CApplicationModel__CAppInfoVtbl; interface __FIIterator_1_Windows__CApplicationModel__CAppInfo { CONST_VTBL struct __FIIterator_1_Windows__CApplicationModel__CAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_get_Current(This,current) \ ( (This)->lpVtbl -> get_Current(This,current) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_get_HasCurrent(This,hasCurrent) \ ( (This)->lpVtbl -> get_HasCurrent(This,hasCurrent) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_MoveNext(This,hasCurrent) \ ( (This)->lpVtbl -> MoveNext(This,hasCurrent) ) #define __FIIterator_1_Windows__CApplicationModel__CAppInfo_GetMany(This,capacity,items,actual) \ ( (This)->lpVtbl -> GetMany(This,capacity,items,actual) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIIterator_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0017 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIIterator_1_Windows__CApplicationModel__CAppInfo */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0017 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0017_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0017_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2539 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2539 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2539_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2539_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0018 */ /* [local] */ #ifndef DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo #define DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0018 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0018_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0018_v0_0_s_ifspec; #ifndef ____FIIterable_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ #define ____FIIterable_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ /* interface __FIIterable_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ /* interface __FIIterable_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIIterable_1_Windows__CApplicationModel__CAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("63d0bffe-0e34-55b3-83d5-314caff2b137") __FIIterable_1_Windows__CApplicationModel__CAppInfo : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE First( /* [retval][out] */ __RPC__deref_out_opt __FIIterator_1_Windows__CApplicationModel__CAppInfo **first) = 0; }; #else /* C style interface */ typedef struct __FIIterable_1_Windows__CApplicationModel__CAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *First )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__deref_out_opt __FIIterator_1_Windows__CApplicationModel__CAppInfo **first); END_INTERFACE } __FIIterable_1_Windows__CApplicationModel__CAppInfoVtbl; interface __FIIterable_1_Windows__CApplicationModel__CAppInfo { CONST_VTBL struct __FIIterable_1_Windows__CApplicationModel__CAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIIterable_1_Windows__CApplicationModel__CAppInfo_First(This,first) \ ( (This)->lpVtbl -> First(This,first) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIIterable_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0019 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIIterable_1_Windows__CApplicationModel__CAppInfo */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0019 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0019_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0019_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2540 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2540 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2540_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2540_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0020 */ /* [local] */ #ifndef DEF___FIIterator_1_Windows__CApplicationModel__CPackage #define DEF___FIIterator_1_Windows__CApplicationModel__CPackage #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0020 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0020_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0020_v0_0_s_ifspec; #ifndef ____FIIterator_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ #define ____FIIterator_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ /* interface __FIIterator_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ /* interface __FIIterator_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIIterator_1_Windows__CApplicationModel__CPackage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0217f069-025c-5ee6-a87f-e782e3b623ae") __FIIterator_1_Windows__CApplicationModel__CPackage : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Current( /* [retval][out] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackage **current) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HasCurrent( /* [retval][out] */ __RPC__out boolean *hasCurrent) = 0; virtual HRESULT STDMETHODCALLTYPE MoveNext( /* [retval][out] */ __RPC__out boolean *hasCurrent) = 0; virtual HRESULT STDMETHODCALLTYPE GetMany( /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) ABI::Windows::ApplicationModel::IPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual) = 0; }; #else /* C style interface */ typedef struct __FIIterator_1_Windows__CApplicationModel__CPackageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Current )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackage **current); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HasCurrent )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__out boolean *hasCurrent); HRESULT ( STDMETHODCALLTYPE *MoveNext )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__out boolean *hasCurrent); HRESULT ( STDMETHODCALLTYPE *GetMany )( __RPC__in __FIIterator_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CApplicationModel_CIPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual); END_INTERFACE } __FIIterator_1_Windows__CApplicationModel__CPackageVtbl; interface __FIIterator_1_Windows__CApplicationModel__CPackage { CONST_VTBL struct __FIIterator_1_Windows__CApplicationModel__CPackageVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIIterator_1_Windows__CApplicationModel__CPackage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_get_Current(This,current) \ ( (This)->lpVtbl -> get_Current(This,current) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_get_HasCurrent(This,hasCurrent) \ ( (This)->lpVtbl -> get_HasCurrent(This,hasCurrent) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_MoveNext(This,hasCurrent) \ ( (This)->lpVtbl -> MoveNext(This,hasCurrent) ) #define __FIIterator_1_Windows__CApplicationModel__CPackage_GetMany(This,capacity,items,actual) \ ( (This)->lpVtbl -> GetMany(This,capacity,items,actual) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIIterator_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0021 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIIterator_1_Windows__CApplicationModel__CPackage */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0021 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0021_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0021_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2541 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2541 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2541_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2541_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0022 */ /* [local] */ #ifndef DEF___FIIterable_1_Windows__CApplicationModel__CPackage #define DEF___FIIterable_1_Windows__CApplicationModel__CPackage #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0022 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0022_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0022_v0_0_s_ifspec; #ifndef ____FIIterable_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ #define ____FIIterable_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ /* interface __FIIterable_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ /* interface __FIIterable_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIIterable_1_Windows__CApplicationModel__CPackage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("69ad6aa7-0c49-5f27-a5eb-ef4d59467b6d") __FIIterable_1_Windows__CApplicationModel__CPackage : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE First( /* [retval][out] */ __RPC__deref_out_opt __FIIterator_1_Windows__CApplicationModel__CPackage **first) = 0; }; #else /* C style interface */ typedef struct __FIIterable_1_Windows__CApplicationModel__CPackageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *First )( __RPC__in __FIIterable_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__deref_out_opt __FIIterator_1_Windows__CApplicationModel__CPackage **first); END_INTERFACE } __FIIterable_1_Windows__CApplicationModel__CPackageVtbl; interface __FIIterable_1_Windows__CApplicationModel__CPackage { CONST_VTBL struct __FIIterable_1_Windows__CApplicationModel__CPackageVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIIterable_1_Windows__CApplicationModel__CPackage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIIterable_1_Windows__CApplicationModel__CPackage_First(This,first) \ ( (This)->lpVtbl -> First(This,first) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIIterable_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0023 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIIterable_1_Windows__CApplicationModel__CPackage */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0023 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0023_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0023_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2542 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2542 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2542_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2542_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0024 */ /* [local] */ #ifndef DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo #define DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0024 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0024_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0024_v0_0_s_ifspec; #ifndef ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ #define ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ /* interface __FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ /* interface __FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIVectorView_1_Windows__CApplicationModel__CAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("8246ed12-33e8-52b3-a5c5-19779de9999e") __FIVectorView_1_Windows__CApplicationModel__CAppInfo : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE GetAt( /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IAppInfo **item) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Size( /* [retval][out] */ __RPC__out unsigned int *size) = 0; virtual HRESULT STDMETHODCALLTYPE IndexOf( /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IAppInfo *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found) = 0; virtual HRESULT STDMETHODCALLTYPE GetMany( /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) ABI::Windows::ApplicationModel::IAppInfo **items, /* [retval][out] */ __RPC__out unsigned int *actual) = 0; }; #else /* C style interface */ typedef struct __FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *GetAt )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIAppInfo **item); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__out unsigned int *size); HRESULT ( STDMETHODCALLTYPE *IndexOf )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIAppInfo *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found); HRESULT ( STDMETHODCALLTYPE *GetMany )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CApplicationModel_CIAppInfo **items, /* [retval][out] */ __RPC__out unsigned int *actual); END_INTERFACE } __FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl; interface __FIVectorView_1_Windows__CApplicationModel__CAppInfo { CONST_VTBL struct __FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetAt(This,index,item) \ ( (This)->lpVtbl -> GetAt(This,index,item) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_get_Size(This,size) \ ( (This)->lpVtbl -> get_Size(This,size) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_IndexOf(This,item,index,found) \ ( (This)->lpVtbl -> IndexOf(This,item,index,found) ) #define __FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetMany(This,startIndex,capacity,items,actual) \ ( (This)->lpVtbl -> GetMany(This,startIndex,capacity,items,actual) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0025 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0025 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0025_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0025_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2543 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2543 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2543_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2543_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0026 */ /* [local] */ #ifndef DEF___FIVectorView_1_Windows__CApplicationModel__CPackage #define DEF___FIVectorView_1_Windows__CApplicationModel__CPackage #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0026 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0026_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0026_v0_0_s_ifspec; #ifndef ____FIVectorView_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ #define ____FIVectorView_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ /* interface __FIVectorView_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ /* interface __FIVectorView_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIVectorView_1_Windows__CApplicationModel__CPackage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0263c4d4-195c-5dc5-a7ca-6806ceca420b") __FIVectorView_1_Windows__CApplicationModel__CPackage : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE GetAt( /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackage **item) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Size( /* [retval][out] */ __RPC__out unsigned int *size) = 0; virtual HRESULT STDMETHODCALLTYPE IndexOf( /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IPackage *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found) = 0; virtual HRESULT STDMETHODCALLTYPE GetMany( /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) ABI::Windows::ApplicationModel::IPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual) = 0; }; #else /* C style interface */ typedef struct __FIVectorView_1_Windows__CApplicationModel__CPackageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *GetAt )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackage **item); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__out unsigned int *size); HRESULT ( STDMETHODCALLTYPE *IndexOf )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIPackage *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found); HRESULT ( STDMETHODCALLTYPE *GetMany )( __RPC__in __FIVectorView_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CApplicationModel_CIPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual); END_INTERFACE } __FIVectorView_1_Windows__CApplicationModel__CPackageVtbl; interface __FIVectorView_1_Windows__CApplicationModel__CPackage { CONST_VTBL struct __FIVectorView_1_Windows__CApplicationModel__CPackageVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIVectorView_1_Windows__CApplicationModel__CPackage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_GetAt(This,index,item) \ ( (This)->lpVtbl -> GetAt(This,index,item) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_get_Size(This,size) \ ( (This)->lpVtbl -> get_Size(This,size) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_IndexOf(This,item,index,found) \ ( (This)->lpVtbl -> IndexOf(This,item,index,found) ) #define __FIVectorView_1_Windows__CApplicationModel__CPackage_GetMany(This,startIndex,capacity,items,actual) \ ( (This)->lpVtbl -> GetMany(This,startIndex,capacity,items,actual) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIVectorView_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0027 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIVectorView_1_Windows__CApplicationModel__CPackage */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0027 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0027_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0027_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2544 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2544 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2544_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2544_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0028 */ /* [local] */ #ifndef DEF___FIVector_1_Windows__CApplicationModel__CPackage #define DEF___FIVector_1_Windows__CApplicationModel__CPackage #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0028 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0028_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0028_v0_0_s_ifspec; #ifndef ____FIVector_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ #define ____FIVector_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ /* interface __FIVector_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ /* interface __FIVector_1_Windows__CApplicationModel__CPackage */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIVector_1_Windows__CApplicationModel__CPackage; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("d1bb509e-6989-5c69-b1ff-d1702fe8aca3") __FIVector_1_Windows__CApplicationModel__CPackage : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE GetAt( /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackage **item) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Size( /* [retval][out] */ __RPC__out unsigned int *size) = 0; virtual HRESULT STDMETHODCALLTYPE GetView( /* [retval][out] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CPackage **view) = 0; virtual HRESULT STDMETHODCALLTYPE IndexOf( /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IPackage *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found) = 0; virtual HRESULT STDMETHODCALLTYPE SetAt( /* [in] */ unsigned int index, /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IPackage *item) = 0; virtual HRESULT STDMETHODCALLTYPE InsertAt( /* [in] */ unsigned int index, /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IPackage *item) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAt( /* [in] */ unsigned int index) = 0; virtual HRESULT STDMETHODCALLTYPE Append( /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::IPackage *item) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAtEnd( void) = 0; virtual HRESULT STDMETHODCALLTYPE Clear( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetMany( /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) ABI::Windows::ApplicationModel::IPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual) = 0; virtual HRESULT STDMETHODCALLTYPE ReplaceAll( /* [in] */ unsigned int count, /* [size_is][in] */ __RPC__in_ecount_full(count) ABI::Windows::ApplicationModel::IPackage **value) = 0; }; #else /* C style interface */ typedef struct __FIVector_1_Windows__CApplicationModel__CPackageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *GetAt )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int index, /* [retval][out] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackage **item); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__out unsigned int *size); HRESULT ( STDMETHODCALLTYPE *GetView )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [retval][out] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CPackage **view); HRESULT ( STDMETHODCALLTYPE *IndexOf )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIPackage *item, /* [out] */ __RPC__out unsigned int *index, /* [retval][out] */ __RPC__out boolean *found); HRESULT ( STDMETHODCALLTYPE *SetAt )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int index, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIPackage *item); HRESULT ( STDMETHODCALLTYPE *InsertAt )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int index, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIPackage *item); HRESULT ( STDMETHODCALLTYPE *RemoveAt )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int index); HRESULT ( STDMETHODCALLTYPE *Append )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CIPackage *item); HRESULT ( STDMETHODCALLTYPE *RemoveAtEnd )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *Clear )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This); HRESULT ( STDMETHODCALLTYPE *GetMany )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int startIndex, /* [in] */ unsigned int capacity, /* [size_is][length_is][out] */ __RPC__out_ecount_part(capacity, *actual) __x_ABI_CWindows_CApplicationModel_CIPackage **items, /* [retval][out] */ __RPC__out unsigned int *actual); HRESULT ( STDMETHODCALLTYPE *ReplaceAll )( __RPC__in __FIVector_1_Windows__CApplicationModel__CPackage * This, /* [in] */ unsigned int count, /* [size_is][in] */ __RPC__in_ecount_full(count) __x_ABI_CWindows_CApplicationModel_CIPackage **value); END_INTERFACE } __FIVector_1_Windows__CApplicationModel__CPackageVtbl; interface __FIVector_1_Windows__CApplicationModel__CPackage { CONST_VTBL struct __FIVector_1_Windows__CApplicationModel__CPackageVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIVector_1_Windows__CApplicationModel__CPackage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetAt(This,index,item) \ ( (This)->lpVtbl -> GetAt(This,index,item) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_get_Size(This,size) \ ( (This)->lpVtbl -> get_Size(This,size) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetView(This,view) \ ( (This)->lpVtbl -> GetView(This,view) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_IndexOf(This,item,index,found) \ ( (This)->lpVtbl -> IndexOf(This,item,index,found) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_SetAt(This,index,item) \ ( (This)->lpVtbl -> SetAt(This,index,item) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_InsertAt(This,index,item) \ ( (This)->lpVtbl -> InsertAt(This,index,item) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_RemoveAt(This,index) \ ( (This)->lpVtbl -> RemoveAt(This,index) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_Append(This,item) \ ( (This)->lpVtbl -> Append(This,item) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_RemoveAtEnd(This) \ ( (This)->lpVtbl -> RemoveAtEnd(This) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_Clear(This) \ ( (This)->lpVtbl -> Clear(This) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_GetMany(This,startIndex,capacity,items,actual) \ ( (This)->lpVtbl -> GetMany(This,startIndex,capacity,items,actual) ) #define __FIVector_1_Windows__CApplicationModel__CPackage_ReplaceAll(This,count,value) \ ( (This)->lpVtbl -> ReplaceAll(This,count,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIVector_1_Windows__CApplicationModel__CPackage_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0029 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIVector_1_Windows__CApplicationModel__CPackage */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0029 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0029_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0029_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2545 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2545 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2545_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2545_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0030 */ /* [local] */ #ifndef DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs #define DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0030 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0030_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0030_v0_0_s_ifspec; #ifndef ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_INTERFACE_DEFINED__ #define ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_INTERFACE_DEFINED__ /* interface __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs */ /* [unique][uuid][object] */ /* interface __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("338579bf-1a35-5cc4-a622-a6f384fd892c") __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Invoke( /* [in] */ __RPC__in_opt IInspectable *sender, /* [in] */ __RPC__in_opt ABI::Windows::ApplicationModel::ISuspendingEventArgs *e) = 0; }; #else /* C style interface */ typedef struct __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs * This); HRESULT ( STDMETHODCALLTYPE *Invoke )( __RPC__in __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs * This, /* [in] */ __RPC__in_opt IInspectable *sender, /* [in] */ __RPC__in_opt __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs *e); END_INTERFACE } __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgsVtbl; interface __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs { CONST_VTBL struct __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgsVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_Invoke(This,sender,e) \ ( (This)->lpVtbl -> Invoke(This,sender,e) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0031 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIEventHandler_1_Windows__CApplicationModel__CSuspendingEventArgs */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0031 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0031_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0031_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2546 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2546 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2546_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2546_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0032 */ /* [local] */ #ifndef DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo #define DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0032 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0032_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0032_v0_0_s_ifspec; #ifndef ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ #define ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ /* interface __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ /* interface __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("07f25b6f-f054-5649-a5ce-b348ddc618b6") __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Invoke( /* [in] */ __RPC__in_opt __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo *asyncInfo, /* [in] */ AsyncStatus status) = 0; }; #else /* C style interface */ typedef struct __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); HRESULT ( STDMETHODCALLTYPE *Invoke )( __RPC__in __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in_opt __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo *asyncInfo, /* [in] */ AsyncStatus status); END_INTERFACE } __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl; interface __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo { CONST_VTBL struct __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_Invoke(This,asyncInfo,status) \ ( (This)->lpVtbl -> Invoke(This,asyncInfo,status) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0033 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0033 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0033_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0033_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2547 */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_2547 */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2547_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_2547_v0_0_s_ifspec; /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0034 */ /* [local] */ #ifndef DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo #define DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo #if !defined(__cplusplus) || defined(RO_NO_TEMPLATE_NAME) /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0034 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0034_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0034_v0_0_s_ifspec; #ifndef ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ #define ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ /* interface __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ /* interface __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ /* [unique][uuid][object] */ EXTERN_C const IID IID___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("07543d91-8610-5152-b0e4-43d6e4cdd0cb") __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo : public IInspectable { public: virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_Completed( /* [in] */ __RPC__in_opt __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo *handler) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Completed( /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo **handler) = 0; virtual HRESULT STDMETHODCALLTYPE GetResults( /* [retval][out] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CAppInfo **results) = 0; }; #else /* C style interface */ typedef struct __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_Completed )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [in] */ __RPC__in_opt __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo *handler); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Completed )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__deref_out_opt __FIAsyncOperationCompletedHandler_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo **handler); HRESULT ( STDMETHODCALLTYPE *GetResults )( __RPC__in __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo * This, /* [retval][out] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CAppInfo **results); END_INTERFACE } __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl; interface __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo { CONST_VTBL struct __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_put_Completed(This,handler) \ ( (This)->lpVtbl -> put_Completed(This,handler) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_get_Completed(This,handler) \ ( (This)->lpVtbl -> get_Completed(This,handler) ) #define __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_GetResults(This,results) \ ( (This)->lpVtbl -> GetResults(This,results) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0035 */ /* [local] */ #endif /* pinterface */ #endif /* DEF___FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CAppInfo */ #if !defined(__cplusplus) struct __x_ABI_CWindows_CApplicationModel_CPackageVersion { UINT16 Major; UINT16 Minor; UINT16 Build; UINT16 Revision; } ; #endif #if !defined(____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IAppDisplayInfo[] = L"Windows.ApplicationModel.IAppDisplayInfo"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0035 */ /* [local] */ #ifdef __cplusplus } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { struct PackageVersion { UINT16 Major; UINT16 Minor; UINT16 Build; UINT16 Revision; } ; } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #endif extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0035_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0035_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IAppDisplayInfo */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("1AEB1103-E4D4-41AA-A4F6-C4A276E79EAC") IAppDisplayInfo : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DisplayName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Description( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual HRESULT STDMETHODCALLTYPE GetLogo( /* [in] */ ABI::Windows::Foundation::Size size, /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::Storage::Streams::IRandomAccessStreamReference **value) = 0; }; extern const __declspec(selectany) IID & IID_IAppDisplayInfo = __uuidof(IAppDisplayInfo); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DisplayName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); HRESULT ( STDMETHODCALLTYPE *GetLogo )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo * This, /* [in] */ __x_ABI_CWindows_CFoundation_CSize size, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CStorage_CStreams_CIRandomAccessStreamReference **value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfoVtbl; interface __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_get_DisplayName(This,value) \ ( (This)->lpVtbl -> get_DisplayName(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_get_Description(This,value) \ ( (This)->lpVtbl -> get_Description(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_GetLogo(This,size,value) \ ( (This)->lpVtbl -> GetLogo(This,size,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0036 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIAppInfo_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IAppInfo[] = L"Windows.ApplicationModel.IAppInfo"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIAppInfo_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0036 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0036_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0036_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIAppInfo_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIAppInfo_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIAppInfo */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IAppInfo */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIAppInfo; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("CF7F59B3-6A09-4DE8-A6C0-5792D56880D1") IAppInfo : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Id( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_AppUserModelId( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DisplayInfo( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IAppDisplayInfo **value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_PackageFamilyName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; }; extern const __declspec(selectany) IID & IID_IAppInfo = __uuidof(IAppInfo); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIAppInfoVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Id )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_AppUserModelId )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DisplayInfo )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIAppDisplayInfo **value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_PackageFamilyName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIAppInfo * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIAppInfoVtbl; interface __x_ABI_CWindows_CApplicationModel_CIAppInfo { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIAppInfoVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_get_Id(This,value) \ ( (This)->lpVtbl -> get_Id(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_get_AppUserModelId(This,value) \ ( (This)->lpVtbl -> get_AppUserModelId(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_get_DisplayInfo(This,value) \ ( (This)->lpVtbl -> get_DisplayInfo(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIAppInfo_get_PackageFamilyName(This,value) \ ( (This)->lpVtbl -> get_PackageFamilyName(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIAppInfo_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0037 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_ISuspendingDeferral[] = L"Windows.ApplicationModel.ISuspendingDeferral"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0037 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0037_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0037_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::ISuspendingDeferral */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CISuspendingDeferral; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("59140509-8BC9-4EB4-B636-DABDC4F46F66") ISuspendingDeferral : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE Complete( void) = 0; }; extern const __declspec(selectany) IID & IID_ISuspendingDeferral = __uuidof(ISuspendingDeferral); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CISuspendingDeferralVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *Complete )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral * This); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CISuspendingDeferralVtbl; interface __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CISuspendingDeferralVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_Complete(This) \ ( (This)->lpVtbl -> Complete(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingDeferral_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0038 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_ISuspendingOperation[] = L"Windows.ApplicationModel.ISuspendingOperation"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0038 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0038_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0038_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CISuspendingOperation */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::ISuspendingOperation */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CISuspendingOperation; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("9DA4CA41-20E1-4E9B-9F65-A9F435340C3A") ISuspendingOperation : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE GetDeferral( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::ISuspendingDeferral **deferral) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Deadline( /* [out][retval] */ __RPC__out ABI::Windows::Foundation::DateTime *value) = 0; }; extern const __declspec(selectany) IID & IID_ISuspendingOperation = __uuidof(ISuspendingOperation); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CISuspendingOperationVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *GetDeferral )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CISuspendingDeferral **deferral); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Deadline )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingOperation * This, /* [out][retval] */ __RPC__out __x_ABI_CWindows_CFoundation_CDateTime *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CISuspendingOperationVtbl; interface __x_ABI_CWindows_CApplicationModel_CISuspendingOperation { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CISuspendingOperationVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_GetDeferral(This,deferral) \ ( (This)->lpVtbl -> GetDeferral(This,deferral) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingOperation_get_Deadline(This,value) \ ( (This)->lpVtbl -> get_Deadline(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingOperation_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0039 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_ISuspendingEventArgs[] = L"Windows.ApplicationModel.ISuspendingEventArgs"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0039 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0039_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0039_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::ISuspendingEventArgs */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("96061C05-2DBA-4D08-B0BD-2B30A131C6AA") ISuspendingEventArgs : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_SuspendingOperation( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::ISuspendingOperation **value) = 0; }; extern const __declspec(selectany) IID & IID_ISuspendingEventArgs = __uuidof(ISuspendingEventArgs); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_SuspendingOperation )( __RPC__in __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CISuspendingOperation **value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgsVtbl; interface __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgsVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_get_SuspendingOperation(This,value) \ ( (This)->lpVtbl -> get_SuspendingOperation(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CISuspendingEventArgs_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0040 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackageIdWithMetadata[] = L"Windows.ApplicationModel.IPackageIdWithMetadata"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0040 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0040_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0040_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackageIdWithMetadata */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("40577A7C-0C9E-443D-9074-855F5CE0A08D") IPackageIdWithMetadata : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ProductId( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Author( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; }; extern const __declspec(selectany) IID & IID_IPackageIdWithMetadata = __uuidof(IPackageIdWithMetadata); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadataVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ProductId )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Author )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadataVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadataVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_get_ProductId(This,value) \ ( (This)->lpVtbl -> get_ProductId(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_get_Author(This,value) \ ( (This)->lpVtbl -> get_Author(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageIdWithMetadata_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0041 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackageWithMetadata[] = L"Windows.ApplicationModel.IPackageWithMetadata"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0041 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0041_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0041_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackageWithMetadata */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("95949780-1DE9-40F2-B452-0DE9F1910012") IPackageWithMetadata : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_InstallDate( /* [out][retval] */ __RPC__out ABI::Windows::Foundation::DateTime *value) = 0; virtual HRESULT STDMETHODCALLTYPE GetThumbnailToken( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual HRESULT STDMETHODCALLTYPE Launch( /* [in] */ __RPC__in HSTRING parameters) = 0; }; extern const __declspec(selectany) IID & IID_IPackageWithMetadata = __uuidof(IPackageWithMetadata); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadataVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_InstallDate )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [out][retval] */ __RPC__out __x_ABI_CWindows_CFoundation_CDateTime *value); HRESULT ( STDMETHODCALLTYPE *GetThumbnailToken )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); HRESULT ( STDMETHODCALLTYPE *Launch )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata * This, /* [in] */ __RPC__in HSTRING parameters); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadataVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadataVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_get_InstallDate(This,value) \ ( (This)->lpVtbl -> get_InstallDate(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_GetThumbnailToken(This,value) \ ( (This)->lpVtbl -> GetThumbnailToken(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_Launch(This,parameters) \ ( (This)->lpVtbl -> Launch(This,parameters) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageWithMetadata_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0042 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackageStatus_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackageStatus[] = L"Windows.ApplicationModel.IPackageStatus"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackageStatus_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0042 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0042_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0042_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackageStatus */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackageStatus */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackageStatus; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("5FE74F71-A365-4C09-A02D-046D525EA1DA") IPackageStatus : public IInspectable { public: virtual HRESULT STDMETHODCALLTYPE VerifyIsOK( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_NotAvailable( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_PackageOffline( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DataOffline( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Disabled( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_NeedsRemediation( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_LicenseIssue( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Modified( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Tampered( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DependencyIssue( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Servicing( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DeploymentInProgress( /* [out][retval] */ __RPC__out boolean *value) = 0; }; extern const __declspec(selectany) IID & IID_IPackageStatus = __uuidof(IPackageStatus); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageStatusVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out] */ __RPC__out TrustLevel *trustLevel); HRESULT ( STDMETHODCALLTYPE *VerifyIsOK )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_NotAvailable )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_PackageOffline )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DataOffline )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Disabled )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_NeedsRemediation )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_LicenseIssue )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Modified )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tampered )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DependencyIssue )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Servicing )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DeploymentInProgress )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatus * This, /* [out][retval] */ __RPC__out boolean *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageStatusVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackageStatus { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageStatusVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_VerifyIsOK(This,value) \ ( (This)->lpVtbl -> VerifyIsOK(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_NotAvailable(This,value) \ ( (This)->lpVtbl -> get_NotAvailable(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_PackageOffline(This,value) \ ( (This)->lpVtbl -> get_PackageOffline(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_DataOffline(This,value) \ ( (This)->lpVtbl -> get_DataOffline(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_Disabled(This,value) \ ( (This)->lpVtbl -> get_Disabled(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_NeedsRemediation(This,value) \ ( (This)->lpVtbl -> get_NeedsRemediation(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_LicenseIssue(This,value) \ ( (This)->lpVtbl -> get_LicenseIssue(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_Modified(This,value) \ ( (This)->lpVtbl -> get_Modified(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_Tampered(This,value) \ ( (This)->lpVtbl -> get_Tampered(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_DependencyIssue(This,value) \ ( (This)->lpVtbl -> get_DependencyIssue(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_Servicing(This,value) \ ( (This)->lpVtbl -> get_Servicing(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatus_get_DeploymentInProgress(This,value) \ ( (This)->lpVtbl -> get_DeploymentInProgress(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageStatus_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0043 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackageId_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackageId[] = L"Windows.ApplicationModel.IPackageId"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackageId_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0043 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0043_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0043_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageId_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageId_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackageId */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackageId */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackageId; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("1ADB665E-37C7-4790-9980-DD7AE74E8BB2") IPackageId : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Name( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Version( /* [out][retval] */ __RPC__out ABI::Windows::ApplicationModel::PackageVersion *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Architecture( /* [out][retval] */ __RPC__out ABI::Windows::System::ProcessorArchitecture *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ResourceId( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Publisher( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_PublisherId( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_FullName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_FamilyName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; }; extern const __declspec(selectany) IID & IID_IPackageId = __uuidof(IPackageId); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageIdVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Version )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__out __x_ABI_CWindows_CApplicationModel_CPackageVersion *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Architecture )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__out __x_ABI_CWindows_CSystem_CProcessorArchitecture *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ResourceId )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Publisher )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_PublisherId )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_FullName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_FamilyName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageId * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageIdVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackageId { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageIdVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackageId_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_Name(This,value) \ ( (This)->lpVtbl -> get_Name(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_Version(This,value) \ ( (This)->lpVtbl -> get_Version(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_Architecture(This,value) \ ( (This)->lpVtbl -> get_Architecture(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_ResourceId(This,value) \ ( (This)->lpVtbl -> get_ResourceId(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_Publisher(This,value) \ ( (This)->lpVtbl -> get_Publisher(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_PublisherId(This,value) \ ( (This)->lpVtbl -> get_PublisherId(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_FullName(This,value) \ ( (This)->lpVtbl -> get_FullName(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageId_get_FamilyName(This,value) \ ( (This)->lpVtbl -> get_FamilyName(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageId_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0044 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackage_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackage[] = L"Windows.ApplicationModel.IPackage"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackage_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0044 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0044_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0044_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackage */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackage */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackage; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("163C792F-BD75-413C-BF23-B1FE7B95D825") IPackage : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Id( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackageId **value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_InstalledLocation( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::Storage::IStorageFolder **value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsFramework( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Dependencies( /* [out][retval] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CPackage **value) = 0; }; extern const __declspec(selectany) IID & IID_IPackage = __uuidof(IPackage); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Id )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackageId **value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_InstalledLocation )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CStorage_CIStorageFolder **value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsFramework )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Dependencies )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage * This, /* [out][retval] */ __RPC__deref_out_opt __FIVectorView_1_Windows__CApplicationModel__CPackage **value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackage { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackage_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_get_Id(This,value) \ ( (This)->lpVtbl -> get_Id(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_get_InstalledLocation(This,value) \ ( (This)->lpVtbl -> get_InstalledLocation(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_get_IsFramework(This,value) \ ( (This)->lpVtbl -> get_IsFramework(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage_get_Dependencies(This,value) \ ( (This)->lpVtbl -> get_Dependencies(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0045 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackage2_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackage2[] = L"Windows.ApplicationModel.IPackage2"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackage2_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0045 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0045_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0045_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage2_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage2_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackage2 */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackage2 */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackage2; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("A6612FB6-7688-4ACE-95FB-359538E7AA01") IPackage2 : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DisplayName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_PublisherDisplayName( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Description( /* [out][retval] */ __RPC__deref_out_opt HSTRING *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Logo( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::Foundation::IUriRuntimeClass **value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsResourcePackage( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsBundle( /* [out][retval] */ __RPC__out boolean *value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsDevelopmentMode( /* [out][retval] */ __RPC__out boolean *value) = 0; }; extern const __declspec(selectany) IID & IID_IPackage2 = __uuidof(IPackage2); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackage2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DisplayName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_PublisherDisplayName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__deref_out_opt HSTRING *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Logo )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CFoundation_CIUriRuntimeClass **value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsResourcePackage )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsBundle )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__out boolean *value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsDevelopmentMode )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage2 * This, /* [out][retval] */ __RPC__out boolean *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackage2Vtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackage2 { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackage2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackage2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_DisplayName(This,value) \ ( (This)->lpVtbl -> get_DisplayName(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_PublisherDisplayName(This,value) \ ( (This)->lpVtbl -> get_PublisherDisplayName(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_Description(This,value) \ ( (This)->lpVtbl -> get_Description(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_Logo(This,value) \ ( (This)->lpVtbl -> get_Logo(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_IsResourcePackage(This,value) \ ( (This)->lpVtbl -> get_IsResourcePackage(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_IsBundle(This,value) \ ( (This)->lpVtbl -> get_IsBundle(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage2_get_IsDevelopmentMode(This,value) \ ( (This)->lpVtbl -> get_IsDevelopmentMode(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage2_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0046 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackage3_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackage3[] = L"Windows.ApplicationModel.IPackage3"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackage3_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0046 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0046_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0046_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackage3_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackage3_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackage3 */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackage3 */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackage3; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("5F738B61-F86A-4917-93D1-F1EE9D3B35D9") IPackage3 : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Status( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackageStatus **value) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_InstalledDate( /* [out][retval] */ __RPC__out ABI::Windows::Foundation::DateTime *value) = 0; virtual HRESULT STDMETHODCALLTYPE GetAppListEntriesAsync( /* [out][retval] */ __RPC__deref_out_opt __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry **operation) = 0; }; extern const __declspec(selectany) IID & IID_IPackage3 = __uuidof(IPackage3); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackage3Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Status )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackageStatus **value); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_InstalledDate )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out][retval] */ __RPC__out __x_ABI_CWindows_CFoundation_CDateTime *value); HRESULT ( STDMETHODCALLTYPE *GetAppListEntriesAsync )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackage3 * This, /* [out][retval] */ __RPC__deref_out_opt __FIAsyncOperation_1___FIVectorView_1_Windows__CApplicationModel__CCore__CAppListEntry **operation); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackage3Vtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackage3 { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackage3Vtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackage3_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_get_Status(This,value) \ ( (This)->lpVtbl -> get_Status(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_get_InstalledDate(This,value) \ ( (This)->lpVtbl -> get_InstalledDate(This,value) ) #define __x_ABI_CWindows_CApplicationModel_CIPackage3_GetAppListEntriesAsync(This,operation) \ ( (This)->lpVtbl -> GetAppListEntriesAsync(This,operation) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackage3_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0047 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIPackageStatics_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IPackageStatics[] = L"Windows.ApplicationModel.IPackageStatics"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIPackageStatics_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0047 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0047_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0047_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIPackageStatics */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IPackageStatics */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIPackageStatics; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("4E534BDF-2960-4878-97A4-9624DEB72F2D") IPackageStatics : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Current( /* [out][retval] */ __RPC__deref_out_opt ABI::Windows::ApplicationModel::IPackage **value) = 0; }; extern const __declspec(selectany) IID & IID_IPackageStatics = __uuidof(IPackageStatics); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIPackageStaticsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Current )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIPackageStatics * This, /* [out][retval] */ __RPC__deref_out_opt __x_ABI_CWindows_CApplicationModel_CIPackage **value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIPackageStaticsVtbl; interface __x_ABI_CWindows_CApplicationModel_CIPackageStatics { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIPackageStaticsVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIPackageStatics_get_Current(This,value) \ ( (This)->lpVtbl -> get_Current(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIPackageStatics_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0048 */ /* [local] */ #if !defined(____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_INTERFACE_DEFINED__) extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_Windows_ApplicationModel_IDesignModeStatics[] = L"Windows.ApplicationModel.IDesignModeStatics"; #endif /* !defined(____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_INTERFACE_DEFINED__) */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0048 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0048_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0048_v0_0_s_ifspec; #ifndef ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_INTERFACE_DEFINED__ #define ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_INTERFACE_DEFINED__ /* interface __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics */ /* [uuid][object] */ /* interface ABI::Windows::ApplicationModel::IDesignModeStatics */ /* [uuid][object] */ EXTERN_C const IID IID___x_ABI_CWindows_CApplicationModel_CIDesignModeStatics; #if defined(__cplusplus) && !defined(CINTERFACE) } /* end extern "C" */ namespace ABI { namespace Windows { namespace ApplicationModel { MIDL_INTERFACE("2C3893CC-F81A-4E7A-B857-76A80887E185") IDesignModeStatics : public IInspectable { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DesignModeEnabled( /* [out][retval] */ __RPC__out boolean *value) = 0; }; extern const __declspec(selectany) IID & IID_IDesignModeStatics = __uuidof(IDesignModeStatics); } /* end namespace */ } /* end namespace */ } /* end namespace */ extern "C" { #else /* C style interface */ typedef struct __x_ABI_CWindows_CApplicationModel_CIDesignModeStaticsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This); HRESULT ( STDMETHODCALLTYPE *GetIids )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This, /* [out] */ __RPC__out ULONG *iidCount, /* [size_is][size_is][out] */ __RPC__deref_out_ecount_full_opt(*iidCount) IID **iids); HRESULT ( STDMETHODCALLTYPE *GetRuntimeClassName )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This, /* [out] */ __RPC__deref_out_opt HSTRING *className); HRESULT ( STDMETHODCALLTYPE *GetTrustLevel )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This, /* [out] */ __RPC__out TrustLevel *trustLevel); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DesignModeEnabled )( __RPC__in __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics * This, /* [out][retval] */ __RPC__out boolean *value); END_INTERFACE } __x_ABI_CWindows_CApplicationModel_CIDesignModeStaticsVtbl; interface __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics { CONST_VTBL struct __x_ABI_CWindows_CApplicationModel_CIDesignModeStaticsVtbl *lpVtbl; }; #ifdef COBJMACROS #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_GetIids(This,iidCount,iids) \ ( (This)->lpVtbl -> GetIids(This,iidCount,iids) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_GetRuntimeClassName(This,className) \ ( (This)->lpVtbl -> GetRuntimeClassName(This,className) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_GetTrustLevel(This,trustLevel) \ ( (This)->lpVtbl -> GetTrustLevel(This,trustLevel) ) #define __x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_get_DesignModeEnabled(This,value) \ ( (This)->lpVtbl -> get_DesignModeEnabled(This,value) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ____x_ABI_CWindows_CApplicationModel_CIDesignModeStatics_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0049 */ /* [local] */ #ifndef RUNTIMECLASS_Windows_ApplicationModel_AppDisplayInfo_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_AppDisplayInfo_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_AppDisplayInfo[] = L"Windows.ApplicationModel.AppDisplayInfo"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_AppInfo_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_AppInfo_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_AppInfo[] = L"Windows.ApplicationModel.AppInfo"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_SuspendingEventArgs_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_SuspendingEventArgs_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_SuspendingEventArgs[] = L"Windows.ApplicationModel.SuspendingEventArgs"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_SuspendingDeferral_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_SuspendingDeferral_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_SuspendingDeferral[] = L"Windows.ApplicationModel.SuspendingDeferral"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_SuspendingOperation_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_SuspendingOperation_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_SuspendingOperation[] = L"Windows.ApplicationModel.SuspendingOperation"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_PackageStatus_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_PackageStatus_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_PackageStatus[] = L"Windows.ApplicationModel.PackageStatus"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_PackageId_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_PackageId_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_PackageId[] = L"Windows.ApplicationModel.PackageId"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_Package_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_Package_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_Package[] = L"Windows.ApplicationModel.Package"; #endif #ifndef RUNTIMECLASS_Windows_ApplicationModel_DesignMode_DEFINED #define RUNTIMECLASS_Windows_ApplicationModel_DesignMode_DEFINED extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_ApplicationModel_DesignMode[] = L"Windows.ApplicationModel.DesignMode"; #endif /* interface __MIDL_itf_windows2Eapplicationmodel_0000_0049 */ /* [local] */ extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0049_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_windows2Eapplicationmodel_0000_0049_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER HSTRING_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in HSTRING * ); unsigned char * __RPC_USER HSTRING_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HSTRING * ); unsigned char * __RPC_USER HSTRING_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HSTRING * ); void __RPC_USER HSTRING_UserFree( __RPC__in unsigned long *, __RPC__in HSTRING * ); unsigned long __RPC_USER HSTRING_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in HSTRING * ); unsigned char * __RPC_USER HSTRING_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HSTRING * ); unsigned char * __RPC_USER HSTRING_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HSTRING * ); void __RPC_USER HSTRING_UserFree64( __RPC__in unsigned long *, __RPC__in HSTRING * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
38.676892
250
0.742917
[ "object" ]
aa414b2f07b88e7b0ff539661c1de9057e306a2d
74,478
c
C
plugins/libplugin-pay.c
santos177/lightning
25f1db30762f7d46290f45551ad4bf41a5879875
[ "MIT" ]
null
null
null
plugins/libplugin-pay.c
santos177/lightning
25f1db30762f7d46290f45551ad4bf41a5879875
[ "MIT" ]
null
null
null
plugins/libplugin-pay.c
santos177/lightning
25f1db30762f7d46290f45551ad4bf41a5879875
[ "MIT" ]
null
null
null
#include <bitcoin/preimage.h> #include <ccan/array_size/array_size.h> #include <ccan/tal/str/str.h> #include <common/json_stream.h> #include <common/pseudorand.h> #include <common/type_to_string.h> #include <plugins/libplugin-pay.h> #define DEFAULT_FINAL_CLTV_DELTA 9 struct payment *payment_new(tal_t *ctx, struct command *cmd, struct payment *parent, struct payment_modifier **mods) { struct payment *p = tal(ctx, struct payment); p->children = tal_arr(p, struct payment *, 0); p->parent = parent; p->modifiers = mods; p->cmd = cmd; p->start_time = time_now(); p->result = NULL; p->why = NULL; p->getroute = tal(p, struct getroute_request); p->label = NULL; p->failreason = NULL; p->getroute->riskfactorppm = 10000000; p->abort = false; /* Copy over the relevant pieces of information. */ if (parent != NULL) { assert(cmd == NULL); tal_arr_expand(&parent->children, p); p->destination = parent->destination; p->amount = parent->amount; p->payment_hash = parent->payment_hash; p->partid = payment_root(p->parent)->next_partid++; p->plugin = parent->plugin; /* Re-establish the unmodified constraints for our sub-payment. */ p->constraints = *parent->start_constraints; p->deadline = parent->deadline; p->invoice = parent->invoice; } else { assert(cmd != NULL); p->partid = 0; p->next_partid = 1; p->plugin = cmd->plugin; p->channel_hints = tal_arr(p, struct channel_hint, 0); p->excluded_nodes = tal_arr(p, struct node_id, 0); } /* Initialize all modifier data so we can point to the fields when * wiring into the param() call in a JSON-RPC handler. The callback * can also just `memcpy` the parent if this outside access is not * required. */ p->modifier_data = tal_arr(p, void *, 0); for (size_t i=0; mods[i] != NULL; i++) { if (mods[i]->data_init != NULL) tal_arr_expand(&p->modifier_data, mods[i]->data_init(p)); else tal_arr_expand(&p->modifier_data, NULL); } return p; } struct payment *payment_root(struct payment *p) { if (p->parent == NULL) return p; else return payment_root(p->parent); } /* Generic handler for RPC failures that should end up failing the payment. */ static struct command_result *payment_rpc_failure(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { payment_fail(p, "Failing a partial payment due to a failed RPC call: %.*s", toks->end - toks->start, buffer + toks->start); return command_still_pending(cmd); } struct payment_tree_result payment_collect_result(struct payment *p) { struct payment_tree_result res; size_t numchildren = tal_count(p->children); res.sent = AMOUNT_MSAT(0); /* If we didn't have a route, we didn't attempt. */ res.attempts = p->route == NULL ? 0 : 1; res.treestates = p->step; res.leafstates = 0; res.preimage = NULL; res.failure = NULL; if (p->step == PAYMENT_STEP_FAILED && p->result != NULL) res.failure = p->result; if (numchildren == 0) { res.leafstates |= p->step; if (p->result && p->result->state == PAYMENT_COMPLETE) { res.sent = p->result->amount_sent; res.preimage = p->result->payment_preimage; } } for (size_t i = 0; i < numchildren; i++) { struct payment_tree_result cres = payment_collect_result(p->children[i]); /* Some of our subpayments have succeeded, aggregate how much * we sent in total. */ if (!amount_msat_add(&res.sent, res.sent, cres.sent)) plugin_err( p->plugin, "Number overflow summing partial payments: %s + %s", type_to_string(tmpctx, struct amount_msat, &res.sent), type_to_string(tmpctx, struct amount_msat, &cres.sent)); /* Bubble up the first preimage we see. */ if (res.preimage == NULL && cres.preimage != NULL) res.preimage = cres.preimage; res.leafstates |= cres.leafstates; res.treestates |= cres.treestates; res.attempts += cres.attempts; /* We bubble the failure result with the highest failcode up * to the root. */ if (res.failure == NULL || (cres.failure != NULL && cres.failure->failcode > res.failure->failcode)) { res.failure = cres.failure; } } return res; } static struct command_result *payment_getinfo_success(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { const jsmntok_t *blockheighttok = json_get_member(buffer, toks, "blockheight"); json_to_number(buffer, blockheighttok, &p->start_block); payment_continue(p); return command_still_pending(cmd); } void payment_start(struct payment *p) { struct payment *root = payment_root(p); p->step = PAYMENT_STEP_INITIALIZED; p->current_modifier = -1; /* Pre-generate the getroute request, so modifiers can have their say, * before we actually call `getroute` */ p->getroute->destination = p->destination; p->getroute->max_hops = ROUTING_MAX_HOPS; if (root->invoice != NULL && root->invoice->min_final_cltv_expiry != 0) p->getroute->cltv = root->invoice->min_final_cltv_expiry; else p->getroute->cltv = DEFAULT_FINAL_CLTV_DELTA; p->getroute->amount = p->amount; p->start_constraints = tal_dup(p, struct payment_constraints, &p->constraints); /* TODO If this is not the root, we can actually skip the getinfo call * and just reuse the parent's value. */ send_outreq(p->plugin, jsonrpc_request_start(p->plugin, NULL, "getinfo", payment_getinfo_success, payment_rpc_failure, p)); } static void payment_exclude_most_expensive(struct payment *p) { struct payment *root = payment_root(p); struct route_hop *e = &p->route[0]; struct amount_msat fee, worst = AMOUNT_MSAT(0); struct channel_hint hint; for (size_t i = 0; i < tal_count(p->route)-1; i++) { if (!amount_msat_sub(&fee, p->route[i].amount, p->route[i+1].amount)) plugin_err(p->plugin, "Negative fee in a route."); if (amount_msat_greater_eq(fee, worst)) { e = &p->route[i]; worst = fee; } } hint.scid.scid = e->channel_id; hint.scid.dir = e->direction; hint.enabled = false; tal_arr_expand(&root->channel_hints, hint); } static void payment_exclude_longest_delay(struct payment *p) { struct payment *root = payment_root(p); struct route_hop *e = &p->route[0]; u32 delay, worst = 0; struct channel_hint hint; for (size_t i = 0; i < tal_count(p->route)-1; i++) { delay = p->route[i].delay - p->route[i+1].delay; if (delay >= worst) { e = &p->route[i]; worst = delay; } } hint.scid.scid = e->channel_id; hint.scid.dir = e->direction; hint.enabled = false; tal_arr_expand(&root->channel_hints, hint); } static struct amount_msat payment_route_fee(struct payment *p) { struct amount_msat fee; if (!amount_msat_sub(&fee, p->route[0].amount, p->amount)) { plugin_log( p->plugin, LOG_BROKEN, "gossipd returned a route with a negative fee: sending %s " "to deliver %s", type_to_string(tmpctx, struct amount_msat, &p->route[0].amount), type_to_string(tmpctx, struct amount_msat, &p->amount)); abort(); } return fee; } /* Update the constraints by subtracting the delta_fee and delta_cltv if the * result is positive. Returns whether or not the update has been applied. */ static WARN_UNUSED_RESULT bool payment_constraints_update(struct payment_constraints *cons, const struct amount_msat delta_fee, const u32 delta_cltv) { if (delta_cltv > cons->cltv_budget) return false; /* amount_msat_sub performs a check before actually subtracting. */ if (!amount_msat_sub(&cons->fee_budget, cons->fee_budget, delta_fee)) return false; cons->cltv_budget -= delta_cltv; return true; } /* Given a route and a couple of channel hints, apply the route to the channel * hints, so we have a better estimation of channel's capacity. We apply a * route to a channel hint before calling `sendonion` so subsequent `route` * calls don't accidentally try to use those out-of-date estimates. We unapply * if the payment failed, i.e., all HTLCs we might have added have been torn * down again. Finally we leave the update in place if the payment went * through, since the balances really changed in that case. The `remove` * argument indicates whether we want to apply (`remove=false`), or clear a * prior application (`remove=true`). */ static void payment_chanhints_apply_route(struct payment *p, bool remove) { struct route_hop *curhop; struct channel_hint *curhint; struct payment *root = payment_root(p); assert(p->route != NULL); for (size_t i = 0; i < tal_count(p->route); i++) { curhop = &p->route[i]; for (size_t j = 0; j < tal_count(root->channel_hints); j++) { curhint = &root->channel_hints[j]; if (short_channel_id_eq(&curhint->scid.scid, &curhop->channel_id) && curhint->scid.dir == curhop->direction) { if (remove && !amount_msat_add( &curhint->estimated_capacity, curhint->estimated_capacity, curhop->amount)) { /* This should never happen, it'd mean * that we unapply a route that would * result in a msatoshi * wrap-around. */ abort(); } else if (!amount_msat_sub( &curhint->estimated_capacity, curhint->estimated_capacity, curhop->amount)) { /* This can happen in case of multipl * concurrent getroute calls using the * same channel_hints, no biggy, it's * an estimation anyway. */ plugin_log( p->plugin, LOG_UNUSUAL, "Could not update the channel hint " "for %s. Could be a concurrent " "`getroute` call.", type_to_string( tmpctx, struct short_channel_id_dir, &curhint->scid)); } } } } } static struct command_result *payment_getroute_result(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { const jsmntok_t *rtok = json_get_member(buffer, toks, "route"); struct amount_msat fee; assert(rtok != NULL); p->route = json_to_route(p, buffer, rtok); p->step = PAYMENT_STEP_GOT_ROUTE; fee = payment_route_fee(p); /* Ensure that our fee and CLTV budgets are respected. */ if (amount_msat_greater(fee, p->constraints.fee_budget)) { payment_exclude_most_expensive(p); payment_fail( p, "Fee exceeds our fee budget: %s > %s, discarding route", type_to_string(tmpctx, struct amount_msat, &fee), type_to_string(tmpctx, struct amount_msat, &p->constraints.fee_budget)); return command_still_pending(cmd); } if (p->route[0].delay > p->constraints.cltv_budget) { payment_exclude_longest_delay(p); payment_fail(p, "CLTV delay exceeds our CLTV budget: %d > %d", p->route[0].delay, p->constraints.cltv_budget); return command_still_pending(cmd); } /* Now update the constraints in fee_budget and cltv_budget so * modifiers know what constraints they need to adhere to. */ if (!payment_constraints_update(&p->constraints, fee, p->route[0].delay)) { plugin_log(p->plugin, LOG_BROKEN, "Could not update constraints."); abort(); } /* Allow modifiers to modify the route, before * payment_compute_onion_payloads uses the route to generate the * onion_payloads */ payment_continue(p); return command_still_pending(cmd); } static struct command_result *payment_getroute_error(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { int code; const jsmntok_t *codetok = json_get_member(buffer, toks, "code"), *msgtok = json_get_member(buffer, toks, "message"); json_to_int(buffer, codetok, &code); p->route = NULL; payment_fail( p, "Error computing a route to %s: %.*s (%d)", type_to_string(tmpctx, struct node_id, p->getroute->destination), json_tok_full_len(msgtok), json_tok_full(buffer, msgtok), code); /* Let payment_finished_ handle this, so we mark it as pending */ return command_still_pending(cmd); } static const struct short_channel_id_dir * payment_get_excluded_channels(const tal_t *ctx, struct payment *p) { struct payment *root = payment_root(p); struct channel_hint *hint; struct short_channel_id_dir *res = tal_arr(ctx, struct short_channel_id_dir, 0); for (size_t i = 0; i < tal_count(root->channel_hints); i++) { hint = &root->channel_hints[i]; if (!hint->enabled) tal_arr_expand(&res, hint->scid); else if (amount_msat_greater_eq(p->amount, hint->estimated_capacity)) tal_arr_expand(&res, hint->scid); } return res; } static const struct node_id *payment_get_excluded_nodes(const tal_t *ctx, struct payment *p) { struct payment *root = payment_root(p); return root->excluded_nodes; } /* Iterate through the channel_hints and exclude any channel that we are * confident will not be able to handle this payment. */ static void payment_getroute_add_excludes(struct payment *p, struct json_stream *js) { const struct node_id *nodes; const struct short_channel_id_dir *chans; json_array_start(js, "exclude"); /* Collect and exclude all channels that are disabled or we know have * insufficient capacity. */ chans = payment_get_excluded_channels(tmpctx, p); for (size_t i=0; i<tal_count(chans); i++) json_add_short_channel_id_dir(js, NULL, &chans[i]); /* Now also exclude nodes that we think have failed. */ nodes = payment_get_excluded_nodes(tmpctx, p); for (size_t i=0; i<tal_count(nodes); i++) json_add_node_id(js, NULL, &nodes[i]); json_array_end(js); } static void payment_getroute(struct payment *p) { struct out_req *req; req = jsonrpc_request_start(p->plugin, NULL, "getroute", payment_getroute_result, payment_getroute_error, p); json_add_node_id(req->js, "id", p->getroute->destination); json_add_amount_msat_only(req->js, "msatoshi", p->getroute->amount); json_add_num(req->js, "cltv", p->getroute->cltv); json_add_num(req->js, "maxhops", p->getroute->max_hops); json_add_member(req->js, "riskfactor", false, "%lf", p->getroute->riskfactorppm / 1000000.0); payment_getroute_add_excludes(p, req->js); send_outreq(p->plugin, req); } static u8 *tal_towire_legacy_payload(const tal_t *ctx, const struct legacy_payload *payload) { const u8 padding[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; /* Prepend 0 byte for realm */ u8 *buf = tal_arrz(ctx, u8, 1); towire_short_channel_id(&buf, &payload->scid); towire_u64(&buf, payload->forward_amt.millisatoshis); /* Raw: low-level serializer */ towire_u32(&buf, payload->outgoing_cltv); towire(&buf, padding, ARRAY_SIZE(padding)); assert(tal_bytelen(buf) == 1 + 32); return buf; } static struct payment_result *tal_sendpay_result_from_json(const tal_t *ctx, const char *buffer, const jsmntok_t *toks) { const jsmntok_t *idtok = json_get_member(buffer, toks, "id"); const jsmntok_t *hashtok = json_get_member(buffer, toks, "payment_hash"); const jsmntok_t *partidtok = json_get_member(buffer, toks, "partid"); const jsmntok_t *senttok = json_get_member(buffer, toks, "amount_sent_msat"); const jsmntok_t *statustok = json_get_member(buffer, toks, "status"); const jsmntok_t *preimagetok = json_get_member(buffer, toks, "payment_preimage"); const jsmntok_t *codetok = json_get_member(buffer, toks, "code"); const jsmntok_t *datatok = json_get_member(buffer, toks, "data"); const jsmntok_t *erridxtok, *msgtok, *failcodetok, *rawmsgtok, *failcodenametok, *errchantok, *errnodetok, *errdirtok; struct payment_result *result; /* Check if we have an error and need to descend into data to get * details. */ if (codetok != NULL && datatok != NULL) { idtok = json_get_member(buffer, datatok, "id"); hashtok = json_get_member(buffer, datatok, "payment_hash"); partidtok = json_get_member(buffer, datatok, "partid"); senttok = json_get_member(buffer, datatok, "amount_sent_msat"); statustok = json_get_member(buffer, datatok, "status"); } /* Initial sanity checks, all these fields must exist. */ if (idtok == NULL || idtok->type != JSMN_PRIMITIVE || hashtok == NULL || hashtok->type != JSMN_STRING || senttok == NULL || senttok->type != JSMN_STRING || statustok == NULL || statustok->type != JSMN_STRING) { return NULL; } result = tal(ctx, struct payment_result); if (codetok != NULL) json_to_u32(buffer, codetok, &result->code); else result->code = 0; /* If the partid is 0 it'd be omitted in waitsendpay, fix this here. */ if (partidtok != NULL) json_to_u32(buffer, partidtok, &result->partid); else result->partid = 0; json_to_u64(buffer, idtok, &result->id); json_to_msat(buffer, senttok, &result->amount_sent); if (json_tok_streq(buffer, statustok, "pending")) { result->state = PAYMENT_PENDING; } else if (json_tok_streq(buffer, statustok, "complete")) { result->state = PAYMENT_COMPLETE; } else if (json_tok_streq(buffer, statustok, "failed")) { result->state = PAYMENT_FAILED; } else { goto fail; } if (preimagetok != NULL) { result->payment_preimage = tal(result, struct preimage); json_to_preimage(buffer, preimagetok, result->payment_preimage); } /* Now extract the error details if the error code is not 0 */ if (result->code != 0) { erridxtok = json_get_member(buffer, datatok, "erring_index"); errnodetok = json_get_member(buffer, datatok, "erring_node"); errchantok = json_get_member(buffer, datatok, "erring_channel"); errdirtok = json_get_member(buffer, datatok, "erring_direction"); failcodetok = json_get_member(buffer, datatok, "failcode"); failcodenametok =json_get_member(buffer, datatok, "failcodename"); msgtok = json_get_member(buffer, toks, "message"); rawmsgtok = json_get_member(buffer, datatok, "raw_message"); if (failcodetok == NULL || failcodetok->type != JSMN_PRIMITIVE || (failcodenametok != NULL && failcodenametok->type != JSMN_STRING) || (erridxtok != NULL && erridxtok->type != JSMN_PRIMITIVE) || (errnodetok != NULL && errnodetok->type != JSMN_STRING) || (errchantok != NULL && errchantok->type != JSMN_STRING) || (errdirtok != NULL && errdirtok->type != JSMN_PRIMITIVE) || msgtok == NULL || msgtok->type != JSMN_STRING || (rawmsgtok != NULL && rawmsgtok->type != JSMN_STRING)) goto fail; if (rawmsgtok != NULL) result->raw_message = json_tok_bin_from_hex(result, buffer, rawmsgtok); else result->raw_message = NULL; if (failcodenametok != NULL) result->failcodename = json_strdup(result, buffer, failcodenametok); else result->failcodename = NULL; json_to_u32(buffer, failcodetok, &result->failcode); result->message = json_strdup(result, buffer, msgtok); if (erridxtok != NULL) { result->erring_index = tal(result, u32); json_to_u32(buffer, erridxtok, result->erring_index); } else { result->erring_index = NULL; } if (errdirtok != NULL) { result->erring_direction = tal(result, int); json_to_int(buffer, errdirtok, result->erring_direction); } else { result->erring_direction = NULL; } if (errnodetok != NULL) { result->erring_node = tal(result, struct node_id); json_to_node_id(buffer, errnodetok, result->erring_node); } else { result->erring_node = NULL; } if (errchantok != NULL) { result->erring_channel = tal(result, struct short_channel_id); json_to_short_channel_id(buffer, errchantok, result->erring_channel); } else { result->erring_channel = NULL; } } return result; fail: return tal_free(result); } static void channel_hints_update(struct payment *root, struct short_channel_id *scid, int direction, bool enabled, struct amount_msat estimated_capacity) { struct channel_hint hint; /* Try and look for an existing hint: */ for (size_t i=0; i<tal_count(root->channel_hints); i++) { struct channel_hint *hint = &root->channel_hints[i]; if (short_channel_id_eq(&hint->scid.scid, scid) && hint->scid.dir == direction) { /* Prefer to disable a channel. */ hint->enabled = hint->enabled & enabled; /* Prefer the more conservative estimate. */ if (amount_msat_greater(hint->estimated_capacity, estimated_capacity)) hint->estimated_capacity = estimated_capacity; return; } } /* No hint found, create one. */ hint.enabled = enabled; hint.scid.scid = *scid; hint.scid.dir = direction; hint.estimated_capacity = estimated_capacity; tal_arr_expand(&root->channel_hints, hint); } /* Try to infer the erring_node, erring_channel and erring_direction from what * we know, but don't override the values that are returned by `waitsendpay`. */ static void payment_result_infer(struct route_hop *route, struct payment_result *r) { int i, len; assert(r != NULL); if (r->code == 0 || r->erring_index == NULL || route == NULL) return; len = tal_count(route); i = *r->erring_index; assert(i <= len); if (r->erring_node == NULL) r->erring_node = &route[i-1].nodeid; /* The above assert was enough for the erring_node, but might be off * by one on channel and direction, in case the destination failed on * us. */ if (i == len) return; if (r->erring_channel == NULL) r->erring_channel = &route[i].channel_id; if (r->erring_direction == NULL) r->erring_direction = &route[i].direction; } static struct command_result * payment_waitsendpay_finished(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { struct payment *root; struct route_hop *hop; assert(p->route != NULL); p->end_time = time_now(); p->result = tal_sendpay_result_from_json(p, buffer, toks); if (p->result == NULL) { plugin_log(p->plugin, LOG_UNUSUAL, "Unable to parse `waitsendpay` result: %.*s", json_tok_full_len(toks), json_tok_full(buffer, toks)); payment_set_step(p, PAYMENT_STEP_FAILED); payment_continue(p); return command_still_pending(cmd); } payment_result_infer(p->route, p->result); if (p->result->state == PAYMENT_COMPLETE) { payment_set_step(p, PAYMENT_STEP_SUCCESS); payment_continue(p); return command_still_pending(cmd); } root = payment_root(p); payment_chanhints_apply_route(p, true); switch (p->result->failcode) { case WIRE_PERMANENT_CHANNEL_FAILURE: case WIRE_CHANNEL_DISABLED: case WIRE_UNKNOWN_NEXT_PEER: case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING: /* All of these result in the channel being marked as disabled. */ assert(*p->result->erring_index < tal_count(p->route)); hop = &p->route[*p->result->erring_index]; channel_hints_update(root, &hop->channel_id, hop->direction, false, AMOUNT_MSAT(0)); break; case WIRE_TEMPORARY_CHANNEL_FAILURE: /* These are an indication that the capacity was insufficient, * remember the amount we tried as an estimate. */ assert(*p->result->erring_index < tal_count(p->route)); hop = &p->route[*p->result->erring_index]; struct amount_msat est = { .millisatoshis = hop->amount.millisatoshis * 0.75}; /* Raw: Multiplication */ channel_hints_update(root, &hop->channel_id, hop->direction, true, est); break; case WIRE_INVALID_ONION_PAYLOAD: case WIRE_INVALID_REALM: case WIRE_PERMANENT_NODE_FAILURE: case WIRE_TEMPORARY_NODE_FAILURE: case WIRE_REQUIRED_NODE_FEATURE_MISSING: case WIRE_INVALID_ONION_VERSION: case WIRE_INVALID_ONION_HMAC: case WIRE_INVALID_ONION_KEY: #if EXPERIMENTAL_FEATURES case WIRE_INVALID_ONION_BLINDING: #endif /* These are reported by the last hop, i.e., the destination of hop i-1. */ assert(*p->result->erring_index - 1 < tal_count(p->route)); hop = &p->route[*p->result->erring_index - 1]; tal_arr_expand(&root->excluded_nodes, hop->nodeid); break; case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS: p->result->code = PAY_DESTINATION_PERM_FAIL; root->abort = true; case WIRE_MPP_TIMEOUT: /* These are permanent failures that should abort all of our * attempts right away. We'll still track pending partial * payments correctly, just not start new ones. */ root->abort = true; break; case WIRE_AMOUNT_BELOW_MINIMUM: case WIRE_EXPIRY_TOO_FAR: case WIRE_EXPIRY_TOO_SOON: case WIRE_FEE_INSUFFICIENT: case WIRE_INCORRECT_CLTV_EXPIRY: case WIRE_FINAL_INCORRECT_CLTV_EXPIRY: /* These are issues that are due to gossipd being out of date, * we ignore them here, and wait for gossipd to adjust * instead. */ break; case WIRE_FINAL_INCORRECT_HTLC_AMOUNT: /* These are symptoms of intermediate hops tampering with the * payment. */ hop = &p->route[*p->result->erring_index]; plugin_log( p->plugin, LOG_UNUSUAL, "Node %s reported an incorrect HTLC amount, this could be " "a prior hop messing with the amounts.", type_to_string(tmpctx, struct node_id, &hop->nodeid)); break; } payment_fail(p, "%s", p->result->message); return command_still_pending(cmd); } static struct command_result *payment_sendonion_success(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { struct out_req *req; req = jsonrpc_request_start(p->plugin, NULL, "waitsendpay", payment_waitsendpay_finished, payment_waitsendpay_finished, p); json_add_sha256(req->js, "payment_hash", p->payment_hash); json_add_num(req->js, "partid", p->partid); send_outreq(p->plugin, req); return command_still_pending(cmd); } static struct command_result *payment_createonion_success(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { struct out_req *req; struct route_hop *first = &p->route[0]; struct secret *secrets; payment_chanhints_apply_route(p, false); p->createonion_response = json_to_createonion_response(p, buffer, toks); req = jsonrpc_request_start(p->plugin, NULL, "sendonion", payment_sendonion_success, payment_rpc_failure, p); json_add_hex_talarr(req->js, "onion", p->createonion_response->onion); json_object_start(req->js, "first_hop"); json_add_short_channel_id(req->js, "channel", &first->channel_id); json_add_num(req->js, "direction", first->direction); json_add_amount_msat_only(req->js, "amount_msat", first->amount); json_add_num(req->js, "delay", first->delay); json_add_node_id(req->js, "id", &first->nodeid); json_object_end(req->js); json_add_sha256(req->js, "payment_hash", p->payment_hash); json_array_start(req->js, "shared_secrets"); secrets = p->createonion_response->shared_secrets; for(size_t i=0; i<tal_count(secrets); i++) json_add_secret(req->js, NULL, &secrets[i]); json_array_end(req->js); json_add_num(req->js, "partid", p->partid); if (p->label) json_add_string(req->js, "label", p->label); send_outreq(p->plugin, req); return command_still_pending(cmd); } /* Temporary serialization method for the tlv_payload.data until we rework the * API that is generated from the specs to use the setter/getter interface. */ static void tlvstream_set_tlv_payload_data(struct tlv_field **stream, struct secret *payment_secret, u64 total_msat) { u8 *ser = tal_arr(NULL, u8, 0); towire_secret(&ser, payment_secret); towire_tu64(&ser, total_msat); tlvstream_set_raw(stream, TLV_TLV_PAYLOAD_PAYMENT_DATA, ser, tal_bytelen(ser)); tal_free(ser); } static void payment_add_hop_onion_payload(struct payment *p, struct createonion_hop *dst, struct route_hop *node, struct route_hop *next, bool final, struct secret *payment_secret) { struct createonion_request *cr = p->createonion_request; u32 cltv = p->start_block + next->delay; u64 msat = next->amount.millisatoshis; /* Raw: TLV payload generation*/ struct tlv_field **fields; static struct short_channel_id all_zero_scid = {.u64 = 0}; /* This is the information of the node processing this payload, while * `next` are the instructions to include in the payload, which is * basically the channel going to the next node. */ dst->style = node->style; dst->pubkey = node->nodeid; switch (node->style) { case ROUTE_HOP_LEGACY: dst->legacy_payload = tal(cr->hops, struct legacy_payload); dst->legacy_payload->forward_amt = next->amount; if (!final) dst->legacy_payload->scid = next->channel_id; else dst->legacy_payload->scid = all_zero_scid; dst->legacy_payload->outgoing_cltv = cltv; break; case ROUTE_HOP_TLV: dst->tlv_payload = tlv_tlv_payload_new(cr->hops); fields = &dst->tlv_payload->fields; tlvstream_set_tu64(fields, TLV_TLV_PAYLOAD_AMT_TO_FORWARD, msat); tlvstream_set_tu32(fields, TLV_TLV_PAYLOAD_OUTGOING_CLTV_VALUE, cltv); if (!final) tlvstream_set_short_channel_id(fields, TLV_TLV_PAYLOAD_SHORT_CHANNEL_ID, &next->channel_id); if (payment_secret != NULL) { assert(final); tlvstream_set_tlv_payload_data(fields, payment_secret, msat); } break; } } static void payment_compute_onion_payloads(struct payment *p) { struct createonion_request *cr; size_t hopcount; struct payment *root = payment_root(p); p->step = PAYMENT_STEP_ONION_PAYLOAD; hopcount = tal_count(p->route); /* Now compute the payload we're about to pass to `createonion` */ cr = p->createonion_request = tal(p, struct createonion_request); cr->assocdata = tal_arr(cr, u8, 0); towire_sha256(&cr->assocdata, p->payment_hash); cr->session_key = NULL; cr->hops = tal_arr(cr, struct createonion_hop, tal_count(p->route)); /* Non-final hops */ for (size_t i = 0; i < hopcount - 1; i++) { /* The message is destined for hop i, but contains fields for * i+1 */ payment_add_hop_onion_payload(p, &cr->hops[i], &p->route[i], &p->route[i + 1], false, NULL); } /* Final hop */ payment_add_hop_onion_payload( p, &cr->hops[hopcount - 1], &p->route[hopcount - 1], &p->route[hopcount - 1], true, root->payment_secret); /* Now allow all the modifiers to mess with the payloads, before we * serialize via a call to createonion in the next step. */ payment_continue(p); } static void payment_sendonion(struct payment *p) { struct out_req *req; u8 *payload, *tlv; req = jsonrpc_request_start(p->plugin, NULL, "createonion", payment_createonion_success, payment_rpc_failure, p); json_array_start(req->js, "hops"); for (size_t i = 0; i < tal_count(p->createonion_request->hops); i++) { json_object_start(req->js, NULL); struct createonion_hop *hop = &p->createonion_request->hops[i]; json_add_node_id(req->js, "pubkey", &hop->pubkey); if (hop->style == ROUTE_HOP_LEGACY) { payload = tal_towire_legacy_payload(tmpctx, hop->legacy_payload); json_add_hex_talarr(req->js, "payload", payload); }else { tlv = tal_arr(tmpctx, u8, 0); towire_tlvstream_raw(&tlv, hop->tlv_payload->fields); payload = tal_arr(tmpctx, u8, 0); towire_bigsize(&payload, tal_bytelen(tlv)); towire(&payload, tlv, tal_bytelen(tlv)); json_add_hex_talarr(req->js, "payload", payload); tal_free(tlv); } tal_free(payload); json_object_end(req->js); } json_array_end(req->js); json_add_hex_talarr(req->js, "assocdata", p->createonion_request->assocdata); if (p->createonion_request->session_key) json_add_secret(req->js, "sessionkey", p->createonion_request->session_key); send_outreq(p->plugin, req); } /* Mutual recursion. */ static void payment_finished(struct payment *p); /* A payment is finished if a) it is in a final state, of b) it's in a * child-spawning state and all of its children are in a final state. */ static bool payment_is_finished(const struct payment *p) { if (p->step == PAYMENT_STEP_FAILED || p->step == PAYMENT_STEP_SUCCESS || p->abort) return true; else if (p->step == PAYMENT_STEP_SPLIT || p->step == PAYMENT_STEP_RETRY) { bool running_children = false; for (size_t i = 0; i < tal_count(p->children); i++) running_children |= !payment_is_finished(p->children[i]); return !running_children; } else { return false; } } static enum payment_step payment_aggregate_states(struct payment *p) { enum payment_step agg = p->step; for (size_t i=0; i<tal_count(p->children); i++) agg |= payment_aggregate_states(p->children[i]); return agg; } /* A payment is finished if a) it is in a final state, of b) it's in a * child-spawning state and all of its children are in a final state. */ static bool payment_is_success(struct payment *p) { return (payment_aggregate_states(p) & PAYMENT_STEP_SUCCESS) != 0; } /* Function to bubble up completions to the root, which actually holds on to * the command that initiated the flow. */ static void payment_child_finished(struct payment *p, struct payment *child) { if (!payment_is_finished(p)) return; /* Should we continue bubbling up? */ payment_finished(p); } static void payment_add_attempt(struct json_stream *s, const char *fieldname, struct payment *p, bool recurse) { bool finished = p->step >= PAYMENT_STEP_RETRY, success = p->step == PAYMENT_STEP_SUCCESS; /* A fieldname is only reasonable if we're not recursing. Otherwise the * fieldname would be reused for all attempts. */ assert(!recurse || fieldname == NULL); json_object_start(s, fieldname); if (!finished) json_add_string(s, "status", "pending"); else if (success) json_add_string(s, "status", "success"); else json_add_string(s, "status", "failed"); if (p->failreason != NULL) json_add_string(s, "failreason", p->failreason); json_add_u64(s, "partid", p->partid); json_add_amount_msat_only(s, "amount", p->amount); if (p->parent != NULL) json_add_u64(s, "parent_partid", p->parent->partid); json_object_end(s); for (size_t i=0; i<tal_count(p->children); i++) { payment_add_attempt(s, fieldname, p->children[i], recurse); } } static void payment_json_add_attempts(struct json_stream *s, const char *fieldname, struct payment *p) { assert(p == payment_root(p)); json_array_start(s, fieldname); payment_add_attempt(s, NULL, p, true); json_array_end(s); } /* This function is called whenever a payment ends up in a final state, or all * leafs in the subtree rooted in the payment are all in a final state. It is * called only once, and it is guaranteed to be called in post-order * traversal, i.e., all children are finished before the parent is called. */ static void payment_finished(struct payment *p) { struct payment_tree_result result = payment_collect_result(p); struct json_stream *ret; struct command *cmd = p->cmd; const char *msg; /* Either none of the leaf attempts succeeded yet, or we have a * preimage. */ assert((result.leafstates & PAYMENT_STEP_SUCCESS) == 0 || result.preimage != NULL); if (p->parent == NULL) { /* We are about to reply, unset the pointer to the cmd so we * don't attempt to return a response twice. */ p->cmd = NULL; if (cmd == NULL) { /* This is the tree root, but we already reported * success or failure, so noop. */ return; } else if (payment_is_success(p)) { assert(result.treestates & PAYMENT_STEP_SUCCESS); assert(result.leafstates & PAYMENT_STEP_SUCCESS); assert(result.preimage != NULL); ret = jsonrpc_stream_success(cmd); json_add_node_id(ret, "destination", p->destination); json_add_sha256(ret, "payment_hash", p->payment_hash); json_add_timeabs(ret, "created_at", p->start_time); json_add_num(ret, "parts", result.attempts); json_add_amount_msat_compat(ret, p->amount, "msatoshi", "amount_msat"); json_add_amount_msat_compat(ret, result.sent, "msatoshi_sent", "amount_sent_msat"); if (result.leafstates != PAYMENT_STEP_SUCCESS) json_add_string( ret, "warning_partial_completion", "Some parts of the payment are not yet " "completed, but we have the confirmation " "from the recipient."); json_add_preimage(ret, "payment_preimage", result.preimage); json_add_string(ret, "status", "complete"); if (command_finished(cmd, ret)) {/* Ignore result. */} return; } else if (result.failure == NULL || result.failure->failcode < NODE) { /* This is failing because we have no more routes to try */ msg = tal_fmt(cmd, "Ran out of routes to try after " "%d attempt%s: see `paystatus`", result.attempts, result.attempts == 1 ? "" : "s"); ret = jsonrpc_stream_fail(cmd, PAY_STOPPED_RETRYING, msg); payment_json_add_attempts(ret, "attempts", p); if (command_finished(cmd, ret)) {/* Ignore result. */} return; } else { struct payment_result *failure = result.failure; assert(failure!= NULL); ret = jsonrpc_stream_fail(cmd, failure->code, failure->message); json_add_u64(ret, "id", failure->id); json_add_u32(ret, "failcode", failure->failcode); json_add_string(ret, "failcodename", failure->failcodename); if (p->bolt11) json_add_string(ret, "bolt11", p->bolt11); json_add_hex_talarr(ret, "raw_message", result.failure->raw_message); json_add_num(ret, "created_at", p->start_time.ts.tv_sec); json_add_string(ret, "message", result.failure->message); json_add_node_id(ret, "destination", p->destination); json_add_sha256(ret, "payment_hash", p->payment_hash); if (result.leafstates & PAYMENT_STEP_SUCCESS) { /* If one sub-payment succeeded then we have * proof of payment, and the payment is a * success. */ json_add_string(ret, "status", "complete"); } else if (result.leafstates & ~PAYMENT_FAILED) { /* If there are non-failed leafs we are still trying. */ json_add_string(ret, "status", "pending"); } else { json_add_string(ret, "status", "failed"); } json_add_amount_msat_compat(ret, p->amount, "msatoshi", "amount_msat"); json_add_amount_msat_compat(ret, result.sent, "msatoshi_sent", "amount_sent_msat"); if (failure != NULL) { if (failure->erring_index) json_add_num(ret, "erring_index", *failure->erring_index); if (failure->erring_node) json_add_node_id(ret, "erring_node", failure->erring_node); if (failure->erring_channel) json_add_short_channel_id( ret, "erring_channel", failure->erring_channel); if (failure->erring_direction) json_add_num( ret, "erring_direction", *failure->erring_direction); } if (command_finished(cmd, ret)) {/* Ignore result. */} return; } } else { payment_child_finished(p->parent, p); return; } } void payment_set_step(struct payment *p, enum payment_step newstep) { p->current_modifier = -1; p->step = newstep; /* Any final state needs an end_time */ if (p->step >= PAYMENT_STEP_SPLIT) p->end_time = time_now(); } void payment_continue(struct payment *p) { struct payment_modifier *mod; void *moddata; /* If we are in the middle of calling the modifiers, continue calling * them, otherwise we can continue with the payment state-machine. */ p->current_modifier++; mod = p->modifiers[p->current_modifier]; if (mod != NULL) { /* There is another modifier, so call it. */ moddata = p->modifier_data[p->current_modifier]; return mod->post_step_cb(moddata, p); } else { /* There are no more modifiers, so reset the call chain and * proceed to the next state. */ p->current_modifier = -1; switch (p->step) { case PAYMENT_STEP_INITIALIZED: payment_getroute(p); return; case PAYMENT_STEP_GOT_ROUTE: payment_compute_onion_payloads(p); return; case PAYMENT_STEP_ONION_PAYLOAD: payment_sendonion(p); return; case PAYMENT_STEP_SUCCESS: case PAYMENT_STEP_FAILED: payment_finished(p); return; case PAYMENT_STEP_RETRY: case PAYMENT_STEP_SPLIT: /* Do nothing, we'll get pinged by a child succeeding * or failing. */ return; } } /* We should never get here, it'd mean one of the state machine called * `payment_continue` after the final state. */ abort(); } void payment_fail(struct payment *p, const char *fmt, ...) { va_list ap; p->end_time = time_now(); payment_set_step(p, PAYMENT_STEP_FAILED); va_start(ap, fmt); p->failreason = tal_vfmt(p, fmt, ap); va_end(ap); plugin_log(p->plugin, LOG_INFORM, "%s", p->failreason); payment_continue(p); } void *payment_mod_get_data(const struct payment *p, const struct payment_modifier *mod) { for (size_t i = 0; p->modifiers[i] != NULL; i++) if (p->modifiers[i] == mod) return p->modifier_data[i]; /* If we ever get here it means that we asked for the data for a * non-existent modifier. This is a compile-time/wiring issue, so we * better check that modifiers match the data we ask for. */ abort(); } static struct retry_mod_data *retry_data_init(struct payment *p); static inline void retry_step_cb(struct retry_mod_data *rd, struct payment *p); static struct retry_mod_data * retry_data_init(struct payment *p) { struct retry_mod_data *rdata = tal(p, struct retry_mod_data); struct retry_mod_data *parent_rdata; /* We start the retry counter from scratch for the root payment, or if * the parent was split, meaning this is a new attempt with new * amounts. */ if (p->parent == NULL || p->parent->step == PAYMENT_STEP_SPLIT) { rdata->retries = 10; } else { parent_rdata = payment_mod_retry_get_data(p->parent); rdata->retries = parent_rdata->retries - 1; } return rdata; } /* Determine whether retrying could possibly succeed. Retrying in this case * means that we repeat the entire flow, including computing a new route, new * payload and a new sendonion call. It does not mean we retry the exact same * attempt that just failed. */ static bool payment_can_retry(struct payment *p) { struct payment_result *res = p->result; u32 idx; bool is_final; if (p->result == NULL) return false; idx = res->erring_index != NULL ? *res->erring_index : 0; is_final = (idx == tal_count(p->route)); /* Full matrix of failure code x is_final. Prefer to retry once too * often over eagerly failing. */ switch (res->failcode) { case WIRE_EXPIRY_TOO_FAR: case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS: case WIRE_INVALID_ONION_PAYLOAD: case WIRE_INVALID_ONION_VERSION: case WIRE_INVALID_REALM: case WIRE_MPP_TIMEOUT: case WIRE_PERMANENT_NODE_FAILURE: case WIRE_REQUIRED_NODE_FEATURE_MISSING: case WIRE_TEMPORARY_NODE_FAILURE: case WIRE_UNKNOWN_NEXT_PEER: return !is_final; case WIRE_AMOUNT_BELOW_MINIMUM: case WIRE_CHANNEL_DISABLED: case WIRE_EXPIRY_TOO_SOON: case WIRE_FEE_INSUFFICIENT: case WIRE_FINAL_INCORRECT_CLTV_EXPIRY: case WIRE_FINAL_INCORRECT_HTLC_AMOUNT: case WIRE_INCORRECT_CLTV_EXPIRY: case WIRE_INVALID_ONION_HMAC: case WIRE_INVALID_ONION_KEY: case WIRE_PERMANENT_CHANNEL_FAILURE: case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING: case WIRE_TEMPORARY_CHANNEL_FAILURE: #if EXPERIMENTAL_FEATURES case WIRE_INVALID_ONION_BLINDING: #endif return true; } /* We should never get here, otherwise the above `switch` isn't * exhaustive. Nevertheless the failcode is provided by the erring * node, so retry anyway. `abort()`ing on externally supplied info is * not a good idea. */ return true; } static inline void retry_step_cb(struct retry_mod_data *rd, struct payment *p) { struct payment *subpayment, *root = payment_root(p); struct retry_mod_data *rdata = payment_mod_retry_get_data(p); struct timeabs now = time_now(); if (p->step != PAYMENT_STEP_FAILED) return payment_continue(p); if (time_after(now, p->deadline)) { plugin_log( p->plugin, LOG_INFORM, "Payment deadline expired, not retrying (partial-)payment " "%s/%d", type_to_string(tmpctx, struct sha256, p->payment_hash), p->partid); root->abort = true; return payment_continue(p); } /* If we failed to find a route, it's unlikely we can suddenly find a * new one without any other changes, so it's time to give up. */ if (p->route == NULL) return payment_continue(p); /* If the root is marked as abort, we do not retry anymore */ if (payment_root(p)->abort) return payment_continue(p); if (!payment_can_retry(p)) return payment_continue(p); /* If the failure was not final, and we tried a route, try again. */ if (rdata->retries > 0) { subpayment = payment_new(p, NULL, p, p->modifiers); payment_start(subpayment); payment_set_step(p, PAYMENT_STEP_RETRY); subpayment->why = tal_fmt(subpayment, "Still have %d attempts left", rdata->retries - 1); plugin_log( p->plugin, LOG_DBG, "Retrying %s/%d (%s), new partid %d. %d attempts left\n", type_to_string(tmpctx, struct sha256, p->payment_hash), p->partid, type_to_string(tmpctx, struct amount_msat, &p->amount), subpayment->partid, rdata->retries - 1); } payment_continue(p); } REGISTER_PAYMENT_MODIFIER(retry, struct retry_mod_data *, retry_data_init, retry_step_cb); static struct command_result * local_channel_hints_listpeers(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { const jsmntok_t *peers, *peer, *channels, *channel, *spendsats, *scid, *dir, *connected; size_t i, j; peers = json_get_member(buffer, toks, "peers"); if (peers == NULL) goto done; /* cppcheck-suppress uninitvar - cppcheck can't undestand these macros. */ json_for_each_arr(i, peer, peers) { channels = json_get_member(buffer, peer, "channels"); if (channels == NULL) continue; connected = json_get_member(buffer, peer, "connected"); json_for_each_arr(j, channel, channels) { struct channel_hint h; spendsats = json_get_member(buffer, channel, "spendable_msat"); scid = json_get_member(buffer, channel, "short_channel_id"); dir = json_get_member(buffer, channel, "direction"); assert(spendsats != NULL && scid != NULL && dir != NULL); json_to_bool(buffer, connected, &h.enabled); json_to_short_channel_id(buffer, scid, &h.scid.scid); json_to_int(buffer, dir, &h.scid.dir); json_to_msat(buffer, spendsats, &h.estimated_capacity); tal_arr_expand(&p->channel_hints, h); } } done: payment_continue(p); return command_still_pending(cmd); } static void local_channel_hints_cb(void *d UNUSED, struct payment *p) { struct out_req *req; /* If we are not the root we don't look up the channel balances since * it is unlikely that the capacities have changed much since the root * payment looked at them. We also only call `listpeers` when the * payment is in state PAYMENT_STEP_INITIALIZED, right before calling * `getroute`. */ if (p->parent != NULL || p->step != PAYMENT_STEP_INITIALIZED) return payment_continue(p); req = jsonrpc_request_start(p->plugin, NULL, "listpeers", local_channel_hints_listpeers, local_channel_hints_listpeers, p); send_outreq(p->plugin, req); } REGISTER_PAYMENT_MODIFIER(local_channel_hints, void *, NULL, local_channel_hints_cb); /* Trim route to this length by taking from the *front* of route * (end points to destination, so we need that bit!) */ static void trim_route(struct route_info **route, size_t n) { size_t remove = tal_count(*route) - n; memmove(*route, *route + remove, sizeof(**route) * n); tal_resize(route, n); } /* Make sure routehints are reasonable length, and (since we assume we * can append), not directly to us. Note: untrusted data! */ static struct route_info **filter_routehints(struct routehints_data *d, struct node_id *myid, struct route_info **hints) { char *mods = tal_strdup(tmpctx, ""); for (size_t i = 0; i < tal_count(hints); i++) { /* Trim any routehint > 10 hops */ size_t max_hops = ROUTING_MAX_HOPS / 2; if (tal_count(hints[i]) > max_hops) { tal_append_fmt(&mods, "Trimmed routehint %zu (%zu hops) to %zu. ", i, tal_count(hints[i]), max_hops); trim_route(&hints[i], max_hops); } /* If we are first hop, trim. */ if (tal_count(hints[i]) > 0 && node_id_eq(&hints[i][0].pubkey, myid)) { tal_append_fmt(&mods, "Removed ourselves from routehint %zu. ", i); trim_route(&hints[i], tal_count(hints[i])-1); } /* If route is empty, remove altogether. */ if (tal_count(hints[i]) == 0) { tal_append_fmt(&mods, "Removed empty routehint %zu. ", i); tal_arr_remove(&hints, i); i--; } } if (!streq(mods, "")) d->routehint_modifications = tal_steal(d, mods); return tal_steal(d, hints); } static bool routehint_excluded(struct payment *p, const struct route_info *routehint) { const struct node_id *nodes = payment_get_excluded_nodes(tmpctx, p); const struct short_channel_id_dir *chans = payment_get_excluded_channels(tmpctx, p); /* Note that we ignore direction here: in theory, we could have * found that one direction of a channel is unavailable, but they * are suggesting we use it the other way. Very unlikely though! */ for (size_t i = 0; i < tal_count(routehint); i++) { const struct route_info *r = &routehint[i]; for (size_t j=0; tal_count(nodes); j++) if (node_id_eq(&r->pubkey, &nodes[j])) return true; for (size_t j = 0; j < tal_count(chans); j++) if (short_channel_id_eq(&chans[j].scid, &r->short_channel_id)) return true; } return false; } static struct route_info *next_routehint(struct routehints_data *d, struct payment *p) { while (tal_count(d->routehints) > 0) { if (!routehint_excluded(p, d->routehints[0])) { d->current_routehint = d->routehints[0]; tal_arr_remove(&d->routehints, 0); return d->current_routehint; } tal_free(d->routehints[0]); tal_arr_remove(&d->routehints, 0); } return NULL; } /* Calculate how many millisatoshi we need at the start of this route * to get msatoshi to the end. */ static bool route_msatoshi(struct amount_msat *total, const struct amount_msat msat, const struct route_info *route, size_t num_route) { *total = msat; for (ssize_t i = num_route - 1; i >= 0; i--) { if (!amount_msat_add_fee(total, route[i].fee_base_msat, route[i].fee_proportional_millionths)) return false; } return true; } /* The pubkey to use is the destination of this routehint. */ static const struct node_id *route_pubkey(const struct payment *p, const struct route_info *routehint, size_t n) { if (n == tal_count(routehint)) return p->destination; return &routehint[n].pubkey; } static u32 route_cltv(u32 cltv, const struct route_info *route, size_t num_route) { for (size_t i = 0; i < num_route; i++) cltv += route[i].cltv_expiry_delta; return cltv; } static void routehint_step_cb(struct routehints_data *d, struct payment *p) { struct routehints_data *pd; struct route_hop hop; const struct payment *root = payment_root(p); if (p->step == PAYMENT_STEP_INITIALIZED) { if (root->invoice == NULL || root->invoice->routes == NULL) return payment_continue(p); /* The root payment gets the unmodified routehints, children may * start dropping some as they learn that they were not * functional. */ if (p->parent == NULL) { d->routehints = filter_routehints(d, p->local_id, p->invoice->routes); } else { pd = payment_mod_get_data(p->parent, &routehints_pay_mod); d->routehints = tal_dup_talarr(d, struct route_info *, pd->routehints); } d->current_routehint = next_routehint(d, p); if (d->current_routehint != NULL) { /* Change the destination and compute the final msatoshi * amount to send to the routehint entry point. */ if (!route_msatoshi(&p->getroute->amount, p->amount, d->current_routehint, tal_count(d->current_routehint))) { } d->final_cltv = p->getroute->cltv; p->getroute->destination = &d->current_routehint[0].pubkey; p->getroute->cltv = route_cltv(p->getroute->cltv, d->current_routehint, tal_count(d->current_routehint)); } } else if (p->step == PAYMENT_STEP_GOT_ROUTE) { /* Now it's time to stitch the two partial routes together. */ struct amount_msat dest_amount; struct route_info *routehint = d->current_routehint; struct route_hop *prev_hop; for (ssize_t i = 0; i < tal_count(routehint); i++) { prev_hop = &p->route[tal_count(p->route)-1]; if (!route_msatoshi(&dest_amount, p->amount, routehint + i + 1, tal_count(routehint) - i - 1)) { /* Just let it fail, since we couldn't stitch * the routes together. */ return payment_continue(p); } hop.nodeid = *route_pubkey(p, routehint, i + 1); hop.style = ROUTE_HOP_TLV; hop.channel_id = routehint[i].short_channel_id; hop.amount = dest_amount; hop.delay = route_cltv(d->final_cltv, routehint + i + 1, tal_count(routehint) - i - 1); /* Should we get a failure inside the routehint we'll * need the direction so we can exclude it. Luckily * it's rather easy to compute given the two * subsequent hops. */ hop.direction = node_id_cmp(&prev_hop->nodeid, &hop.nodeid) > 0 ? 1 : 0; tal_arr_expand(&p->route, hop); } } payment_continue(p); } static struct routehints_data *routehint_data_init(struct payment *p) { /* We defer the actual initialization to the step callback when we have * the invoice attached. */ return talz(p, struct routehints_data); } REGISTER_PAYMENT_MODIFIER(routehints, struct routehints_data *, routehint_data_init, routehint_step_cb); /* For tiny payments the fees incurred due to the fixed base_fee may dominate * the overall cost of the payment. Since these payments are often used as a * way to signal, rather than actually transfer the amount, we add an * exemption that allows tiny payments to exceed the fee allowance. This is * implemented by setting a larger allowance than we would normally do if the * payment is below the threshold. */ static struct exemptfee_data *exemptfee_data_init(struct payment *p) { if (p->parent == NULL) { struct exemptfee_data *d = tal(p, struct exemptfee_data); d->amount = AMOUNT_MSAT(5000); return d; } else { return payment_mod_exemptfee_get_data(p->parent); } } static void exemptfee_cb(struct exemptfee_data *d, struct payment *p) { if (p->step != PAYMENT_STEP_INITIALIZED || p->parent != NULL) return payment_continue(p); if (amount_msat_greater_eq(d->amount, p->constraints.fee_budget)) { plugin_log( p->plugin, LOG_INFORM, "Payment fee constraint %s is below exemption threshold, " "allowing a maximum fee of %s", type_to_string(tmpctx, struct amount_msat, &p->constraints.fee_budget), type_to_string(tmpctx, struct amount_msat, &d->amount)); p->constraints.fee_budget = d->amount; p->start_constraints->fee_budget = d->amount; } return payment_continue(p); } REGISTER_PAYMENT_MODIFIER(exemptfee, struct exemptfee_data *, exemptfee_data_init, exemptfee_cb); /* BOLT #7: * * If a route is computed by simply routing to the intended recipient and * summing the `cltv_expiry_delta`s, then it's possible for intermediate nodes * to guess their position in the route. Knowing the CLTV of the HTLC, the * surrounding network topology, and the `cltv_expiry_delta`s gives an * attacker a way to guess the intended recipient. Therefore, it's highly * desirable to add a random offset to the CLTV that the intended recipient * will receive, which bumps all CLTVs along the route. * * In order to create a plausible offset, the origin node MAY start a limited * random walk on the graph, starting from the intended recipient and summing * the `cltv_expiry_delta`s, and use the resulting sum as the offset. This * effectively creates a _shadow route extension_ to the actual route and * provides better protection against this attack vector than simply picking a * random offset would. */ static struct shadow_route_data *shadow_route_init(struct payment *p) { if (p->parent != NULL) { return payment_mod_shadowroute_get_data(p->parent); } else { struct shadow_route_data *d = tal(p, struct shadow_route_data); d->fuzz_amount = true; return d; } } /* Mutual recursion */ static struct command_result *shadow_route_listchannels(struct command *cmd, const char *buf, const jsmntok_t *result, struct payment *p); static struct command_result *shadow_route_extend(struct shadow_route_data *d, struct payment *p) { struct out_req *req; req = jsonrpc_request_start(p->plugin, NULL, "listchannels", shadow_route_listchannels, payment_rpc_failure, p); json_add_string(req->js, "source", type_to_string(req, struct node_id, &d->destination)); return send_outreq(p->plugin, req); } static struct command_result *shadow_route_listchannels(struct command *cmd, const char *buf, const jsmntok_t *result, struct payment *p) { /* Use reservoir sampling across the capable channels. */ struct shadow_route_data *d = payment_mod_shadowroute_get_data(p); struct payment_constraints *cons = &d->constraints; struct route_info *best = NULL; size_t i; u64 sample = 0; struct amount_msat best_fee; const jsmntok_t *sattok, *delaytok, *basefeetok, *propfeetok, *desttok, *channelstok, *chan; channelstok = json_get_member(buf, result, "channels"); json_for_each_arr(i, chan, channelstok) { u64 v = pseudorand(UINT64_MAX); struct route_info curr; struct amount_sat capacity; struct amount_msat fee; sattok = json_get_member(buf, chan, "satoshis"); delaytok = json_get_member(buf, chan, "delay"); basefeetok = json_get_member(buf, chan, "base_fee_millisatoshi"); propfeetok = json_get_member(buf, chan, "fee_per_millionth"); desttok = json_get_member(buf, chan, "destination"); if (sattok == NULL || delaytok == NULL || delaytok->type != JSMN_PRIMITIVE || basefeetok == NULL || basefeetok->type != JSMN_PRIMITIVE || propfeetok == NULL || propfeetok->type != JSMN_PRIMITIVE || desttok == NULL) continue; json_to_u16(buf, delaytok, &curr.cltv_expiry_delta); json_to_number(buf, basefeetok, &curr.fee_base_msat); json_to_number(buf, propfeetok, &curr.fee_proportional_millionths); json_to_sat(buf, sattok, &capacity); json_to_node_id(buf, desttok, &curr.pubkey); if (!best || v > sample) { /* If the capacity is insufficient to pass the amount * it's not a plausible extension. */ if (amount_msat_greater_sat(p->amount, capacity)) continue; if (curr.cltv_expiry_delta > cons->cltv_budget) continue; if (!amount_msat_fee( &fee, p->amount, curr.fee_base_msat, curr.fee_proportional_millionths)) { /* Fee computation failed... */ continue; } if (amount_msat_greater_eq(fee, cons->fee_budget)) continue; best = tal_dup(tmpctx, struct route_info, &curr); best_fee = fee; sample = v; } } if (best != NULL) { bool ok; /* Ok, we found an extension, let's add it. */ d->destination = best->pubkey; /* Apply deltas to the constraints in the shadow route so we * don't overshoot our 1/4th target. */ if (!payment_constraints_update(&d->constraints, best_fee, best->cltv_expiry_delta)) { best = NULL; goto next; } /* Now do the same to the payment constraints so other * modifiers don't do it either. */ ok = payment_constraints_update(&p->constraints, best_fee, best->cltv_expiry_delta); /* And now the thing that caused all of this: adjust the call * to getroute. */ if (d->fuzz_amount) { /* Only fuzz the amount to route to the destination if * we didn't opt-out earlier. */ ok &= amount_msat_add(&p->getroute->amount, p->getroute->amount, best_fee); } p->getroute->cltv += best->cltv_expiry_delta; assert(ok); } next: /* Now it's time to decide whether we want to extend or continue. */ if (best == NULL || pseudorand(2) == 0) { payment_continue(p); return command_still_pending(cmd); } else { return shadow_route_extend(d, p); } } static void shadow_route_cb(struct shadow_route_data *d, struct payment *p) { #if DEVELOPER if (!d->use_shadow) return payment_continue(p); #endif if (p->step != PAYMENT_STEP_INITIALIZED) return payment_continue(p); d->destination = *p->destination; /* Allow shadowroutes to consume up to 1/4th of our budget. */ d->constraints.cltv_budget = p->constraints.cltv_budget / 4; d->constraints.fee_budget = p->constraints.fee_budget; d->constraints.fee_budget.millisatoshis /= 4; /* Raw: msat division. */ if (pseudorand(2) == 0) { return payment_continue(p); } else { shadow_route_extend(d, p); } } REGISTER_PAYMENT_MODIFIER(shadowroute, struct shadow_route_data *, shadow_route_init, shadow_route_cb); static void direct_pay_override(struct payment *p) { /* The root has performed the search for a direct channel. */ struct payment *root = payment_root(p); struct direct_pay_data *d; struct channel_hint *hint = NULL; /* If we were unable to find a direct channel we don't need to do * anything. */ d = payment_mod_directpay_get_data(root); if (d->chan == NULL) return payment_continue(p); /* If we have a channel we need to make sure that it still has * sufficient capacity. Look it up in the channel_hints. */ for (size_t i=0; i<tal_count(root->channel_hints); i++) { struct short_channel_id_dir *cur = &root->channel_hints[i].scid; if (short_channel_id_eq(&cur->scid, &d->chan->scid) && cur->dir == d->chan->dir) { hint = &root->channel_hints[i]; break; } } if (hint && hint->enabled && amount_msat_greater(hint->estimated_capacity, p->amount)) { /* Now build a route that consists only of this single hop */ p->route = tal_arr(p, struct route_hop, 1); p->route[0].amount = p->amount; p->route[0].delay = p->getroute->cltv; p->route[0].channel_id = hint->scid.scid; p->route[0].direction = hint->scid.dir; p->route[0].nodeid = *p->destination; p->route[0].style = ROUTE_HOP_TLV; plugin_log(p->plugin, LOG_DBG, "Found a direct channel (%s) with sufficient " "capacity, skipping route computation.", type_to_string(tmpctx, struct short_channel_id_dir, &hint->scid)); payment_set_step(p, PAYMENT_STEP_GOT_ROUTE); } payment_continue(p); } /* Now that we have the listpeers result for the root payment, let's search * for a direct channel that is a) connected and b) in state normal. We will * check the capacity based on the channel_hints in the override. */ static struct command_result *direct_pay_listpeers(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { struct listpeers_result *r = json_to_listpeers_result(tmpctx, buffer, toks); struct direct_pay_data *d = payment_mod_directpay_get_data(p); if (tal_count(r->peers) == 1) { struct listpeers_peer *peer = r->peers[0]; if (!peer->connected) goto cont; for (size_t i=0; i<tal_count(peer->channels); i++) { struct listpeers_channel *chan = r->peers[0]->channels[i]; if (!streq(chan->state, "CHANNELD_NORMAL")) continue; d->chan = tal(d, struct short_channel_id_dir); d->chan->scid = *chan->scid; d->chan->dir = *chan->direction; } } cont: direct_pay_override(p); return command_still_pending(cmd); } static void direct_pay_cb(struct direct_pay_data *d, struct payment *p) { struct out_req *req; /* Look up the direct channel only on root. */ if (p->step != PAYMENT_STEP_INITIALIZED) return payment_continue(p); req = jsonrpc_request_start(p->plugin, NULL, "listpeers", direct_pay_listpeers, direct_pay_listpeers, p); json_add_node_id(req->js, "id", p->destination); send_outreq(p->plugin, req); } static struct direct_pay_data *direct_pay_init(struct payment *p) { struct direct_pay_data *d = tal(p, struct direct_pay_data); d->chan = NULL; return d; } REGISTER_PAYMENT_MODIFIER(directpay, struct direct_pay_data *, direct_pay_init, direct_pay_cb); static struct command_result *waitblockheight_rpc_cb(struct command *cmd, const char *buffer, const jsmntok_t *toks, struct payment *p) { struct payment *subpayment; subpayment = payment_new(p, NULL, p, p->modifiers); payment_start(subpayment); payment_set_step(p, PAYMENT_STEP_RETRY); subpayment->why = tal_fmt(subpayment, "Retrying after waiting for blockchain sync."); payment_continue(p); return command_still_pending(cmd); } static void waitblockheight_cb(void *d, struct payment *p) { struct out_req *req; struct timeabs now = time_now(); struct timerel remaining; u32 blockheight = p->start_block; int failcode; const u8 *raw_message; if (p->step != PAYMENT_STEP_FAILED) return payment_continue(p); /* If we don't have an error message to parse we can't wait for blockheight. */ if (p->result == NULL) return payment_continue(p); if (time_after(now, p->deadline)) return payment_continue(p); failcode = p->result->failcode; raw_message = p->result->raw_message; remaining = time_between(p->deadline, now); if (failcode == 17 /* Former final_expiry_too_soon */) { blockheight = p->start_block + 1; } else { /* If it's incorrect_or_unknown_payment_details, that tells us * what height they're at */ struct amount_msat unused; const void *ptr = raw_message; if (!fromwire_incorrect_or_unknown_payment_details( ptr, &unused, &blockheight)) return payment_continue(p); } /* If we are already at the desired blockheight there is no point in * waiting, and it is likely just some other error. Notice that * start_block gets set by the initial getinfo call for each * attempt.*/ if (blockheight <= p->start_block) return payment_continue(p); plugin_log(p->plugin, LOG_INFORM, "Remote node appears to be on a longer chain, which causes " "CLTV timeouts to be incorrect. Waiting up to %" PRIu64 " seconds to catch up to block %d before retrying.", time_to_sec(remaining), blockheight); /* Set temporarily set the state of the payment to not failed, so * interim status queries don't show this as terminally failed. We're * in control for this payment so nobody else could be fooled by * this. The callback will set it to retry anyway. */ payment_set_step(p, PAYMENT_STEP_RETRY); req = jsonrpc_request_start(p->plugin, NULL, "waitblockheight", waitblockheight_rpc_cb, waitblockheight_rpc_cb, p); json_add_u32(req->js, "blockheight", blockheight); json_add_u32(req->js, "timeout", time_to_sec(remaining)); send_outreq(p->plugin, req); } REGISTER_PAYMENT_MODIFIER(waitblockheight, void *, NULL, waitblockheight_cb); /***************************************************************************** * presplit -- Early MPP splitter modifier. * * This splitter modifier is applied to the root payment, and splits the * payment into parts that are more likely to succeed right away. The * parameters are derived from probing the network for channel capacities, and * may be adjusted in future. */ /*By probing the capacity from a well-connected vantage point in the network * we found that the 80th percentile of capacities is >= 9765 sats. * * Rounding to 10e6 msats per part there is a ~80% chance that the payment * will go through without requiring further splitting. The fuzzing is * symmetric and uniformy distributed around this value, so this should not * change the success rate much. For the remaining 20% of payments we might * require a split to make the parts succeed, so we try only a limited number * of times before we split adaptively. * * Notice that these numbers are based on a worst case assumption that * payments from any node to any other node are equally likely, which isn't * really the case, so this is likely a lower bound on the success rate. * * As the network evolves these numbers are also likely to change. */ #define MPP_TARGET_SIZE (10 * 1000 * 1000) #define MPP_TARGET_MSAT AMOUNT_MSAT(MPP_TARGET_SIZE) #define MPP_TARGET_FUZZ ( 1 * 1000 * 1000) static struct presplit_mod_data *presplit_mod_data_init(struct payment *p) { struct presplit_mod_data *d; if (p->parent == NULL) { d = tal(p, struct presplit_mod_data); d->disable = false; return d; } else { return payment_mod_presplit_get_data(p->parent); } } static bool payment_supports_mpp(struct payment *p) { if (p->invoice == NULL || p->invoice->features == NULL) return false; return feature_offered(p->invoice->features, OPT_BASIC_MPP); } static void presplit_cb(struct presplit_mod_data *d, struct payment *p) { struct payment *root = payment_root(p); struct amount_msat amt = root->amount; if (d->disable) return payment_continue(p); if (!payment_supports_mpp(p)) return payment_continue(p); if (p->step == PAYMENT_STEP_ONION_PAYLOAD) { /* We need to tell the last hop the total we're going to * send. Presplit disables amount fuzzing, so we should always * get the exact value through. */ size_t lastidx = tal_count(p->createonion_request->hops) - 1; struct createonion_hop *hop = &p->createonion_request->hops[lastidx]; if (hop->style == ROUTE_HOP_TLV) { struct tlv_field **fields = &hop->tlv_payload->fields; tlvstream_set_tlv_payload_data( fields, root->payment_secret, root->amount.millisatoshis); /* Raw: onion payload */ } } else if (p == root && p->step == PAYMENT_STEP_INITIALIZED) { /* The presplitter only acts on the root and only in the first * step. */ size_t count = 0; /* We need to opt-in to the MPP sending facility no matter * what we do. That means setting all partids to a non-zero * value. */ root->partid++; /* If we are already below the target size don't split it * either. */ if (amount_msat_greater(MPP_TARGET_MSAT, p->amount)) return payment_continue(p); /* Ok, we know we should split, so split here and then skip this * payment and start the children instead. */ while (!amount_msat_eq(amt, AMOUNT_MSAT(0))) { struct payment *c = payment_new(p, NULL, p, p->modifiers); /* Pseudorandom number in the range [-1, 1]. */ double rand = pseudorand_double() * 2 - 1; double multiplier; c->amount.millisatoshis = rand * MPP_TARGET_FUZZ + MPP_TARGET_SIZE; /* Raw: Multiplication */ /* Clamp the value to the total amount, so the fuzzing * doesn't go above the total. */ if (amount_msat_greater(c->amount, amt)) c->amount = amt; multiplier = (double)c->amount.millisatoshis / (double)p->amount.millisatoshis; /* Raw: msat division. */ if (!amount_msat_sub(&amt, amt, c->amount)) plugin_err( p->plugin, "Cannot subtract %s from %s in splitter", type_to_string(tmpctx, struct amount_msat, &c->amount), type_to_string(tmpctx, struct amount_msat, &amt)); /* Now adjust the constraints so we don't multiply them * when splitting. */ c->constraints.fee_budget.millisatoshis *= multiplier; /* Raw: Multiplication */ payment_start(c); count++; } p->step = PAYMENT_STEP_SPLIT; p->end_time = time_now(); p->why = tal_fmt( p, "Split into %zu sub-payments due to initial size (%s > " "%dmsat)", count, type_to_string(tmpctx, struct amount_msat, &root->amount), MPP_TARGET_SIZE); plugin_log(p->plugin, LOG_INFORM, "%s", p->why); p->result = NULL; p->route = NULL; } payment_continue(p); } REGISTER_PAYMENT_MODIFIER(presplit, struct presplit_mod_data *, presplit_mod_data_init, presplit_cb); /***************************************************************************** * Adaptive splitter -- Split payment if we can't get it through. * * The adaptive splitter splits the amount of a failed payment in half, with * +/- 10% randomness, and then starts two attempts, one for either side of * the split. The goal is to find two smaller routes, that still adhere to our * constraints, but that can complete the payment. */ #define MPP_ADAPTIVE_LOWER_LIMIT AMOUNT_MSAT(100 * 1000) static struct presplit_mod_data *adaptive_splitter_data_init(struct payment *p) { struct presplit_mod_data *d; if (p->parent == NULL) { d = tal(p, struct presplit_mod_data); d->disable = false; return d; } else { return payment_mod_presplit_get_data(p->parent); } } static void adaptive_splitter_cb(struct presplit_mod_data *d, struct payment *p) { struct payment *root = payment_root(p); if (d->disable) return payment_continue(p); if (!payment_supports_mpp(p) || root->abort) return payment_continue(p); if (p->step == PAYMENT_STEP_ONION_PAYLOAD) { /* We need to tell the last hop the total we're going to * send. Presplit disables amount fuzzing, so we should always * get the exact value through. */ size_t lastidx = tal_count(p->createonion_request->hops) - 1; struct createonion_hop *hop = &p->createonion_request->hops[lastidx]; if (hop->style == ROUTE_HOP_TLV) { struct tlv_field **fields = &hop->tlv_payload->fields; tlvstream_set_tlv_payload_data( fields, root->payment_secret, root->amount.millisatoshis); /* Raw: onion payload */ } } else if (p->step == PAYMENT_STEP_FAILED && !p->abort) { if (amount_msat_greater(p->amount, MPP_ADAPTIVE_LOWER_LIMIT)) { struct payment *a, *b; /* Random number in the range [90%, 110%] */ double rand = pseudorand_double() * 0.2 + 0.9; u64 mid = p->amount.millisatoshis / 2 * rand; /* Raw: multiplication */ bool ok; a = payment_new(p, NULL, p, p->modifiers); b = payment_new(p, NULL, p, p->modifiers); a->amount.millisatoshis = mid; /* Raw: split. */ b->amount.millisatoshis -= mid; /* Raw: split. */ /* Adjust constraints since we don't want to double our * fee allowance when we split. */ a->constraints.fee_budget.millisatoshis *= (double)a->amount.millisatoshis / (double)p->amount.millisatoshis; /* Raw: msat division. */ ok = amount_msat_sub(&b->constraints.fee_budget, p->constraints.fee_budget, a->constraints.fee_budget); /* Should not fail, mid is less than 55% of original * amount. fee_budget_a <= 55% of fee_budget_p (parent * of the new payments).*/ assert(ok); payment_start(a); payment_start(b); p->step = PAYMENT_STEP_SPLIT; } else { plugin_log(p->plugin, LOG_INFORM, "Lower limit of adaptive splitter reached " "(%s < %s), not splitting further.", type_to_string(tmpctx, struct amount_msat, &p->amount), type_to_string(tmpctx, struct amount_msat, &MPP_ADAPTIVE_LOWER_LIMIT)); } } payment_continue(p); } REGISTER_PAYMENT_MODIFIER(adaptive_splitter, struct presplit_mod_data *, adaptive_splitter_data_init, adaptive_splitter_cb);
32.241558
138
0.697495
[ "vector" ]
aa42a1fc6044ab4f14d2bb727a83eb7b29495f53
294
h
C
LittleWrapper/utils/env_utils.h
yahinstudio/LittleWrapper
46f28fb05e643b53fd3c96c08634f97aac4b35da
[ "MIT" ]
null
null
null
LittleWrapper/utils/env_utils.h
yahinstudio/LittleWrapper
46f28fb05e643b53fd3c96c08634f97aac4b35da
[ "MIT" ]
1
2021-09-25T15:33:03.000Z
2021-09-25T15:33:03.000Z
LittleWrapper/utils/env_utils.h
yahinstudio/LittleWrapper
46f28fb05e643b53fd3c96c08634f97aac4b35da
[ "MIT" ]
1
2022-01-20T10:06:08.000Z
2022-01-20T10:06:08.000Z
#pragma once #include <string> #include <vector> std::string get_exe_path(); std::string get_exe_filename(bool no_suffix); std::string get_current_work_dir(); void changed_current_work_dir(std::string newdir); std::vector<std::string> get_environments(); std::string get_temp_directory();
19.6
50
0.77551
[ "vector" ]
aa45e24b34603751c8e21cae4c631bd41eb54b1a
494
c
C
qemu_mode/qemu-2.10.0/roms/u-boot/common/board_info.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
31
2018-01-16T17:11:44.000Z
2022-03-16T13:51:24.000Z
qemu_mode/qemu-2.10.0/roms/u-boot/common/board_info.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
1
2021-04-29T09:08:08.000Z
2021-05-08T07:57:06.000Z
qemu_mode/qemu-2.10.0/roms/u-boot/common/board_info.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
30
2018-05-02T08:43:27.000Z
2022-01-23T03:25:54.000Z
/* * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <libfdt.h> #include <linux/compiler.h> int __weak checkboard(void) { return 0; } /* * If the root node of the DTB has a "model" property, show it. * Then call checkboard(). */ int __weak show_board_info(void) { #ifdef CONFIG_OF_CONTROL DECLARE_GLOBAL_DATA_PTR; const char *model; model = fdt_getprop(gd->fdt_blob, 0, "model", NULL); if (model) printf("Model: %s\n", model); #endif return checkboard(); }
15.4375
63
0.680162
[ "model" ]
aa4bb2869e675746bd117d1fc32cf57b0f07ebf6
3,618
h
C
GUI/OpenGL/Selection.h
Said6289/SPlisHSPlasH
fe0a37b05e25fa9d61bb7bd7372d1f26543d4e35
[ "MIT" ]
1,011
2016-11-17T19:31:00.000Z
2022-03-31T12:05:05.000Z
GUI/OpenGL/Selection.h
Said6289/SPlisHSPlasH
fe0a37b05e25fa9d61bb7bd7372d1f26543d4e35
[ "MIT" ]
127
2016-12-06T14:03:17.000Z
2022-03-29T01:51:56.000Z
GUI/OpenGL/Selection.h
Said6289/SPlisHSPlasH
fe0a37b05e25fa9d61bb7bd7372d1f26543d4e35
[ "MIT" ]
231
2016-11-21T03:54:31.000Z
2022-03-31T18:23:50.000Z
#ifndef __SELECTION_H__ #define __SELECTION_H__ #include "SPlisHSPlasH/Common.h" #include "MiniGL.h" #ifdef WIN32 #define NOMINMAX #include "windows.h" #endif #ifdef __APPLE__ #include <OpenGL/GL.h> #include <OpenGL/GLU.h> #else #include "GL/gl.h" #include "GL/glu.h" #endif #include <vector> namespace SPH { class Selection { public: Selection(){} ~Selection(){} struct SelectionPlane { Vector3r normal; Real d; }; template<typename PositionIteratorType> static void selectRect(const Eigen::Vector2i &start, const Eigen::Vector2i &end, const PositionIteratorType &posBegin, const PositionIteratorType &posEnd, std::vector<unsigned int> &hits) { int ip1y = end[1]; int ip2y = start[1]; int ileft = end[0] > start[0] ? start[0] : end[0]; int iright = end[0] < start[0] ? start[0] : end[0]; int itop = ip1y > ip2y ? ip1y : ip2y; int ibottom = ip1y < ip2y ? ip1y : ip2y; float left = (float)ileft; float right = (float)iright; float top = (float)itop; float bottom = (float)ibottom; if (left != right && top != bottom) { GLint viewport[4]; GLdouble mv[16],pm[16]; glGetIntegerv(GL_VIEWPORT, viewport); glGetDoublev(GL_MODELVIEW_MATRIX, mv); glGetDoublev(GL_PROJECTION_MATRIX, pm); GLdouble resx,resy,resz; float zNear = MiniGL::getZNear(); float zFar = MiniGL::getZFar(); gluUnProject(left, viewport[3] - top, zNear , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector0((Real)resx, (Real)resy, (Real)resz); gluUnProject(left, viewport[3] - top, zFar , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector1((Real)resx, (Real)resy, (Real)resz); gluUnProject(left, viewport[3] - bottom, zNear , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector2((Real)resx, (Real)resy, (Real)resz); gluUnProject(right, viewport[3] - top, zNear , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector3((Real)resx, (Real)resy, (Real)resz); gluUnProject(right, viewport[3] - bottom, zNear , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector4((Real)resx, (Real)resy, (Real)resz); gluUnProject(right, viewport[3] - bottom, zFar , mv, pm, viewport, &resx, &resy, &resz); const Vector3r vector5((Real)resx, (Real)resy, (Real)resz); SelectionPlane plane[4]; plane[0].normal = (vector3-vector0).cross(vector1-vector0); plane[0].d = -plane[0].normal.dot(vector0); plane[1].normal = (vector5-vector4).cross(vector3-vector4); plane[1].d = -plane[1].normal.dot(vector4); plane[2].normal = (vector2-vector4).cross(vector5-vector4); plane[2].d = -plane[2].normal.dot(vector4); plane[3].normal = (vector1-vector0).cross(vector2-vector0); plane[3].d = -plane[3].normal.dot(vector0); processSelectionHits(plane, posBegin, posEnd, hits); } } template<typename PositionIteratorType> static void processSelectionHits(SelectionPlane *planes, const PositionIteratorType &posBegin, const PositionIteratorType &posEnd, std::vector<unsigned int> &hits) { /////determine selected vertices////////// PositionIteratorType posIter; unsigned int index = 0; posIter = posBegin; while (true) { bool inQuad = true; const Vector3r p((*posIter)[0], (*posIter)[1], (*posIter)[2]); for (int j = 0; j < 4; ++j) { const Real d = planes[j].normal.dot(p) + planes[j].d; inQuad &= (d < 0); if (!inQuad) break; } if (inQuad) { hits.push_back(index); } index++; if (posIter == posEnd) break; posIter++; } } }; } #endif
29.414634
189
0.648425
[ "vector" ]
aa4f951a8f16e60ce08597414fe70d5b5064e4f2
1,866
h
C
tests/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83.h
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
1
2021-07-12T02:57:17.000Z
2021-07-16T02:07:29.000Z
testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83.h Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-83.tmpl.h */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83 { #ifndef OMITBAD class CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_bad { public: CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_bad(char * dataCopy); ~CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_bad(); private: char * data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodG2B { public: CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodG2B(char * dataCopy); ~CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodG2B(); private: char * data; }; class CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodB2G { public: CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodB2G(char * dataCopy); ~CWE762_Mismatched_Memory_Management_Routines__delete_array_char_malloc_83_goodB2G(); private: char * data; }; #endif /* OMITGOOD */ }
30.096774
122
0.801715
[ "object" ]
aa526880ba286c8ebfabf7163bef81e70bcd1dbe
2,850
h
C
tiny_slam/src/core/laser_scan_grid_world.h
HungEmb/DATNrepo
eb381a84ea0d69352f3dbbf2f6e5883a9ceac123
[ "Apache-2.0" ]
1
2021-12-18T16:01:34.000Z
2021-12-18T16:01:34.000Z
tiny_slam/src/core/laser_scan_grid_world.h
phucbk2001/DATNrepo
eb381a84ea0d69352f3dbbf2f6e5883a9ceac123
[ "Apache-2.0" ]
null
null
null
tiny_slam/src/core/laser_scan_grid_world.h
phucbk2001/DATNrepo
eb381a84ea0d69352f3dbbf2f6e5883a9ceac123
[ "Apache-2.0" ]
1
2021-12-18T16:01:25.000Z
2021-12-18T16:01:25.000Z
/** * \file * \brief Defines the special type of World. * There is class LaserScanGridWorld derived from World. */ #ifndef __LASER_SCAN_GRID_WORLD_H #define __LASER_SCAN_GRID_WORLD_H #include <memory> #include "sensor_data.h" #include "state_data.h" #include "maps/grid_cell_strategy.h" #include "maps/grid_map.h" /** * \brief Tracks a robots perception of an environment. * The environment is represented by a GridMap; A laser scan with * transformation is expected as a sensor data. */ class LaserScanGridWorld : public World<TransformedLaserScan, GridMap> { public: //types using MapType = GridMap; using Point = DiscretePoint2D; public: // methods /** * Creates a world as a Map of Grid Cells. * \param gcs A shared pointer to a cell strategy. */ LaserScanGridWorld(std::shared_ptr<GridCellStrategy> gcs, const GridMapParams &init_params) : _map(gcs->cell_factory(), init_params) {} /** * Updates the map cells according to a given sensor data. Straightforward * scan points projection is used. * \param scan The current scan from Laser Rangefinder. */ virtual void handle_observation(TransformedLaserScan &scan) { const RobotState& pose = World<TransformedLaserScan, MapType>::pose(); for (const auto &sp : scan.points) { // move to world frame assume sensor is in robots' (0,0) double x_world = pose.x + sp.range * std::cos(sp.angle + pose.theta); double y_world = pose.y + sp.range * std::sin(sp.angle + pose.theta); handle_scan_point(map(), pose.x, pose.y, x_world, y_world, sp.is_occupied, scan.quality); } } /** * Updates a cell of a given map according to given parameters. * \param map A current map. * \param laser_x,lasery Coordinates of a laser. * \param beam_end_x,beam_end_y Coordinates of a current point on a scan. * \param is_occ The current assumption whether the cell is occupied. * \param quality A scan quality. The greater the value the more probable the * transformed scan. */ virtual void handle_scan_point(MapType &map, double laser_x, double laser_y, double beam_end_x, double beam_end_y, bool is_occ, double quality) { Point robot_pt = map.world_to_cell(laser_x, laser_y); Point obst_pt = map.world_to_cell(beam_end_x, beam_end_y); std::vector<Point> pts = DiscreteLine2D(robot_pt, obst_pt).points(); map.update_cell(pts.back(), Occupancy{is_occ ? 1.0 : 0.0, 1.0}, quality); pts.pop_back(); for (const auto &pt : pts) { map.update_cell(pt, Occupancy{0.0, 1.0}, quality); } } virtual const MapType& map() const { return _map; } virtual MapType& map() { return _map; } private: // fields MapType _map; }; #endif
33.139535
79
0.668421
[ "vector" ]
aa5515fdb3ab7cb4f2db7973a1eb6ee685049b00
523
h
C
linedetect.h
lchia/vashingpoint
6d45d6d0adf66219a451930a09b16cfee35ff860
[ "Apache-2.0" ]
null
null
null
linedetect.h
lchia/vashingpoint
6d45d6d0adf66219a451930a09b16cfee35ff860
[ "Apache-2.0" ]
null
null
null
linedetect.h
lchia/vashingpoint
6d45d6d0adf66219a451930a09b16cfee35ff860
[ "Apache-2.0" ]
null
null
null
#ifndef LINEDETECT_H #define LINEDETECT_H #include <opencv2/core/core.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <vector> #include <algorithm> #include <math.h> #include <time.h> #include <ratio> #include <chrono> #include <ctime> #include <string> extern "C" { #include "lsd.h" }; class LineDetect { public: LineDetect(); std::vector<std::vector<double>> ld(cv::Mat img, double threshold_length, bool showing); }; #endif // LINEDETECT_H
17.433333
92
0.715105
[ "vector" ]
aa55e3cec665a736a5fba5fff57309712703d02a
36,381
c
C
linux-2.6.16-unmod/arch/x86_64/kernel/setup.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/x86_64/kernel/setup.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/arch/x86_64/kernel/setup.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
1
2019-05-14T16:36:45.000Z
2019-05-14T16:36:45.000Z
/* * linux/arch/x86-64/kernel/setup.c * * Copyright (C) 1995 Linus Torvalds * * Nov 2001 Dave Jones <davej@suse.de> * Forked from i386 setup code. * * $Id$ */ /* * This file handles the architecture-dependent parts of initialization */ #include <linux/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/a.out.h> #include <linux/tty.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/config.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/highmem.h> #include <linux/bootmem.h> #include <linux/module.h> #include <asm/processor.h> #include <linux/console.h> #include <linux/seq_file.h> #include <linux/crash_dump.h> #include <linux/root_dev.h> #include <linux/pci.h> #include <linux/acpi.h> #include <linux/kallsyms.h> #include <linux/edd.h> #include <linux/mmzone.h> #include <linux/kexec.h> #include <linux/cpufreq.h> #include <linux/dmi.h> #include <linux/dma-mapping.h> #include <asm/mtrr.h> #include <asm/uaccess.h> #include <asm/system.h> #include <asm/io.h> #include <asm/smp.h> #include <asm/msr.h> #include <asm/desc.h> #include <video/edid.h> #include <asm/e820.h> #include <asm/dma.h> #include <asm/mpspec.h> #include <asm/mmu_context.h> #include <asm/bootsetup.h> #include <asm/proto.h> #include <asm/setup.h> #include <asm/mach_apic.h> #include <asm/numa.h> #include <asm/swiotlb.h> #include <asm/sections.h> #include <asm/gart-mapping.h> /* * Machine setup.. */ struct cpuinfo_x86 boot_cpu_data __read_mostly; unsigned long mmu_cr4_features; int acpi_disabled; EXPORT_SYMBOL(acpi_disabled); #ifdef CONFIG_ACPI extern int __initdata acpi_ht; extern acpi_interrupt_flags acpi_sci_flags; int __initdata acpi_force = 0; #endif int acpi_numa __initdata; /* Boot loader ID as an integer, for the benefit of proc_dointvec */ int bootloader_type; unsigned long saved_video_mode; /* * Setup options */ struct screen_info screen_info; struct sys_desc_table_struct { unsigned short length; unsigned char table[0]; }; struct edid_info edid_info; struct e820map e820; extern int root_mountflags; char command_line[COMMAND_LINE_SIZE]; struct resource standard_io_resources[] = { { .name = "dma1", .start = 0x00, .end = 0x1f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic1", .start = 0x20, .end = 0x21, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer0", .start = 0x40, .end = 0x43, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "timer1", .start = 0x50, .end = 0x53, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "keyboard", .start = 0x60, .end = 0x6f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma page reg", .start = 0x80, .end = 0x8f, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "pic2", .start = 0xa0, .end = 0xa1, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "dma2", .start = 0xc0, .end = 0xdf, .flags = IORESOURCE_BUSY | IORESOURCE_IO }, { .name = "fpu", .start = 0xf0, .end = 0xff, .flags = IORESOURCE_BUSY | IORESOURCE_IO } }; #define STANDARD_IO_RESOURCES \ (sizeof standard_io_resources / sizeof standard_io_resources[0]) #define IORESOURCE_RAM (IORESOURCE_BUSY | IORESOURCE_MEM) struct resource data_resource = { .name = "Kernel data", .start = 0, .end = 0, .flags = IORESOURCE_RAM, }; struct resource code_resource = { .name = "Kernel code", .start = 0, .end = 0, .flags = IORESOURCE_RAM, }; #define IORESOURCE_ROM (IORESOURCE_BUSY | IORESOURCE_READONLY | IORESOURCE_MEM) static struct resource system_rom_resource = { .name = "System ROM", .start = 0xf0000, .end = 0xfffff, .flags = IORESOURCE_ROM, }; static struct resource extension_rom_resource = { .name = "Extension ROM", .start = 0xe0000, .end = 0xeffff, .flags = IORESOURCE_ROM, }; static struct resource adapter_rom_resources[] = { { .name = "Adapter ROM", .start = 0xc8000, .end = 0, .flags = IORESOURCE_ROM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_ROM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_ROM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_ROM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_ROM }, { .name = "Adapter ROM", .start = 0, .end = 0, .flags = IORESOURCE_ROM } }; #define ADAPTER_ROM_RESOURCES \ (sizeof adapter_rom_resources / sizeof adapter_rom_resources[0]) static struct resource video_rom_resource = { .name = "Video ROM", .start = 0xc0000, .end = 0xc7fff, .flags = IORESOURCE_ROM, }; static struct resource video_ram_resource = { .name = "Video RAM area", .start = 0xa0000, .end = 0xbffff, .flags = IORESOURCE_RAM, }; #define romsignature(x) (*(unsigned short *)(x) == 0xaa55) static int __init romchecksum(unsigned char *rom, unsigned long length) { unsigned char *p, sum = 0; for (p = rom; p < rom + length; p++) sum += *p; return sum == 0; } static void __init probe_roms(void) { unsigned long start, length, upper; unsigned char *rom; int i; /* video rom */ upper = adapter_rom_resources[0].start; for (start = video_rom_resource.start; start < upper; start += 2048) { rom = isa_bus_to_virt(start); if (!romsignature(rom)) continue; video_rom_resource.start = start; /* 0 < length <= 0x7f * 512, historically */ length = rom[2] * 512; /* if checksum okay, trust length byte */ if (length && romchecksum(rom, length)) video_rom_resource.end = start + length - 1; request_resource(&iomem_resource, &video_rom_resource); break; } start = (video_rom_resource.end + 1 + 2047) & ~2047UL; if (start < upper) start = upper; /* system rom */ request_resource(&iomem_resource, &system_rom_resource); upper = system_rom_resource.start; /* check for extension rom (ignore length byte!) */ rom = isa_bus_to_virt(extension_rom_resource.start); if (romsignature(rom)) { length = extension_rom_resource.end - extension_rom_resource.start + 1; if (romchecksum(rom, length)) { request_resource(&iomem_resource, &extension_rom_resource); upper = extension_rom_resource.start; } } /* check for adapter roms on 2k boundaries */ for (i = 0; i < ADAPTER_ROM_RESOURCES && start < upper; start += 2048) { rom = isa_bus_to_virt(start); if (!romsignature(rom)) continue; /* 0 < length <= 0x7f * 512, historically */ length = rom[2] * 512; /* but accept any length that fits if checksum okay */ if (!length || start + length > upper || !romchecksum(rom, length)) continue; adapter_rom_resources[i].start = start; adapter_rom_resources[i].end = start + length - 1; request_resource(&iomem_resource, &adapter_rom_resources[i]); start = adapter_rom_resources[i++].end & ~2047UL; } } static __init void parse_cmdline_early (char ** cmdline_p) { char c = ' ', *to = command_line, *from = COMMAND_LINE; int len = 0; int userdef = 0; for (;;) { if (c != ' ') goto next_char; #ifdef CONFIG_SMP /* * If the BIOS enumerates physical processors before logical, * maxcpus=N at enumeration-time can be used to disable HT. */ else if (!memcmp(from, "maxcpus=", 8)) { extern unsigned int maxcpus; maxcpus = simple_strtoul(from + 8, NULL, 0); } #endif #ifdef CONFIG_ACPI /* "acpi=off" disables both ACPI table parsing and interpreter init */ if (!memcmp(from, "acpi=off", 8)) disable_acpi(); if (!memcmp(from, "acpi=force", 10)) { /* add later when we do DMI horrors: */ acpi_force = 1; acpi_disabled = 0; } /* acpi=ht just means: do ACPI MADT parsing at bootup, but don't enable the full ACPI interpreter */ if (!memcmp(from, "acpi=ht", 7)) { if (!acpi_force) disable_acpi(); acpi_ht = 1; } else if (!memcmp(from, "pci=noacpi", 10)) acpi_disable_pci(); else if (!memcmp(from, "acpi=noirq", 10)) acpi_noirq_set(); else if (!memcmp(from, "acpi_sci=edge", 13)) acpi_sci_flags.trigger = 1; else if (!memcmp(from, "acpi_sci=level", 14)) acpi_sci_flags.trigger = 3; else if (!memcmp(from, "acpi_sci=high", 13)) acpi_sci_flags.polarity = 1; else if (!memcmp(from, "acpi_sci=low", 12)) acpi_sci_flags.polarity = 3; /* acpi=strict disables out-of-spec workarounds */ else if (!memcmp(from, "acpi=strict", 11)) { acpi_strict = 1; } #ifdef CONFIG_X86_IO_APIC else if (!memcmp(from, "acpi_skip_timer_override", 24)) acpi_skip_timer_override = 1; #endif #endif if (!memcmp(from, "disable_timer_pin_1", 19)) disable_timer_pin_1 = 1; if (!memcmp(from, "enable_timer_pin_1", 18)) disable_timer_pin_1 = -1; if (!memcmp(from, "nolapic", 7) || !memcmp(from, "disableapic", 11)) disable_apic = 1; /* Don't confuse with noapictimer */ if (!memcmp(from, "noapic", 6) && (from[6] == ' ' || from[6] == 0)) skip_ioapic_setup = 1; /* Make sure to not confuse with apic= */ if (!memcmp(from, "apic", 4) && (from[4] == ' ' || from[4] == 0)) { skip_ioapic_setup = 0; ioapic_force = 1; } if (!memcmp(from, "mem=", 4)) parse_memopt(from+4, &from); if (!memcmp(from, "memmap=", 7)) { /* exactmap option is for used defined memory */ if (!memcmp(from+7, "exactmap", 8)) { #ifdef CONFIG_CRASH_DUMP /* If we are doing a crash dump, we * still need to know the real mem * size before original memory map is * reset. */ saved_max_pfn = e820_end_of_ram(); #endif from += 8+7; end_pfn_map = 0; e820.nr_map = 0; userdef = 1; } else { parse_memmapopt(from+7, &from); userdef = 1; } } #ifdef CONFIG_NUMA if (!memcmp(from, "numa=", 5)) numa_setup(from+5); #endif if (!memcmp(from,"iommu=",6)) { iommu_setup(from+6); } if (!memcmp(from,"oops=panic", 10)) panic_on_oops = 1; if (!memcmp(from, "noexec=", 7)) nonx_setup(from + 7); #ifdef CONFIG_KEXEC /* crashkernel=size@addr specifies the location to reserve for * a crash kernel. By reserving this memory we guarantee * that linux never set's it up as a DMA target. * Useful for holding code to do something appropriate * after a kernel panic. */ else if (!memcmp(from, "crashkernel=", 12)) { unsigned long size, base; size = memparse(from+12, &from); if (*from == '@') { base = memparse(from+1, &from); /* FIXME: Do I want a sanity check * to validate the memory range? */ crashk_res.start = base; crashk_res.end = base + size - 1; } } #endif #ifdef CONFIG_PROC_VMCORE /* elfcorehdr= specifies the location of elf core header * stored by the crashed kernel. This option will be passed * by kexec loader to the capture kernel. */ else if(!memcmp(from, "elfcorehdr=", 11)) elfcorehdr_addr = memparse(from+11, &from); #endif #ifdef CONFIG_HOTPLUG_CPU else if (!memcmp(from, "additional_cpus=", 16)) setup_additional_cpus(from+16); #endif next_char: c = *(from++); if (!c) break; if (COMMAND_LINE_SIZE <= ++len) break; *(to++) = c; } if (userdef) { printk(KERN_INFO "user-defined physical RAM map:\n"); e820_print_map("user"); } *to = '\0'; *cmdline_p = command_line; } #ifndef CONFIG_NUMA static void __init contig_initmem_init(unsigned long start_pfn, unsigned long end_pfn) { unsigned long bootmap_size, bootmap; bootmap_size = bootmem_bootmap_pages(end_pfn)<<PAGE_SHIFT; bootmap = find_e820_area(0, end_pfn<<PAGE_SHIFT, bootmap_size); if (bootmap == -1L) panic("Cannot find bootmem map of size %ld\n",bootmap_size); bootmap_size = init_bootmem(bootmap >> PAGE_SHIFT, end_pfn); e820_bootmem_free(NODE_DATA(0), 0, end_pfn << PAGE_SHIFT); reserve_bootmem(bootmap, bootmap_size); } #endif /* Use inline assembly to define this because the nops are defined as inline assembly strings in the include files and we cannot get them easily into strings. */ asm("\t.data\nk8nops: " K8_NOP1 K8_NOP2 K8_NOP3 K8_NOP4 K8_NOP5 K8_NOP6 K8_NOP7 K8_NOP8); extern unsigned char k8nops[]; static unsigned char *k8_nops[ASM_NOP_MAX+1] = { NULL, k8nops, k8nops + 1, k8nops + 1 + 2, k8nops + 1 + 2 + 3, k8nops + 1 + 2 + 3 + 4, k8nops + 1 + 2 + 3 + 4 + 5, k8nops + 1 + 2 + 3 + 4 + 5 + 6, k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7, }; extern char __vsyscall_0; /* Replace instructions with better alternatives for this CPU type. This runs before SMP is initialized to avoid SMP problems with self modifying code. This implies that assymetric systems where APs have less capabilities than the boot processor are not handled. In this case boot with "noreplacement". */ void apply_alternatives(void *start, void *end) { struct alt_instr *a; int diff, i, k; for (a = start; (void *)a < end; a++) { u8 *instr; if (!boot_cpu_has(a->cpuid)) continue; BUG_ON(a->replacementlen > a->instrlen); instr = a->instr; /* vsyscall code is not mapped yet. resolve it manually. */ if (instr >= (u8 *)VSYSCALL_START && instr < (u8*)VSYSCALL_END) instr = __va(instr - (u8*)VSYSCALL_START + (u8*)__pa_symbol(&__vsyscall_0)); __inline_memcpy(instr, a->replacement, a->replacementlen); diff = a->instrlen - a->replacementlen; /* Pad the rest with nops */ for (i = a->replacementlen; diff > 0; diff -= k, i += k) { k = diff; if (k > ASM_NOP_MAX) k = ASM_NOP_MAX; __inline_memcpy(instr + i, k8_nops[k], k); } } } static int no_replacement __initdata = 0; void __init alternative_instructions(void) { extern struct alt_instr __alt_instructions[], __alt_instructions_end[]; if (no_replacement) return; apply_alternatives(__alt_instructions, __alt_instructions_end); } static int __init noreplacement_setup(char *s) { no_replacement = 1; return 0; } __setup("noreplacement", noreplacement_setup); #if defined(CONFIG_EDD) || defined(CONFIG_EDD_MODULE) struct edd edd; #ifdef CONFIG_EDD_MODULE EXPORT_SYMBOL(edd); #endif /** * copy_edd() - Copy the BIOS EDD information * from boot_params into a safe place. * */ static inline void copy_edd(void) { memcpy(edd.mbr_signature, EDD_MBR_SIGNATURE, sizeof(edd.mbr_signature)); memcpy(edd.edd_info, EDD_BUF, sizeof(edd.edd_info)); edd.mbr_signature_nr = EDD_MBR_SIG_NR; edd.edd_info_nr = EDD_NR; } #else static inline void copy_edd(void) { } #endif #define EBDA_ADDR_POINTER 0x40E static void __init reserve_ebda_region(void) { unsigned int addr; /** * there is a real-mode segmented pointer pointing to the * 4K EBDA area at 0x40E */ addr = *(unsigned short *)phys_to_virt(EBDA_ADDR_POINTER); addr <<= 4; if (addr) reserve_bootmem_generic(addr, PAGE_SIZE); } void __init setup_arch(char **cmdline_p) { unsigned long kernel_end; ROOT_DEV = old_decode_dev(ORIG_ROOT_DEV); screen_info = SCREEN_INFO; edid_info = EDID_INFO; saved_video_mode = SAVED_VIDEO_MODE; bootloader_type = LOADER_TYPE; #ifdef CONFIG_BLK_DEV_RAM rd_image_start = RAMDISK_FLAGS & RAMDISK_IMAGE_START_MASK; rd_prompt = ((RAMDISK_FLAGS & RAMDISK_PROMPT_FLAG) != 0); rd_doload = ((RAMDISK_FLAGS & RAMDISK_LOAD_FLAG) != 0); #endif setup_memory_region(); copy_edd(); if (!MOUNT_ROOT_RDONLY) root_mountflags &= ~MS_RDONLY; init_mm.start_code = (unsigned long) &_text; init_mm.end_code = (unsigned long) &_etext; init_mm.end_data = (unsigned long) &_edata; init_mm.brk = (unsigned long) &_end; code_resource.start = virt_to_phys(&_text); code_resource.end = virt_to_phys(&_etext)-1; data_resource.start = virt_to_phys(&_etext); data_resource.end = virt_to_phys(&_edata)-1; parse_cmdline_early(cmdline_p); early_identify_cpu(&boot_cpu_data); /* * partially used pages are not usable - thus * we are rounding upwards: */ end_pfn = e820_end_of_ram(); check_efer(); init_memory_mapping(0, (end_pfn_map << PAGE_SHIFT)); zap_low_mappings(0); #ifdef CONFIG_ACPI /* * Initialize the ACPI boot-time table parser (gets the RSDP and SDT). * Call this early for SRAT node setup. */ acpi_boot_table_init(); #endif #ifdef CONFIG_ACPI_NUMA /* * Parse SRAT to discover nodes. */ acpi_numa_init(); #endif #ifdef CONFIG_NUMA numa_initmem_init(0, end_pfn); #else contig_initmem_init(0, end_pfn); #endif /* Reserve direct mapping */ reserve_bootmem_generic(table_start << PAGE_SHIFT, (table_end - table_start) << PAGE_SHIFT); /* reserve kernel */ kernel_end = round_up(__pa_symbol(&_end),PAGE_SIZE); reserve_bootmem_generic(HIGH_MEMORY, kernel_end - HIGH_MEMORY); /* * reserve physical page 0 - it's a special BIOS page on many boxes, * enabling clean reboots, SMP operation, laptop functions. */ reserve_bootmem_generic(0, PAGE_SIZE); /* reserve ebda region */ reserve_ebda_region(); #ifdef CONFIG_SMP /* * But first pinch a few for the stack/trampoline stuff * FIXME: Don't need the extra page at 4K, but need to fix * trampoline before removing it. (see the GDT stuff) */ reserve_bootmem_generic(PAGE_SIZE, PAGE_SIZE); /* Reserve SMP trampoline */ reserve_bootmem_generic(SMP_TRAMPOLINE_BASE, PAGE_SIZE); #endif #ifdef CONFIG_ACPI_SLEEP /* * Reserve low memory region for sleep support. */ acpi_reserve_bootmem(); #endif #ifdef CONFIG_X86_LOCAL_APIC /* * Find and reserve possible boot-time SMP configuration: */ find_smp_config(); #endif #ifdef CONFIG_BLK_DEV_INITRD if (LOADER_TYPE && INITRD_START) { if (INITRD_START + INITRD_SIZE <= (end_pfn << PAGE_SHIFT)) { reserve_bootmem_generic(INITRD_START, INITRD_SIZE); initrd_start = INITRD_START ? INITRD_START + PAGE_OFFSET : 0; initrd_end = initrd_start+INITRD_SIZE; } else { printk(KERN_ERR "initrd extends beyond end of memory " "(0x%08lx > 0x%08lx)\ndisabling initrd\n", (unsigned long)(INITRD_START + INITRD_SIZE), (unsigned long)(end_pfn << PAGE_SHIFT)); initrd_start = 0; } } #endif #ifdef CONFIG_KEXEC if (crashk_res.start != crashk_res.end) { reserve_bootmem(crashk_res.start, crashk_res.end - crashk_res.start + 1); } #endif paging_init(); check_ioapic(); #ifdef CONFIG_ACPI /* * Read APIC and some other early information from ACPI tables. */ acpi_boot_init(); #endif init_cpu_to_node(); #ifdef CONFIG_X86_LOCAL_APIC /* * get boot-time SMP configuration: */ if (smp_found_config) get_smp_config(); init_apic_mappings(); #endif /* * Request address space for all standard RAM and ROM resources * and also for regions reported as reserved by the e820. */ probe_roms(); e820_reserve_resources(); request_resource(&iomem_resource, &video_ram_resource); { unsigned i; /* request I/O space for devices used on all i[345]86 PCs */ for (i = 0; i < STANDARD_IO_RESOURCES; i++) request_resource(&ioport_resource, &standard_io_resources[i]); } e820_setup_gap(); #ifdef CONFIG_GART_IOMMU iommu_hole_init(); #endif #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif } static int __cpuinit get_model_name(struct cpuinfo_x86 *c) { unsigned int *v; if (c->extended_cpuid_level < 0x80000004) return 0; v = (unsigned int *) c->x86_model_id; cpuid(0x80000002, &v[0], &v[1], &v[2], &v[3]); cpuid(0x80000003, &v[4], &v[5], &v[6], &v[7]); cpuid(0x80000004, &v[8], &v[9], &v[10], &v[11]); c->x86_model_id[48] = 0; return 1; } static void __cpuinit display_cacheinfo(struct cpuinfo_x86 *c) { unsigned int n, dummy, eax, ebx, ecx, edx; n = c->extended_cpuid_level; if (n >= 0x80000005) { cpuid(0x80000005, &dummy, &ebx, &ecx, &edx); printk(KERN_INFO "CPU: L1 I Cache: %dK (%d bytes/line), D cache %dK (%d bytes/line)\n", edx>>24, edx&0xFF, ecx>>24, ecx&0xFF); c->x86_cache_size=(ecx>>24)+(edx>>24); /* On K8 L1 TLB is inclusive, so don't count it */ c->x86_tlbsize = 0; } if (n >= 0x80000006) { cpuid(0x80000006, &dummy, &ebx, &ecx, &edx); ecx = cpuid_ecx(0x80000006); c->x86_cache_size = ecx >> 16; c->x86_tlbsize += ((ebx >> 16) & 0xfff) + (ebx & 0xfff); printk(KERN_INFO "CPU: L2 Cache: %dK (%d bytes/line)\n", c->x86_cache_size, ecx & 0xFF); } if (n >= 0x80000007) cpuid(0x80000007, &dummy, &dummy, &dummy, &c->x86_power); if (n >= 0x80000008) { cpuid(0x80000008, &eax, &dummy, &dummy, &dummy); c->x86_virt_bits = (eax >> 8) & 0xff; c->x86_phys_bits = eax & 0xff; } } #ifdef CONFIG_NUMA static int nearby_node(int apicid) { int i; for (i = apicid - 1; i >= 0; i--) { int node = apicid_to_node[i]; if (node != NUMA_NO_NODE && node_online(node)) return node; } for (i = apicid + 1; i < MAX_LOCAL_APIC; i++) { int node = apicid_to_node[i]; if (node != NUMA_NO_NODE && node_online(node)) return node; } return first_node(node_online_map); /* Shouldn't happen */ } #endif /* * On a AMD dual core setup the lower bits of the APIC id distingush the cores. * Assumes number of cores is a power of two. */ static void __init amd_detect_cmp(struct cpuinfo_x86 *c) { #ifdef CONFIG_SMP int cpu = smp_processor_id(); unsigned bits; #ifdef CONFIG_NUMA int node = 0; unsigned apicid = phys_proc_id[cpu]; #endif bits = 0; while ((1 << bits) < c->x86_max_cores) bits++; /* Low order bits define the core id (index of core in socket) */ cpu_core_id[cpu] = phys_proc_id[cpu] & ((1 << bits)-1); /* Convert the APIC ID into the socket ID */ phys_proc_id[cpu] >>= bits; #ifdef CONFIG_NUMA node = phys_proc_id[cpu]; if (apicid_to_node[apicid] != NUMA_NO_NODE) node = apicid_to_node[apicid]; if (!node_online(node)) { /* Two possibilities here: - The CPU is missing memory and no node was created. In that case try picking one from a nearby CPU - The APIC IDs differ from the HyperTransport node IDs which the K8 northbridge parsing fills in. Assume they are all increased by a constant offset, but in the same order as the HT nodeids. If that doesn't result in a usable node fall back to the path for the previous case. */ int ht_nodeid = apicid - (phys_proc_id[0] << bits); if (ht_nodeid >= 0 && apicid_to_node[ht_nodeid] != NUMA_NO_NODE) node = apicid_to_node[ht_nodeid]; /* Pick a nearby node */ if (!node_online(node)) node = nearby_node(apicid); } numa_set_node(cpu, node); printk(KERN_INFO "CPU %d(%d) -> Node %d -> Core %d\n", cpu, c->x86_max_cores, node, cpu_core_id[cpu]); #endif #endif } static int __init init_amd(struct cpuinfo_x86 *c) { int r; unsigned level; #ifdef CONFIG_SMP unsigned long value; /* * Disable TLB flush filter by setting HWCR.FFDIS on K8 * bit 6 of msr C001_0015 * * Errata 63 for SH-B3 steppings * Errata 122 for all steppings (F+ have it disabled by default) */ if (c->x86 == 15) { rdmsrl(MSR_K8_HWCR, value); value |= 1 << 6; wrmsrl(MSR_K8_HWCR, value); } #endif /* Bit 31 in normal CPUID used for nonstandard 3DNow ID; 3DNow is IDd by bit 31 in extended CPUID (1*32+31) anyway */ clear_bit(0*32+31, &c->x86_capability); /* On C+ stepping K8 rep microcode works well for copy/memset */ level = cpuid_eax(1); if (c->x86 == 15 && ((level >= 0x0f48 && level < 0x0f50) || level >= 0x0f58)) set_bit(X86_FEATURE_REP_GOOD, &c->x86_capability); r = get_model_name(c); if (!r) { switch (c->x86) { case 15: /* Should distinguish Models here, but this is only a fallback anyways. */ strcpy(c->x86_model_id, "Hammer"); break; } } display_cacheinfo(c); /* c->x86_power is 8000_0007 edx. Bit 8 is constant TSC */ if (c->x86_power & (1<<8)) set_bit(X86_FEATURE_CONSTANT_TSC, &c->x86_capability); if (c->extended_cpuid_level >= 0x80000008) { c->x86_max_cores = (cpuid_ecx(0x80000008) & 0xff) + 1; if (c->x86_max_cores & (c->x86_max_cores - 1)) c->x86_max_cores = 1; amd_detect_cmp(c); } return r; } static void __cpuinit detect_ht(struct cpuinfo_x86 *c) { #ifdef CONFIG_SMP u32 eax, ebx, ecx, edx; int index_msb, core_bits; int cpu = smp_processor_id(); cpuid(1, &eax, &ebx, &ecx, &edx); c->apicid = phys_pkg_id(0); if (!cpu_has(c, X86_FEATURE_HT) || cpu_has(c, X86_FEATURE_CMP_LEGACY)) return; smp_num_siblings = (ebx & 0xff0000) >> 16; if (smp_num_siblings == 1) { printk(KERN_INFO "CPU: Hyper-Threading is disabled\n"); } else if (smp_num_siblings > 1 ) { if (smp_num_siblings > NR_CPUS) { printk(KERN_WARNING "CPU: Unsupported number of the siblings %d", smp_num_siblings); smp_num_siblings = 1; return; } index_msb = get_count_order(smp_num_siblings); phys_proc_id[cpu] = phys_pkg_id(index_msb); printk(KERN_INFO "CPU: Physical Processor ID: %d\n", phys_proc_id[cpu]); smp_num_siblings = smp_num_siblings / c->x86_max_cores; index_msb = get_count_order(smp_num_siblings) ; core_bits = get_count_order(c->x86_max_cores); cpu_core_id[cpu] = phys_pkg_id(index_msb) & ((1 << core_bits) - 1); if (c->x86_max_cores > 1) printk(KERN_INFO "CPU: Processor Core ID: %d\n", cpu_core_id[cpu]); } #endif } /* * find out the number of processor cores on the die */ static int __cpuinit intel_num_cpu_cores(struct cpuinfo_x86 *c) { unsigned int eax; if (c->cpuid_level < 4) return 1; __asm__("cpuid" : "=a" (eax) : "0" (4), "c" (0) : "bx", "dx"); if (eax & 0x1f) return ((eax >> 26) + 1); else return 1; } static void srat_detect_node(void) { #ifdef CONFIG_NUMA unsigned node; int cpu = smp_processor_id(); /* Don't do the funky fallback heuristics the AMD version employs for now. */ node = apicid_to_node[hard_smp_processor_id()]; if (node == NUMA_NO_NODE) node = 0; numa_set_node(cpu, node); if (acpi_numa > 0) printk(KERN_INFO "CPU %d -> Node %d\n", cpu, node); #endif } static void __cpuinit init_intel(struct cpuinfo_x86 *c) { /* Cache sizes */ unsigned n; init_intel_cacheinfo(c); n = c->extended_cpuid_level; if (n >= 0x80000008) { unsigned eax = cpuid_eax(0x80000008); c->x86_virt_bits = (eax >> 8) & 0xff; c->x86_phys_bits = eax & 0xff; /* CPUID workaround for Intel 0F34 CPU */ if (c->x86_vendor == X86_VENDOR_INTEL && c->x86 == 0xF && c->x86_model == 0x3 && c->x86_mask == 0x4) c->x86_phys_bits = 36; } if (c->x86 == 15) c->x86_cache_alignment = c->x86_clflush_size * 2; if ((c->x86 == 0xf && c->x86_model >= 0x03) || (c->x86 == 0x6 && c->x86_model >= 0x0e)) set_bit(X86_FEATURE_CONSTANT_TSC, &c->x86_capability); set_bit(X86_FEATURE_SYNC_RDTSC, &c->x86_capability); c->x86_max_cores = intel_num_cpu_cores(c); srat_detect_node(); } static void __cpuinit get_cpu_vendor(struct cpuinfo_x86 *c) { char *v = c->x86_vendor_id; if (!strcmp(v, "AuthenticAMD")) c->x86_vendor = X86_VENDOR_AMD; else if (!strcmp(v, "GenuineIntel")) c->x86_vendor = X86_VENDOR_INTEL; else c->x86_vendor = X86_VENDOR_UNKNOWN; } struct cpu_model_info { int vendor; int family; char *model_names[16]; }; /* Do some early cpuid on the boot CPU to get some parameter that are needed before check_bugs. Everything advanced is in identify_cpu below. */ void __cpuinit early_identify_cpu(struct cpuinfo_x86 *c) { u32 tfms; c->loops_per_jiffy = loops_per_jiffy; c->x86_cache_size = -1; c->x86_vendor = X86_VENDOR_UNKNOWN; c->x86_model = c->x86_mask = 0; /* So far unknown... */ c->x86_vendor_id[0] = '\0'; /* Unset */ c->x86_model_id[0] = '\0'; /* Unset */ c->x86_clflush_size = 64; c->x86_cache_alignment = c->x86_clflush_size; c->x86_max_cores = 1; c->extended_cpuid_level = 0; memset(&c->x86_capability, 0, sizeof c->x86_capability); /* Get vendor name */ cpuid(0x00000000, (unsigned int *)&c->cpuid_level, (unsigned int *)&c->x86_vendor_id[0], (unsigned int *)&c->x86_vendor_id[8], (unsigned int *)&c->x86_vendor_id[4]); get_cpu_vendor(c); /* Initialize the standard set of capabilities */ /* Note that the vendor-specific code below might override */ /* Intel-defined flags: level 0x00000001 */ if (c->cpuid_level >= 0x00000001) { __u32 misc; cpuid(0x00000001, &tfms, &misc, &c->x86_capability[4], &c->x86_capability[0]); c->x86 = (tfms >> 8) & 0xf; c->x86_model = (tfms >> 4) & 0xf; c->x86_mask = tfms & 0xf; if (c->x86 == 0xf) c->x86 += (tfms >> 20) & 0xff; if (c->x86 >= 0x6) c->x86_model += ((tfms >> 16) & 0xF) << 4; if (c->x86_capability[0] & (1<<19)) c->x86_clflush_size = ((misc >> 8) & 0xff) * 8; } else { /* Have CPUID level 0 only - unheard of */ c->x86 = 4; } #ifdef CONFIG_SMP phys_proc_id[smp_processor_id()] = (cpuid_ebx(1) >> 24) & 0xff; #endif } /* * This does the hard work of actually picking apart the CPU stuff... */ void __cpuinit identify_cpu(struct cpuinfo_x86 *c) { int i; u32 xlvl; early_identify_cpu(c); /* AMD-defined flags: level 0x80000001 */ xlvl = cpuid_eax(0x80000000); c->extended_cpuid_level = xlvl; if ((xlvl & 0xffff0000) == 0x80000000) { if (xlvl >= 0x80000001) { c->x86_capability[1] = cpuid_edx(0x80000001); c->x86_capability[6] = cpuid_ecx(0x80000001); } if (xlvl >= 0x80000004) get_model_name(c); /* Default name */ } /* Transmeta-defined flags: level 0x80860001 */ xlvl = cpuid_eax(0x80860000); if ((xlvl & 0xffff0000) == 0x80860000) { /* Don't set x86_cpuid_level here for now to not confuse. */ if (xlvl >= 0x80860001) c->x86_capability[2] = cpuid_edx(0x80860001); } /* * Vendor-specific initialization. In this section we * canonicalize the feature flags, meaning if there are * features a certain CPU supports which CPUID doesn't * tell us, CPUID claiming incorrect flags, or other bugs, * we handle them here. * * At the end of this section, c->x86_capability better * indicate the features this CPU genuinely supports! */ switch (c->x86_vendor) { case X86_VENDOR_AMD: init_amd(c); break; case X86_VENDOR_INTEL: init_intel(c); break; case X86_VENDOR_UNKNOWN: default: display_cacheinfo(c); break; } select_idle_routine(c); detect_ht(c); /* * On SMP, boot_cpu_data holds the common feature set between * all CPUs; so make sure that we indicate which features are * common between the CPUs. The first time this routine gets * executed, c == &boot_cpu_data. */ if (c != &boot_cpu_data) { /* AND the already accumulated flags with these */ for (i = 0 ; i < NCAPINTS ; i++) boot_cpu_data.x86_capability[i] &= c->x86_capability[i]; } #ifdef CONFIG_X86_MCE mcheck_init(c); #endif if (c == &boot_cpu_data) mtrr_bp_init(); else mtrr_ap_init(); #ifdef CONFIG_NUMA numa_add_cpu(smp_processor_id()); #endif } void __cpuinit print_cpu_info(struct cpuinfo_x86 *c) { if (c->x86_model_id[0]) printk("%s", c->x86_model_id); if (c->x86_mask || c->cpuid_level >= 0) printk(" stepping %02x\n", c->x86_mask); else printk("\n"); } /* * Get CPU information for use by the procfs. */ static int show_cpuinfo(struct seq_file *m, void *v) { struct cpuinfo_x86 *c = v; /* * These flag bits must match the definitions in <asm/cpufeature.h>. * NULL means this bit is undefined or reserved; either way it doesn't * have meaning as far as Linux is concerned. Note that it's important * to realize there is a difference between this table and CPUID -- if * applications want to get the raw CPUID data, they should access * /dev/cpu/<cpu_nr>/cpuid instead. */ static char *x86_cap_flags[] = { /* Intel-defined */ "fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mce", "cx8", "apic", NULL, "sep", "mtrr", "pge", "mca", "cmov", "pat", "pse36", "pn", "clflush", NULL, "dts", "acpi", "mmx", "fxsr", "sse", "sse2", "ss", "ht", "tm", "ia64", NULL, /* AMD-defined */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "syscall", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "nx", NULL, "mmxext", NULL, NULL, "fxsr_opt", "rdtscp", NULL, NULL, "lm", "3dnowext", "3dnow", /* Transmeta-defined */ "recovery", "longrun", NULL, "lrti", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* Other (Linux-defined) */ "cxmmx", NULL, "cyrix_arr", "centaur_mcr", NULL, "constant_tsc", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* Intel-defined (#2) */ "pni", NULL, NULL, "monitor", "ds_cpl", "vmx", NULL, "est", "tm2", NULL, "cid", NULL, NULL, "cx16", "xtpr", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* VIA/Cyrix/Centaur-defined */ NULL, NULL, "rng", "rng_en", NULL, NULL, "ace", "ace_en", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* AMD-defined (#2) */ "lahf_lm", "cmp_legacy", "svm", NULL, "cr8_legacy", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; static char *x86_power_flags[] = { "ts", /* temperature sensor */ "fid", /* frequency id control */ "vid", /* voltage id control */ "ttp", /* thermal trip */ "tm", "stc", NULL, /* nothing */ /* constant_tsc - moved to flags */ }; #ifdef CONFIG_SMP if (!cpu_online(c-cpu_data)) return 0; #endif seq_printf(m,"processor\t: %u\n" "vendor_id\t: %s\n" "cpu family\t: %d\n" "model\t\t: %d\n" "model name\t: %s\n", (unsigned)(c-cpu_data), c->x86_vendor_id[0] ? c->x86_vendor_id : "unknown", c->x86, (int)c->x86_model, c->x86_model_id[0] ? c->x86_model_id : "unknown"); if (c->x86_mask || c->cpuid_level >= 0) seq_printf(m, "stepping\t: %d\n", c->x86_mask); else seq_printf(m, "stepping\t: unknown\n"); if (cpu_has(c,X86_FEATURE_TSC)) { unsigned int freq = cpufreq_quick_get((unsigned)(c-cpu_data)); if (!freq) freq = cpu_khz; seq_printf(m, "cpu MHz\t\t: %u.%03u\n", freq / 1000, (freq % 1000)); } /* Cache size */ if (c->x86_cache_size >= 0) seq_printf(m, "cache size\t: %d KB\n", c->x86_cache_size); #ifdef CONFIG_SMP if (smp_num_siblings * c->x86_max_cores > 1) { int cpu = c - cpu_data; seq_printf(m, "physical id\t: %d\n", phys_proc_id[cpu]); seq_printf(m, "siblings\t: %d\n", cpus_weight(cpu_core_map[cpu])); seq_printf(m, "core id\t\t: %d\n", cpu_core_id[cpu]); seq_printf(m, "cpu cores\t: %d\n", c->booted_cores); } #endif seq_printf(m, "fpu\t\t: yes\n" "fpu_exception\t: yes\n" "cpuid level\t: %d\n" "wp\t\t: yes\n" "flags\t\t:", c->cpuid_level); { int i; for ( i = 0 ; i < 32*NCAPINTS ; i++ ) if ( test_bit(i, &c->x86_capability) && x86_cap_flags[i] != NULL ) seq_printf(m, " %s", x86_cap_flags[i]); } seq_printf(m, "\nbogomips\t: %lu.%02lu\n", c->loops_per_jiffy/(500000/HZ), (c->loops_per_jiffy/(5000/HZ)) % 100); if (c->x86_tlbsize > 0) seq_printf(m, "TLB size\t: %d 4K pages\n", c->x86_tlbsize); seq_printf(m, "clflush size\t: %d\n", c->x86_clflush_size); seq_printf(m, "cache_alignment\t: %d\n", c->x86_cache_alignment); seq_printf(m, "address sizes\t: %u bits physical, %u bits virtual\n", c->x86_phys_bits, c->x86_virt_bits); seq_printf(m, "power management:"); { unsigned i; for (i = 0; i < 32; i++) if (c->x86_power & (1 << i)) { if (i < ARRAY_SIZE(x86_power_flags) && x86_power_flags[i]) seq_printf(m, "%s%s", x86_power_flags[i][0]?" ":"", x86_power_flags[i]); else seq_printf(m, " [%d]", i); } } seq_printf(m, "\n\n"); return 0; } static void *c_start(struct seq_file *m, loff_t *pos) { return *pos < NR_CPUS ? cpu_data + *pos : NULL; } static void *c_next(struct seq_file *m, void *v, loff_t *pos) { ++*pos; return c_start(m, pos); } static void c_stop(struct seq_file *m, void *v) { } struct seq_operations cpuinfo_op = { .start =c_start, .next = c_next, .stop = c_stop, .show = show_cpuinfo, }; static int __init run_dmi_scan(void) { dmi_scan_machine(); return 0; } core_initcall(run_dmi_scan);
25.747346
89
0.662983
[ "model" ]
aa65157ab8f3d006d24ae098cea860bdb90a1281
49,762
h
C
iterators/query.h
reeseschultz/godex
38a7e7c4a48f6255a8e3beb7c86242bf07b907b6
[ "MIT" ]
576
2021-01-13T08:12:57.000Z
2022-03-29T14:21:50.000Z
iterators/query.h
reeseschultz/godex
38a7e7c4a48f6255a8e3beb7c86242bf07b907b6
[ "MIT" ]
101
2021-01-14T14:19:25.000Z
2022-03-07T06:56:33.000Z
iterators/query.h
reeseschultz/godex
38a7e7c4a48f6255a8e3beb7c86242bf07b907b6
[ "MIT" ]
41
2021-01-13T07:37:48.000Z
2022-03-24T07:14:47.000Z
#pragma once #include "../storage/storage.h" #include "../systems/system.h" #include "../world/world.h" // ---------------------------------------------------------------- Query filters template <class C> struct Not {}; template <class C> struct Create {}; template <class C> struct Maybe {}; template <class C> struct Changed {}; /// Some storages have the ability to store multiple components per `Entity`, /// to get all the stored components you can use the `Batch` filter: /// `Query<Batch<MyEvent>> query;` /// /// This filter allow nesting, indeed it's possible to specify sub filters: /// - `Query<Batch<Changed<MyEvent>> query;` /// - `Query<Batch<Maybe<const MyEvent>> query;` /// - `Query<Batch<const MyEvent> query;` /// /// You can access the data like an array, here an example: /// ``` /// Query<Batch<Changed<MyEvent>> query; /// for( auto [event] : query ){ /// if(event.is_empty()){ /// print_line("No events"); /// }else{ /// for(uint32_t i = 0; i < event.get_size(); i+=1){ /// print_line(event[i]); /// } /// } /// } /// ``` template <class C> class Batch { C data; uint32_t size; public: Batch() = default; Batch(const Batch &) = default; Batch(C p_data, uint32_t p_size) : data(p_data), size(p_size) {} // Get the component at position `index`. C operator[](uint32_t p_index) { #ifdef DEBUG_ENABLED CRASH_COND(p_index >= size); #endif return data + p_index; } // Get the component at position `index`. const std::remove_const<C> operator[](uint32_t p_index) const { #ifdef DEBUG_ENABLED CRASH_COND(p_index >= size); #endif return data + p_index; } /// Get the components count. uint32_t get_size() const { return size; } /// Returns `true` if this contains 0 components. bool is_empty() const { return data == nullptr; } }; /// The `Any` filter is satisfied if at least 1 sub filter is satisfied: /// in such cases all are ruturned or `nullptr` instead. /// /// ``` /// Query<Any<Changed<Transform>, Changed<Active>> query; /// ``` /// /// NOTICE: You can't nest `Any` twice like this: /// ``` /// Query<Any<Any<Transform, Active>> query; /// ``` /// (It doesn't make sense) template <class... Cs> struct Any {}; /// The `Join` filter is just an utility that collapse the sub components /// to one, taking the first `satisfied`. /// /// For example, this `Query<Join<TagA, TagB>>` returns all the entities /// that contains TagA or TagB. /// The syntax to extract the data is the following: /// ``` /// Query<Join<TagA, TagB>> query; /// /// auto [tag] = query[entity_1]; /// if( tag.is<TagA>() ){ /// TagA* tag_a = tag.as<TagA>(); /// } else /// if( tag.is<TagB>() ){ /// TagB* tag_b = tag.as<TagB>(); /// } /// ``` template <class... Cs> struct Join {}; struct JoinData { private: void *ptr; godex::component_id id; bool is_const; public: JoinData(void *p_ptr, godex::component_id p_id, bool p_const) : ptr(p_ptr), id(p_id), is_const(p_const) {} JoinData() = default; JoinData(const JoinData &) = default; /// Returns `true` when the wrapped ptr is `nullptr`. bool is_null() const { return ptr == nullptr; } /// Returns `true` if `T` is a valid conversion. This function take into /// account mutability. /// ``` /// Join join; /// if( join.is<TestComponent>() ){ /// join.as<TestComponent>(); /// } else /// if ( join.is<const TestComponent>() ) { /// join.as<const TestComponent>(); /// } /// ``` template <class T> bool is() const { return id == T::get_component_id() && std::is_const<T>::value == is_const; } /// Unwrap the pointer, and cast it to T. /// It's possible to check the type using `is<TypeHere>()`. template <class T> T *as() { #ifdef DEBUG_ENABLED // Just check the mutability here, no need to check the type also, so // it's possible to cast it easily to other types (like the base type). if (unlikely(ptr != nullptr)) { ERR_FAIL_COND_V_MSG(std::is_const<T>::value != is_const, nullptr, "Please retrieve this JOINED data with the correct mutability."); } #endif return static_cast<T *>(ptr); } /// If the data is const, never return the pointer as non const. template <class T> const T *as() const { return static_cast<const std::remove_const_t<T> *>(ptr); } }; // --------------------------------------------------------- Fetch Elements Type /// This is an utility that is used by the `QueryResultTuple` to fetch the /// variable type for a specific element of the query. /// The first template parameter `S`, stands for `Search`, and can be used to /// point a specific Query element. /// The following templates are just the `Query` definition. /// /// ```cpp /// fetch_element_type<0, 0, int, Any<int, float>, bool> // This is int* /// fetch_element_type<1, 0, int, Any<int, float>, bool> // This is float* /// /// fetch_element_type<0, 0, Not<int>, Any<int, Batch<Changed<float>>>, Maybe<bool>, EntityID> // This is int* /// fetch_element_type<1, 0, Not<int>, Any<int, Batch<Changed<float>>>, Maybe<bool>, EntityID> // This is int* /// fetch_element_type<2, 0, Not<int>, Any<int, Batch<Changed<float>>>, Maybe<bool>, EntityID> // This is Batch<float*> /// fetch_element_type<3, 0, Not<int>, Any<int, Batch<Changed<float>>>, Maybe<bool>, EntityID> // This is float* /// fetch_element_type<4, 0, Not<int>, Any<int, Batch<Changed<float>>>, Maybe<bool>, EntityID> // This is bool* /// ``` /// /// # How it works /// When you call `fetch_element_type`, as shown, the compiler fetches the `type` /// of the element where `S` and `I` are the same. /// /// @tparam S stands for `Search` /// @tparam I stands for `Index`, this must always be 0 when you define it. /// @tparam ...Cs The Query type. template <std::size_t S, std::size_t I, class... Cs> struct fetch_element {}; /// Just an utility. template <std::size_t S, std::size_t B, class... Cs> using fetch_element_type = typename fetch_element<S, B, Cs...>::type; /// Query element type found: It's just a pointer. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, C, Cs...> : fetch_element<S, S + 1, Cs...> { using type = C *; }; /// We found the `Changed` filter, fetch the type now. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, Changed<C>, Cs...> : fetch_element<S, S + 1, Cs...> { // Keep search the sub type: so we can nest with other filters. using type = fetch_element_type<0, 0, C>; }; /// We found the `Not` filter, fetch the type now. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, Not<C>, Cs...> : fetch_element<S, S + 1, Cs...> { // Keep search the sub type: so we can nest with other filters. using type = fetch_element_type<0, 0, C>; }; /// We found the `Create` filter, fetch the type now. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, Create<C>, Cs...> : fetch_element<S, S + 1, Cs...> { // Just C *; using type = C *; }; /// We found the `Maybe` filter, fetch the type now. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, Maybe<C>, Cs...> : fetch_element<S, S + 1, Cs...> { // Keep search the sub type: so we can nest with other filters. using type = fetch_element_type<0, 0, C>; }; /// We found the `Batch` filter, fetch the type now. template <std::size_t S, class C, class... Cs> struct fetch_element<S, S, Batch<C>, Cs...> : fetch_element<S, S + 1, Cs...> { // Append `Batch` but also keep search the sub type: so we can nest other filters. using type = Batch<fetch_element_type<0, 0, C>>; }; /// We found the `Join` filter, fetch the type now. template <std::size_t S, class... C, class... Cs> struct fetch_element<S, S, Join<C...>, Cs...> : fetch_element<S, S + 1, Cs...> { // Just JoinData. using type = JoinData; }; /// We found the `EntityID` filter, fetch the type now. template <std::size_t S, class... Cs> struct fetch_element<S, S, EntityID, Cs...> : fetch_element<S, S + 1, Cs...> { // The type is just an `EntityID`. using type = EntityID; }; /// Found specialization `Any` where `S` and `I` are the same: Flatten it as usual. template <std::size_t S, class... C, class... Cs> struct fetch_element<S, S, Any<C...>, Cs...> : fetch_element<S, S, C..., Cs...> { }; /// Found specialization `Any`: Just flatten its sub types. template <std::size_t S, std::size_t I, class... C, class... Cs> struct fetch_element<S, I, Any<C...>, Cs...> : fetch_element<S, I, C..., Cs...> {}; /// `S` and `I` are not yet the same: Just check the next `I`. template <std::size_t S, std::size_t I, class C, class... Cs> struct fetch_element<S, I, C, Cs...> : fetch_element<S, I + 1, Cs...> {}; // ---------------------------------------------------------- Query Result Tuple /// This class is the base query result tuple. /// /// `I` stands for `Index` and it's used to index the types. /// /// `I` must be always 0 when you define a new tuple so it can index all the /// components correctly. /// However, never use this directly rather use `QueryResultTuple`. template <std::size_t I, class... Cs> struct QueryResultTuple_Impl { /// The count of elements in this tuple. static constexpr std::size_t SIZE = I; }; /// No filter specialization. template <std::size_t I, class C, class... Cs> struct QueryResultTuple_Impl<I, C, Cs...> : public QueryResultTuple_Impl<I + 1, Cs...> { C *value = nullptr; }; /// `Batch` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryResultTuple_Impl<I, Batch<C>, Cs...> : public QueryResultTuple_Impl<I + 1, Cs...> { Batch<fetch_element_type<0, 0, C>> value = Batch<fetch_element_type<0, 0, C>>(nullptr, 0); }; /// `Join` filter specialization. template <std::size_t I, class... C, class... Cs> struct QueryResultTuple_Impl<I, Join<C...>, Cs...> : public QueryResultTuple_Impl<I + 1, Cs...> { JoinData value = JoinData(nullptr, godex::COMPONENT_NONE, true); }; /// `EntityID` filter specialization. template <std::size_t I, class... Cs> struct QueryResultTuple_Impl<I, EntityID, Cs...> : public QueryResultTuple_Impl<I + 1, Cs...> { EntityID value; }; /// Flatten all the Filter, so we can store the data on the same level. /// This template is able to flatten the filters: `Changed`, `Not`, `Maybe`, `Any`, `Join` /// /// Notice: This is just forwarding the declaration, indeed this has the same /// index the flattened data has. /// /// ``` /// This: /// QeryResultTuple_Impl<0, int, Not<float>> /// /// Is compiled as: /// `ResultTuple<0, int> : /// ResultTuple<1, Not<>> : /// ResultTuple<1, float> /// ``` /// The `set` and `get` functions are able to fetch the data anyway. template <std::size_t I, class... C, class... Cs, template <class> class Filter> struct QueryResultTuple_Impl<I, Filter<C...>, Cs...> : public QueryResultTuple_Impl<I, C..., Cs...> {}; /// `QueryResultTuple` is the tuple returned by the `Query`. You can fetch the /// data using the `get` function: /// ```cpp /// Query<Transform, Mesh> query; /// QueryResult result = query.get(); /// Transform* t = get<0>(result); /// ``` /// /// Or you can use the structured bindings: /// ```cpp /// Query<Transform, Mesh> query; /// QueryResult result = query.get(); /// auto [transform, mesh] = result; /// ``` template <class... Cs> struct QueryResultTuple : public QueryResultTuple_Impl<0, Cs...> {}; // ---------------------------------------------------------- Structured Bindings /// Bindings to allow use structured bidnings. /// These are necessary to tell the compiler how to decompose the custom class. namespace std { template <class... Cs> struct tuple_size<QueryResultTuple<Cs...>> : std::integral_constant<int, QueryResultTuple<Cs...>::SIZE> {}; template <size_t S, class... Cs> struct tuple_element<S, QueryResultTuple<Cs...>> { using type = typename fetch_element<S, 0, Cs...>::type; }; } // namespace std // ----------------------------------------------------------------- Tuple Setter /// Set the data inside the tuple at give index `S`. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, C, Cs...> &tuple) noexcept { tuple.value = p_val; } /// Set the batched data inside the tuple at give index `S`. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Batch<C>, Cs...> &tuple) noexcept { tuple.value = p_val; } /// Set the joined data inside the tuple at give index `S`. template <std::size_t S, class T, class... C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Join<C...>, Cs...> &tuple) noexcept { tuple.value = p_val; } /** * NOTE: I tried to use this: * ``` * template <std::size_t S, class T, class... C, class... Cs, template <class> class Filter> * constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Filter<C>, Cs...> &tuple) noexcept {} * ``` * but it doesn't recursivelly calls itself when there are more than 1 nested * level. So I've separated these. */ /// Remove the filter `Changed` and set the value. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Changed<C>, Cs...> &tuple) noexcept { // Forward to subfilters. set_impl<S>(p_val, static_cast<QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Ignore the filter `Not` and set the value. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Not<C>, Cs...> &tuple) noexcept { // Forward to subfilters. set_impl<S>(p_val, static_cast<QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Ignore the filter `Create` and set the value. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Create<C>, Cs...> &tuple) noexcept { set_impl<S>(p_val, static_cast<QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Ignore the filter `Maybe` and set the value. template <std::size_t S, class T, class C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Maybe<C>, Cs...> &tuple) noexcept { // Forward to subfilters. set_impl<S>(p_val, static_cast<QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Ignore the filter `Any` and set the value. template <std::size_t S, class T, class... C, class... Cs> constexpr void set_impl(T p_val, QueryResultTuple_Impl<S, Any<C...>, Cs...> &tuple) noexcept { // Forward to subfilters. set_impl<S>(p_val, static_cast<QueryResultTuple_Impl<S, C..., Cs...> &>(tuple)); } /// Can be used to set the data inside a tuple. template <std::size_t S, class T, class... Cs> constexpr void set(QueryResultTuple<Cs...> &tuple, T p_val) noexcept { set_impl<S>(p_val, tuple); } // ----------------------------------------------------------------- Tuple Getter /// Fetches the data from the the tuple, because `Search` is equal to the element `Index`. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, C, Cs...> &tuple) noexcept { return tuple.value; } /// Fetches the batched data from the tuple. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Batch<C>, Cs...> &tuple) noexcept { return tuple.value; } /// Fetches the joined data from the tuple. template <std::size_t S, class... C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Join<C...>, Cs...> &tuple) noexcept { return tuple.value; } /// Fetches the Created data from the tuple. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Create<C>, Cs...> &tuple) noexcept { return tuple.value; } /** * NOTE: I tried to use this: * ``` * template <std::size_t S, class... C, class... Cs, template <class...> class Filter> * constexpr auto get_impl(const QueryResultTuple_Impl<S, Filter<C...>, Cs...> &tuple) noexcept { * ``` * but it doesn't recursivelly calls itself when there are more than 1 nested * level. So I've separated these. */ /// Skip the filter `Changed`. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Changed<C>, Cs...> &tuple) noexcept { // Forward to subfilters. return get_impl<S>(static_cast<const QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Skip the filter `Not`. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Not<C>, Cs...> &tuple) noexcept { // Forward to subfilters. return get_impl<S>(static_cast<const QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Skip the filter `Maybe`. template <std::size_t S, class C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Maybe<C>, Cs...> &tuple) noexcept { // Forward to subfilters. return get_impl<S>(static_cast<const QueryResultTuple_Impl<S, C, Cs...> &>(tuple)); } /// Skip the filter `Any`. template <std::size_t S, class... C, class... Cs> constexpr auto get_impl(const QueryResultTuple_Impl<S, Any<C...>, Cs...> &tuple) noexcept { // Forward to subfilters. return get_impl<S>(static_cast<const QueryResultTuple_Impl<S, C..., Cs...> &>(tuple)); } /// Can be used to fetch the data from a tuple. template <std::size_t S, class... Cs> constexpr fetch_element_type<S, 0, Cs...> get(const QueryResultTuple<Cs...> &tuple) noexcept { return get_impl<S>(tuple); } // --------------------------------------------------------------- Query Storages /// `QueryStorage` specialization with 0 template arguments. template <std::size_t I, class... Cs> struct QueryStorage { QueryStorage(World *p_world) {} void set_world_notification_active(bool p_active) {} void initiate_process(World *p_world) {} void conclude_process(World *p_world) {} constexpr static bool is_filter_derminant() { // False by default. return false; } EntitiesBuffer get_entities() const { // This is a NON determinant filter, so just return UINT32_MAX. return { UINT32_MAX, nullptr }; } bool filter_satisfied(EntityID p_entity) const { return true; } bool can_fetch(EntityID p_entity) const { return false; } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // Nothing to fetch. } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) {} }; // -------------------------------------------------------------------- EntityID /// Fetch the `EntityID`. template <std::size_t I, class... Cs> struct QueryStorage<I, EntityID, Cs...> : public QueryStorage<I + 1, Cs...> { QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); } EntitiesBuffer get_entities() const { return QueryStorage<I + 1, Cs...>::get_entities(); } bool filter_satisfied(EntityID p_entity) const { return QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return true; } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // Set the `EntityID` at position `I`. set<I>(r_result, p_id); // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // ---------------------------------------------------------------------- Create /// `QueryStorage` `Create` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, Create<C>, Cs...> : public QueryStorage<I + 1, Cs...> { Storage<C> *storage = nullptr; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world) { // Make sure this storage exist. p_world->create_storage<C>(); } void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); storage = p_world->get_storage<C>(); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); storage = nullptr; } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); } EntitiesBuffer get_entities() const { // This is a NON determinant filter, so just return the other filter. return QueryStorage<I + 1, Cs...>::get_entities(); } bool filter_satisfied(EntityID p_entity) const { // The `Create` filter never stops the execution. return QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { // The `Create` filter allows always to fetch. return true; } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { if (!storage->has(p_id)) { storage->insert(p_id, C()); } set<I>(r_result, storage->get(p_id, p_mode)); // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return storage; } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { // Always add as mutable, since the `Crate` filter always require mutability. r_info.mutable_components.insert(C::get_component_id()); // This filter, also use the storage, signal it too. r_info.mutable_components_storage.insert(C::get_component_id()); QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // ----------------------------------------------------------------------- Maybe /// `QueryStorage` `Maybe` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, Maybe<C>, Cs...> : public QueryStorage<I + 1, Cs...> { QueryStorage<I, C> query_storage; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world), query_storage(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); query_storage.initiate_process(p_world); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); query_storage.conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); query_storage.set_world_notification_active(p_active); } EntitiesBuffer get_entities() const { // This is a NON determinant filter, so just return the other filter. return QueryStorage<I + 1, Cs...>::get_entities(); } bool filter_satisfied(EntityID p_entity) const { // The `Maybe` filter never stops the execution. return QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return query_storage.can_fetch(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { if (query_storage.filter_satisfied(p_id)) { // Ask the sub storage to fetch the data. query_storage.fetch(p_id, p_mode, r_result); } // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return query_storage.get_inner_storage(); } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { QueryStorage<0, C>::get_components(r_info, p_force_immutable); QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // -------------------------------------------------------------------------- Not /// `QueryStorage` `Not` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, Not<C>, Cs...> : public QueryStorage<I + 1, Cs...> { QueryStorage<I, C> query_storage; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world), query_storage(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); query_storage.initiate_process(p_world); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); query_storage.conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); query_storage.set_world_notification_active(p_active); } EntitiesBuffer get_entities() const { // This is a NON determinant filter, so just return the other filter. return QueryStorage<I + 1, Cs...>::get_entities(); } bool filter_satisfied(EntityID p_entity) const { // The `Not` filter is satisfied if the sub filter is not satisfied: // it's a lot similar to an `!true == false`. return query_storage.filter_satisfied(p_entity) == false && QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return query_storage.can_fetch(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // If there is something to fetch, fetch it. if (query_storage.can_fetch(p_id)) { query_storage.fetch(p_id, p_mode, r_result); } // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return query_storage.get_inner_storage(); } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { // The `Not` collects the data always immutable, so force take it // immutably. QueryStorage<I, C>::get_components(r_info, true); QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // --------------------------------------------------------------------- Changed /// `QueryStorage` `Changed` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, Changed<C>, Cs...> : public QueryStorage<I + 1, Cs...> { World *world = nullptr; EntityList changed; Storage<C> *storage = nullptr; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world), world(p_world) { Storage<C> *s = p_world->get_storage<C>(); if (s) { s->add_change_listener(&changed); } } ~QueryStorage() { Storage<C> *s = world->get_storage<C>(); if (s) { s->remove_change_listener(&changed); } } void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); storage = p_world->get_storage<C>(); // Make sure this doesn't change at this point. changed.freeze(); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); storage = nullptr; // Unfreeze the list and clear it to listen on the new events. changed.unfreeze(); changed.clear(); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); Storage<C> *s = world->get_storage<C>(); if (s) { if (p_active) { s->add_change_listener(&changed); } else { s->remove_change_listener(&changed); } } } constexpr static bool is_filter_derminant() { // The `Changed` is a determinant filter. return true; } EntitiesBuffer get_entities() const { // This is a determinant filter, that iterates over the changed // components of this storage. const EntitiesBuffer o_entities = QueryStorage<I + 1, Cs...>::get_entities(); if (unlikely(storage == nullptr)) { return o_entities; } const EntitiesBuffer entities(changed.size(), changed.get_entities_ptr()); return entities.count < o_entities.count ? entities : o_entities; } bool filter_satisfied(EntityID p_entity) const { if (unlikely(storage == nullptr)) { // This is a required field, since there is no storage this can end // immediately. return false; } return changed.has(p_entity) && QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return storage && storage->has(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { #ifdef DEBUG_ENABLED // This can't happen because `is_done` returns true. CRASH_COND_MSG(storage == nullptr, "The storage" + String(typeid(Storage<C>).name()) + " is null."); #endif if constexpr (std::is_const<C>::value) { set<I>(r_result, const_cast<const Storage<C> *>(storage)->get(p_id, p_mode)); } else { set<I>(r_result, storage->get(p_id, p_mode)); } // Keep going QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return storage; } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { if (std::is_const<C>::value || p_force_immutable) { r_info.immutable_components.insert(C::get_component_id()); } else { r_info.mutable_components.insert(C::get_component_id()); } QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // ----------------------------------------------------------------------- Batch /// `QueryStorage` `Batch` filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, Batch<C>, Cs...> : public QueryStorage<I + 1, Cs...> { // Here I'm using `0` (instead of `I`) because the data is fetched locally // and then parsed by this storage. QueryStorage<0, C> query_storage; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world), query_storage(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); query_storage.initiate_process(p_world); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); query_storage.conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); query_storage.set_world_notification_active(p_active); } EntitiesBuffer get_entities() const { return query_storage.get_entities(); } bool filter_satisfied(EntityID p_entity) const { return query_storage.filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return query_storage.can_fetch(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // Fetch the batched data. QueryResultTuple<C> tuple; query_storage.fetch(p_id, p_mode, tuple); fetch_element_type<0, 0, C> data = get<0>(tuple); if (query_storage.get_inner_storage() != nullptr && data != nullptr) { set<I>(r_result, Batch<fetch_element_type<0, 0, C>>( data, query_storage.get_inner_storage()->get_batch_size(p_id))); } // Keep going QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return query_storage.get_inner_storage(); } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { QueryStorage<I + 1, C>::get_components(r_info, p_force_immutable); QueryStorage<I + 1, Cs...>::get_components(r_info); } }; // ----------------------------------------------------- Any-Join Storage Utility /// *** Any-Join Storage Utility *** /// /// This class is used by the filters `Any` and `Join`. /// We need this because those two filters allow to have multiple components: /// `Query<Any<TagA, TagB>>` and `Query<Join<TagA, TagB>>` /// this class deal with the sub components. /// /// @tparam `I`: Stands for `INDEX`, and it's always set to the /// given filter `I` by the `Any` filter or 0 by `Join`. /// /// @tparam `INCREMENT`: This paramenter is used to control if we want to /// index (or not) the sub storages. /// - The filter `Any` set it to 1, so the sub storages /// can directly set the data inside the tuple. /// - The filter `Join` instead, before to insert the /// data inside the tuple, has to manipulate it, /// so it's more convienient keep the storage index /// to 0. /// template <std::size_t I, std::size_t INCREMENT, class... Cs> struct AJUtility { /// Used by the `Any` filter, to know how many components there are. static constexpr std::size_t LAST_INDEX = I; AJUtility(World *p_world) {} void initiate_process(World *p_world) {} void conclude_process(World *p_world) {} void set_world_notification_active(bool p_active) {} /// At this point, it's sure all filters are determinant. constexpr static bool all_determinant() { return true; } /// At this point, it's sure no determinant filters. constexpr static bool any_determinant() { return false; } void get_entities(EntityList &r_entities) const {} bool filter_satisfied(EntityID p_entity) const { // Not satisfied. return false; } bool can_fetch(EntityID p_entity) const { // Not satisfied. return false; } template <class... Qs> void any_fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const {} JoinData join_fetch(EntityID p_id, Space p_mode) const { return JoinData(nullptr, godex::COMPONENT_NONE, true); } }; template <std::size_t I, std::size_t INCREMENT, class C, class... Cs> struct AJUtility<I, INCREMENT, C, Cs...> : AJUtility<I + INCREMENT, INCREMENT, Cs...> { QueryStorage<I, C> storage; AJUtility(World *p_world) : AJUtility<I + INCREMENT, INCREMENT, Cs...>(p_world), storage(p_world) {} void initiate_process(World *p_world) { AJUtility<I + INCREMENT, INCREMENT, Cs...>::initiate_process(p_world); storage.initiate_process(p_world); } void conclude_process(World *p_world) { AJUtility<I + INCREMENT, INCREMENT, Cs...>::conclude_process(p_world); storage.conclude_process(p_world); } void set_world_notification_active(bool p_active) { AJUtility<I + INCREMENT, INCREMENT, Cs...>::set_world_notification_active(p_active); storage.set_world_notification_active(p_active); } /// Return `true` when all subfilters are terminant. constexpr static bool all_determinant() { if constexpr (QueryStorage<I, C>::is_filter_derminant()) { return AJUtility<I + INCREMENT, INCREMENT, Cs...>::all_determinant(); } else { return false; } } /// Return `true` if at least one is determinant. constexpr static bool any_determinant() { if constexpr (QueryStorage<I, C>::is_filter_derminant()) { return true; } else { // Keep search return AJUtility<I + INCREMENT, INCREMENT, Cs...>::any_determinant(); } } void get_entities(EntityList &r_entities) const { if (storage.get_entities().count != UINT32_MAX) { // This is a determinant fitler, take the `Entities`. for (uint32_t i = 0; i < storage.get_entities().count; i += 1) { r_entities.insert(storage.get_entities().entities[i]); } } AJUtility<I + INCREMENT, INCREMENT, Cs...>::get_entities(r_entities); } bool filter_satisfied(EntityID p_entity) const { // Is someone able to satisfy the filter? if (storage.filter_satisfied(p_entity)) { // Satisfied. return true; } else { // Not in storage, try the next one. return AJUtility<I + INCREMENT, INCREMENT, Cs...>::filter_satisfied(p_entity); } } bool can_fetch(EntityID p_entity) const { // Is someone able to fetch? if (storage.can_fetch(p_entity)) { // Satisfied. return true; } else { // Not in storage, try the next one. return AJUtility<I + INCREMENT, INCREMENT, Cs...>::can_fetch(p_entity); } } /// Used by `Any` to fetch the data. /// Fetches all the components if there is something to fetch. template <class... Qs> void any_fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { if (storage.can_fetch(p_id)) { // There is something to fetch, fetch it. storage.fetch(p_id, p_mode, r_result); } AJUtility<I + INCREMENT, INCREMENT, Cs...>::any_fetch(p_id, p_mode, r_result); } /// Used by `Join` to fetch the data. /// Fetches just the first one that exist. JoinData join_fetch(EntityID p_id, Space p_mode) const { if (storage.can_fetch(p_id)) { // There is something to fetch, fetch it. QueryResultTuple<C> tuple; storage.fetch(p_id, p_mode, tuple); return JoinData( (void *)get<0>(tuple), std::remove_pointer_t<fetch_element_type<0, 0, C>>::get_component_id(), std::is_const_v<std::remove_pointer_t<fetch_element_type<0, 0, C>>>); } else { return AJUtility<0, 0, Cs...>::join_fetch(p_id, p_mode); } } }; // -------------------------------------------------------------------------- Any /// `QueryStorage` `Any` filter specialization. /// /// Returns all the components if at least one satisfy the sub filter. /// /// Notice: You can't specify `Any` as sub component: `Query<Any<Any<Transform>>>` /// though, you can specify `Join`: `Query<Any<Join<TagA, TagB>>>` template <std::size_t I, class... C, class... Cs> struct QueryStorage<I, Any<C...>, Cs...> : QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...> { AJUtility<I, 1, C...> sub_storages; EntityList entities; QueryStorage(World *p_world) : QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...>(p_world), sub_storages(p_world) {} void initiate_process(World *p_world) { QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...>::initiate_process(p_world); sub_storages.initiate_process(p_world); entities.clear(); // TODO Can we cache this somehow? // track of the biggest `EntityID` it has. // So the `entities` list we have here could be prepared, and a lot of // reallocation can be avoided. sub_storages.get_entities(entities); } void conclude_process(World *p_world) { QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...>::conclude_process(p_world); sub_storages.conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...>::set_world_notification_active(p_active); sub_storages.set_world_notification_active(p_active); } constexpr static bool is_filter_derminant() { // The `Any` storage is a determinant filter if at least one subfilter is. return AJUtility<I, 1, C...>::any_determinant(); } EntitiesBuffer get_entities() const { if constexpr (is_filter_derminant()) { return EntitiesBuffer(entities.size(), entities.get_entities_ptr()); } else { return EntitiesBuffer(UINT32_MAX, nullptr); } } bool filter_satisfied(EntityID p_entity) const { // Just check if we have this entity. if constexpr (AJUtility<I, 1, C...>::all_determinant()) { // Since all the filters are determinant, we can just check this: return entities.has(p_entity); } else { // Not all filters are determinant, so we need to check one by one, // because even a not determinant filter may satisfy the process. return sub_storages.filter_satisfied(p_entity); } } bool can_fetch(EntityID p_entity) const { return sub_storages.can_fetch(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // Fetch the data from the sub storages. sub_storages.any_fetch(p_id, p_mode, r_result); // Keep going. QueryStorage<AJUtility<I, 1, C...>::LAST_INDEX, Cs...>::fetch(p_id, p_mode, r_result); } // TODO how? here we have multiple storages. //auto get_inner_storage() const { // return query_storage.get_inner_storage(); //} static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { // Take the components storages used, taking advantage of the // get_components function. QueryStorage<0, C...>::get_components(r_info, p_force_immutable); QueryStorage<0, Cs...>::get_components(r_info); } }; // ------------------------------------------------------------------------- Join /// `QueryStorage` `Join`. /// /// Returns the first component that satisfy the sub filters. /// /// Notice: You can't specify `Any` as sub filter: `Query<Join<Any<Transform>>>` template <std::size_t I, class... C, class... Cs> struct QueryStorage<I, Join<C...>, Cs...> : QueryStorage<I + 1, Cs...> { AJUtility<0, 0, C...> sub_storages; EntityList entities; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world), sub_storages(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); sub_storages.initiate_process(p_world); entities.clear(); // TODO Exist a way to cache this? // track of the biggest `EntityID` it has. // So the `entities` list we have here could be prepared, and a lot of // reallocation can be avoided. sub_storages.get_entities(entities); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); sub_storages.conclude_process(p_world); } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); sub_storages.set_world_notification_active(p_active); } constexpr static bool is_filter_derminant() { // The `Join` storage is a determinant filter if at least one subfilter is. return AJUtility<0, 0, C...>::any_determinant(); } EntitiesBuffer get_entities() const { if constexpr (is_filter_derminant()) { return EntitiesBuffer(entities.size(), entities.get_entities_ptr()); } else { return EntitiesBuffer(UINT32_MAX, nullptr); } } bool filter_satisfied(EntityID p_entity) const { // Just check if we have this entity. if constexpr (AJUtility<0, 0, C...>::all_determinant()) { // Since all the filters are determinant, we can just check this: return entities.has(p_entity); } else { // Not all filters are determinant, so we need to check one by one, // because even a not determinant filter may satisfy the process. return sub_storages.filter_satisfied(p_entity); } } bool can_fetch(EntityID p_entity) const { return sub_storages.can_fetch(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { // Fetch the data from the sub storages. set<I>(r_result, sub_storages.join_fetch(p_id, p_mode)); // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } // TODO how? here we have multiple storages. //auto get_inner_storage() const { // return query_storage.get_inner_storage(); //} static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { // Take the components storages used, taking advantage of the // get_components function. QueryStorage<0, C...>::get_components(r_info, p_force_immutable); QueryStorage<0, Cs...>::get_components(r_info); } }; // -------------------------------------------------------------------- No filter /// `QueryStorage` no filter specialization. template <std::size_t I, class C, class... Cs> struct QueryStorage<I, C, Cs...> : QueryStorage<I + 1, Cs...> { Storage<C> *storage = nullptr; QueryStorage(World *p_world) : QueryStorage<I + 1, Cs...>(p_world) {} void initiate_process(World *p_world) { QueryStorage<I + 1, Cs...>::initiate_process(p_world); storage = p_world->get_storage<C>(); } void conclude_process(World *p_world) { QueryStorage<I + 1, Cs...>::conclude_process(p_world); storage = nullptr; } void set_world_notification_active(bool p_active) { QueryStorage<I + 1, Cs...>::set_world_notification_active(p_active); } constexpr static bool is_filter_derminant() { // The `With` is a determinant filter. return true; } EntitiesBuffer get_entities() const { // This is a determinant filter, that iterates over the existing // components of this storage. const EntitiesBuffer o_entities = QueryStorage<I + 1, Cs...>::get_entities(); if (unlikely(storage == nullptr)) { return o_entities; } const EntitiesBuffer entities = storage->get_stored_entities(); return entities.count < o_entities.count ? entities : o_entities; } bool filter_satisfied(EntityID p_entity) const { if (unlikely(storage == nullptr)) { // This is a required field, since there is no storage this can end // immediately. return false; } return storage->has(p_entity) && QueryStorage<I + 1, Cs...>::filter_satisfied(p_entity); } bool can_fetch(EntityID p_entity) const { return storage && storage->has(p_entity); } template <class... Qs> void fetch(EntityID p_id, Space p_mode, QueryResultTuple<Qs...> &r_result) const { #ifdef DEBUG_ENABLED // This can't happen because `is_done` returns true. CRASH_COND_MSG(storage == nullptr, "The storage" + String(typeid(Storage<C>).name()) + " is null."); #endif // Set the `Component` inside th tuple. if constexpr (std::is_const<C>::value) { set<I>(r_result, const_cast<const Storage<C> *>(storage)->get(p_id, p_mode)); } else { set<I>(r_result, storage->get(p_id, p_mode)); } // Keep going. QueryStorage<I + 1, Cs...>::fetch(p_id, p_mode, r_result); } auto get_inner_storage() const { return storage; } static void get_components(SystemExeInfo &r_info, const bool p_force_immutable = false) { if (std::is_const<C>::value || p_force_immutable) { r_info.immutable_components.insert(C::get_component_id()); } else { r_info.mutable_components.insert(C::get_component_id()); } QueryStorage<I + 1, Cs...>::get_components(r_info); } }; /// This is the fastest `Query`. /// Using the variadic template, it's build at compile time. Since the /// components must be known at compile time, this query can't by used by /// scripts that have to rely on the `DynamicQuery`. template <class... Cs> class Query { /// Fetch space. Space m_space = LOCAL; /// List of entities to check. EntitiesBuffer entities = EntitiesBuffer(0, nullptr); // Storages QueryStorage<0, Cs...> q; public: Query(World *p_world) : q(p_world) { } void initiate_process(World *p_world) { m_space = LOCAL; q.initiate_process(p_world); // Prepare the query: // Ask all the pointed storage to return a list of entities to iterate; // the query, takes the smallest one, and iterates over it. entities = q.get_entities(); if (unlikely(entities.count == UINT32_MAX)) { entities.count = 0; ERR_PRINT("This query is not valid, you are using only non determinant fileters (like `Not` and `Maybe`)."); } } void conclude_process(World *p_world) { q.conclude_process(p_world); } void set_world_notification_active(bool p_active) { q.set_world_notification_active(p_active); } struct Iterator { using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = QueryResultTuple<Cs...>; Iterator(Query<Cs...> *p_query, const EntityID *p_entity) : query(p_query), entity(p_entity) {} bool is_valid() const { return *this != query->end(); } value_type fetch() const { return operator*(); } value_type operator*() const { QueryResultTuple<Cs...> result; query->q.fetch(*entity, query->m_space, result); return result; } Iterator &operator++() { entity = query->next_valid_entity(entity); return *this; } Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; } friend bool operator==(const Iterator &a, const Iterator &b) { return a.entity == b.entity; } friend bool operator!=(const Iterator &a, const Iterator &b) { return a.entity != b.entity; } private: Query<Cs...> *query; const EntityID *entity; }; /// Allow to specify the space you want to fetch the data, you can use this /// in conjuction with the iterator and the random access: /// ``` /// // Iterator example: /// for (auto [tr] : query.space(GLOBAL)) { /// // ... /// } /// /// // Random access /// if (query.has(1)) { /// auto [tr] = query.space(GLOBAL)[1]; /// } /// ``` Query<Cs...> &space(Space p_space) { m_space = p_space; return *this; } /// Returns the forward `Iterator`, you can use in this way: /// ``` /// for (auto [tr] : query) { /// // ... /// } /// ``` Iterator begin() { // Returns the next available Entity. if (entities.count > 0) { if (q.filter_satisfied(*entities.entities) == false) { return Iterator(this, next_valid_entity(entities.entities)); } } return Iterator(this, entities.entities); } /// Used to know the last element of the `Iterator`. Iterator end() { return Iterator(this, entities.entities + entities.count); } /// Returns true if this `Entity` exists and can be fetched. /// ``` /// if(query.has(1)) { /// auto [component1, component2] = query[1]; /// } /// ``` bool has(EntityID p_entity) const { return q.filter_satisfied(p_entity); } /// Fetch the specific `Entity` component. /// If the `Entity` doesn't meet the query requirements, this function /// crashes, so it's necessary to use the function `has` to check if the /// entity can be fetched. /// ``` /// if(query.has(1)) { /// auto [component1, component2] = query[1]; /// } /// ``` QueryResultTuple<Cs...> operator[](EntityID p_entity) { QueryResultTuple<Cs...> result; q.fetch(p_entity, m_space, result); return result; } /// Counts the Entities that meets the requirements of this `Query`. /// IMPORTANT: Don't use this function to create C like loop: instead rely /// on the iterator. uint32_t count() { uint32_t count = 0; for (Iterator it = begin(); it != end(); ++it) { count += 1; } return count; } static void get_components(SystemExeInfo &r_info) { QueryStorage<0, Cs...>::get_components(r_info); } private: const EntityID *next_valid_entity(const EntityID *p_current) { const EntityID *next = p_current + 1; // Search the next valid entity. for (; next != (entities.entities + entities.count); next += 1) { if (q.filter_satisfied(*next)) { // This is fine to return. return next; } } // Nothing more to iterate. return next; } };
32.083817
134
0.66804
[ "mesh", "transform" ]
aa68d9422f8e8f6f640a483033e69b21c5a07c05
10,034
h
C
tcmalloc/tcmalloc_policy.h
cpp-pm/tcmalloc
1e9265bbfda7240d121337444790dd507743cbf9
[ "Apache-2.0" ]
null
null
null
tcmalloc/tcmalloc_policy.h
cpp-pm/tcmalloc
1e9265bbfda7240d121337444790dd507743cbf9
[ "Apache-2.0" ]
null
null
null
tcmalloc/tcmalloc_policy.h
cpp-pm/tcmalloc
1e9265bbfda7240d121337444790dd507743cbf9
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The TCMalloc Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file defines policies used when allocation memory. // // An allocation policy encapsulates four policies: // // - Out of memory policy. // Dictates how to handle OOM conditions. // // struct OomPolicyTemplate { // // Invoked when we failed to allocate memory // // Must either terminate, throw, or return nullptr // static void* handle_oom(size_t size); // }; // // - Alignment policy // Dictates alignment to use for an allocation. // Must be trivially copyable. // // struct AlignPolicyTemplate { // // Returns the alignment to use for the memory allocation, // // or 1 to use small allocation table alignments (8 bytes) // // Returned value Must be a non-zero power of 2. // size_t align() const; // }; // // - Hook invocation policy // dictates invocation of allocation hooks // // struct HooksPolicyTemplate { // // Returns true if allocation hooks must be invoked. // static bool invoke_hooks(); // }; // // - NUMA partition policy // When NUMA awareness is enabled this dictates which NUMA partition we will // allocate memory from. Must be trivially copyable. // // struct NumaPartitionPolicyTemplate { // // Returns the NUMA partition to allocate from. // size_t partition() const; // // // Returns the NUMA partition to allocate from multiplied by // // kNumBaseClasses - i.e. the first size class that corresponds to the // // NUMA partition to allocate from. // size_t scaled_partition() const; // }; #ifndef TCMALLOC_TCMALLOC_POLICY_H_ #define TCMALLOC_TCMALLOC_POLICY_H_ #include <errno.h> #include <stddef.h> #include <stdint.h> #include <cstddef> #include "tcmalloc/common.h" #include "tcmalloc/internal/logging.h" #include "tcmalloc/internal/numa.h" #include "tcmalloc/internal/percpu.h" #include "tcmalloc/new_extension.h" #include "tcmalloc/static_vars.h" GOOGLE_MALLOC_SECTION_BEGIN namespace tcmalloc { namespace tcmalloc_internal { // NullOomPolicy: returns nullptr struct NullOomPolicy { static inline constexpr void* handle_oom(size_t size) { return nullptr; } static constexpr bool can_return_nullptr() { return true; } }; // MallocOomPolicy: sets errno to ENOMEM and returns nullptr struct MallocOomPolicy { static inline void* handle_oom(size_t size) { errno = ENOMEM; return nullptr; } static constexpr bool can_return_nullptr() { return true; } }; // CppOomPolicy: terminates the program struct CppOomPolicy { static ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NORETURN void* handle_oom( size_t size) { Crash(kCrashWithStats, __FILE__, __LINE__, "Unable to allocate (new failed)", size); __builtin_unreachable(); } static constexpr bool can_return_nullptr() { return false; } }; // DefaultAlignPolicy: use default small size table based allocation struct DefaultAlignPolicy { // Important: the value here is explicitly '1' to indicate that the used // alignment is the default alignment of the size tables in tcmalloc. // The constexpr value of 1 will optimize out the alignment checks and // iterations in the GetSizeClass() calls for default aligned allocations. static constexpr size_t align() { return 1; } }; // MallocAlignPolicy: use std::max_align_t allocation struct MallocAlignPolicy { static constexpr size_t align() { return alignof(std::max_align_t); } }; // AlignAsPolicy: use user provided alignment class AlignAsPolicy { public: AlignAsPolicy() = delete; explicit constexpr AlignAsPolicy(size_t value) : value_(value) {} explicit constexpr AlignAsPolicy(std::align_val_t value) : AlignAsPolicy(static_cast<size_t>(value)) {} size_t constexpr align() const { return value_; } private: size_t value_; }; struct AllocationAccessHotPolicy { // Important: the value here is explicitly kHot to allow the value to be // constant propagated. This allows allocations without a hot/cold hint to // use the normal fast path. static constexpr AllocationAccess access() { return AllocationAccess::kHot; } }; struct AllocationAccessColdPolicy { static constexpr AllocationAccess access() { return AllocationAccess::kCold; } }; using DefaultAllocationAccessPolicy = AllocationAccessHotPolicy; // InvokeHooksPolicy: invoke memory allocation hooks struct InvokeHooksPolicy { static constexpr bool invoke_hooks() { return true; } }; // NoHooksPolicy: do not invoke memory allocation hooks struct NoHooksPolicy { static constexpr bool invoke_hooks() { return false; } }; // Use a fixed NUMA partition. class FixedNumaPartitionPolicy { public: explicit constexpr FixedNumaPartitionPolicy(size_t partition) : partition_(partition) {} size_t constexpr partition() const { return partition_; } size_t constexpr scaled_partition() const { return partition_ * kNumBaseClasses; } private: size_t partition_; }; // Use the NUMA partition which the executing CPU is local to. struct LocalNumaPartitionPolicy { // Note that the partition returned may change between calls if the executing // thread migrates between NUMA nodes & partitions. Users of this function // should not rely upon multiple invocations returning the same partition. size_t partition() const { return Static::numa_topology().GetCurrentPartition(); } size_t scaled_partition() const { return Static::numa_topology().GetCurrentScaledPartition(); } }; // TCMallocPolicy defines the compound policy object containing // the OOM, alignment and hooks policies. // Is trivially constructible, copyable and destructible. template <typename OomPolicy = CppOomPolicy, typename AlignPolicy = DefaultAlignPolicy, typename AccessPolicy = DefaultAllocationAccessPolicy, typename HooksPolicy = InvokeHooksPolicy, typename NumaPolicy = LocalNumaPartitionPolicy> class TCMallocPolicy { public: constexpr TCMallocPolicy() = default; explicit constexpr TCMallocPolicy(AlignPolicy align, NumaPolicy numa) : align_(align), numa_(numa) {} // OOM policy static void* handle_oom(size_t size) { return OomPolicy::handle_oom(size); } // Alignment policy constexpr size_t align() const { return align_.align(); } // NUMA partition constexpr size_t numa_partition() const { return numa_.partition(); } // NUMA partition multiplied by kNumBaseClasses constexpr size_t scaled_numa_partition() const { return numa_.scaled_partition(); } constexpr AllocationAccess access() const { return AccessPolicy::access(); } // Hooks policy static constexpr bool invoke_hooks() { return HooksPolicy::invoke_hooks(); } // Returns this policy aligned as 'align' template <typename align_t> constexpr TCMallocPolicy<OomPolicy, AlignAsPolicy, AccessPolicy, HooksPolicy, NumaPolicy> AlignAs(align_t align) const { return TCMallocPolicy<OomPolicy, AlignAsPolicy, AccessPolicy, HooksPolicy, NumaPolicy>(AlignAsPolicy{align}, numa_); } // Returns this policy for frequent access constexpr TCMallocPolicy<OomPolicy, AlignPolicy, AllocationAccessHotPolicy, HooksPolicy, NumaPolicy> AccessAsHot() const { return TCMallocPolicy<OomPolicy, AlignPolicy, AllocationAccessHotPolicy, HooksPolicy, NumaPolicy>(align_, numa_); } // Returns this policy for infrequent access constexpr TCMallocPolicy<OomPolicy, AlignPolicy, AllocationAccessColdPolicy, HooksPolicy, NumaPolicy> AccessAsCold() const { return TCMallocPolicy<OomPolicy, AlignPolicy, AllocationAccessColdPolicy, HooksPolicy, NumaPolicy>(align_, numa_); } // Returns this policy with a nullptr OOM policy. constexpr TCMallocPolicy<NullOomPolicy, AlignPolicy, AccessPolicy, HooksPolicy, NumaPolicy> Nothrow() const { return TCMallocPolicy<NullOomPolicy, AlignPolicy, AccessPolicy, HooksPolicy, NumaPolicy>(align_, numa_); } // Returns this policy with NewAllocHook invocations disabled. constexpr TCMallocPolicy<OomPolicy, AlignPolicy, AccessPolicy, NoHooksPolicy, NumaPolicy> WithoutHooks() const { return TCMallocPolicy<OomPolicy, AlignPolicy, AccessPolicy, NoHooksPolicy, NumaPolicy>(align_, numa_); } // Returns this policy with a fixed NUMA partition. constexpr TCMallocPolicy<OomPolicy, AlignPolicy, AccessPolicy, NoHooksPolicy, FixedNumaPartitionPolicy> InNumaPartition(size_t partition) const { return TCMallocPolicy<OomPolicy, AlignPolicy, AccessPolicy, NoHooksPolicy, FixedNumaPartitionPolicy>( align_, FixedNumaPartitionPolicy{partition}); } // Returns this policy with a fixed NUMA partition matching that of the // previously allocated `ptr`. constexpr auto InSameNumaPartitionAs(void* ptr) const { return InNumaPartition(NumaPartitionFromPointer(ptr)); } static constexpr bool can_return_nullptr() { return OomPolicy::can_return_nullptr(); } private: AlignPolicy align_; NumaPolicy numa_; }; using CppPolicy = TCMallocPolicy<CppOomPolicy, DefaultAlignPolicy>; using MallocPolicy = TCMallocPolicy<MallocOomPolicy, MallocAlignPolicy>; } // namespace tcmalloc_internal } // namespace tcmalloc GOOGLE_MALLOC_SECTION_END #endif // TCMALLOC_TCMALLOC_POLICY_H_
33.898649
80
0.726729
[ "object" ]
aa6d8100c0a0bc9d07aab7f234f242359cbd7e63
273
h
C
src/CubeModel.h
Pfizerr/eduRend
9209479c5c6f23c18cb352592a753e6500c20a07
[ "MIT" ]
null
null
null
src/CubeModel.h
Pfizerr/eduRend
9209479c5c6f23c18cb352592a753e6500c20a07
[ "MIT" ]
null
null
null
src/CubeModel.h
Pfizerr/eduRend
9209479c5c6f23c18cb352592a753e6500c20a07
[ "MIT" ]
null
null
null
#ifndef CUBEMODEL_H #include "Model.h" class CubeModel : public Model { unsigned nbr_indices = 0; public: CubeModel( ID3D11Device* dx3ddevice, ID3D11DeviceContext* dx3ddevice_context); virtual void Render() const; ~CubeModel() { } }; #endif // !CUBEMODEL_H
13
43
0.717949
[ "render", "model" ]
aa7158de6b69aaa185e472deb0a04a356cd87783
63,746
h
C
include/Platform/Universal Windows/UWP/WindowsMediaCore.h
zpf1452233/WinObjC
015afb819551ba6116f9deb294bcc3c02643275a
[ "MIT" ]
1
2021-02-23T00:39:32.000Z
2021-02-23T00:39:32.000Z
include/Platform/Universal Windows/UWP/WindowsMediaCore.h
zpf1452233/WinObjC
015afb819551ba6116f9deb294bcc3c02643275a
[ "MIT" ]
null
null
null
include/Platform/Universal Windows/UWP/WindowsMediaCore.h
zpf1452233/WinObjC
015afb819551ba6116f9deb294bcc3c02643275a
[ "MIT" ]
null
null
null
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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. // //****************************************************************************** // WindowsMediaCore.h // Generated from winmd2objc #pragma once #ifndef OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT #define OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT __declspec(dllimport) #ifndef IN_WinObjC_Frameworks_UWP_BUILD #pragma comment(lib, "ObjCUWPWindowsMediaCaptureDevicesCorePlaybackProtection.lib") #endif #endif #include <UWP/interopBase.h> @class WMCAudioStreamDescriptor, WMCVideoStreamDescriptor, WMCMediaStreamSource, WMCMediaStreamSourceClosedEventArgs, WMCMediaStreamSourceStartingEventArgs, WMCMediaStreamSourceSampleRequestedEventArgs, WMCMediaStreamSourceSwitchStreamsRequestedEventArgs, WMCMediaStreamSourceSampleRenderedEventArgs, WMCMediaStreamSamplePropertySet, WMCMediaStreamSample, WMCMediaStreamSampleProtectionProperties, WMCMediaStreamSourceClosedRequest, WMCMediaStreamSourceStartingRequestDeferral, WMCMediaStreamSourceStartingRequest, WMCMediaStreamSourceSampleRequestDeferral, WMCMediaStreamSourceSampleRequest, WMCMediaStreamSourceSwitchStreamsRequestDeferral, WMCMediaStreamSourceSwitchStreamsRequest, WMCMseStreamSource, WMCMseSourceBufferList, WMCMseSourceBuffer, WMCHighDynamicRangeControl, WMCSceneAnalysisEffect, WMCSceneAnalyzedEventArgs, WMCHighDynamicRangeOutput, WMCSceneAnalysisEffectFrame, WMCSceneAnalysisEffectDefinition, WMCFaceDetectionEffectFrame, WMCFaceDetectedEventArgs, WMCFaceDetectionEffect, WMCFaceDetectionEffectDefinition, WMCVideoStabilizationEffectEnabledChangedEventArgs, WMCVideoStabilizationEffect, WMCVideoStabilizationEffectDefinition, WMCMediaSourceError, WMCMediaSource, WMCMediaBinder, WMCMediaBindingEventArgs, WMCMediaSourceOpenOperationCompletedEventArgs, WMCTimedTextSource, WMCTimedMetadataTrack, WMCMediaSourceStateChangedEventArgs, WMCTimedTextRegion, WMCTimedTextStyle, WMCTimedTextLine, WMCTimedTextSubformat, WMCTimedMetadataTrackError, WMCMediaCueEventArgs, WMCTimedMetadataTrackFailedEventArgs, WMCTimedTextSourceResolveResultEventArgs, WMCVideoTrack, WMCVideoTrackOpenFailedEventArgs, WMCVideoTrackSupportInfo, WMCAudioTrack, WMCAudioTrackOpenFailedEventArgs, WMCAudioTrackSupportInfo, WMCTimedTextCue, WMCDataCue; @class WMCMseTimeRange, WMCTimedTextPadding, WMCTimedTextSize, WMCTimedTextDouble, WMCTimedTextPoint; @protocol WMCIMediaSource, WMCIMediaStreamDescriptor, WMCIAudioStreamDescriptor, WMCIAudioStreamDescriptor2, WMCIAudioStreamDescriptorFactory, WMCIVideoStreamDescriptor, WMCIVideoStreamDescriptorFactory, WMCIMediaStreamSource, WMCIMediaStreamSource2, WMCIMediaStreamSourceFactory, WMCIMediaStreamSample, WMCIMediaStreamSampleStatics, WMCIMediaStreamSampleProtectionProperties, WMCIMediaStreamSourceClosedRequest, WMCIMediaStreamSourceClosedEventArgs, WMCIMediaStreamSourceStartingRequestDeferral, WMCIMediaStreamSourceStartingRequest, WMCIMediaStreamSourceStartingEventArgs, WMCIMediaStreamSourceSampleRequestDeferral, WMCIMediaStreamSourceSampleRequest, WMCIMediaStreamSourceSampleRequestedEventArgs, WMCIMediaStreamSourceSwitchStreamsRequestDeferral, WMCIMediaStreamSourceSwitchStreamsRequest, WMCIMediaStreamSourceSwitchStreamsRequestedEventArgs, WMCIMediaStreamSourceSampleRenderedEventArgs, WMCIMseStreamSourceStatics, WMCIMseStreamSource, WMCIMseSourceBuffer, WMCIMseSourceBufferList, WMCIHighDynamicRangeControl, WMCISceneAnalysisEffect, WMCIHighDynamicRangeOutput, WMCISceneAnalysisEffectFrame, WMCISceneAnalyzedEventArgs, WMCIFaceDetectionEffectFrame, WMCIFaceDetectedEventArgs, WMCIFaceDetectionEffect, WMCIFaceDetectionEffectDefinition, WMCIVideoStabilizationEffectEnabledChangedEventArgs, WMCIVideoStabilizationEffect, WMCIMediaSourceError, WMCIMediaSourceOpenOperationCompletedEventArgs, WMCIMediaSourceStateChangedEventArgs, WMCIMediaSourceStatics, WMCIMediaSourceStatics2, WMCIMediaBinder, WMCIMediaBindingEventArgs, WMCIMediaSource2, WMCIMediaSource3, WMCIMediaCue, WMCITimedTextCue, WMCITimedTextRegion, WMCITimedTextStyle, WMCITimedTextSubformat, WMCITimedTextLine, WMCISingleSelectMediaTrackList, WMCIMediaTrack, WMCITimedMetadataTrackError, WMCIMediaCueEventArgs, WMCITimedMetadataTrackFailedEventArgs, WMCIDataCue, WMCITimedMetadataTrackFactory, WMCITimedMetadataTrack, WMCITimedTextSourceResolveResultEventArgs, WMCITimedTextSource, WMCITimedTextSourceStatics, WMCIVideoTrackSupportInfo, WMCIAudioTrackSupportInfo, WMCIVideoTrackOpenFailedEventArgs, WMCIAudioTrackOpenFailedEventArgs, WMCIVideoTrack, WMCIAudioTrack, WMCITimedMetadataTrack2; // Windows.Media.Core.MediaStreamSourceClosedReason enum _WMCMediaStreamSourceClosedReason { WMCMediaStreamSourceClosedReasonDone = 0, WMCMediaStreamSourceClosedReasonUnknownError = 1, WMCMediaStreamSourceClosedReasonAppReportedError = 2, WMCMediaStreamSourceClosedReasonUnsupportedProtectionSystem = 3, WMCMediaStreamSourceClosedReasonProtectionSystemFailure = 4, WMCMediaStreamSourceClosedReasonUnsupportedEncodingFormat = 5, WMCMediaStreamSourceClosedReasonMissingSampleRequestedEventHandler = 6, }; typedef unsigned WMCMediaStreamSourceClosedReason; // Windows.Media.Core.MediaStreamSourceErrorStatus enum _WMCMediaStreamSourceErrorStatus { WMCMediaStreamSourceErrorStatusOther = 0, WMCMediaStreamSourceErrorStatusOutOfMemory = 1, WMCMediaStreamSourceErrorStatusFailedToOpenFile = 2, WMCMediaStreamSourceErrorStatusFailedToConnectToServer = 3, WMCMediaStreamSourceErrorStatusConnectionToServerLost = 4, WMCMediaStreamSourceErrorStatusUnspecifiedNetworkError = 5, WMCMediaStreamSourceErrorStatusDecodeError = 6, WMCMediaStreamSourceErrorStatusUnsupportedMediaFormat = 7, }; typedef unsigned WMCMediaStreamSourceErrorStatus; // Windows.Media.Core.MseReadyState enum _WMCMseReadyState { WMCMseReadyStateClosed = 0, WMCMseReadyStateOpen = 1, WMCMseReadyStateEnded = 2, }; typedef unsigned WMCMseReadyState; // Windows.Media.Core.MseEndOfStreamStatus enum _WMCMseEndOfStreamStatus { WMCMseEndOfStreamStatusSuccess = 0, WMCMseEndOfStreamStatusNetworkError = 1, WMCMseEndOfStreamStatusDecodeError = 2, WMCMseEndOfStreamStatusUnknownError = 3, }; typedef unsigned WMCMseEndOfStreamStatus; // Windows.Media.Core.MseAppendMode enum _WMCMseAppendMode { WMCMseAppendModeSegments = 0, WMCMseAppendModeSequence = 1, }; typedef unsigned WMCMseAppendMode; // Windows.Media.Core.FaceDetectionMode enum _WMCFaceDetectionMode { WMCFaceDetectionModeHighPerformance = 0, WMCFaceDetectionModeBalanced = 1, WMCFaceDetectionModeHighQuality = 2, }; typedef unsigned WMCFaceDetectionMode; // Windows.Media.Core.VideoStabilizationEffectEnabledChangedReason enum _WMCVideoStabilizationEffectEnabledChangedReason { WMCVideoStabilizationEffectEnabledChangedReasonProgrammatic = 0, WMCVideoStabilizationEffectEnabledChangedReasonPixelRateTooHigh = 1, WMCVideoStabilizationEffectEnabledChangedReasonRunningSlowly = 2, }; typedef unsigned WMCVideoStabilizationEffectEnabledChangedReason; // Windows.Media.Core.MediaTrackKind enum _WMCMediaTrackKind { WMCMediaTrackKindAudio = 0, WMCMediaTrackKindVideo = 1, WMCMediaTrackKindTimedMetadata = 2, }; typedef unsigned WMCMediaTrackKind; // Windows.Media.Core.TimedMetadataKind enum _WMCTimedMetadataKind { WMCTimedMetadataKindCaption = 0, WMCTimedMetadataKindChapter = 1, WMCTimedMetadataKindCustom = 2, WMCTimedMetadataKindData = 3, WMCTimedMetadataKindDescription = 4, WMCTimedMetadataKindSubtitle = 5, }; typedef unsigned WMCTimedMetadataKind; // Windows.Media.Core.TimedMetadataTrackErrorCode enum _WMCTimedMetadataTrackErrorCode { WMCTimedMetadataTrackErrorCodeNone = 0, WMCTimedMetadataTrackErrorCodeDataFormatError = 1, WMCTimedMetadataTrackErrorCodeNetworkError = 2, WMCTimedMetadataTrackErrorCodeInternalError = 3, }; typedef unsigned WMCTimedMetadataTrackErrorCode; // Windows.Media.Core.TimedTextScrollMode enum _WMCTimedTextScrollMode { WMCTimedTextScrollModePopon = 0, WMCTimedTextScrollModeRollup = 1, }; typedef unsigned WMCTimedTextScrollMode; // Windows.Media.Core.TimedTextUnit enum _WMCTimedTextUnit { WMCTimedTextUnitPixels = 0, WMCTimedTextUnitPercentage = 1, }; typedef unsigned WMCTimedTextUnit; // Windows.Media.Core.TimedTextWritingMode enum _WMCTimedTextWritingMode { WMCTimedTextWritingModeLeftRightTopBottom = 0, WMCTimedTextWritingModeRightLeftTopBottom = 1, WMCTimedTextWritingModeTopBottomRightLeft = 2, WMCTimedTextWritingModeTopBottomLeftRight = 3, WMCTimedTextWritingModeLeftRight = 4, WMCTimedTextWritingModeRightLeft = 5, WMCTimedTextWritingModeTopBottom = 6, }; typedef unsigned WMCTimedTextWritingMode; // Windows.Media.Core.TimedTextDisplayAlignment enum _WMCTimedTextDisplayAlignment { WMCTimedTextDisplayAlignmentBefore = 0, WMCTimedTextDisplayAlignmentAfter = 1, WMCTimedTextDisplayAlignmentCenter = 2, }; typedef unsigned WMCTimedTextDisplayAlignment; // Windows.Media.Core.TimedTextLineAlignment enum _WMCTimedTextLineAlignment { WMCTimedTextLineAlignmentStart = 0, WMCTimedTextLineAlignmentEnd = 1, WMCTimedTextLineAlignmentCenter = 2, }; typedef unsigned WMCTimedTextLineAlignment; // Windows.Media.Core.TimedTextWrapping enum _WMCTimedTextWrapping { WMCTimedTextWrappingNoWrap = 0, WMCTimedTextWrappingWrap = 1, }; typedef unsigned WMCTimedTextWrapping; // Windows.Media.Core.TimedTextWeight enum _WMCTimedTextWeight { WMCTimedTextWeightNormal = 400, WMCTimedTextWeightBold = 700, }; typedef unsigned WMCTimedTextWeight; // Windows.Media.Core.TimedTextFlowDirection enum _WMCTimedTextFlowDirection { WMCTimedTextFlowDirectionLeftToRight = 0, WMCTimedTextFlowDirectionRightToLeft = 1, }; typedef unsigned WMCTimedTextFlowDirection; // Windows.Media.Core.MediaDecoderStatus enum _WMCMediaDecoderStatus { WMCMediaDecoderStatusFullySupported = 0, WMCMediaDecoderStatusUnsupportedSubtype = 1, WMCMediaDecoderStatusUnsupportedEncoderProperties = 2, WMCMediaDecoderStatusDegraded = 3, }; typedef unsigned WMCMediaDecoderStatus; // Windows.Media.Core.AudioDecoderDegradation enum _WMCAudioDecoderDegradation { WMCAudioDecoderDegradationNone = 0, WMCAudioDecoderDegradationDownmixTo2Channels = 1, WMCAudioDecoderDegradationDownmixTo6Channels = 2, WMCAudioDecoderDegradationDownmixTo8Channels = 3, }; typedef unsigned WMCAudioDecoderDegradation; // Windows.Media.Core.AudioDecoderDegradationReason enum _WMCAudioDecoderDegradationReason { WMCAudioDecoderDegradationReasonNone = 0, WMCAudioDecoderDegradationReasonLicensingRequirement = 1, }; typedef unsigned WMCAudioDecoderDegradationReason; // Windows.Media.Core.MediaSourceStatus enum _WMCMediaSourceStatus { WMCMediaSourceStatusFullySupported = 0, WMCMediaSourceStatusUnknown = 1, }; typedef unsigned WMCMediaSourceStatus; // Windows.Media.Core.MediaSourceState enum _WMCMediaSourceState { WMCMediaSourceStateInitial = 0, WMCMediaSourceStateOpening = 1, WMCMediaSourceStateOpened = 2, WMCMediaSourceStateFailed = 3, WMCMediaSourceStateClosed = 4, }; typedef unsigned WMCMediaSourceState; #include "WindowsMediaFaceAnalysis.h" #include "WindowsMediaProtection.h" #include "WindowsMediaMediaProperties.h" #include "WindowsFoundation.h" #include "WindowsStorageStreams.h" #include "WindowsStorageFileProperties.h" #include "WindowsMediaDevicesCore.h" #include "WindowsMedia.h" #include "WindowsMediaCapture.h" #include "WindowsMediaEffects.h" #include "WindowsMediaDevices.h" #include "WindowsMediaStreamingAdaptive.h" #include "WindowsStorage.h" #include "WindowsMediaPlayback.h" #include "WindowsFoundationCollections.h" #include "WindowsUI.h" #import <Foundation/Foundation.h> // [struct] Windows.Media.Core.MseTimeRange OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMseTimeRange : NSObject + (instancetype)new; @property (retain) WFTimeSpan* start; @property (retain) WFTimeSpan* end; @end // [struct] Windows.Media.Core.TimedTextPadding OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextPadding : NSObject + (instancetype)new; @property double before; @property double after; @property double start; @property double end; @property WMCTimedTextUnit unit; @end // [struct] Windows.Media.Core.TimedTextSize OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextSize : NSObject + (instancetype)new; @property double height; @property double width; @property WMCTimedTextUnit unit; @end // [struct] Windows.Media.Core.TimedTextDouble OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextDouble : NSObject + (instancetype)new; @property double value; @property WMCTimedTextUnit unit; @end // [struct] Windows.Media.Core.TimedTextPoint OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextPoint : NSObject + (instancetype)new; @property double x; @property double y; @property WMCTimedTextUnit unit; @end // Windows.Media.Core.IMediaSource #ifndef __WMCIMediaSource_DEFINED__ #define __WMCIMediaSource_DEFINED__ @protocol WMCIMediaSource @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCIMediaSource : RTObject <WMCIMediaSource> @end #endif // __WMCIMediaSource_DEFINED__ // Windows.Media.Core.IMediaStreamDescriptor #ifndef __WMCIMediaStreamDescriptor_DEFINED__ #define __WMCIMediaStreamDescriptor_DEFINED__ @protocol WMCIMediaStreamDescriptor @property (readonly) BOOL isSelected; @property (retain) NSString * language; @property (retain) NSString * name; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCIMediaStreamDescriptor : RTObject <WMCIMediaStreamDescriptor> @end #endif // __WMCIMediaStreamDescriptor_DEFINED__ // Windows.Media.Core.IMediaCue #ifndef __WMCIMediaCue_DEFINED__ #define __WMCIMediaCue_DEFINED__ @protocol WMCIMediaCue @property (retain) WFTimeSpan* duration; @property (retain) NSString * id; @property (retain) WFTimeSpan* startTime; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCIMediaCue : RTObject <WMCIMediaCue> @end #endif // __WMCIMediaCue_DEFINED__ // Windows.Media.Core.ISingleSelectMediaTrackList #ifndef __WMCISingleSelectMediaTrackList_DEFINED__ #define __WMCISingleSelectMediaTrackList_DEFINED__ @protocol WMCISingleSelectMediaTrackList @property int selectedIndex; - (EventRegistrationToken)addSelectedIndexChangedEvent:(void(^)(RTObject<WMCISingleSelectMediaTrackList>*, RTObject*))del; - (void)removeSelectedIndexChangedEvent:(EventRegistrationToken)tok; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCISingleSelectMediaTrackList : RTObject <WMCISingleSelectMediaTrackList> @end #endif // __WMCISingleSelectMediaTrackList_DEFINED__ // Windows.Media.Core.IMediaTrack #ifndef __WMCIMediaTrack_DEFINED__ #define __WMCIMediaTrack_DEFINED__ @protocol WMCIMediaTrack @property (readonly) NSString * id; @property (retain) NSString * label; @property (readonly) NSString * language; @property (readonly) WMCMediaTrackKind trackKind; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCIMediaTrack : RTObject <WMCIMediaTrack> @end #endif // __WMCIMediaTrack_DEFINED__ // Windows.Media.Core.AudioStreamDescriptor #ifndef __WMCAudioStreamDescriptor_DEFINED__ #define __WMCAudioStreamDescriptor_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCAudioStreamDescriptor : RTObject <WMCIMediaStreamDescriptor> + (WMCAudioStreamDescriptor*)make:(WMMAudioEncodingProperties*)encodingProperties ACTIVATOR; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMMAudioEncodingProperties* encodingProperties; @property (retain) id /* unsigned int */ trailingEncoderPadding; @property (retain) id /* unsigned int */ leadingEncoderPadding; @property (retain) NSString * name; @property (retain) NSString * language; @property (readonly) BOOL isSelected; @end #endif // __WMCAudioStreamDescriptor_DEFINED__ // Windows.Media.Core.VideoStreamDescriptor #ifndef __WMCVideoStreamDescriptor_DEFINED__ #define __WMCVideoStreamDescriptor_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoStreamDescriptor : RTObject <WMCIMediaStreamDescriptor> + (WMCVideoStreamDescriptor*)make:(WMMVideoEncodingProperties*)encodingProperties ACTIVATOR; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * name; @property (retain) NSString * language; @property (readonly) BOOL isSelected; @property (readonly) WMMVideoEncodingProperties* encodingProperties; @end #endif // __WMCVideoStreamDescriptor_DEFINED__ // Windows.Media.Core.MediaStreamSource #ifndef __WMCMediaStreamSource_DEFINED__ #define __WMCMediaStreamSource_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSource : RTObject <WMCIMediaSource> + (WMCMediaStreamSource*)makeFromDescriptor:(RTObject<WMCIMediaStreamDescriptor>*)descriptor ACTIVATOR; + (WMCMediaStreamSource*)makeFromDescriptors:(RTObject<WMCIMediaStreamDescriptor>*)descriptor descriptor2:(RTObject<WMCIMediaStreamDescriptor>*)descriptor2 ACTIVATOR; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) RTObject<WSSIRandomAccessStreamReference>* thumbnail; @property (retain) WMPMediaProtectionManager* mediaProtectionManager; @property (retain) WFTimeSpan* duration; @property BOOL canSeek; @property (retain) WFTimeSpan* bufferTime; @property (readonly) WSFMusicProperties* musicProperties; @property (readonly) WSFVideoProperties* videoProperties; - (EventRegistrationToken)addClosedEvent:(void(^)(WMCMediaStreamSource*, WMCMediaStreamSourceClosedEventArgs*))del; - (void)removeClosedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addPausedEvent:(void(^)(WMCMediaStreamSource*, RTObject*))del; - (void)removePausedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addSampleRequestedEvent:(void(^)(WMCMediaStreamSource*, WMCMediaStreamSourceSampleRequestedEventArgs*))del; - (void)removeSampleRequestedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addStartingEvent:(void(^)(WMCMediaStreamSource*, WMCMediaStreamSourceStartingEventArgs*))del; - (void)removeStartingEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addSwitchStreamsRequestedEvent:(void(^)(WMCMediaStreamSource*, WMCMediaStreamSourceSwitchStreamsRequestedEventArgs*))del; - (void)removeSwitchStreamsRequestedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addSampleRenderedEvent:(void(^)(WMCMediaStreamSource*, WMCMediaStreamSourceSampleRenderedEventArgs*))del; - (void)removeSampleRenderedEvent:(EventRegistrationToken)tok; - (void)notifyError:(WMCMediaStreamSourceErrorStatus)errorStatus; - (void)addStreamDescriptor:(RTObject<WMCIMediaStreamDescriptor>*)descriptor; - (void)setBufferedRange:(WFTimeSpan*)startOffset endOffset:(WFTimeSpan*)endOffset; - (void)addProtectionKey:(RTObject<WMCIMediaStreamDescriptor>*)streamDescriptor keyIdentifier:(NSArray* /* uint8_t */)keyIdentifier licenseData:(NSArray* /* uint8_t */)licenseData; @end #endif // __WMCMediaStreamSource_DEFINED__ // Windows.Media.Core.MediaStreamSourceClosedEventArgs #ifndef __WMCMediaStreamSourceClosedEventArgs_DEFINED__ #define __WMCMediaStreamSourceClosedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceClosedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaStreamSourceClosedRequest* request; @end #endif // __WMCMediaStreamSourceClosedEventArgs_DEFINED__ // Windows.Media.Core.MediaStreamSourceStartingEventArgs #ifndef __WMCMediaStreamSourceStartingEventArgs_DEFINED__ #define __WMCMediaStreamSourceStartingEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceStartingEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaStreamSourceStartingRequest* request; @end #endif // __WMCMediaStreamSourceStartingEventArgs_DEFINED__ // Windows.Media.Core.MediaStreamSourceSampleRequestedEventArgs #ifndef __WMCMediaStreamSourceSampleRequestedEventArgs_DEFINED__ #define __WMCMediaStreamSourceSampleRequestedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSampleRequestedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaStreamSourceSampleRequest* request; @end #endif // __WMCMediaStreamSourceSampleRequestedEventArgs_DEFINED__ // Windows.Media.Core.MediaStreamSourceSwitchStreamsRequestedEventArgs #ifndef __WMCMediaStreamSourceSwitchStreamsRequestedEventArgs_DEFINED__ #define __WMCMediaStreamSourceSwitchStreamsRequestedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSwitchStreamsRequestedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaStreamSourceSwitchStreamsRequest* request; @end #endif // __WMCMediaStreamSourceSwitchStreamsRequestedEventArgs_DEFINED__ // Windows.Media.Core.MediaStreamSourceSampleRenderedEventArgs #ifndef __WMCMediaStreamSourceSampleRenderedEventArgs_DEFINED__ #define __WMCMediaStreamSourceSampleRenderedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSampleRenderedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WFTimeSpan* sampleLag; @end #endif // __WMCMediaStreamSourceSampleRenderedEventArgs_DEFINED__ // Windows.Media.Core.MediaStreamSamplePropertySet #ifndef __WMCMediaStreamSamplePropertySet_DEFINED__ #define __WMCMediaStreamSamplePropertySet_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSamplePropertySet : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) unsigned int size; - (id)objectForKey: (id)key; - (NSArray*)allKeys; - (NSArray*)allKeysForObject: (id)obj; - (NSArray*)allValues; - (id)keyEnumerator; - (unsigned int)count; -(void)setObject: (id)obj forKey: (id)key; -(void)setObject:(id)object forKeyedSubscript:(id)key; -(void)removeObjectForKey: (id)key; -(void)removeAllObjects; -(void)removeObjectsForKeys:(NSArray*)keys; -(void)addEntriesFromDictionary:(NSDictionary*)otherDict; -(void)addEntriesFromDictionaryNoReplace:(NSDictionary*)otherDict; -(void)setDictionary: (NSDictionary*)dict; @end #endif // __WMCMediaStreamSamplePropertySet_DEFINED__ // Windows.Media.Core.MediaStreamSample #ifndef __WMCMediaStreamSample_DEFINED__ #define __WMCMediaStreamSample_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSample : RTObject + (WMCMediaStreamSample*)createFromBuffer:(RTObject<WSSIBuffer>*)buffer timestamp:(WFTimeSpan*)timestamp; + (void)createFromStreamAsync:(RTObject<WSSIInputStream>*)stream count:(unsigned int)count timestamp:(WFTimeSpan*)timestamp success:(void (^)(WMCMediaStreamSample*))success failure:(void (^)(NSError*))failure; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property BOOL keyFrame; @property (retain) WFTimeSpan* duration; @property BOOL discontinuous; @property (retain) WFTimeSpan* decodeTimestamp; @property (readonly) WSSBuffer* buffer; @property (readonly) WMCMediaStreamSamplePropertySet* extendedProperties; @property (readonly) WMCMediaStreamSampleProtectionProperties* protection; @property (readonly) WFTimeSpan* timestamp; - (EventRegistrationToken)addProcessedEvent:(void(^)(WMCMediaStreamSample*, RTObject*))del; - (void)removeProcessedEvent:(EventRegistrationToken)tok; @end #endif // __WMCMediaStreamSample_DEFINED__ // Windows.Media.Core.MediaStreamSampleProtectionProperties #ifndef __WMCMediaStreamSampleProtectionProperties_DEFINED__ #define __WMCMediaStreamSampleProtectionProperties_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSampleProtectionProperties : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif - (void)setKeyIdentifier:(NSArray* /* uint8_t */)value; - (void)getKeyIdentifier:(NSArray* /* uint8_t */*)value; - (void)setInitializationVector:(NSArray* /* uint8_t */)value; - (void)getInitializationVector:(NSArray* /* uint8_t */*)value; - (void)setSubSampleMapping:(NSArray* /* uint8_t */)value; - (void)getSubSampleMapping:(NSArray* /* uint8_t */*)value; @end #endif // __WMCMediaStreamSampleProtectionProperties_DEFINED__ // Windows.Media.Core.MediaStreamSourceClosedRequest #ifndef __WMCMediaStreamSourceClosedRequest_DEFINED__ #define __WMCMediaStreamSourceClosedRequest_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceClosedRequest : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaStreamSourceClosedReason reason; @end #endif // __WMCMediaStreamSourceClosedRequest_DEFINED__ // Windows.Media.Core.MediaStreamSourceStartingRequestDeferral #ifndef __WMCMediaStreamSourceStartingRequestDeferral_DEFINED__ #define __WMCMediaStreamSourceStartingRequestDeferral_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceStartingRequestDeferral : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif - (void)complete; @end #endif // __WMCMediaStreamSourceStartingRequestDeferral_DEFINED__ // Windows.Media.Core.MediaStreamSourceStartingRequest #ifndef __WMCMediaStreamSourceStartingRequest_DEFINED__ #define __WMCMediaStreamSourceStartingRequest_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceStartingRequest : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) id /* WFTimeSpan* */ startPosition; - (WMCMediaStreamSourceStartingRequestDeferral*)getDeferral; - (void)setActualStartPosition:(WFTimeSpan*)position; @end #endif // __WMCMediaStreamSourceStartingRequest_DEFINED__ // Windows.Media.Core.MediaStreamSourceSampleRequestDeferral #ifndef __WMCMediaStreamSourceSampleRequestDeferral_DEFINED__ #define __WMCMediaStreamSourceSampleRequestDeferral_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSampleRequestDeferral : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif - (void)complete; @end #endif // __WMCMediaStreamSourceSampleRequestDeferral_DEFINED__ // Windows.Media.Core.MediaStreamSourceSampleRequest #ifndef __WMCMediaStreamSourceSampleRequest_DEFINED__ #define __WMCMediaStreamSourceSampleRequest_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSampleRequest : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WMCMediaStreamSample* sample; @property (readonly) RTObject<WMCIMediaStreamDescriptor>* streamDescriptor; - (WMCMediaStreamSourceSampleRequestDeferral*)getDeferral; - (void)reportSampleProgress:(unsigned int)progress; @end #endif // __WMCMediaStreamSourceSampleRequest_DEFINED__ // Windows.Media.Core.MediaStreamSourceSwitchStreamsRequestDeferral #ifndef __WMCMediaStreamSourceSwitchStreamsRequestDeferral_DEFINED__ #define __WMCMediaStreamSourceSwitchStreamsRequestDeferral_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSwitchStreamsRequestDeferral : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif - (void)complete; @end #endif // __WMCMediaStreamSourceSwitchStreamsRequestDeferral_DEFINED__ // Windows.Media.Core.MediaStreamSourceSwitchStreamsRequest #ifndef __WMCMediaStreamSourceSwitchStreamsRequest_DEFINED__ #define __WMCMediaStreamSourceSwitchStreamsRequest_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaStreamSourceSwitchStreamsRequest : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) RTObject<WMCIMediaStreamDescriptor>* newStreamDescriptor __attribute__ ((ns_returns_not_retained)); @property (readonly) RTObject<WMCIMediaStreamDescriptor>* oldStreamDescriptor; - (WMCMediaStreamSourceSwitchStreamsRequestDeferral*)getDeferral; @end #endif // __WMCMediaStreamSourceSwitchStreamsRequest_DEFINED__ // Windows.Media.Core.MseStreamSource #ifndef __WMCMseStreamSource_DEFINED__ #define __WMCMseStreamSource_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMseStreamSource : RTObject <WMCIMediaSource> + (BOOL)isContentTypeSupported:(NSString *)contentType; + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) id /* WFTimeSpan* */ duration; @property (readonly) WMCMseSourceBufferList* activeSourceBuffers; @property (readonly) WMCMseReadyState readyState; @property (readonly) WMCMseSourceBufferList* sourceBuffers; - (EventRegistrationToken)addClosedEvent:(void(^)(WMCMseStreamSource*, RTObject*))del; - (void)removeClosedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addEndedEvent:(void(^)(WMCMseStreamSource*, RTObject*))del; - (void)removeEndedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addOpenedEvent:(void(^)(WMCMseStreamSource*, RTObject*))del; - (void)removeOpenedEvent:(EventRegistrationToken)tok; - (WMCMseSourceBuffer*)addSourceBuffer:(NSString *)mimeType; - (void)removeSourceBuffer:(WMCMseSourceBuffer*)buffer; - (void)endOfStream:(WMCMseEndOfStreamStatus)status; @end #endif // __WMCMseStreamSource_DEFINED__ // Windows.Media.Core.MseSourceBufferList #ifndef __WMCMseSourceBufferList_DEFINED__ #define __WMCMseSourceBufferList_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMseSourceBufferList : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSArray* /* WMCMseSourceBuffer* */ buffers; - (EventRegistrationToken)addSourceBufferAddedEvent:(void(^)(WMCMseSourceBufferList*, RTObject*))del; - (void)removeSourceBufferAddedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addSourceBufferRemovedEvent:(void(^)(WMCMseSourceBufferList*, RTObject*))del; - (void)removeSourceBufferRemovedEvent:(EventRegistrationToken)tok; @end #endif // __WMCMseSourceBufferList_DEFINED__ // Windows.Media.Core.MseSourceBuffer #ifndef __WMCMseSourceBuffer_DEFINED__ #define __WMCMseSourceBuffer_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMseSourceBuffer : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WFTimeSpan* timestampOffset; @property WMCMseAppendMode mode; @property (retain) WFTimeSpan* appendWindowStart; @property (retain) id /* WFTimeSpan* */ appendWindowEnd; @property (readonly) NSArray* /* WMCMseTimeRange* */ buffered; @property (readonly) BOOL isUpdating; - (EventRegistrationToken)addAbortedEvent:(void(^)(WMCMseSourceBuffer*, RTObject*))del; - (void)removeAbortedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addErrorOccurredEvent:(void(^)(WMCMseSourceBuffer*, RTObject*))del; - (void)removeErrorOccurredEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addUpdateEndedEvent:(void(^)(WMCMseSourceBuffer*, RTObject*))del; - (void)removeUpdateEndedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addUpdateStartingEvent:(void(^)(WMCMseSourceBuffer*, RTObject*))del; - (void)removeUpdateStartingEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addUpdatedEvent:(void(^)(WMCMseSourceBuffer*, RTObject*))del; - (void)removeUpdatedEvent:(EventRegistrationToken)tok; - (void)appendBuffer:(RTObject<WSSIBuffer>*)buffer; - (void)appendStream:(RTObject<WSSIInputStream>*)stream; - (void)appendStreamMaxSize:(RTObject<WSSIInputStream>*)stream maxSize:(uint64_t)maxSize; - (void)abort; - (void)remove:(WFTimeSpan*)start end:(id /* WFTimeSpan* */)end; @end #endif // __WMCMseSourceBuffer_DEFINED__ // Windows.Media.Core.HighDynamicRangeControl #ifndef __WMCHighDynamicRangeControl_DEFINED__ #define __WMCHighDynamicRangeControl_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCHighDynamicRangeControl : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property BOOL enabled; @end #endif // __WMCHighDynamicRangeControl_DEFINED__ // Windows.Media.IMediaExtension #ifndef __WMIMediaExtension_DEFINED__ #define __WMIMediaExtension_DEFINED__ @protocol WMIMediaExtension - (void)setProperties:(RTObject<WFCIPropertySet>*)configuration; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMIMediaExtension : RTObject <WMIMediaExtension> @end #endif // __WMIMediaExtension_DEFINED__ // Windows.Media.Core.SceneAnalysisEffect #ifndef __WMCSceneAnalysisEffect_DEFINED__ #define __WMCSceneAnalysisEffect_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCSceneAnalysisEffect : RTObject <WMIMediaExtension> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WFTimeSpan* desiredAnalysisInterval; @property (readonly) WMCHighDynamicRangeControl* highDynamicRangeAnalyzer; - (EventRegistrationToken)addSceneAnalyzedEvent:(void(^)(WMCSceneAnalysisEffect*, WMCSceneAnalyzedEventArgs*))del; - (void)removeSceneAnalyzedEvent:(EventRegistrationToken)tok; - (void)setProperties:(RTObject<WFCIPropertySet>*)configuration; @end #endif // __WMCSceneAnalysisEffect_DEFINED__ // Windows.Media.Core.SceneAnalyzedEventArgs #ifndef __WMCSceneAnalyzedEventArgs_DEFINED__ #define __WMCSceneAnalyzedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCSceneAnalyzedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCSceneAnalysisEffectFrame* resultFrame; @end #endif // __WMCSceneAnalyzedEventArgs_DEFINED__ // Windows.Media.Core.HighDynamicRangeOutput #ifndef __WMCHighDynamicRangeOutput_DEFINED__ #define __WMCHighDynamicRangeOutput_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCHighDynamicRangeOutput : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) double certainty; @property (readonly) NSArray* /* WMDCFrameController* */ frameControllers; @end #endif // __WMCHighDynamicRangeOutput_DEFINED__ // Windows.Foundation.IClosable #ifndef __WFIClosable_DEFINED__ #define __WFIClosable_DEFINED__ @protocol WFIClosable - (void)close; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WFIClosable : RTObject <WFIClosable> @end #endif // __WFIClosable_DEFINED__ // Windows.Media.IMediaFrame #ifndef __WMIMediaFrame_DEFINED__ #define __WMIMediaFrame_DEFINED__ @protocol WMIMediaFrame <WFIClosable> @property (retain) id /* WFTimeSpan* */ duration; @property (readonly) RTObject<WFCIPropertySet>* extendedProperties; @property BOOL isDiscontinuous; @property (readonly) BOOL isReadOnly; @property (retain) id /* WFTimeSpan* */ relativeTime; @property (retain) id /* WFTimeSpan* */ systemRelativeTime; @property (readonly) NSString * type; - (void)close; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMIMediaFrame : RTObject <WMIMediaFrame> @end #endif // __WMIMediaFrame_DEFINED__ // Windows.Media.Core.SceneAnalysisEffectFrame #ifndef __WMCSceneAnalysisEffectFrame_DEFINED__ #define __WMCSceneAnalysisEffectFrame_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCSceneAnalysisEffectFrame : RTObject <WMIMediaFrame, WFIClosable> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCCapturedFrameControlValues* frameControlValues; @property (readonly) WMCHighDynamicRangeOutput* highDynamicRange; @property (retain) id /* WFTimeSpan* */ systemRelativeTime; @property (retain) id /* WFTimeSpan* */ relativeTime; @property BOOL isDiscontinuous; @property (retain) id /* WFTimeSpan* */ duration; @property (readonly) RTObject<WFCIPropertySet>* extendedProperties; @property (readonly) BOOL isReadOnly; @property (readonly) NSString * type; - (void)close; @end #endif // __WMCSceneAnalysisEffectFrame_DEFINED__ // Windows.Media.Effects.IVideoEffectDefinition #ifndef __WMEIVideoEffectDefinition_DEFINED__ #define __WMEIVideoEffectDefinition_DEFINED__ @protocol WMEIVideoEffectDefinition @property (readonly) NSString * activatableClassId; @property (readonly) RTObject<WFCIPropertySet>* properties; @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMEIVideoEffectDefinition : RTObject <WMEIVideoEffectDefinition> @end #endif // __WMEIVideoEffectDefinition_DEFINED__ // Windows.Media.Core.SceneAnalysisEffectDefinition #ifndef __WMCSceneAnalysisEffectDefinition_DEFINED__ #define __WMCSceneAnalysisEffectDefinition_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCSceneAnalysisEffectDefinition : RTObject <WMEIVideoEffectDefinition> + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSString * activatableClassId; @property (readonly) RTObject<WFCIPropertySet>* properties; @end #endif // __WMCSceneAnalysisEffectDefinition_DEFINED__ // Windows.Media.Core.FaceDetectionEffectFrame #ifndef __WMCFaceDetectionEffectFrame_DEFINED__ #define __WMCFaceDetectionEffectFrame_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCFaceDetectionEffectFrame : RTObject <WMIMediaFrame, WFIClosable> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSArray* /* WMFDetectedFace* */ detectedFaces; @property (retain) id /* WFTimeSpan* */ systemRelativeTime; @property (retain) id /* WFTimeSpan* */ relativeTime; @property BOOL isDiscontinuous; @property (retain) id /* WFTimeSpan* */ duration; @property (readonly) RTObject<WFCIPropertySet>* extendedProperties; @property (readonly) BOOL isReadOnly; @property (readonly) NSString * type; - (void)close; @end #endif // __WMCFaceDetectionEffectFrame_DEFINED__ // Windows.Media.Core.FaceDetectedEventArgs #ifndef __WMCFaceDetectedEventArgs_DEFINED__ #define __WMCFaceDetectedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCFaceDetectedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCFaceDetectionEffectFrame* resultFrame; @end #endif // __WMCFaceDetectedEventArgs_DEFINED__ // Windows.Media.Core.FaceDetectionEffect #ifndef __WMCFaceDetectionEffect_DEFINED__ #define __WMCFaceDetectionEffect_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCFaceDetectionEffect : RTObject <WMIMediaExtension> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property BOOL enabled; @property (retain) WFTimeSpan* desiredDetectionInterval; - (EventRegistrationToken)addFaceDetectedEvent:(void(^)(WMCFaceDetectionEffect*, WMCFaceDetectedEventArgs*))del; - (void)removeFaceDetectedEvent:(EventRegistrationToken)tok; - (void)setProperties:(RTObject<WFCIPropertySet>*)configuration; @end #endif // __WMCFaceDetectionEffect_DEFINED__ // Windows.Media.Core.FaceDetectionEffectDefinition #ifndef __WMCFaceDetectionEffectDefinition_DEFINED__ #define __WMCFaceDetectionEffectDefinition_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCFaceDetectionEffectDefinition : RTObject <WMEIVideoEffectDefinition> + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property BOOL synchronousDetectionEnabled; @property WMCFaceDetectionMode detectionMode; @property (readonly) NSString * activatableClassId; @property (readonly) RTObject<WFCIPropertySet>* properties; @end #endif // __WMCFaceDetectionEffectDefinition_DEFINED__ // Windows.Media.Core.VideoStabilizationEffectEnabledChangedEventArgs #ifndef __WMCVideoStabilizationEffectEnabledChangedEventArgs_DEFINED__ #define __WMCVideoStabilizationEffectEnabledChangedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoStabilizationEffectEnabledChangedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCVideoStabilizationEffectEnabledChangedReason reason; @end #endif // __WMCVideoStabilizationEffectEnabledChangedEventArgs_DEFINED__ // Windows.Media.Core.VideoStabilizationEffect #ifndef __WMCVideoStabilizationEffect_DEFINED__ #define __WMCVideoStabilizationEffect_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoStabilizationEffect : RTObject <WMIMediaExtension> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property BOOL enabled; - (EventRegistrationToken)addEnabledChangedEvent:(void(^)(WMCVideoStabilizationEffect*, WMCVideoStabilizationEffectEnabledChangedEventArgs*))del; - (void)removeEnabledChangedEvent:(EventRegistrationToken)tok; - (WMCVideoStreamConfiguration*)getRecommendedStreamConfiguration:(WMDVideoDeviceController*)controller desiredProperties:(WMMVideoEncodingProperties*)desiredProperties; - (void)setProperties:(RTObject<WFCIPropertySet>*)configuration; @end #endif // __WMCVideoStabilizationEffect_DEFINED__ // Windows.Media.Core.VideoStabilizationEffectDefinition #ifndef __WMCVideoStabilizationEffectDefinition_DEFINED__ #define __WMCVideoStabilizationEffectDefinition_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoStabilizationEffectDefinition : RTObject <WMEIVideoEffectDefinition> + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSString * activatableClassId; @property (readonly) RTObject<WFCIPropertySet>* properties; @end #endif // __WMCVideoStabilizationEffectDefinition_DEFINED__ // Windows.Media.Core.MediaSourceError #ifndef __WMCMediaSourceError_DEFINED__ #define __WMCMediaSourceError_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaSourceError : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) HRESULT extendedError; @end #endif // __WMCMediaSourceError_DEFINED__ // Windows.Media.Playback.IMediaPlaybackSource #ifndef __WMPIMediaPlaybackSource_DEFINED__ #define __WMPIMediaPlaybackSource_DEFINED__ @protocol WMPIMediaPlaybackSource @end OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMPIMediaPlaybackSource : RTObject <WMPIMediaPlaybackSource> @end #endif // __WMPIMediaPlaybackSource_DEFINED__ // Windows.Media.Core.MediaSource #ifndef __WMCMediaSource_DEFINED__ #define __WMCMediaSource_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaSource : RTObject <WFIClosable, WMPIMediaPlaybackSource> + (WMCMediaSource*)createFromMediaBinder:(WMCMediaBinder*)binder; + (WMCMediaSource*)createFromAdaptiveMediaSource:(WMSAAdaptiveMediaSource*)mediaSource; + (WMCMediaSource*)createFromMediaStreamSource:(WMCMediaStreamSource*)mediaSource; + (WMCMediaSource*)createFromMseStreamSource:(WMCMseStreamSource*)mediaSource; + (WMCMediaSource*)createFromIMediaSource:(RTObject<WMCIMediaSource>*)mediaSource; + (WMCMediaSource*)createFromStorageFile:(RTObject<WSIStorageFile>*)file; + (WMCMediaSource*)createFromStream:(RTObject<WSSIRandomAccessStream>*)stream contentType:(NSString *)contentType; + (WMCMediaSource*)createFromStreamReference:(RTObject<WSSIRandomAccessStreamReference>*)stream contentType:(NSString *)contentType; + (WMCMediaSource*)createFromUri:(WFUri*)uri; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WFCValueSet* customProperties; @property (readonly) id /* WFTimeSpan* */ duration; @property (readonly) NSMutableArray<RTObservableCollection>* /* WMCTimedMetadataTrack* */ externalTimedMetadataTracks; @property (readonly) NSMutableArray<RTObservableCollection>* /* WMCTimedTextSource* */ externalTimedTextSources; @property (readonly) BOOL isOpen; @property (readonly) WMCMediaSourceState state; - (EventRegistrationToken)addOpenOperationCompletedEvent:(void(^)(WMCMediaSource*, WMCMediaSourceOpenOperationCompletedEventArgs*))del; - (void)removeOpenOperationCompletedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addStateChangedEvent:(void(^)(WMCMediaSource*, WMCMediaSourceStateChangedEventArgs*))del; - (void)removeStateChangedEvent:(EventRegistrationToken)tok; - (void)close; - (void)reset; @end #endif // __WMCMediaSource_DEFINED__ // Windows.Media.Core.MediaBinder #ifndef __WMCMediaBinder_DEFINED__ #define __WMCMediaBinder_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaBinder : RTObject + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * token; @property (readonly) WMCMediaSource* source; - (EventRegistrationToken)addBindingEvent:(void(^)(WMCMediaBinder*, WMCMediaBindingEventArgs*))del; - (void)removeBindingEvent:(EventRegistrationToken)tok; @end #endif // __WMCMediaBinder_DEFINED__ // Windows.Media.Core.MediaBindingEventArgs #ifndef __WMCMediaBindingEventArgs_DEFINED__ #define __WMCMediaBindingEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaBindingEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaBinder* mediaBinder; - (EventRegistrationToken)addCanceledEvent:(void(^)(WMCMediaBindingEventArgs*, RTObject*))del; - (void)removeCanceledEvent:(EventRegistrationToken)tok; - (WFDeferral*)getDeferral; - (void)setUri:(WFUri*)uri; - (void)setStream:(RTObject<WSSIRandomAccessStream>*)stream contentType:(NSString *)contentType; - (void)setStreamReference:(RTObject<WSSIRandomAccessStreamReference>*)stream contentType:(NSString *)contentType; @end #endif // __WMCMediaBindingEventArgs_DEFINED__ // Windows.Media.Core.MediaSourceOpenOperationCompletedEventArgs #ifndef __WMCMediaSourceOpenOperationCompletedEventArgs_DEFINED__ #define __WMCMediaSourceOpenOperationCompletedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaSourceOpenOperationCompletedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaSourceError* error; @end #endif // __WMCMediaSourceOpenOperationCompletedEventArgs_DEFINED__ // Windows.Media.Core.TimedTextSource #ifndef __WMCTimedTextSource_DEFINED__ #define __WMCTimedTextSource_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextSource : RTObject + (WMCTimedTextSource*)createFromStream:(RTObject<WSSIRandomAccessStream>*)stream; + (WMCTimedTextSource*)createFromUri:(WFUri*)uri; + (WMCTimedTextSource*)createFromStreamWithLanguage:(RTObject<WSSIRandomAccessStream>*)stream defaultLanguage:(NSString *)defaultLanguage; + (WMCTimedTextSource*)createFromUriWithLanguage:(WFUri*)uri defaultLanguage:(NSString *)defaultLanguage; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif - (EventRegistrationToken)addResolvedEvent:(void(^)(WMCTimedTextSource*, WMCTimedTextSourceResolveResultEventArgs*))del; - (void)removeResolvedEvent:(EventRegistrationToken)tok; @end #endif // __WMCTimedTextSource_DEFINED__ // Windows.Media.Core.TimedMetadataTrack #ifndef __WMCTimedMetadataTrack_DEFINED__ #define __WMCTimedMetadataTrack_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedMetadataTrack : RTObject <WMCIMediaTrack> + (WMCTimedMetadataTrack*)make:(NSString *)id language:(NSString *)language kind:(WMCTimedMetadataKind)kind ACTIVATOR; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * label; @property (readonly) NSString * id; @property (readonly) NSString * language; @property (readonly) WMCMediaTrackKind trackKind; @property (readonly) NSArray* /* RTObject<WMCIMediaCue>* */ activeCues; @property (readonly) NSArray* /* RTObject<WMCIMediaCue>* */ cues; @property (readonly) NSString * dispatchType; @property (readonly) WMCTimedMetadataKind timedMetadataKind; @property (readonly) NSString * name; @property (readonly) WMPMediaPlaybackItem* playbackItem; - (EventRegistrationToken)addCueEnteredEvent:(void(^)(WMCTimedMetadataTrack*, WMCMediaCueEventArgs*))del; - (void)removeCueEnteredEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addCueExitedEvent:(void(^)(WMCTimedMetadataTrack*, WMCMediaCueEventArgs*))del; - (void)removeCueExitedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addTrackFailedEvent:(void(^)(WMCTimedMetadataTrack*, WMCTimedMetadataTrackFailedEventArgs*))del; - (void)removeTrackFailedEvent:(EventRegistrationToken)tok; - (void)addCue:(RTObject<WMCIMediaCue>*)cue; - (void)removeCue:(RTObject<WMCIMediaCue>*)cue; @end #endif // __WMCTimedMetadataTrack_DEFINED__ // Windows.Media.Core.MediaSourceStateChangedEventArgs #ifndef __WMCMediaSourceStateChangedEventArgs_DEFINED__ #define __WMCMediaSourceStateChangedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaSourceStateChangedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaSourceState newState; @property (readonly) WMCMediaSourceState oldState; @end #endif // __WMCMediaSourceStateChangedEventArgs_DEFINED__ // Windows.Media.Core.TimedTextRegion #ifndef __WMCTimedTextRegion_DEFINED__ #define __WMCTimedTextRegion_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextRegion : RTObject + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * name; @property (retain) WMCTimedTextDouble* lineHeight; @property BOOL isOverflowClipped; @property (retain) WMCTimedTextSize* extent; @property WMCTimedTextDisplayAlignment displayAlignment; @property (retain) WMCTimedTextPadding* padding; @property (retain) WUColor* background; @property int zIndex; @property WMCTimedTextWritingMode writingMode; @property WMCTimedTextWrapping textWrapping; @property WMCTimedTextScrollMode scrollMode; @property (retain) WMCTimedTextPoint* position; @end #endif // __WMCTimedTextRegion_DEFINED__ // Windows.Media.Core.TimedTextStyle #ifndef __WMCTimedTextStyle_DEFINED__ #define __WMCTimedTextStyle_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextStyle : RTObject + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WUColor* foreground; @property WMCTimedTextWeight fontWeight; @property (retain) WMCTimedTextDouble* fontSize; @property (retain) NSString * fontFamily; @property WMCTimedTextFlowDirection flowDirection; @property BOOL isBackgroundAlwaysShown; @property (retain) WUColor* background; @property (retain) WMCTimedTextDouble* outlineThickness; @property (retain) WMCTimedTextDouble* outlineRadius; @property (retain) WUColor* outlineColor; @property (retain) NSString * name; @property WMCTimedTextLineAlignment lineAlignment; @end #endif // __WMCTimedTextStyle_DEFINED__ // Windows.Media.Core.TimedTextLine #ifndef __WMCTimedTextLine_DEFINED__ #define __WMCTimedTextLine_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextLine : RTObject + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * text; @property (readonly) NSMutableArray* /* WMCTimedTextSubformat* */ subformats; @end #endif // __WMCTimedTextLine_DEFINED__ // Windows.Media.Core.TimedTextSubformat #ifndef __WMCTimedTextSubformat_DEFINED__ #define __WMCTimedTextSubformat_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextSubformat : RTObject + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WMCTimedTextStyle* subformatStyle; @property int startIndex; @property int length; @end #endif // __WMCTimedTextSubformat_DEFINED__ // Windows.Media.Core.TimedMetadataTrackError #ifndef __WMCTimedMetadataTrackError_DEFINED__ #define __WMCTimedMetadataTrackError_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedMetadataTrackError : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCTimedMetadataTrackErrorCode errorCode; @property (readonly) HRESULT extendedError; @end #endif // __WMCTimedMetadataTrackError_DEFINED__ // Windows.Media.Core.MediaCueEventArgs #ifndef __WMCMediaCueEventArgs_DEFINED__ #define __WMCMediaCueEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCMediaCueEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) RTObject<WMCIMediaCue>* cue; @end #endif // __WMCMediaCueEventArgs_DEFINED__ // Windows.Media.Core.TimedMetadataTrackFailedEventArgs #ifndef __WMCTimedMetadataTrackFailedEventArgs_DEFINED__ #define __WMCTimedMetadataTrackFailedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedMetadataTrackFailedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCTimedMetadataTrackError* error; @end #endif // __WMCTimedMetadataTrackFailedEventArgs_DEFINED__ // Windows.Media.Core.TimedTextSourceResolveResultEventArgs #ifndef __WMCTimedTextSourceResolveResultEventArgs_DEFINED__ #define __WMCTimedTextSourceResolveResultEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextSourceResolveResultEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCTimedMetadataTrackError* error; @property (readonly) NSArray* /* WMCTimedMetadataTrack* */ tracks; @end #endif // __WMCTimedTextSourceResolveResultEventArgs_DEFINED__ // Windows.Media.Core.VideoTrack #ifndef __WMCVideoTrack_DEFINED__ #define __WMCVideoTrack_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoTrack : RTObject <WMCIMediaTrack> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) NSString * label; @property (readonly) NSString * id; @property (readonly) NSString * language; @property (readonly) WMCMediaTrackKind trackKind; @property (readonly) NSString * name; @property (readonly) WMPMediaPlaybackItem* playbackItem; @property (readonly) WMCVideoTrackSupportInfo* supportInfo; - (EventRegistrationToken)addOpenFailedEvent:(void(^)(WMCVideoTrack*, WMCVideoTrackOpenFailedEventArgs*))del; - (void)removeOpenFailedEvent:(EventRegistrationToken)tok; - (WMMVideoEncodingProperties*)getEncodingProperties; @end #endif // __WMCVideoTrack_DEFINED__ // Windows.Media.Core.VideoTrackOpenFailedEventArgs #ifndef __WMCVideoTrackOpenFailedEventArgs_DEFINED__ #define __WMCVideoTrackOpenFailedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoTrackOpenFailedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) HRESULT extendedError; @end #endif // __WMCVideoTrackOpenFailedEventArgs_DEFINED__ // Windows.Media.Core.VideoTrackSupportInfo #ifndef __WMCVideoTrackSupportInfo_DEFINED__ #define __WMCVideoTrackSupportInfo_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCVideoTrackSupportInfo : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaDecoderStatus decoderStatus; @property (readonly) WMCMediaSourceStatus mediaSourceStatus; @end #endif // __WMCVideoTrackSupportInfo_DEFINED__ // Windows.Media.Core.AudioTrack #ifndef __WMCAudioTrack_DEFINED__ #define __WMCAudioTrack_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCAudioTrack : RTObject <WMCIMediaTrack> #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSString * name; @property (readonly) WMPMediaPlaybackItem* playbackItem; @property (readonly) WMCAudioTrackSupportInfo* supportInfo; @property (retain) NSString * label; @property (readonly) NSString * id; @property (readonly) NSString * language; @property (readonly) WMCMediaTrackKind trackKind; - (EventRegistrationToken)addOpenFailedEvent:(void(^)(WMCAudioTrack*, WMCAudioTrackOpenFailedEventArgs*))del; - (void)removeOpenFailedEvent:(EventRegistrationToken)tok; - (WMMAudioEncodingProperties*)getEncodingProperties; @end #endif // __WMCAudioTrack_DEFINED__ // Windows.Media.Core.AudioTrackOpenFailedEventArgs #ifndef __WMCAudioTrackOpenFailedEventArgs_DEFINED__ #define __WMCAudioTrackOpenFailedEventArgs_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCAudioTrackOpenFailedEventArgs : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) HRESULT extendedError; @end #endif // __WMCAudioTrackOpenFailedEventArgs_DEFINED__ // Windows.Media.Core.AudioTrackSupportInfo #ifndef __WMCAudioTrackSupportInfo_DEFINED__ #define __WMCAudioTrackSupportInfo_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCAudioTrackSupportInfo : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WMCMediaDecoderStatus decoderStatus; @property (readonly) WMCAudioDecoderDegradation degradation; @property (readonly) WMCAudioDecoderDegradationReason degradationReason; @property (readonly) WMCMediaSourceStatus mediaSourceStatus; @end #endif // __WMCAudioTrackSupportInfo_DEFINED__ // Windows.Media.Core.TimedTextCue #ifndef __WMCTimedTextCue_DEFINED__ #define __WMCTimedTextCue_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCTimedTextCue : RTObject <WMCIMediaCue> + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) WFTimeSpan* startTime; @property (retain) NSString * id; @property (retain) WFTimeSpan* duration; @property (retain) WMCTimedTextStyle* cueStyle; @property (retain) WMCTimedTextRegion* cueRegion; @property (readonly) NSMutableArray* /* WMCTimedTextLine* */ lines; @end #endif // __WMCTimedTextCue_DEFINED__ // Windows.Media.Core.DataCue #ifndef __WMCDataCue_DEFINED__ #define __WMCDataCue_DEFINED__ OBJCUWPWINDOWSMEDIACAPTUREDEVICESCOREPLAYBACKPROTECTIONEXPORT @interface WMCDataCue : RTObject <WMCIMediaCue> + (instancetype)make __attribute__ ((ns_returns_retained)); #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (retain) RTObject<WSSIBuffer>* data; @property (retain) WFTimeSpan* startTime; @property (retain) NSString * id; @property (retain) WFTimeSpan* duration; @end #endif // __WMCDataCue_DEFINED__
41.718586
2,163
0.849716
[ "object" ]
aa7473772581160c0784c9e080a19788b8ed782d
1,148
h
C
include/dataset.h
mrdvince/dermatologist
252a4fab935b2ab3cf03808ffa7166633f04ef16
[ "MIT" ]
null
null
null
include/dataset.h
mrdvince/dermatologist
252a4fab935b2ab3cf03808ffa7166633f04ef16
[ "MIT" ]
null
null
null
include/dataset.h
mrdvince/dermatologist
252a4fab935b2ab3cf03808ffa7166633f04ef16
[ "MIT" ]
null
null
null
#pragma once #include <dirent.h> #include <torch/torch.h> #include <torch/script.h> #include <opencv2/opencv.hpp> torch::Tensor read_data(std::string image_path); torch::Tensor read_labels(int label); std::vector<torch::Tensor> process_images(std::vector<std::string> list_of_images); std::vector<torch::Tensor> process_labels(std::vector<int> list_of_labels); std::pair<std::vector<std::string>, std::vector<int>> load_data_from_folder(std::vector<std::string> folder_names); class CDataset : public torch::data::Dataset<CDataset> { private: std::vector<torch::Tensor> images, labels; size_t dataset_size; public: CDataset(std::vector<std::string> list_images, std::vector<int> list_labels) { images = process_images(list_images); labels = process_labels(list_labels); dataset_size = images.size(); }; // get item torch::data::Example<> get(size_t index) override { torch::Tensor image = images.at(index); torch::Tensor label = labels.at(index); return {image, label}; }; torch::optional<size_t> size() const override { return dataset_size; }; };
34.787879
115
0.688153
[ "vector" ]
aa7a389652ca0a7162939a17534e6cc64226703a
15,015
h
C
Include/ZL_Data.h
laxa88/ZillaLib
dd90e8356a4ccb370e151d4bfae4623b8fe46ae7
[ "Zlib" ]
106
2016-03-23T00:14:03.000Z
2022-03-11T16:38:18.000Z
Include/ZL_Data.h
laxa88/ZillaLib
dd90e8356a4ccb370e151d4bfae4623b8fe46ae7
[ "Zlib" ]
15
2018-10-27T15:54:44.000Z
2022-03-23T22:38:16.000Z
Include/ZL_Data.h
laxa88/ZillaLib
dd90e8356a4ccb370e151d4bfae4623b8fe46ae7
[ "Zlib" ]
8
2017-10-21T15:31:31.000Z
2022-03-11T16:38:19.000Z
/* ZillaLib Copyright (C) 2010-2020 Bernhard Schelling This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef __ZL_DATA__ #define __ZL_DATA__ #if defined(_MSC_VER) && (_MSC_VER <= 1200) #pragma warning(disable:4786) //'Some STL template class' : identifier was truncated to '255' characters in the debug information #pragma warning(disable:4530) //C++ exception handler used, but unwind semantics are not enabled #endif #include <vector> #include <map> #include "ZL_Math.h" #include "ZL_File.h" #include "ZL_Application.h" //JSON format parser and writer struct ZL_Json { struct Iterator { operator bool () const { return (cursor >= begin && cursor < end); } ZL_Json& operator*() { return *(ZL_Json*)(void*)(cursor); } ZL_Json* operator->() { return (ZL_Json*)(void*)(cursor); } Iterator & operator++() { ++cursor; return *this; } Iterator & operator--() { --cursor; return *this; } size_t GetIndex() { return (cursor - begin); } private: struct ZL_JSON_Impl **cursor, **begin, **end; friend struct ZL_Json; }; ZL_Json(); ZL_Json(const char *json); ZL_Json(const char *json, size_t len); ZL_Json(const ZL_String &json); ZL_Json(const ZL_File &file); ~ZL_Json(); ZL_Json(const ZL_Json &source); ZL_Json &operator =(const ZL_Json &source) { SetReference(source); return *this; } ZL_Json &operator =(const char* NewString) { SetString(NewString); return *this; } ZL_Json &operator =(scalar NewFloat) { SetFloat(NewFloat); return *this; } ZL_Json &operator =(int NewInt) { SetInt(NewInt); return *this; } ZL_Json &operator =(bool NewBool) { SetBool(NewBool); return *this; } operator bool() const { return (impl!=NULL); } bool operator!() const { return (impl==NULL); } bool operator==(const ZL_Json &b) const { return (impl==b.impl); } bool operator!=(const ZL_Json &b) const { return (impl!=b.impl); } enum eType { TYPE_NULL, TYPE_OBJECT, TYPE_ARRAY, TYPE_STRING, TYPE_NUMBER, TYPE_TRUE, TYPE_FALSE }; eType GetType() const; //for arrays and objects size_t Size() const; //number of array/object children Iterator GetIterator() const; std::vector<ZL_Json> GetChildren() const; ZL_Json GetChild(size_t index) const; ZL_Json GetChildOf(const char* child_key, size_t index) const; //returns child of child ZL_Json GetByKey(const char* key) const; //returns uninitialized element if not exist (checkable with ! operator) //get the value of this element const char* GetString(const char* default_value = NULL) const; //return default_value if not TYPE_STRING scalar GetFloat(scalar default_value = 0) const; //return default_value if not TYPE_NUMBER int GetInt(int default_value = 0) const; //return default_value if not TYPE_NUMBER bool GetBool() const; bool IsNull() const; bool HasKey(const char* key) const; const char* GetKey() const; //if value in object //get a value of a child element const char* GetStringOf(const char* child_key, const char* default_value = NULL) const; const char* GetStringOf(size_t child_index, const char* default_value = NULL) const; scalar GetFloatOf(const char* child_key, scalar default_value = 0) const; scalar GetFloatOf(size_t child_index, scalar default_value = 0) const; int GetIntOf(const char* child_key, int default_value = 0) const; int GetIntOf(size_t child_index, int default_value = 0) const; bool GetBoolOf(const char* child_key) const; bool GetBoolOf(size_t child_index) const; ZL_Json operator()(size_t index) const { return GetChild(index); } //get nth child ZL_Json operator[](const char* key); //get/create object key-value ZL_Json Add(); //add element to array void SetString(const char* NewString); void SetFloat(scalar NewFloat); void SetInt(int NewInt); void SetBool(bool NewBool); void SetNull(); void SetReference(const ZL_Json &source); void SetKey(const char* NewKey); Iterator Erase(Iterator it); bool Erase(const char* key); //erases only the first matching object key bool Erase(const ZL_Json &child); bool EraseAt(size_t index); void Clear(); //only clears array/object, use SetNull otherwise //return json formatted string ZL_String ToString(bool PrettyPrint = true) const; operator ZL_String () const { return ToString(); } //for C++11 range-based for loops Iterator begin() const { return GetIterator(); } Iterator end() const { Iterator it = GetIterator(); it.cursor = it.end; return it; } private: struct ZL_JSON_Impl* impl; ZL_Json(struct ZL_JSON_Impl*); }; //XML format parser and writer struct ZL_Xml { ZL_Xml(); ZL_Xml(const ZL_File &file); ZL_Xml(const ZL_String &xml); ~ZL_Xml(); ZL_Xml(const ZL_Xml &source); ZL_Xml &operator =(const ZL_Xml &source); bool operator!() const { return (impl==NULL); } bool operator==(const ZL_Xml &b) const { return (impl==b.impl); } bool operator!=(const ZL_Xml &b) const { return (impl!=b.impl); } ZL_Xml AddChild(ZL_Xml &Child); void AddChild(ZL_Xml *pChild); ZL_Xml AddChild(const ZL_String& name); void RemoveChild(const ZL_Xml *pChild); void RemoveChildren(const ZL_String& name); const ZL_String& GetName() const; void SetName(const ZL_String& newname); const ZL_String& GetText() const; void SetText(const ZL_String& newtext); ZL_String ToString() const; operator ZL_String () const { return ToString(); } void SetParameter(const ZL_String &name, const ZL_String &paramval = ZL_String::EmptyString); void RemoveParameter(const ZL_String &name); bool HasParameter(const ZL_String &name) const; std::map<ZL_String, ZL_String>& GetParameters(); std::vector<ZL_Xml> GetChildren() const; std::vector<ZL_Xml> GetChildrenByName(const ZL_String &name) const; ZL_String& operator[](const ZL_String &paramname) const; std::allocator<ZL_String>::reference operator[](const ZL_String &paramname); ZL_Xml operator()(const ZL_String &childname); private: struct ZL_Xml_Impl* impl; ZL_Xml(struct ZL_Xml_Impl*); }; //Manages Base64 encoding and decoding struct ZL_Base64 { //Encode a buffer to a string base64 encoded static ZL_String Encode(const void* InputBuffer, size_t BufSize); //Decode a string base64 encoded into a vector and return length of decoded data static size_t Decode(const ZL_String& Base64Data, std::vector<unsigned char>& output); //Decode a string base64 encoded into a given buffer, returned length of decoded data will be of max BufSize static size_t Decode(const ZL_String& Base64Data, void* OutputBuffer, size_t BufSize); //Compute maximum possible size of decoded base64 stream (actual decoded might be 1 or 2 bytes smaller) static size_t DecodedMaxSize(size_t EncodedSize); //Test if a string is well Base64 encoded static bool IsBase64(const ZL_String& Base64Data); }; //Data compression struct ZL_Compression { enum { NO_COMPRESSION = 0, BEST_SPEED = 1, BEST_COMPRESSION = 9, DEFAULT_COMPRESSION = 6 }; //Compress data and append it to an automatically sized output vector and return the compressed size (if ReserveMaxCompressSize is false, multiple re-allocations might be made) static size_t Compress(const void* DecompressedBuffer, size_t DecompressedSize, std::vector<unsigned char>& Output, int Level = DEFAULT_COMPRESSION, bool ReserveMaxCompressSize = false); static inline size_t Compress(const std::vector<unsigned char>& Decompressed, std::vector<unsigned char>& Output, int Level = DEFAULT_COMPRESSION, bool ReserveMaxCompressSize = false) { return Compress((Decompressed.empty() ? NULL : &Decompressed[0]), Decompressed.size(), Output, Level, ReserveMaxCompressSize); } //Returns the upper bound on the amount of data that could be generated by calling Compress static size_t CompressMaxSize(size_t DecompressedSize); //Compress data into a fixed size buffer and returns true if the given buffer was large enough (CompressedSize will be modified to actual size) static bool Compress(const void* DecompressedBuffer, size_t DecompressedSize, const void* CompressedBuffer, size_t* CompressedSize, int Level = DEFAULT_COMPRESSION); //Decompress and append data to an automatically sized output vector and return size of output (if DecompressedSizeHint is not large enough, multiple re-allocations might be made) static size_t Decompress(const void* CompressedBuffer, size_t CompressedSize, std::vector<unsigned char>& Output, size_t DecompressedSizeHint = 0); static inline size_t Decompress(const std::vector<unsigned char>& Compressed, std::vector<unsigned char>& Output, size_t DecompressedSizeHint = 0) { return Decompress((Compressed.empty() ? NULL : &Compressed[0]), Compressed.size(), Output, DecompressedSizeHint); } //Decompress data into a fixed size buffer and returns true if the given buffer was large enough (DecompressedSize will be modified to actual size) static bool Decompress(const void* CompressedBuffer, size_t CompressedSize, const void* DecompressedBuffer, size_t* DecompressedSize); }; //Calculate checksums struct ZL_Checksum { static unsigned int CRC32(const void* Data, size_t DataSize); static unsigned int Fast(const void* Data, size_t DataSize); static unsigned int Fast4(const void* Data, size_t DataSize); //DataSize must be 4 byte aligned static void SHA1(const void* Data, size_t DataSize, unsigned char OutResult[20]); }; inline size_t ZL_Hash(i64 x) { x *= 0xff51afd7ed558ccd; return (size_t)(x ^ (x >> 32)); } inline size_t ZL_Hash(u64 x) { x *= 0xff51afd7ed558ccd; return (size_t)(x ^ (x >> 32)); } inline size_t ZL_Hash(int x) { x *= 0x85ebca6b; return (size_t)(x ^ (x >> 12)); } inline size_t ZL_Hash(unsigned int x) { x *= 0x85ebca6b; return (size_t)(x ^ (x >> 12)); } #ifdef ZL_IS_64_BIT inline size_t ZL_Hash(const void* x) { return ZL_Hash((u64)x); ZL_STATIC_ASSERT(sizeof(x) == 8); } #else inline size_t ZL_Hash(const void* x) { return ZL_Hash((unsigned int)x); ZL_STATIC_ASSERT(sizeof(x) == 4); } #endif //A name that is a checksum of a string for easy lookups and comparison (does not keep the string itself, just the 4 byte checksum) struct ZL_NameID { ZL_NameID() : IDValue(0) {} ZL_NameID(const char* str) : IDValue(ZL_Checksum::CRC32(str, strlen(str))) {} ZL_NameID(const char* str, size_t len) : IDValue(ZL_Checksum::CRC32(str, len)) {} ZL_NameID(const ZL_String& str) : IDValue(ZL_Checksum::CRC32(str.c_str(), str.length())) {} bool operator!() const { return (IDValue == 0); } bool operator==(const ZL_NameID &b) const { return (IDValue==b.IDValue); } bool operator!=(const ZL_NameID &b) const { return (IDValue!=b.IDValue); } bool operator<(const ZL_NameID& b) const { return (IDValue<b.IDValue); } unsigned int IDValue; }; //A hash map, TKey needs a ZL_Hash function, a == operator, and a ! operator that returns true when memory is zeroed, both TKey and TVal need to be trivially copyable template <typename TKey, typename TVal> struct ZL_TMap { TVal NotFoundValue; ZL_TMap() : NotFoundValue(TVal()), len(0), cap(0), keys(NULL), vals(NULL) { #ifdef ZL_HAVE_TYPE_TRAITS ZL_STATIC_ASSERTMSG(std::is_trivially_copyable<TKey>::value, Map_key_type_needs_to_be_trivially_copyable); ZL_STATIC_ASSERTMSG(std::is_trivially_copyable<TVal>::value, Map_value_type_needs_to_be_trivially_copyable); #endif } ~ZL_TMap() { free(keys); free(vals); } TVal& Get(TKey key) { ZL_ASSERT(!!key); if (len == 0) return NotFoundValue; for (size_t i = (size_t)ZL_Hash(key);; i++) { if (keys[i &= cap - 1] == key) return vals[i]; if (!keys[i]) return NotFoundValue; } } TVal& Put(TKey key, const TVal& val) { ZL_ASSERT(!!key); if (2*len >= cap) Grow(2*cap); for (size_t i = (size_t)ZL_Hash(key);; i++) { if (!keys[i &= cap - 1]) { len++; keys[i] = key; return vals[i] = val; } if (keys[i] == key) return vals[i] = val; } } bool Remove(TKey key) { ZL_ASSERT(!!key); if (len == 0) return false; for (size_t i = (size_t)ZL_Hash(key);; i++) { if (keys[i &= cap - 1] == key) { keys[i] = 0; len--; return true; } if (!keys[i]) return false; } } void Clear() { memset(keys, len = 0, cap * sizeof(TKey)); } private: size_t len, cap; TKey *keys; TVal *vals; void Grow(size_t new_cap) { TKey *oldKeys = keys; TVal *oldVals = vals; size_t oldCap = cap; len = 0; cap = (new_cap < 16 ? 16 : new_cap); keys = (TKey *)calloc(cap, sizeof(TKey)); vals = (TVal *)malloc(cap * sizeof(TVal)); for (size_t i = 0; i < oldCap; i++) if (!!oldKeys[i]) Put(oldKeys[i], oldVals[i]); free(oldKeys); free(oldVals); } }; //A hash set, TKey needs to be trivially copyable, a ZL_Hash function and a == operator, and also needs a ! operator that returns true when memory is zeroed template <typename TKey> struct ZL_TSet { ZL_TSet() : len(0), cap(0), keys(NULL) { #ifdef ZL_HAVE_TYPE_TRAITS ZL_STATIC_ASSERTMSG(std::is_trivial<TKey>::value, Set_key_type_needs_to_be_trivially_copyable); #endif } ~ZL_TSet() { free(keys); } bool Get(TKey key) { ZL_ASSERT(!!key); if (len == 0) return false; for (size_t i = (size_t)ZL_Hash(key);; i++) { if (keys[i &= cap - 1] == key) return true; if (!keys[i]) return false; } } bool Put(TKey key) { ZL_ASSERT(!!key); if (2*len >= cap) Grow(2*cap); for (size_t i = (size_t)ZL_Hash(key);; i++) { if (!keys[i &= cap - 1]) { len++; keys[i] = key; return true; } if (keys[i] == key) return false; } } bool Remove(TKey key) { ZL_ASSERT(!!key); if (len == 0) return false; for (size_t i = (size_t)ZL_Hash(key);; i++) { if (keys[i &= cap - 1] == key) { keys[i] = 0; len--; return true; } if (!keys[i]) return false; } } void Clear() { memset(keys, len = 0, cap * sizeof(TKey)); } private: size_t len, cap; TKey *keys; void Grow(size_t new_cap) { TKey *oldKeys = keys; size_t oldCap = cap; len = 0; cap = (new_cap < 16 ? 16 : new_cap); keys = (TKey *)calloc(cap, sizeof(TKey)); for (size_t i = 0; i < oldCap; i++) if (!!oldKeys[i]) Put(oldKeys[i]); free(oldKeys); } }; #endif //__ZL_DATA__
39.933511
316
0.700699
[ "object", "vector" ]
aa7c59562c83c7b404d0c821959f87f77f862aa9
4,643
c
C
Projeto/src/Object.c
lellisls/CG-CatAndDog
c89a24fc5bcd302e6295695f6ba0414e70039c86
[ "MIT" ]
null
null
null
Projeto/src/Object.c
lellisls/CG-CatAndDog
c89a24fc5bcd302e6295695f6ba0414e70039c86
[ "MIT" ]
null
null
null
Projeto/src/Object.c
lellisls/CG-CatAndDog
c89a24fc5bcd302e6295695f6ba0414e70039c86
[ "MIT" ]
null
null
null
#include "../inc/Object.h" #include "stdio.h" #include "math.h" PObject CreateObject(int nVertex, int nSlices) { PObject obj = (PObject) malloc(sizeof(TObject)); obj->currentSlice = 0; obj->currentVertex = 0; obj->nVertex = nVertex; obj->nSlices = nSlices; obj->sliceCtr = ZeroPt3D(); obj->polygon = (struct sPt3D**) malloc(nSlices * sizeof(struct sPt3D*)); int slice; for (slice = 0; slice < nSlices; ++slice) obj->polygon[slice] = (struct sPt3D*) malloc(nVertex * sizeof(struct sPt3D)); resetTransformMatrix(); return obj; } void AddVertex(PObject obj, GLfloat x, GLfloat y) { if (obj->currentVertex == obj->nVertex) { printf("ERROR: In Object.c at function AddVertex: Cannot add Vertex, currentVertex is out of bounds!\n"); exit(1); } obj->polygon[0][ obj->currentVertex ].x = x; obj->polygon[0][ obj->currentVertex ].y = y; obj->polygon[0][ obj->currentVertex ].z = 0.0f; obj->currentVertex ++; } void Extrude(PObject obj) { if (obj->currentSlice == obj->nSlices) { printf("ERROR: In Object.c at function Extrude: Cannot extrude, currentSlice is out of bounds!\n"); exit(1); } obj->currentSlice ++; int vtx; for (vtx = 0; vtx < obj->currentVertex; ++vtx) { Pt3DTransform(&(obj->polygon[obj->currentSlice - 1][ vtx ])); obj->polygon[obj->currentSlice][ vtx ].x = obj->polygon[obj->currentSlice - 1][ vtx ].x; obj->polygon[obj->currentSlice][ vtx ].y = obj->polygon[obj->currentSlice - 1][ vtx ].y; obj->polygon[obj->currentSlice][ vtx ].z = obj->polygon[obj->currentSlice - 1][ vtx ].z; } resetTransformMatrix(); } void TranslateSlice(PObject obj, GLfloat dx, GLfloat dy, GLfloat dz) { translate3D(dx, dy, dz); obj->sliceCtr->x += dx; obj->sliceCtr->y += dy; obj->sliceCtr->z += dz; } void TranslateSlice2(PObject obj, GLfloat dx, GLfloat dy, GLfloat dz) { translate3D(dx, dy, dz); obj->sliceCtr->x += 0; } void ScaleSlice(PObject obj, GLfloat sx, GLfloat sy) { scale3D(sx, sy, 1, obj->sliceCtr); } void RotateSlice(PObject obj, GLfloat ax, GLfloat ay, GLfloat az) { Pt3D p1 = CreatePt3D(obj->sliceCtr->x, obj->sliceCtr->y, obj->sliceCtr->z); Pt3D p2 = CreatePt3D(obj->sliceCtr->x, obj->sliceCtr->y, obj->sliceCtr->z + 1); Pt3D p3 = CreatePt3D(obj->sliceCtr->x, obj->sliceCtr->y, obj->sliceCtr->z); Pt3D p4 = CreatePt3D(obj->sliceCtr->x, obj->sliceCtr->y + 1, obj->sliceCtr->z); Pt3D p5 = CreatePt3D(obj->sliceCtr->x, obj->sliceCtr->y, obj->sliceCtr->z); Pt3D p6 = CreatePt3D(obj->sliceCtr->x + 1, obj->sliceCtr->y, obj->sliceCtr->z); rotate3Dv(p1, p2, ax); rotate3Dv(p3, p4, ay); rotate3Dv(p5, p6, az); freePt3D(p1); freePt3D(p2); freePt3D(p3); freePt3D(p4); freePt3D(p5); freePt3D(p6); } void FinalizeObject(PObject obj) { int vtx; for (vtx = 0; vtx < obj->currentVertex; ++vtx) Pt3DTransform(&(obj->polygon[obj->currentSlice][ vtx ])); resetTransformMatrix(); } void DrawObject(PObject obj, int format) { glPushMatrix(); int slice, vtx; glBegin(format); for (vtx = 0; vtx < obj->currentVertex; ++vtx) { Pt3D pt = &(obj->polygon[0][vtx]); glVertex3d(pt->x, pt->y, pt->z); } glEnd(); glBegin(format); for (vtx = 0; vtx < obj->currentVertex; ++vtx) { Pt3D pt = &(obj->polygon[obj->currentSlice][vtx]); glVertex3d(pt->x, pt->y, pt->z); } glEnd(); for (vtx = 0; vtx < obj->currentVertex - 1; ++vtx) { for (slice = 0; slice < obj->currentSlice; ++slice) { glBegin(format); Pt3D pt = &(obj->polygon[slice][vtx]); glVertex3d(pt->x, pt->y, pt->z); pt = &(obj->polygon[slice + 1][vtx]); glVertex3d(pt->x, pt->y, pt->z); pt = &(obj->polygon[slice + 1][vtx + 1]); glVertex3d(pt->x, pt->y, pt->z); pt = &(obj->polygon[slice][vtx + 1]); glVertex3d(pt->x, pt->y, pt->z); glEnd(); } } glPopMatrix(); } void freeObj(PObject obj) { int slice; for (slice = 0; slice < obj->currentSlice; ++slice) { free(obj->polygon[slice]); } free(obj->polygon); free(obj->sliceCtr); free(obj); } PObject CreateCircleObject(int nVertex, int nSlices) { PObject obj = CreateObject(nVertex + 1, nSlices); float angle, step = 360.0f / (float)nVertex; for (angle = 0.0f; angle <= 360.0f; angle += step) { float radian = angle / 180.0f * PI; AddVertex(obj, sin(radian), cos(radian)); } return obj; }
30.346405
113
0.588413
[ "object" ]
aa7c72d8bb5bc41b996fa52f91fa213ba515737c
12,764
h
C
templates/http-custom-cpp/{{ projectName }}/include/pistache/description.h
XieEDeHeiShou/funcraft
558dd0a61a6ce4b31aa941582b95d83588473152
[ "MIT" ]
724
2019-07-11T02:58:00.000Z
2022-02-09T06:17:22.000Z
templates/http-custom-cpp/{{ projectName }}/include/pistache/description.h
XieEDeHeiShou/funcraft
558dd0a61a6ce4b31aa941582b95d83588473152
[ "MIT" ]
548
2019-07-10T06:49:45.000Z
2022-02-13T05:16:57.000Z
templates/http-custom-cpp/{{ projectName }}/include/pistache/description.h
XieEDeHeiShou/funcraft
558dd0a61a6ce4b31aa941582b95d83588473152
[ "MIT" ]
118
2019-07-10T03:06:27.000Z
2022-02-12T06:01:28.000Z
/* Mathieu Stefani, 24 février 2016 An API description (reflection) mechanism that is based on Swagger */ #pragma once #include <cstdint> #include <string> #include <vector> #include <type_traits> #include <memory> #include <algorithm> #include <pistache/http_defs.h> #include <pistache/mime.h> #include <pistache/optional.h> #include <pistache/router.h> #include <pistache/iterator_adapter.h> namespace Pistache { namespace Rest { namespace Type { // Data Types #define DATA_TYPE \ TYPE(Integer, std::int32_t , "integer", "int32") \ TYPE(Long , std::int64_t , "integer", "int64") \ TYPE(Float , float , "number" , "float") \ TYPE(Double , double , "number" , "double") \ TYPE(String , std::string , "string" , "") \ TYPE(Byte , char , "string" , "byte") \ TYPE(Binary , std::vector<std::uint8_t>, "string" , "binary") \ TYPE(Bool , bool , "boolean", "") \ COMPLEX_TYPE(Date , "string", "date") \ COMPLEX_TYPE(Datetime, "string", "date-time") \ COMPLEX_TYPE(Password, "string", "password") \ COMPLEX_TYPE(Array , "array", "array") #define TYPE(rest, cpp, _, __) \ typedef cpp rest; #define COMPLEX_TYPE(rest, _, __) \ struct rest { }; DATA_TYPE #undef TYPE #undef COMPLEX_TYPE } // namespace Type #define SCHEMES \ SCHEME(Http , "http") \ SCHEME(Https, "https") \ SCHEME(Ws , "ws") \ SCHEME(Wss , "wss") \ enum class Scheme { #define SCHEME(e, _) e, SCHEMES #undef SCHEME }; const char* schemeString(Scheme scheme); namespace Schema { namespace Traits { template<typename DT> struct IsDataType : public std::false_type { }; #define TYPE(rest, _, __, ___) \ template<> struct IsDataType<Type::rest> : public std::true_type { }; #define COMPLEX_TYPE(rest, _, __) \ template<> struct IsDataType<Type::rest> : public std::true_type { }; DATA_TYPE #undef TYPE #undef COMPLEX_TYPE template<typename DT> struct DataTypeInfo; #define TYPE(rest, _, typeStr, formatStr) \ template<> struct DataTypeInfo<Type::rest> { \ static const char *typeName() { return typeStr; } \ static const char *format() { return formatStr; } \ }; #define COMPLEX_TYPE(rest, typeStr, formatStr) \ template<> struct DataTypeInfo<Type::rest> { \ static const char* typeName() { return typeStr; } \ static const char* format() { return formatStr; } \ }; DATA_TYPE #undef TYPE #undef COMPLEX_TYPE template<typename DT> struct DataTypeValidation { static bool validate(const std::string& ) { return true; } }; } // namespace Traits struct ProduceConsume { ProduceConsume() : produce() , consume() { } std::vector<Http::Mime::MediaType> produce; std::vector<Http::Mime::MediaType> consume; }; struct Contact { Contact(std::string name, std::string url, std::string email); std::string name; std::string url; std::string email; }; struct License { License(std::string name, std::string url); std::string name; std::string url; }; struct Info { Info(std::string title, std::string version, std::string description = ""); std::string title; std::string version; std::string description; std::string termsOfService; Optional<Contact> contact; Optional<License> license; }; struct InfoBuilder { InfoBuilder(Info* info); InfoBuilder& termsOfService(std::string value); InfoBuilder& contact(std::string name, std::string url, std::string email); InfoBuilder& license(std::string name, std::string url); private: Info *info_; }; struct DataType { virtual const char* typeName() const = 0; virtual const char* format() const = 0; virtual bool validate(const std::string& input) const = 0; virtual ~DataType() {} }; template<typename T> struct DataTypeT : public DataType { const char* typeName() const { return Traits::DataTypeInfo<T>::typeName(); } const char* format() const { return Traits::DataTypeInfo<T>::format(); } bool validate(const std::string& input) const { return Traits::DataTypeValidation<T>::validate(input); } virtual ~DataTypeT() {} }; template<typename T> std::unique_ptr<DataType> makeDataType() { static_assert(Traits::IsDataType<T>::value, "Unknown Data Type"); return std::unique_ptr<DataType>(new DataTypeT<T>()); } struct Parameter { Parameter( std::string name, std::string description); template<typename T, typename... Args> static Parameter create(Args&& ...args) { Parameter p(std::forward<Args>(args)...); p.type = makeDataType<T>(); return p; } std::string name; std::string description; bool required; std::shared_ptr<DataType> type; }; struct Response { Response(Http::Code statusCode, std::string description); Http::Code statusCode; std::string description; }; struct ResponseBuilder { ResponseBuilder(Http::Code statusCode, std::string description); operator Response() const { return response_; } private: Response response_; }; struct PathDecl { PathDecl(std::string value, Http::Method method); std::string value; Http::Method method; }; struct Path { Path(std::string value, Http::Method method, std::string description); std::string value; Http::Method method; std::string description; bool hidden; ProduceConsume pc; std::vector<Parameter> parameters; std::vector<Response> responses; Route::Handler handler; static std::string swaggerFormat(const std::string& path); bool isBound() const { return handler != nullptr; } }; class PathGroup { public: struct Group : public std::vector<Path> { bool isHidden() const { if (empty()) return false; return std::all_of(begin(), end(), [](const Path& path) { return path.hidden; }); } }; typedef std::unordered_map<std::string, Group> Map; typedef Map::iterator iterator; typedef Map::const_iterator const_iterator; typedef std::vector<Path>::iterator group_iterator; typedef FlatMapIteratorAdapter<Map> flat_iterator; enum class Format { Default, Swagger }; bool hasPath(const std::string& name, Http::Method method) const; bool hasPath(const Path& path) const; PathGroup() : groups_() { } Group paths(const std::string& name) const; Optional<Path> path(const std::string& name, Http::Method method) const; group_iterator add(Path path); template<typename... Args> group_iterator emplace(Args&& ...args) { return add(Path(std::forward<Args>(args)...)); } const_iterator begin() const; const_iterator end() const; flat_iterator flatBegin() const; flat_iterator flatEnd() const; Map groups() const { return groups_; } private: Map groups_; }; struct PathBuilder { PathBuilder(Path* path); template<typename... Mimes> PathBuilder& produces(Mimes... mimes) { Http::Mime::MediaType m[sizeof...(Mimes)] = { mimes... }; std::copy(std::begin(m), std::end(m), std::back_inserter(path_->pc.produce)); return *this; } template<typename... Mimes> PathBuilder& consumes(Mimes... mimes) { Http::Mime::MediaType m[sizeof...(Mimes)] = { mimes... }; std::copy(std::begin(m), std::end(m), std::back_inserter(path_->pc.consume)); return *this; } template<typename T> PathBuilder& parameter(std::string name, std::string description) { path_->parameters.push_back(Parameter::create<T>(std::move(name), std::move(description))); return *this; } PathBuilder& response(Http::Code statusCode, std::string description) { path_->responses.push_back(Response(statusCode, std::move(description))); return *this; } PathBuilder& response(Response response) { path_->responses.push_back(std::move(response)); return *this; } /* @CodeDup: should re-use Routes::bind */ template<typename Result, typename Cls, typename... Args, typename Obj> PathBuilder& bind(Result (Cls::*func)(Args...), Obj obj) { #define CALL_MEMBER_FN(obj, pmf) ((obj)->*(pmf)) path_->handler = [=](const Rest::Request& request, Http::ResponseWriter response) { CALL_MEMBER_FN(obj, func)(request, std::move(response)); return Route::Result::Ok; }; #undef CALL_MEMBER_FN return *this; } template<typename Result, typename... Args> PathBuilder& bind(Result (*func)(Args...)) { path_->handler = [=](const Rest::Request& request, Http::ResponseWriter response) { func(request, std::move(response)); return Route::Result::Ok; }; return *this; } PathBuilder& hide(bool value = true) { path_->hidden = value; return *this; } private: Path* path_; }; struct SubPath { SubPath(std::string prefix, PathGroup* paths); PathBuilder route(std::string name, Http::Method method, std::string description = ""); PathBuilder route(PathDecl fragment, std::string description = ""); SubPath path(std::string prefix); template<typename T> void parameter(std::string name, std::string description) { parameters.push_back(Parameter::create<T>(std::move(name), std::move(description))); } std::string prefix; std::vector<Parameter> parameters; PathGroup* paths; }; } // namespace Schema class Description { public: Description(std::string title, std::string version, std::string description = ""); Schema::InfoBuilder info(); Description& host(std::string value); Description& basePath(std::string value); template<typename... Schemes> Description& schemes(Schemes... _schemes) { Scheme s[sizeof...(Schemes)] = { _schemes... }; std::copy(std::begin(s), std::end(s), std::back_inserter(schemes_)); return *this; } template<typename... Mimes> Description& produces(Mimes... mimes) { Http::Mime::MediaType m[sizeof...(Mimes)] = { mimes... }; std::copy(std::begin(m), std::end(m), std::back_inserter(pc.produce)); return *this; } template<typename... Mimes> Description& consumes(Mimes... mimes) { Http::Mime::MediaType m[sizeof...(Mimes)] = { mimes... }; std::copy(std::begin(m), std::end(m), std::back_inserter(pc.consume)); return *this; } Schema::PathDecl options(std::string name); Schema::PathDecl get(std::string name); Schema::PathDecl post(std::string name); Schema::PathDecl head(std::string name); Schema::PathDecl put(std::string name); Schema::PathDecl patch(std::string name); Schema::PathDecl del(std::string name); Schema::PathDecl trace(std::string name); Schema::PathDecl connect(std::string name); Schema::SubPath path(std::string name); Schema::PathBuilder route(std::string name, Http::Method method, std::string description = ""); Schema::PathBuilder route(Schema::PathDecl fragment, std::string description = ""); Schema::ResponseBuilder response(Http::Code statusCode, std::string description); Schema::Info rawInfo() const { return info_; } std::string rawHost() const { return host_; } std::string rawBasePath() const { return basePath_; } std::vector<Scheme> rawSchemes() const { return schemes_; } Schema::ProduceConsume rawPC() const { return pc; } Schema::PathGroup rawPaths() const { return paths_; } private: Schema::Info info_; std::string host_; std::string basePath_; std::vector<Scheme> schemes_; Schema::ProduceConsume pc; Schema::PathGroup paths_; }; class Swagger { public: Swagger(const Description& description) : description_(description) , uiPath_() , uiDirectory_() , apiPath_() , serializer_() { } typedef std::function<std::string (const Description&)> Serializer; Swagger& uiPath(std::string path); Swagger& uiDirectory(std::string dir); Swagger& apiPath(std::string path); Swagger& serializer(Serializer serialize); void install(Rest::Router& router); private: Description description_; std::string uiPath_; std::string uiDirectory_; std::string apiPath_; Serializer serializer_; }; } // namespace Rest } // namespace Pistache
26.75891
108
0.62927
[ "vector" ]
aa876fcfad82feec149ac9892e2b1b50268e9b67
2,297
h
C
inc/guide/grid.h
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
2
2017-06-16T19:27:55.000Z
2020-04-05T02:18:07.000Z
inc/guide/grid.h
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
null
null
null
inc/guide/grid.h
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
2
2019-09-03T19:23:20.000Z
2020-08-29T21:46:17.000Z
#ifndef T_GRID_H #define T_GRID_H //------------------------------------------------------------------- /** @class TGrid @brief This class allows us to create backgrounds for every single control that gui is containing. The most powerful feature of the class is that skin creators will not be constrained when designing the look of their controls, because of the smart way a grid is created. A control could contains multiple grids to reflect their different states. For example, a button could be pressed, highlighted, disabled etc. A grid is made by rows, and every row is created from columns. @see <code>TGridRow</code> @see <code>TGridColumn</code> @author Razvan Predescu (2004) */ //------------------------------------------------------------------- #undef N_DEFINES #define N_DEFINES TGrid #include "guide/ndefdllclass.h" #ifndef T_GRIDROW_H #include "guide/gridrow.h" #endif typedef stl::list<TGridRow*> TGridRowsList; //------------------------------------------------------------------- class N_PUBLIC TGrid : public TObject { int Width; int Height; TString Name; TGridRowsList Rows; public: TGrid(); virtual ~TGrid(); virtual void Assign(TObject* Object); virtual void ApplySkin(TObject* Object); virtual void ParseSkin(TiXmlElement* XmlElement); void SetName(const char* AName); TString GetName(void) const { return Name; } void SetWidth(int Value); int GetWidth(void) const { return Width; } void SetHeight(int Value); int GetHeight(void) const { return Height; } /// Get a row from Index position TGridRow* GetRow(int Index); /// Get rows list TGridRowsList* GetRows(void) { return &Rows; } /// Insert a row at specified position void InsertRow(int Index, TGridRow* Item); /// Append a row void AppendRow(TGridRow* Item); /// Remove a row by reference void RemoveRow(TGridRow* Item); /// Remove a row by index void RemoveRow(int Index); /// Returns the row's index int IndexOf(TGridRow* Item); /// Returns the number of rows int Count(void) const; /// Remove all the rows void Clear(void); /// Paint the grid void Paint(TCanvas* Canvas); /// Realign the rows void RealignRows(void); private: TGridRow* GetLastAlignedRow(TAlignRow Value); }; //------------------------------------------------------------------- #endif
27.345238
69
0.648237
[ "object" ]
aa87fc470649bfb6b6ee1b3ae2ed5d419a176aee
9,020
h
C
MSVC/14.24.28314/atlmfc/include/afxwinforms.h
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
MSVC/14.24.28314/atlmfc/include/afxwinforms.h
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
MSVC/14.24.28314/atlmfc/include/afxwinforms.h
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #ifndef __AFX_WINFORMS_H__ #define __AFX_WINFORMS_H__ #ifndef __cplusplus #error MFC requires C++ compilation (use a .cpp suffix) #endif #ifndef __cplusplus_cli #error MFC WinForms support requires /clr (does not support oldSyntax) #endif #ifndef _AFXDLL #error MFC WinForms support requires MFC dll version. #endif #pragma once #using <mscorlib.dll> #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> #using <mfcmifc80.dll> #ifdef BUILD_MFCM #define AFX_MFCM_EXPORT __declspec(dllexport) #else #define AFX_MFCM_EXPORT __declspec(dllimport) #ifndef _MFC_FILENAME_VER #define _MFC_FILENAME_VER "140" #endif #ifndef _MFC_FILENAME_VER_DOT #define _MFC_FILENAME_VER_DOT "14.0" #endif #ifndef _UNICODE #ifdef _DEBUG #pragma comment(lib, "mfcm" _MFC_FILENAME_VER "d.lib") #else #pragma comment(lib, "mfcm" _MFC_FILENAME_VER ".lib") #endif #else #ifdef _DEBUG #pragma comment(lib, "mfcm" _MFC_FILENAME_VER "ud.lib") #else #pragma comment(lib, "mfcm" _MFC_FILENAME_VER "u.lib") #endif #endif #endif //BUILD_MFCM #include <vcclr.h> #include <msclr/event.h> #include <afxdisp.h> #include <afxpriv.h> namespace Microsoft { namespace VisualC { namespace MFC { /*============================================================================*/ // CWin32Window - Win32 HWND wrapper implementing IWin32Window. Used to pass // Parent HWNDs from MFC to WinForms. // public ref class CWin32Window : public System::Windows::Forms::IWin32Window { const HWND m_hWnd; public: CWin32Window(HWND hWnd) : m_hWnd(hWnd){} property System::IntPtr Handle { virtual System::IntPtr get() { return static_cast<System::IntPtr>(m_hWnd); } } }; /*============================================================================*/ // CControlCreationInfoEx - Inits and Cleanup CControlCreationInfo struct // GCHandle information. // class CControlCreationInfoEx : public CControlCreationInfo { public: typedef System::Runtime::InteropServices::GCHandle GCHandle; CControlCreationInfoEx(); void Init(System::Object^ p,HandleKind hk); ~CControlCreationInfoEx(); }; /*============================================================================*/ // Notification from __gc Helper class. __interface IHandleEvents { void OnHandleCreated(System::Object^ o, System::EventArgs^ e); void OnHandleDestroyed(System::Object^ o, System::EventArgs^ e); }; public ref class CWinFormsEventsHelper { public: CWinFormsEventsHelper(); property System::Windows::Forms::Control^ Control { System::Windows::Forms::Control^ get(); void set(System::Windows::Forms::Control^ pControl); } void Advise(IHandleEvents* pSink); void Unadvise(IHandleEvents* pSink); private: void OnHandleCreated( System::Object^ o, System::EventArgs^ args); void OnHandleDestroyed( System::Object^ o, System::EventArgs^ args); public: System::Windows::Forms::Control^ m_pControl; IHandleEvents* m_pSink; }; /*============================================================================*/ // CWinFormsControlSite - overrides COleControlSite when the ActiveX is a // WinForm control. class CWinFormsControlSite : public COleControlSite,public IHandleEvents { public: CWinFormsControlSite(COleControlContainer* pCtrlCont); ~CWinFormsControlSite(); virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg); virtual void GetProperty(DISPID dwDispID, VARTYPE vtProp, void* pvProp) const; void SetControlEnabled(bool bEnable); virtual void SetPropertyV(DISPID dwDispID, VARTYPE vtProp, va_list argList); virtual DWORD GetStyle() const; virtual HRESULT CreateOrLoad(const CControlCreationInfo& creationInfo); virtual HRESULT CreateControlCommon(CWnd* pWndCtrl, REFCLSID clsid,const CControlCreationInfo& creationInfo, LPCTSTR lpszWindowName, DWORD dwStyle, const POINT* ppt, const SIZE* psize, UINT nID, CFile* pPersist, BOOL bStorage, BSTR bstrLicKey); void OnHandleCreatedHandler(); virtual void OnHandleCreated( gcroot<System::Object^> , gcroot<System::EventArgs^> ); virtual void OnHandleDestroyed( gcroot<System::Object^> , gcroot<System::EventArgs^> ); virtual void OnHandleCreated(System::Object^, System::EventArgs^); virtual void OnHandleDestroyed(System::Object^, System::EventArgs^); System::Windows::Forms::Control^ get_Control() const; gcroot<CWinFormsEventsHelper^> m_gcEventHelper; }; /*============================================================================*/ // CWinFormsControl // Provides the basic functionality for AX hosting of WinForms Control // template<class TManagedControl> class CWinFormsControl : public CWnd { public: CWinFormsControl(); inline TManagedControl^ GetControl() const; inline operator TManagedControl^() const; inline TManagedControl^ operator->() const; inline HWND GetControlHandle() const; inline BOOL CreateManagedControl(System::Type^ pType,DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, int nID); inline BOOL CreateManagedControl(typename TManagedControl^ pControl,DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, int nID); inline BOOL CreateManagedControl(DWORD dwStyle,const RECT& rect, CWnd* pParentWnd, int nID); /*============================================================================*/ //Purpose: Create a WinForms control and placing it on top // of a STATIC control, placed in Resource Editor as a place holder // for the .Net control. //Input: window styles, IDC_ of STATIC place holder, and Parent CWnd* //Return: TRUE if creation succeeded. /*============================================================================*/ inline BOOL CreateManagedControl(DWORD dwStyle,int nPlaceHolderID, CWnd* pParentWnd); //Creates a control of managed type. inline BOOL InternalCreateManagedControl(const CControlCreationInfo& info,DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, int nID); }; /*============================================================================*/ // CWinFormsView // Provides generic functionality for AX hosting of WinForms Control as an MFC View // class CWinFormsView : public CView { DECLARE_DYNAMIC(CWinFormsView) public: CWinFormsView(System::Type^ pManagedViewType); System::Windows::Forms::Control^ GetControl() const; operator System::Windows::Forms::Control^() const; protected: virtual void OnInitialUpdate(); virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView); virtual BOOL PreTranslateMessage(MSG* pMsg); BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); protected: virtual void OnDraw(CDC*) { }; afx_msg void OnSize(UINT nType, int cx, int cy); gcroot<System::Type^> m_pManagedViewType; private: CWinFormsControl<System::Windows::Forms::Control> m_control; gcroot<System::Object^> m_CmdSource; DECLARE_MESSAGE_MAP() }; #define IDC_WINFRMCTRL_DIALOG 45002 // // The WinForms Form wrapper // template <typename TManagedControl> class CWinFormsDialog : public CDialog { public: enum { IDD = AFX_IDD_EMPTYDIALOG }; public: CWinFormsDialog(UINT nIDTemplate = IDD, CWnd* pParentWnd = NULL); virtual BOOL OnInitDialog(); // // The .Net Control interface accessors // inline TManagedControl^ GetControl() const; inline operator TManagedControl^() const throw(); inline TManagedControl^ operator->() const throw(); inline HWND GetControlHandle() const throw(); protected: CWinFormsControl<TManagedControl> m_control; afx_msg void OnSize(UINT nType, int cx, int cy); private: DECLARE_MESSAGE_MAP() gcroot<TManagedControl^> m_pWFControl; }; template <typename T> void DDX_ManagedControl(CDataExchange* pDX, int nIDC,CWinFormsControl<T>& control); namespace Internal { using Microsoft::VisualC::MFC::CControlCreationInfoEx; using Microsoft::VisualC::MFC::CWin32Window; using Microsoft::VisualC::MFC::IHandleEvents; using Microsoft::VisualC::MFC::CWinFormsEventsHelper; } } //namespace MFC } //VisualC } //Microsoft using Microsoft::VisualC::MFC::CWinFormsView; using Microsoft::VisualC::MFC::CWinFormsDialog; using Microsoft::VisualC::MFC::CWinFormsControl; using Microsoft::VisualC::MFC::CWinFormsControlSite; using Microsoft::VisualC::MFC::DDX_ManagedControl; #ifdef _AFX_ENABLE_INLINES #define _AFXWIN_INLINE AFX_INLINE #endif #include <afxwinforms.inl> #endif // __AFX_WINFORMS_H__
26.845238
109
0.712417
[ "object" ]
aa8c339cc0556f01345243caf022ee02b471e3a3
3,491
h
C
ml/tensor_view.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
ml/tensor_view.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
ml/tensor_view.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ml/mojom/tensor.mojom.h" #include <vector> #ifndef ML_TENSOR_VIEW_H_ #define ML_TENSOR_VIEW_H_ namespace ml { // Provides basic error checking and a common interface for mojom::TensorPtrs of // any underlying data type. // // Basic usage of a TensorView is as follows. // Non-const view: // TensorPtr ptr; // TensorView<double> view(ptr); // view.Allocate(); // Creates a FloatList in ptr. // view.GetValues().push_back(0.5); // Adds first elem of FloatList in ptr. // // Const view: // const TensorPtr ptr = ... // const TensorView<double> view(ptr); // double v = view.GetValues()[0]; // Gets first elem of FloatList in ptr. // // Type-specific funtionality is implemented in template specializations below. template <typename T> class TensorView { public: // The given tensor must outlive this view. explicit TensorView( const chromeos::machine_learning::mojom::TensorPtr& tensor) : tensor_(tensor) {} // Return the shape array of the tensor. std::vector<int64_t>& GetShape() { return tensor_->shape->value; } const std::vector<int64_t>& GetShape() const { return tensor_->shape->value; } // Return the value array of the tensor. // Defined only in each specialization for T. std::vector<T>& GetValues(); const std::vector<T>& GetValues() const { return const_cast<TensorView<T>*>(this)->GetValues(); } // Return true if the tensor contains values of the correct type. Should be // specialized for each tensor data type T. bool IsValidType() const { return false; } // Return true if the tensor is in a valid format (i.e. valid dimensions and // the right number of entries for its shape). bool IsValidFormat() const { const std::vector<int64_t>& dims = GetShape(); // Special case: no entries. if (dims.empty()) return GetValues().empty(); // Otherwise, values size should be the product of all dimension lengths. int64_t num_entries = 1; for (const int64_t dim : dims) { if (dim < 0) return false; num_entries *= dim; } return num_entries == GetValues().size(); } // Allocate memory for the members of the tensor object (including values). void Allocate() { tensor_->shape = chromeos::machine_learning::mojom::Int64List::New(); // TODO(hidehiko): assigning std::vector<>() to `value` is unneeded // on libmojo uprev. Remove them after the uprev. tensor_->shape->value = std::vector<int64_t>(); tensor_->data = chromeos::machine_learning::mojom::ValueList::New(); AllocateValues(); } private: // Allocate memory for the value array of this tensor. // Defined only in each specialization for T. void AllocateValues(); const chromeos::machine_learning::mojom::TensorPtr& tensor_; DISALLOW_COPY_AND_ASSIGN(TensorView); }; // Specializations for int tensors. template <> std::vector<int64_t>& TensorView<int64_t>::GetValues(); template <> bool TensorView<int64_t>::IsValidType() const; template <> void TensorView<int64_t>::AllocateValues(); // Specializations for float tensors. template <> std::vector<double>& TensorView<double>::GetValues(); template <> bool TensorView<double>::IsValidType() const; template <> void TensorView<double>::AllocateValues(); } // namespace ml #endif // ML_TENSOR_VIEW_H_
30.622807
80
0.693784
[ "object", "shape", "vector" ]
aa8da254a365c2b007838cf96bf02bbdb45c1fc7
776
h
C
language-extensions/python/include/Common.h
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
82
2019-05-24T00:36:57.000Z
2022-02-21T23:51:46.000Z
language-extensions/python/include/Common.h
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
20
2019-07-05T06:12:28.000Z
2022-03-31T20:48:30.000Z
language-extensions/python/include/Common.h
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
35
2019-05-24T01:44:07.000Z
2022-02-28T13:29:44.000Z
//************************************************************************************************* // Copyright (C) Microsoft Corporation. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // // @File: Common.h // // Purpose: // Common headers for extension // //************************************************************************************************* #pragma once #ifdef _WIN64 #include <windows.h> #endif #include <string> #include <iostream> #include <exception> #include <stdio.h> #include <vector> #include <sql.h> #include <sqlext.h> #include <sqltypes.h> #include <boost/python.hpp> #include <boost/python/numpy.hpp>
25.032258
100
0.503866
[ "vector" ]
aa91295197957620ece36b2d48e41fc2cda573c1
20,928
h
C
sound/pci/echoaudio/echoaudio_dsp.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
sound/pci/echoaudio/echoaudio_dsp.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
sound/pci/echoaudio/echoaudio_dsp.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/**************************************************************************** Copyright Echo Digital Audio Corporation (c) 1998 - 2004 All rights reserved www.echoaudio.com This file is part of Echo Digital Audio's generic driver library. Echo Digital Audio's generic driver 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ************************************************************************* Translation from C++ and adaptation for use in ALSA-Driver were made by Giuliano Pochini <pochini@shiny.it> ****************************************************************************/ #ifndef _ECHO_DSP_ #define _ECHO_DSP_ /**** Echogals: Darla20, Gina20, Layla20, and Darla24 ****/ #if defined(ECHOGALS_FAMILY) #define NUM_ASIC_TESTS 5 #define READ_DSP_TIMEOUT 1000000L /* one second */ /**** Echo24: Gina24, Layla24, Mona, Mia, Mia-midi ****/ #elif defined(ECHO24_FAMILY) #define DSP_56361 /* Some Echo24 cards use the 56361 DSP */ #define READ_DSP_TIMEOUT 100000L /* .1 second */ /**** 3G: Gina3G, Layla3G ****/ #elif defined(ECHO3G_FAMILY) #define DSP_56361 #define READ_DSP_TIMEOUT 100000L /* .1 second */ #define MIN_MTC_1X_RATE 32000 /**** Indigo: Indigo, Indigo IO, Indigo DJ ****/ #elif defined(INDIGO_FAMILY) #define DSP_56361 #define READ_DSP_TIMEOUT 100000L /* .1 second */ #else #error No family is defined #endif /* * * Max inputs and outputs * */ #define DSP_MAXAUDIOINPUTS 16 /* Max audio input channels */ #define DSP_MAXAUDIOOUTPUTS 16 /* Max audio output channels */ #define DSP_MAXPIPES 32 /* Max total pipes (input + output) */ /* * * These are the offsets for the memory-mapped DSP registers; the DSP base * address is treated as the start of a u32 array. */ #define CHI32_CONTROL_REG 4 #define CHI32_STATUS_REG 5 #define CHI32_VECTOR_REG 6 #define CHI32_DATA_REG 7 /* * * Interesting bits within the DSP registers * */ #define CHI32_VECTOR_BUSY 0x00000001 #define CHI32_STATUS_REG_HF3 0x00000008 #define CHI32_STATUS_REG_HF4 0x00000010 #define CHI32_STATUS_REG_HF5 0x00000020 #define CHI32_STATUS_HOST_READ_FULL 0x00000004 #define CHI32_STATUS_HOST_WRITE_EMPTY 0x00000002 #define CHI32_STATUS_IRQ 0x00000040 /* * * DSP commands sent via slave mode; these are sent to the DSP by write_dsp() * */ #define DSP_FNC_SET_COMMPAGE_ADDR 0x02 #define DSP_FNC_LOAD_LAYLA_ASIC 0xa0 #define DSP_FNC_LOAD_GINA24_ASIC 0xa0 #define DSP_FNC_LOAD_MONA_PCI_CARD_ASIC 0xa0 #define DSP_FNC_LOAD_LAYLA24_PCI_CARD_ASIC 0xa0 #define DSP_FNC_LOAD_MONA_EXTERNAL_ASIC 0xa1 #define DSP_FNC_LOAD_LAYLA24_EXTERNAL_ASIC 0xa1 #define DSP_FNC_LOAD_3G_ASIC 0xa0 /* * * Defines to handle the MIDI input state engine; these are used to properly * extract MIDI time code bytes and their timestamps from the MIDI input stream. * */ #define MIDI_IN_STATE_NORMAL 0 #define MIDI_IN_STATE_TS_HIGH 1 #define MIDI_IN_STATE_TS_LOW 2 #define MIDI_IN_STATE_F1_DATA 3 #define MIDI_IN_SKIP_DATA (-1) /*---------------------------------------------------------------------------- Setting the sample rates on Layla24 is somewhat schizophrenic. For standard rates, it works exactly like Mona and Gina24. That is, for 8, 11.025, 16, 22.05, 32, 44.1, 48, 88.2, and 96 kHz, you just set the appropriate bits in the control register and write the control register. In order to support MIDI time code sync (and possibly SMPTE LTC sync in the future), Layla24 also has "continuous sample rate mode". In this mode, Layla24 can generate any sample rate between 25 and 50 kHz inclusive, or 50 to 100 kHz inclusive for double speed mode. To use continuous mode: -Set the clock select bits in the control register to 0xe (see the #define below) -Set double-speed mode if you want to use sample rates above 50 kHz -Write the control register as you would normally -Now, you need to set the frequency register. First, you need to determine the value for the frequency register. This is given by the following formula: frequency_reg = (LAYLA24_MAGIC_NUMBER / sample_rate) - 2 Note the #define below for the magic number -Wait for the DSP handshake -Write the frequency_reg value to the .SampleRate field of the comm page -Send the vector command SET_LAYLA24_FREQUENCY_REG (see vmonkey.h) Once you have set the control register up for continuous mode, you can just write the frequency register to change the sample rate. This could be used for MIDI time code sync. For MTC sync, the control register is set for continuous mode. The driver then just keeps writing the SET_LAYLA24_FREQUENCY_REG command. -----------------------------------------------------------------------------*/ #define LAYLA24_MAGIC_NUMBER 677376000 #define LAYLA24_CONTINUOUS_CLOCK 0x000e /* * * DSP vector commands * */ #define DSP_VC_RESET 0x80ff #ifndef DSP_56361 #define DSP_VC_ACK_INT 0x8073 #define DSP_VC_SET_VMIXER_GAIN 0x0000 /* Not used, only for compile */ #define DSP_VC_START_TRANSFER 0x0075 /* Handshke rqd. */ #define DSP_VC_METERS_ON 0x0079 #define DSP_VC_METERS_OFF 0x007b #define DSP_VC_UPDATE_OUTVOL 0x007d /* Handshke rqd. */ #define DSP_VC_UPDATE_INGAIN 0x007f /* Handshke rqd. */ #define DSP_VC_ADD_AUDIO_BUFFER 0x0081 /* Handshke rqd. */ #define DSP_VC_TEST_ASIC 0x00eb #define DSP_VC_UPDATE_CLOCKS 0x00ef /* Handshke rqd. */ #define DSP_VC_SET_LAYLA_SAMPLE_RATE 0x00f1 /* Handshke rqd. */ #define DSP_VC_SET_GD_AUDIO_STATE 0x00f1 /* Handshke rqd. */ #define DSP_VC_WRITE_CONTROL_REG 0x00f1 /* Handshke rqd. */ #define DSP_VC_MIDI_WRITE 0x00f5 /* Handshke rqd. */ #define DSP_VC_STOP_TRANSFER 0x00f7 /* Handshke rqd. */ #define DSP_VC_UPDATE_FLAGS 0x00fd /* Handshke rqd. */ #define DSP_VC_GO_COMATOSE 0x00f9 #else /* !DSP_56361 */ /* Vector commands for families that use either the 56301 or 56361 */ #define DSP_VC_ACK_INT 0x80F5 #define DSP_VC_SET_VMIXER_GAIN 0x00DB /* Handshke rqd. */ #define DSP_VC_START_TRANSFER 0x00DD /* Handshke rqd. */ #define DSP_VC_METERS_ON 0x00EF #define DSP_VC_METERS_OFF 0x00F1 #define DSP_VC_UPDATE_OUTVOL 0x00E3 /* Handshke rqd. */ #define DSP_VC_UPDATE_INGAIN 0x00E5 /* Handshke rqd. */ #define DSP_VC_ADD_AUDIO_BUFFER 0x00E1 /* Handshke rqd. */ #define DSP_VC_TEST_ASIC 0x00ED #define DSP_VC_UPDATE_CLOCKS 0x00E9 /* Handshke rqd. */ #define DSP_VC_SET_LAYLA24_FREQUENCY_REG 0x00E9 /* Handshke rqd. */ #define DSP_VC_SET_LAYLA_SAMPLE_RATE 0x00EB /* Handshke rqd. */ #define DSP_VC_SET_GD_AUDIO_STATE 0x00EB /* Handshke rqd. */ #define DSP_VC_WRITE_CONTROL_REG 0x00EB /* Handshke rqd. */ #define DSP_VC_MIDI_WRITE 0x00E7 /* Handshke rqd. */ #define DSP_VC_STOP_TRANSFER 0x00DF /* Handshke rqd. */ #define DSP_VC_UPDATE_FLAGS 0x00FB /* Handshke rqd. */ #define DSP_VC_GO_COMATOSE 0x00d9 #endif /* !DSP_56361 */ /* * * Timeouts * */ #define HANDSHAKE_TIMEOUT 20000 /* send_vector command timeout (20ms) */ #define VECTOR_BUSY_TIMEOUT 100000 /* 100ms */ #define MIDI_OUT_DELAY_USEC 2000 /* How long to wait after MIDI fills up */ /* * * Flags for .Flags field in the comm page * */ #define DSP_FLAG_MIDI_INPUT 0x0001 /* Enable MIDI input */ #define DSP_FLAG_SPDIF_NONAUDIO 0x0002 /* Sets the "non-audio" bit * in the S/PDIF out status * bits. Clear this flag for * audio data; * set it for AC3 or WMA or * some such */ #define DSP_FLAG_PROFESSIONAL_SPDIF 0x0008 /* 1 Professional, 0 Consumer */ /* * * Clock detect bits reported by the DSP for Gina20, Layla20, Darla24, and Mia * */ #define GLDM_CLOCK_DETECT_BIT_WORD 0x0002 #define GLDM_CLOCK_DETECT_BIT_SUPER 0x0004 #define GLDM_CLOCK_DETECT_BIT_SPDIF 0x0008 #define GLDM_CLOCK_DETECT_BIT_ESYNC 0x0010 /* * * Clock detect bits reported by the DSP for Gina24, Mona, and Layla24 * */ #define GML_CLOCK_DETECT_BIT_WORD96 0x0002 #define GML_CLOCK_DETECT_BIT_WORD48 0x0004 #define GML_CLOCK_DETECT_BIT_SPDIF48 0x0008 #define GML_CLOCK_DETECT_BIT_SPDIF96 0x0010 #define GML_CLOCK_DETECT_BIT_WORD (GML_CLOCK_DETECT_BIT_WORD96 | GML_CLOCK_DETECT_BIT_WORD48) #define GML_CLOCK_DETECT_BIT_SPDIF (GML_CLOCK_DETECT_BIT_SPDIF48 | GML_CLOCK_DETECT_BIT_SPDIF96) #define GML_CLOCK_DETECT_BIT_ESYNC 0x0020 #define GML_CLOCK_DETECT_BIT_ADAT 0x0040 /* * * Layla clock numbers to send to DSP * */ #define LAYLA20_CLOCK_INTERNAL 0 #define LAYLA20_CLOCK_SPDIF 1 #define LAYLA20_CLOCK_WORD 2 #define LAYLA20_CLOCK_SUPER 3 /* * * Gina/Darla clock states * */ #define GD_CLOCK_NOCHANGE 0 #define GD_CLOCK_44 1 #define GD_CLOCK_48 2 #define GD_CLOCK_SPDIFIN 3 #define GD_CLOCK_UNDEF 0xff /* * * Gina/Darla S/PDIF status bits * */ #define GD_SPDIF_STATUS_NOCHANGE 0 #define GD_SPDIF_STATUS_44 1 #define GD_SPDIF_STATUS_48 2 #define GD_SPDIF_STATUS_UNDEF 0xff /* * * Layla20 output clocks * */ #define LAYLA20_OUTPUT_CLOCK_SUPER 0 #define LAYLA20_OUTPUT_CLOCK_WORD 1 /**************************************************************************** Magic constants for the Darla24 hardware ****************************************************************************/ #define GD24_96000 0x0 #define GD24_48000 0x1 #define GD24_44100 0x2 #define GD24_32000 0x3 #define GD24_22050 0x4 #define GD24_16000 0x5 #define GD24_11025 0x6 #define GD24_8000 0x7 #define GD24_88200 0x8 #define GD24_EXT_SYNC 0x9 /* * * Return values from the DSP when ASIC is loaded * */ #define ASIC_ALREADY_LOADED 0x1 #define ASIC_NOT_LOADED 0x0 /* * * DSP Audio formats * * These are the audio formats that the DSP can transfer * via input and output pipes. LE means little-endian, * BE means big-endian. * * DSP_AUDIOFORM_MS_8 * * 8-bit mono unsigned samples. For playback, * mono data is duplicated out the left and right channels * of the output bus. The "MS" part of the name * means mono->stereo. * * DSP_AUDIOFORM_MS_16LE * * 16-bit signed little-endian mono samples. Playback works * like the previous code. * * DSP_AUDIOFORM_MS_24LE * * 24-bit signed little-endian mono samples. Data is packed * three bytes per sample; if you had two samples 0x112233 and 0x445566 * they would be stored in memory like this: 33 22 11 66 55 44. * * DSP_AUDIOFORM_MS_32LE * * 24-bit signed little-endian mono samples in a 32-bit * container. In other words, each sample is a 32-bit signed * integer, where the actual audio data is left-justified * in the 32 bits and only the 24 most significant bits are valid. * * DSP_AUDIOFORM_SS_8 * DSP_AUDIOFORM_SS_16LE * DSP_AUDIOFORM_SS_24LE * DSP_AUDIOFORM_SS_32LE * * Like the previous ones, except now with stereo interleaved * data. "SS" means stereo->stereo. * * DSP_AUDIOFORM_MM_32LE * * Similar to DSP_AUDIOFORM_MS_32LE, except that the mono * data is not duplicated out both the left and right outputs. * This mode is used by the ASIO driver. Here, "MM" means * mono->mono. * * DSP_AUDIOFORM_MM_32BE * * Just like DSP_AUDIOFORM_MM_32LE, but now the data is * in big-endian format. * */ #define DSP_AUDIOFORM_MS_8 0 /* 8 bit mono */ #define DSP_AUDIOFORM_MS_16LE 1 /* 16 bit mono */ #define DSP_AUDIOFORM_MS_24LE 2 /* 24 bit mono */ #define DSP_AUDIOFORM_MS_32LE 3 /* 32 bit mono */ #define DSP_AUDIOFORM_SS_8 4 /* 8 bit stereo */ #define DSP_AUDIOFORM_SS_16LE 5 /* 16 bit stereo */ #define DSP_AUDIOFORM_SS_24LE 6 /* 24 bit stereo */ #define DSP_AUDIOFORM_SS_32LE 7 /* 32 bit stereo */ #define DSP_AUDIOFORM_MM_32LE 8 /* 32 bit mono->mono little-endian */ #define DSP_AUDIOFORM_MM_32BE 9 /* 32 bit mono->mono big-endian */ #define DSP_AUDIOFORM_SS_32BE 10 /* 32 bit stereo big endian */ #define DSP_AUDIOFORM_INVALID 0xFF /* Invalid audio format */ /* * * Super-interleave is defined as interleaving by 4 or more. Darla20 and Gina20 * do not support super interleave. * * 16 bit, 24 bit, and 32 bit little endian samples are supported for super * interleave. The interleave factor must be even. 16 - way interleave is the * current maximum, so you can interleave by 4, 6, 8, 10, 12, 14, and 16. * * The actual format code is derived by taking the define below and or-ing with * the interleave factor. So, 32 bit interleave by 6 is 0x86 and * 16 bit interleave by 16 is (0x40 | 0x10) = 0x50. * */ #define DSP_AUDIOFORM_SUPER_INTERLEAVE_16LE 0x40 #define DSP_AUDIOFORM_SUPER_INTERLEAVE_24LE 0xc0 #define DSP_AUDIOFORM_SUPER_INTERLEAVE_32LE 0x80 /* * * Gina24, Mona, and Layla24 control register defines * */ #define GML_CONVERTER_ENABLE 0x0010 #define GML_SPDIF_PRO_MODE 0x0020 /* Professional S/PDIF == 1, consumer == 0 */ #define GML_SPDIF_SAMPLE_RATE0 0x0040 #define GML_SPDIF_SAMPLE_RATE1 0x0080 #define GML_SPDIF_TWO_CHANNEL 0x0100 /* 1 == two channels, 0 == one channel */ #define GML_SPDIF_NOT_AUDIO 0x0200 #define GML_SPDIF_COPY_PERMIT 0x0400 #define GML_SPDIF_24_BIT 0x0800 /* 1 == 24 bit, 0 == 20 bit */ #define GML_ADAT_MODE 0x1000 /* 1 == ADAT mode, 0 == S/PDIF mode */ #define GML_SPDIF_OPTICAL_MODE 0x2000 /* 1 == optical mode, 0 == RCA mode */ #define GML_SPDIF_CDROM_MODE 0x3000 /* 1 == CDROM mode, * 0 == RCA or optical mode */ #define GML_DOUBLE_SPEED_MODE 0x4000 /* 1 == double speed, 0 == single speed */ #define GML_DIGITAL_IN_AUTO_MUTE 0x800000 #define GML_96KHZ (0x0 | GML_DOUBLE_SPEED_MODE) #define GML_88KHZ (0x1 | GML_DOUBLE_SPEED_MODE) #define GML_48KHZ 0x2 #define GML_44KHZ 0x3 #define GML_32KHZ 0x4 #define GML_22KHZ 0x5 #define GML_16KHZ 0x6 #define GML_11KHZ 0x7 #define GML_8KHZ 0x8 #define GML_SPDIF_CLOCK 0x9 #define GML_ADAT_CLOCK 0xA #define GML_WORD_CLOCK 0xB #define GML_ESYNC_CLOCK 0xC #define GML_ESYNCx2_CLOCK 0xD #define GML_CLOCK_CLEAR_MASK 0xffffbff0 #define GML_SPDIF_RATE_CLEAR_MASK (~(GML_SPDIF_SAMPLE_RATE0|GML_SPDIF_SAMPLE_RATE1)) #define GML_DIGITAL_MODE_CLEAR_MASK 0xffffcfff #define GML_SPDIF_FORMAT_CLEAR_MASK 0xfffff01f /* * * Mia sample rate and clock setting constants * */ #define MIA_32000 0x0040 #define MIA_44100 0x0042 #define MIA_48000 0x0041 #define MIA_88200 0x0142 #define MIA_96000 0x0141 #define MIA_SPDIF 0x00000044 #define MIA_SPDIF96 0x00000144 #define MIA_MIDI_REV 1 /* Must be Mia rev 1 for MIDI support */ /* * * 3G register bits * */ #define E3G_CONVERTER_ENABLE 0x0010 #define E3G_SPDIF_PRO_MODE 0x0020 /* Professional S/PDIF == 1, consumer == 0 */ #define E3G_SPDIF_SAMPLE_RATE0 0x0040 #define E3G_SPDIF_SAMPLE_RATE1 0x0080 #define E3G_SPDIF_TWO_CHANNEL 0x0100 /* 1 == two channels, 0 == one channel */ #define E3G_SPDIF_NOT_AUDIO 0x0200 #define E3G_SPDIF_COPY_PERMIT 0x0400 #define E3G_SPDIF_24_BIT 0x0800 /* 1 == 24 bit, 0 == 20 bit */ #define E3G_DOUBLE_SPEED_MODE 0x4000 /* 1 == double speed, 0 == single speed */ #define E3G_PHANTOM_POWER 0x8000 /* 1 == phantom power on, 0 == phantom power off */ #define E3G_96KHZ (0x0 | E3G_DOUBLE_SPEED_MODE) #define E3G_88KHZ (0x1 | E3G_DOUBLE_SPEED_MODE) #define E3G_48KHZ 0x2 #define E3G_44KHZ 0x3 #define E3G_32KHZ 0x4 #define E3G_22KHZ 0x5 #define E3G_16KHZ 0x6 #define E3G_11KHZ 0x7 #define E3G_8KHZ 0x8 #define E3G_SPDIF_CLOCK 0x9 #define E3G_ADAT_CLOCK 0xA #define E3G_WORD_CLOCK 0xB #define E3G_CONTINUOUS_CLOCK 0xE #define E3G_ADAT_MODE 0x1000 #define E3G_SPDIF_OPTICAL_MODE 0x2000 #define E3G_CLOCK_CLEAR_MASK 0xbfffbff0 #define E3G_DIGITAL_MODE_CLEAR_MASK 0xffffcfff #define E3G_SPDIF_FORMAT_CLEAR_MASK 0xfffff01f /* Clock detect bits reported by the DSP */ #define E3G_CLOCK_DETECT_BIT_WORD96 0x0001 #define E3G_CLOCK_DETECT_BIT_WORD48 0x0002 #define E3G_CLOCK_DETECT_BIT_SPDIF48 0x0004 #define E3G_CLOCK_DETECT_BIT_ADAT 0x0004 #define E3G_CLOCK_DETECT_BIT_SPDIF96 0x0008 #define E3G_CLOCK_DETECT_BIT_WORD (E3G_CLOCK_DETECT_BIT_WORD96|E3G_CLOCK_DETECT_BIT_WORD48) #define E3G_CLOCK_DETECT_BIT_SPDIF (E3G_CLOCK_DETECT_BIT_SPDIF48|E3G_CLOCK_DETECT_BIT_SPDIF96) /* Frequency control register */ #define E3G_MAGIC_NUMBER 677376000 #define E3G_FREQ_REG_DEFAULT (E3G_MAGIC_NUMBER / 48000 - 2) #define E3G_FREQ_REG_MAX 0xffff /* 3G external box types */ #define E3G_GINA3G_BOX_TYPE 0x00 #define E3G_LAYLA3G_BOX_TYPE 0x10 #define E3G_ASIC_NOT_LOADED 0xffff #define E3G_BOX_TYPE_MASK 0xf0 /* Indigo express control register values */ #define INDIGO_EXPRESS_32000 0x02 #define INDIGO_EXPRESS_44100 0x01 #define INDIGO_EXPRESS_48000 0x00 #define INDIGO_EXPRESS_DOUBLE_SPEED 0x10 #define INDIGO_EXPRESS_QUAD_SPEED 0x04 #define INDIGO_EXPRESS_CLOCK_MASK 0x17 /* * * Gina20 & Layla20 have input gain controls for the analog inputs; * this is the magic number for the hardware that gives you 0 dB at -10. * */ #define GL20_INPUT_GAIN_MAGIC_NUMBER 0xC8 /* * * Defines how much time must pass between DSP load attempts * */ #define DSP_LOAD_ATTEMPT_PERIOD 1000000L /* One second */ /* * * Size of arrays for the comm page. MAX_PLAY_TAPS and MAX_REC_TAPS are * no longer used, but the sizes must still be right for the DSP to see * the comm page correctly. * */ #define MONITOR_ARRAY_SIZE 0x180 #define VMIXER_ARRAY_SIZE 0x40 #define MIDI_OUT_BUFFER_SIZE 32 #define MIDI_IN_BUFFER_SIZE 256 #define MAX_PLAY_TAPS 168 #define MAX_REC_TAPS 192 #define DSP_MIDI_OUT_FIFO_SIZE 64 /* sg_entry is a single entry for the scatter-gather list. The array of struct sg_entry struct is read by the DSP, so all values must be little-endian. */ #define MAX_SGLIST_ENTRIES 512 struct sg_entry { __le32 addr; __le32 size; }; /**************************************************************************** The comm page. This structure is read and written by the DSP; the DSP code is a firm believer in the byte offsets written in the comments at the end of each line. This structure should not be changed. Any reads from or writes to this structure should be in little-endian format. ****************************************************************************/ struct comm_page { /* Base Length*/ __le32 comm_size; /* size of this object 0x000 4 */ __le32 flags; /* See Appendix A below 0x004 4 */ __le32 unused; /* Unused entry 0x008 4 */ __le32 sample_rate; /* Card sample rate in Hz 0x00c 4 */ __le32 handshake; /* DSP command handshake 0x010 4 */ __le32 cmd_start; /* Chs. to start mask 0x014 4 */ __le32 cmd_stop; /* Chs. to stop mask 0x018 4 */ __le32 cmd_reset; /* Chs. to reset mask 0x01c 4 */ __le16 audio_format[DSP_MAXPIPES]; /* Chs. audio format 0x020 32*2 */ struct sg_entry sglist_addr[DSP_MAXPIPES]; /* Chs. Physical sglist addrs 0x060 32*8 */ __le32 position[DSP_MAXPIPES]; /* Positions for ea. ch. 0x160 32*4 */ s8 vu_meter[DSP_MAXPIPES]; /* VU meters 0x1e0 32*1 */ s8 peak_meter[DSP_MAXPIPES]; /* Peak meters 0x200 32*1 */ s8 line_out_level[DSP_MAXAUDIOOUTPUTS]; /* Output gain 0x220 16*1 */ s8 line_in_level[DSP_MAXAUDIOINPUTS]; /* Input gain 0x230 16*1 */ s8 monitors[MONITOR_ARRAY_SIZE]; /* Monitor map 0x240 0x180 */ __le32 play_coeff[MAX_PLAY_TAPS]; /* Gina/Darla play filters - obsolete 0x3c0 168*4 */ __le32 rec_coeff[MAX_REC_TAPS]; /* Gina/Darla record filters - obsolete 0x660 192*4 */ __le16 midi_input[MIDI_IN_BUFFER_SIZE]; /* MIDI input data transfer buffer 0x960 256*2 */ u8 gd_clock_state; /* Chg Gina/Darla clock state 0xb60 1 */ u8 gd_spdif_status; /* Chg. Gina/Darla S/PDIF state 0xb61 1 */ u8 gd_resampler_state; /* Should always be 3 0xb62 1 */ u8 filler2; /* 0xb63 1 */ __le32 nominal_level_mask; /* -10 level enable mask 0xb64 4 */ __le16 input_clock; /* Chg. Input clock state 0xb68 2 */ __le16 output_clock; /* Chg. Output clock state 0xb6a 2 */ __le32 status_clocks; /* Current Input clock state 0xb6c 4 */ __le32 ext_box_status; /* External box status 0xb70 4 */ __le32 cmd_add_buffer; /* Pipes to add (obsolete) 0xb74 4 */ __le32 midi_out_free_count; /* # of bytes free in MIDI output FIFO 0xb78 4 */ __le32 unused2; /* Cyclic pipes 0xb7c 4 */ __le32 control_register; /* Mona, Gina24, Layla24, 3G ctrl reg 0xb80 4 */ __le32 e3g_frq_register; /* 3G frequency register 0xb84 4 */ u8 filler[24]; /* filler 0xb88 24*1 */ s8 vmixer[VMIXER_ARRAY_SIZE]; /* Vmixer levels 0xba0 64*1 */ u8 midi_output[MIDI_OUT_BUFFER_SIZE]; /* MIDI output data 0xbe0 32*1 */ }; #endif /* _ECHO_DSP_ */
29.939914
96
0.725631
[ "object", "vector" ]
aa9613d8838682c22ddbe8b444ea987cfad648fb
3,509
h
C
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/tab/tab_classintervalmap.h
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/tab/tab_classintervalmap.h
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/tab/tab_classintervalmap.h
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_TAB_CLASSCLASSINTERVALMAP #define INCLUDED_TAB_CLASSCLASSINTERVALMAP #ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif // Library headers. #ifndef INCLUDED_SET #include <set> #define INCLUDED_SET #endif // PCRaster library headers. #ifndef INCLUDED_COM_INTERVALMAP #include "com_intervalmap.h" #define INCLUDED_COM_INTERVALMAP #endif #ifndef INCLUDED_COM_CLONE #include "com_clone.h" #define INCLUDED_COM_CLONE #endif // Module headers. namespace tab { template< class IntervalMapT, typename Class =int > class ClassIntervalMap : public std::map<Class,IntervalMapT> { typedef std::map<Class,IntervalMapT> Base; typedef typename Base::const_iterator I; typedef typename std::set<Class> S; typedef typename S::iterator SI; typedef std::vector<const com::Interval<typename IntervalMapT::IT> *> Intervals; Intervals d_intervals; //! Assignment operator. NOT IMPLEMENTED. ClassIntervalMap& operator= (const ClassIntervalMap& rhs); //! Copy constructor. NOT IMPLEMENTED. ClassIntervalMap (const ClassIntervalMap& rhs); public: //---------------------------------------------------------------------------- // CREATORS //---------------------------------------------------------------------------- ClassIntervalMap(const Intervals& intervals) { com::copyClone(intervals,d_intervals); } virtual ~ClassIntervalMap() { com::deleteCloneContainer(d_intervals); } //---------------------------------------------------------------------------- // MANIPULATORS //---------------------------------------------------------------------------- //! if class no yet in map then add with initial 0 count void addClass(Class row) { if (this->count(row)==0) (*this)[row].insertIntervals(d_intervals); } /*! \brief incr count for class combination \a r \a c, * or set to 1 if not existent * \todo * let addClass return the position to apply visit on * now 2 lookups then 1. */ void visit(Class r,double c) { addClass(r); (*this)[r].visit(c); } //! as incr(r,c) void operator()(Class r,double c) { visit(r,c); } //---------------------------------------------------------------------------- // ACCESSORS //---------------------------------------------------------------------------- /* S rowClasses() const { S s; for (I i=begin();i!=end();++i) s.insert(i->first); return s; } //! union set of all classes occurring in some columns S colClasses() const { S s; for (I i=begin();i!=end();++i) { S a(i->second.classes()); s.insert(a.begin(),a.end()); } return s; } //! return the count, 0 if not in map size_t getCount(Class r, Class c) const { I i=find(r); if (i!=end()) return i->second.getCount(c); return 0; } */ }; //------------------------------------------------------------------------------ // INLINE FUNCTIONS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // FREE FUNCTIONS //------------------------------------------------------------------------------ } // namespace tab #endif
24.538462
81
0.471929
[ "vector" ]
aa98b31b749ca0a6b14707e5284f52674bb9bbc4
28,574
c
C
src/postgres/src/backend/executor/ybcModifyTable.c
haneefmubarak/yugabyte-db
510d3394d927c6d4993d4915df20baa78854e89d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/postgres/src/backend/executor/ybcModifyTable.c
haneefmubarak/yugabyte-db
510d3394d927c6d4993d4915df20baa78854e89d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/postgres/src/backend/executor/ybcModifyTable.c
haneefmubarak/yugabyte-db
510d3394d927c6d4993d4915df20baa78854e89d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
/*-------------------------------------------------------------------------------------------------- * * ybcModifyTable.c * YB routines to stmt_handle ModifyTable nodes. * * Copyright (c) YugaByte, Inc. * * 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. * * IDENTIFICATION * src/backend/executor/ybcModifyTable.c * *-------------------------------------------------------------------------------------------------- */ #include "postgres.h" #include "access/htup_details.h" #include "access/sysattr.h" #include "access/xact.h" #include "catalog/pg_type.h" #include "catalog/ybctype.h" #include "utils/relcache.h" #include "utils/rel.h" #include "utils/lsyscache.h" #include "nodes/execnodes.h" #include "commands/dbcommands.h" #include "executor/tuptable.h" #include "executor/ybcExpr.h" #include "executor/ybcModifyTable.h" #include "miscadmin.h" #include "catalog/catalog.h" #include "catalog/pg_attribute.h" #include "catalog/pg_namespace.h" #include "catalog/pg_database.h" #include "utils/catcache.h" #include "utils/inval.h" #include "utils/relcache.h" #include "utils/rel.h" #include "executor/tuptable.h" #include "executor/ybcExpr.h" #include "utils/syscache.h" #include "yb/yql/pggate/ybc_pggate.h" #include "pg_yb_utils.h" /* * Hack to ensure that the next CommandCounterIncrement() will call * CommandEndInvalidationMessages(). The result of this call is not * needed on the yb side, however the side effects are. */ void MarkCurrentCommandUsed() { (void) GetCurrentCommandId(true); } /* * Returns whether a relation's attribute is a real column in the backing * YugaByte table. (It implies we can both read from and write to it). */ bool IsRealYBColumn(Relation rel, int attrNum) { return (attrNum > 0 && !TupleDescAttr(rel->rd_att, attrNum - 1)->attisdropped) || (rel->rd_rel->relhasoids && attrNum == ObjectIdAttributeNumber); } /* * Returns whether a relation's attribute is a YB system column. */ bool IsYBSystemColumn(int attrNum) { return (attrNum == YBRowIdAttributeNumber || attrNum == YBIdxBaseTupleIdAttributeNumber || attrNum == YBUniqueIdxKeySuffixAttributeNumber); } /* * Returns whether relation is capable of single row execution. */ bool YBCIsSingleRowTxnCapableRel(ResultRelInfo *resultRelInfo) { bool has_triggers = resultRelInfo->ri_TrigDesc && resultRelInfo->ri_TrigDesc->numtriggers > 0; bool has_indices = YBCRelInfoHasSecondaryIndices(resultRelInfo); return !has_indices && !has_triggers; } /* * Get the type ID of a real or virtual attribute (column). * Returns InvalidOid if the attribute number is invalid. */ static Oid GetTypeId(int attrNum, TupleDesc tupleDesc) { switch (attrNum) { case SelfItemPointerAttributeNumber: return TIDOID; case ObjectIdAttributeNumber: return OIDOID; case MinTransactionIdAttributeNumber: return XIDOID; case MinCommandIdAttributeNumber: return CIDOID; case MaxTransactionIdAttributeNumber: return XIDOID; case MaxCommandIdAttributeNumber: return CIDOID; case TableOidAttributeNumber: return OIDOID; default: if (attrNum > 0 && attrNum <= tupleDesc->natts) return TupleDescAttr(tupleDesc, attrNum - 1)->atttypid; else return InvalidOid; } } /* * Get primary key columns as bitmap of a table. */ static Bitmapset *GetTablePrimaryKey(Relation rel, AttrNumber minattr, bool includeYBSystemColumns) { Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); int natts = RelationGetNumberOfAttributes(rel); Bitmapset *pkey = NULL; YBCPgTableDesc ybc_tabledesc = NULL; /* Get the primary key columns 'pkey' from YugaByte. */ HandleYBStatus(YBCPgGetTableDesc(dboid, relid, &ybc_tabledesc)); for (AttrNumber attnum = minattr; attnum <= natts; attnum++) { if ((!includeYBSystemColumns && !IsRealYBColumn(rel, attnum)) || (!IsRealYBColumn(rel, attnum) && !IsYBSystemColumn(attnum))) { continue; } bool is_primary = false; bool is_hash = false; HandleYBTableDescStatus(YBCPgGetColumnInfo(ybc_tabledesc, attnum, &is_primary, &is_hash), ybc_tabledesc); if (is_primary) { pkey = bms_add_member(pkey, attnum - minattr); } } HandleYBStatus(YBCPgDeleteTableDesc(ybc_tabledesc)); return pkey; } /* * Get primary key columns as bitmap of a table for real YB columns. */ Bitmapset *GetYBTablePrimaryKey(Relation rel) { return GetTablePrimaryKey(rel, FirstLowInvalidHeapAttributeNumber + 1 /* minattr */, false /* includeYBSystemColumns */); } /* * Get primary key columns as bitmap of a table for real and system YB columns. */ Bitmapset *GetFullYBTablePrimaryKey(Relation rel) { return GetTablePrimaryKey(rel, YBSystemFirstLowInvalidAttributeNumber + 1 /* minattr */, true /* includeYBSystemColumns */); } /* * Get the ybctid from a YB scan slot for UPDATE/DELETE. */ Datum YBCGetYBTupleIdFromSlot(TupleTableSlot *slot) { /* * Look for ybctid in the tuple first if the slot contains a tuple packed with ybctid. * Otherwise, look for it in the attribute list as a junk attribute. */ if (slot->tts_tuple != NULL && slot->tts_tuple->t_ybctid != 0) { return slot->tts_tuple->t_ybctid; } for (int idx = 0; idx < slot->tts_nvalid; idx++) { Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, idx); if (strcmp(NameStr(att->attname), "ybctid") == 0 && !slot->tts_isnull[idx]) { Assert(att->atttypid == BYTEAOID); return slot->tts_values[idx]; } } return 0; } /* * Get the ybctid from a tuple. * * Note that if the relation has a DocDB RowId attribute, this will generate a new RowId value * meaning the ybctid will be unique. Therefore you should only use this if the relation has * a primary key or you're doing an insert. */ Datum YBCGetYBTupleIdFromTuple(YBCPgStatement pg_stmt, Relation rel, HeapTuple tuple, TupleDesc tupleDesc) { Bitmapset *pkey = GetFullYBTablePrimaryKey(rel); AttrNumber minattr = YBSystemFirstLowInvalidAttributeNumber + 1; const int nattrs = bms_num_members(pkey); YBCPgAttrValueDescriptor *attrs = (YBCPgAttrValueDescriptor*)palloc(nattrs * sizeof(YBCPgAttrValueDescriptor)); uint64_t tuple_id = 0; YBCPgAttrValueDescriptor *next_attr = attrs; int col = -1; while ((col = bms_next_member(pkey, col)) >= 0) { AttrNumber attnum = col + minattr; next_attr->attr_num = attnum; /* * Don't need to fill in for the DocDB RowId column, however we still * need to add the column to the statement to construct the ybctid. */ if (attnum != YBRowIdAttributeNumber) { Oid type_id = (attnum > 0) ? TupleDescAttr(tupleDesc, attnum - 1)->atttypid : InvalidOid; next_attr->type_entity = YBCDataTypeFromOidMod(attnum, type_id); next_attr->datum = heap_getattr(tuple, attnum, tupleDesc, &next_attr->is_null); } else { next_attr->datum = 0; next_attr->is_null = false; next_attr->type_entity = NULL; } ++next_attr; } HandleYBStmtStatus(YBCPgDmlBuildYBTupleId(pg_stmt, attrs, nattrs, &tuple_id), pg_stmt); pfree(attrs); return (Datum)tuple_id; } /* * Bind ybctid to the statement. */ static void YBCBindTupleId(YBCPgStatement pg_stmt, Datum tuple_id) { YBCPgExpr ybc_expr = YBCNewConstant(pg_stmt, BYTEAOID, tuple_id, false /* is_null */); HandleYBStmtStatus(YBCPgDmlBindColumn(pg_stmt, YBTupleIdAttributeNumber, ybc_expr), pg_stmt); } /* * Check if operation changes a system table, ignore changes during * initialization (bootstrap mode). */ static bool IsSystemCatalogChange(Relation rel) { return IsSystemRelation(rel) && !IsBootstrapProcessingMode(); } /* * Utility method to execute a prepared write statement. * Will handle the case if the write changes the system catalogs meaning * we need to increment the catalog versions accordingly. */ static YBCStatus YBCExecWriteStmt(YBCPgStatement ybc_stmt, Relation rel, int *rows_affected_count) { bool is_syscatalog_change = IsSystemCatalogChange(rel); bool modifies_row = false; HandleYBStmtStatus(YBCPgDmlModifiesRow(ybc_stmt, &modifies_row), ybc_stmt); /* * If this write may invalidate catalog cache tuples (i.e. UPDATE or DELETE), * or this write may insert into a cached list, we must increment the * cache version so other sessions can invalidate their caches. * NOTE: If this relation caches lists, an INSERT could effectively be * UPDATINGing the list object. */ bool is_syscatalog_version_change = is_syscatalog_change && (modifies_row || RelationHasCachedLists(rel)); /* Let the master know if this should increment the catalog version. */ if (is_syscatalog_version_change) { HandleYBStmtStatus(YBCPgSetIsSysCatalogVersionChange(ybc_stmt), ybc_stmt); } HandleYBStmtStatus(YBCPgSetCatalogCacheVersion(ybc_stmt, yb_catalog_cache_version), ybc_stmt); /* Execute the insert. */ YBCStatus status = YBCPgDmlExecWriteOp(ybc_stmt, rows_affected_count); /* * Optimization to increment the catalog version for the local cache as * this backend is already aware of this change and should update its * catalog caches accordingly (without needing to ask the master). * Note that, since the master catalog version should have been identically * incremented, it will continue to match with the local cache version if * and only if no other master changes occurred in the meantime (i.e. from * other backends). * If changes occurred, then a cache refresh will be needed as usual. */ if (!status && is_syscatalog_version_change) { // TODO(shane) also update the shared memory catalog version here. yb_catalog_cache_version += 1; } return status; } /* * Utility method to handle the status of an insert statement to return unique * constraint violation error message due to duplicate key in primary key or * unique index / constraint. */ static void YBCHandleInsertStatus(YBCStatus status, Relation rel, YBCPgStatement stmt) { if (!status) return; HandleYBStatus(YBCPgDeleteStatement(stmt)); if (YBCStatusIsDuplicateKey(status)) { char *constraint; /* * If this is the base table and there is a primary key, the primary key is * the constraint. Otherwise, the rel is the unique index constraint. */ if (!rel->rd_index && rel->rd_pkindex != InvalidOid) { Relation pkey = RelationIdGetRelation(rel->rd_pkindex); constraint = pstrdup(RelationGetRelationName(pkey)); RelationClose(pkey); } else { constraint = pstrdup(RelationGetRelationName(rel)); } YBCFreeStatus(status); ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("duplicate key value violates unique constraint \"%s\"", constraint))); } else { HandleYBStatus(status); } } /* * Utility method to insert a tuple into the relation's backing YugaByte table. */ static Oid YBCExecuteInsertInternal(Relation rel, TupleDesc tupleDesc, HeapTuple tuple, bool is_single_row_txn) { Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); AttrNumber minattr = FirstLowInvalidHeapAttributeNumber + 1; int natts = RelationGetNumberOfAttributes(rel); Bitmapset *pkey = GetYBTablePrimaryKey(rel); YBCPgStatement insert_stmt = NULL; bool is_null = false; /* Generate a new oid for this row if needed */ if (rel->rd_rel->relhasoids) { if (!OidIsValid(HeapTupleGetOid(tuple))) HeapTupleSetOid(tuple, GetNewOid(rel)); } /* Create the INSERT request and add the values from the tuple. */ HandleYBStatus(YBCPgNewInsert(dboid, relid, is_single_row_txn, &insert_stmt)); /* Get the ybctid for the tuple and bind to statement */ tuple->t_ybctid = YBCGetYBTupleIdFromTuple(insert_stmt, rel, tuple, tupleDesc); YBCBindTupleId(insert_stmt, tuple->t_ybctid); for (AttrNumber attnum = minattr; attnum <= natts; attnum++) { /* Skip virtual (system) and dropped columns */ if (!IsRealYBColumn(rel, attnum)) { continue; } Oid type_id = GetTypeId(attnum, tupleDesc); Datum datum = heap_getattr(tuple, attnum, tupleDesc, &is_null); /* Check not-null constraint on primary key early */ if (is_null && bms_is_member(attnum - minattr, pkey)) { HandleYBStatus(YBCPgDeleteStatement(insert_stmt)); ereport(ERROR, (errcode(ERRCODE_NOT_NULL_VIOLATION), errmsg( "Missing/null value for primary key column"))); } /* Add the column value to the insert request */ YBCPgExpr ybc_expr = YBCNewConstant(insert_stmt, type_id, datum, is_null); HandleYBStmtStatus(YBCPgDmlBindColumn(insert_stmt, attnum, ybc_expr), insert_stmt); } /* * For system tables, mark tuple for invalidation from system caches * at next command boundary. Do this now so if there is an error with insert * we will re-query to get the correct state from the master. */ if (IsCatalogRelation(rel)) { MarkCurrentCommandUsed(); CacheInvalidateHeapTuple(rel, tuple, NULL); } /* Execute the insert */ YBCHandleInsertStatus(YBCExecWriteStmt(insert_stmt, rel, NULL /* rows_affected_count */), rel, insert_stmt); /* Clean up */ HandleYBStatus(YBCPgDeleteStatement(insert_stmt)); insert_stmt = NULL; return HeapTupleGetOid(tuple); } /* * Utility method to bind const to column */ static void BindColumn(YBCPgStatement stmt, int attr_num, Oid type_id, Datum datum, bool is_null) { YBCPgExpr expr = YBCNewConstant(stmt, type_id, datum, is_null); HandleYBStmtStatus(YBCPgDmlBindColumn(stmt, attr_num, expr), stmt); } /* * Utility method to set keys and value to index write statement */ static void PrepareIndexWriteStmt(YBCPgStatement stmt, Relation index, Datum *values, bool *isnull, int natts, Datum ybbasectid, bool ybctid_as_value) { TupleDesc tupdesc = RelationGetDescr(index); if (ybbasectid == 0) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg( "Missing base table ybctid in index write request"))); } bool has_null_attr = false; for (AttrNumber attnum = 1; attnum <= natts; ++attnum) { Oid type_id = GetTypeId(attnum, tupdesc); Datum value = values[attnum - 1]; bool is_null = isnull[attnum - 1]; has_null_attr = has_null_attr || is_null; BindColumn(stmt, attnum, type_id, value, is_null); } const bool unique_index = index->rd_index->indisunique; /* * For unique indexes we need to set the key suffix system column: * - to ybbasectid if at least one index key column is null. * - to NULL otherwise (setting is_null to true is enough). */ if (unique_index) BindColumn(stmt, YBUniqueIdxKeySuffixAttributeNumber, BYTEAOID, ybbasectid, !has_null_attr /* is_null */); /* * We may need to set the base ctid column: * - for unique indexes only if we need it as a value (i.e. for inserts) * - for non-unique indexes always (it is a key column). */ if (ybctid_as_value || !unique_index) BindColumn(stmt, YBIdxBaseTupleIdAttributeNumber, BYTEAOID, ybbasectid, false /* is_null */); } Oid YBCExecuteInsert(Relation rel, TupleDesc tupleDesc, HeapTuple tuple) { return YBCExecuteInsertInternal(rel, tupleDesc, tuple, false /* is_single_row_txn */); } Oid YBCExecuteNonTxnInsert(Relation rel, TupleDesc tupleDesc, HeapTuple tuple) { return YBCExecuteInsertInternal(rel, tupleDesc, tuple, true /* is_single_row_txn */); } Oid YBCHeapInsert(TupleTableSlot *slot, HeapTuple tuple, EState *estate) { /* * get information on the (current) result relation */ ResultRelInfo *resultRelInfo = estate->es_result_relation_info; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; if (estate->es_yb_is_single_row_modify_txn) { /* * Try to execute the statement as a single row transaction (rather * than a distributed transaction) if it is safe to do so. * I.e. if we are in a single-statement transaction that targets a * single row (i.e. single-row-modify txn), and there are no indices * or triggers on the target table. */ return YBCExecuteNonTxnInsert(resultRelationDesc, slot->tts_tupleDescriptor, tuple); } else { return YBCExecuteInsert(resultRelationDesc, slot->tts_tupleDescriptor, tuple); } } void YBCExecuteInsertIndex(Relation index, Datum *values, bool *isnull, Datum ybctid) { Assert(index->rd_rel->relkind == RELKIND_INDEX); Assert(ybctid != 0); Oid dboid = YBCGetDatabaseOid(index); Oid relid = RelationGetRelid(index); YBCPgStatement insert_stmt = NULL; /* Create the INSERT request and add the values from the tuple. */ HandleYBStatus(YBCPgNewInsert(dboid, relid, false /* is_single_row_txn */, &insert_stmt)); PrepareIndexWriteStmt(insert_stmt, index, values, isnull, RelationGetNumberOfAttributes(index), ybctid, true /* ybctid_as_value */); /* Execute the insert and clean up. */ YBCHandleInsertStatus(YBCExecWriteStmt(insert_stmt, index, NULL /* rows_affected_count */), index, insert_stmt); HandleYBStatus(YBCPgDeleteStatement(insert_stmt)); } bool YBCExecuteDelete(Relation rel, TupleTableSlot *slot, EState *estate, ModifyTableState *mtstate) { Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); YBCPgStatement delete_stmt = NULL; bool isSingleRow = mtstate->yb_mt_is_single_row_update_or_delete; Datum ybctid = 0; /* Create DELETE request. */ HandleYBStatus(YBCPgNewDelete(dboid, relid, estate->es_yb_is_single_row_modify_txn, &delete_stmt)); /* * Look for ybctid. Raise error if ybctid is not found. * * If single row delete, generate ybctid from tuple values, otherwise * retrieve it from the slot. */ if (isSingleRow) { HeapTuple tuple = ExecMaterializeSlot(slot); ybctid = YBCGetYBTupleIdFromTuple(delete_stmt, rel, tuple, slot->tts_tupleDescriptor); } else { ybctid = YBCGetYBTupleIdFromSlot(slot); } if (ybctid == 0) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg( "Missing column ybctid in DELETE request to YugaByte database"))); } /* Bind ybctid to identify the current row. */ YBCPgExpr ybctid_expr = YBCNewConstant(delete_stmt, BYTEAOID, ybctid, false /* is_null */); HandleYBStmtStatus(YBCPgDmlBindColumn(delete_stmt, YBTupleIdAttributeNumber, ybctid_expr), delete_stmt); /* Delete row from foreign key cache */ HandleYBStatus(YBCPgDeleteFromForeignKeyReferenceCache(relid, ybctid)); /* Execute the statement. */ int rows_affected_count = 0; HandleYBStmtStatus(YBCExecWriteStmt(delete_stmt, rel, &rows_affected_count), delete_stmt); if (rows_affected_count == 0 && !isSingleRow) { ereport(ERROR, (errcode(ERRCODE_NO_DATA), errmsg( "Row specified in DELETE request was not found in YugaByte database"))); } /* Cleanup. */ HandleYBStatus(YBCPgDeleteStatement(delete_stmt)); delete_stmt = NULL; return rows_affected_count > 0; } void YBCExecuteDeleteIndex(Relation index, Datum *values, bool *isnull, Datum ybctid) { Assert(index->rd_rel->relkind == RELKIND_INDEX); Oid dboid = YBCGetDatabaseOid(index); Oid relid = RelationGetRelid(index); YBCPgStatement delete_stmt = NULL; /* Create the DELETE request and add the values from the tuple. */ HandleYBStatus(YBCPgNewDelete(dboid, relid, false /* is_single_row_txn */, &delete_stmt)); PrepareIndexWriteStmt(delete_stmt, index, values, isnull, IndexRelationGetNumberOfKeyAttributes(index), ybctid, false /* ybctid_as_value */); /* Delete row from foreign key cache */ HandleYBStatus(YBCPgDeleteFromForeignKeyReferenceCache(relid, ybctid)); HandleYBStmtStatus(YBCExecWriteStmt(delete_stmt, index, NULL /* rows_affected_count */), delete_stmt); HandleYBStatus(YBCPgDeleteStatement(delete_stmt)); } bool YBCExecuteUpdate(Relation rel, TupleTableSlot *slot, HeapTuple tuple, EState *estate, ModifyTableState *mtstate, Bitmapset *updatedCols) { TupleDesc tupleDesc = slot->tts_tupleDescriptor; Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); YBCPgStatement update_stmt = NULL; bool isSingleRow = mtstate->yb_mt_is_single_row_update_or_delete; Datum ybctid = 0; /* Create update statement. */ HandleYBStatus(YBCPgNewUpdate(dboid, relid, estate->es_yb_is_single_row_modify_txn, &update_stmt)); /* * Look for ybctid. Raise error if ybctid is not found. * * If single row update, generate ybctid from tuple values, otherwise * retrieve it from the slot. */ if (isSingleRow) { ybctid = YBCGetYBTupleIdFromTuple(update_stmt, rel, tuple, slot->tts_tupleDescriptor); } else { ybctid = YBCGetYBTupleIdFromSlot(slot); } if (ybctid == 0) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg( "Missing column ybctid in UPDATE request to YugaByte database"))); } /* Bind ybctid to identify the current row. */ YBCPgExpr ybctid_expr = YBCNewConstant(update_stmt, BYTEAOID, ybctid, false /* is_null */); HandleYBStmtStatus(YBCPgDmlBindColumn(update_stmt, YBTupleIdAttributeNumber, ybctid_expr), update_stmt); /* Assign new values to the updated columns for the current row. */ tupleDesc = RelationGetDescr(rel); bool whole_row = bms_is_member(InvalidAttrNumber, updatedCols); for (int idx = 0; idx < tupleDesc->natts; idx++) { AttrNumber attnum = TupleDescAttr(tupleDesc, idx)->attnum; bool has_default = TupleDescAttr(tupleDesc, idx)->atthasdef; /* Skip virtual (system) and dropped columns */ if (!IsRealYBColumn(rel, attnum)) continue; /* Skip unmodified columns */ int bms_idx = attnum - YBGetFirstLowInvalidAttributeNumber(rel); if (!whole_row && !bms_is_member(bms_idx, updatedCols) && !has_default) continue; bool is_null = false; Datum d = heap_getattr(tuple, attnum, tupleDesc, &is_null); YBCPgExpr ybc_expr = YBCNewConstant(update_stmt, TupleDescAttr(tupleDesc, idx)->atttypid, d, is_null); HandleYBStmtStatus(YBCPgDmlAssignColumn(update_stmt, attnum, ybc_expr), update_stmt); } /* Execute the statement. */ int rows_affected_count = 0; HandleYBStmtStatus(YBCExecWriteStmt(update_stmt, rel, &rows_affected_count), update_stmt); if (rows_affected_count == 0 && !isSingleRow) { ereport(ERROR, (errcode(ERRCODE_NO_DATA), errmsg( "Row specified in UPDATE request was not found in YugaByte database"))); } /* Cleanup. */ HandleYBStatus(YBCPgDeleteStatement(update_stmt)); update_stmt = NULL; /* * If the relation has indexes, save the ybctid to insert the updated row into the indexes. */ if (YBRelHasSecondaryIndices(rel)) { tuple->t_ybctid = ybctid; } return rows_affected_count > 0; } void YBCDeleteSysCatalogTuple(Relation rel, HeapTuple tuple) { Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); YBCPgStatement delete_stmt = NULL; if (tuple->t_ybctid == 0) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg( "Missing column ybctid in DELETE request to YugaByte database"))); /* Prepare DELETE statement. */ HandleYBStatus(YBCPgNewDelete(dboid, relid, false /* is_single_row_txn */, &delete_stmt)); /* Bind ybctid to identify the current row. */ YBCPgExpr ybctid_expr = YBCNewConstant(delete_stmt, BYTEAOID, tuple->t_ybctid, false /* is_null */); /* Delete row from foreign key cache */ HandleYBStatus(YBCPgDeleteFromForeignKeyReferenceCache(relid, tuple->t_ybctid)); HandleYBStmtStatus(YBCPgDmlBindColumn(delete_stmt, YBTupleIdAttributeNumber, ybctid_expr), delete_stmt); /* * Mark tuple for invalidation from system caches at next command * boundary. Do this now so if there is an error with delete we will * re-query to get the correct state from the master. */ MarkCurrentCommandUsed(); CacheInvalidateHeapTuple(rel, tuple, NULL); HandleYBStmtStatus(YBCExecWriteStmt(delete_stmt, rel, NULL /* rows_affected_count */), delete_stmt); /* Complete execution */ HandleYBStatus(YBCPgDeleteStatement(delete_stmt)); delete_stmt = NULL; } void YBCUpdateSysCatalogTuple(Relation rel, HeapTuple oldtuple, HeapTuple tuple) { Oid dboid = YBCGetDatabaseOid(rel); Oid relid = RelationGetRelid(rel); TupleDesc tupleDesc = RelationGetDescr(rel); int natts = RelationGetNumberOfAttributes(rel); YBCPgStatement update_stmt = NULL; /* Create update statement. */ HandleYBStatus(YBCPgNewUpdate(dboid, relid, false /* is_single_row_txn */, &update_stmt)); AttrNumber minattr = FirstLowInvalidHeapAttributeNumber + 1; Bitmapset *pkey = GetYBTablePrimaryKey(rel); /* Bind the ybctid to the statement. */ YBCBindTupleId(update_stmt, tuple->t_ybctid); /* Assign values to the non-primary-key columns to update the current row. */ for (int idx = 0; idx < natts; idx++) { AttrNumber attnum = TupleDescAttr(tupleDesc, idx)->attnum; /* Skip primary-key columns */ if (bms_is_member(attnum - minattr, pkey)) { continue; } bool is_null = false; Datum d = heap_getattr(tuple, attnum, tupleDesc, &is_null); YBCPgExpr ybc_expr = YBCNewConstant(update_stmt, TupleDescAttr(tupleDesc, idx)->atttypid, d, is_null); HandleYBStmtStatus(YBCPgDmlAssignColumn(update_stmt, attnum, ybc_expr), update_stmt); } /* * Mark old tuple for invalidation from system caches at next command * boundary, and mark the new tuple for invalidation in case we abort. * In case when there is no old tuple, we will invalidate with the * new tuple at next command boundary instead. Do these now so if there * is an error with update we will re-query to get the correct state * from the master. */ MarkCurrentCommandUsed(); if (oldtuple) CacheInvalidateHeapTuple(rel, oldtuple, tuple); else CacheInvalidateHeapTuple(rel, tuple, NULL); /* Execute the statement and clean up */ HandleYBStmtStatus(YBCExecWriteStmt(update_stmt, rel, NULL /* rows_affected_count */), update_stmt); HandleYBStatus(YBCPgDeleteStatement(update_stmt)); update_stmt = NULL; } void YBCStartBufferingWriteOperations() { HandleYBStatus(YBCPgStartBufferingWriteOperations()); } void YBCFlushBufferedWriteOperations() { HandleYBStatus(YBCPgFlushBufferedWriteOperations()); } bool YBCRelInfoHasSecondaryIndices(ResultRelInfo *resultRelInfo) { return resultRelInfo->ri_NumIndices > 1 || (resultRelInfo->ri_NumIndices == 1 && !resultRelInfo->ri_IndexRelationDescs[0]->rd_index->indisprimary); }
31.538631
101
0.682159
[ "object" ]