blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f74a8913e9ee030bc338e2edf62e9cede9c43206
c8814f2e344cf72bc25ad84e2e596505bbddcdf2
/2 数学/2.1 代数/2.1.6 Adaptive Simpson's Rule.cpp
9199127800ba70a28e47bf9928fea491269d7bb1
[]
no_license
Hukeqing/ACM-Template-SingDanceRap
b648d7058f05be8e6c268e27cc63e18fa2168f1a
3c61332d5630ab466a48b95b9c67de31e1e63087
refs/heads/master
2023-02-02T14:38:07.376220
2020-12-24T01:57:44
2020-12-24T01:57:44
189,908,584
1
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
double F(double x) { //Simpson公式用到的函数 } double simpson(double a, double b)//三点Simpson法,这里要求F是一个全局函数 { double c = a + (b - a) / 2; return (F(a) + 4 * F(c) + F(b))*(b - a) / 6; } double asr(double a, double b, double eps, double A)//自适应Simpson公式(递归过程)。已知整个区间[a,b]上的三点Simpson值A { double c = a + (b - a) / 2; double L = simpson(a, c), R = simpson(c, b); if (fabs(L + R - A) <= 15 * eps)return L + R + (L + R - A) / 15.0; return asr(a, c, eps / 2, L) + asr(c, b, eps / 2, R); } double asr(double a, double b, double eps)//自适应Simpson公式(主过程) { return asr(a, b, eps, simpson(a, b)); }
[ "zhangyf3210@163.com" ]
zhangyf3210@163.com
3409e97e3aa0cc58fb40e02e0f697b619fd3baa5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_new_log_2930.cpp
311f467a108ed4623a3d07973a3f99a4d21ea6aa
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
46
cpp
error_errno("error while reading from stdin");
[ "993273596@qq.com" ]
993273596@qq.com
a3dba22f54bcc80a4cccfb1e45576f021ebaa069
5d309f75555c9fa49cd1bb0f953c6ee73d711fe6
/garnet/bin/zxdb/symbols/function.h
3ea0485a1fbac1a243eb14eac685a3a2b743cf75
[ "BSD-3-Clause" ]
permissive
the-locksmith/fuchsia
d2d0b7d6e011a1468cb299441494be2c9c5cae0a
2620709744ff49fe289169a8af63f8499239333b
refs/heads/master
2021-10-21T10:55:16.114376
2019-02-28T22:37:39
2019-03-04T00:05:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,063
h
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <string> #include "garnet/bin/zxdb/symbols/code_block.h" #include "garnet/bin/zxdb/symbols/file_line.h" #include "garnet/bin/zxdb/symbols/variable_location.h" namespace zxdb { // Represents a function (a "subprogram" in DWARF parlance). This is different // than a "FunctionType" which is the type used to represent function pointers. // // Some functions in DWARF are "implementations" that have code ranges // associated with them, and some are "specifications" (akin to C forward // declarations) that don't. The context about the namespaces and parent // classes comes from the specification, while the implementation of the // function may be outside of any namespace or class definitions. // // It seems Clang puts the function parameters in both places, some attributes // like DW_AT_frame_base will only be on the implementation, and others like // DW_AT_decl_file/line, DW_AT_accessibility, and the return type (DW_AT_type) // are only on the specification. // // In the case of an implementation, the decoder will attempt to fill in the // attributes from the specification automatically so this Function object // will have full context. Be aware that this won't necessarily match the // DIE that generated the object. // // NAMING: The "full name" (as returned by Symbol::GetFullName()) of a function // is the qualified name without any return types or parameters. Some callers // may want parameters, we can add a helper function in the future if necessary // (for display we would often want to syntax highlight these differently so // this is often betetr done at a a different layer). class Function final : public CodeBlock { public: // Construct with fxl::MakeRefCounted(). // Symbol overrides. const Function* AsFunction() const override; const std::string& GetAssignedName() const final { return assigned_name_; } // Returns true if this function is an inlined function instance. bool is_inline() const { return tag() == Symbol::kTagInlinedSubroutine; } // The containing block is the CodeBlock that contains an inlined function. // This will be null for non-inlined functions. // // For inlined functions, Symbol::parent() will contain the lexical parent of // the inlined function (a class or namespace) while the containing block // will be the CodeBlock (of any type) that the code is inlined into. const LazySymbol& containing_block() const { return containing_block_; } void set_containing_block(LazySymbol c) { containing_block_ = std::move(c); } // Unmangled name. Does not include any class or namespace qualifications. // (see Symbol::GetAssignedName) void set_assigned_name(std::string n) { assigned_name_ = std::move(n); } // Mangled name. const std::string& linkage_name() const { return linkage_name_; } void set_linkage_name(std::string n) { linkage_name_ = std::move(n); } // The location in the source code of the declaration. May be empty. const FileLine& decl_line() const { return decl_line_; } void set_decl_line(FileLine decl) { decl_line_ = std::move(decl); } // For inline functions, this can be set to indicate the call location. const FileLine& call_line() const { return call_line_; } void set_call_line(FileLine call) { call_line_ = std::move(call); } // The return value type. This should be some kind of Type object. Will be // empty for void return types. const LazySymbol& return_type() const { return return_type_; } void set_return_type(const LazySymbol& rt) { return_type_ = rt; } // Parameters passed to the function. These should be Variable objects. const std::vector<LazySymbol>& parameters() const { return parameters_; } void set_parameters(std::vector<LazySymbol> p) { parameters_ = std::move(p); } // The frame base is the location where "fbreg" expressions are evaluated // relative to (this will be most local variables in a function). This can // be an empty location if there's no frame base or it's not needed (e.g. // for inline functions). // // When compiled with full stack frames, this will usually evaluate to the // contents of the CPU's "BP" register, but can be different or arbitrarily // complicated, especially when things are optimized. const VariableLocation& frame_base() const { return frame_base_; } void set_frame_base(VariableLocation base) { frame_base_ = std::move(base); } // The object pointer is the "this" object for the current function. // Quick summary: Use GetObjectPointerVariable() to retrieve "this". // // The object_pointer() will be a reference to a parameter (object type // Variable). It should theoretically match one of the entries in the // parameters() list but we can't guarantee what the compiler has generated. // The variable will be the implicit object ("this") pointer for member // functions. For nonmember or static member functions the object pointer // will be null. // // For inlined functions the location on the object_pointer variable may be // wrong. Typically an inlined subroutine consists of two entries: // // Shared entry for all inlined instances: // (1) DW_TAG_subprogram "InlinedFunc" // DW_AT_object_pointer = reference to (2) // (2) DW_TAG_formal_parameter "this" // <info on the parameter> // // Specific inlined function instance: // (3) DW_TAG_inlined_subroutine "InlinedFunc" // DW_AT_abstract_origin = reference to (1) // (4) DW_TAG_formal_parameter "this" // DW_AT_abstract_origin = reference to (2) // <info on parameter, possibly different than (2)> // // Looking at the object pointer will give the variable on the abstract // origin, while the inlined subroutine will have its own declaration for // "this" which will have a location specific to this inlined instantiation. // // The GetObjectPointerVariable() function handles this case and returns the // correct resulting variable. It will return null if there is no object // pointer. const LazySymbol& object_pointer() const { return object_pointer_; } void set_object_pointer(const LazySymbol& op) { object_pointer_ = op; } const Variable* GetObjectPointerVariable() const; private: FRIEND_REF_COUNTED_THREAD_SAFE(Function); FRIEND_MAKE_REF_COUNTED(Function); // The tag must be either "subprogram" or "inlined subroutine" according to // whether or not this is an inlined function. explicit Function(int tag); ~Function(); // Symbol protected overrides. std::string ComputeFullName() const override; LazySymbol containing_block_; std::string assigned_name_; std::string linkage_name_; FileLine decl_line_; FileLine call_line_; LazySymbol return_type_; std::vector<LazySymbol> parameters_; VariableLocation frame_base_; LazySymbol object_pointer_; }; } // namespace zxdb
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2d1f5ac9e3cd721411bcaedb3a8899b26da5b85d
6c45a2bc233267188bfaff0f2e7c61d910b4edaa
/util/cpp/exception.h
054e76883e1b0593d535ce00284c688d9fa068e3
[]
no_license
nextonr/code
b86a88ea4cdb274ff39ed91ec1cad9fa21ba0a1b
c4a717dbfbafb853f8856496594b139f63ff63ef
refs/heads/master
2021-10-28T13:17:56.292640
2019-04-24T01:12:14
2019-04-24T01:12:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
// // Created by hujianzhe on 16-5-2. // #ifndef UTIL_CPP_EXCEPTION_H #define UTIL_CPP_EXCEPTION_H #include "cpp_compiler_define.h" #include <stdio.h> #include <exception> #include <stdexcept> #define assert_throw(exp)\ if (!(exp)) {\ throw std::logic_error(__FILE__"(" MACRO_TOSTRING(__LINE__) "): " #exp "\r\n");\ } #define logic_throw(exp, fmt, ...)\ if (!(exp)) {\ char _str[512];\ snprintf(_str, sizeof(_str), __FILE__"(" MACRO_TOSTRING(__LINE__) "): %s\r\n" fmt "\r\n", #exp, ##__VA_ARGS__);\ throw std::logic_error(_str);\ } #endif
[ "776095293@qq.com" ]
776095293@qq.com
b6233d62361331640263d652ddcb63c1d91715be
639d6f230b480183879b6d3035032e9d6c1b13c4
/Inheritance/Inheritance -II/Ass2/smanager.h
c17d7ee5b16db139596ced2790553240b593e6c5
[]
no_license
Sweety4/CPP-Solution
5a1dbf29e549f4563e5aabc996a096c2b0332a0c
d9365a9cf3bbac0d4a21732eb847b5b46e4d536f
refs/heads/main
2023-01-12T01:17:28.183053
2020-11-09T13:37:14
2020-11-09T13:37:14
311,346,419
1
0
null
null
null
null
UTF-8
C++
false
false
231
h
#include"sales.h" #include"manager.h" class cSalesManager :public cSalesPerson, public cManager { public: cSalesManager(); cSalesManager(int, const char*, float, float, float, float, float); void Accept(); void Display(); };
[ "sweetyjangale5@gmail.com" ]
sweetyjangale5@gmail.com
32730fd65a04eae568300105327e0c9b6c89cf97
60c9d985436e81a18e5b4b1332f14212312f6e7a
/edbee-data/code/cpp/b_qabstractgraphicsshapeitem_w.hpp
bf7dfe071a463330c81f5a67d88c706ddb36cce9
[]
no_license
visualambda/simpleIDE
53b69e47de6e4f9ad333ae9d00d3bfb3a571048c
37e3395c5fffa2cf1ca74652382461eadaffa9aa
refs/heads/master
2020-03-23T07:22:19.938662
2018-08-16T03:43:26
2018-08-16T03:43:26
141,267,532
1
0
null
null
null
null
UTF-8
C++
false
false
272
hpp
////////// GENERATED FILE, EDITS WILL BE LOST ////////// #ifndef HOPPY_MODULE_qtah_qabstractgraphicsshapeitemwrap #define HOPPY_MODULE_qtah_qabstractgraphicsshapeitemwrap extern "C" { } // extern "C" #endif // ifndef HOPPY_MODULE_qtah_qabstractgraphicsshapeitemwrap
[ "jellyzone@gmail.com" ]
jellyzone@gmail.com
d839acface5b079f6f17b2ac28d4d8d7dd7cf18c
e17c7cf738ee8c59789e9bef6aca875715545912
/tests/commoninjectiondll.cpp
6a59bbfc27384e8c4242030e048a9709f0fa4041
[]
no_license
KDE/libkcw
e279b1336b2228716853e3bc9465a1424adacd75
810b71cc946d7fa0625d481d4245cfb6d3f2a04c
refs/heads/master
2016-09-08T01:32:43.445800
2014-01-17T21:07:48
2014-01-17T21:08:45
42,731,774
2
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
/* Copyright 2013-2014 Patrick Spendrin <ps_ml@gmx.de> * * 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. */ #include "kcwsharedmemory.h" #include "kcwdebug.h" #include <windows.h> extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /* lpvReserved */ ) { switch(dwReason) { case DLL_PROCESS_ATTACH: { KcwSharedMemory<int> shmem(L"injectortest", 1, false); KcwSharedMemory<WCHAR> shmemvar(L"injectortestvar", 9, false); *shmem += 1; memcpy(shmemvar.data(), _wgetenv(L"MYTEST"), 9 * sizeof(WCHAR)); break; } case DLL_PROCESS_DETACH: { break; } }; return TRUE; }
[ "ps_ml@gmx.de" ]
ps_ml@gmx.de
b400c02b21759270f8bde3fa1505c960d65042b6
a193f7b36932acfc1c9d151f9268c232bacd7c87
/dsp-checking/src/util/ieee_float.h
251f42febabbce9a21e6d286aac7e61637da020e
[ "BSD-2-Clause" ]
permissive
ashokkelur/CBMC-With-DSP-C
c21dbfacf956b77b8ea5a381e15b292128713b52
1de07c526bfe67e265c39126de1dfe3e419b50a4
refs/heads/master
2021-01-23T14:04:10.599920
2013-09-14T09:21:47
2013-09-14T09:21:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,063
h
/*******************************************************************\ Module: Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #ifndef CPROVER_IEEE_FLOAT_H #define CPROVER_IEEE_FLOAT_H #include <ostream> #include <mp_arith.h> #include <format_spec.h> class exprt; class floatbv_typet; class ieee_float_spect { public: // Bits for fraction (excluding hidden bit) and exponent, // respectively unsigned f, e; mp_integer bias() const; ieee_float_spect(const floatbv_typet &type) { from_type(type); } void from_type(const floatbv_typet &type); ieee_float_spect():f(0), e(0) { } ieee_float_spect(unsigned _f, unsigned _e):f(_f), e(_e) { } inline unsigned width() const { // add one for the sign bit return f+e+1; } mp_integer max_exponent() const; mp_integer max_fraction() const; class floatbv_typet to_type() const; // the well-know standard formats inline static ieee_float_spect single_precision() { return ieee_float_spect(23, 8); } inline static ieee_float_spect double_precision() { return ieee_float_spect(52, 11); } }; class ieee_floatt { public: // ROUND_TO_EVEN is also known as "round to nearest, ties to even", and // is the IEEE default typedef enum { ROUND_TO_EVEN, ROUND_TO_ZERO, ROUND_TO_PLUS_INF, ROUND_TO_MINUS_INF, UNKNOWN, NONDETERMINISTIC } rounding_modet; rounding_modet rounding_mode; ieee_float_spect spec; ieee_floatt(const ieee_float_spect &_spec): rounding_mode(ROUND_TO_EVEN), spec(_spec), sign(false), exponent(0), fraction(0), NaN(false), infinity(false) { } ieee_floatt(): rounding_mode(ROUND_TO_EVEN), sign(false), exponent(0), fraction(0), NaN(false), infinity(false) { } ieee_floatt(const exprt &expr): rounding_mode(ROUND_TO_EVEN) { from_expr(expr); } void negate() { sign=!sign; } void set_sign(bool _sign) { sign = _sign; } void make_zero() { sign=false; exponent=0; fraction=0; NaN=false; infinity = false; } void make_NaN(); void make_plus_infinity(); void make_minus_infinity(); void make_fltmax(); void make_fltmin(); // set to next representable number towards plus or minus infinity void increment(bool distinguish_zero=false) { if(is_zero() && get_sign() && distinguish_zero) negate(); else next_representable(true); } void decrement(bool distinguish_zero=false) { if(is_zero() && !get_sign() && distinguish_zero) negate(); else next_representable(false); } bool is_zero() const { return !NaN && !infinity && fraction==0 && exponent==0; } bool get_sign() const { return sign; } bool is_NaN() const { return NaN; } bool is_infinity() const { return !NaN && infinity; } const mp_integer &get_exponent() const { return exponent; } const mp_integer &get_fraction() const { return fraction; } // performs conversion to ieee floating point format void from_integer(const mp_integer &i); void from_base10(const mp_integer &exp, const mp_integer &frac); void build(const mp_integer &exp, const mp_integer &frac); void unpack(const mp_integer &i); void from_double(const double d); void from_float(const float f); // perfroms conversions from ieee float-point format // to something else double to_double() const; float to_float() const; bool is_double() const; bool is_float() const; mp_integer pack() const; void extract(mp_integer &_exponent, mp_integer &_fraction) const; mp_integer to_integer() const; // this rounds to zero // conversions void change_spec(const ieee_float_spect &dest_spec); // output void print(std::ostream &out) const; std::string to_ansi_c_string() const { return format(format_spect()); } std::string format(const format_spect &format_spec) const; friend inline std::ostream& operator << (std::ostream &out, const ieee_floatt &f) { return out << f.to_ansi_c_string(); } // expressions exprt to_expr() const; void from_expr(const exprt &expr); // the usual opertors ieee_floatt &operator /= (const ieee_floatt &other); ieee_floatt &operator *= (const ieee_floatt &other); ieee_floatt &operator += (const ieee_floatt &other); ieee_floatt &operator -= (const ieee_floatt &other); friend bool operator < (const ieee_floatt &a, const ieee_floatt &b); friend bool operator <=(const ieee_floatt &a, const ieee_floatt &b); friend bool operator > (const ieee_floatt &a, const ieee_floatt &b); friend bool operator >=(const ieee_floatt &a, const ieee_floatt &b); // warning: these do packed equality, not IEEE equality // e.g., NAN==NAN friend bool operator ==(const ieee_floatt &a, const ieee_floatt &b); friend bool operator !=(const ieee_floatt &a, const ieee_floatt &b); friend bool operator ==(const ieee_floatt &a, int i); // these do IEEE equality, i.e., NAN!=NAN friend bool ieee_equal(const ieee_floatt &a, const ieee_floatt &b); friend bool ieee_not_equal(const ieee_floatt &a, const ieee_floatt &b); protected: void divide_and_round(mp_integer &fraction, const mp_integer &factor); void align(); void next_representable(bool greater); // we store the number unpacked bool sign; mp_integer exponent; // this is unbiased mp_integer fraction; // this _does_ include the hidden bit bool NaN, infinity; }; bool operator < (const ieee_floatt &a, const ieee_floatt &b); bool operator <=(const ieee_floatt &a, const ieee_floatt &b); bool operator > (const ieee_floatt &a, const ieee_floatt &b); bool operator >=(const ieee_floatt &a, const ieee_floatt &b); bool operator ==(const ieee_floatt &a, const ieee_floatt &b); bool operator !=(const ieee_floatt &a, const ieee_floatt &b); std::ostream& operator << (std::ostream &, const ieee_floatt &); bool ieee_equal(const ieee_floatt &a, const ieee_floatt &b); bool ieee_not_equal(const ieee_floatt &a, const ieee_floatt &b); #endif
[ "ashoksarf@gmail.com" ]
ashoksarf@gmail.com
1b70c37250a73c91ce70de2ae0dfed2b4b7817a2
48a8a4fc4954111becec90f8fa05ac55d065526c
/HDU_2011多项式求和.cpp
f508b386237a55534150fa053894c43c8ce223f9
[]
no_license
vanishblue/OJ
9dc4ed397e1aaa7c769991e9a966299ee2d9468a
8ec972c7bdb7c5850aab10dbb3a70fc94213495d
refs/heads/master
2020-04-24T09:11:44.193865
2019-03-10T08:06:06
2019-03-10T08:06:06
171,855,348
3
1
null
null
null
null
UTF-8
C++
false
false
356
cpp
#include <iostream> #include <iomanip> #include <cmath> using namespace std ; int main() { int m, n, i, j ; cin>>m ; for (i=0; i<m; i++) { double sum=1 ; cin>>n ; for (j=2; j<=n; j++) { if (j%2 == 0) sum -= double(1)/double(j) ; else sum += double(1)/double(j) ; } cout<<fixed<<setprecision(2)<<sum<<endl ; } return 0 ; }
[ "904644710@qq.com" ]
904644710@qq.com
fe4f68537a94a31886347d1135b7290b62ba277f
6d1bea5c9109dffb129bd61f59db1346c0b114bc
/software/cse/assistance/buffer_dim1.h
56b4d4cb5d72fc84426afe5986857ff07f44325d
[]
no_license
chibby0ne/split_row_threshold
8517399e9bd17e450c66fc138b92a6c3444c0d99
42dee227bcfb8058dd6a14b704111b931cfa4e7a
refs/heads/master
2020-12-31T03:55:46.137550
2014-08-29T06:23:30
2014-08-29T06:23:30
16,789,111
0
1
null
null
null
null
UTF-8
C++
false
false
11,096
h
// // Copyright (C) 2011 Creonic GmbH // // This file is part of the Creonic simulation environment (CSE) // for communication systems. // /// \file /// \brief Specialization of the buffer class for dim = 1 /// \author Timo Lehnigk-Emden /// \date 2011/06/10 // #ifndef BUFFER_DIM1_H_ #define BUFFER_DIM1_H_ #include "buffer_abstract.h" // Enable IT++ Support and library dependency #ifdef ITPP_SUPPORT #include <itpp/itbase.h> #endif /// Buffer class with one dimension (array) /** * Buffer class to store data into a matrix array. * Class is a specialization of the buffer<T,dim> class with dim = 1. * In addition if the ITPP_SUPPORT definition is set the class member functions support * the Vec<T> data type of the it++ library. * Class as an explicit it++ support, that mean to operate with the Vec<T> * type from it++ instantiate the class with the type T and NOT with the type * Vec<T> ! * In addition it has many functions to read and write data to native C++ arrays. * * \ingroup base_class * \ingroup assistance */ template <class T> class Buffer<T,1> : public Buffer_Abstract { public: /// Buffer View, a new buffer object is created which uses the memory of the given buffer Buffer(const Buffer<T,1>& buffer, Buffer_Abstract::BUFFER_TYPE_ENUM buffer_type); /// Copy constructor Buffer(const Buffer<T,1>& buffer); /// Create a new buffer with zero elements Buffer(); /// Create a new buffer and initialize it with the given values explicit Buffer(const char* init_value); /// Create a new buffer with a given size /** * @param size Number of elements which can the buffer store */ explicit Buffer(unsigned int size); /// Creates a partial view or a copy of the given buffer Buffer(const Buffer<T,1>& buffer, unsigned int start_pos, unsigned int length, Buffer_Abstract::BUFFER_TYPE_ENUM buffer_type); /// Destructor virtual ~Buffer(); /// Append the given value to the buffer and return a buffer reference. Buffer<T,1>& operator()(T value) { this->Append(value); return (*this); } /// Resize the buffer from the current size to a new size /** * \param size New size of the buffer * \param copy Holds the data if copy=true, if the new buffer size is smaller than the previous one, the oversized date were discarded. * \param error_out Enable or disable the error messages. An error can occurs if you want to keep the values, * but the new buffer size is smaller than the old one. */ void Resize(unsigned int size, bool copy = false, bool error_out = true); /// Transform the current buffer instance to a (partial) view of another buffer. /** * \param src_buffer Buffer to create the view on. * \param start_pos Starting position of the view of the source buffer * \param length Length of the view (number of elements). * = 0: Create a view up to the end of the original buffer */ void Transform_To_View(const Buffer<T,1>& src_buffer, unsigned int start_pos = 0, unsigned int length = 0); /// Get a single element of the buffer (constant) /** * @param i position to set or get, beginning with zero */ const T& operator[](int i) const { return mem_ptr_[i]; } //T operator[](int i) const { return mem_ptr_[i]; } /// Get or Set a single element of the buffer /** * @param i position to set or get, beginning with zero */ T& operator[](int i) { return mem_ptr_[i]; } /// Copy the values from buffer to buffer /** * @param input buffer to copy. */ Buffer<T,1> &operator=(const Buffer<T,1>& input); /// Set the value in the buffer from the given string /** * The format is val1, val2, val3. The operator throws the invalid_argument exception in * case of an conversion error. * The buffer is automatically resized to the number of elements read */ Buffer<T,1>& operator=(const std::string& input); /// Write date into the buffer /** * @param input Pointer to data to write into the buffer. Number of * elements in input must be equal or greater than the buffer. */ Buffer<T,1> &operator=(T *input); /// Set all elements to zero (clear the buffer) void Clear() { for(unsigned int i = 0; i < length_; i++) (*this)[i] = static_cast<T>(0); } /// Set all elements to the given value. void Set(T input) { for(unsigned int i = 0; i < length_; i++) (*this)[i] = static_cast<T>(input); } /// Get the pointer of the internal memory of the buffer, only for advanced users T* Data_Ptr(); /// Get the pointer of the internal memory of the buffer, only for advanced users const T* Data_Ptr() const; /// Write data into the buffer, same as = operator /** * @param input Pointer the array to copy the data. Number of elements in input must be equal or greater than the buffer. */ void Write(T *input); /// Write the Sub array/vector into the buffer /** * @param[in] input Pointer to the date to write into the buffer * @param start Index of the buffer to start writing * @param end Index of the buffer to stop writing the data, if =-1 copy all data up to the end */ void Write_Sub_Vector(T* input,int start, int end=-1); /// Read the whole buffer /** * @param[out] output Pointer to the array to copy the date form the buffer into the array. output array must be great enough to store all data. */ void Read(T* output); /// Read the sub array/vector out of the buffer. /** * @param[out] output Pointer to the array to copy the date from the buffer into the array. output array must be great enough to store all data. * @param start Index of the buffer to start reading * @param end Index of the buffer to stop reading, if =-1 copy all data up to the end */ void Read_Sub_Vector(T* output, int start, int end=-1); /// Compare the value of the current buffer with another one and return the number of differences int Compare(const Buffer<T,1> &buffer); /// Compare the value of the current buffer with another one bool operator==(const Buffer<T,1> &input); /// Append a single element to the Buffer (Resize included). void Append(T input); // Functions for it++ Vec<T> data type #ifdef ITPP_SUPPORT /** * For use with the it++ data type Vec<T>, see operator =() * \overload */ Buffer<T,1> &operator=(itpp::Vec<T> &input); /** * For use with the it++ data type bvec, see operator =() * \overload */ Buffer<T,1> &operator=(itpp::bvec &input); /** * For use with the it++ data type itpp::Vec<T>, see Read() * \overload void Read(itpp::Vec<T> &output) */ void Read(itpp::Vec<T> &output); /** * For use with the it++ data type itpp::Vec<T>, see Read_Sub_Vector() * \overload void Read_Sub_Vector(itpp::Vec<T>& output, int start, int end=-1); */ void Read_Sub_Vector(itpp::Vec<T> &output,int start, int end=-1); /// Create a new vector which contains a copy of all data of the buffer /** * @return New vector of type itpp::Vec<T> */ itpp::Vec<T> Read(); /// Return a new vector which contains parts of the buffer values /** * @param start First index of data to read from buffer * @param end Last index of data to read * @return New vector of type itpp::Vec<T> which contains the requested date */ itpp::Vec<T> Read_Sub_Vector(int start, int end=-1); /// Read the converted values from buffer and stores them into the given itpp vec container. /** * \param destination itpp vec container to write the converted data to type T_IT from the buffer. * The size of the destination container is adapted automatically to the size of the buffer. */ template<typename T_IT> void Read_Convert(itpp::Vec<T_IT>& destination); /** * For use with the it++ data type itpp::Vec<T>, see Write() * \overload void Write(itpp::Vec<T> &input); */ void Write(itpp::Vec<T> &input); /** * For use with the it++ data type itpp::Vec<T>, see Write_Sub_Vector() * \overload void Write_Sub_Vector(itpp::Vec<T> &input, int start, int end=-1); */ void Write_Sub_Vector(itpp::Vec<T> &input, int start, int end = -1); /// Write the converted values from the given itpp vec container into the buffer. /** * \param source itpp container to read the data, convert them to the buffer type T and write them into the buffer. * The size of the buffer is adapted automatically to the size of the source container. */ template<typename T_IT> void Write_Convert(const itpp::Vec<T_IT>& source); #endif /// Overload of << operator inline friend std::ostream & operator<<(std::ostream & os, Buffer<T,1> & data) { if(data.length_ != 0) { for(unsigned int i=0; i < data.length_ - 1; i++) os << data.mem_ptr_[i] << ", "; // Print last data without comma and whitespace at the end os << data.mem_ptr_[data.length_ - 1]; } return os; } /// Overload of >> operator inline friend std::istream & operator>>(std::istream & os, Buffer<T,1> & data) { for(unsigned int i = 0; i < data.length_; i++) os >> data.mem_ptr_[i]; return os; } /// Dump the content of the buffer to stdout or a file. /** * @param filename If a file name is give, the buffer is written to a file * @param append = false, file content is overwritten, = true append the date to the file * @param linebreak = false, values separated by blank, = true values separated by linebreak */ void Dump(std::string filename="", bool append=false, bool linebreak=false); /// Dump the content of the buffer modulo 2^mod_bw to stdout or a file. /** * @param filename If a file name is give, the buffer is written to a file * @param append = false, file content is overwritten, = true append the date to the file * @param mod_bw All values are dumped modulo 2^mod_bw * @param separator Values are separated by this string. Default is a blank. */ void Dump_Modulo(int mod_bw, std::string filename="", bool append=false, const char* separator=" "); /// Stream the content of the buffer modulo 2^mod_bw /** * @param mod_bw All values are dumped modulo 2^mod_bw * @param separator Values are separated by this string. Default is a blank. */ std::string Stream_Modulo(int mod_bw, const char* separator=" "); /// Return the number of elements (length) of the buffer unsigned int length() const {return length_;} /// Return a Buffer with the current dimensions of the buffer Buffer<unsigned int, 1> dim() { Buffer<unsigned int, 1> ret(1); ret[0] = length_; return ret; } /// Return the maximum value in the buffer T Max(); private: /// Set the buffer values from a string void Set_From_String(const std::string& input); void View_Parent_Changed(); /// Name of the current buffer instance std::string instance_name_; /// Internal memory allocation function void Alloc_Mem(); /// Store the length of the current memory unsigned int length_; /// Pointer to the memory T *mem_ptr_; /// Buffer View of buffer bool view_; /// Original view parameter class View_Parameter { public: unsigned int length_; /// length of the view unsigned int start_pos_; /// start position of the view Buffer<T, 1>* parent; /// Pointer to the original buffer object } view_parameter_; }; #endif
[ "chibby0ne@gmail.com" ]
chibby0ne@gmail.com
560af4df8881ed1d0fa8bbe5bcd89a028f242f46
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/scrape/data/Tokitsukaze and Discard Items/z7z_Eta_TLE.cpp
c945a26c8713e770a9c572c9acc0a09ea6ceb1a6
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
944
cpp
// SeptEtavioxy #include<cstdio> #include<cctype> #include<cstring> #include<algorithm> #include<cmath> #define re register #define ll long long #define il inline #define rep(i,s,t) for(re int i=(s);i<=(t);i++) #define each(i,u) for(int i=head[u];i;i=bow[i].nxt) #define pt(ch) putchar(ch) #define pti(x) printf("%d",x) #define ptll(x) printf("%I64d",x) #define file(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout) using namespace std; // c_ints il ll ci(){ re char ch; while(isspace(ch=getchar())); re ll x= ch^'0'; while(isdigit(ch=getchar()))x=(x*10)+(ch^'0'); return x; } enum{M=100023}; ll a[M]; int main(){ ci(); ll m= ci(), k= ci(); rep(i,1,m) a[i]= ci(); ll end= k, cnt= 0, p= 1; ll move; while( p<=m ){ move= 0; while( p<=m && a[p]<=end ){ move++; p++; } if( move ) cnt++, end+=move; else end+=k; } ptll(cnt); return 0; } /* 10 7 3 1 2 4 5 7 9 10 */
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
78d89fcda093f3f8ec82bb3eb7ac05f6bee0fe30
32480b903bb45c3c6d194e68f76773ff3abbd883
/inc/ewa_base/basic/system.h
b6143888db9eb92895dd16a0bc8a4100a1fad6dc
[ "Apache-2.0" ]
permissive
xuanya4202/ew_base
636b34300df887cde6b5ad32974f6ad1f6e784e9
e00073412c4da14500b15075fd0dd0c52d65ad4a
refs/heads/master
2021-01-16T20:53:09.671552
2016-06-28T06:15:10
2016-06-28T06:15:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,282
h
#ifndef __H_EW_BASIC_SYSTEM__ #define __H_EW_BASIC_SYSTEM__ #include "ewa_base/config.h" #include "ewa_base/basic/string_detail.h" #include "ewa_base/basic/string.h" #include "ewa_base/basic/stringbuffer.h" #include "ewa_base/basic/platform.h" #include "ewa_base/basic/bitflags.h" #include "ewa_base/basic/stream.h" #include "ewa_base/basic/file.h" #define EW_FUNCTION_TRACER(lv) FunctionTracer __function_tracer(__FUNCTION__,lv); EW_ENTER class DLLIMPEXP_EWA_BASE System { public: static bool Execute(const String& s); static bool Execute(const String& s,StringBuffer<char>& result); static Stream ExecuteRedirect(const String& s,bool* status=NULL); static const String& GetModulePath(); static int GetCacheLineSize(); static int GetCpuCount(); static int GetPageSize(); static int GetPid(); static double GetCpuTime(); // Debug break. static void DebugBreak(); // Exit process with return code v. static void Exit(int v); static void CheckErrno(const String& s); static void CheckError(const String& s); static void SetLastError(const String& msg); static String GetLastError(); static void Update(); static int64_t GetMemTotalPhys(); static int64_t GetMemAvailPhys(); static int64_t GetMemTotalVirtual(); static int64_t GetMemAvailVirtual(); static String GetUsername(); static String GetEnv(const String& name,const String& value_if_not_found=""); static bool IsPathSep(char ch); static char GetPathSep(); static String AdjustPath(const String& path,bool sep); static String MakePath(const String& file,const String& path); static bool IsRelative(const String& file); static String GetCwd(); static bool SetCwd(const String& s); static size_t Backtrace(void** stack,size_t frames); #define STRING_FORMAT_LEVEL(X,Y) DoLog(Y,X) #ifndef NDEBUG STRING_FORMAT_FUNCTIONS(static void LogDebug,STRING_FORMAT_LEVEL,LOGLEVEL_DEBUG) #else static inline void LogDebug(...) {} #endif STRING_FORMAT_FUNCTIONS(static void LogInfo,STRING_FORMAT_LEVEL,LOGLEVEL_INFO) STRING_FORMAT_FUNCTIONS(static void LogTrace,STRING_FORMAT_LEVEL,LOGLEVEL_TRACE) STRING_FORMAT_FUNCTIONS(static void Printf,STRING_FORMAT_LEVEL,LOGLEVEL_PRINT) STRING_FORMAT_FUNCTIONS(static void LogMessage,STRING_FORMAT_LEVEL,LOGLEVEL_MESSAGE) STRING_FORMAT_FUNCTIONS(static void LogWarning,STRING_FORMAT_LEVEL,LOGLEVEL_WARNING) STRING_FORMAT_FUNCTIONS(static void LogError,STRING_FORMAT_LEVEL,LOGLEVEL_ERROR) STRING_FORMAT_FUNCTIONS(static void LogFatal,STRING_FORMAT_LEVEL,LOGLEVEL_FATAL) #undef STRING_FORMAT_LEVEL static bool SetLogFile(const String& fn,bool app=true); // default is enabled static void SetLogEnable(bool f); static void DoLog(int v,const char* msg,...); }; class FunctionTracer { public: FunctionTracer(const char* s,int lv=LOGLEVEL_TRACE); ~FunctionTracer(); private: const void* func; int level; }; class KO_Policy_module { public: typedef void* type; typedef type const_reference; static type invalid_value(){return NULL;} static void destroy(type& o); }; class DLLIMPEXP_EWA_BASE DllModule { public: typedef KO_Handle<KO_Policy_module> impl_type; bool Open(const String& dll); void Close(); void* GetSymbol(const String& s); bool IsOpen(){return impl.ok();} protected: impl_type impl; }; EW_LEAVE #endif
[ "hanwd@eastfdtd.com" ]
hanwd@eastfdtd.com
8e4201de96492868aa6a32058e1977e12560e038
00dafa658072a1d4cb00ef74e151291ae8a39773
/2d/Linux/include/rapidjson/internal/stack.h
e19e2b5b0ab44bbb89791b743cc791fc68149c50
[]
no_license
MenosGrandes/Magisterka
bef997ea3fad2e5f3b46e6c9d2869a14d2bbddb4
41ff3e5ce17c53362e7383dfb47a623c7f4096cf
refs/heads/master
2021-01-21T11:39:54.601295
2015-10-06T06:32:56
2015-10-06T06:32:56
38,577,027
0
0
null
null
null
null
UTF-8
C++
false
false
5,777
h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_INTERNAL_STACK_H_ #define RAPIDJSON_INTERNAL_STACK_H_ #include "../rapidjson.h" RAPIDJSON_NAMESPACE_BEGIN namespace internal { /////////////////////////////////////////////////////////////////////////////// // Stack //! A type-unsafe stack for storing different types of data. /*! \tparam Allocator Allocator for allocating stack memory. */ template <typename Allocator> class Stack { public: // Optimization note: Do not allocate memory for stack_ in constructor. // Do it lazily when first Push() -> Expand() -> Resize(). Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) { RAPIDJSON_ASSERT(stackCapacity > 0); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS Stack(Stack&& rhs) : allocator_(rhs.allocator_), ownAllocator_(rhs.ownAllocator_), stack_(rhs.stack_), stackTop_(rhs.stackTop_), stackEnd_(rhs.stackEnd_), initialCapacity_(rhs.initialCapacity_) { rhs.allocator_ = 0; rhs.ownAllocator_ = 0; rhs.stack_ = 0; rhs.stackTop_ = 0; rhs.stackEnd_ = 0; rhs.initialCapacity_ = 0; } #endif ~Stack() { Destroy(); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS Stack& operator=(Stack&& rhs) { if (&rhs != this) { Destroy(); allocator_ = rhs.allocator_; ownAllocator_ = rhs.ownAllocator_; stack_ = rhs.stack_; stackTop_ = rhs.stackTop_; stackEnd_ = rhs.stackEnd_; initialCapacity_ = rhs.initialCapacity_; rhs.allocator_ = 0; rhs.ownAllocator_ = 0; rhs.stack_ = 0; rhs.stackTop_ = 0; rhs.stackEnd_ = 0; rhs.initialCapacity_ = 0; } return *this; } #endif void Clear() { stackTop_ = stack_; } void ShrinkToFit() { if (Empty()) { // If the stack is empty, completely deallocate the memory. Allocator::Free(stack_); stack_ = 0; stackTop_ = 0; stackEnd_ = 0; } else Resize(GetSize()); } // Optimization note: try to minimize the size of this function for force inline. // Expansion is run very infrequently, so it is moved to another (probably non-inline) function. template<typename T> RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) { // Expand the stack if needed if (stackTop_ + sizeof(T) * count >= stackEnd_) Expand<T>(count); T* ret = reinterpret_cast<T*>(stackTop_); stackTop_ += sizeof(T) * count; return ret; } template<typename T> T* Pop(size_t count) { RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); stackTop_ -= count * sizeof(T); return reinterpret_cast<T*>(stackTop_); } template<typename T> T* Top() { RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); return reinterpret_cast<T*>(stackTop_ - sizeof(T)); } template<typename T> T* Bottom() { return (T*)stack_; } Allocator& GetAllocator() { return *allocator_; } bool Empty() const { return stackTop_ == stack_; } size_t GetSize() const { return static_cast<size_t>(stackTop_ - stack_); } size_t GetCapacity() const { return static_cast<size_t>(stackEnd_ - stack_); } private: template<typename T> void Expand(size_t count) { // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity. size_t newCapacity; if (stack_ == 0) { if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); newCapacity = initialCapacity_; } else { newCapacity = GetCapacity(); newCapacity += (newCapacity + 1) / 2; } size_t newSize = GetSize() + sizeof(T) * count; if (newCapacity < newSize) newCapacity = newSize; Resize(newCapacity); } void Resize(size_t newCapacity) { const size_t size = GetSize(); // Backup the current size stack_ = (char*)allocator_->Realloc(stack_, GetCapacity(), newCapacity); stackTop_ = stack_ + size; stackEnd_ = stack_ + newCapacity; } void Destroy() { Allocator::Free(stack_); RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack } // Prohibit copy constructor & assignment operator. Stack(const Stack&); Stack& operator=(const Stack&); Allocator* allocator_; Allocator* ownAllocator_; char *stack_; char *stackTop_; char *stackEnd_; size_t initialCapacity_; }; } // namespace internal RAPIDJSON_NAMESPACE_END #endif // RAPIDJSON_STACK_H_
[ "kaczor201@o2.pl" ]
kaczor201@o2.pl
8a20a24764ce62d7881a0567dd08439a01bb7e38
25590fa39d365f8cf43d73114f24f9e9a28eb7e2
/Lecture-04 Codes/count_char_2.cpp
08b8ee5bc3baff6e83f64559b76286ca94ad110d
[]
no_license
coding-blocks-archives/Launchpad-LIVE-June-2017
767e89b7533967403d185f1064035352d19ef5b9
b501baaafdeebcca75854386e844099bf09dab49
refs/heads/master
2021-01-20T05:13:06.691930
2017-08-25T16:38:44
2017-08-25T16:38:44
101,419,477
1
6
null
null
null
null
UTF-8
C++
false
false
784
cpp
#include<iostream> using namespace std; int main(){ /// Read a string till $ doesnt come char ch; int digits=0,alpha=0,spaces=0,other=0; ///Read the first input character ch = cin.get(); ///Termination - $ while(ch!='$'){ if(ch>='0'&&ch<='9'){ digits++; } else if(ch>='a'&&ch<='z'){ alpha++; } else if(ch==' '||ch=='\n'){ spaces++; } else{ other++; } ///Read the next character ch = cin.get(); } cout<<"Count is "<<digits<<" Digits "<<endl; cout<<"Count is "<<spaces<<" Spaces "<<endl; cout<<"Count is "<<other<<" Others "<<endl; cout<<"Count is "<<alpha<<" Alphabets "<<endl; return 0; }
[ "prateeknarang111@gmail.com" ]
prateeknarang111@gmail.com
89c9dbaccf92d1f45f5166602cb3f6fe5eeb5d41
028c80416394aebf537bcf44d7ee043ca4c4837d
/Engine/Tests/TestComponents/UniquePtr/UniquePtrTest.cpp
34695fe063ed40f850bddf06ff3524dbb2ebd3dd
[ "Zlib" ]
permissive
Matthew-Krueger/GEOGL
e1042a297b8a2bd0d72816e42612b63c54de05fd
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
refs/heads/main
2023-09-05T20:04:24.899078
2021-11-05T13:35:57
2021-11-05T13:35:57
316,266,739
0
0
Zlib
2021-02-20T18:48:49
2020-11-26T15:15:47
C++
UTF-8
C++
false
false
8,249
cpp
/******************************************************************************* * Copyright (c) 2020 Matthew Krueger * * * * 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. * * * *******************************************************************************/ #include <Catch/Catch2.hpp> #include <GEOGL/Utils.hpp> #include "../../../Source/Utils/Memory/Pointers.hpp" class Test1{ public: explicit Test1(std::string string): storedString(std::move(string)){ }; ~Test1() = default; const std::string& getStoredString(){ return storedString; } private: std::string storedString; }; /* Note, test case does not work individually, for some reason. My allocation tracking code is weird */ TEST_CASE("Trying to create a GEOGL::unique_ptr.", "[UniquePtrTests]") { std::cerr << "Testing creating and destructing a test object works\n"; size_t bytesInUse = GEOGL::getBytesAllocated()-GEOGL::getBytesDeallocated(); { GEOGL::unique_ptr<Test1> test("Hello"); /* don't test require that the starting bytes in use are different for current if in release mode, or * if track memory allocations is off. Otherwise it could get weird */ #if GEOGL_TRACK_MEMORY_ALLOC_FLAG REQUIRE(bytesInUse!=0); REQUIRE(bytesInUse<GEOGL::getBytesAllocated()); REQUIRE(bytesInUse!=GEOGL::getBytesAllocated()); #endif } size_t bytesInUseAfter = GEOGL::getBytesAllocated() - GEOGL::getBytesDeallocated(); REQUIRE(bytesInUse == bytesInUseAfter); } TEST_CASE("DeReferencing UniquePtr overloads", "[UniquePtrTests]") { std::cerr << "Testing DeReferencing overloads\n"; SECTION("Testing with string Test1") { std::string testString = "Test1"; GEOGL::unique_ptr<Test1> test(testString); REQUIRE(testString == (*test).getStoredString()); REQUIRE(testString == test->getStoredString()); REQUIRE(test.get() != nullptr); } SECTION("Testing with string TheQuickBrownFoxJumpedOverTheLazyDog") { std::string testString = "TheQuickBrownFoxJumpedOverTheLazyDog"; GEOGL::unique_ptr<Test1> test(testString); REQUIRE(testString == (*test).getStoredString()); REQUIRE(testString == test->getStoredString()); REQUIRE(test.get() != nullptr); } SECTION("Testing with string The Big Sun in The $ky1234") { std::string testString = "The Big Sun in The $ky1234"; GEOGL::unique_ptr<Test1> test(testString); REQUIRE(testString == (*test).getStoredString()); REQUIRE(testString == test->getStoredString()); REQUIRE(test.get() != nullptr); } } TEST_CASE("Move Assignment Unique Ptr", "[UniquePtrTests]") { SECTION("Testing with string ABC123DoReMiABC123") { std::string startString = "ABC123DoReMiABC123"; GEOGL::unique_ptr<Test1> test(startString); GEOGL::unique_ptr<Test1> test2(std::move(test)); REQUIRE(test2.get()); /* NOLINT bugprone-use-after-move can be disabled because I want to make sure it fails */ REQUIRE(test.get() == nullptr); // NOLINT(bugprone-use-after-move) REQUIRE(test2.get() != nullptr); /* even though if test test.get != nullptr, and test2.get() == test1.get() it should be identical, no harm in checking */ /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test2).getStoredString() == startString); REQUIRE(test2->getStoredString() == startString); } SECTION("Testing with string Its as Easy as 123") { std::string startString = "Its as Easy as 123"; GEOGL::unique_ptr<Test1> test(startString); GEOGL::unique_ptr<Test1> test2(std::move(test)); REQUIRE(test2.get()); /* NOLINT bugprone-use-after-move can be disabled because I want to make sure it fails */ REQUIRE(test.get() == nullptr); // NOLINT(bugprone-use-after-move) REQUIRE(test2.get() != nullptr); /* even though if test test.get != nullptr, and test2.get() == test1.get() it should be identical, no harm in checking */ /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test2).getStoredString() == startString); REQUIRE(test2->getStoredString() == startString); } SECTION("Testing with string Staring Michael Jackson") { std::string startString = "Staring Michael Jackson"; GEOGL::unique_ptr<Test1> test(startString); GEOGL::unique_ptr<Test1> test2(std::move(test)); REQUIRE(test2.get()); /* NOLINT bugprone-use-after-move can be disabled because I want to make sure it fails */ REQUIRE(test.get() == nullptr); // NOLINT(bugprone-use-after-move) REQUIRE(test2.get() != nullptr); /* even though if test test.get != nullptr, and test2.get() == test1.get() it should be identical, no harm in checking */ /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test2).getStoredString() == startString); REQUIRE(test2->getStoredString() == startString); } } TEST_CASE("make_unique Assignment", "[UniquePtrTest]") { std::cerr << "Testing make_unique Assignment\n"; SECTION("Testing with string ABC123DoReMiABC123") { std::string startString = "ABC123DoReMiABC123"; auto test = GEOGL::make_unique<Test1>(startString); REQUIRE(test.get()); REQUIRE(test.get() != nullptr); /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test).getStoredString() == startString); REQUIRE(test->getStoredString() == startString); } SECTION("Testing with string Its as Easy as 123") { std::string startString = "ABC123DoReMiABC123"; auto test = GEOGL::make_unique<Test1>(startString); REQUIRE(test.get()); REQUIRE(test.get() != nullptr); /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test).getStoredString() == startString); REQUIRE(test->getStoredString() == startString); } SECTION("Testing with string Staring Michael Jackson") { std::string startString = "ABC123DoReMiABC123"; auto test = GEOGL::make_unique<Test1>(startString); REQUIRE(test.get()); REQUIRE(test.get() != nullptr); /* Test it both ways to ensure there is no difference in accessing the pointer */ REQUIRE((*test).getStoredString() == startString); REQUIRE(test->getStoredString() == startString); } }
[ "contact@matthewkrueger.com" ]
contact@matthewkrueger.com
736b1fe77342c9f83b3df438af513e6828c09ce6
09b7d2f60e3d710f9590dcc283ac0d94bea0938b
/modplayer.cpp
ba4d2b3c679b08757c77552c8461fa00bb6ba317
[]
no_license
metanas/Champions
fde617280bf59961b7a6acd102c34ebff0a153b1
6ac49e9c9f473adda157c9d6e9f13508b2625024
refs/heads/master
2020-04-03T14:04:56.514671
2017-07-14T16:38:34
2017-07-14T16:38:34
95,134,976
0
1
null
2017-07-14T16:38:35
2017-06-22T16:24:16
C++
UTF-8
C++
false
false
2,718
cpp
#include "modplayer.h" #include "ui_modplayer.h" #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlQueryModel> #include <QDebug> #include <QModelIndex> extern QSqlDatabase db; modplayer::modplayer(QWidget *parent) : QDialog(parent), ui(new Ui::modplayer) { ui->setupUi(this); } modplayer::~modplayer() { hide(); } void modplayer::on_pushButton_clicked() { hide(); } void modplayer::on_pushButton_2_clicked() { QSqlQueryModel *modal = new QSqlQueryModel(); QSqlQuery req; if (!ui->Equipe->text().isEmpty()) req.prepare("SELECT * FROM Joueur where Equipe='" + ui->Equipe->text() +"'"); else if (!ui->Nom->text().isEmpty()) req.prepare("SELECT * FROM Joueur where Nom='" + ui->Nom->text() + "'"); else if (!ui->Prenom->text().isEmpty()) req.prepare("SELECT * FROM Joueur where Prenom='" + ui->Prenom->text()+ "'"); else if (!ui->Num->text().isEmpty()) req.prepare("SELECT * FROM Joueur where Numero='" + ui->Num->text() + "'"); else if (!ui->dateEdit->text().isEmpty()) req.prepare("SELECT * FROM Joueur where Date_de_naissance='" + ui->dateEdit->text() + "'"); else if (!ui->Nast->text().isEmpty()) req.prepare("SELECT * FROM Joueur where nationalite='" + ui->Nast->text() + "'"); else if (!ui->Poste->currentText().isEmpty()) req.prepare("SELECT * FROM Joueur where Poste='" + ui->Poste->currentText() + "'"); req.exec(); modal->setQuery(req); ui->tableView->setModel(modal); } void modplayer::on_tableView_clicked(const QModelIndex &index) { QSqlQuery req; if (index.column() == 0){ req.prepare("SELECT * FROM Joueur where Nom='" + index.data().toString() + "'"); } req.exec(); req.next(); ui->Nom->setText(req.value(0).toString()); ui->Prenom->setText(req.value(1).toString()); ui->Num->setValue(req.value(2).toInt()); ui->dateEdit->setDate(req.value(3).toDate()); ui->Equipe->setText(req.value(4).toString()); QString post = req.value(5).toString(); int indx = ui->Poste->findText(post); ui->Poste->setCurrentIndex(indx); ui->Nast->setText(req.value(6).toString()); Player = req.value(0).toString(); } void modplayer::on_pushButton_3_clicked() { QSqlQuery req; req.prepare("Update Joueur set Nom='" +ui->Nom->text() + "', Prenom='" + ui->Prenom->text() + "', Numero=" + ui->Num->text() + ", Date_de_naissance='" + ui->dateEdit->text() + "', Equipe='" + ui->Equipe->text() + "', Poste='" +ui->Poste->currentText() + "', Nationalite='" + ui->Nast->text() + "' where Nom='" + Player + "'"); req.exec(); }
[ "metanas@pre-history.com" ]
metanas@pre-history.com
b3176918361d6464cad6e33f0797f99a6f246828
1a20961af3b03b46c109b09812143a7ef95c6caa
/Book/DX/DX9.Luna/BookICode/Book Part II Code/Chapter 3/D3DXCreate/d3dxcreate.cpp
b8ac5042ba2f4ac7f315a4c4197298aa9cfc6f9f
[]
no_license
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
6,657
cpp
////////////////////////////////////////////////////////////////////////////////////////////////// // // File: d3dxcreate.cpp // // Author: Frank D. Luna (C) All Rights Reserved // // System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 // // Desc: Renders several D3DX shapes in wireframe mode and has the camera // fly around the scene. Demonstrates the D3DXCreate* functions, and // demonstrates more complex transformations used to position the objects // in the world and move the camera around the world. // ////////////////////////////////////////////////////////////////////////////////////////////////// #include "d3dUtility.h" // // Globals // IDirect3DDevice9* Device = 0; const int Width = 640; const int Height = 480; // Store 5 objects. //z 创建了 5 个 ID3DXMesh object 。 ID3DXMesh* Objects[5] = {0, 0, 0, 0, 0}; // World matrices for each object. These matrices // specify the locations of the objects in the world. //z 2015-10-20 09:59 object 在 world 中的位置。 D3DXMATRIX ObjWorldMatrices[5]; // // Framework Functions // bool Setup() { // // Create the objects. // //z 2015-10-20 09:59 创建 teapot D3DXCreateTeapot( Device, &Objects[0], 0); //z 创建 box D3DXCreateBox( Device, 2.0f, // width 2.0f, // height 2.0f, // depth &Objects[1], 0); // cylinder is built aligned on z-axis //z 创建 cylinder D3DXCreateCylinder( Device, 1.0f, // radius at negative z end 1.0f, // radius at positive z end 3.0f, // length of cylinder 10, // slices 10, // stacks &Objects[2], 0); //z 创建 torus D3DXCreateTorus( Device, 1.0f, // inner radius 3.0f, // outer radius 10, // sides 10, // rings &Objects[3], 0); //z 创建 sphere D3DXCreateSphere( Device, 1.0f, // radius 10, // slices 10, // stacks &Objects[4], 0); // // Build world matrices - position the objects in world space. // For example, ObjWorldMatrices[1] will position Objects[1] at // (-5, 0, 5). Likewise, ObjWorldMatrices[2] will position // Objects[2] at (5, 0, 5). // //z 构建世界坐标系 matrices,将 objects 放置到 world space 中去。 D3DXMatrixTranslation(&ObjWorldMatrices[0], 0.0f, 0.0f, 0.0f); D3DXMatrixTranslation(&ObjWorldMatrices[1], -5.0f, 0.0f, 5.0f); D3DXMatrixTranslation(&ObjWorldMatrices[2], 5.0f, 0.0f, 5.0f); D3DXMatrixTranslation(&ObjWorldMatrices[3], -5.0f, 0.0f, -5.0f); D3DXMatrixTranslation(&ObjWorldMatrices[4], 5.0f, 0.0f, -5.0f); // // Set the projection matrix. // //z 设置 projection matrix 2015-10-20 10:01 D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); // // Switch to wireframe mode. // ///z 设置填充样式 Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); return true; } void Cleanup() { //z 使用完毕后,清理程序申请的资源 for(int i = 0; i < 5; i++) d3d::Release<ID3DXMesh*>(Objects[i]); } bool Display(float timeDelta) { if( Device ) { //z 总感觉还是比较抽象,不能太理解;估计得找找基本的图形学的书看看才好的。 //z 2015-10-20 10:02 让摄像机动起来 // Animate the camera: (详细描述了了 camera 是如何动的) // The camera will circle around the center of the scene. We use the // sin and cos functions to generate points on the circle, then scale them // by 10 to further the radius. In addition the camera will move up and down // as it circles about the scene. //z static float angle = (3.0f * D3DX_PI) / 2.0f; //z camera height 以及 camera height direction ,方向 static float cameraHeight = 0.0f; static float cameraHeightDirection = 5.0f; //z angel 以及 camera 等会发生变化。 D3DXVECTOR3 position( cosf(angle) * 10.0f, cameraHeight, sinf(angle) * 10.0f ); // the camera is targetted at the origin of the world //z target 为 world 的原点 D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); // the worlds up vector D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &position, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); // compute the position for the next frame angle += timeDelta; if( angle >= 6.28f ) angle = 0.0f; // compute the height of the camera for the next frame cameraHeight += cameraHeightDirection * timeDelta; if( cameraHeight >= 10.0f ) cameraHeightDirection = -5.0f; if( cameraHeight <= -10.0f ) cameraHeightDirection = 5.0f; // // Draw the Scene: // Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0); Device->BeginScene(); for(int i = 0; i < 5; i++) { //z 绘制生成的各个 mesh 。 // Set the world matrix that positions the object. Device->SetTransform(D3DTS_WORLD, &ObjWorldMatrices[i]); // Draw the object using the previously set world matrix. Objects[i]->DrawSubset(0); } Device->EndScene(); Device->Present(0, 0, 0, 0); } return true; } // // WndProc // LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch( msg ) { case WM_DESTROY: ::PostQuitMessage(0); break; case WM_KEYDOWN: if( wParam == VK_ESCAPE ) ::DestroyWindow(hwnd); break; } return ::DefWindowProc(hwnd, msg, wParam, lParam); } // // WinMain // int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { if(!d3d::InitD3D(hinstance, Width, Height, true, D3DDEVTYPE_HAL, &Device)) { ::MessageBox(0, "InitD3D() - FAILED", 0, 0); return 0; } if(!Setup()) { ::MessageBox(0, "Setup() - FAILED", 0, 0); return 0; } d3d::EnterMsgLoop( Display ); Cleanup(); Device->Release(); return 0; }
[ "126.org@gmail.com" ]
126.org@gmail.com
7edf3839297c5216f0d6a2b593b7417e34a5c84e
d2566520060aa4e0dc9ee53cca3cfe8b0bc09cb9
/src/IO/STLTxtMeshReader.hpp
9e2b4a8c7be5ab2903be251b120a907ed095f482
[ "BSD-2-Clause" ]
permissive
supermangithu/quinoa
f4a452de8ff1011a89dec1365a32730299ceecc1
2dd7ead9592b43a06fa25fec2f7fa7687f6169bf
refs/heads/master
2023-04-13T14:42:02.394865
2020-09-12T13:35:33
2020-09-12T13:35:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,455
hpp
// ***************************************************************************** /*! \file src/IO/STLTxtMeshReader.hpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019-2020 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief ASCII STL (STereoLithography) reader class declaration \details ASCII STL (STereoLithographu) reader class declaration. */ // ***************************************************************************** #ifndef STLTxtMeshReader_h #define STLTxtMeshReader_h #include <iostream> #include <stddef.h> #include <string> #include "Types.hpp" #include "Reader.hpp" #include "Exception.hpp" namespace tk { class STLMesh; //! \brief STLTxtMeshReader : tk::Reader //! \details Mesh reader class facilitating reading a mesh from a file in //! ASCII STL format. class STLTxtMeshReader : public Reader { public: //! Constructor explicit STLTxtMeshReader( const std::string& filename, STLMesh& mesh ); //! Read ASCII STL mesh void readMesh(); private: //! \brief ASCII STL keyword with operator>> redefined to do error checking //! without contaminating client-code struct STLKeyword { std::string read; //!< Keyword read in from input const std::string correct; //!< Keyword that should be read in //! Initializer constructor explicit STLKeyword( const std::string& corr ) noexcept : read(), correct(corr) {} //! Operator >> for reading a keyword and hande error friend std::ifstream& operator>> (std::ifstream& is, STLKeyword& kw) { is >> kw.read; ErrChk( kw.read == kw.correct, "Corruption in ASCII STL file while parsing keyword '" + kw.read + "', should be '" + kw.correct + "'" ); return is; } }; //! Read (or count vertices in) ASCII STL mesh std::size_t readFacets( const bool store, tk::real* const x = nullptr, tk::real* const y = nullptr, tk::real* const z = nullptr ); const bool STORE = true; //!< Indicator to store facets const bool COUNT = false; //!< Indicator to only count facets STLMesh& m_mesh; //!< Mesh }; } // tk:: #endif // STLTxtMeshReader_h
[ "jbakosi@lanl.gov" ]
jbakosi@lanl.gov
f4e1deb141f37ecccfdfb178dfa38fb950ea8573
c075cfe521103977789d600b61ad05b605f4fb10
/div 231/ZAD_A.cpp
3f03174e2170dedc5fef0c618699794593f11709
[]
no_license
igoroogle/codeforces
dd3c99b6a5ceb19d7d9495b370d4b2ef8949f534
579cd1d2aa30a0b0b4cc61d104a02499c69ac152
refs/heads/master
2020-07-20T12:37:07.225539
2019-09-05T19:21:27
2019-09-05T19:35:26
206,639,451
0
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; string s; int main() { int n, i, a = 0, b = 0, c = 0; cin >> s; n = s.length(); i = 0; while (s[i] != '+') { a++; i++; } i++; while (s[i] != '=') { b++; i++; } i++; while (i < n) { c++; i++; } if (a + b == c) cout << s << endl; else if ((c > 1) && (a + 1 + b == c - 1)) { cout << '|' << s.substr(0, n - 1) << endl; } else if ((a > 1) && (a - 1 + b == c + 1)) { cout << s.substr(1, n - 1) << '|' << endl; } else if ((b > 1) && (a + b - 1 == c + 1)) { cout << s.substr(0, a + b) << s.substr(a + b + 1, n - a - b) << '|' << endl; } else cout << "Impossible\n"; return 0; }
[ "160698qnigor98" ]
160698qnigor98
3912aa182835fbd99124ab32cd7179e289edc75f
2b7cefbcb2c3c393884f998bb1ca1b57badf8455
/addons/lsv/config.cpp
93630630237c475c35591042149631659ff1f3ca
[]
no_license
A3CN-CFOD/A3CN_Vehicles
3a6bafebe2c488db770ba5600955218a168c4ee0
7b4acfbdfbab92b11dee0c20be801c2073fd3ac5
refs/heads/master
2021-04-28T19:49:13.702634
2019-06-05T12:42:43
2019-06-05T12:42:43
121,905,127
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
class CfgPatches { class A3_Soft_F_Exp_LSV_02 { addonRootClass="A3_Soft_F_Exp"; requiredAddons[]= { "A3_Soft_F_Exp","a3cn_vehicles_main" }; requiredVersion=0.1; units[]= { "A3CN_LSV_01_BLACK","A3CN_LSV_02_ADAX","A3CN_LSV_02_ATAK","A3CN_LSV_02_CASCAVEL","A3CN_LSV_02_EVEREST","A3CN_LSV_02_KAPPA","A3CN_LSV_02_KRAKEN","A3CN_LSV_02_MYTRA","A3CN_LSV_02_TAIPAN","A3CN_LSV_02_VIBORA" }; weapons[]={}; }; }; #include "CfgFactionClasses.hpp" #include "CfgVehicles.hpp"
[ "jonathan.pereira@gmail.com" ]
jonathan.pereira@gmail.com
de756c8fcaa45e87ea0477ec614f72998dc334dc
31910701e20b9fbfc484b0bf446d45aa7611050c
/firmware/obsoleted/nixie_clock/clock_time.cpp
76a8fcacdee8f8ce25cea00a441b04ea09585546
[ "MIT" ]
permissive
shengwen-tw/nixie-clock
a9395bb66fdca4de8d06de103d5b81b81c366411
85358b9cba41331ac872cd237b1a8c61e36650e9
refs/heads/master
2023-08-24T00:35:45.704868
2020-02-23T14:17:50
2020-02-23T14:17:50
13,616,554
1
1
null
null
null
null
UTF-8
C++
false
false
7,351
cpp
#include <Arduino.h> #include <Wire.h> /* RTC Clock */ #include <Time.h> #include <DS1307RTC.h> /* Music player module */ #include <Garan.h> #include <SoftwareSerial.h> #include "pin_def.h" #include "display.h" #include "clock_time.h" SoftwareSerial garanSerial(bargan_rx, bargan_tx); Garan player(garanSerial); clock_time::clock_time() { clock_mode = CLOCK_TIME, time_mode = TIME_MODE; hour_format = FORMAT_24HR; now_set = HOUR; } /* Digit blink related functions */ int clock_time::get_blink_time() { return blink_time; } void clock_time::set_blink_time(int time) { blink_time = time; } void clock_time::set_blink_digit(int digit, int status) { status ? blink_digit[digit] = true : blink_digit[digit] = false; } void clock_time::clear_blink_digit() { for(int i = 0; i < 8; i++) blink_digit[i] = false; } bool clock_time::is_blink_digit(int digit) { for(int i = 0; i < 8; i++) { if(blink_digit[digit] == true) return true; } return false; } /* Clock mode functions */ int clock_time::get_clock_mode() { return clock_mode; } void clock_time::set_clock_mode(int mode) { clock_mode = mode; } int clock_time::get_time_mode() { return time_mode; } void clock_time::set_time_mode(int mode) { time_mode = mode; } int clock_time::get_hour_format() { return hour_format; } void clock_time::set_hour_format(int format) { format ? hour_format = FORMAT_24HR : hour_format = FORMAT_12HR; } /* Time display functions */ void clock_time::read_time() { cur_time.year = year(); cur_time.month = month(); cur_time.day = day(); hour_format ? cur_time.hour = hour() : cur_time.hour = hourFormat12(); cur_time.minute = minute(); cur_time.second = second(); } void clock_time::sort_to_digit(time *_time) { /* Year */ date_digit[7] = _time->year / 1000; date_digit[6] = (_time->year / 100) % 10; date_digit[5] = (_time->year / 10) % 100; date_digit[4] = _time->year % 10; /* Month */ date_digit[3] = _time->month / 10; date_digit[2] = _time->month % 10; /* Day */ date_digit[1] = _time->day / 10; date_digit[0] = _time->day % 10; /* Hour */ time_digit[7] = _time->hour / 10; time_digit[6] = _time->hour % 10; /* Minute*/ time_digit[4] = _time->minute / 10; time_digit[3] = _time->minute % 10; /* Second */ time_digit[1] = _time->second / 10; time_digit[0] = _time->second % 10; /* Empty */ time_digit[5] = EMPTY_DIGIT; time_digit[2] = EMPTY_DIGIT; } void clock_time::display_time() { /* Initial the time of the RTC if the flag of it is set to be timeNotSet */ if(timeStatus() == timeNotSet) initial_time(); /* If the RTC is not finished Initializing, stop actions */ else if(timeStatus() == timeNeedsSync) return; if(get_clock_mode() == CLOCK_ALARM || get_clock_mode() == CLOCK_ALARM_SETTING) { sort_to_digit(&alarm_time); set_time_mode(TIME_MODE); //Turn to the time mode } else { read_time(); sort_to_digit(&cur_time); } for(int i = 0; i < 8; i++) { /* Date mode */ if(time_mode == DATE_MODE) { if(get_blink_time() < blink_duty && is_blink_digit(i)) { continue; } else { show_number(date_digit[i], i); if(i == 2 || i == 4) show_dot(i); } /* Time mode */ } else if(time_mode == TIME_MODE) { if(time_digit[i] != EMPTY_DIGIT) { if(get_blink_time() < blink_duty && is_blink_digit(i)) continue; else show_number(time_digit[i], i); } else { show_dot(i); } /* Unknown mode */ } else { } delay(1); } } /* Time setting functons */ void clock_time::initial_time() { setTime(0, 0, 1, 1, 1, 2000); //Initial the time with 2000/1/1 - 0:0:1 set_alarm_time(12, 0, 0); //Set the alarm at 0:0:1 } int clock_time::get_now_setting() { return now_set; } void clock_time::set_setting_digit(int time) { now_set = time; /* XXX: Hardcode can be improve! */ switch(time) { case YEAR: set_blink_digit(7, ENABLE); set_blink_digit(6, ENABLE); set_blink_digit(5, ENABLE); set_blink_digit(4, ENABLE); break; case MONTH: set_blink_digit(3, ENABLE); set_blink_digit(2, ENABLE); break; case DAY: set_blink_digit(1, ENABLE); set_blink_digit(0, ENABLE); break; case HOUR: set_blink_digit(7, ENABLE); set_blink_digit(6, ENABLE); break; case MINUTE: set_blink_digit(4, ENABLE); set_blink_digit(3, ENABLE); break; case SECOND: set_blink_digit(1, ENABLE); set_blink_digit(0, ENABLE); break; } } void clock_time::inc_in_range(int *num, int lower, int upper) { if(*num >= lower && *num < upper) (*num)++; else *num = lower; } void clock_time::inc_time(int clock_mode) { time *_time; if(clock_mode == CLOCK_TIME) _time = &cur_time; else if(clock_mode == CLOCK_ALARM) _time = &alarm_time; switch(get_now_setting()) { case YEAR: inc_in_range(&_time->year, 2000, 2100); break; case MONTH: inc_in_range(&_time->month, 1, 12); break; case DAY: /* If the current month is set to be february */ if(cur_time.month == 2) { if(isleap(_time->year)) inc_in_range(&_time->day, 1, 29); //Is the leap year else inc_in_range(&_time->day, 1, 28); //Not the leap year /* These month contain 30 days */ } else if(cur_time.month == 2 || cur_time.month == 4 || cur_time.month == 6 || cur_time.month == 9 || cur_time.month == 11){ inc_in_range(&_time->day, 1, 30); /* These month contain 31 days */ } else { inc_in_range(&_time->day, 1, 31); } break; case HOUR: inc_in_range(&_time->hour, 0, 23); break; case MINUTE: inc_in_range(&_time->minute, 0, 59); break; case SECOND: inc_in_range(&_time->second, 0, 59); break; } setTime(cur_time.hour, cur_time.minute, cur_time.second, cur_time.day, cur_time.month, cur_time.year); } /* Music functions */ void clock_time::play_music(char *music_name) { player.setVolume(5); //FIXME:The volume should be initialized at other place player.singlePlay(1); //player.singlePlayName(music_name); //FIXME:Dosen't work } void stop_music() { } /* Alarm related functions */ void clock_time::set_alarm_time(int hour, int minute, int second) { alarm_time.hour = hour; alarm_time.minute = minute; alarm_time.second = second; } bool clock_time::check_alarm_time() { //If the current time minus the alarm time equal means time's up return !(bool)(cur_time.hour - alarm_time.hour + cur_time.minute - alarm_time.minute + cur_time.second - alarm_time.second); }
[ "l1996812@gmail.com" ]
l1996812@gmail.com
b01c53545116f5cbc4e1ee628476c5083e399a53
597fb3047835a8c9f53289fa71ecc74b067f24cd
/units_ve/wb_vga_lcd/tests/wb_vga_lcd_test_base.cpp
e26da07cc763bff69af777c6cc03e6f19c67fae8
[]
no_license
yeloer/socblox
5ad7fb6e82ac29f2d57f7d758501f87f568b5562
d2e83c343dfdac477e23b9b31b8d3a32a1238073
refs/heads/master
2020-05-31T23:30:36.277012
2016-03-01T00:49:40
2016-03-01T00:49:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,294
cpp
/* * wb_vga_lcd_test_base.cpp * * Created on: Jan 11, 2014 * Author: ballance */ #include "wb_vga_lcd_test_base.h" #include "svf_elf_loader.h" wb_vga_lcd_test_base::wb_vga_lcd_test_base(const char *name) : svf_test(name) { // TODO Auto-generated constructor stub } wb_vga_lcd_test_base::~wb_vga_lcd_test_base() { // TODO Auto-generated destructor stub } void wb_vga_lcd_test_base::build() { m_env = wb_vga_lcd_env::type_id.create("m_env", this); } void wb_vga_lcd_test_base::connect() { const char *TB_ROOT_c; if (!get_config_string("TB_ROOT", &TB_ROOT_c)) { fprintf(stdout, "FATAL"); } string TB_ROOT(TB_ROOT_c); // TODO: connect BFMs wb_master_bfm_dpi_mgr::connect(TB_ROOT + ".bfm0", m_env->bfm0->bfm_port); } void wb_vga_lcd_test_base::start() { m_runthread.init(this, &wb_vga_lcd_test_base::run); m_runthread.start(); } void wb_vga_lcd_test_base::run() { svf_string target_exe; svf_string testname = "unknown"; fprintf(stdout, "run thread\n"); raise_objection(); if (!cmdline().valueplusarg("TARGET_EXE=", target_exe)) { // TODO: fatal } cmdline().valueplusarg("TESTNAME=", testname); } void wb_vga_lcd_test_base::shutdown() { } svf_test_ctor_def(wb_vga_lcd_test_base)
[ "ballance@ballance-VirtualBox" ]
ballance@ballance-VirtualBox
fede79543bec725355e07ac2aa95c98e894172a6
a15950e54e6775e6f7f7004bb90a5585405eade7
/services/service_manager/sandbox/switches.cc
2854d5025c7caf557a596a5d881be186144d0918
[ "BSD-3-Clause" ]
permissive
whycoding126/chromium
19f6b44d0ec3e4f1b5ef61cc083cae587de3df73
9191e417b00328d59a7060fa6bbef061a3fe4ce4
refs/heads/master
2023-02-26T22:57:28.582142
2018-04-09T11:12:57
2018-04-09T11:12:57
128,760,157
1
0
null
2018-04-09T11:17:03
2018-04-09T11:17:03
null
UTF-8
C++
false
false
4,110
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/service_manager/sandbox/switches.h" #include "build/build_config.h" #if defined(OS_WIN) #include "base/command_line.h" #include "base/win/windows_version.h" #endif namespace service_manager { namespace switches { // Type of sandbox to apply to the process running the service, one of the // values in the next block. const char kServiceSandboxType[] = "service-sandbox-type"; // Must be in sync with "sandbox_type" values as used in service manager's // manifest.json catalog files. const char kNoneSandbox[] = "none"; const char kNoneSandboxAndElevatedPrivileges[] = "none_and_elevated"; const char kNetworkSandbox[] = "network"; const char kPpapiSandbox[] = "ppapi"; const char kUtilitySandbox[] = "utility"; const char kCdmSandbox[] = "cdm"; const char kPdfCompositorSandbox[] = "pdf_compositor"; const char kProfilingSandbox[] = "profiling"; // Flags owned by the service manager sandbox. // Enables the sandboxed processes to run without a job object assigned to them. // This flag is required to allow Chrome to run in RemoteApps or Citrix. This // flag can reduce the security of the sandboxed processes and allow them to do // certain API calls like shut down Windows or access the clipboard. Also we // lose the chance to kill some processes until the outer job that owns them // finishes. const char kAllowNoSandboxJob[] = "allow-no-sandbox-job"; // Allows debugging of sandboxed processes (see zygote_main_linux.cc). const char kAllowSandboxDebugging[] = "allow-sandbox-debugging"; // Disable appcontainer/lowbox for renderer on Win8+ platforms. const char kDisableAppContainer[] = "disable-appcontainer"; // Disable the seccomp filter sandbox (seccomp-bpf) (Linux only). const char kDisableSeccompFilterSandbox[] = "disable-seccomp-filter-sandbox"; // Disable the setuid sandbox (Linux only). const char kDisableSetuidSandbox[] = "disable-setuid-sandbox"; // Disables the Win32K process mitigation policy for child processes. const char kDisableWin32kLockDown[] = "disable-win32k-lockdown"; // Ensable appcontainer/lowbox for renderer on Win8+ platforms. const char kEnableAppContainer[] = "enable-appcontainer"; // Allows shmat() system call in the GPU sandbox. const char kGpuSandboxAllowSysVShm[] = "gpu-sandbox-allow-sysv-shm"; // Makes GPU sandbox failures fatal. const char kGpuSandboxFailuresFatal[] = "gpu-sandbox-failures-fatal"; #if defined(OS_WIN) // Allows third party modules to inject by disabling the BINARY_SIGNATURE // mitigation policy on Win10+. Also has other effects in ELF. const char kAllowThirdPartyModules[] = "allow-third-party-modules"; // Add additional capabilities to the AppContainer sandbox on the GPU process. const char kAddGpuAppContainerCaps[] = "add-gpu-appcontainer-caps"; // Disables AppContainer sandbox on the GPU process. const char kDisableGpuAppContainer[] = "disable-gpu-appcontainer"; // Disables low-privilege AppContainer sandbox on the GPU process. const char kDisableGpuLpac[] = "disable-gpu-lpac"; // Enables AppContainer sandbox on the GPU process. const char kEnableGpuAppContainer[] = "enable-gpu-appcontainer"; #endif // Flags spied upon from other layers. const char kGpuProcess[] = "gpu-process"; const char kPpapiBrokerProcess[] = "ppapi-broker"; const char kPpapiPluginProcess[] = "ppapi"; const char kRendererProcess[] = "renderer"; const char kUtilityProcess[] = "utility"; const char kDisableGpuSandbox[] = "disable-gpu-sandbox"; const char kNoSandbox[] = "no-sandbox"; #if defined(OS_WIN) const char kNoSandboxAndElevatedPrivileges[] = "no-sandbox-and-elevated"; #endif const char kEnableSandboxLogging[] = "enable-sandbox-logging"; } // namespace switches #if defined(OS_WIN) bool IsWin32kLockdownEnabled() { return base::win::GetVersion() >= base::win::VERSION_WIN8 && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableWin32kLockDown); } #endif } // namespace service_manager
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
cc366e06f16f364d420441fb61691dddddc2f742
9f6a6ea3dcf25a9a9e75b5ff525a236ccecf6b82
/List.h
9711bd023e37b9a46b255c3d41fda127ff5f46dd
[]
no_license
nathand777/Assignment-3-UNO
334542b34126878fb039659a68f3d5e7f9377eda
18e5c5d9e9fb79c5fef030a895df0c2613509890
refs/heads/master
2021-03-22T04:30:40.846406
2017-04-29T17:17:07
2017-04-29T17:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,395
h
#pragma once #include <assert.h> const int DEFAULT_LIST = 200; template <class T> class List { public: List(unsigned int capacity = DEFAULT_LIST); // constructor for an empty list of specified capacity; // if capacity is not supplied, the default size is used ~List(); // destructor bool isEmpty() const; // returns true if the list is empty, and false otherwise bool isFull() const; // returns true if the list is full, and false otherwise unsigned int getLength() const; // returns the number of Ts currently in the list void insert(unsigned int pos, T item); // inserts T into the list at location pos; // PRECONDITION: pos is between 1 and getLength()+1 T remove(unsigned int pos); // removes the element at location pos from the list, and returns it; // PRECONDITION: the list is not empty, and pos is between 1 and getLength(); T retrieve(unsigned int pos) const; // find the element stored at location pos in the list and return it; // PRECONDITION: the list is not empty, and pos is between 1 and getLength(); T replace(unsigned int pos, T item); // replace the element at location pos in the list with T, // and return the element that was displaced; // PRECONDITION: the list is not empty, and pos is between 1 and getLength(); void append(T item) { return insert(getLength() + 1, item); } // adds an T at the back of the list T back() const { return retrieve(getLength()); } // retrieves an T from the back of the list T popBack() { return remove(getLength()); } // removes an T from the back of the list void swap(unsigned int i, unsigned int j); // swaps two Ts located in positions i and j template <class Equality> // "find" uses linear search to return position of the first T identical to "key", int find(T key) const; // returns -1 if no identical T is found. Extra template argument <class Equality> // must be a functor like "IsEqual" or "IsEqualDeref" defined in StandardFunctors.h. // EXAMPLE: call lst.find<IsEqual>(4) returns location of integer 4 inside List<int> lst; template <class Order> // these two functions sort (via either "selection" or "insertion" sorting algorithms) void selectionSort(); // content of the list based on specified "Order". Additional template argument <class Order> // should be a comparison functor like "IsLess" or "IsGreaterDeref" from StandardFunctors.h template <class Order> // EXAMPLE: can be called in main() as a.selectionSort<IsLess>(); void insertionSort(); // to sort integers in List<int> a; in increasing order private: T * m_container; // pointer to array to hold the list unsigned int m_max_capacity; // maximum capacity of the list unsigned int m_size; // number of Ts currently in the list unsigned int translate(unsigned int pos) const; // converts a list position to the corresponding array index void replaceContainer(); // private function replaces the underlying array with one that holds // the same values as the original, but has double the capacity public: class Iterator { private: T* _ptr; public: Iterator(T* ptr):_ptr(ptr){} Iterator operator++() { Iterator i = *this; _ptr++; return i; } // for forward traversing, e,g, Iterator i=begin(); ... ++i; bool operator != (const Iterator& b) { return _ptr != b._ptr; } T operator *() { return *_ptr; } T getValue() { return *_ptr; } void setValue(T val) { *_ptr = val; } }; // linked list objects create forward-traversal iterators using the two functions below Iterator begin() { return Iterator(&m_container[0]); } Iterator end() { return Iterator(&m_container[m_size]); } }; template <class T> List<T> ::List(unsigned int capacity) { m_max_capacity = capacity; m_container = new T[m_max_capacity]; m_size = 0; } template <class T> List<T> :: ~List() { delete[] m_container; } template <class T> bool List<T> ::isEmpty() const { return (m_size == 0); } template <class T> bool List<T> ::isFull() const { return false; } template <class T> unsigned int List<T> ::getLength() const { return m_size; } template <class T> void List<T> ::insert(unsigned int pos, T item) { // PRECONDITION: pos is between 1 and m_size+1 assert((pos >= 1) && (pos <= m_size + 1)&& "List index is out of bounds (in insert)"); if (m_size == m_max_capacity) replaceContainer(); for (unsigned int k = m_size; k >= pos; k--) m_container[translate(k + 1)] = m_container[translate(k)]; m_container[translate(pos)] = item; m_size++; } template <class T> T List<T> ::remove(unsigned int pos) { // PRECONDITION: the list is not empty, and pos is between 1 and m_size assert((pos >= 1) && (pos <= m_size)&& "List index is out of bounds (in remove)"); T returnValue = m_container[translate(pos)]; for (unsigned int k = pos + 1; k <= m_size; k++) m_container[translate(k - 1)] = m_container[translate(k)]; m_size--; return returnValue; } template <class T> T List<T> ::retrieve(unsigned int pos) const { // PRECONDITION: the list is not empty, and pos is between 1 and m_size assert((pos >= 1) && (pos <= m_size)&& "List index is out of bounds (in retrieve)"); return m_container[translate(pos)]; } template <class T> T List<T> ::replace(unsigned int pos, T item) { // PRECONDITION: the list is not empty, and pos is between 1 and m_size assert((pos >= 1) && (pos <= m_size)&& "List index is out of bounds (in replace)"); T returnVal = m_container[translate(pos)]; m_container[translate(pos)] = item; return returnVal; } template <class T> void List<T> ::swap(unsigned i, unsigned j) { // PRECONDITION: indexes iand j should be within the range of the list assert((i >= 1) && (i <= m_size) && (j >= 1) && (j <= m_size) && "List index is out of bounds (in swap)"); if (i == j) return; T temp = m_container[translate(i)]; m_container[translate(i)] = m_container[translate(j)]; m_container[translate(j)] = temp; } template <class T> unsigned int List<T> ::translate(unsigned int pos) const { return pos - 1; } template <class T> void List<T> ::replaceContainer() { T * newList; newList = new T[2 * m_max_capacity]; for (unsigned int k = 0; k < m_size; k++) newList[k] = m_container[k]; m_max_capacity = 2 * m_max_capacity; delete[] m_container; m_container = newList; } template <class T> template <class Equality> int List<T> ::find(T key) const { for (unsigned int i = 1; i <= getLength(); i++) if (Equality::compare(retrieve(i), key)) return i; return -1; } template <class T> template <class Order> void List<T> ::selectionSort() { unsigned minSoFar, i, k; for (i = 1; i < getLength(); i++) { // unsorted part starts at i minSoFar = i; for (k = i + 1; k <= getLength(); k++) { //searching for minimum T in the unsorted part if (Order::compare(retrieve(k), retrieve(minSoFar))) minSoFar = k; } swap(i, minSoFar); // moving min T into the end of the sorted part } } template <class T> template <class Order> void List<T>::insertionSort() { unsigned i, k; for (i = 2; i <= getLength(); i++) { // moving i-th T into the sorted part of container for (k = i - 1; k > 0; k--) { if (Order::compare(retrieve(k), retrieve(k + 1))) break; else swap(k, k + 1); // NOTE: i-th T is shifted "down" until the right spot } // inside sorted part [1 <= k <= (i-1)] is found } }
[ "natha@DESKTOP-BAGU637" ]
natha@DESKTOP-BAGU637
587fda175486bf9c2e54c7298d4493cbc5243920
6e9b20902f4e232d12e865f192ea5128ae253ba7
/Fluid/4.8/phi
9b4aadadf58e82eb61c418f5386584ae5c262ccc
[]
no_license
abarcaortega/FSI_3
1de5ed06ca7731016e5136820aecdc0a74042723
016638757f56e7b8b33af4a1af8e0635b88ffbbc
refs/heads/master
2020-08-03T22:28:04.707884
2019-09-30T16:33:31
2019-09-30T16:33:31
211,905,379
0
0
null
null
null
null
UTF-8
C++
false
false
55,477
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "4.8"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 5457 ( 0.198418 0.00158237 0.19648 0.00193735 0.194192 0.00228805 0.191509 0.00268354 0.188428 0.00308114 0.184951 0.0034767 0.181072 0.00387849 0.176778 0.00429392 0.17205 0.00472811 0.166865 0.0051851 0.161197 0.00566837 0.155016 0.00618088 0.148291 0.0067248 0.14099 0.00730116 0.133081 0.00790932 0.124534 0.00854626 0.115329 0.0092057 0.105452 0.009877 0.0949078 0.0105439 0.0837245 0.0111834 0.07196 0.0117645 0.0597117 0.0122482 0.047123 0.0125887 0.0343828 0.0127402 0.0216877 0.0126951 0.0090374 0.0126502 -0.00291637 0.0119538 -0.00847229 0.00555593 -0.0080431 -0.00042919 -0.0080431 0.199928 0.0016542 0.199176 0.00268977 0.197965 0.00349896 0.196332 0.00431668 0.194272 0.00514114 0.191782 0.0059667 0.188855 0.0068054 0.185478 0.00767069 0.181633 0.00857292 0.177298 0.00952039 0.172446 0.0105204 0.167048 0.0115791 0.161071 0.0127014 0.154482 0.0138899 0.147247 0.0151442 0.139335 0.0164592 0.130717 0.0178234 0.121377 0.019217 0.111312 0.0206086 0.100542 0.0219531 0.0891181 0.0231889 0.0771305 0.0242358 0.0647245 0.0249947 0.052117 0.0253478 0.0396565 0.0251556 0.0281063 0.0242005 0.0185956 0.0214644 0.00879771 0.0153538 0.00118375 0.00718477 -0.00685935 0.199781 0.00187363 0.199087 0.00338359 0.197946 0.00463986 0.196409 0.00585326 0.194483 0.00706723 0.192164 0.0082857 0.189447 0.00952276 0.186321 0.0107961 0.182774 0.0121207 0.178785 0.0135092 0.174333 0.0149724 0.169392 0.01652 0.163933 0.0181598 0.157926 0.019897 0.151338 0.0217323 0.144137 0.0236608 0.136291 0.0256687 0.127778 0.0277307 0.118581 0.0298053 0.108703 0.0318309 0.0981715 0.0337206 0.0870492 0.0353581 0.0754525 0.0365914 0.0635753 0.037225 0.0517333 0.0369976 0.0403979 0.0355359 0.0297395 0.0321228 0.0191664 0.0259269 0.00959786 0.0167533 0.00273851 0.199703 0.00217056 0.199008 0.00407889 0.197887 0.00576036 0.196376 0.00736413 0.194488 0.0089553 0.192222 0.0105516 0.189575 0.0121704 0.186539 0.013832 0.183104 0.0155551 0.179258 0.0173555 0.174983 0.0192473 0.170261 0.0212425 0.165069 0.0233514 0.159385 0.025581 0.153184 0.0279339 0.146438 0.0304058 0.139124 0.032983 0.131217 0.0356379 0.122698 0.0383244 0.113557 0.0409716 0.1038 0.0434775 0.0934579 0.0457006 0.0825966 0.0474526 0.0713338 0.0484878 0.0598418 0.0484896 0.0483176 0.0470601 0.0368115 0.0436289 0.0251882 0.0375502 0.0133357 0.0286058 0.0160742 0.199667 0.00250314 0.198964 0.00478213 0.197863 0.00686166 0.196381 0.00884578 0.194532 0.010804 0.192318 0.0127662 0.189734 0.0147541 0.186776 0.0167905 0.183434 0.0188967 0.179698 0.0210912 0.175556 0.0233901 0.170991 0.0258075 0.165987 0.0283551 0.160527 0.0310411 0.154591 0.0338693 0.148161 0.0368362 0.141215 0.0399286 0.133734 0.0431192 0.125697 0.0463611 0.117088 0.0495809 0.107895 0.0526709 0.0981156 0.0554796 0.0877656 0.0578026 0.0768795 0.0593739 0.0655094 0.0598597 0.0537086 0.058861 0.0414544 0.0558831 0.028588 0.0504166 0.0148525 0.0423413 0.0309267 0.199653 0.00285033 0.198949 0.00548618 0.197871 0.00793958 0.196427 0.0102899 0.194627 0.012604 0.192473 0.0149197 0.189964 0.0172637 0.187093 0.0196613 0.183854 0.0221359 0.180237 0.0247083 0.17623 0.0273965 0.171822 0.030216 0.166997 0.0331797 0.161741 0.0362969 0.156038 0.039572 0.149872 0.0430027 0.143224 0.0465767 0.136074 0.0502685 0.128402 0.0540333 0.120183 0.0578005 0.111388 0.0614652 0.10199 0.0648784 0.0919555 0.0678368 0.0812546 0.0700748 0.0698547 0.0712596 0.0577172 0.0709984 0.0447609 0.0688394 0.0308493 0.0643282 0.0158732 0.0573174 0.0467999 0.19965 0.00320027 0.198954 0.00618216 0.197904 0.00898919 0.196505 0.0116896 0.194763 0.0143462 0.192681 0.0170017 0.190257 0.0196873 0.187487 0.0224309 0.184365 0.0252579 0.180883 0.0281912 0.177029 0.0312504 0.172792 0.0344525 0.16816 0.0378117 0.163119 0.0413384 0.157653 0.0450382 0.151745 0.0489101 0.145378 0.0529442 0.138529 0.0571179 0.13117 0.0613914 0.12327 0.0657012 0.114783 0.0699519 0.105655 0.0740062 0.0958173 0.0776747 0.0851866 0.0807054 0.0736686 0.0827776 0.0611617 0.0835053 0.0475554 0.0824457 0.0327587 0.0791249 0.0167829 0.0732932 0.0635828 0.199655 0.00354562 0.198975 0.00686226 0.197959 0.0100049 0.19661 0.0130383 0.194934 0.0160222 0.192934 0.0190022 0.190608 0.0220133 0.187952 0.025086 0.184962 0.0282478 0.18163 0.0315232 0.177947 0.0349337 0.173902 0.0384978 0.169482 0.0422311 0.164675 0.0461457 0.159464 0.0502489 0.153832 0.0545423 0.147757 0.0590193 0.141212 0.0636625 0.134164 0.0684396 0.126568 0.0732979 0.118362 0.078157 0.10947 0.082899 0.0997869 0.0873574 0.0891876 0.0913046 0.0775254 0.0944399 0.0646475 0.0963832 0.0504175 0.0966758 0.0347682 0.0947743 0.0177898 0.0902715 0.0813726 0.199664 0.00388144 0.199006 0.00752006 0.19803 0.0109812 0.196739 0.0143297 0.195137 0.0176242 0.193227 0.020912 0.191009 0.0242311 0.188481 0.0276146 0.185637 0.0310917 0.182471 0.0346888 0.178976 0.038429 0.175141 0.0423326 0.170955 0.0464169 0.166405 0.050696 0.161474 0.0551798 0.156143 0.0598735 0.150387 0.0647754 0.144174 0.0698753 0.137462 0.075151 0.130196 0.0805643 0.122298 0.0860546 0.113667 0.0915301 0.104169 0.0968559 0.0936342 0.101839 0.0818649 0.106209 0.0686495 0.109599 0.053802 0.111523 0.0372365 0.11134 0.0190834 0.108425 0.100456 0.199677 0.00420422 0.199047 0.0081503 0.198116 0.0119125 0.196887 0.015558 0.195367 0.0191451 0.193556 0.0227226 0.191456 0.0263309 0.189065 0.0300053 0.18638 0.0337769 0.183395 0.0376736 0.180104 0.0417202 0.176498 0.0459387 0.172567 0.0503484 0.168297 0.054966 0.163672 0.0598045 0.158672 0.0648736 0.153269 0.0701779 0.147429 0.075716 0.141101 0.0814786 0.134221 0.0874449 0.126696 0.0935789 0.118405 0.099821 0.109184 0.106078 0.0988197 0.112203 0.0870527 0.117976 0.0735899 0.123061 0.0581485 0.126965 0.0405519 0.128936 0.0209013 0.128075 0.121357 0.199693 0.00451129 0.199095 0.00874868 0.198213 0.0127941 0.197053 0.0167177 0.19562 0.0205785 0.193916 0.0244264 0.191943 0.0283039 0.1897 0.0322482 0.187185 0.0362919 0.184394 0.0404645 0.181322 0.0447923 0.177962 0.0492991 0.174304 0.0540063 0.170337 0.0589331 0.166045 0.0640965 0.161408 0.0695108 0.156398 0.0751881 0.150977 0.0811369 0.145093 0.0873624 0.138674 0.093864 0.131619 0.100634 0.12379 0.10765 0.114996 0.114871 0.104983 0.122216 0.0934191 0.12954 0.0798981 0.136582 0.063968 0.142895 0.0452348 0.14767 0.0236116 0.149698 0.144969 0.199711 0.0048006 0.199148 0.00931169 0.19832 0.0136217 0.197234 0.0178039 0.195894 0.0219186 0.194303 0.0260167 0.192465 0.0301424 0.190379 0.0343343 0.188044 0.0386266 0.185459 0.04305 0.182619 0.0476322 0.179519 0.0523987 0.176152 0.0573729 0.172509 0.0625766 0.168575 0.0680303 0.164332 0.0737539 0.159754 0.0797664 0.154803 0.0860872 0.14943 0.092736 0.14356 0.0997337 0.137091 0.107102 0.129878 0.114863 0.121716 0.123034 0.112315 0.131618 0.101273 0.140581 0.0880455 0.14981 0.0719231 0.159017 0.0520863 0.167506 0.0278856 0.173899 0.172855 0.19973 0.00507053 0.199205 0.00983647 0.198435 0.0143917 0.197427 0.0188126 0.196185 0.0231606 0.194713 0.0274879 0.193016 0.0318398 0.191094 0.0362562 0.188948 0.0407724 0.186578 0.0454203 0.183981 0.0502287 0.181156 0.0552245 0.178096 0.0604328 0.174795 0.0658777 0.171242 0.0715832 0.167422 0.0775739 0.163313 0.0838755 0.158883 0.0905172 0.154086 0.0975327 0.148857 0.104963 0.143101 0.112858 0.13668 0.121284 0.129393 0.130321 0.120942 0.140068 0.110883 0.15064 0.0985434 0.16215 0.0829014 0.174659 0.0624358 0.187972 0.0351248 0.20121 0.207979 0.199751 0.00531983 0.199266 0.0103207 0.198557 0.0151011 0.197629 0.0197401 0.19649 0.0243005 0.195142 0.0288352 0.193591 0.0333906 0.19184 0.0380076 0.18989 0.0427224 0.187743 0.0475675 0.185399 0.0525727 0.182858 0.0577658 0.180117 0.0631732 0.177174 0.0688211 0.174021 0.0747359 0.170649 0.0809459 0.167042 0.0874825 0.163177 0.0943826 0.159018 0.101691 0.154516 0.109465 0.149594 0.11778 0.144142 0.126736 0.137993 0.136471 0.130886 0.147175 0.122407 0.159119 0.111861 0.172696 0.0980177 0.188502 0.0785372 0.207452 0.0486638 0.231084 0.256643 0.199772 0.00554753 0.19933 0.0107626 0.198684 0.0157476 0.19784 0.0205837 0.196806 0.0253349 0.195586 0.0300549 0.194186 0.0347907 0.19261 0.0395839 0.190861 0.0444712 0.188943 0.0494855 0.186859 0.0546572 0.18461 0.0600145 0.182198 0.0655847 0.179624 0.071395 0.176887 0.0774735 0.173982 0.0838508 0.170902 0.090562 0.167637 0.0976486 0.164165 0.105163 0.160459 0.113171 0.156474 0.121765 0.152145 0.131065 0.147371 0.141244 0.141995 0.152552 0.135751 0.165363 0.128171 0.180277 0.118312 0.198361 0.103923 0.221841 0.0776904 0.257316 0.334334 0.00369613 -0.00369613 0.00724843 -0.0035523 0.0101998 -0.00295133 0.0125476 -0.00234788 0.0143895 -0.00184183 0.0158284 -0.00143894 0.0169538 -0.0011254 0.0178393 -0.000885485 0.0185442 -0.000704952 0.0191161 -0.00057185 0.0195926 -0.000476498 0.0200036 -0.00041103 0.0203723 -0.000368693 0.0207155 -0.000343146 0.0210434 -0.000327916 0.0213595 -0.000316155 0.0216604 -0.000300864 0.0219362 -0.000275809 0.0221733 -0.000237085 0.022358 -0.000184663 0.0224807 -0.000122707 0.0225386 -5.79858e-05 0.0225381 5.54869e-07 0.0224759 6.21962e-05 0.0223507 0.00012516 0.0221536 0.000197096 0.0218837 0.000269942 0.0215549 0.000328812 0.0212149 0.000339971 0.000241183 0.00339372 -0.00708985 0.00667354 -0.00683212 0.00944597 -0.00572376 0.011717 -0.00461895 0.0135786 -0.00370341 0.0151208 -0.00298111 0.0164182 -0.00242278 0.0175292 -0.00199653 0.0184993 -0.001675 0.0193637 -0.00143623 0.02015 -0.00126281 0.0208798 -0.00114086 0.0215699 -0.0010588 0.022233 -0.00100626 0.0228782 -0.000973055 0.0235106 -0.000948634 0.0241318 -0.000922055 0.0247391 -0.000883068 0.0253265 -0.000824506 0.025887 -0.000745109 0.0264149 -0.000650627 0.0269077 -0.000550851 0.0273606 -0.000452274 0.0277732 -0.000350424 0.0281385 -0.000240136 0.0284444 -0.000108812 0.028675 3.93658e-05 0.0288339 0.000169902 0.0289596 0.000214285 0.000163375 0.00283802 -0.00992786 0.00547465 -0.00946876 0.00765129 -0.0079004 0.0094147 -0.00638236 0.0108579 -0.00514666 0.0120579 -0.00418108 0.0130756 -0.00344044 0.0139548 -0.00287579 0.0147284 -0.0024486 0.0154217 -0.0021295 0.0160545 -0.00189563 0.0166426 -0.0017289 0.0171982 -0.00161444 0.017731 -0.00153912 0.0182484 -0.00149046 0.0187554 -0.00145561 0.0192543 -0.00142097 0.0197444 -0.00137315 0.0202218 -0.00130188 0.0206809 -0.00120418 0.0211171 -0.00108689 0.0215301 -0.00096382 0.0219244 -0.000846543 0.0223087 -0.000734759 0.0226875 -0.000618938 0.0230635 -0.000484815 0.0234312 -0.000328342 0.0237689 -0.000167758 0.0240394 -5.62198e-05 -5.75634e-06 0.00222489 -0.0121527 0.00410702 -0.0113509 0.0055675 -0.00936088 0.00671214 -0.007527 0.00763183 -0.00606635 0.00838467 -0.00493391 0.00901683 -0.0040726 0.00955527 -0.00341424 0.0100194 -0.00291272 0.0104245 -0.00253456 0.0107826 -0.00225382 0.0111039 -0.00205013 0.0113962 -0.00190679 0.0116665 -0.00180935 0.0119205 -0.00174447 0.0121635 -0.00169864 0.0123996 -0.0016571 0.0126307 -0.00160422 0.0128553 -0.00152648 0.0130687 -0.00141757 0.0132648 -0.00128305 0.0134405 -0.00113953 0.0135987 -0.00100474 0.0137486 -0.000884613 0.0138996 -0.000769933 0.0140555 -0.000640669 0.0142085 -0.00048143 0.0143417 -0.000300962 0.0144099 -0.000124355 -4.07503e-05 0.00151261 -0.0136654 0.00256096 -0.0123992 0.00324242 -0.0100423 0.00370722 -0.0079918 0.00403954 -0.00639867 0.00427137 -0.00516574 0.0044378 -0.00423903 0.0045492 -0.00352564 0.0046149 -0.00297842 0.00464299 -0.00256265 0.00464006 -0.00225088 0.00461159 -0.00202167 0.00456239 -0.00185759 0.00449708 -0.00174403 0.00442065 -0.00166804 0.00433882 -0.00161681 0.00425759 -0.00157586 0.00418174 -0.00152837 0.00411278 -0.00145752 0.00404688 -0.00135167 0.00397399 -0.00121016 0.00388004 -0.00104557 0.00375356 -0.00087827 0.0035916 -0.000722648 0.00340072 -0.000579053 0.00319898 -0.000438928 0.00299584 -0.00027829 0.00277198 -7.71043e-05 0.00255568 9.19429e-05 8.75653e-05 0.000693041 -0.0143584 0.000839028 -0.0125452 0.000702596 -0.00990591 0.000460335 -0.00774954 0.000141246 -0.00607958 -0.000206389 -0.0048181 -0.000578533 -0.00386688 -0.000965773 -0.0031384 -0.00136153 -0.00258266 -0.00176014 -0.00216404 -0.00215765 -0.00185337 -0.00255098 -0.00162834 -0.00293732 -0.00147125 -0.0033139 -0.00136745 -0.00367742 -0.00130452 -0.00402367 -0.00127056 -0.00434792 -0.00125162 -0.00464641 -0.00122988 -0.00491801 -0.00118592 -0.005165 -0.00110468 -0.00539323 -0.000981928 -0.00561188 -0.000826922 -0.00583173 -0.000658421 -0.00606107 -0.000493316 -0.00630288 -0.000337241 -0.00656352 -0.000178284 -0.00684155 -2.63899e-07 -0.00708029 0.000161635 -0.00723103 0.00024269 0.000214114 -0.000266186 -0.0140922 -0.00104104 -0.0117704 -0.00199203 -0.00895492 -0.00299548 -0.0067461 -0.00399793 -0.00507713 -0.00496223 -0.00385381 -0.00587775 -0.00295136 -0.00673697 -0.00227919 -0.00753515 -0.00178449 -0.00827098 -0.00142821 -0.00894612 -0.00117823 -0.0095643 -0.00101016 -0.0101304 -0.000905101 -0.0106498 -0.000848067 -0.011127 -0.000827331 -0.0115648 -0.000832745 -0.0119645 -0.00085193 -0.0123276 -0.000866792 -0.0126576 -0.000855885 -0.012961 -0.000801324 -0.0132462 -0.000696692 -0.0135229 -0.000550253 -0.0137992 -0.000382124 -0.0140812 -0.000211365 -0.0143716 -4.68296e-05 -0.0146498 9.99789e-05 -0.0148804 0.000230263 -0.0150603 0.00034158 -0.0152081 0.00039053 0.000354375 -0.00128716 -0.0128051 -0.003062 -0.00999553 -0.00485701 -0.0071599 -0.00660749 -0.00499562 -0.00825336 -0.00343126 -0.00975686 -0.00235031 -0.0110986 -0.00160963 -0.0122834 -0.00109442 -0.0133248 -0.000742996 -0.0142414 -0.000511658 -0.0150516 -0.000368018 -0.0157721 -0.000289688 -0.0164172 -0.000260015 -0.0169994 -0.00026578 -0.0175293 -0.000297519 -0.0180133 -0.000348683 -0.0184545 -0.000410738 -0.0188554 -0.000465929 -0.0192209 -0.000490371 -0.0195596 -0.000462602 -0.019882 -0.000374281 -0.0201983 -0.000233954 -0.0205161 -6.43814e-05 -0.020825 9.75385e-05 -0.0210995 0.000227654 -0.0213336 0.000334166 -0.0215389 0.000435505 -0.0217169 0.000519573 -0.0218731 0.000546788 0.000515419 -0.00248002 -0.010325 -0.00536707 -0.00710848 -0.00806346 -0.00446352 -0.0105131 -0.00254599 -0.0126943 -0.0012501 -0.0146225 -0.000422022 -0.0162979 6.57387e-05 -0.0177096 0.000317219 -0.0188753 0.000422798 -0.0198461 0.000459116 -0.0206696 0.000455474 -0.0213823 0.000422989 -0.0220113 0.000369042 -0.022578 0.000300918 -0.0230988 0.000223217 -0.0235839 0.000136444 -0.0240371 4.24222e-05 -0.024455 -4.79508e-05 -0.0248357 -0.00010975 -0.0251882 -0.000110037 -0.0255278 -3.4678e-05 -0.0258591 9.7355e-05 -0.0261698 0.000246321 -0.026451 0.000378719 -0.0267063 0.000482949 -0.0269359 0.000563699 -0.0271355 0.000635124 -0.0273078 0.000691863 -0.0274668 0.000705845 0.000686048 -0.00404587 -0.00627916 -0.00842605 -0.00272831 -0.0123697 -0.000519832 -0.0156217 0.000705973 -0.0181831 0.00131133 -0.0201667 0.00156154 -0.0217188 0.00161784 -0.0229721 0.00157049 -0.024023 0.00147378 -0.0249201 0.00135614 -0.0256983 0.00123372 -0.0263831 0.0011078 -0.0269924 0.000978284 -0.0275414 0.00084996 -0.0280438 0.000725631 -0.0285071 0.000599756 -0.0289309 0.000466147 -0.0293139 0.000335134 -0.0296614 0.000237671 -0.0299811 0.000209693 -0.0302821 0.000266334 -0.030575 0.000390197 -0.0308673 0.000538671 -0.0311541 0.000665467 -0.0314185 0.00074743 -0.0316488 0.000793966 -0.0318431 0.000829432 -0.0320107 0.000859425 -0.0321707 0.000865864 0.000857693 -0.00632294 4.37844e-05 -0.0118005 0.00274921 -0.0160984 0.00377814 -0.0193885 0.00399602 -0.0219573 0.00388015 -0.0239939 0.0035981 -0.0256268 0.00325075 -0.0269497 0.00289338 -0.0280334 0.00255755 -0.0289422 0.00226495 -0.029726 0.00201747 -0.0304151 0.00179694 -0.0310263 0.00158943 -0.0315743 0.001398 -0.0320755 0.0012268 -0.032539 0.00106324 -0.0329606 0.000887751 -0.0333295 0.000704038 -0.0336447 0.000552921 -0.0339244 0.000489332 -0.034197 0.000538999 -0.0344839 0.000677047 -0.0347864 0.000841189 -0.0350875 0.000966572 -0.0353622 0.00102212 -0.0355931 0.00102492 -0.0357811 0.00101736 -0.0359426 0.00102099 -0.0361007 0.00102389 0.00102735 -0.00783215 0.00787593 -0.0141496 0.00906664 -0.0189501 0.00857862 -0.0226066 0.00765259 -0.0253743 0.00664781 -0.0274808 0.00570458 -0.0291199 0.00488984 -0.0304225 0.00419601 -0.0314715 0.00360661 -0.032341 0.00313439 -0.0330944 0.00277086 -0.0337647 0.00246732 -0.0343608 0.00218551 -0.0348932 0.00193039 -0.035383 0.00171656 -0.035844 0.00152422 -0.0362666 0.00131037 -0.0366279 0.00106541 -0.0369208 0.000845798 -0.0371706 0.000739098 -0.0374205 0.00078892 -0.0377019 0.000958453 -0.038016 0.00115532 -0.0383363 0.00128685 -0.0386249 0.00131067 -0.0388563 0.00125637 -0.0390345 0.00119555 -0.0391863 0.00117277 -0.0393389 0.00117652 0.00119214 -0.00939055 0.0172665 -0.0170791 0.0167552 -0.0224258 0.0139254 -0.0261636 0.0113904 -0.0288715 0.00935571 -0.0308509 0.00768396 -0.0323544 0.0063934 -0.0335438 0.00538538 -0.0344871 0.00454989 -0.0352586 0.00390594 -0.0359435 0.00345575 -0.0365773 0.0031011 -0.0371467 0.00275494 -0.0376491 0.00243278 -0.0381147 0.00218215 -0.0385692 0.00197867 -0.0389957 0.00173688 -0.0393492 0.00141897 -0.0396085 0.00110502 -0.0398098 0.000940449 -0.0400223 0.00100137 -0.0402937 0.00122994 -0.040624 0.00148555 -0.0409719 0.00163476 -0.0412804 0.00161921 -0.0415117 0.00148762 -0.0416737 0.00135756 -0.0418092 0.00130831 -0.0419531 0.00132042 0.00134978 -0.0124379 0.0297044 -0.0217173 0.0260346 -0.0270285 0.0192366 -0.0302506 0.0146125 -0.0325866 0.0116917 -0.0341927 0.00929005 -0.0353744 0.00757513 -0.0363545 0.00636541 -0.0371291 0.00532451 -0.0377381 0.0045149 -0.0383126 0.00403033 -0.0389011 0.00368954 -0.0394393 0.00329321 -0.0398932 0.00288664 -0.0403131 0.00260203 -0.040755 0.00242057 -0.0411941 0.00217601 -0.0415451 0.00176995 -0.0417575 0.00131744 -0.0418841 0.00106703 -0.0420388 0.00115603 -0.0422967 0.00148791 -0.0426524 0.00184119 -0.0430418 0.0020242 -0.04338 0.00195743 -0.0436097 0.00171729 -0.0437444 0.00149222 -0.0438533 0.00141723 -0.0439856 0.00145277 0.00149957 -0.0177284 0.0474328 -0.0289344 0.0372406 -0.0334632 0.0237654 -0.0349144 0.0160637 -0.0365558 0.0133331 -0.0374719 0.0102061 -0.0380746 0.00817784 -0.0388086 0.0070994 -0.0394244 0.00594034 -0.0397913 0.00488177 -0.040186 0.00442505 -0.0407325 0.00423599 -0.0412534 0.00381411 -0.0416407 0.003274 -0.0419834 0.00294474 -0.0424112 0.00284831 -0.0428892 0.00265403 -0.0432583 0.00213905 -0.043409 0.00146816 -0.0434177 0.00107576 -0.0434829 0.00122116 -0.043724 0.001729 -0.0441203 0.00223749 -0.044572 0.00247594 -0.0449542 0.00233963 -0.04518 0.00194307 -0.0452688 0.00158103 -0.045334 0.00148248 -0.0454538 0.00157255 0.00164475 0.207447 0.0057603 0.207034 0.0111752 0.206432 0.0163501 0.205647 0.0213682 0.204688 0.0262942 0.203561 0.0311824 0.202271 0.0360802 0.200825 0.0410296 0.199229 0.0460675 0.197488 0.0512268 0.195607 0.056538 0.193592 0.0620294 0.191448 0.0677282 0.189182 0.0736619 0.186796 0.079859 0.184296 0.0863509 0.181684 0.0931734 0.178963 0.10037 0.176133 0.107993 0.173191 0.116113 0.170134 0.124822 0.166957 0.134242 0.163655 0.144547 0.160229 0.155978 0.156703 0.168889 0.15317 0.183809 0.149995 0.201535 0.148857 0.22298 0.160548 0.245626 0.258788 0.236093 0.21249 0.00595273 0.212118 0.0115481 0.211574 0.0168937 0.210868 0.0220741 0.210008 0.0271547 0.209 0.0321899 0.207853 0.0372274 0.206574 0.0423089 0.20517 0.0474711 0.20365 0.0527469 0.202022 0.0581661 0.200295 0.0637563 0.198479 0.0695443 0.196584 0.0755565 0.194623 0.0818207 0.192607 0.0883667 0.190551 0.0952287 0.188474 0.102447 0.186396 0.110071 0.184345 0.118164 0.182363 0.126804 0.180509 0.136096 0.178884 0.146172 0.177658 0.157203 0.177153 0.169393 0.178024 0.182939 0.181686 0.197873 0.190743 0.213923 0.206201 0.230167 0.24568 0.21931 0.217658 0.00612267 0.217329 0.0118771 0.21685 0.0173724 0.21623 0.0226938 0.215478 0.0279071 0.214601 0.0330665 0.213609 0.0382196 0.21251 0.0434075 0.211315 0.0486665 0.210033 0.0540285 0.208677 0.0595223 0.207259 0.0651744 0.205793 0.07101 0.204296 0.0770536 0.202786 0.0833306 0.201285 0.0898676 0.19982 0.0966943 0.198422 0.103845 0.197134 0.111359 0.196012 0.119286 0.195134 0.127682 0.194613 0.136617 0.194619 0.146166 0.195416 0.156407 0.197414 0.167395 0.201224 0.179129 0.207615 0.191482 0.217249 0.204289 0.229845 0.21757 0.228747 0.246779 0.222951 0.00626814 0.22267 0.0121584 0.222262 0.0177806 0.221735 0.0232202 0.2211 0.0285427 0.220364 0.0338021 0.219538 0.0390453 0.218633 0.0443126 0.217661 0.0496393 0.216633 0.0550559 0.215566 0.0605898 0.214475 0.0662656 0.213378 0.0721061 0.212299 0.0781331 0.211262 0.084368 0.210296 0.0908327 0.20944 0.0975505 0.208739 0.104546 0.20825 0.111848 0.208052 0.119485 0.208246 0.127489 0.208972 0.13589 0.210424 0.144714 0.212866 0.153965 0.216643 0.163618 0.222176 0.173597 0.229913 0.183745 0.240425 0.193777 0.254631 0.203365 0.210255 0.273123 0.228374 0.00638727 0.228144 0.0123885 0.227812 0.0181132 0.227385 0.0236465 0.226874 0.0290535 0.226289 0.0343874 0.225641 0.0396939 0.224941 0.0450124 0.224203 0.0503767 0.223444 0.0558156 0.222679 0.0613545 0.221929 0.0670154 0.221217 0.0728182 0.220569 0.078781 0.220017 0.0849205 0.219597 0.0912526 0.219355 0.0977927 0.219346 0.104555 0.219639 0.111554 0.220324 0.1188 0.221512 0.126301 0.223348 0.134054 0.226018 0.142044 0.229752 0.150231 0.23483 0.15854 0.24158 0.166846 0.250382 0.174943 0.261681 0.182478 0.27595 0.189095 0.19371 0.292495 0.233929 0.00647837 0.233754 0.012564 0.233502 0.0183654 0.233181 0.0239669 0.232802 0.0294323 0.232376 0.034814 0.231913 0.0401563 0.231429 0.0454971 0.230937 0.0508683 0.230456 0.0562968 0.230005 0.0618054 0.229607 0.0674134 0.229288 0.0731371 0.229079 0.0789902 0.229015 0.0849843 0.229139 0.0911287 0.229501 0.0974303 0.230163 0.103893 0.231199 0.110518 0.232701 0.117299 0.234779 0.124222 0.237571 0.131262 0.24124 0.138375 0.245978 0.145493 0.252005 0.152513 0.259564 0.159287 0.268897 0.16561 0.280182 0.171193 0.293515 0.175763 0.178806 0.308419 0.23962 0.00653997 0.239502 0.0126821 0.239334 0.0185333 0.239125 0.024176 0.238884 0.0296731 0.238623 0.0350752 0.238354 0.040425 0.238092 0.0457587 0.237854 0.0511061 0.23766 0.0564918 0.237529 0.0619358 0.237489 0.0674541 0.237566 0.0730593 0.237796 0.0787607 0.238216 0.0845643 0.238872 0.0904728 0.239817 0.0964854 0.241114 0.102596 0.242837 0.108795 0.245074 0.115061 0.247928 0.121368 0.251519 0.127671 0.255982 0.133912 0.261466 0.140009 0.268128 0.145851 0.276117 0.151297 0.285554 0.156173 0.296484 0.160263 0.308895 0.163352 0.165172 0.32253 0.245448 0.00657079 0.24539 0.0127404 0.24531 0.0186132 0.245216 0.0242697 0.245119 0.0297707 0.245029 0.0351653 0.244959 0.0404943 0.244926 0.0457917 0.244947 0.0510849 0.245043 0.0563962 0.245236 0.0617424 0.245554 0.0671365 0.246026 0.0725871 0.246688 0.078099 0.247579 0.0836732 0.248746 0.0893062 0.250241 0.0949902 0.252126 0.100712 0.25447 0.10645 0.257354 0.112178 0.260866 0.117855 0.265106 0.123432 0.270176 0.128842 0.276185 0.134 0.283231 0.138805 0.291396 0.143132 0.300727 0.146842 0.311213 0.149778 0.322785 0.151779 0.152715 0.335242 0.251418 0.00656981 0.251422 0.0127369 0.251432 0.0186026 0.251457 0.0242445 0.251507 0.0297216 0.251591 0.0350807 0.251725 0.0403604 0.251924 0.0455926 0.252207 0.0508023 0.252594 0.0560088 0.25311 0.0612265 0.253782 0.0664646 0.254641 0.0717284 0.255721 0.0770184 0.257064 0.0823309 0.258712 0.0876575 0.260718 0.0929846 0.263137 0.0982927 0.266032 0.103555 0.269471 0.108739 0.273527 0.113799 0.278277 0.118682 0.283796 0.123323 0.290154 0.127643 0.297406 0.131553 0.305587 0.134951 0.314698 0.137731 0.324694 0.139782 0.335475 0.140997 0.141319 0.346871 0.257532 0.0065363 0.257599 0.0126703 0.257702 0.0184994 0.257848 0.0240982 0.258047 0.0295232 0.258309 0.0348189 0.258648 0.0400216 0.25908 0.0451606 0.259623 0.0502586 0.2603 0.0553322 0.261133 0.0603928 0.262151 0.0654468 0.263384 0.0704959 0.264865 0.0755372 0.266633 0.0805632 0.268729 0.0855614 0.271199 0.090514 0.274094 0.0953978 0.277467 0.100183 0.281373 0.104833 0.285869 0.109303 0.29101 0.113541 0.296846 0.117487 0.303417 0.121072 0.310746 0.124223 0.318837 0.126861 0.327662 0.128907 0.337156 0.130288 0.347215 0.130938 0.130837 0.357697 0.263794 0.00646977 0.263925 0.0125396 0.264122 0.0183025 0.26439 0.0238296 0.264739 0.0291746 0.265178 0.0343794 0.265722 0.039478 0.266385 0.0444972 0.267187 0.0494571 0.268147 0.0543718 0.26929 0.05925 0.270641 0.0640954 0.27223 0.0689069 0.274089 0.0736787 0.276252 0.0784002 0.278757 0.0830563 0.281644 0.0876267 0.284956 0.092086 0.288736 0.0964034 0.293026 0.100542 0.297868 0.104461 0.303298 0.108111 0.309345 0.11144 0.316027 0.114391 0.323343 0.116906 0.331276 0.118927 0.339783 0.1204 0.348794 0.121277 0.35821 0.121522 0.121136 0.367911 0.270207 0.00637005 0.270402 0.0123446 0.270693 0.0180117 0.271084 0.0234386 0.271582 0.0286761 0.272198 0.0337635 0.272944 0.0387321 0.273835 0.0436063 0.274888 0.0484037 0.276124 0.0531361 0.277564 0.0578099 0.279233 0.0624264 0.281158 0.0669821 0.283368 0.0714691 0.285893 0.075875 0.288766 0.0801829 0.292021 0.0843715 0.295692 0.0884151 0.299812 0.0922835 0.304412 0.0959425 0.309519 0.0993538 0.315154 0.102476 0.321328 0.105265 0.328043 0.107676 0.335285 0.109665 0.343022 0.11119 0.351204 0.112217 0.359763 0.112718 0.36861 0.112676 0.112102 0.377643 0.276774 0.00623725 0.277033 0.0120855 0.277417 0.0176274 0.277929 0.0229262 0.278576 0.0280295 0.279366 0.0329738 0.28031 0.0377879 0.281422 0.0424937 0.282719 0.0471067 0.284219 0.0516363 0.285942 0.056087 0.28791 0.0604582 0.290148 0.0647447 0.29268 0.0689373 0.295532 0.0730224 0.298732 0.0769826 0.302307 0.0807967 0.306282 0.08444 0.310681 0.0878845 0.315524 0.0910993 0.320827 0.0940512 0.326597 0.0967057 0.332835 0.0990275 0.339528 0.100982 0.346654 0.102539 0.354176 0.103669 0.362041 0.104352 0.370185 0.104574 0.378529 0.104331 0.103641 0.38699 0.283498 0.00607174 0.283821 0.0117631 0.284297 0.0171509 0.284929 0.0222945 0.28572 0.0272378 0.28668 0.0320147 0.287816 0.0366514 0.289142 0.0411675 0.290673 0.0455763 0.292423 0.0498856 0.294412 0.054098 0.296659 0.0582115 0.299184 0.0622199 0.302008 0.0661132 0.305153 0.0698776 0.308639 0.073496 0.312488 0.0769483 0.316716 0.0802117 0.321339 0.0832612 0.326369 0.08607 0.331809 0.0886105 0.33766 0.0908549 0.343911 0.0927761 0.350545 0.0943493 0.357531 0.0955529 0.36483 0.09637 0.372392 0.0967897 0.380158 0.0968082 0.38806 0.096429 0.0956724 0.396029 0.290384 0.00587416 0.290768 0.0113786 0.291335 0.0165844 0.292083 0.0215463 0.293016 0.0263051 0.294139 0.0308917 0.29546 0.0353299 0.296991 0.0396371 0.298742 0.0438248 0.300729 0.047899 0.302966 0.0518611 0.305469 0.0557083 0.308255 0.0594337 0.311341 0.0630271 0.314744 0.0664753 0.318478 0.069762 0.322557 0.072869 0.326992 0.0757761 0.331792 0.0784615 0.336959 0.0809032 0.342491 0.0830787 0.348379 0.0849665 0.354608 0.086547 0.361155 0.0878029 0.367987 0.0887208 0.375065 0.0892916 0.382343 0.0895119 0.389767 0.0893841 0.397279 0.0889164 0.0881301 0.404822 0.297435 0.00564538 0.297879 0.0109338 0.298533 0.0159305 0.299394 0.0206856 0.300462 0.0252366 0.301743 0.0296116 0.30324 0.0338321 0.304964 0.0379133 0.306924 0.0418652 0.30913 0.0456924 0.311596 0.0493955 0.314333 0.052971 0.317355 0.056412 0.320673 0.0597086 0.3243 0.0628484 0.328245 0.0658169 0.332517 0.0685978 0.337119 0.0711738 0.342054 0.0735269 0.347318 0.0756392 0.352903 0.0774933 0.358796 0.0790735 0.364977 0.080366 0.37142 0.08136 0.378092 0.082048 0.384957 0.082427 0.391971 0.0824984 0.399086 0.0822685 0.406255 0.0817482 0.0809584 0.413426 0.304654 0.00538645 0.305157 0.0104309 0.305895 0.0151924 0.306864 0.0197168 0.308062 0.0240382 0.309492 0.028182 0.311156 0.0321674 0.313062 0.0360078 0.315216 0.0397117 0.317625 0.0432827 0.3203 0.0467207 0.323249 0.050022 0.326481 0.0531801 0.330004 0.0561858 0.333824 0.0590278 0.337948 0.0616936 0.342376 0.0641691 0.34711 0.06644 0.352145 0.0684919 0.357473 0.0703108 0.363083 0.0718839 0.368956 0.0732002 0.375071 0.0742509 0.381402 0.0750298 0.387915 0.0755345 0.394576 0.0757656 0.401347 0.075728 0.408185 0.0754303 0.415049 0.0748846 0.0741104 0.421897 0.312046 0.0050986 0.312605 0.00987209 0.313424 0.0143738 0.314495 0.018645 0.315817 0.0227165 0.317388 0.0266112 0.319209 0.030346 0.321284 0.0339328 0.323617 0.0373786 0.326214 0.0406865 0.329078 0.0438558 0.332217 0.0468831 0.335635 0.0497621 0.339336 0.0524849 0.343323 0.0550415 0.347595 0.0574213 0.352151 0.0596128 0.356987 0.0616044 0.362094 0.0633848 0.367461 0.0649439 0.373072 0.0662725 0.378909 0.0673636 0.384947 0.0682122 0.391161 0.0688161 0.39752 0.0691757 0.403991 0.0692948 0.410539 0.0691799 0.417128 0.068841 0.423722 0.0682903 0.067546 0.430287 0.319615 0.00478314 0.320227 0.00926011 0.321122 0.0134785 0.322292 0.0174754 0.32373 0.0212784 0.325433 0.0249077 0.327401 0.0283784 0.329633 0.0317006 0.332131 0.0348804 0.334898 0.0379203 0.337934 0.0408194 0.341243 0.0435745 0.344825 0.0461803 0.34868 0.0486296 0.352807 0.0509143 0.357203 0.0530255 0.361862 0.0549541 0.366775 0.056691 0.371932 0.0582281 0.377318 0.0595579 0.382915 0.0606748 0.388704 0.0615746 0.394661 0.0622555 0.40076 0.0627177 0.406971 0.0629641 0.413266 0.063 0.419613 0.0628332 0.42598 0.0624739 0.432336 0.0619339 0.0612298 0.438652 0.327365 0.00444144 0.328027 0.00859761 0.328995 0.0125107 0.330257 0.0162137 0.331804 0.0197309 0.333632 0.0230803 0.335736 0.0262748 0.338113 0.0293233 0.340762 0.0322309 0.343683 0.0349996 0.346874 0.0376286 0.350333 0.0401151 0.354059 0.0424544 0.358048 0.0446407 0.362295 0.0466674 0.366793 0.0485273 0.371534 0.0502134 0.376506 0.051719 0.381695 0.0530384 0.387087 0.0541668 0.39266 0.0551008 0.398396 0.0558389 0.404271 0.0563812 0.410258 0.0567299 0.416333 0.0568893 0.422468 0.0568656 0.428634 0.0566671 0.434804 0.0563035 0.440952 0.0557864 0.0551304 0.447051 0.3353 0.00407484 0.336011 0.00788725 0.337047 0.0114744 0.338396 0.0148652 0.340045 0.0180811 0.341988 0.0211374 0.344218 0.0240453 0.346729 0.0268124 0.349517 0.0294431 0.352577 0.0319389 0.355907 0.0342991 0.3595 0.0365214 0.363353 0.038602 0.367458 0.0405361 0.371806 0.0423185 0.37639 0.0439437 0.381197 0.0454066 0.386213 0.0467026 0.391424 0.0478276 0.396812 0.0487791 0.402357 0.0495557 0.408038 0.0501574 0.413834 0.0505859 0.419719 0.0508446 0.42567 0.0509386 0.431661 0.0508745 0.437667 0.0506603 0.443665 0.0503056 0.449631 0.0498206 0.0492184 0.455543 0.343426 0.0036846 0.344182 0.00713149 0.345283 0.0103733 0.346713 0.0134352 0.348458 0.0163354 0.350509 0.019087 0.352855 0.0216994 0.355488 0.0241788 0.358403 0.0265289 0.361591 0.028751 0.365045 0.0308447 0.368759 0.0328078 0.372723 0.0346376 0.376929 0.0363301 0.381366 0.0378815 0.386022 0.0392878 0.390883 0.0405453 0.395935 0.041651 0.40116 0.0426026 0.40654 0.0433989 0.412056 0.0440399 0.417686 0.044527 0.423409 0.0448626 0.429203 0.045051 0.435044 0.0450974 0.44091 0.0450083 0.446779 0.0447916 0.452629 0.0444558 0.458439 0.0440104 0.0434665 0.464191 0.351746 0.00327175 0.352546 0.00633244 0.353708 0.00921079 0.355215 0.0119284 0.35705 0.0145001 0.359201 0.0169366 0.361654 0.0192455 0.364401 0.0214318 0.367432 0.0234987 0.370735 0.0254472 0.374303 0.0272769 0.378125 0.0289862 0.38219 0.0305728 0.386486 0.032034 0.391 0.0333668 0.39572 0.0345685 0.400628 0.0356367 0.40571 0.0365695 0.410947 0.0373659 0.41632 0.0380258 0.421809 0.0385502 0.427395 0.0389409 0.433057 0.0392013 0.438772 0.0393356 0.444521 0.0393489 0.450281 0.0392476 0.456034 0.0390388 0.46176 0.0387301 0.467441 0.0383297 0.0378475 0.47306 0.360267 0.00283692 0.361108 0.00549152 0.362329 0.00798951 0.363909 0.0103488 0.365828 0.0125807 0.368072 0.0146928 0.370626 0.0166913 0.373478 0.0185801 0.376615 0.0203617 0.380026 0.0220368 0.383697 0.0236052 0.387618 0.0250656 0.391774 0.0264164 0.396153 0.0276555 0.400738 0.028781 0.405516 0.0297909 0.410469 0.0306839 0.415579 0.031459 0.420829 0.032116 0.4262 0.0326555 0.431671 0.0330791 0.437222 0.0333891 0.442835 0.0335888 0.448488 0.0336823 0.454163 0.0336746 0.459839 0.0335713 0.465499 0.0333788 0.471125 0.0331037 0.476702 0.0327532 0.0323355 0.482214 0.368993 0.00238003 0.369876 0.00460894 0.371154 0.00671105 0.372803 0.00869976 0.374803 0.0105815 0.377134 0.012361 0.379783 0.0140429 0.382733 0.0156302 0.385969 0.0171248 0.389479 0.018527 0.393248 0.0198366 0.397261 0.0210527 0.401503 0.0221741 0.405959 0.0231994 0.410613 0.0241272 0.415447 0.0249565 0.420445 0.0256863 0.425587 0.0263166 0.430856 0.0268475 0.436231 0.0272801 0.441694 0.0276162 0.447225 0.0278581 0.452805 0.028009 0.458415 0.0280727 0.464036 0.0280536 0.46965 0.0279566 0.475242 0.0277871 0.480795 0.0275508 0.486295 0.0272534 0.0269019 0.491728 0.377932 0.00189948 0.378858 0.00368278 0.380193 0.00537607 0.381908 0.00698438 0.383983 0.00850704 0.386397 0.00994645 0.389134 0.0113061 0.392176 0.0125883 0.395507 0.0137939 0.399111 0.0149232 0.402971 0.0159758 0.407073 0.0169513 0.411398 0.0178486 0.415931 0.0186668 0.420653 0.019405 0.425547 0.0200627 0.430594 0.0206395 0.435775 0.0211355 0.441071 0.0215513 0.446463 0.021888 0.451932 0.0221473 0.457459 0.0223315 0.463024 0.0224433 0.468611 0.022486 0.474201 0.0224633 0.479779 0.0223793 0.485328 0.0222383 0.490833 0.0220451 0.496282 0.0218044 0.0215217 0.501663 0.387091 0.00139006 0.388068 0.0027058 0.389462 0.00398206 0.391243 0.00520292 0.393392 0.00635889 0.395886 0.00745178 0.398708 0.00848451 0.401838 0.00945823 0.405259 0.0103731 0.408953 0.0112292 0.412902 0.0120261 0.41709 0.0127634 0.421498 0.0134404 0.426108 0.0140567 0.430902 0.0146115 0.43586 0.0151046 0.440964 0.015536 0.446193 0.0159059 0.451529 0.016215 0.456953 0.0164642 0.462445 0.0166551 0.467987 0.0167895 0.473561 0.0168696 0.479149 0.0168981 0.484734 0.0168779 0.490302 0.016812 0.495836 0.0167037 0.501325 0.0165567 0.506755 0.0163742 0.0161604 0.512116 0.396484 0.00083875 0.397517 0.00167243 0.398966 0.00253318 0.40081 0.0033592 0.403029 0.00413995 0.405601 0.0048799 0.408505 0.00558081 0.41172 0.00624232 0.41523 0.00686397 0.419013 0.00744552 0.423053 0.00798667 0.427329 0.00848707 0.431823 0.00894627 0.436516 0.00936386 0.441388 0.00973953 0.44642 0.0100731 0.451591 0.0103647 0.456882 0.0106144 0.462274 0.0108229 0.467748 0.010991 0.473283 0.0111196 0.478862 0.0112102 0.484468 0.0112643 0.490082 0.0112838 0.495689 0.0112706 0.501274 0.011227 0.506823 0.0111552 0.512322 0.0110577 0.517759 0.010937 0.0107962 0.523123 0.406193 0.000155631 0.40729 0.000575548 0.40879 0.0010336 0.410692 0.00145657 0.412976 0.00185661 0.415616 0.00223919 0.418594 0.00260354 0.421888 0.00294836 0.425479 0.00327302 0.429347 0.00357724 0.433473 0.00386075 0.437837 0.00412326 0.442418 0.00436448 0.447198 0.00458416 0.452156 0.00478209 0.45727 0.0049582 0.462523 0.0051125 0.467892 0.00524515 0.473358 0.00535642 0.478903 0.00544676 0.484505 0.00551674 0.490149 0.00556708 0.495814 0.00559863 0.501486 0.00561233 0.507147 0.00560925 0.512784 0.00559053 0.518381 0.00555735 0.523928 0.00551097 0.529413 0.00545258 0.00538406 0.534825 0.415475 0.41605 0.417084 0.418541 0.420397 0.422636 0.42524 0.428188 0.431461 0.435039 0.438899 0.443023 0.447387 0.451971 0.456753 0.461712 0.466824 0.472069 0.477426 0.482872 0.488389 0.493956 0.499555 0.505167 0.510776 0.516367 0.521924 0.527435 0.532888 0.538272 0.128381 0.107712 0.0386162 0.089765 0.0573655 -0.0187493 0.210765 0.116256 0.19465 0.105881 0.0898832 0.162132 0.252518 0.110517 0.251917 0.106482 0.0995244 0.242275 0.280121 0.103519 0.284041 0.102562 0.099859 0.283706 0.299927 0.096087 0.306128 0.0963612 0.0956327 0.310354 0.315778 0.088728 0.322752 0.0893869 0.089504 0.32888 0.329395 0.0818625 0.336222 0.0825598 0.0829578 0.342769 0.341514 0.0755912 0.347864 0.0762098 0.0766442 0.354177 0.352595 0.0698674 0.358416 0.0703887 0.0707815 0.364278 0.362945 0.0646197 0.368277 0.0650564 0.0653956 0.373663 0.372751 0.0597797 0.377659 0.0601488 0.0604406 0.382614 0.382137 0.0552862 0.386684 0.0556019 0.055855 0.391269 0.391189 0.0510874 0.395431 0.0513604 0.051582 0.399704 0.399976 0.0471402 0.403958 0.0473784 0.0475741 0.407966 0.408552 0.0434096 0.412312 0.0436188 0.0437926 0.416093 0.41697 0.0398663 0.420537 0.0400509 0.0402059 0.424124 0.425277 0.0364861 0.428678 0.0366494 0.0367879 0.432096 0.433525 0.0332481 0.436781 0.0333928 0.0335165 0.440053 0.441766 0.0301346 0.444896 0.0302626 0.0303728 0.44804 0.450056 0.0271292 0.453077 0.0272422 0.0273401 0.45611 0.458455 0.0242175 0.461381 0.0243166 0.0244031 0.464317 0.467023 0.0213854 0.469868 0.0214717 0.0215475 0.472723 0.475825 0.0186197 0.478603 0.018694 0.0187596 0.481391 0.484927 0.0159068 0.487651 0.0159697 0.0160254 0.490385 0.494401 0.0132338 0.497085 0.0132859 0.0133322 0.499778 0.504311 0.0105858 0.506969 0.0106272 0.0106639 0.509638 0.514751 0.00795056 0.517397 0.00798164 0.00800955 0.520051 0.525765 0.00530842 0.528418 0.00532888 0.00534666 0.531081 0.537482 0.00265132 0.54015 0.00266045 0.002669 0.542828 0.540923 0.543584 0.546253 -0.0372846 0.0659681 -0.0467433 0.0466993 -0.0471403 0.0241624 -0.0407313 0.00965473 -0.0416929 0.0142947 -0.0421083 0.0106215 -0.0419915 0.00806111 -0.0426213 0.00772913 -0.043153 0.00647205 -0.0429916 0.00472038 -0.043035 0.00446847 -0.0436461 0.00484711 -0.0442721 0.0044401 -0.044604 0.0036059 -0.0448025 0.0031432 -0.0452157 0.00326154 -0.0457907 0.00322901 -0.046226 0.00257439 -0.0462914 0.00153353 -0.0460971 0.000881424 -0.046017 0.00114112 -0.0462539 0.00196594 -0.0467393 0.00272286 -0.0473086 0.00304519 -0.0477753 0.00280639 -0.0480033 0.002171 -0.0480155 0.00159328 -0.048006 0.00147298 -0.0481197 0.00168623 0.00181047 0.0977098 0.13039 0.0483047 0.0961045 0.00104078 0.0714263 -0.0333396 0.0440351 -0.0474603 0.0284154 -0.049669 0.0128302 -0.0451846 0.00357664 -0.0447591 0.00730366 -0.0454053 0.00711827 -0.0446075 0.00392258 -0.044513 0.00437399 -0.045544 0.00587804 -0.0464438 0.00533991 -0.0465571 0.00371922 -0.0462879 0.002874 -0.0466458 0.00361941 -0.0474332 0.00401646 -0.0480505 0.00319169 -0.0480499 0.00153286 -0.0475167 0.000348252 -0.0471946 0.00081898 -0.0474354 0.0022068 -0.0480613 0.00334872 -0.0487988 0.00378269 -0.0493812 0.00338878 -0.0495979 0.00238775 -0.049465 0.00146039 -0.0493116 0.00131956 -0.0494245 0.00179909 0.00204067 0.205082 0.167584 0.164381 0.136806 0.125446 0.110361 0.0837239 0.085757 0.0458513 0.066288 0.00640187 0.0522796 -0.0259109 0.0358894 -0.0436782 0.0250709 -0.0499143 0.0133544 -0.049029 0.00303729 -0.045227 0.000572024 -0.0460057 0.00665674 -0.0473652 0.00669946 -0.047162 0.00351603 -0.0464278 0.00213972 -0.0470082 0.00419988 -0.0483379 0.00534617 -0.0493733 0.004227 -0.0492758 0.00143536 -0.0479648 -0.000962657 -0.0470947 -5.11759e-05 -0.0474101 0.00252225 -0.0482873 0.00422588 -0.0492729 0.00476834 -0.0500217 0.00413753 -0.0502165 0.00258256 -0.0498448 0.00108865 -0.0494344 0.000909221 -0.0495585 0.00192318 0.00248559 0.268844 0.182445 0.244797 0.160853 0.216051 0.139107 0.183472 0.118336 0.150181 0.0995796 0.119051 0.083409 0.0869605 0.0679803 0.0573793 0.0546521 0.0273739 0.0433598 -0.00439735 0.0348085 -0.0295311 0.0257058 -0.0425064 0.0196319 -0.0480206 0.0122137 -0.0486333 0.0041287 -0.0459036 -0.000589987 -0.0450737 0.00336999 -0.0469947 0.00726721 -0.0487936 0.00602593 -0.0479804 0.000622085 -0.0460969 -0.00284615 -0.0449794 -0.00116862 -0.0457872 0.00333002 -0.0471532 0.00559189 -0.048527 0.00614209 -0.049541 0.00515158 -0.0497111 0.00275267 -0.0489453 0.000322873 -0.0479545 -8.15786e-05 -0.0480382 0.00200686 0.00338302 0.308801 0.183998 0.298375 0.17128 0.281455 0.156027 0.25987 0.139921 0.235482 0.123967 0.209953 0.108938 0.183124 0.0948089 0.156018 0.0817587 0.129247 0.0701301 0.103982 0.0600739 0.0788225 0.0508654 0.0559706 0.0424838 0.0338057 0.0343786 0.0094154 0.028519 -0.0135498 0.0223752 -0.0293734 0.0191936 -0.0376673 0.0155611 -0.0418193 0.0101779 -0.0433202 0.00212298 -0.0408473 -0.005319 -0.0398454 -0.00217058 -0.0414477 0.00493238 -0.0435501 0.00769426 -0.0452883 0.00788026 -0.046437 0.00630028 -0.0464485 0.00276421 -0.0447617 -0.00136389 -0.0432474 -0.00159596 -0.0436395 0.002399 0.00528015 0.335005 0.177873 0.334245 0.17204 0.327412 0.16286 0.315631 0.151703 0.30005 0.139548 0.281809 0.127179 0.261647 0.114971 0.240225 0.103181 0.218231 0.0921238 0.196251 0.0820542 0.174298 0.0728181 0.152699 0.0640825 0.131159 0.0559189 0.110734 0.048944 0.0902751 0.0428342 0.0716869 0.0377818 0.0548883 0.0323597 0.0387391 0.0263271 0.0194081 0.021454 -0.00367593 0.017765 -0.0212947 0.0154482 -0.0299436 0.0135813 -0.0342298 0.0119804 -0.0366996 0.0103501 -0.03821 0.00781074 -0.0385866 0.0031408 -0.037538 -0.00241257 -0.0358598 -0.00327412 -0.0366923 0.00323155 0.00868679 0.352733 0.167908 0.358124 0.16665 0.35872 0.162264 0.354862 0.15556 0.347143 0.147268 0.3363 0.138022 0.322992 0.128279 0.307775 0.118397 0.291197 0.108702 0.273797 0.0994538 0.255941 0.0906744 0.237756 0.082267 0.219355 0.0743199 0.201184 0.0671154 0.183302 0.0607158 0.166221 0.0548627 0.149588 0.0489925 0.132814 0.0431015 0.116298 0.0379704 0.0999914 0.0340712 0.0842742 0.0311654 0.0695401 0.0283154 0.0560908 0.0254297 0.043896 0.0225449 0.0324334 0.0192733 0.0195923 0.0159819 0.0031133 0.0140664 -0.0127614 0.0126006 -0.0213419 0.011812 0.0154649 0.36552 0.156566 0.374254 0.157915 0.379698 0.156819 0.381668 0.15359 0.38029 0.148645 0.375896 0.142416 0.368884 0.135291 0.359668 0.127614 0.348681 0.119688 0.336375 0.11176 0.323098 0.103951 0.30905 0.0963152 0.294419 0.0889507 0.279504 0.0820308 0.264598 0.0756217 0.249875 0.0695855 0.23517 0.0636981 0.220296 0.0579755 0.205458 0.0528082 0.190955 0.048574 0.177029 0.045091 0.163556 0.0417886 0.150481 0.0385053 0.137787 0.0352385 0.125137 0.0319236 0.112235 0.0288842 0.0994683 0.0268328 0.086398 0.0256709 0.0728189 0.025391 0.0272636 0.375665 0.145179 0.385799 0.147782 0.393961 0.148657 0.399732 0.14782 0.402934 0.145443 0.403588 0.141762 0.401843 0.137036 0.397932 0.131526 0.392139 0.12548 0.384782 0.119118 0.376137 0.112596 0.366423 0.106029 0.355847 0.0995272 0.344657 0.0932208 0.333097 0.0871813 0.321302 0.0813809 0.309253 0.075747 0.296912 0.0703161 0.284411 0.0653096 0.272042 0.0609427 0.259997 0.0571364 0.248186 0.0535997 0.236514 0.0501773 0.224903 0.0468493 0.213172 0.0436541 0.201228 0.0408288 0.189269 0.0387919 0.177279 0.0376608 0.165259 0.0374109 0.0381229 0.384508 0.134334 0.394888 0.137402 0.404244 0.139301 0.412135 0.139928 0.418263 0.139315 0.42247 0.137555 0.424722 0.134785 0.42508 0.131167 0.423681 0.12688 0.420703 0.122095 0.41634 0.11696 0.410769 0.111599 0.404172 0.106125 0.396742 0.10065 0.388667 0.0952557 0.380078 0.0899709 0.371024 0.0848002 0.361544 0.0797968 0.351756 0.0750972 0.341868 0.0708304 0.332022 0.0669831 0.322204 0.0634172 0.312354 0.0600273 0.302402 0.0568017 0.29225 0.0538062 0.281859 0.0512193 0.27135 0.0493008 0.260843 0.0481678 0.25048 0.0477743 0.0478812 0.392741 0.124206 0.402799 0.127345 0.412413 0.129687 0.421229 0.131112 0.428953 0.131591 0.435367 0.131141 0.440338 0.129813 0.443813 0.127693 0.445806 0.124887 0.446385 0.121515 0.445652 0.117693 0.443721 0.11353 0.440719 0.109127 0.436787 0.104583 0.432063 0.0999798 0.42666 0.0953739 0.420653 0.0908071 0.414109 0.0863408 0.407135 0.0820716 0.399875 0.0780902 0.392441 0.0744165 0.384862 0.070997 0.377109 0.0677796 0.369141 0.0647695 0.360913 0.0620351 0.352421 0.0597114 0.343755 0.0579667 0.335035 0.0568873 0.326393 0.0564163 0.0562642 0.40069 0.114785 0.410213 0.117822 0.419604 0.120296 0.428614 0.122101 0.43701 0.123196 0.444586 0.123565 0.451184 0.123215 0.456696 0.122181 0.461065 0.120518 0.464282 0.118299 0.466371 0.115605 0.467383 0.112518 0.467388 0.109121 0.466474 0.105497 0.464733 0.101721 0.462251 0.0978561 0.459099 0.0939592 0.455346 0.0900938 0.45108 0.0863372 0.446408 0.0827624 0.441418 0.0794059 0.436152 0.0762629 0.430609 0.0733226 0.424773 0.0706063 0.418629 0.0681788 0.412196 0.0661444 0.405544 0.0646189 0.398767 0.0636635 0.391956 0.0632277 0.0630581 0.408494 0.105996 0.417449 0.108866 0.426425 0.111321 0.435253 0.113273 0.443765 0.114683 0.451801 0.115529 0.459217 0.115799 0.465898 0.115501 0.471757 0.114658 0.476744 0.113312 0.480835 0.111513 0.484033 0.10932 0.486361 0.106793 0.48786 0.103998 0.488582 0.100999 0.488582 0.0978561 0.487914 0.0946271 0.486635 0.091373 0.484812 0.0881602 0.482523 0.0850518 0.479836 0.0820927 0.476794 0.0793052 0.47341 0.0767063 0.469687 0.0743294 0.46563 0.0722357 0.461265 0.0705092 0.456647 0.0692367 0.451845 0.0684659 0.446907 0.0681661 0.0681471 0.41621 0.0977513 0.424639 0.100437 0.433157 0.102803 0.44165 0.10478 0.45 0.106333 0.458089 0.107441 0.465802 0.108085 0.47304 0.108263 0.479717 0.107981 0.485768 0.107261 0.491148 0.106133 0.495832 0.104636 0.499811 0.102813 0.503094 0.100715 0.505702 0.0983918 0.507661 0.0958966 0.509006 0.093282 0.509776 0.0906035 0.510017 0.0879189 0.509784 0.0852849 0.509127 0.0827494 0.508084 0.0803488 0.506674 0.0781161 0.50491 0.0760934 0.502807 0.0743389 0.500391 0.0729246 0.497706 0.0719217 0.494797 0.0713753 0.491683 0.0712801 0.0715124 0.42387 0.0899753 0.431833 0.0924733 0.439916 0.0947199 0.448038 0.096658 0.456114 0.0982582 0.464055 0.099499 0.471777 0.100363 0.479199 0.100841 0.486247 0.100933 0.492859 0.100649 0.498986 0.100006 0.504591 0.0990309 0.509651 0.0977537 0.514154 0.0962114 0.518101 0.0944448 0.5215 0.0924974 0.524368 0.090415 0.526725 0.088246 0.528602 0.0860414 0.530035 0.0838522 0.531059 0.0817259 0.531702 0.0797051 0.531987 0.0778313 0.531929 0.0761512 0.531547 0.0747212 0.530865 0.0736063 0.529916 0.0728707 0.528729 0.0725628 0.527306 0.0727028 0.0732284 0.431497 0.0826021 0.439056 0.0849149 0.446748 0.0870277 0.454513 0.0888926 0.462288 0.0904838 0.470005 0.0917817 0.477599 0.0927691 0.485006 0.0934344 0.492165 0.0937738 0.499023 0.0937906 0.505535 0.0934952 0.511661 0.0929042 0.517375 0.0920401 0.522656 0.0909305 0.527493 0.0896074 0.531884 0.0881065 0.535832 0.0864668 0.539348 0.0847303 0.542448 0.0829415 0.545154 0.0811463 0.54749 0.0793903 0.549477 0.0777177 0.551135 0.0761734 0.55248 0.0748058 0.553531 0.0736702 0.55431 0.0728275 0.554841 0.0723394 0.555144 0.0722602 0.555215 0.072632 0.0734447 0.439121 0.0755774 0.446327 0.0777089 0.453674 0.0796805 0.461115 0.0814514 0.4686 0.0829992 0.476076 0.0843058 0.483491 0.0853546 0.490792 0.0861333 0.49793 0.0866354 0.50486 0.0868606 0.511541 0.0868141 0.517938 0.0865069 0.524023 0.0859551 0.529774 0.0851796 0.535176 0.0842059 0.540219 0.0830634 0.5449 0.0817851 0.549224 0.0804071 0.553196 0.0789687 0.556832 0.0775111 0.560145 0.0760769 0.563153 0.0747097 0.565872 0.0734547 0.568317 0.0723605 0.570506 0.0714809 0.57246 0.0708743 0.574197 0.0706018 0.575734 0.0707238 0.577067 0.0712988 0.0723575 0.446775 0.0688553 0.453674 0.0708096 0.460719 0.0726358 0.467871 0.0742991 0.47509 0.07578 0.482334 0.0770622 0.489559 0.0781299 0.496721 0.0789707 0.50378 0.0795767 0.510696 0.0799449 0.517432 0.0800774 0.523959 0.0799807 0.530247 0.0796663 0.536277 0.0791503 0.54203 0.0784527 0.547495 0.0775978 0.552667 0.0766135 0.557543 0.0755311 0.562127 0.0743851 0.566425 0.0732124 0.570449 0.0720527 0.574212 0.0709473 0.577726 0.0699402 0.581008 0.0690789 0.584074 0.0684154 0.586942 0.0680063 0.589631 0.0679127 0.592156 0.0681986 0.594521 0.0689337 0.070177 0.454499 0.0623965 0.461131 0.0641774 0.467911 0.0658558 0.474808 0.0674019 0.481789 0.0687989 0.488819 0.0700322 0.495862 0.0710874 0.50288 0.0719524 0.509838 0.0726185 0.516702 0.0730813 0.523439 0.0733402 0.530021 0.073399 0.536421 0.0732655 0.54262 0.0729516 0.548599 0.0724733 0.554347 0.0718505 0.559854 0.0711066 0.565116 0.0702687 0.570134 0.0693669 0.574912 0.0684345 0.579457 0.0675076 0.58378 0.0666249 0.587892 0.0658282 0.591807 0.0651631 0.595543 0.0646794 0.599118 0.0644317 0.602551 0.0644802 0.605859 0.0648906 0.609054 0.0657379 0.0670978 0.46234 0.0561662 0.46874 0.0577772 0.475289 0.0593064 0.481963 0.0607283 0.488733 0.0620286 0.495571 0.0631943 0.502446 0.0642127 0.509326 0.0650721 0.516181 0.0657641 0.522979 0.0662831 0.529692 0.0666272 0.536293 0.0667979 0.542758 0.0668001 0.549067 0.0666427 0.555203 0.0663381 0.561151 0.0659025 0.566902 0.0653556 0.57245 0.0647203 0.577794 0.0640232 0.582934 0.0632937 0.587878 0.0625645 0.592631 0.0618712 0.597207 0.061253 0.601617 0.0607525 0.605879 0.0604171 0.610012 0.0602989 0.614036 0.0604561 0.617973 0.0609537 0.621844 0.0618672 0.0632795 0.470351 0.0501328 0.476551 0.0515772 0.482901 0.0529563 0.489381 0.0542488 0.495967 0.0554424 0.502635 0.0565259 0.50936 0.0574879 0.516114 0.058318 0.52287 0.059008 0.529601 0.0595521 0.536281 0.0599473 0.542885 0.0601937 0.549391 0.0602941 0.555779 0.060255 0.562031 0.0600858 0.568134 0.0597997 0.574077 0.0594129 0.579852 0.058945 0.585456 0.0584187 0.59089 0.0578601 0.596156 0.0572983 0.601261 0.0567658 0.606216 0.0562982 0.611033 0.0559354 0.615729 0.0557212 0.620323 0.0557048 0.624838 0.0559412 0.629299 0.0564927 0.633735 0.0574316 0.0588413 0.478589 0.0442668 0.484619 0.0455472 0.4908 0.046776 0.497114 0.047935 0.503542 0.049014 0.510064 0.0500035 0.516659 0.0508936 0.523302 0.051675 0.529969 0.0523401 0.536638 0.0528832 0.543285 0.053301 0.549886 0.0535924 0.556421 0.053759 0.562871 0.0538053 0.569218 0.0537385 0.575449 0.0535689 0.581552 0.0533099 0.587519 0.052978 0.593345 0.0525926 0.599029 0.0521764 0.604572 0.0517549 0.609981 0.0513572 0.615264 0.0510155 0.620433 0.050766 0.625505 0.0506489 0.6305 0.0507095 0.635443 0.0509987 0.640361 0.0515745 0.645289 0.0525038 0.0538656 0.487118 0.0385397 0.493007 0.0396585 0.499046 0.0407366 0.505222 0.0417591 0.511519 0.0427172 0.517919 0.0436033 0.524404 0.0444086 0.530954 0.0451253 0.537547 0.0457465 0.544164 0.0462669 0.550781 0.0466831 0.55738 0.0469934 0.563941 0.0471987 0.570444 0.0473017 0.576875 0.047308 0.583218 0.0472258 0.589462 0.0470658 0.595598 0.0468418 0.601621 0.04657 0.607527 0.04627 0.613318 0.0459638 0.618999 0.045677 0.624576 0.0454382 0.630063 0.0452794 0.635474 0.0452371 0.640832 0.0453518 0.646161 0.0456697 0.651493 0.0462433 0.656864 0.0471327 0.0484108 0.496001 0.0329237 0.501778 0.0338824 0.507705 0.0348096 0.513771 0.0356929 0.519963 0.0365251 0.526266 0.0372998 0.532665 0.03801 0.539141 0.0386488 0.545678 0.0392102 0.552255 0.0396897 0.558854 0.0400839 0.565457 0.040391 0.572044 0.0406111 0.5786 0.040746 0.585108 0.0408 0.591554 0.0407793 0.597928 0.0406926 0.604218 0.0405509 0.61042 0.040368 0.61653 0.0401601 0.622548 0.0399462 0.628477 0.0397479 0.634325 0.0395902 0.640103 0.039501 0.645828 0.0395121 0.651521 0.0396595 0.657207 0.0399836 0.662919 0.0405308 0.668698 0.0413535 0.0425164 0.505311 0.0273904 0.511003 0.0281904 0.516847 0.0289661 0.522832 0.0297077 0.528947 0.0304097 0.535181 0.0310667 0.541518 0.031673 0.547944 0.0322228 0.554442 0.0327114 0.560997 0.0331347 0.567592 0.0334897 0.574208 0.0337748 0.580829 0.0339895 0.58744 0.0341351 0.594026 0.0342146 0.600572 0.0342329 0.607068 0.0341966 0.613504 0.0341148 0.619874 0.0339985 0.626173 0.033861 0.632401 0.0337179 0.638561 0.0335876 0.644661 0.0334908 0.65071 0.0334513 0.656726 0.0334962 0.66273 0.0336559 0.668748 0.0339654 0.674815 0.0344641 0.680971 0.035197 0.0362214 0.515117 0.0219106 0.520756 0.0225521 0.526546 0.0231758 0.53248 0.0237738 0.538548 0.0243416 0.544739 0.0248753 0.551042 0.0253704 0.557442 0.0258223 0.563927 0.0262271 0.57048 0.0265815 0.577087 0.0268831 0.583731 0.0271303 0.590398 0.0273227 0.597072 0.027461 0.603739 0.0275473 0.610387 0.0275852 0.617004 0.0275799 0.62358 0.0275383 0.63011 0.027469 0.636588 0.0273826 0.643014 0.0272916 0.649391 0.0272106 0.655726 0.0271565 0.662029 0.0271485 0.668316 0.0272089 0.674609 0.0273626 0.680936 0.0276383 0.687332 0.0280685 0.693839 0.0286896 0.0295483 0.525508 0.0164543 0.531122 0.0169375 0.53689 0.0174077 0.542804 0.0178596 0.548856 0.0182899 0.555036 0.0186955 0.561333 0.0190731 0.567736 0.0194194 0.574232 0.0197314 0.580807 0.0200066 0.587447 0.0202431 0.594137 0.0204396 0.600864 0.0205957 0.607613 0.0207119 0.614371 0.0207894 0.621125 0.020831 0.627865 0.0208403 0.634581 0.0208224 0.641266 0.0207838 0.647917 0.0207322 0.654531 0.020677 0.661112 0.0206294 0.667667 0.0206021 0.674205 0.0206099 0.680744 0.0206697 0.687306 0.0208009 0.693919 0.0210259 0.700617 0.0213701 0.707444 0.0218628 0.0225454 0.536547 0.0109882 0.542173 0.0113113 0.547953 0.0116276 0.553882 0.0119313 0.559951 0.0122207 0.566153 0.0124939 0.572477 0.0127489 0.578913 0.0129833 0.585449 0.0131951 0.592073 0.0133826 0.598772 0.0135447 0.605531 0.0136803 0.612338 0.0137891 0.619178 0.0138714 0.62604 0.013928 0.63291 0.0139606 0.639779 0.0139717 0.646636 0.0139645 0.653477 0.0139434 0.660295 0.0139136 0.667091 0.0138814 0.673866 0.0138542 0.680628 0.0138408 0.687386 0.0138512 0.694159 0.013897 0.700968 0.0139918 0.707843 0.0141512 0.714819 0.0143935 0.721942 0.01474 0.0152197 0.54834 0.00547596 0.554009 0.00564256 0.559834 0.00580214 0.565811 0.00595426 0.571933 0.00609927 0.57819 0.00623636 0.584575 0.0063642 0.591077 0.00648158 0.597684 0.00658748 0.604386 0.0066811 0.611169 0.00676176 0.61802 0.00682901 0.624927 0.00688264 0.631875 0.00692276 0.638853 0.0069498 0.645849 0.0069646 0.652853 0.00696838 0.659854 0.00696283 0.666848 0.00695012 0.673828 0.00693292 0.680795 0.00691445 0.687751 0.00689855 0.694702 0.0068897 0.70166 0.00689311 0.708642 0.00691486 0.715672 0.00696214 0.722779 0.00704375 0.730002 0.00717129 0.737379 0.00736247 0.00766185 0.551729 0.557371 0.563173 0.569128 0.575227 0.581463 0.587827 0.594309 0.600897 0.607578 0.614339 0.621168 0.628051 0.634974 0.641924 0.648888 0.655857 0.662819 0.66977 0.676702 0.683617 0.690515 0.697405 0.704298 0.711213 0.718175 0.725219 0.73239 0.739753 ) ; boundaryField { inlet { type calculated; value nonuniform List<scalar> 45 ( -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.2 -0.20766 -0.212683 -0.217828 -0.223097 -0.228493 -0.23402 -0.239681 -0.245479 -0.251417 -0.257499 -0.263728 -0.270107 -0.276641 -0.283333 -0.290186 -0.297206 -0.304395 -0.311758 -0.3193 -0.327023 -0.334934 -0.343036 -0.351334 -0.359832 -0.368536 -0.377451 -0.386582 -0.395933 -0.40551 -0.415319 ) ; } outlet { type calculated; value nonuniform List<scalar> 45 ( 0.0209737 0.0290374 0.0242085 0.0144449 0.00242737 -0.00735758 -0.0153484 -0.0220342 -0.0276374 -0.0323423 -0.0362703 -0.0395037 -0.0421108 -0.0441354 -0.045599 -0.0482854 -0.0496547 -0.0500034 -0.0489356 -0.0455366 -0.040099 -0.02812 0.0610202 0.154399 0.240722 0.31801 0.385162 0.441818 0.488318 0.52559 0.554999 0.578154 0.596701 0.612134 0.625662 0.638173 0.650264 0.662319 0.674593 0.687266 0.700512 0.714447 0.729268 0.744937 0.747415 ) ; } flap { type calculated; value uniform 0; } upperWall { type calculated; value uniform 0; } lowerWall { type calculated; value uniform 0; } frontAndBack { type empty; value nonuniform 0(); } } // ************************************************************************* //
[ "aldo.abarca.ortega@gmail.com" ]
aldo.abarca.ortega@gmail.com
0075ebb280f63271b8b6704930ae02db989d50f5
76c1ad64811a9fefa089f34758a4c1544606ac43
/repos/b_2748/b_2748/main.cpp
921e821f8015935d3b97db81aa1fb338694b827c
[]
no_license
yuzin97/Algorithm
903ac31053506019dc8b5abb632a9478c5edfcd7
3ae065da9d0e84f5eb19b30c49b7d542a1ee38cf
refs/heads/master
2020-06-18T07:43:52.527135
2019-09-11T06:55:16
2019-09-11T06:55:16
196,217,223
0
0
null
null
null
null
UHC
C++
false
false
322
cpp
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> using namespace std; int main() { int num; long long int arr[90]; //longlong int로하고 lld로해야함 ㅜ-ㅜ scanf("%d", &num); arr[0] = 0; arr[1] = 1; for (int i = 2; i <= num; i++) { arr[i] = arr[i - 1] + arr[i - 2]; } printf("%lld", arr[num]); }
[ "97dbwls1224@gmail.com" ]
97dbwls1224@gmail.com
d077c8d48b5701c318454a4aa0d17a96e8e35a9e
ad58f920284c7ef84426cad087cfbce6466ddbf1
/数据挖掘作业2--黄建峰--2120150994/数据挖掘作业2--黄建峰--2120150994/程序/关联规则挖掘程序/ruleMining.cpp
2a7d7919835b31c4d2c0ab185831700bcea4f054
[]
no_license
hjf579068/second-homework
e36e584f13173a64e3edd25e846af8636bba1ff6
7a86ee0ad8de5ae8b0cad82fcc6988de9893828b
refs/heads/master
2021-01-20T19:33:55.522614
2016-07-08T10:40:25
2016-07-08T10:40:25
62,881,532
0
0
null
null
null
null
GB18030
C++
false
false
5,556
cpp
#include<iostream> #include<fstream> #include<string.h> using namespace std; void freComputer(int database[][10], int count, int rule[][15], int frequ[], int rcount, int length) { for(int i = 0; i < rcount; i++) { for(int j = 0; j < count; j++) { int flag = 1; for(int k = 0; k < length; k++) { if(!database[j][rule[i][k]]) { flag = 0; break; } } if(flag) { frequ[i] = frequ[i] + 1; } } } } void link1(int a[], int b[], int length,int cc[]) { int i, j, k = 0; for( i = 0, j = 0; i < length && j < length;) { if(a[i] < b[j]) { cc[k] = a[i]; i = i + 1; k = k + 1; } else { if(a[i] > b[j]) { cc[k] = b[j]; j = j + 1; k = k + 1; } else { cc[k] = a[i]; i = i + 1; j = j + 1; k = k + 1; } } } if(i == length && j < length) { cc[k] = b[j]; } if(i < length && j == length) { cc[k] = a[i]; } } int joint(int rule[200][15], int rcount, int length, int res[200][15]) { int count = 0; for(int i = 0; i < rcount - 1; i++) { for(int j = i + 1; j < rcount; j++) { int flag = 0; for(int k = 0; k < length; k++) { for(int t = 0; t < length; t++) { if(rule[i][k] == rule[j][t]) { flag = flag + 1; break; } } } if(flag == length - 1) { int temp[15]; link1(rule[i], rule[j], length, temp); if(count == 0) { for(int k = 0; k <= length; k++) { res[count][k] = temp[k]; } count = count + 1; } else { int flagN = 1; for(int k =0; k < count; k++) { int t; for(t = 0; t <= length; t++) { if(temp[t] != res[k][t]) break; } if(t > length) { flagN = 0; break; } } if(flagN) { for(int k = 0; k <= length; k++) { res[count][k] = temp[k]; } count = count + 1; } } } } } return count; } int main() { int database[200][10] = {0}, count, freq[15][200] = {0}, freItem[15][200][15], freCount[15], minS; float minSupport = 0.2; ifstream in("D:\\processed.txt"); int i = 0; while (!in.eof()) { int tem[8]; for(int j = 0; j < 8;j++) { in>>tem[j]; } for(int j = 0; j < 8;j++) { if(tem[j]) { database[i][tem[j]] = 1; } } i = i + 1; } count = i - 1; minS = count * minSupport; /*第一次扫描,计算每个候选项的频数,并将频数在最小支持度之上的项记录下来*/ int rule1[200][15], freq1[200] = {0}; for(int t = 0; t < 9; t++) { rule1[t][0] = t + 1; } freComputer(database, count, rule1, freq1, 9, 1); int count1 = 0; for(int i = 0; i < 9; i++) { if(freq1[i] >= minS) { freItem[1][count1][0] = rule1[i][0]; freq[1][count1] = freq1[i]; count1++; } } freCount[1] = count1; /*将单项项目拼接产生包含两项的候选项,并计算候选项的频数,然后将频数在最小支持度之上的项记录下来*/ int rule2[200][15], freq2[200] = {0}, temp2; temp2 = joint(freItem[1], freCount[1], 1, rule2); freComputer(database, count, rule2, freq2, temp2, 2); int count2 = 0; for(int i = 0; i < temp2; i++) { if(freq2[i] >= minS) { for(int j = 0; j < 2; j++) { freItem[2][count2][j] = rule2[i][j]; } freq[2][count2] = freq2[i]; count2++; } } freCount[2] = count2; int itemNum = 3; while(1) { int ruleTemp[200][15], freqTemp[200] = {0}, count_temp; count_temp = joint(freItem[itemNum - 1], freCount[itemNum - 1], itemNum - 1, ruleTemp); freComputer(database, count, ruleTemp, freqTemp, count_temp, itemNum); int countI = 0; for(int i = 0; i < count_temp; i++) { if(freqTemp[i] >= minS) { for(int j = 0; j < itemNum; j++) { freItem[itemNum][countI][j] = ruleTemp[i][j]; } freq[itemNum][countI] = freqTemp[i]; countI++; } } freCount[itemNum] = countI; if(freCount[itemNum] <= 1) { break; } else itemNum++; } //for(int i = 1; i < itemNum; i++) //{ // for(int j = 0; j < freCount[i];j++) // { // printf("频繁项集: "); // for(int k = 0; k < i; k++) // { // printf("%d ",freItem[i][j][k]); // } // printf(" 频数: %d\n", freq[i][j]); // } //} for(int i = 2; i < itemNum; i++) { for(int j = 0; j < freCount[i];j++) { if(freItem[i][j][i-1] == 8 ||freItem[i][j][i-1] == 9){ float supp, conf, countTemp[2]; int tem[15], k; countTemp[0] = freq[i][j]; for(k = 0; k < i - 1; k++) { tem[k] = freItem[i][j][k]; } for(int k1 = 0; k1 < freCount[i-1];k1++) { int k2, flag = 1; for(k2 = 0; k2 < i - 1; k2++) { if(tem[k2] != freItem[i-1][k1][k2]) { flag = 0; break; } } if(flag) { countTemp[1] = freq[i-1][k1]; break; } } supp = countTemp[0] / 120; conf = countTemp[0] / countTemp[1]; if(conf>=0.8){ for(k = 0; k < i - 1; k++) { if(k == 0) { printf("%d", freItem[i][j][k]); } else { printf("∧%d", freItem[i][j][k]); } } printf("->%d",freItem[i][j][k]); printf(": "); printf("%.f÷120 = %.3f; ",countTemp[0], supp); printf("%.f÷%.f = %.3f",countTemp[0], countTemp[1], conf); if(freItem[i][j][i - 1]== 8) { printf("; %.3f÷0.492=%.3f", conf, conf/0.492); } if(freItem[i][j][i - 1]== 9) { printf("; %.3f÷0.417=%.3f", conf, conf/0.417); } printf("\n"); } } } } system("pause"); return 0; }
[ "1048124392@qq.com" ]
1048124392@qq.com
ab8ee2cdb172cd23bb1e1c99da1afcdccef7d139
8010df1fef10ddfd83bf07966cbf7e2e4b0d7ee9
/include/winsdk/cppwinrt/winrt/impl/Windows.UI.Core.AnimationMetrics.0.h
350e5d42164053a2f574cdf6483bc14e3ad937a5
[ "MIT" ]
permissive
light-tech/MSCpp
a23ab987b7e12329ab2d418b06b6b8055bde5ca2
012631b58c402ceec73c73d2bda443078bc151ef
refs/heads/master
2022-12-26T23:51:21.686396
2020-10-15T13:40:34
2020-10-15T13:40:34
188,921,341
6
0
null
null
null
null
UTF-8
C++
false
false
13,657
h
// C++/WinRT v2.0.190620.2 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef WINRT_Windows_UI_Core_AnimationMetrics_0_H #define WINRT_Windows_UI_Core_AnimationMetrics_0_H namespace winrt::Windows::Foundation { struct Point; } namespace winrt::Windows::UI::Core::AnimationMetrics { enum class AnimationEffect : int32_t { Expand = 0, Collapse = 1, Reposition = 2, FadeIn = 3, FadeOut = 4, AddToList = 5, DeleteFromList = 6, AddToGrid = 7, DeleteFromGrid = 8, AddToSearchGrid = 9, DeleteFromSearchGrid = 10, AddToSearchList = 11, DeleteFromSearchList = 12, ShowEdgeUI = 13, ShowPanel = 14, HideEdgeUI = 15, HidePanel = 16, ShowPopup = 17, HidePopup = 18, PointerDown = 19, PointerUp = 20, DragSourceStart = 21, DragSourceEnd = 22, TransitionContent = 23, Reveal = 24, Hide = 25, DragBetweenEnter = 26, DragBetweenLeave = 27, SwipeSelect = 28, SwipeDeselect = 29, SwipeReveal = 30, EnterPage = 31, TransitionPage = 32, CrossFade = 33, Peek = 34, UpdateBadge = 35, }; enum class AnimationEffectTarget : int32_t { Primary = 0, Added = 1, Affected = 2, Background = 3, Content = 4, Deleted = 5, Deselected = 6, DragSource = 7, Hidden = 8, Incoming = 9, Outgoing = 10, Outline = 11, Remaining = 12, Revealed = 13, RowIn = 14, RowOut = 15, Selected = 16, Selection = 17, Shown = 18, Tapped = 19, }; enum class PropertyAnimationType : int32_t { Scale = 0, Translation = 1, Opacity = 2, }; struct IAnimationDescription; struct IAnimationDescriptionFactory; struct IOpacityAnimation; struct IPropertyAnimation; struct IScaleAnimation; struct AnimationDescription; struct OpacityAnimation; struct PropertyAnimation; struct ScaleAnimation; struct TranslationAnimation; } namespace winrt::impl { template <> struct category<Windows::UI::Core::AnimationMetrics::IAnimationDescription> { using type = interface_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::IAnimationDescriptionFactory> { using type = interface_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::IOpacityAnimation> { using type = interface_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::IPropertyAnimation> { using type = interface_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::IScaleAnimation> { using type = interface_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::AnimationDescription> { using type = class_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::OpacityAnimation> { using type = class_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::PropertyAnimation> { using type = class_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::ScaleAnimation> { using type = class_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::TranslationAnimation> { using type = class_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::AnimationEffect> { using type = enum_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::AnimationEffectTarget> { using type = enum_category; }; template <> struct category<Windows::UI::Core::AnimationMetrics::PropertyAnimationType> { using type = enum_category; }; template <> struct name<Windows::UI::Core::AnimationMetrics::IAnimationDescription> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.IAnimationDescription" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::IAnimationDescriptionFactory> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.IAnimationDescriptionFactory" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::IOpacityAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.IOpacityAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::IPropertyAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.IPropertyAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::IScaleAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.IScaleAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::AnimationDescription> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.AnimationDescription" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::OpacityAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.OpacityAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::PropertyAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.PropertyAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::ScaleAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.ScaleAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::TranslationAnimation> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.TranslationAnimation" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::AnimationEffect> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.AnimationEffect" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::AnimationEffectTarget> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.AnimationEffectTarget" }; }; template <> struct name<Windows::UI::Core::AnimationMetrics::PropertyAnimationType> { static constexpr auto & value{ L"Windows.UI.Core.AnimationMetrics.PropertyAnimationType" }; }; template <> struct guid_storage<Windows::UI::Core::AnimationMetrics::IAnimationDescription> { static constexpr guid value{ 0x7D11A549,0xBE3D,0x41DE,{ 0xB0,0x81,0x05,0xC1,0x49,0x96,0x2F,0x9B } }; }; template <> struct guid_storage<Windows::UI::Core::AnimationMetrics::IAnimationDescriptionFactory> { static constexpr guid value{ 0xC6E27ABE,0xC1FB,0x48B5,{ 0x92,0x71,0xEC,0xC7,0x0A,0xC8,0x6E,0xF0 } }; }; template <> struct guid_storage<Windows::UI::Core::AnimationMetrics::IOpacityAnimation> { static constexpr guid value{ 0x803AABE5,0xEE7E,0x455F,{ 0x84,0xE9,0x25,0x06,0xAF,0xB8,0xD2,0xB4 } }; }; template <> struct guid_storage<Windows::UI::Core::AnimationMetrics::IPropertyAnimation> { static constexpr guid value{ 0x3A01B4DA,0x4D8C,0x411E,{ 0xB6,0x15,0x1A,0xDE,0x68,0x3A,0x99,0x03 } }; }; template <> struct guid_storage<Windows::UI::Core::AnimationMetrics::IScaleAnimation> { static constexpr guid value{ 0x023552C7,0x71AB,0x428C,{ 0x9C,0x9F,0xD3,0x17,0x80,0x96,0x49,0x95 } }; }; template <> struct default_interface<Windows::UI::Core::AnimationMetrics::AnimationDescription> { using type = Windows::UI::Core::AnimationMetrics::IAnimationDescription; }; template <> struct default_interface<Windows::UI::Core::AnimationMetrics::OpacityAnimation> { using type = Windows::UI::Core::AnimationMetrics::IOpacityAnimation; }; template <> struct default_interface<Windows::UI::Core::AnimationMetrics::PropertyAnimation> { using type = Windows::UI::Core::AnimationMetrics::IPropertyAnimation; }; template <> struct default_interface<Windows::UI::Core::AnimationMetrics::ScaleAnimation> { using type = Windows::UI::Core::AnimationMetrics::IScaleAnimation; }; template <> struct default_interface<Windows::UI::Core::AnimationMetrics::TranslationAnimation> { using type = Windows::UI::Core::AnimationMetrics::IPropertyAnimation; }; template <> struct abi<Windows::UI::Core::AnimationMetrics::IAnimationDescription> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Animations(void**) noexcept = 0; virtual int32_t __stdcall get_StaggerDelay(int64_t*) noexcept = 0; virtual int32_t __stdcall get_StaggerDelayFactor(float*) noexcept = 0; virtual int32_t __stdcall get_DelayLimit(int64_t*) noexcept = 0; virtual int32_t __stdcall get_ZOrder(int32_t*) noexcept = 0; }; }; template <> struct abi<Windows::UI::Core::AnimationMetrics::IAnimationDescriptionFactory> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall CreateInstance(int32_t, int32_t, void**) noexcept = 0; }; }; template <> struct abi<Windows::UI::Core::AnimationMetrics::IOpacityAnimation> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_InitialOpacity(void**) noexcept = 0; virtual int32_t __stdcall get_FinalOpacity(float*) noexcept = 0; }; }; template <> struct abi<Windows::UI::Core::AnimationMetrics::IPropertyAnimation> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Type(int32_t*) noexcept = 0; virtual int32_t __stdcall get_Delay(int64_t*) noexcept = 0; virtual int32_t __stdcall get_Duration(int64_t*) noexcept = 0; virtual int32_t __stdcall get_Control1(Windows::Foundation::Point*) noexcept = 0; virtual int32_t __stdcall get_Control2(Windows::Foundation::Point*) noexcept = 0; }; }; template <> struct abi<Windows::UI::Core::AnimationMetrics::IScaleAnimation> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_InitialScaleX(void**) noexcept = 0; virtual int32_t __stdcall get_InitialScaleY(void**) noexcept = 0; virtual int32_t __stdcall get_FinalScaleX(float*) noexcept = 0; virtual int32_t __stdcall get_FinalScaleY(float*) noexcept = 0; virtual int32_t __stdcall get_NormalizedOrigin(Windows::Foundation::Point*) noexcept = 0; }; }; template <typename D> struct consume_Windows_UI_Core_AnimationMetrics_IAnimationDescription { [[nodiscard]] auto Animations() const; [[nodiscard]] auto StaggerDelay() const; [[nodiscard]] auto StaggerDelayFactor() const; [[nodiscard]] auto DelayLimit() const; [[nodiscard]] auto ZOrder() const; }; template <> struct consume<Windows::UI::Core::AnimationMetrics::IAnimationDescription> { template <typename D> using type = consume_Windows_UI_Core_AnimationMetrics_IAnimationDescription<D>; }; template <typename D> struct consume_Windows_UI_Core_AnimationMetrics_IAnimationDescriptionFactory { auto CreateInstance(Windows::UI::Core::AnimationMetrics::AnimationEffect const& effect, Windows::UI::Core::AnimationMetrics::AnimationEffectTarget const& target) const; }; template <> struct consume<Windows::UI::Core::AnimationMetrics::IAnimationDescriptionFactory> { template <typename D> using type = consume_Windows_UI_Core_AnimationMetrics_IAnimationDescriptionFactory<D>; }; template <typename D> struct consume_Windows_UI_Core_AnimationMetrics_IOpacityAnimation { [[nodiscard]] auto InitialOpacity() const; [[nodiscard]] auto FinalOpacity() const; }; template <> struct consume<Windows::UI::Core::AnimationMetrics::IOpacityAnimation> { template <typename D> using type = consume_Windows_UI_Core_AnimationMetrics_IOpacityAnimation<D>; }; template <typename D> struct consume_Windows_UI_Core_AnimationMetrics_IPropertyAnimation { [[nodiscard]] auto Type() const; [[nodiscard]] auto Delay() const; [[nodiscard]] auto Duration() const; [[nodiscard]] auto Control1() const; [[nodiscard]] auto Control2() const; }; template <> struct consume<Windows::UI::Core::AnimationMetrics::IPropertyAnimation> { template <typename D> using type = consume_Windows_UI_Core_AnimationMetrics_IPropertyAnimation<D>; }; template <typename D> struct consume_Windows_UI_Core_AnimationMetrics_IScaleAnimation { [[nodiscard]] auto InitialScaleX() const; [[nodiscard]] auto InitialScaleY() const; [[nodiscard]] auto FinalScaleX() const; [[nodiscard]] auto FinalScaleY() const; [[nodiscard]] auto NormalizedOrigin() const; }; template <> struct consume<Windows::UI::Core::AnimationMetrics::IScaleAnimation> { template <typename D> using type = consume_Windows_UI_Core_AnimationMetrics_IScaleAnimation<D>; }; } #endif
[ "lightech@outlook.com" ]
lightech@outlook.com
519d19cef1ab927f28fbc5b4e1e791905076c211
8d4bb9d87512349825216448ed79bf8c1cdb341e
/Bar/cadeira.cpp
1f51c7284e09e38dcd06a4212a81701178804b06
[]
no_license
andr3smp/Bar
13b366d5ed6e129ea1f3548c2f015d67e294e0c6
9adadef2b24ac42efa88b8c63515f377460290f3
refs/heads/master
2021-01-15T21:44:03.389623
2013-04-18T13:27:46
2013-04-18T13:27:46
null
0
0
null
null
null
null
IBM852
C++
false
false
9,006
cpp
#define _USE_MATH_DEFINES #include "cadeira.h" #include "cubo.h" #include "cilindro.h" #include "esfera.h" #include <GL/glut.h> #include <math.h> /** * Construtor da class Cadeira. * Inicializa as variaveis de largura, altura, espessura, fatias e camadas. */ Cadeira::Cadeira(){ this->comprimento = 0.0f; this->largura = 0.0f; this->altura = 0.0f; this->espessura = 0.0f; this->fatias = 0.0f; this->camadas = 0.0f; } /** * Construtor da class Cadeira. *@param c * Variavel que especifica a comprimento da cadeira *@param l * Variavel que especifica a largura da cadeira *@param a * Variavel que especifica a altura da cadeira *@param e * Variavel que especifica a espessura da cadeira *@param f * Variavel que especifica as fatias da cadeira *@param p * Variavel que especifica as camadas da cadeira */ Cadeira::Cadeira(float c, float l, float a, float e, float f, float p){ this->comprimento = c; this->largura = l; this->altura = a; this->espessura = e; this->fatias = f; this->camadas = p; } /* Metodo que desenha o esqueleto de uma cadeira em que as pernas base e costas sao desenhadas a partir * do construtor Cubo */ void Cadeira::desenhaBasePernas(){ Cubo *base; Cubo *perna[4]; Cubo *costas; //Base da Mesa glPushMatrix(); glTranslatef(0.0f, 4.5f * this->altura / 10.0f, 0.0f); base = new Cubo(this->comprimento, this->espessura, this->largura, this->fatias, this->camadas);; base->desenha(); glPopMatrix(); //Perna da Frente Direita glPushMatrix(); glTranslatef(this->comprimento/2 - this->espessura/2, (2.25f * this->altura) / 10.0f - this->espessura / 4, this->largura/2 - this->espessura/2); perna[0] = new Cubo(this->espessura, (4.5f * this->altura / 10.0f) - this->espessura/2 , this->espessura, this->fatias, this->camadas); perna[0]->desenha(); glPopMatrix(); //Perna da Frente Esquerda glPushMatrix(); glTranslatef(-this->comprimento/2 + this->espessura/2, (2.25f * this->altura) / 10.0f - this->espessura / 4, this->largura/2 - this->espessura/2); perna[1] = new Cubo(this->espessura, (4.5f * this->altura / 10.0f) - this->espessura/2 , this->espessura, this->fatias, this->camadas); perna[1]->desenha(); glPopMatrix(); //Perna de Tras Direita glPushMatrix(); glTranslatef(this->comprimento/2 - this->espessura/2, (2.25f * this->altura) / 10.0f - this->espessura / 4, -this->largura/2 + this->espessura/2); perna[2] = new Cubo(this->espessura, (4.5f * this->altura / 10.0f) - this->espessura/2 , this->espessura, this->fatias, this->camadas); perna[2]->desenha(); glPopMatrix(); //Perna de Tras Esquerda glPushMatrix(); glTranslatef(-this->comprimento/2 + this->espessura/2, (2.25f * this->altura) / 10.0f - this->espessura / 4, -this->largura/2 + this->espessura/2); perna[3] = new Cubo(this->espessura, (4.5f * this->altura / 10.0f) - this->espessura/2 , this->espessura, this->fatias, this->camadas); perna[3]->desenha(); glPopMatrix(); //Tabua Para as Costas glPushMatrix(); glTranslatef(0.0f, 7.25f * this->altura / 10 + this->espessura / 4, - this->largura / 2 + this->espessura/2); costas = new Cubo(this->comprimento, (5.5f * this->altura / 10.0f) - this->espessura /2, this->espessura, this->fatias, this->camadas); costas->desenha(); glPopMatrix(); } /*Metodo que desenha uma cadeira standard, em que as pernas estao ligadas perpendicularmente */ void Cadeira::desenhaA(){ Cubo *tabua[4]; desenhaBasePernas(); //Tabua que Liga as Pernas da Direita glPushMatrix(); glTranslatef(this->comprimento/2 - this->espessura/2, this->altura / 10.0f, 0.0f); tabua[0] = new Cubo(this->espessura, this->espessura / 2, this->largura - 2 * this->espessura, this->fatias, this->camadas); tabua[0]->desenha(); glPopMatrix(); //Tabua que Liga as Pernas da Esquerda glPushMatrix(); glTranslatef(-this->comprimento/2 + this->espessura/2, this->altura / 10, 0.0f); tabua[1] = new Cubo(this->espessura, this->espessura / 2, this->largura - 2* this->espessura, this->fatias, this->camadas); tabua[1]->desenha(); glPopMatrix(); //Tabua que Liga as Pernas da Frente glPushMatrix(); glTranslatef(0.0f, this->altura / 10, this->largura/2 - this->espessura/2); tabua[2] = new Cubo(this->comprimento - 2 * this->espessura, this->espessura/2, this->espessura, this->fatias, this->camadas); tabua[2]->desenha(); glPopMatrix(); //Tabua que Liga as Pernas de Tras glPushMatrix(); glTranslatef(0.0f, this->altura / 10, -this->largura/2 + this->espessura/2); tabua[3] = new Cubo(this->comprimento - 2 * this->espessura, this->espessura/2, this->espessura, this->fatias, this->camadas); tabua[3]->desenha(); glPopMatrix(); } /* metodo que desenha um Banco */ void Cadeira::desenhaB(){ Cilindro *base; Cilindro *perna[4]; float graus = 0.0f; //Base da Mesa glPushMatrix(); glTranslatef(0.0f, this->altura, 0.0f); base = new Cilindro(this->largura, this->espessura, this->fatias * 3, this->camadas * 2); base->desenha(); glPopMatrix(); //Pernas for(int i = 0; i < 4; i++) { glPushMatrix(); glTranslatef((this->largura - this->espessura) * cos(graus), this->altura / 2, (this->largura - this->espessura) * sin(graus)); perna[i] = new Cilindro(this->espessura / 2, this->altura - this->espessura, this->fatias * 3, this->camadas); perna[i]->desenha(); glPopMatrix(); graus = graus + M_PI / 2; } } /* Metodo que desenha um banco comprido com uma tabua a ligar as pernas pelo meio */ void Cadeira::desenhaC(){ Cubo *base; Cubo *perna[4]; Cubo *tabua[3]; desenhaBasePernas(); //Tabua que Liga as Pernas da Direita glPushMatrix(); glTranslatef(this->comprimento/2 - this->espessura/2, this->altura / 10, 0.0f); tabua[0] = new Cubo(this->espessura, this->espessura / 2, this->largura - 2 * this->espessura, this->fatias, this->camadas); tabua[0]->desenha(); glPopMatrix(); //Tabua que Liga as Pernas da Esquerda glPushMatrix(); glTranslatef(-this->comprimento/2 + this->espessura/2, this->altura / 10, 0.0f); tabua[1] = new Cubo(this->espessura, this->espessura / 2, this->largura - 2 * this->espessura, this->fatias, this->camadas); tabua[1]->desenha(); glPopMatrix(); //Tabua Central glPushMatrix(); glTranslatef(0.0f, this->altura / 10, 0.0f); tabua[2] = new Cubo(this->comprimento - 2 * this->espessura, this->espessura / 2, this->espessura, this->fatias, this->camadas); tabua[2]->desenha(); glPopMatrix(); } /*Metodo que desenha a cadeira de um rei, com sitios para pousar os brašos, esferas no topo da cadeira, e um meio cilindro */ void Cadeira::desenhaD(){ Esfera *ornamento[2]; Cubo *bracos[4]; Cilindro *metade; desenhaBasePernas(); //Desenho do Brašo Direito glPushMatrix(); glTranslatef(this->comprimento/2 - this->espessura / 4, 7.0f * this->altura / 10.0f, this->espessura/2); bracos[0] = new Cubo(this->espessura / 2, this->espessura / 2, this->largura - this->espessura, this->fatias, this->camadas); bracos[0]->desenha(); glPopMatrix(); glPushMatrix(); glTranslatef(this->comprimento / 2 - this->espessura / 4, 5.75f * this->altura / 10.0f - this->espessura/8 + this->espessura / 4, this->largura/2 - this->espessura/4); bracos[0] = new Cubo(this->espessura / 2, 2.5f * this->altura / 10.0f - this->espessura / 4 - this->espessura / 2, this->espessura / 2, this->fatias, this->camadas); bracos[0]->desenha(); glPopMatrix(); //Desenho do Brašo Esquerdo glPushMatrix(); glTranslatef(-this->comprimento/2 + this->espessura / 4, 7.0f * this->altura / 10.0f, this->espessura/2); bracos[2] = new Cubo(this->espessura / 2, this->espessura / 2, this->largura - this->espessura, this->fatias, this->camadas); bracos[2]->desenha(); glPopMatrix(); glPushMatrix(); glTranslatef(-this->comprimento / 2 + this->espessura / 4, 5.75f * this->altura / 10.0f - this->espessura/8 + this->espessura / 4, this->largura/2 - this->espessura/4); bracos[0] = new Cubo(this->espessura / 2, 2.5f * this->altura / 10.0f - this->espessura / 4 - this->espessura / 2, this->espessura / 2, this->fatias, this->camadas); bracos[0]->desenha(); glPopMatrix(); //Bolas No Canto Superior da Cadeira glPushMatrix(); glTranslatef(-this->comprimento / 2 + this->espessura / 2, this->altura + this->espessura /2, -this->largura / 2 + this->espessura / 2); ornamento[0] = new Esfera(this->espessura / 2, this->fatias * 4, this->camadas * 3); ornamento[0]->desenha(); glPopMatrix(); glPushMatrix(); glTranslatef(this->comprimento / 2 - this->espessura / 2, this->altura + this->espessura /2, -this->largura / 2 + this->espessura / 2); ornamento[0] = new Esfera(this->espessura / 2, this->fatias * 4, this->camadas * 3); ornamento[0]->desenha(); glPopMatrix(); glPushMatrix(); glTranslatef(0.0f,this->altura,-this->largura / 2 + this->espessura / 2); glRotatef(270.0f,1.0f,0.0f,0.0f); metade = new Cilindro(this->comprimento / 2 - this->espessura, this->espessura, this->fatias, this->camadas); metade->meioCilindro(); glPopMatrix(); }
[ "tiagoavpinto@hotmail.com" ]
tiagoavpinto@hotmail.com
d291587bbf02c819f41040035ec7cfb9608de60d
92756269d7ba6a7c0a57ba8fcc1fd5f17cfba88f
/source/dialog_projectsettings.cpp
bff6441546cda4e391f6ed4c9dc742e3d8d73b35
[]
no_license
kapiten79/timecontrol
1a2ee54986029dd21e7109ad7aa3c90d2d2b4755
59b70fb99e105f8f7552b046dfbec003080e528f
refs/heads/master
2020-04-05T15:44:05.397613
2018-11-10T12:51:32
2018-11-10T12:51:32
156,981,274
0
0
null
null
null
null
UTF-8
C++
false
false
5,598
cpp
#include "dialog_projectsettings.h" #include "ui_dialog_projectsettings.h" Dialog_projectSettings::Dialog_projectSettings(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog_projectSettings) { ui->setupUi(this); cps.model = this; } Dialog_projectSettings::~Dialog_projectSettings() { } void Dialog_projectSettings::init_window(QString p_caller) { qDebug() << "Функция Dialog_projectSettings::init_window() запустилась " << caller; this->open(); cps.model = this; caller = p_caller; QDir upDir; if (caller == "createNewProj") { this->setWindowTitle("Параметры проекта нового проекта"); ui->lineEdit ->setEnabled(true); ui->pushButton ->setEnabled(true); ui->lineEditProjectName ->setEnabled(true); qDebug() << *cps.workDir << " != " << QDir::homePath(); if (*cps.workDir != QDir::homePath()) { qDebug() << "Это не каталог по умолчанию"; upDir.setPath(*cps.workDir); upDir.cdUp(); ui->lineEdit->setText(upDir.path()); } else { ui->lineEdit->setText(*cps.workDir); } ui->lineEditProjectName ->clear(); ui->lineEditProjectPrice ->clear(); ui->plainTextEditProjectDescription ->clear(); ui->lineEditContactName ->clear(); ui->lineEdiContactPthone ->clear(); ui->lineEditContactEmail ->clear(); } else { this->setWindowTitle("Параметры проекта '" + cps.pList->projNameSt+"'"); ui->lineEdit ->setEnabled(false); ui->pushButton ->setEnabled(false); ui->lineEditProjectName ->setEnabled(false); ui->lineEditProjectName ->setText (cps.pList->projNameSt) ; ui->lineEditProjectPrice ->setText (cps.pList->projPriceSt) ; ui->plainTextEditProjectDescription ->setPlainText (cps.pList->projDescriptionSt) ; ui->lineEditContactName ->setText (cps.pList->projContactNameSt) ; ui->lineEdiContactPthone ->setText (cps.pList->projPhoneSt) ; ui->lineEditContactEmail ->setText (cps.pList->projEmailSt) ; /** Если редактируются данные проекта, мне нужно указать в данной строке родительскую папку рабочего каталога */ upDir.setPath(*cps.workDir); upDir.cdUp(); ui->lineEdit->setText(upDir.path()); } } void Dialog_projectSettings::on_buttonBoxAcceptDecline_accepted() { qDebug() << "Функция Dialog_projectSettings::on_buttonBoxAcceptDecline_accepted() запустилась " << caller; if (ui->lineEditProjectName->text() != "") { cps.pList->projNameSt = ui->lineEditProjectName ->text (); cps.pList->projPriceSt = ui->lineEditProjectPrice ->text (); cps.pList->projDescriptionSt = ui->plainTextEditProjectDescription ->toPlainText (); cps.pList->projContactNameSt = ui->lineEditContactName ->text (); cps.pList->projPhoneSt = ui->lineEdiContactPthone ->text (); cps.pList->projEmailSt = ui->lineEditContactEmail ->text (); qDebug() << "Коллер " << caller; if (caller == "createNewProj") { cps.create_newProject(); qDebug() << "Эммитируется сигнела s_setProjParams "; emit s_setProjParams(); } else { cps.writeProjToJSON(); connect (this, SIGNAL(s_setProjParams()), parentObj, SLOT(setProjParams())); emit s_setProjParams(); disconnect (this, SIGNAL(s_setProjParams()), parentObj, SLOT(setProjParams())); } } } /* Нажатие кнопки выбора родительского каталога папки проекта */ void Dialog_projectSettings::on_pushButton_clicked() { qDebug() << "Функция Dialog_projectSettings::on_pushButton_clicked() запустилась " << *cps.workDir; /** Открываем диалоговое окно выбора каталога */ QString dir = QFileDialog::getExistingDirectory(this, tr("Выберите каталог проекта или создайте новый ..."), *cps.workDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); /** Указываем в окне новый каталог */ ui->lineEdit->setText(dir); /** Присваиваем имя проекта переменной workDir */ delete(cps.workDir); cps.workDir = new QString(dir); } /* Обработка нажатия кнопки отменя создания проекта */ void Dialog_projectSettings::on_buttonBoxAcceptDecline_rejected() { qDebug() << "Dialog_projectSettings::on_buttonBoxAcceptDecline_rejected() " << *cps.workDir; //cps.workDir = ""; }
[ "mihon79@inbox.ru" ]
mihon79@inbox.ru
36de4fe00d6043c5954c83378117d7899af4b401
0019f0af5518efe2144b6c0e63a89e3bd2bdb597
/antares/src/kits/game/DirectWindow.cpp
d82273cb0d0aff351d69622e94b965023f933283
[]
no_license
mmanley/Antares
5ededcbdf09ef725e6800c45bafd982b269137b1
d35f39c12a0a62336040efad7540c8c5bce9678a
refs/heads/master
2020-06-02T22:28:26.722064
2010-03-08T21:51:31
2010-03-08T21:51:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,744
cpp
/* * Copyright 2003-2009, Antares Inc. * Authors: * Stefano Ceccherini <stefano.ceccherini@gmail.com> * Carwyn Jones <turok2@currantbun.com> * * Distributed under the terms of the MIT License. */ #include <DirectWindow.h> #include <stdio.h> #include <string.h> #include <Screen.h> #include <clipping.h> #include <AppServerLink.h> #include <DirectWindowPrivate.h> #include <ServerProtocol.h> //#define DEBUG 1 #define OUTPUT printf //#define OUTPUT debug_printf // We don't need this kind of locking, since the directDaemonFunc // doesn't access critical shared data. #define DW_NEEDS_LOCKING 0 enum dw_status_bits { DW_STATUS_AREA_CLONED = 0x1, DW_STATUS_THREAD_STARTED = 0x2, DW_STATUS_SEM_CREATED = 0x4 }; #if DEBUG static void print_direct_buffer_state(const direct_buffer_state &state) { char string[128]; int modeState = state & B_DIRECT_MODE_MASK; if (modeState == B_DIRECT_START) strcpy(string, "B_DIRECT_START"); else if (modeState == B_DIRECT_MODIFY) strcpy(string, "B_DIRECT_MODIFY"); else if (modeState == B_DIRECT_STOP) strcpy(string, "B_DIRECT_STOP"); if (state & B_CLIPPING_MODIFIED) strcat(string, " | B_CLIPPING_MODIFIED"); if (state & B_BUFFER_RESIZED) strcat(string, " | B_BUFFER_RESIZED"); if (state & B_BUFFER_MOVED) strcat(string, " | B_BUFFER_MOVED"); if (state & B_BUFFER_RESET) strcat(string, " | B_BUFFER_RESET"); OUTPUT("direct_buffer_state: %s\n", string); } static void print_direct_driver_state(const direct_driver_state &state) { if (state == 0) return; char string[64]; if (state == B_DRIVER_CHANGED) strcpy(string, "B_DRIVER_CHANGED"); else if (state == B_MODE_CHANGED) strcpy(string, "B_MODE_CHANGED"); OUTPUT("direct_driver_state: %s\n", string); } #if DEBUG > 1 static void print_direct_buffer_layout(const buffer_layout &layout) { char string[64]; if (layout == B_BUFFER_NONINTERLEAVED) strcpy(string, "B_BUFFER_NONINTERLEAVED"); else strcpy(string, "unknown"); OUTPUT("layout: %s\n", string); } static void print_direct_buffer_orientation(const buffer_orientation &orientation) { char string[64]; switch (orientation) { case B_BUFFER_TOP_TO_BOTTOM: strcpy(string, "B_BUFFER_TOP_TO_BOTTOM"); break; case B_BUFFER_BOTTOM_TO_TOP: strcpy(string, "B_BUFFER_BOTTOM_TO_TOP"); break; default: strcpy(string, "unknown"); break; } OUTPUT("orientation: %s\n", string); } #endif // DEBUG > 2 static void print_direct_buffer_info(const direct_buffer_info &info) { print_direct_buffer_state(info.buffer_state); print_direct_driver_state(info.driver_state); # if DEBUG > 1 OUTPUT("bits: %p\n", info.bits); OUTPUT("pci_bits: %p\n", info.pci_bits); OUTPUT("bytes_per_row: %ld\n", info.bytes_per_row); OUTPUT("bits_per_pixel: %lu\n", info.bits_per_pixel); OUTPUT("pixel_format: %d\n", info.pixel_format); print_direct_buffer_layout(info.layout); print_direct_buffer_orientation(info.orientation); # if DEBUG > 2 // TODO: this won't work correctly with debug_printf() printf("CLIPPING INFO:\n"); printf("clipping_rects count: %ld\n", info.clip_list_count); printf("- window_bounds:\n"); BRegion region; region.Set(info.window_bounds); region.PrintToStream(); region.MakeEmpty(); for (uint32 i = 0; i < info.clip_list_count; i++) region.Include(info.clip_list[i]); printf("- clip_list:\n"); region.PrintToStream(); # endif # endif OUTPUT("\n"); } #endif // DEBUG // #pragma mark - BDirectWindow::BDirectWindow(BRect frame, const char *title, window_type type, uint32 flags, uint32 workspace) : BWindow(frame, title, type, flags, workspace) { _InitData(); } BDirectWindow::BDirectWindow(BRect frame, const char *title, window_look look, window_feel feel, uint32 flags, uint32 workspace) : BWindow(frame, title, look, feel, flags, workspace) { _InitData(); } BDirectWindow::~BDirectWindow() { _DisposeData(); } // #pragma mark - BWindow API implementation BArchivable * BDirectWindow::Instantiate(BMessage *data) { return NULL; } status_t BDirectWindow::Archive(BMessage *data, bool deep) const { return inherited::Archive(data, deep); } void BDirectWindow::Quit() { inherited::Quit(); } void BDirectWindow::DispatchMessage(BMessage *message, BHandler *handler) { inherited::DispatchMessage(message, handler); } void BDirectWindow::MessageReceived(BMessage *message) { inherited::MessageReceived(message); } void BDirectWindow::FrameMoved(BPoint newPosition) { inherited::FrameMoved(newPosition); } void BDirectWindow::WorkspacesChanged(uint32 oldWorkspaces, uint32 newWorkspaces) { inherited::WorkspacesChanged(oldWorkspaces, newWorkspaces); } void BDirectWindow::WorkspaceActivated(int32 index, bool state) { inherited::WorkspaceActivated(index, state); } void BDirectWindow::FrameResized(float newWidth, float newHeight) { inherited::FrameResized(newWidth, newHeight); } void BDirectWindow::Minimize(bool minimize) { inherited::Minimize(minimize); } void BDirectWindow::Zoom(BPoint recPosition, float recWidth, float recHeight) { inherited::Zoom(recPosition, recWidth, recHeight); } void BDirectWindow::ScreenChanged(BRect screenFrame, color_space depth) { inherited::ScreenChanged(screenFrame, depth); } void BDirectWindow::MenusBeginning() { inherited::MenusBeginning(); } void BDirectWindow::MenusEnded() { inherited::MenusEnded(); } void BDirectWindow::WindowActivated(bool state) { inherited::WindowActivated(state); } void BDirectWindow::Show() { inherited::Show(); } void BDirectWindow::Hide() { inherited::Hide(); } BHandler * BDirectWindow::ResolveSpecifier(BMessage *msg, int32 index, BMessage *specifier, int32 form, const char *property) { return inherited::ResolveSpecifier(msg, index, specifier, form, property); } status_t BDirectWindow::GetSupportedSuites(BMessage *data) { return inherited::GetSupportedSuites(data); } status_t BDirectWindow::Perform(perform_code d, void *arg) { return inherited::Perform(d, arg); } void BDirectWindow::task_looper() { inherited::task_looper(); } BMessage * BDirectWindow::ConvertToMessage(void *raw, int32 code) { return inherited::ConvertToMessage(raw, code); } // #pragma mark - BDirectWindow specific API void BDirectWindow::DirectConnected(direct_buffer_info *info) { // implemented in subclasses } status_t BDirectWindow::GetClippingRegion(BRegion *region, BPoint *origin) const { if (region == NULL) return B_BAD_VALUE; if (IsLocked() || !_LockDirect()) return B_ERROR; if (fInDirectConnect) { _UnlockDirect(); return B_ERROR; } // BPoint's coordinates are floats. We can only work // with integers._DaemonStarter int32 originX, originY; if (origin == NULL) { originX = 0; originY = 0; } else { originX = (int32)origin->x; originY = (int32)origin->y; } #ifndef ANTARES_TARGET_PLATFORM_DANO // Since we are friend of BRegion, we can access its private members. // Otherwise, we would need to call BRegion::Include(clipping_rect) // for every clipping_rect in our clip_list, and that would be much // more overkill than this (tested ). if (!region->_SetSize(fBufferDesc->clip_list_count)) { _UnlockDirect(); return B_NO_MEMORY; } region->fCount = fBufferDesc->clip_list_count; region->fBounds = region->_ConvertToInternal(fBufferDesc->clip_bounds); for (uint32 c = 0; c < fBufferDesc->clip_list_count; c++) { region->fData[c] = region->_ConvertToInternal( fBufferDesc->clip_list[c]); } // adjust bounds by the given origin point region->OffsetBy(-originX, -originY); #endif _UnlockDirect(); return B_OK; } status_t BDirectWindow::SetFullScreen(bool enable) { if (fIsFullScreen == enable) return B_OK; status_t status = B_ERROR; if (Lock()) { fLink->StartMessage(AS_DIRECT_WINDOW_SET_FULLSCREEN); fLink->Attach<bool>(enable); if (fLink->FlushWithReply(status) == B_OK && status == B_OK) { fIsFullScreen = enable; } Unlock(); } return status; } bool BDirectWindow::IsFullScreen() const { return fIsFullScreen; } /*static*/ bool BDirectWindow::SupportsWindowMode(screen_id id) { display_mode mode; status_t status = BScreen(id).GetMode(&mode); if (status == B_OK) return (mode.flags & B_PARALLEL_ACCESS) != 0; return false; } // #pragma mark - Private methods /*static*/ int32 BDirectWindow::_daemon_thread(void *arg) { return static_cast<BDirectWindow *>(arg)->_DirectDaemon(); } int32 BDirectWindow::_DirectDaemon() { while (!fDaemonKiller) { // This sem is released by the app_server when our // clipping region changes, or when our window is moved, // resized, etc. etc. status_t status; do { status = acquire_sem(fDisableSem); } while (status == B_INTERRUPTED); if (status != B_OK) { //fprintf(stderr, "DirectDaemon: failed to acquire direct sem: %s\n", // strerror(status)); return -1; } #if DEBUG print_direct_buffer_info(*fBufferDesc); #endif if (_LockDirect()) { if ((fBufferDesc->buffer_state & B_DIRECT_MODE_MASK) == B_DIRECT_START) fConnectionEnable = true; fInDirectConnect = true; DirectConnected(fBufferDesc); fInDirectConnect = false; if ((fBufferDesc->buffer_state & B_DIRECT_MODE_MASK) == B_DIRECT_STOP) fConnectionEnable = false; _UnlockDirect(); } // The app_server then waits (with a timeout) on this sem. // If we aren't quick enough to release this sem, our app // will be terminated by the app_server if ((status = release_sem(fDisableSemAck)) != B_OK) { //fprintf(stderr, "DirectDaemon: failed to release sem: %s\n", //strerror(status)); return -1; } } return 0; } bool BDirectWindow::_LockDirect() const { // LockDirect() and UnlockDirect() are no-op on BeOS. I tried to call BeOS's // version repeatedly, from the same thread and from different threads, // nothing happened. // They're not needed though, as the direct_daemon_thread doesn't change // any shared data. They are probably here for future enhancements. status_t status = B_OK; #if DW_NEEDS_LOCKING BDirectWindow *casted = const_cast<BDirectWindow *>(this); if (atomic_add(&casted->fDirectLock, 1) > 0) { do { status = acquire_sem(casted->fDirectSem); } while (status == B_INTERRUPTED); } if (status == B_OK) { casted->fDirectLockOwner = find_thread(NULL); casted->fDirectLockCount++; } #endif return status == B_OK; } void BDirectWindow::_UnlockDirect() const { #if DW_NEEDS_LOCKING BDirectWindow *casted = const_cast<BDirectWindow *>(this); if (atomic_add(&casted->fDirectLock, -1) > 1) release_sem(casted->fDirectSem); casted->fDirectLockCount--; #endif } void BDirectWindow::_InitData() { fConnectionEnable = false; fIsFullScreen = false; fInDirectConnect = false; fInitStatus = 0; status_t status = B_ERROR; struct direct_window_sync_data syncData; fLink->StartMessage(AS_DIRECT_WINDOW_GET_SYNC_DATA); if (fLink->FlushWithReply(status) == B_OK && status == B_OK) fLink->Read<direct_window_sync_data>(&syncData); if (status != B_OK) return; #if DW_NEEDS_LOCKING fDirectLock = 0; fDirectLockCount = 0; fDirectLockOwner = -1; fDirectLockStack = NULL; fDirectSem = create_sem(0, "direct sem"); if (fDirectSem > 0) fInitStatus |= DW_STATUS_SEM_CREATED; #endif fSourceClippingArea = syncData.area; fDisableSem = syncData.disable_sem; fDisableSemAck = syncData.disable_sem_ack; fClonedClippingArea = clone_area("cloned direct area", (void**)&fBufferDesc, B_ANY_ADDRESS, B_READ_AREA, fSourceClippingArea); if (fClonedClippingArea > 0) { fInitStatus |= DW_STATUS_AREA_CLONED; fDirectDaemonId = spawn_thread(_daemon_thread, "direct daemon", B_DISPLAY_PRIORITY, this); if (fDirectDaemonId > 0) { fDaemonKiller = false; if (resume_thread(fDirectDaemonId) == B_OK) fInitStatus |= DW_STATUS_THREAD_STARTED; else kill_thread(fDirectDaemonId); } } } void BDirectWindow::_DisposeData() { // wait until the connection terminates: we can't destroy // the object until the client receives the B_DIRECT_STOP // notification, or bad things will happen while (fConnectionEnable) snooze(50000); _LockDirect(); if (fInitStatus & DW_STATUS_THREAD_STARTED) { fDaemonKiller = true; // delete this sem, otherwise the Direct daemon thread // will wait forever on it delete_sem(fDisableSem); status_t retVal; wait_for_thread(fDirectDaemonId, &retVal); } #if DW_NEEDS_LOCKING if (fInitStatus & DW_STATUS_SEM_CREATED) delete_sem(fDirectSem); #endif if (fInitStatus & DW_STATUS_AREA_CLONED) delete_area(fClonedClippingArea); } void BDirectWindow::_ReservedDirectWindow1() {} void BDirectWindow::_ReservedDirectWindow2() {} void BDirectWindow::_ReservedDirectWindow3() {} void BDirectWindow::_ReservedDirectWindow4() {}
[ "michael@Inferno.(none)" ]
michael@Inferno.(none)
24977deca27712077d4abaca4e90df2c63816597
4148a68bf831bd703429bf5fdf1d7fdb03054831
/api/josh/inversion.cpp
87946067be12a52b86f6efb27c40c1623dfa7623
[]
no_license
timlyo/Calculator
bf8a2f96b03e7bb792e8d1d4ad02c548f117d476
7183e82bfd8ebbbd85a4cdfeb32f9e210a1250de
refs/heads/master
2020-05-16T23:50:07.350669
2014-04-04T11:51:17
2014-04-04T11:51:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <string> #include "inversion.h" using std::string; string inversionClass::inversion(string binary){ string tempString; tempString.erase(); for (int x = binary.size()-1; x >=0; x--) { tempString.push_back(binary[x]); } return tempString; }
[ "timlyomaddison@gmail.com" ]
timlyomaddison@gmail.com
7fb50caf53076da4a192bacd961ca2a41bda0556
9b727ccbf91d12bbe10adb050784c04b4753758c
/ZOJ/Summer2013/PracticeContest2/f.cpp
2aabc8712f4fefbd92f5633b01aeb302a21b4354
[]
no_license
codeAligned/acm-icpc-1
b57ab179228f2acebaef01082fe6b67b0cae6403
090acaeb3705b6cf48790b977514965b22f6d43f
refs/heads/master
2020-09-19T19:39:30.929711
2015-10-06T15:13:12
2015-10-06T15:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
927
cpp
#include <cstdio> #include <cstring> const int MAXN=55; typedef char str[MAXN]; str word[MAXN]; int ans[MAXN]; int n; bool prefix(str a, str b) { if (strlen(a)>strlen(b)) return false; int len=strlen(a); for (int i=0; i<len; i++) if (a[i]!=b[i]) return false; return true; } bool check(int cur, int len) { str pre; for (int i=0; i<=len; i++) pre[i]=word[cur][i]; pre[++len]='\0'; for (int i=0; i<n; i++) if (cur!=i&&prefix(pre,word[i])) return false; return true; } int main() { int test; scanf("%d", &test); while (test--) { scanf("%d", &n); for (int i=0; i<n; i++) scanf("%s", word[i]); for (int i=0; i<n; i++) { int m=strlen(word[i]); for (int j=0; j<m; j++) if (check(i,j)) { ans[i]=j; break; } } for (int i=0; i<n; i++) { for (int j=0; j<=ans[i]; j++) putchar(word[i][j]); if (i==n-1) putchar('\n'); else putchar(' '); } } return 0; }
[ "zimpha@gmail.com" ]
zimpha@gmail.com
0a78a153a9dbbdba8115970e2f0df8a6160a97de
ad71ab3c39785830a112951075afe97c9948f5bc
/ZF/ZFAlgorithm/zfsrc/ZFAlgorithm/ZFXml.cpp
2270f00751e9040b1b447a0ebcb23121ffc59506
[ "Vim", "MIT" ]
permissive
ZFFrameworkDist/ZFFramework
0f8027126ef41e59c762cd68d878cac28fae1ea4
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
refs/heads/master
2021-08-04T04:40:41.207724
2021-05-25T08:36:10
2021-05-25T08:36:10
120,870,315
0
0
null
null
null
null
UTF-8
C++
false
false
56,937
cpp
#include "ZFXml.h" #include "protocol/ZFProtocolZFXml.h" ZF_NAMESPACE_GLOBAL_BEGIN // ============================================================ ZFENUM_DEFINE(ZFXmlType) ZFENUM_DEFINE(ZFXmlVisitType) ZFTYPEID_ACCESS_ONLY_DEFINE(ZFXmlVisitData, ZFXmlVisitData) ZFTYPEID_ACCESS_ONLY_DEFINE(ZFXmlVisitCallback, ZFXmlVisitCallback) ZFEXPORT_VAR_READONLY_DEFINE(ZFXmlVisitCallback, ZFXmlVisitCallbackDefault, ZFXmlVisitCallbackForOutput()) // ============================================================ zfbool ZFXmlOutputToken::operator == (ZF_IN ZFXmlOutputToken const &ref) const { return (zftrue && this->xmlNewLineToken == ref.xmlNewLineToken && this->xmlIndentToken == ref.xmlIndentToken && this->xmlDeclarationTagLeft == ref.xmlDeclarationTagLeft && this->xmlDeclarationTagRight == ref.xmlDeclarationTagRight && this->xmlDocTypeTagLeft == ref.xmlDocTypeTagLeft && this->xmlDocTypeTagRight == ref.xmlDocTypeTagRight && this->xmlPITagLeft == ref.xmlPITagLeft && this->xmlPITagRight == ref.xmlPITagRight && this->xmlElementBeginTagLeft == ref.xmlElementBeginTagLeft && this->xmlElementBeginTagRight == ref.xmlElementBeginTagRight && this->xmlElementEndTagLeft == ref.xmlElementEndTagLeft && this->xmlElementEndTagRight == ref.xmlElementEndTagRight && this->xmlElementSingleTagLeft == ref.xmlElementSingleTagLeft && this->xmlElementSingleTagRight == ref.xmlElementSingleTagRight && this->xmlAttributeEqualTag == ref.xmlAttributeEqualTag && this->xmlAttributeQuoteTagLeft == ref.xmlAttributeQuoteTagLeft && this->xmlAttributeQuoteTagRight == ref.xmlAttributeQuoteTagRight && this->xmlAttributeSingleQuoteTagLeft == ref.xmlAttributeSingleQuoteTagLeft && this->xmlAttributeSingleQuoteTagRight == ref.xmlAttributeSingleQuoteTagRight && this->xmlTextCDATATagLeft == ref.xmlTextCDATATagLeft && this->xmlTextCDATATagRight == ref.xmlTextCDATATagRight && this->xmlCommentTagLeft == ref.xmlCommentTagLeft && this->xmlCommentTagRight == ref.xmlCommentTagRight ); } zfbool ZFXmlOutputFlags::operator == (ZF_IN ZFXmlOutputFlags const &ref) const { return (zftrue && this->xmlToken == ref.xmlToken && this->xmlGlobalLineBeginToken == ref.xmlGlobalLineBeginToken && this->xmlElementAddNewLineAtHeadIfNotSingleLine == ref.xmlElementAddNewLineAtHeadIfNotSingleLine && this->xmlElementAttributeCountBeforeAddNewLine == ref.xmlElementAttributeCountBeforeAddNewLine && this->xmlElementTrimTagIfNoChildren == ref.xmlElementTrimTagIfNoChildren && this->xmlElementEndTagAtSameLineIfNoChildElement == ref.xmlElementEndTagAtSameLineIfNoChildElement && this->xmlAttributeUseSingleQuote == ref.xmlAttributeUseSingleQuote ); } ZFTYPEID_ACCESS_ONLY_DEFINE(ZFXmlOutputFlags, ZFXmlOutputFlags) // ============================================================ ZFEXPORT_VAR_READONLY_DEFINE(ZFXmlOutputFlags, ZFXmlOutputFlagsDefault, ZFXmlOutputFlags()) static const ZFXmlOutputFlags &_ZFP_ZFXmlOutputFlagsTrimInit(void) { static ZFXmlOutputFlags d; d.xmlElementAttributeCountBeforeAddNewLine = zfindexMax(); d.xmlElementTrimTagIfNoChildren = zftrue; d.xmlToken.xmlNewLineToken.removeAll(); d.xmlToken.xmlIndentToken.removeAll(); return d; } ZFEXPORT_VAR_READONLY_DEFINE(ZFXmlOutputFlags, ZFXmlOutputFlagsTrim, _ZFP_ZFXmlOutputFlagsTrimInit()) static const ZFXmlOutputFlags &_ZFP_ZFXmlOutputFlagsDetailedInit(void) { static ZFXmlOutputFlags d; d.xmlElementAddNewLineAtHeadIfNotSingleLine = zftrue; d.xmlElementAttributeCountBeforeAddNewLine = 1; d.xmlElementEndTagAtSameLineIfNoChildElement = zftrue; return d; } ZFEXPORT_VAR_READONLY_DEFINE(ZFXmlOutputFlags, ZFXmlOutputFlagsDetailed, _ZFP_ZFXmlOutputFlagsDetailedInit()) // ============================================================ static zfbool _ZFP_ZFXmlOutputElementUseSingleTag(ZF_IN const ZFXmlItem &element, ZF_IN const ZFXmlOutputFlags &flags, ZF_IN const ZFXmlVisitData &data) { return (flags.xmlElementTrimTagIfNoChildren && element.xmlChildFirst().xmlIsNull()); } static zfbool _ZFP_ZFXmlOutputElementAttributeNeedNewLine(ZF_IN const ZFXmlItem &element, ZF_IN const ZFXmlOutputFlags &flags, ZF_IN const ZFXmlVisitData &data) { if(element.xmlIsNull()) { return zffalse; } ZFXmlItem xmlAttribute = element.xmlAttributeFirst(); if(flags.xmlElementAttributeCountBeforeAddNewLine == zfindexMax()) { return zffalse; } if(flags.xmlElementAttributeCountBeforeAddNewLine == 0) { return !xmlAttribute.xmlIsNull(); } zfindex xmlAttributeCount = 0; while(!xmlAttribute.xmlIsNull()) { ++xmlAttributeCount; if(xmlAttributeCount > flags.xmlElementAttributeCountBeforeAddNewLine) { return zftrue; } xmlAttribute = xmlAttribute.xmlAttributeNext(); } return zffalse; } static zfbool _ZFP_ZFXmlOutputElementChildNeedNewLine(ZF_IN const ZFXmlItem &xmlChild, ZF_IN const ZFXmlOutputFlags &flags, ZF_IN const ZFXmlVisitData &data) { if(flags.xmlElementTrimTagIfNoChildren && xmlChild.xmlIsNull()) { return zffalse; } if(!flags.xmlElementEndTagAtSameLineIfNoChildElement) { return zftrue; } if(xmlChild.xmlType() != ZFXmlType::e_XmlText) { return zftrue; } for(ZFXmlItem t = xmlChild.xmlSiblingNext(); !t.xmlIsNull(); t = t.xmlSiblingNext()) { if(t.xmlType() != ZFXmlType::e_XmlText) { return zftrue; } } for(ZFXmlItem t = xmlChild.xmlSiblingPrev(); !t.xmlIsNull(); t = t.xmlSiblingPrev()) { if(t.xmlType() != ZFXmlType::e_XmlText) { return zftrue; } } return zffalse; } static zfbool _ZFP_ZFXmlOutputAttributeNeedNewLine(ZF_IN const ZFXmlItem &xmlAttribute, ZF_IN const ZFXmlOutputFlags &flags, ZF_IN const ZFXmlVisitData &data) { return (flags.xmlElementAttributeCountBeforeAddNewLine == 0 || (flags.xmlElementAttributeCountBeforeAddNewLine != zfindexMax() && data.siblingIndex > 0 && (data.siblingIndex % flags.xmlElementAttributeCountBeforeAddNewLine) == 0)); } zfclass _ZFP_I_ZFXmlOutputOwner : zfextends ZFObject { ZFOBJECT_DECLARE(_ZFP_I_ZFXmlOutputOwner, ZFObject) public: ZFOutput outputCallback; ZFXmlOutputFlags flags; public: ZFMETHOD_INLINE_1(zfbool, onVisit, ZFMP_IN(const ZFXmlVisitData &, data)) { switch(data.xmlItem.xmlType()) { case ZFXmlType::e_XmlElement: return this->onVisitXmlElement(data); case ZFXmlType::e_XmlAttribute: return this->onVisitXmlAttribute(data); case ZFXmlType::e_XmlText: return this->onVisitXmlText(data); case ZFXmlType::e_XmlComment: return this->onVisitXmlComment(data); case ZFXmlType::e_XmlDocument: return this->onVisitXmlDocument(data); case ZFXmlType::e_XmlDeclaration: return this->onVisitXmlDeclaration(data); case ZFXmlType::e_XmlDocType: return this->onVisitXmlDocType(data); case ZFXmlType::e_XmlPI: return this->onVisitXmlPI(data); default: return zffalse; } } private: zfbool onVisitXmlElement(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: if(data.depth > 0 || data.siblingIndex > 0) { this->add(flags.xmlToken.xmlNewLineToken); } this->add(flags.xmlGlobalLineBeginToken); if((data.depth > 0 && data.siblingIndex > 0) && flags.xmlElementAddNewLineAtHeadIfNotSingleLine && (_ZFP_ZFXmlOutputElementAttributeNeedNewLine(data.xmlItem, flags, data) || _ZFP_ZFXmlOutputElementChildNeedNewLine(data.xmlItem.xmlChildFirst(), flags, data))) { this->add(flags.xmlToken.xmlNewLineToken); this->add(flags.xmlGlobalLineBeginToken); } this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); if(_ZFP_ZFXmlOutputElementUseSingleTag(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlElementSingleTagLeft); } else { this->add(flags.xmlToken.xmlElementBeginTagLeft); } this->add(data.xmlItem.xmlName()); break; case ZFXmlVisitType::e_Exit: if(!data.xmlItem.xmlAttributeFirst().xmlIsNull() && _ZFP_ZFXmlOutputElementUseSingleTag(data.xmlItem, flags, data)) { this->add(" "); } if(_ZFP_ZFXmlOutputElementUseSingleTag(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlElementSingleTagRight); } else { this->add(flags.xmlToken.xmlElementBeginTagRight); } break; case ZFXmlVisitType::e_ExitChildren: if(!_ZFP_ZFXmlOutputElementUseSingleTag(data.xmlItem, flags, data)) { if(_ZFP_ZFXmlOutputElementChildNeedNewLine(data.xmlItem.xmlChildFirst(), flags, data) || _ZFP_ZFXmlOutputElementAttributeNeedNewLine(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlNewLineToken); this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); } this->add(flags.xmlToken.xmlElementEndTagLeft); this->add(data.xmlItem.xmlName()); this->add(flags.xmlToken.xmlElementEndTagRight); } break; default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlAttribute(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: { if(_ZFP_ZFXmlOutputAttributeNeedNewLine(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlNewLineToken); this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); } else if(data.depth > 0 || data.siblingIndex > 0) { this->add(" "); } this->add(data.xmlItem.xmlName()); this->add(flags.xmlToken.xmlAttributeEqualTag); if(flags.xmlAttributeUseSingleQuote) { this->add(flags.xmlToken.xmlAttributeSingleQuoteTagLeft); ZFXmlEscapeCharEncode(this->outputCallback, data.xmlItem.xmlValue()); this->add(flags.xmlToken.xmlAttributeSingleQuoteTagRight); } else { this->add(flags.xmlToken.xmlAttributeQuoteTagLeft); ZFXmlEscapeCharEncode(this->outputCallback, data.xmlItem.xmlValue()); this->add(flags.xmlToken.xmlAttributeQuoteTagRight); } } break; case ZFXmlVisitType::e_Exit: break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlText(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: if(_ZFP_ZFXmlOutputElementChildNeedNewLine(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlNewLineToken); this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); } if(data.xmlItem.xmlTextCDATA()) { this->add(flags.xmlToken.xmlTextCDATATagLeft); } this->addEncoded(data.xmlItem.xmlValue()); break; case ZFXmlVisitType::e_Exit: if(data.xmlItem.xmlTextCDATA()) { this->add(flags.xmlToken.xmlTextCDATATagRight); } if(_ZFP_ZFXmlOutputElementChildNeedNewLine(data.xmlItem, flags, data)) { this->add(flags.xmlToken.xmlNewLineToken); this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth - 1); } break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlComment(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: { if(data.depth > 0 || data.siblingIndex > 0) { this->add(flags.xmlToken.xmlNewLineToken); } this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); this->add(flags.xmlToken.xmlCommentTagLeft); this->add(data.xmlItem.xmlValue()); break; } case ZFXmlVisitType::e_Exit: this->add(flags.xmlToken.xmlCommentTagRight); break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlDocument(ZF_IN const ZFXmlVisitData &data) { return zftrue; } zfbool onVisitXmlDeclaration(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: if(data.depth > 0 || data.siblingIndex > 0) { this->add(flags.xmlToken.xmlNewLineToken); } this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); this->add(flags.xmlToken.xmlDeclarationTagLeft); break; case ZFXmlVisitType::e_Exit: { if(data.xmlItem.xmlAttributeFirst().xmlIsNull()) { this->add(" "); } this->add(flags.xmlToken.xmlDeclarationTagRight); } break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlDocType(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: if(data.depth > 0 || data.siblingIndex > 0) { this->add(flags.xmlToken.xmlNewLineToken); } this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); this->add(flags.xmlToken.xmlDocTypeTagLeft); this->add(" "); this->add(data.xmlItem.xmlValue()); break; case ZFXmlVisitType::e_Exit: this->add(flags.xmlToken.xmlDocTypeTagRight); break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } zfbool onVisitXmlPI(ZF_IN const ZFXmlVisitData &data) { switch(data.xmlVisitType) { case ZFXmlVisitType::e_Enter: if(data.depth > 0 || data.siblingIndex > 0) { this->add(flags.xmlToken.xmlNewLineToken); } this->add(flags.xmlGlobalLineBeginToken); this->addIndent(flags.xmlToken.xmlIndentToken, data.depth); this->add(flags.xmlToken.xmlPITagLeft); this->add(data.xmlItem.xmlName()); this->add(" "); this->add(data.xmlItem.xmlValue()); break; case ZFXmlVisitType::e_Exit: this->add(flags.xmlToken.xmlPITagRight); break; case ZFXmlVisitType::e_ExitChildren: default: zfCoreCriticalShouldNotGoHere(); break; } return zftrue; } private: inline void add(const zfchar *s) { if(s && *s) { this->outputCallback.execute(s); } } inline void addEncoded(const zfchar *s) { if(s && *s) { ZFXmlEscapeCharEncode(this->outputCallback, s); } } void addIndent(const zfchar *xmlIndentToken, zfindex indentLevel = 1) { if(xmlIndentToken && *xmlIndentToken) { for(zfindex i = 0; i < indentLevel; ++i) { this->outputCallback.execute(xmlIndentToken); } } } }; ZFMETHOD_FUNC_DEFINE_2(ZFXmlVisitCallback, ZFXmlVisitCallbackForOutput, ZFMP_IN_OPT(const ZFOutput &, outputCallback, ZFOutputDefault()), ZFMP_IN_OPT(const ZFXmlOutputFlags &, flags, ZFXmlOutputFlagsDefault())) { if(!outputCallback.callbackIsValid()) { return ZFCallbackNull(); } _ZFP_I_ZFXmlOutputOwner *owner = zfAlloc(_ZFP_I_ZFXmlOutputOwner); owner->outputCallback = outputCallback; owner->flags = flags; ZFXmlVisitCallback callback = ZFCallbackForMemberMethod( owner, ZFMethodAccess(_ZFP_I_ZFXmlOutputOwner, onVisit)); callback.callbackOwnerObjectRetain(); zfRelease(owner); return callback; } // ============================================================ zfclassLikePOD _ZFP_ZFXmlMemoryPoolString { private: void *_token; union { zfchar *_s; const zfchar *_sInPool; } _s; private: _ZFP_ZFXmlMemoryPoolString(ZF_IN const _ZFP_ZFXmlMemoryPoolString &ref); _ZFP_ZFXmlMemoryPoolString &operator = (ZF_IN const _ZFP_ZFXmlMemoryPoolString &ref); public: _ZFP_ZFXmlMemoryPoolString(void) : _token(zfnull) , _s() { } _ZFP_ZFXmlMemoryPoolString(ZF_IN const zfchar *s) : _token(zfnull) , _s() { _s._s = zfsCopy(s); } _ZFP_ZFXmlMemoryPoolString(ZF_IN const zfchar *s, ZF_IN void *token) : _token(token) , _s() { _s._sInPool = s; } ~_ZFP_ZFXmlMemoryPoolString(void) { if(_token) { ZFPROTOCOL_ACCESS(ZFXml)->xmlMemoryPoolRelease(_token, _s._sInPool); } else { zffree(_s._s); } } public: void value(ZF_IN const zfchar *value) { if(_token) { ZFPROTOCOL_ACCESS(ZFXml)->xmlMemoryPoolRelease(_token, _s._sInPool); _token = zfnull; _s._s = zfnull; } zfsChange(_s._s, value); } void value(ZF_IN const zfchar *value, ZF_IN void *token) { if(_token) { ZFPROTOCOL_ACCESS(ZFXml)->xmlMemoryPoolRelease(_token, _s._sInPool); _token = zfnull; _s._s = zfnull; } else { zffree(_s._s); } _token = token; _s._sInPool = value; } inline const zfchar *value(void) const { return _s._sInPool; } }; zfclassNotPOD _ZFP_ZFXmlItemPrivate { public: zfuint refCount; ZFXmlTypeEnum xmlType; _ZFP_ZFXmlItemPrivate *xmlParent; _ZFP_ZFXmlMemoryPoolString xmlName; _ZFP_ZFXmlMemoryPoolString xmlValue; _ZFP_ZFXmlItemPrivate *xmlAttributeFirst; _ZFP_ZFXmlItemPrivate *xmlAttributeLast; _ZFP_ZFXmlItemPrivate *xmlChildFirst; _ZFP_ZFXmlItemPrivate *xmlChildLast; // prev/next attribute or sibling depending on xmlType _ZFP_ZFXmlItemPrivate *xmlPrev; _ZFP_ZFXmlItemPrivate *xmlNext; zfbool xmlAttributeNeedSort; zfbool xmlTextCDATA; public: _ZFP_ZFXmlItemPrivate(void) : refCount(1) , xmlType(ZFXmlType::e_XmlNull) , xmlParent(zfnull) , xmlName() , xmlValue() , xmlAttributeFirst(zfnull) , xmlAttributeLast(zfnull) , xmlChildFirst(zfnull) , xmlChildLast(zfnull) , xmlPrev(zfnull) , xmlNext(zfnull) , xmlAttributeNeedSort(zftrue) , xmlTextCDATA(zffalse) { } ~_ZFP_ZFXmlItemPrivate(void) { this->xmlAttributeRemoveAll(); this->xmlChildRemoveAll(); } public: void xmlAttributeRemoveAll(void) { if(this->xmlAttributeFirst) { _ZFP_ZFXmlItemPrivate *xmlAttribute = this->xmlAttributeFirst; this->xmlAttributeFirst = zfnull; this->xmlAttributeLast = zfnull; while(xmlAttribute != zfnull) { _ZFP_ZFXmlItemPrivate *xmlAttributeTmp = xmlAttribute; xmlAttribute = xmlAttribute->xmlNext; xmlAttributeTmp->xmlParent = zfnull; xmlAttributeTmp->xmlPrev = zfnull; xmlAttributeTmp->xmlNext = zfnull; --(xmlAttributeTmp->refCount); if(xmlAttributeTmp->refCount == 0) { zfdelete(xmlAttributeTmp); } } } } void xmlChildRemoveAll(void) { if(this->xmlChildFirst) { _ZFP_ZFXmlItemPrivate *xmlChild = this->xmlChildFirst; this->xmlChildFirst = zfnull; this->xmlChildLast = zfnull; while(xmlChild != zfnull) { _ZFP_ZFXmlItemPrivate *xmlChildTmp = xmlChild; xmlChild = xmlChild->xmlNext; xmlChildTmp->xmlParent = zfnull; xmlChildTmp->xmlPrev = zfnull; xmlChildTmp->xmlNext = zfnull; --(xmlChildTmp->refCount); if(xmlChildTmp->refCount == 0) { zfdelete(xmlChildTmp); } } } } public: void xmlAttributeAttach(ZF_IN _ZFP_ZFXmlItemPrivate *addThis, ZF_IN _ZFP_ZFXmlItemPrivate *beforeThis) { this->xmlAttributeNeedSort = zftrue; ++(addThis->refCount); addThis->xmlParent = this; if(beforeThis == zfnull) { addThis->xmlPrev = this->xmlAttributeLast; if(this->xmlAttributeLast == zfnull) { this->xmlAttributeLast = addThis; } else { this->xmlAttributeLast->xmlNext = addThis; this->xmlAttributeLast = addThis; } if(this->xmlAttributeFirst == zfnull) { this->xmlAttributeFirst = addThis; } } else { if(beforeThis->xmlPrev == zfnull) { this->xmlAttributeFirst = addThis; } else { beforeThis->xmlPrev->xmlNext = addThis; } addThis->xmlPrev = beforeThis->xmlPrev; beforeThis->xmlPrev = addThis; addThis->xmlNext = beforeThis; } } void xmlAttributeDetach(ZF_IN _ZFP_ZFXmlItemPrivate *removeThis) { this->xmlAttributeNeedSort = zftrue; --(removeThis->refCount); removeThis->xmlParent = zfnull; if(this->xmlAttributeFirst == removeThis) { this->xmlAttributeFirst = removeThis->xmlNext; } if(this->xmlAttributeLast == removeThis) { this->xmlAttributeLast = removeThis->xmlPrev; } if(removeThis->xmlPrev != zfnull) { removeThis->xmlPrev->xmlNext = removeThis->xmlNext; } if(removeThis->xmlNext != zfnull) { removeThis->xmlNext->xmlPrev = removeThis->xmlPrev; } removeThis->xmlPrev = zfnull; removeThis->xmlNext = zfnull; if(removeThis->refCount == 0) { zfdelete(removeThis); } } void xmlChildAttach(ZF_IN _ZFP_ZFXmlItemPrivate *addThis, ZF_IN _ZFP_ZFXmlItemPrivate *beforeThis) { ++(addThis->refCount); addThis->xmlParent = this; if(beforeThis == zfnull) { addThis->xmlPrev = this->xmlChildLast; if(this->xmlChildLast == zfnull) { this->xmlChildLast = addThis; } else { this->xmlChildLast->xmlNext = addThis; this->xmlChildLast = addThis; } if(this->xmlChildFirst == zfnull) { this->xmlChildFirst = addThis; } } else { if(beforeThis->xmlPrev == zfnull) { this->xmlChildFirst = addThis; } else { beforeThis->xmlPrev->xmlNext = addThis; } addThis->xmlPrev = beforeThis->xmlPrev; beforeThis->xmlPrev = addThis; addThis->xmlNext = beforeThis; } } void xmlChildDetach(ZF_IN _ZFP_ZFXmlItemPrivate *removeThis) { --(removeThis->refCount); removeThis->xmlParent = zfnull; if(this->xmlChildFirst == removeThis) { this->xmlChildFirst = removeThis->xmlNext; } if(this->xmlChildLast == removeThis) { this->xmlChildLast = removeThis->xmlPrev; } if(removeThis->xmlPrev != zfnull) { removeThis->xmlPrev->xmlNext = removeThis->xmlNext; } if(removeThis->xmlNext != zfnull) { removeThis->xmlNext->xmlPrev = removeThis->xmlPrev; } removeThis->xmlPrev = zfnull; removeThis->xmlNext = zfnull; if(removeThis->refCount == 0) { zfdelete(removeThis); } } public: static ZFCompareResult _ZFP_ZFXmlAttributeSortComparer(ZF_IN _ZFP_ZFXmlItemPrivate * const &v0, ZF_IN _ZFP_ZFXmlItemPrivate * const &v1) { zfint cmpResult = zfscmp(v0->xmlName.value(), v1->xmlName.value()); if(cmpResult < 0) { return ZFCompareSmaller; } else if(cmpResult == 0) { return ZFCompareTheSame; } else { return ZFCompareGreater; } } void xmlAttributeSort(void) { if(this->xmlAttributeNeedSort) { this->xmlAttributeNeedSort = zffalse; if(this->xmlAttributeFirst != zfnull) { ZFCoreArrayPOD<_ZFP_ZFXmlItemPrivate *> tmp; _ZFP_ZFXmlItemPrivate *xmlAttribute = this->xmlAttributeFirst; while(xmlAttribute != zfnull) { tmp.add(xmlAttribute); xmlAttribute = xmlAttribute->xmlNext; } tmp.sort(_ZFP_ZFXmlAttributeSortComparer); this->xmlAttributeFirst = tmp[0]; this->xmlAttributeLast = tmp[tmp.count() - 1]; for(zfindex i = tmp.count() - 1; i != zfindexMax(); --i) { xmlAttribute = tmp[i]; if(i + 1 < tmp.count()) { xmlAttribute->xmlNext = tmp[i + 1]; } else { xmlAttribute->xmlNext = zfnull; } if(i > 0) { xmlAttribute->xmlPrev = tmp[i - 1]; } else { xmlAttribute->xmlPrev = zfnull; } } } } } void xmlAttributeSortRecursively(void) { this->xmlAttributeSort(); if(this->xmlType == ZFXmlType::e_XmlElement || this->xmlType == ZFXmlType::e_XmlDocument) { _ZFP_ZFXmlItemPrivate *xmlChild = this->xmlChildFirst; while(xmlChild != zfnull) { xmlChild->xmlAttributeSortRecursively(); xmlChild = xmlChild->xmlNext; } } } }; static void _ZFP_ZFXmlCopyNode(ZF_IN ZFXmlItem &to, ZF_IN const ZFXmlItem &from) { to.xmlName(from.xmlName()); to.xmlValue(from.xmlValue()); switch(from.xmlType()) { case ZFXmlType::e_XmlText: { to.xmlTextCDATA(from.xmlTextCDATA()); break; } case ZFXmlType::e_XmlElement: case ZFXmlType::e_XmlDeclaration: { ZFXmlItem fromAttribute = from.xmlAttributeFirst(); while(!fromAttribute.xmlIsNull()) { to.xmlAttributeAdd(fromAttribute.xmlClone()); fromAttribute = fromAttribute.xmlAttributeNext(); } break; } default: break; } } static void _ZFP_ZFXmlCopyTree(ZF_IN ZFXmlItem &to, ZF_IN const ZFXmlItem &from) { _ZFP_ZFXmlCopyNode(to, from); switch(from.xmlType()) { case ZFXmlType::e_XmlElement: { ZFXmlItem fromChild = from.xmlChildFirst(); while(!fromChild.xmlIsNull()) { to.xmlChildAdd(fromChild.xmlCloneTree()); fromChild = fromChild.xmlSiblingNext(); } break; } case ZFXmlType::e_XmlDocument: { ZFXmlItem fromChild = from.xmlChildFirst(); while(!fromChild.xmlIsNull()) { to.xmlChildAdd(fromChild.xmlCloneTree()); fromChild = fromChild.xmlSiblingNext(); } break; } default: break; } } #define _ZFP_ZFXmlAssertCanHaveAttribute(item) \ zfCoreAssert((item).xmlType() == ZFXmlType::e_XmlElement || (item).xmlType() == ZFXmlType::e_XmlDeclaration) #define _ZFP_ZFXmlAssertCanHaveChild(item) \ zfCoreAssert((item).xmlType() == ZFXmlType::e_XmlElement || (item).xmlType() == ZFXmlType::e_XmlDocument) #define _ZFP_ZFXmlAssertCanBeAttribute(item) \ zfCoreAssert((item).xmlType() == ZFXmlType::e_XmlAttribute) #define _ZFP_ZFXmlAssertCanBeChild(item) \ zfCoreAssert((item).xmlType() != ZFXmlType::e_XmlAttribute && (item).xmlType() != ZFXmlType::e_XmlNull && (item).xmlType() != ZFXmlType::e_XmlDocument) // ============================================================ // ZFXmlItem ZFXmlItem::ZFXmlItem(ZF_IN _ZFP_ZFXmlItemPrivate *ref) { if(ref) { d = ref; ++(d->refCount); } else { d = zfnew(_ZFP_ZFXmlItemPrivate); } } ZFXmlItem::ZFXmlItem(void) : d(zfnew(_ZFP_ZFXmlItemPrivate)) { } ZFXmlItem::ZFXmlItem(ZF_IN ZFXmlTypeEnum xmlType) : d(zfnew(_ZFP_ZFXmlItemPrivate)) { d->xmlType = xmlType; } ZFXmlItem::ZFXmlItem(ZF_IN const ZFXmlItem &ref) : d(ref.d) { ++(d->refCount); } ZFXmlItem::~ZFXmlItem(void) { --(d->refCount); if(d->refCount == 0) { zfdelete(d); } } ZFXmlItem &ZFXmlItem::operator = (ZF_IN const ZFXmlItem &ref) { _ZFP_ZFXmlItemPrivate *dTmp = d; d = ref.d; ++(ref.d->refCount); --(dTmp->refCount); if(dTmp->refCount == 0) { zfdelete(dTmp); } return *this; } zfbool ZFXmlItem::operator == (ZF_IN const ZFXmlItem &ref) const { return (d == ref.d || (d->xmlType == ZFXmlType::e_XmlNull && ref.d->xmlType == ZFXmlType::e_XmlNull)); } // ============================================================ void ZFXmlItem::objectInfoT(ZF_IN_OUT zfstring &ret) const { ret += ZFTOKEN_ZFObjectInfoLeft; ret += ZFXmlType::EnumNameForValue(this->xmlType()); if(this->xmlName() != zfnull) { ret += ", name: "; ret += this->xmlName(); } ret += ZFTOKEN_ZFObjectInfoRight; } zfindex ZFXmlItem::objectRetainCount(void) const { return d->refCount; } // ============================================================ ZFXmlTypeEnum ZFXmlItem::xmlType(void) const { return d->xmlType; } ZFXmlItem ZFXmlItem::xmlParent(void) const { return ZFXmlItem(d->xmlParent); } void ZFXmlItem::xmlName(ZF_IN const zfchar *name) { zfCoreAssert(!this->xmlIsNull()); d->xmlName.value(name); } const zfchar *ZFXmlItem::xmlName(void) const { return d->xmlName.value(); } void ZFXmlItem::xmlValue(ZF_IN const zfchar *value) { zfCoreAssert(!this->xmlIsNull()); d->xmlValue.value(value); } const zfchar *ZFXmlItem::xmlValue(void) const { return d->xmlValue.value(); } void ZFXmlItem::_ZFP_ZFXml_xmlMemoryPool_xmlName(ZF_IN const zfchar *xmlName, ZF_IN void *token) { d->xmlName.value(xmlName, token); } void ZFXmlItem::_ZFP_ZFXml_xmlMemoryPool_xmlValue(ZF_IN const zfchar *xmlValue, ZF_IN void *token) { d->xmlValue.value(xmlValue, token); } // ============================================================ void ZFXmlItem::xmlVisit(ZF_IN const ZFXmlVisitCallback &callback /* = ZFXmlVisitCallbackForOutput() */) const { if(!callback.callbackIsValid() || this->xmlType() == ZFXmlType::e_XmlNull) { return ; } ZFCoreArray<ZFXmlVisitData> datas; datas.add(ZFXmlVisitData(*this, ZFXmlVisitType::e_Enter, 0, 0)); while(datas.count() > 0) { ZFXmlVisitData data = datas.removeLastAndGet(); if(data.xmlVisitType == ZFXmlVisitType::e_Enter) { if(callback.execute(data)) { ZFXmlTypeEnum xmlType = data.xmlItem.xmlType(); if(xmlType == ZFXmlType::e_XmlElement || xmlType == ZFXmlType::e_XmlDocument) { if(data.xmlItem.xmlType() == ZFXmlType::e_XmlElement) { datas.add(ZFXmlVisitData(data.xmlItem, ZFXmlVisitType::e_ExitChildren, data.depth, data.siblingIndex)); } ZFXmlItem xmlChild = data.xmlItem.xmlChildLast(); if(!xmlChild.xmlIsNull()) { zfindex xmlChildDepth = ((data.xmlItem.xmlType() == ZFXmlType::e_XmlDocument) ? data.depth : data.depth + 1); zfindex startIndex = ((zfindex)datas.count()) - 1; do { datas.add(ZFXmlVisitData(xmlChild, ZFXmlVisitType::e_Enter, xmlChildDepth, 0)); xmlChild = xmlChild.xmlSiblingPrev(); } while(!xmlChild.xmlIsNull()); for(zfindex i = ((zfindex)datas.count()) - 1, xmlChildIndex = 0; i != startIndex; --i, ++xmlChildIndex) { datas[i].siblingIndex = xmlChildIndex; } } } datas.add(ZFXmlVisitData(data.xmlItem, ZFXmlVisitType::e_Exit, data.depth, data.siblingIndex)); if(xmlType == ZFXmlType::e_XmlElement || xmlType == ZFXmlType::e_XmlDeclaration) { ZFXmlItem xmlAttribute = data.xmlItem.xmlAttributeLast(); if(!xmlAttribute.xmlIsNull()) { zfindex xmlAttributeDepth = data.depth + 1; zfindex startIndex = ((zfindex)datas.count()) - 1; do { datas.add(ZFXmlVisitData(xmlAttribute, ZFXmlVisitType::e_Enter, xmlAttributeDepth, 0)); xmlAttribute = xmlAttribute.xmlAttributePrev(); } while(!xmlAttribute.xmlIsNull()); for(zfindex i = ((zfindex)datas.count()) - 1, xmlChildIndex = 0; i != startIndex; --i, ++xmlChildIndex) { datas[i].siblingIndex = xmlChildIndex; } } } } } else { if(!callback.execute(data)) { for(zfindex i = ((zfindex)datas.count()) - 1; i != zfindexMax(); --i) { if(datas[i].depth == data.depth) { datas.remove(i); } } } } } } // ============================================================ ZFXmlItem ZFXmlItem::xmlClone(void) const { ZFXmlItem ret(this->xmlType()); if(this->xmlType() != ZFXmlType::e_XmlNull) { _ZFP_ZFXmlCopyNode(ret, *this); } return ret; } ZFXmlItem ZFXmlItem::xmlCloneTree(void) const { ZFXmlItem ret(this->xmlType()); if(this->xmlType() != ZFXmlType::e_XmlNull) { _ZFP_ZFXmlCopyTree(ret, *this); } return ret; } // ============================================================ void ZFXmlItem::xmlAttributeAdd(ZF_IN const ZFXmlItem &addThis, ZF_IN_OPT const ZFXmlItem *beforeThis /* = zfnull */) { _ZFP_ZFXmlAssertCanHaveAttribute(*this); _ZFP_ZFXmlAssertCanBeAttribute(addThis); zfCoreAssertWithMessage(addThis.d->xmlParent == zfnull, "adding a attribute that already has parent, remove it first"); if(beforeThis != zfnull && beforeThis->d->xmlParent == d && beforeThis->xmlType() == ZFXmlType::e_XmlAttribute) { d->xmlAttributeAttach(addThis.d, beforeThis->d); } else { d->xmlAttributeAttach(addThis.d, zfnull); } } void ZFXmlItem::xmlAttributeAdd(ZF_IN const zfchar *key, ZF_IN const zfchar *value, ZF_IN_OPT const ZFXmlItem *beforeThis /* = zfnull */) { if(!zfsIsEmpty(key)) { ZFXmlItem xmlAttribute(ZFXmlType::e_XmlAttribute); xmlAttribute.xmlName(key); xmlAttribute.xmlValue(value); this->xmlAttributeAdd(xmlAttribute, beforeThis); } } void ZFXmlItem::xmlAttributeRemove(ZF_IN const ZFXmlItem &removeThis) { if(removeThis.d->xmlParent != d || removeThis.xmlType() != ZFXmlType::e_XmlAttribute) { return ; } d->xmlAttributeDetach(removeThis.d); } void ZFXmlItem::xmlAttributeRemove(ZF_IN const zfchar *name /* = zfnull */) { if(d->xmlAttributeFirst == zfnull || zfsIsEmpty(name)) { return ; } for(_ZFP_ZFXmlItemPrivate *xmlAttribute = d->xmlAttributeFirst; xmlAttribute != zfnull; xmlAttribute = xmlAttribute->xmlNext) { if(zfscmpTheSame(xmlAttribute->xmlName.value(), name)) { d->xmlAttributeDetach(xmlAttribute); break; } } } void ZFXmlItem::xmlAttributeRemoveAll(void) { d->xmlAttributeRemoveAll(); } ZFXmlItem ZFXmlItem::xmlAttribute(ZF_IN const zfchar *name) const { if(d->xmlAttributeFirst == zfnull || zfsIsEmpty(name)) { return ZFXmlItem(); } for(_ZFP_ZFXmlItemPrivate *xmlAttribute = d->xmlAttributeFirst; xmlAttribute != zfnull; xmlAttribute = xmlAttribute->xmlNext) { if(zfscmpTheSame(xmlAttribute->xmlName.value(), name)) { return ZFXmlItem(xmlAttribute); } } return ZFXmlItem(); } const zfchar *ZFXmlItem::xmlAttributeValue(ZF_IN const zfchar *name) const { if(d->xmlAttributeFirst == zfnull || zfsIsEmpty(name)) { return zfnull; } for(_ZFP_ZFXmlItemPrivate *xmlAttribute = d->xmlAttributeFirst; xmlAttribute != zfnull; xmlAttribute = xmlAttribute->xmlNext) { if(zfscmpTheSame(xmlAttribute->xmlName.value(), name)) { return xmlAttribute->xmlValue.value(); } } return zfnull; } ZFXmlItem ZFXmlItem::xmlAttributeFirst(void) const { return ZFXmlItem(d->xmlAttributeFirst); } ZFXmlItem ZFXmlItem::xmlAttributeLast(void) const { return ZFXmlItem(d->xmlAttributeLast); } ZFXmlItem ZFXmlItem::xmlAttributeNext(void) const { return ZFXmlItem((d->xmlType == ZFXmlType::e_XmlAttribute) ? d->xmlNext : zfnull); } ZFXmlItem ZFXmlItem::xmlAttributePrev(void) const { return ZFXmlItem((d->xmlType == ZFXmlType::e_XmlAttribute) ? d->xmlPrev : zfnull); } // ============================================================ void ZFXmlItem::xmlAttributeSort(void) { d->xmlAttributeSort(); } void ZFXmlItem::xmlAttributeSortRecursively(void) { d->xmlAttributeSortRecursively(); } // ============================================================ void ZFXmlItem::xmlChildAdd(ZF_IN const ZFXmlItem &addThis, ZF_IN_OPT const ZFXmlItem *beforeThis /* = zfnull */) { _ZFP_ZFXmlAssertCanHaveChild(*this); _ZFP_ZFXmlAssertCanBeChild(addThis); zfCoreAssertWithMessage(addThis.d->xmlParent == zfnull, "adding a child that already has parent, remove it first"); if(beforeThis != zfnull && beforeThis->d->xmlParent == d && beforeThis->xmlType() != ZFXmlType::e_XmlAttribute) { d->xmlChildAttach(addThis.d, beforeThis->d); } else { d->xmlChildAttach(addThis.d, zfnull); } } void ZFXmlItem::xmlChildRemove(ZF_IN const ZFXmlItem &removeThis) { if(removeThis.d->xmlParent != d || removeThis.xmlType() == ZFXmlType::e_XmlAttribute) { return ; } d->xmlChildDetach(removeThis.d); } void ZFXmlItem::xmlChildRemoveAll(void) { d->xmlChildRemoveAll(); } ZFXmlItem ZFXmlItem::xmlChildFirst(ZF_IN_OPT const zfchar *name /* = zfnull */, ZF_IN_OPT const ZFXmlItem *afterThis /* = zfnull */) const { _ZFP_ZFXmlItemPrivate *xmlChild = (afterThis != zfnull && afterThis->d->xmlParent == d && afterThis->xmlType() != ZFXmlType::e_XmlAttribute) ? afterThis->d->xmlNext : d->xmlChildFirst; if(zfsIsEmpty(name)) { return ZFXmlItem(xmlChild); } else { while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name)) { xmlChild = xmlChild->xmlNext; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlChildLast(ZF_IN_OPT const zfchar *name /* = zfnull */, ZF_IN_OPT const ZFXmlItem *beforeThis /* = zfnull */) const { _ZFP_ZFXmlItemPrivate *xmlChild = (beforeThis != zfnull && beforeThis->d->xmlParent == d && beforeThis->xmlType() != ZFXmlType::e_XmlAttribute) ? beforeThis->d->xmlPrev : d->xmlChildLast; if(zfsIsEmpty(name)) { return ZFXmlItem(xmlChild); } else { while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name)) { xmlChild = xmlChild->xmlPrev; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlChildElementFirst(ZF_IN_OPT const zfchar *name /* = zfnull */, ZF_IN_OPT const ZFXmlItem *afterThis /* = zfnull */) const { _ZFP_ZFXmlItemPrivate *xmlChild = (afterThis != zfnull && afterThis->d->xmlParent == d && afterThis->xmlType() != ZFXmlType::e_XmlAttribute) ? afterThis->d->xmlNext : d->xmlChildFirst; if(zfsIsEmpty(name)) { return ZFXmlItem(xmlChild); } else { while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name) && xmlChild->xmlType != ZFXmlType::e_XmlElement) { xmlChild = xmlChild->xmlNext; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlChildElementLast(ZF_IN_OPT const zfchar *name /* = zfnull */, ZF_IN_OPT const ZFXmlItem *beforeThis /* = zfnull */) const { _ZFP_ZFXmlItemPrivate *xmlChild = (beforeThis != zfnull && beforeThis->d->xmlParent == d && beforeThis->xmlType() != ZFXmlType::e_XmlAttribute) ? beforeThis->d->xmlPrev : d->xmlChildLast; if(zfsIsEmpty(name)) { return ZFXmlItem(xmlChild); } else { while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name) && xmlChild->xmlType != ZFXmlType::e_XmlElement) { xmlChild = xmlChild->xmlPrev; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlSiblingNext(ZF_IN const zfchar *name /* = zfnull */) const { if(d->xmlType == ZFXmlType::e_XmlAttribute) { return ZFXmlItem(); } if(zfsIsEmpty(name)) { return ZFXmlItem(d->xmlNext); } else { _ZFP_ZFXmlItemPrivate *xmlChild = d->xmlNext; while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name)) { xmlChild = xmlChild->xmlNext; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlSiblingPrev(ZF_IN const zfchar *name /* = zfnull */) const { if(d->xmlType == ZFXmlType::e_XmlAttribute) { return ZFXmlItem(); } if(zfsIsEmpty(name)) { return ZFXmlItem(d->xmlPrev); } else { _ZFP_ZFXmlItemPrivate *xmlChild = d->xmlPrev; while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name)) { xmlChild = xmlChild->xmlPrev; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlSiblingElementNext(ZF_IN const zfchar *name /* = zfnull */) const { if(d->xmlType == ZFXmlType::e_XmlAttribute) { return ZFXmlItem(); } if(zfsIsEmpty(name)) { return ZFXmlItem(d->xmlNext); } else { _ZFP_ZFXmlItemPrivate *xmlChild = d->xmlNext; while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name) && xmlChild->xmlType != ZFXmlType::e_XmlElement) { xmlChild = xmlChild->xmlNext; } return ZFXmlItem(xmlChild); } } ZFXmlItem ZFXmlItem::xmlSiblingElementPrev(ZF_IN const zfchar *name /* = zfnull */) const { if(d->xmlType == ZFXmlType::e_XmlAttribute) { return ZFXmlItem(); } if(zfsIsEmpty(name)) { return ZFXmlItem(d->xmlPrev); } else { _ZFP_ZFXmlItemPrivate *xmlChild = d->xmlPrev; while(xmlChild != zfnull && !zfscmpTheSame(xmlChild->xmlName.value(), name) && xmlChild->xmlType != ZFXmlType::e_XmlElement) { xmlChild = xmlChild->xmlPrev; } return ZFXmlItem(xmlChild); } } // ============================================================ void ZFXmlItem::xmlTextCDATA(ZF_IN zfbool xmlTextCDATA) { zfCoreAssert(this->xmlType() == ZFXmlType::e_XmlText); d->xmlTextCDATA = xmlTextCDATA; } zfbool ZFXmlItem::xmlTextCDATA(void) const { return d->xmlTextCDATA; } // ============================================================ ZFTYPEID_DEFINE_BY_STRING_CONVERTER(ZFXmlItem, ZFXmlItem, { v = ZFPROTOCOL_ACCESS(ZFXml)->xmlParse(src, srcLen); return !v.xmlIsNull(); }, { return ZFXmlItemToString(s, v, ZFXmlOutputFlagsTrim()); }) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, objectInfoT, ZFMP_IN_OUT(zfstring &, ret)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, zfstring, objectInfo) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, zfindex, objectRetainCount) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlTypeEnum, xmlType) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, zfbool, xmlIsNull) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlParent) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlName, ZFMP_IN(const zfchar *, name)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, const zfchar *, xmlName) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlValue, ZFMP_IN(const zfchar *, value)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, const zfchar *, xmlValue) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlVisit, ZFMP_IN(const ZFXmlVisitCallback &, callback)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlClone) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlCloneTree) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, void, xmlAttributeAdd, ZFMP_IN(const ZFXmlItem &, addThis), ZFMP_IN_OPT(const ZFXmlItem *, beforeThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_3(v_ZFXmlItem, void, xmlAttributeAdd, ZFMP_IN(const zfchar *, key), ZFMP_IN(const zfchar *, value), ZFMP_IN_OPT(const ZFXmlItem *, beforeThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlAttributeRemove, ZFMP_IN(const ZFXmlItem &, removeThis)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlAttributeRemove, ZFMP_IN(const zfchar *, name)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, void, xmlAttributeRemoveAll) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, ZFXmlItem, xmlAttribute, ZFMP_IN(const zfchar *, name)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, const zfchar *, xmlAttributeValue, ZFMP_IN(const zfchar *, name)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlAttributeFirst) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlAttributeLast) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlAttributeNext) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, ZFXmlItem, xmlAttributePrev) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, void, xmlAttributeSort) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, void, xmlAttributeSortRecursively) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, void, xmlChildAdd, ZFMP_IN(const ZFXmlItem &, addThis), ZFMP_IN_OPT(const ZFXmlItem *, beforeThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlChildRemove, ZFMP_IN(const ZFXmlItem &, removeThis)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, void, xmlChildRemoveAll) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, ZFXmlItem, xmlChildFirst, ZFMP_IN_OPT(const zfchar *, name, zfnull), ZFMP_IN_OPT(const ZFXmlItem *, afterThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, ZFXmlItem, xmlChildLast, ZFMP_IN_OPT(const zfchar *, name, zfnull), ZFMP_IN_OPT(const ZFXmlItem *, beforeThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, ZFXmlItem, xmlChildElementFirst, ZFMP_IN_OPT(const zfchar *, name, zfnull), ZFMP_IN_OPT(const ZFXmlItem *, afterThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_2(v_ZFXmlItem, ZFXmlItem, xmlChildElementLast, ZFMP_IN_OPT(const zfchar *, name, zfnull), ZFMP_IN_OPT(const ZFXmlItem *, beforeThis, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, ZFXmlItem, xmlSiblingNext, ZFMP_IN_OPT(const zfchar *, name, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, ZFXmlItem, xmlSiblingPrev, ZFMP_IN_OPT(const zfchar *, name, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, ZFXmlItem, xmlSiblingElementNext, ZFMP_IN_OPT(const zfchar *, name, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, ZFXmlItem, xmlSiblingElementPrev, ZFMP_IN_OPT(const zfchar *, name, zfnull)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_1(v_ZFXmlItem, void, xmlTextCDATA, ZFMP_IN(zfbool, xmlTextCDATA)) ZFMETHOD_USER_REGISTER_FOR_WRAPPER_FUNC_0(v_ZFXmlItem, zfbool, xmlTextCDATA) // ============================================================ ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlElement) {return ZFXmlItem(ZFXmlType::e_XmlElement);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlAttribute) {return ZFXmlItem(ZFXmlType::e_XmlAttribute);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlText) {return ZFXmlItem(ZFXmlType::e_XmlText);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlComment) {return ZFXmlItem(ZFXmlType::e_XmlComment);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlDocument) {return ZFXmlItem(ZFXmlType::e_XmlDocument);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlDeclaration) {return ZFXmlItem(ZFXmlType::e_XmlDeclaration);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlDocType) {return ZFXmlItem(ZFXmlType::e_XmlDocType);} ZFMETHOD_FUNC_DEFINE_0(ZFXmlItem, ZFXmlPI) {return ZFXmlItem(ZFXmlType::e_XmlPI);} // ============================================================ ZFMETHOD_FUNC_DEFINE_1(ZFXmlItem, ZFXmlItemFromInput, ZFMP_IN(const ZFInput &, callback)) { return ZFPROTOCOL_ACCESS(ZFXml)->xmlParse(callback); } ZFMETHOD_FUNC_DEFINE_2(ZFXmlItem, ZFXmlItemFromString, ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, size, zfindexMax())) { return ZFPROTOCOL_ACCESS(ZFXml)->xmlParse(src, size); } ZFMETHOD_FUNC_DEFINE_1(ZFXmlItem, ZFXmlParseFirstElement, ZFMP_IN(const ZFInput &, callback)) { return ZFXmlItem(ZFXmlItemFromInput(callback).xmlChildElementFirst()); } ZFMETHOD_FUNC_DEFINE_2(ZFXmlItem, ZFXmlParseFirstElement, ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, size, zfindexMax())) { return ZFXmlItem(ZFXmlItemFromString(src, size).xmlChildElementFirst()); } ZFMETHOD_FUNC_DEFINE_3(zfbool, ZFXmlItemToOutput, ZFMP_IN_OUT(const ZFOutput &, output), ZFMP_IN(const ZFXmlItem &, xmlItem), ZFMP_IN_OPT(const ZFXmlOutputFlags &, outputFlags, ZFXmlOutputFlagsDefault())) { if(!output.callbackIsValid() || xmlItem.xmlIsNull()) { return zffalse; } xmlItem.xmlVisit(ZFXmlVisitCallbackForOutput(output, outputFlags)); return zftrue; } ZFMETHOD_FUNC_DEFINE_3(zfbool, ZFXmlItemToString, ZFMP_IN_OUT(zfstring &, ret), ZFMP_IN(const ZFXmlItem &, xmlItem), ZFMP_IN(const ZFXmlOutputFlags &, outputFlags)) { return ZFXmlItemToOutput(ZFOutputForString(ret), xmlItem, outputFlags); } ZFMETHOD_FUNC_DEFINE_2(zfstring, ZFXmlItemToString, ZFMP_IN(const ZFXmlItem &, xmlItem), ZFMP_IN(const ZFXmlOutputFlags &, outputFlags)) { zfstring ret; ZFXmlItemToString(ret, xmlItem, outputFlags); return ret; } // ============================================================ // escape chars ZFMETHOD_FUNC_DEFINE_3(void, ZFXmlEscapeCharEncode, ZFMP_OUT(zfstring &, dst), ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, count, zfindexMax())) { ZFXmlEscapeCharEncode(ZFOutputForString(dst), src, count); } ZFMETHOD_FUNC_DEFINE_3(void, ZFXmlEscapeCharEncode, ZFMP_OUT(const ZFOutput &, dst), ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, count, zfindexMax())) { ZFPROTOCOL_ACCESS(ZFXml)->xmlEscapeCharEncode(dst, src, count); } ZFMETHOD_FUNC_DEFINE_3(void, ZFXmlEscapeCharDecode, ZFMP_OUT(zfstring &, dst), ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, count, zfindexMax())) { ZFXmlEscapeCharDecode(ZFOutputForString(dst), src, count); } ZFMETHOD_FUNC_DEFINE_3(void, ZFXmlEscapeCharDecode, ZFMP_OUT(const ZFOutput &, dst), ZFMP_IN(const zfchar *, src), ZFMP_IN_OPT(zfindex, count, zfindexMax())) { ZFPROTOCOL_ACCESS(ZFXml)->xmlEscapeCharDecode(dst, src, count); } ZF_NAMESPACE_GLOBAL_END
[ "z@zsaber.com" ]
z@zsaber.com
c7bee58df2ee18cd415951d980fdaa4bd080b8aa
571c39f625479a10f2543ed033133705ef6c0d56
/src/ThirdParty/xerces/mac/xerces-c-3.1.1/src/xercesc/util/MutexManagers/PosixMutexMgr.cpp
5e019c191b50287e865e164678f468bcb21d32b7
[ "Apache-2.0" ]
permissive
k8w/pixi-animate-extension
4578879da61e7f8ed8aec373903defdafdbaf816
e9a15d42db1d0a2a1e228f58bf2aa50346ca3ef4
refs/heads/master
2021-05-06T11:16:31.477555
2018-01-24T04:25:53
2018-01-24T04:25:53
114,258,145
1
0
null
2017-12-14T14:10:19
2017-12-14T14:10:18
null
UTF-8
C++
false
false
2,899
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: PosixMutexMgr.cpp 471747 2006-11-06 14:31:56Z amassari $ */ // on some platforms, THREAD_MUTEX_RECURSIVE is defined only if _GNU_SOURCE is defined #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <pthread.h> #include <xercesc/util/MutexManagers/PosixMutexMgr.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/RuntimeException.hpp> #include <xercesc/util/PanicHandler.hpp> XERCES_CPP_NAMESPACE_BEGIN // Wrap up the mutex with XMemory class PosixMutexWrap : public XMemory { public: pthread_mutex_t m; }; PosixMutexMgr::PosixMutexMgr() { } PosixMutexMgr::~PosixMutexMgr() { } XMLMutexHandle PosixMutexMgr::create(MemoryManager* const manager) { PosixMutexWrap* mutex = new (manager) PosixMutexWrap; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); if (pthread_mutex_init(&mutex->m, &attr)) XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr); pthread_mutexattr_destroy(&attr); return (void*)(mutex); } void PosixMutexMgr::destroy(XMLMutexHandle mtx, MemoryManager* const manager) { PosixMutexWrap* mutex = (PosixMutexWrap*)(mtx); if (mutex != NULL) { if (pthread_mutex_destroy(&mutex->m)) { ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::Mutex_CouldNotDestroy, manager); } delete mutex; } } void PosixMutexMgr::lock(XMLMutexHandle mtx) { PosixMutexWrap* mutex = (PosixMutexWrap*)(mtx); if (mutex != NULL) { if (pthread_mutex_lock(&mutex->m)) XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr); } } void PosixMutexMgr::unlock(XMLMutexHandle mtx) { PosixMutexWrap* mutex = (PosixMutexWrap*)(mtx); if (mutex != NULL) { if (pthread_mutex_unlock(&mutex->m)) XMLPlatformUtils::panic(PanicHandler::Panic_MutexErr); } } XERCES_CPP_NAMESPACE_END
[ "mbittarelli@Matts-MacBook-Pro.local" ]
mbittarelli@Matts-MacBook-Pro.local
957080ebeb5d5807f711e042ae45e766844c2226
8b8e0463cbaca1b1a4142731142b5ede1134ffef
/Sources/ExtLibs/imgui/imgui.cpp
9e6899893b23a1393467e81b80b63ea4ee184bf7
[]
no_license
PubFork/NumeaEngine
610c48dc5053b7de4c2d9af279a1f667ac9fedee
9cf32bf82ba3dc9fb19e539d346126442ff22cda
refs/heads/master
2020-12-04T01:29:27.951874
2018-08-30T04:28:27
2018-08-30T04:28:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
435,165
cpp
// dear imgui, v1.50 WIP // (main code and documentation) // See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // This library is free but I need your support to sustain development and maintenance. // If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui /* Index - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - How can I help? - How do I update to a newer version of ImGui? - What is ImTextureID and how do I display an image? - I integrated ImGui in my engine and the text or lines are blurry.. - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - ISSUES & TODO-LIST - CODE MISSION STATEMENT ================= - easy to use to create code-driven and data-driven tools - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools - easy to hack and improve - minimize screen real-estate usage - minimize setup and maintenance - minimize state storage on user side - portable, minimize dependencies, run on target (consoles, phones, etc.) - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - doesn't look fancy, doesn't animate - limited layout features, intricate layouts are typically crafted in code - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction. END-USER GUIDE ============== - double-click title bar to collapse window - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() - click and drag on lower right corner to resize window - click and drag on any empty space to move window - double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - use mouse wheel to scroll - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) - CTRL+Click on a slider or drag box to input value as text - text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump - CTRL+Shift+Left/Right to select words - CTRL+A our Double-Click to select all - CTRL+X,CTRL+C,CTRL+V to use OS clipboard - CTRL+Z,CTRL+Y to undo/redo - ESCAPE to revert text to its original value - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) PROGRAMMER GUIDE ================ - read the FAQ below this section! - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest. you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). - getting started: - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. - every frame: 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' 2/ call ImGui::NewFrame() as early as you can! 3/ use any ImGui function you want between NewFrame() and Render() 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) - all rendering information are stored into command-lists until ImGui::Render() is called. - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. - refer to the examples applications in the examples/ folder for instruction on how to setup your code. - a typical application skeleton may be: // Application init ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; io.IniFilename = "imgui.ini"; io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. // TODO: Fill others settings of the io structure // Load texture atlas // There is a default font so you don't need to care about choosing a font yet unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' // Application main loop while (true) { // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) // TODO: fill all fields of IO structure and call NewFrame ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = 1.0f/60.0f; io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; io.MouseDown[1] = mouse_button_1; io.KeysDown[i] = ... // 2) call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); // 3) most of your application code here MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any ImGui functions // 4) render & swap video buffers ImGui::Render(); SwapBuffers(); } - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. Also read releases logs https://github.com/ocornut/imgui/releases for more details. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. this necessary change will break your rendering function! the fix should be very easy. sorry for that :( - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) became: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). argument 'cmd_lists' -> 'draw_data->CmdLists' argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' ImDrawList 'commands' -> 'CmdBuffer' ImDrawList 'vtx_buffer' -> 'VtxBuffer' ImDrawList n/a -> 'IdxBuffer' (new) ImDrawCmd 'vtx_count' -> 'ElemCount' ImDrawCmd 'clip_rect' -> 'ClipRect' ImDrawCmd 'user_callback' -> 'UserCallback' ImDrawCmd 'texture_id' -> 'TextureId' - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. this sequence: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); // <Copy to GPU> became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // <Copy to GPU> io.Fonts->TexID = (your_texture_identifier); you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. it is now recommended that you sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: How can I help? A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. Q: How do I update to a newer version of ImGui? A: Overwrite the following files: imgui.cpp imgui.h imgui_demo.cpp imgui_draw.cpp imgui_internal.h stb_rect_pack.h stb_textedit.h stb_truetype.h Don't overwrite imconfig.h if you have made modification to your copy. Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! Q: What is ImTextureID and how do I display an image? A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. It is your responsibility to get textures uploaded to your GPU. Q: I integrated ImGui in my engine and the text or lines are blurry.. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) A: Yes. A primer on the use of labels/IDs in ImGui.. - Elements that are not clickable, such as Text() items don't need an ID. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer. Button("OK"); // Label = "OK", ID = hash of "OK" Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows or in two different locations of a tree. - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Both buttons will be treated as the same. Fear not! this is easy to solve and there are many ways to solve it! - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. use "##" to pass a complement to the ID that won't be visible to the end-user: Button("Play"); // Label = "Play", ID = hash of "Play" Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) - If you want to completely hide the label, but still need an ID: Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) Use "###" to pass a label that isn't part of ID: Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) sprintf(buf, "My game (%f FPS)###MyGame"); Begin(buf); // Variable label, ID = hash of "MyGame" - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! for (int i = 0; i < 100; i++) { PushID(i); Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) PopID(); } - More example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); Button("Click"); // Label = "Click", ID = hash of "node" + "Click" PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" PopID(); PopID(); - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) { Button("Click"); // Label = "Click", ID = hash of "node" + "Click" TreePop(); } - When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine. When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.) Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) A: Use the font atlas to load the TTF file you want: ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I easily use icons in my application? A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions. Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) ImGuiIO& io = ImGui::GetIO(); ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime // Options ImFontConfig config; config.OversampleH = 3; config.OversampleV = 1; config.GlyphExtraSpacing.x = 1.0f; io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can call Render() multiple times (e.g for VR renders). - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! ISSUES & TODO-LIST ================== Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github) - doc: add a proper documentation+regression testing system (#435) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690) - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. - window: allow resizing of child windows (possibly given min/max for each axis?) - window: background options for child windows, border option (disable rounding) - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) - window: resizing from any sides? + mouse cursor directives for app. !- window: begin with *p_open == false should return false. - window: get size/pos helpers given names (see discussion in #249) - window: a collapsed window can be stuck behind the main menu bar? - window: when window is small, prioritize resize button over close button. - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). !- scrolling: allow immediately effective change of scroll if we haven't appended items yet - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. - widgets: clean up widgets internal toward exposing everything. - widgets: add disabled and read-only modes (#211) - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. !- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) - input text: expose CursorPos in char filter event (#816) - input text: flag to disable live update of the user buffer (also applies to float/int text input) - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) - input text multi-line: line numbers? status bar? (follow up on #200) - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. - button: provide a button that looks framed. - text: proper alignment options - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - layout: horizontal layout helper (#97) - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - layout: BeginGroup() needs a border option. - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) - columns: add a conditional parameter to SetColumnOffset() (#513, #125) - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) - columns: user specify columns size (#513, #125) - columns: flag to add horizontal separator above/below? - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) - combo: sparse combo boxes (via function call?) / iterators - combo: contents should extends to fit label if combo widget is small - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) - listbox: multiple selection - listbox: user may want to initial scroll to focus on the one selected value? - listbox: keyboard navigation. - listbox: scrolling should track modified selection. !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse - menus: local shortcuts, global shortcuts (#456, #126) - menus: icons - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely - statusbar: add a per-window status bar helper similar to what menubar does. - tabs (#261, #351) - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) !- color: the color helpers/typing is a mess and needs sorting out. - color: add a better color picker (#346) - node/graph editor (#306) - pie menus patterns (#434) - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider & drag: int data passing through a float - drag float: up/down axis - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) - tree node / optimization: avoid formatting when clipped. - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - settings: write more decent code to allow saving/loading new fields - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file - style: add window shadows. - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. - style: color-box not always square? - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). - style: global scale setting. - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle - text: simple markup language for color change? - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) - font: fix AddRemapChar() to work before font has been built. - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wildcards (with implicit leading/trailing *), regexps - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) !- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing - keyboard: full keyboard navigation and focus. (#323) - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). - input: support track pad style scrolling & slider edit. - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) - style editor: color child window height expressed in multiple of line height. - remote: make a system like RemoteImGui first-class citizen/project (#75) - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. - examples: directx9: save/restore device state more thoroughly. - examples: window minimize, maximize (#583) - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) - optimization: use another hash function than crc32, e.g. FNV1a - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays - optimization: better clipping for multi-component widgets */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #define IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_PLACEMENT_NEW #include "imgui_internal.h" #include <ctype.h> // toupper, isprint #include <stdlib.h> // NULL, malloc, free, qsort, atoi #include <stdio.h> // vsnprintf, sscanf, printf #include <limits.h> // INT_MIN, INT_MAX #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang warnings with -Weverything #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); static void PushMultiItemsWidths(int components, float w_full = 0.0f); static float GetDraggedColumnOffset(int column_index); static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); static ImFont* GetDefaultFont(); static void SetCurrentFont(ImFont* font); static void SetCurrentWindow(ImGuiWindow* window); static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static inline bool IsWindowContentHoverable(ImGuiWindow* window); static void ClearSetNextWindowData(); static void CheckStacksSize(ImGuiWindow* window, bool write); static void Scrollbar(ImGuiWindow* window, bool horizontal); static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list); static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window); static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window); static ImGuiIniData* FindWindowSettings(const char* name); static ImGuiIniData* AddWindowSettings(const char* name); static void LoadIniSettingsFromDisk(const char* ini_filename); static void SaveIniSettingsToDisk(const char* ini_filename); static void MarkIniSettingsDirty(); static void PushColumnClipRect(int column_index = -1); static ImRect GetVisibleRect(); static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); static void CloseInactivePopups(); static void ClosePopupToLevel(int remaining); static void ClosePopup(ImGuiID id); static bool IsPopupOpen(ImGuiID id); static ImGuiWindow* GetFrontMostModalRootWindow(); static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- static const char* GetClipboardTextFn_DefaultImpl(void* user_data); static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); //----------------------------------------------------------------------------- // Context //----------------------------------------------------------------------------- // Default font atlas storage . // New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. static ImFontAtlas GImDefaultFontAtlas; // Default context storage + current context pointer. // Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() // ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by: // - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) // - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 #ifndef GImGui static ImGuiContext GImDefaultContext; ImGuiContext* GImGui = &GImDefaultContext; #endif //----------------------------------------------------------------------------- // User facing structures //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowMinSize = ImVec2(32,32); // Minimum window size WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f/60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; Fonts = &GImDefaultFontAtlas; FontGlobalScale = 1.0f; FontDefault = NULL; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; MouseDragThreshold = 6.0f; for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; for (int i = 0; i < ImGuiKey_COUNT; i++) KeyMap[i] = -1; KeyRepeatDelay = 0.250f; KeyRepeatRate = 0.050f; UserData = NULL; // User functions RenderDrawListsFn = NULL; MemAllocFn = malloc; MemFreeFn = free; GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ClipboardUserData = NULL; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; // Set OS X style defaults based on __APPLE__ compile time flag #ifdef __APPLE__ OSXBehaviors = true; #endif } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { const int n = ImStrlenW(InputCharacters); if (n + 1 < IM_ARRAYSIZE(InputCharacters)) { InputCharacters[n] = c; InputCharacters[n+1] = '\0'; } } void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); ImWchar wchars[wchars_buf_len]; ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) AddInputCharacter(wchars[i]); } //----------------------------------------------------------------------------- // HELPERS //----------------------------------------------------------------------------- #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else #define IM_NEWLINE "\n" #endif bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) { bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; return ((b1 == b2) && (b2 == b3)); } int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } void ImStrncpy(char* dst, const char* src, int count) { if (count < 1) return; strncpy(dst, src, (size_t)count); dst[count-1] = 0; } char* ImStrdup(const char *str) { size_t len = strlen(str) + 1; void* buff = ImGui::MemAlloc(len); return (char*)memcpy(buff, (const void*)str, len); } int ImStrlenW(const ImWchar* str) { int n = 0; while (*str++) n++; return n; } const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line { while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; } const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } // MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. int ImFormatString(char* buf, int buf_size, const char* fmt, ...) { IM_ASSERT(buf_size > 0); va_list args; va_start(args, fmt); int w = vsnprintf(buf, buf_size, fmt, args); va_end(args); if (w == -1 || w >= buf_size) w = buf_size - 1; buf[w] = 0; return w; } int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) { IM_ASSERT(buf_size > 0); int w = vsnprintf(buf, buf_size, fmt, args); if (w == -1 || w >= buf_size) w = buf_size - 1; buf[w] = 0; return w; } // Pass data_size==0 for zero-terminated strings // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHash(const void* data, int data_size, ImU32 seed) { static ImU32 crc32_lut[256] = { 0 }; if (!crc32_lut[1]) { const ImU32 polynomial = 0xEDB88320; for (ImU32 i = 0; i < 256; i++) { ImU32 crc = i; for (ImU32 j = 0; j < 8; j++) crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); crc32_lut[i] = crc; } } seed = ~seed; ImU32 crc = seed; const unsigned char* current = (const unsigned char*)data; if (data_size > 0) { // Known size while (data_size--) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; } else { // Zero-terminated string while (unsigned char c = *current++) { // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. if (c == '#' && current[0] == '#' && current[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } return ~crc; } //----------------------------------------------------------------------------- // ImText* helpers //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bits character, process single character input. // Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { unsigned int c = (unsigned int)-1; const unsigned char* str = (const unsigned char*)in_text; if (!(*str & 0x80)) { c = (unsigned int)(*str++); *out_char = c; return 1; } if ((*str & 0xe0) == 0xc0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 2) return 1; if (*str < 0xc2) return 2; c = (unsigned int)((*str++ & 0x1f) << 6); if ((*str & 0xc0) != 0x80) return 2; c += (*str++ & 0x3f); *out_char = c; return 2; } if ((*str & 0xf0) == 0xe0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 3) return 1; if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x0f) << 12); if ((*str & 0xc0) != 0x80) return 3; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 3; c += (*str++ & 0x3f); *out_char = c; return 3; } if ((*str & 0xf8) == 0xf0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 4) return 1; if (*str > 0xf4) return 4; if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x07) << 18); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 12); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 4; c += (*str++ & 0x3f); // utf-8 encodings of values used in surrogate pairs are invalid if ((c & 0xFFFFF800) == 0xD800) return 4; *out_char = c; return 4; } *out_char = 0; return 0; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return (int)(buf_out - buf); } int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c >= 0xdc00 && c < 0xe000) { return 0; } if (c >= 0xd800 && c < 0xdc00) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c ) & 0x3f)); return 4; } //else if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c >= 0xdc00 && c < 0xe000) return 0; if (c >= 0xd800 && c < 0xdc00) return 4; return 3; } int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { float s = 1.0f/255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { ImU32 out; out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; return out; } ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImU32 ImGui::GetColorU32(const ImVec4& col) { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ColorConvertFloat4ToU32(c); } // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { float K = 0.f; if (g < b) { const float tmp = g; g = b; b = tmp; K = -1.f; } if (r < g) { const float tmp = r; r = g; g = tmp; K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { if (s == 0.0f) { // gray out_r = out_g = out_b = v; return; } h = fmodf(h, 1.0f) / (60.0f/360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); float q = v * (1.0f - s * f); float t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } FILE* ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(__CYGWIN__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; ImVector<ImWchar> buf; buf.resize(filename_wsize + mode_wsize); ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); if (out_file_size) *out_file_size = 0; FILE* f; if ((f = ImFileOpen(filename, file_open_mode)) == NULL) return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return NULL; } int file_size = (int)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return NULL; } if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) { fclose(f); ImGui::MemFree(file_data); return NULL; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // ImGuiStorage //----------------------------------------------------------------------------- // Helper: Key->value storage void ImGuiStorage::Clear() { Data.clear(); } // std::lower_bound but without the bullshit static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key) { ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); ImVector<ImGuiStorage::Pair>::iterator last = data.end(); int count = (int)(last - first); while (count > 0) { int count2 = count / 2; ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return GetInt(key, default_val ? 1 : 0) != 0; } float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_i; } bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return (bool*)GetIntRef(key, default_val ? 1 : 0); } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::PushItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (width != 0.0f) ImGui::PopItemWidth(); if (value_changed) Build(); return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out) { out.resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out.push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out.push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) continue; if (Filters[i].front() != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; if (text == NULL) text = ""; for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) continue; if (f.front() == '-') { // Subtract if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // ImGuiTextBuffer //----------------------------------------------------------------------------- // On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #define va_copy(dest, src) (dest = src) #endif // Helper: Text buffer for logging/accumulating text void ImGuiTextBuffer::appendv(const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) return; const int write_off = Buf.Size; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int double_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); } Buf.resize(needed_sz); ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); } void ImGuiTextBuffer::append(const char* fmt, ...) { va_list args; va_start(args, fmt); appendv(fmt, args); va_end(args); } //----------------------------------------------------------------------------- // ImGuiSimpleColumns //----------------------------------------------------------------------------- ImGuiSimpleColumns::ImGuiSimpleColumns() { Count = 0; Spacing = Width = NextWidth = 0.0f; memset(Pos, 0, sizeof(Pos)); memset(NextWidths, 0, sizeof(NextWidths)); } void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); Count = count; Width = NextWidth = 0.0f; Spacing = spacing; if (clear) memset(NextWidths, 0, sizeof(NextWidths)); for (int i = 0; i < Count; i++) { if (i > 0 && NextWidths[i] > 0.0f) Width += Spacing; Pos[i] = (float)(int)Width; Width += NextWidths[i]; NextWidths[i] = 0.0f; } } float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double { NextWidth = 0.0f; NextWidths[0] = ImMax(NextWidths[0], w0); NextWidths[1] = ImMax(NextWidths[1], w1); NextWidths[2] = ImMax(NextWidths[2], w2); for (int i = 0; i < 3; i++) NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); return ImMax(Width, NextWidth); } float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) { return ImMax(0.0f, avail_w - Width); } //----------------------------------------------------------------------------- // ImGuiListClipper //----------------------------------------------------------------------------- static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions? ImGui::SetCursorPosY(pos_y); ImGuiWindow* window = ImGui::GetCurrentWindow(); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (window->DC.ColumnsCount > 1) window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { StartPosY = ImGui::GetCursorPosY(); ItemsHeight = items_height; ItemsCount = count; StepNo = 0; DisplayEnd = DisplayStart = -1; if (ItemsHeight > 0.0f) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } void ImGuiListClipper::End() { if (ItemsCount < 0) return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } bool ImGuiListClipper::Step() { if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) { ItemsCount = -1; return false; } if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. { DisplayStart = 0; DisplayEnd = 1; StartPosY = ImGui::GetCursorPosY(); StepNo = 1; return true; } if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } float items_height = ImGui::GetCursorPosY() - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically Begin(ItemsCount-1, items_height); DisplayStart++; DisplayEnd++; StepNo = 3; return true; } if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; return true; } if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. End(); return false; } //----------------------------------------------------------------------------- // ImGuiWindow //----------------------------------------------------------------------------- ImGuiWindow::ImGuiWindow(const char* name) { Name = ImStrdup(name); ID = ImHash(name, 0); IDStack.push_back(ID); MoveId = GetID("#MOVE"); Flags = 0; IndexWithinParent = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); Scroll = ImVec2(0.0f, 0.0f); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); ScrollbarX = ScrollbarY = false; ScrollbarSizes = ImVec2(0.0f, 0.0f); BorderSize = 0.0f; Active = WasActive = false; Accessed = false; Collapsed = false; SkipItems = false; BeginCount = 0; PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoPosLastDirection = -1; HiddenFrames = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; SetWindowPosCenterWanted = false; LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); IM_PLACEMENT_NEW(DrawList) ImDrawList(); DrawList->_OwnerName = Name; RootWindow = NULL; RootNonPopupWindow = NULL; ParentWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() { DrawList->~ImDrawList(); ImGui::MemFree(DrawList); DrawList = NULL; ImGui::MemFree(Name); Name = NULL; } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHash(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); } //----------------------------------------------------------------------------- // Internal API exposed in imgui_internal.h //----------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = window->CalcFontSize(); } ImGuiWindow* ImGui::GetParentWindow() { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindowStack.Size >= 2); return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; } void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.ActiveId = id; g.ActiveIdAllowOverlap = false; g.ActiveIdIsJustActivated = true; if (id) g.ActiveIdIsAlive = true; g.ActiveIdWindow = window; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); } void ImGui::SetHoveredID(ImGuiID id) { ImGuiContext& g = *GImGui; g.HoveredId = id; g.HoveredIdAllowOverlap = false; } void ImGui::KeepAliveID(ImGuiID id) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = true; } // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Always align ourselves on pixel boundaries ImGuiContext& g = *GImGui; const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug window->DC.PrevLineHeight = line_height; window->DC.PrevLineTextBaseOffset = text_base_offset; window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; } void ImGui::ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } // Declare item bounding box for clipping and interaction. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface // declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) { ImGuiWindow* window = GetCurrentWindow(); window->DC.LastItemId = id ? *id : 0; window->DC.LastItemRect = bb; window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; if (IsClippedEx(bb, id, false)) return false; // This is a sensible default, but widgets are free to override it after calling ItemAdd() ImGuiContext& g = *GImGui; if (IsMouseHoveringRect(bb.Min, bb.Max)) { // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() window->DC.LastItemHoveredRect = true; if (g.HoveredRootWindow == window->RootWindow) if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId)) if (IsWindowContentHoverable(window)) window->DC.LastItemHoveredAndUsable = true; } return true; } bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (!bb.Overlaps(window->ClipRect)) if (!id || *id != GImGui->ActiveId) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } // NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) { ImGuiContext& g = *GImGui; if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) { ImGuiWindow* window = GetCurrentWindowRead(); if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) if (IsWindowContentHoverable(g.HoveredRootWindow)) return true; } return false; } bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) { ImGuiContext& g = *GImGui; const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; window->FocusIdxAllCounter++; if (allow_keyboard_focus) window->FocusIdxTabCounter++; // Process keyboard input at this point: TAB, Shift-TAB switch focus // We can always TAB out of a widget that doesn't allow tabbing in. if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); } if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus) if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) return true; return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->FocusIdxAllCounter--; window->FocusIdxTabCounter--; } ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) { ImGuiContext& g = *GImGui; ImVec2 content_max; if (size.x < 0.0f || size.y < 0.0f) content_max = g.CurrentWindow->Pos + GetContentRegionMax(); if (size.x <= 0.0f) size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; if (size.y <= 0.0f) size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; return size; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiWindow* window = GetCurrentWindowRead(); if (wrap_pos_x == 0.0f) wrap_pos_x = GetContentRegionMax().x + window->Pos.x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space return ImMax(wrap_pos_x - pos.x, 1.0f); } //----------------------------------------------------------------------------- void* ImGui::MemAlloc(size_t sz) { GImGui->IO.MetricsAllocs++; return GImGui->IO.MemAllocFn(sz); } void ImGui::MemFree(void* ptr) { if (ptr) GImGui->IO.MetricsAllocs--; return GImGui->IO.MemFreeFn(ptr); } const char* ImGui::GetClipboardText() { return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { if (GImGui->IO.SetClipboardTextFn) GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module ImGuiContext* ImGui::GetCurrentContext() { return GImGui; } void ImGui::SetCurrentContext(ImGuiContext* ctx) { #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. #else GImGui = ctx; #endif } ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) { if (!malloc_fn) malloc_fn = malloc; ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); IM_PLACEMENT_NEW(ctx) ImGuiContext(); ctx->IO.MemAllocFn = malloc_fn; ctx->IO.MemFreeFn = free_fn ? free_fn : free; return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { void (*free_fn)(void*) = ctx->IO.MemFreeFn; ctx->~ImGuiContext(); free_fn(ctx); if (GImGui == ctx) SetCurrentContext(NULL); } ImGuiIO& ImGui::GetIO() { return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { return GImGui->Style; } // Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; } float ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } void ImGui::NewFrame() { ImGuiContext& g = *GImGui; // Check user data IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting if (!g.Initialized) { // Initialize on first frame g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); IM_ASSERT(g.Settings.empty()); LoadIniSettingsFromDisk(g.IO.IniFilename); g.Initialized = true; } SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.Tooltip[0] = '\0'; g.OverlayDrawList.Clear(); g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); g.OverlayDrawList.PushClipRectFullScreen(); // Mark rendering data as invalid to prevent user who may have a handle on it to use it g.RenderDrawData.Valid = false; g.RenderDrawData.CmdLists = NULL; g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; // Update inputs state if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta g.IO.MouseDelta = ImVec2(0.0f, 0.0f); else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) { if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); } } memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Clear reference to active widget if the widget isn't alive anymore g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) ClearActiveID(); g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; g.ActiveIdIsJustActivated = false; // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) { KeepAliveID(g.MovedWindowMoveId); IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId); if (g.IO.MouseDown[0]) { if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) { g.MovedWindow->PosFloat += g.IO.MouseDelta; if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)) MarkIniSettingsDirty(); } FocusWindow(g.MovedWindow); } else { ClearActiveID(); g.MovedWindow = NULL; g.MovedWindowMoveId = 0; } } else { g.MovedWindow = NULL; g.MovedWindowMoveId = 0; } // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) SaveIniSettingsToDisk(g.IO.IniFilename); } // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) g.HoveredRootWindow = g.HoveredWindow->RootWindow; else g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) { g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); ImGuiWindow* window = g.HoveredRootWindow; while (window && window != modal_window) window = window->ParentWindow; if (!window) g.HoveredRootWindow = g.HoveredWindow = NULL; } else { g.ModalWindowDarkeningRatio = 0.0f; } // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. int mouse_earliest_button_down = -1; bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) mouse_earliest_button_down = i; } bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; if (g.CaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); g.MouseCursor = ImGuiMouseCursor_Arrow; g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. if (!mouse_avail_to_imgui) g.HoveredWindow = g.HoveredRootWindow = NULL; // Scale & Scrolling if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) { ImGuiWindow* window = g.HoveredWindow; if (g.IO.KeyCtrl) { if (g.IO.FontAllowUserScaling) { // Zoom / Scale window float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; window->Pos += offset; window->PosFloat += offset; window->Size *= scale; window->SizeFull *= scale; } } else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) { // Scroll const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); } } // Pressing TAB activate widget focus // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) g.FocusedWindow->FocusIdxTabRequestNext = 0; // Mark all windows as not visible for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; window->Active = false; window->Accessed = false; } // Closing the focused window restore focus to the first active root window in descending z-order if (g.FocusedWindow && !g.FocusedWindow->WasActive) for (int i = g.Windows.Size-1; i >= 0; i--) if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) { FocusWindow(g.Windows[i]); break; } // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.CurrentPopupStack.resize(0); CloseInactivePopups(); // Create implicit window - we will only render it if the user has added something to it. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); ImGui::Begin("Debug"); } // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. void ImGui::Shutdown() { ImGuiContext& g = *GImGui; // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. g.IO.Fonts->Clear(); // Cleanup of other data are conditional on actually having used ImGui. if (!g.Initialized) return; SaveIniSettingsToDisk(g.IO.IniFilename); for (int i = 0; i < g.Windows.Size; i++) { g.Windows[i]->~ImGuiWindow(); ImGui::MemFree(g.Windows[i]); } g.Windows.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.FocusedWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; g.ActiveIdWindow = NULL; g.MovedWindow = NULL; for (int i = 0; i < g.Settings.Size; i++) ImGui::MemFree(g.Settings[i].Name); g.Settings.clear(); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.CurrentPopupStack.clear(); g.SetNextWindowSizeConstraintCallback = NULL; g.SetNextWindowSizeConstraintCallbackUserData = NULL; for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].clear(); g.OverlayDrawList.ClearFreeMemory(); g.ColorEditModeStorage.Clear(); if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } g.InputTextState.Text.clear(); g.InputTextState.InitialText.clear(); g.InputTextState.TempTextBuffer.clear(); if (g.LogFile && g.LogFile != stdout) { fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard) { g.LogClipboard->~ImGuiTextBuffer(); ImGui::MemFree(g.LogClipboard); } g.Initialized = false; } static ImGuiIniData* FindWindowSettings(const char* name) { ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); for (int i = 0; i != g.Settings.Size; i++) { ImGuiIniData* ini = &g.Settings[i]; if (ini->Id == id) return ini; } return NULL; } static ImGuiIniData* AddWindowSettings(const char* name) { GImGui->Settings.resize(GImGui->Settings.Size + 1); ImGuiIniData* ini = &GImGui->Settings.back(); ini->Name = ImStrdup(name); ini->Id = ImHash(name, 0); ini->Collapsed = false; ini->Pos = ImVec2(FLT_MAX,FLT_MAX); ini->Size = ImVec2(0,0); return ini; } // Zero-tolerance, poor-man .ini parsing // FIXME: Write something less rubbish static void LoadIniSettingsFromDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; if (!ini_filename) return; int file_size; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1); if (!file_data) return; ImGuiIniData* settings = NULL; const char* buf_end = file_data + file_size; for (const char* line_start = file_data; line_start < buf_end; ) { const char* line_end = line_start; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') { char name[64]; ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); settings = FindWindowSettings(name); if (!settings) settings = AddWindowSettings(name); } else if (settings) { float x, y; int i; if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line_start, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } line_start = line_end+1; } ImGui::MemFree(file_data); } static void SaveIniSettingsToDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; if (!ini_filename) return; // Gather data from windows that were active during this session for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiIniData* settings = FindWindowSettings(window->Name); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write .ini file // If a window wasn't opened in this session we preserve its settings FILE* f = ImFileOpen(ini_filename, "wt"); if (!f) return; for (int i = 0; i != g.Settings.Size; i++) { const ImGuiIniData* settings = &g.Settings[i]; if (settings->Pos.x == FLT_MAX) continue; const char* name = settings->Name; if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() name = p; fprintf(f, "[%s]\n", name); fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); fprintf(f, "Collapsed=%d\n", settings->Collapsed); fprintf(f, "\n"); } fclose(f); } static void MarkIniSettingsDirty() { ImGuiContext& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } // FIXME: Add a more explicit sort order in the window structure. static int ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* a = *(const ImGuiWindow**)lhs; const ImGuiWindow* b = *(const ImGuiWindow**)rhs; if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) return d; return (a->IndexWithinParent - b->IndexWithinParent); } static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window) { out_sorted_windows.push_back(window); if (window->Active) { int count = window->DC.ChildWindows.Size; if (count > 1) qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active) AddWindowToSortedBuffer(out_sorted_windows, child); } } } static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list) { if (draw_list->CmdBuffer.empty()) return; // Remove trailing command if unused ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); if (draw_list->CmdBuffer.empty()) return; } // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices) // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly. IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above. out_render_list.push_back(draw_list); GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; } static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window) { AddDrawListToRenderList(out_render_list, window->DrawList); for (int i = 0; i < window->DC.ChildWindows.Size; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (!child->Active) // clipped children may have been marked not active continue; if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) continue; AddWindowToRenderList(out_render_list, child); } } // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); window->ClipRect = window->DrawList->_ClipRectStack.back(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. void ImGui::EndFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again // Render tooltip if (g.Tooltip[0]) { ImGui::BeginTooltip(); ImGui::TextUnformatted(g.Tooltip); ImGui::EndTooltip(); } // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) { g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); g.OsImePosSet = g.OsImePosRequest; } // Hide implicit "Debug" window if it hasn't been used IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls if (g.CurrentWindow && !g.CurrentWindow->Accessed) g.CurrentWindow->Active = false; ImGui::End(); // Click to focus window and start moving (after we're done with all our widgets) if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) { if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear { if (g.HoveredRootWindow != NULL) { FocusWindow(g.HoveredWindow); if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) { g.MovedWindow = g.HoveredWindow; g.MovedWindowMoveId = g.HoveredRootWindow->MoveId; SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); } } else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } } // Sort the window list so that all child windows are after their parent // We cannot do that on FocusWindow() because childs may not exist yet g.WindowsSortBuffer.resize(0); g.WindowsSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it continue; AddWindowToSortedBuffer(g.WindowsSortBuffer, window); } IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong g.Windows.swap(g.WindowsSortBuffer); // Clear Input data for next frame g.IO.MouseWheel = 0.0f; memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); g.FrameCountEnded = g.FrameCount; } void ImGui::Render() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() if (g.FrameCountEnded != g.FrameCount) ImGui::EndFrame(); g.FrameCountRendered = g.FrameCount; // Skip render altogether if alpha is 0.0 // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. if (g.Style.Alpha > 0.0f) { // Gather windows to render g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].resize(0); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) { // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. g.IO.MetricsActiveWindows++; if (window->Flags & ImGuiWindowFlags_Popup) AddWindowToRenderList(g.RenderDrawLists[1], window); else if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToRenderList(g.RenderDrawLists[2], window); else AddWindowToRenderList(g.RenderDrawLists[0], window); } } // Flatten layers int n = g.RenderDrawLists[0].Size; int flattened_size = n; for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) flattened_size += g.RenderDrawLists[i].Size; g.RenderDrawLists[0].resize(flattened_size); for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) { ImVector<ImDrawList*>& layer = g.RenderDrawLists[i]; if (layer.empty()) continue; memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); n += layer.Size; } // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) { const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; const ImVec2 size = cursor_data.Size; const ImTextureID tex_id = g.IO.Fonts->TexID; g.OverlayDrawList.PushTextureID(tex_id); g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill g.OverlayDrawList.PopTextureID(); } if (!g.OverlayDrawList.VtxBuffer.empty()) AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); // Setup draw data g.RenderDrawData.Valid = true; g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.RenderDrawData); } } const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; return text_display_end; } // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) { vfprintf(g.LogFile, fmt, args); } else { g.LogClipboard->appendv(fmt, args); } va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = ImGui::GetCurrentWindowRead(); if (!text_end) text_end = ImGui::FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; window->DC.LogLinePosY = ref_pos.y; const char* text_remaining = text; if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogStartDepth = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. const char* line_end = text_remaining; while (line_end < text_end) if (*line_end == '\n') break; else line_end++; if (line_end >= text_end) line_end = NULL; const bool is_first_line = (text == text_remaining); bool is_last_line = false; if (line_end == NULL) { is_last_line = true; line_end = text_end; } if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } if (is_last_line) break; text_remaining = line_end + 1; } } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindRenderedTextEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } const int text_len = (int)(text_display_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) LogRenderedText(pos, text, text_display_end); } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) text_end = text + strlen(text); // FIXME-OPT const int text_len = (int)(text_end - text); if (text_len > 0) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) LogRenderedText(pos, text, text_end); } } // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Hide anything after a '##' string const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } if (g.LogEnabled) LogRenderedText(pos, text, text_display_end); } // Render a rectangle shaped with optional rounding and borders void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); } } // Render a triangle to denote expanded/collapsed state void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = g.FontSize * 1.00f; const float r = h * 0.40f * scale; ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); ImVec2 a, b, c; if (is_open) { center.y -= r*0.25f; a = center + ImVec2(0,1)*r; b = center + ImVec2(-0.866f,-0.5f)*r; c = center + ImVec2(0.866f,-0.5f)*r; } else { a = center + ImVec2(1,0)*r; b = center + ImVec2(-0.500f,0.866f)*r; c = center + ImVec2(-0.500f,-0.866f)*r; } window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); } void ImGui::RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImVec2 a, b, c; float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); a.x = pos.x + 0.5f + start_x; b.x = a.x + rem_third; c.x = a.x + rem_third * 3.0f; b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); a.y = b.y - rem_third; c.y = b.y - rem_third * 2.0f; window->DrawList->PathLineTo(a); window->DrawList->PathLineTo(b); window->DrawList->PathLineTo(c); window->DrawList->PathStroke(col, false); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) const float font_scale = font_size / font->FontSize; const float character_spacing_x = 1.0f * font_scale; if (text_size.x > 0.0f) text_size.x -= character_spacing_x; text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; } // Helper to calculate coarse clipping of large list of evenly sized items. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *out_items_display_end = items_count; return; } if (window->SkipItems) { *out_items_display_start = *out_items_display_end = 0; return; } const ImVec2 pos = window->DC.CursorPos; int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back // FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size-1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active) continue; if (window->Flags & ImGuiWindowFlags_NoInputs) continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) continue; // Using the clipped AABB so a child window will typically be clipped by its parent. ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } return NULL; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); // Clip ImRect rect_clipped(r_min, r_max); if (clip) rect_clipped.Clip(window->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); return rect_for_touch.Contains(g.IO.MousePos); } bool ImGui::IsMouseHoveringWindow() { ImGuiContext& g = *GImGui; return g.HoveredWindow == g.CurrentWindow; } bool ImGui::IsMouseHoveringAnyWindow() { ImGuiContext& g = *GImGui; return g.HoveredWindow != NULL; } bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) { return FindHoveredWindow(pos, false) != NULL; } static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { const int key_index = GImGui->IO.KeyMap[key]; return ImGui::IsKeyPressed(key_index, repeat); } int ImGui::GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT); return GImGui->IO.KeyMap[key]; } bool ImGui::IsKeyDown(int key_index) { if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); return GImGui->IO.KeysDown[key_index]; } bool ImGui::IsKeyPressed(int key_index, bool repeat) { ImGuiContext& g = *GImGui; if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[key_index]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; } return false; } bool ImGui::IsKeyReleased(int key_index) { ImGuiContext& g = *GImGui; if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index]) return true; return false; } bool ImGui::IsMouseDown(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; } return false; } bool ImGui::IsMouseReleased(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; } // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.CurrentPopupStack.Size > 0) return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; return g.IO.MousePos; } ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). return ImVec2(0.0f, 0.0f); } void ImGui::ResetMouseDragDelta(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; } void ImGui::CaptureMouseFromApp(bool capture) { GImGui->CaptureMouseNextFrame = capture ? 1 : 0; } bool ImGui::IsItemHovered() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredAndUsable; } bool ImGui::IsItemHoveredRect() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredRect; } bool ImGui::IsItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = GetCurrentWindowRead(); return g.ActiveId == window->DC.LastItemId; } return false; } bool ImGui::IsItemClicked(int mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(); } bool ImGui::IsAnyItemHovered() { return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { return GImGui->ActiveId != 0; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindowRead(); ImRect r(window->ClipRect); return r.Overlaps(window->DC.LastItemRect); } // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. void ImGui::SetItemAllowOverlap() { ImGuiContext& g = *GImGui; if (g.HoveredId == g.CurrentWindow->DC.LastItemId) g.HoveredIdAllowOverlap = true; if (g.ActiveId == g.CurrentWindow->DC.LastItemId) g.ActiveIdAllowOverlap = true; } ImVec2 ImGui::GetItemRectMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) { ImGuiWindow* window = GetCurrentWindowRead(); ImRect rect = window->DC.LastItemRect; rect.Expand(outward); return rect.GetClosestPoint(pos, on_edge); } // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. void ImGui::SetTooltipV(const char* fmt, va_list args) { ImGuiContext& g = *GImGui; ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } static ImRect GetVisibleRect() { ImGuiContext& g = *GImGui; if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } void ImGui::BeginTooltip() { ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("##Tooltip", NULL, flags); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls ImGui::End(); } static bool IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetID(str_id); int current_stack_size = g.CurrentPopupStack.Size; ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) if (g.OpenPopupStack.Size < current_stack_size + 1) g.OpenPopupStack.push_back(popup_ref); else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id) { g.OpenPopupStack.resize(current_stack_size+1); g.OpenPopupStack[current_stack_size] = popup_ref; } } void ImGui::OpenPopup(const char* str_id) { ImGui::OpenPopupEx(str_id, false); } static void CloseInactivePopups() { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.empty()) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows int n = 0; if (g.FocusedWindow) { for (n = 0; n < g.OpenPopupStack.Size; n++) { ImGuiPopupRef& popup = g.OpenPopupStack[n]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; bool has_focus = false; for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); if (!has_focus) break; } } if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below g.OpenPopupStack.resize(n); } static ImGuiWindow* GetFrontMostModalRootWindow() { ImGuiContext& g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) if (front_most_popup->Flags & ImGuiWindowFlags_Modal) return front_most_popup; return NULL; } static void ClosePopupToLevel(int remaining) { ImGuiContext& g = *GImGui; if (remaining > 0) ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); else ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); g.OpenPopupStack.resize(remaining); } static void ClosePopup(ImGuiID id) { if (!IsPopupOpen(id)) return; ImGuiContext& g = *GImGui; ClosePopupToLevel(g.OpenPopupStack.Size - 1); } // Close the popup we have begin-ed into. void ImGui::CloseCurrentPopup() { ImGuiContext& g = *GImGui; int popup_idx = g.CurrentPopupStack.Size - 1; if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) return; while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) popup_idx--; ClosePopupToLevel(popup_idx); } static inline void ClearSetNextWindowData() { ImGuiContext& g = *GImGui; g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; } static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(str_id); if (!IsPopupOpen(id)) { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; char name[20]; if (flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame bool is_open = ImGui::Begin(name, NULL, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) ImGui::EndPopup(); return is_open; } bool ImGui::BeginPopup(const char* str_id) { if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); } bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id)) { ClearSetNextWindowData(); // We behave like Begin() and need to consume those values return false; } ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; bool is_open = ImGui::Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { ImGui::EndPopup(); if (is_open) ClosePopup(id); return false; } return is_open; } void ImGui::EndPopup() { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); ImGui::End(); if (!(window->Flags & ImGuiWindowFlags_Modal)) ImGui::PopStyleVar(); } // This is a helper to handle the most simple case of associating one named popup to one given widget. // 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling // this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. // 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() // and passing true to the OpenPopupEx(). // Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that // the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu // driven by click position. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { if (IsItemHovered() && IsMouseClicked(mouse_button)) OpenPopupEx(str_id, false); return BeginPopup(str_id); } bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) { if (!str_id) str_id = "window_context_menu"; if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(str_id, true); return BeginPopup(str_id); } bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context_menu"; if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) OpenPopupEx(str_id, true); return BeginPopup(str_id); } static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = ImGui::GetCurrentWindow(); ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; const ImVec2 content_avail = ImGui::GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; flags |= extra_flags; char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id); bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; return ret; } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { return BeginChildEx(NULL, id, size_arg, border, extra_flags); } void ImGui::EndChild() { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) { ImGui::End(); } else { // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. ImVec2 sz = GetWindowSize(); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f sz.x = ImMax(4.0f, sz.x); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) sz.y = ImMax(4.0f, sz.y); ImGui::End(); window = GetCurrentWindow(); ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz); ItemSize(sz); ItemAdd(bb, NULL); } } // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); } void ImGui::EndChildFrame() { ImGui::EndChild(); ImGui::PopStyleVar(2); ImGui::PopStyleColor(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) ImGuiContext& g = *GImGui; int* p_backup = &window->DC.StackSizesBackup[0]; { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID Mismatch!"); p_backup++; } // User forgot PopID() { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot EndGroup() { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++; }// User forgot EndPopup()/EndMenu() { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor() { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar() { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) { const ImGuiStyle& style = GImGui->Style; // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. ImVec2 safe_padding = style.DisplaySafeAreaPadding; ImRect r_outer(GetVisibleRect()); r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). { const int dir = (n == -1) ? *last_dir : n; ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) continue; *last_dir = dir; return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); } // Fallback, try to keep within display *last_dir = -1; ImVec2 pos = base_pos; pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); return pos; } ImGuiWindow* ImGui::FindWindowByName(const char* name) { // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block ImGuiContext& g = *GImGui; ImGuiID id = ImHash(name, 0); for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i]->ID == id) return g.Windows[i]; return NULL; } static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; // Create window the first time ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); IM_PLACEMENT_NEW(window) ImGuiWindow(name); window->Flags = flags; if (flags & ImGuiWindowFlags_NoSavedSettings) { // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. window->Size = window->SizeFull = size; } else { // Retrieve settings from .ini file // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->PosFloat = ImVec2(60, 60); window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); ImGuiIniData* settings = FindWindowSettings(name); if (!settings) { settings = AddWindowSettings(name); } else { window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver; } if (settings->Pos.x != FLT_MAX) { window->PosFloat = settings->Pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->Collapsed = settings->Collapsed; } if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize)) size = settings->Size; window->Size = window->SizeFull = size; } if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } else { if (window->Size.x <= 0.0f) window->AutoFitFramesX = 2; if (window->Size.y <= 0.0f) window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once else g.Windows.push_back(window); return window; } static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; if (g.SetNextWindowSizeConstraint) { // Using -1,-1 on either X/Y axis to preserve the current size. ImRect cr = g.SetNextWindowSizeConstraintRect; new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; if (g.SetNextWindowSizeConstraintCallback) { ImGuiSizeConstraintCallbackData data; data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; data.Pos = window->Pos; data.CurrentSize = window->SizeFull; data.DesiredSize = new_size; g.SetNextWindowSizeConstraintCallback(&data); new_size = data.DesiredSize; } } if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) new_size = ImMax(new_size, g.Style.WindowMinSize); window->SizeFull = new_size; } // Push a new ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); } bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; IM_ASSERT(name != NULL); // Window name required IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet if (flags & ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; // Find or create bool window_is_new = false; ImGuiWindow* window = FindWindowByName(name); if (!window) { window = CreateNewWindow(name, size_on_first_use, flags); window_is_new = true; } const int current_frame = ImGui::GetFrameCount(); const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); if (first_begin_of_the_frame) window->Flags = (ImGuiWindowFlags)flags; else flags = window->Flags; // Add to stack ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); CheckStacksSize(window, true); IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; window_was_active &= (window->PopupId == popup_ref.PopupId); window_was_active &= (window == popup_ref.Window); popup_ref.Window = window; g.CurrentPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; } const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); // Process SetNextWindow***() calls bool window_pos_set_by_api = false, window_size_set_by_api = false; if (g.SetNextWindowPosCond) { const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) { window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); } else { SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); } window->DC.CursorPos = backup_cursor_pos; g.SetNextWindowPosCond = 0; } if (g.SetNextWindowSizeCond) { if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); g.SetNextWindowSizeCond = 0; } if (g.SetNextWindowContentSizeCond) { window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; g.SetNextWindowContentSizeCond = 0; } else if (first_begin_of_the_frame) { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); } if (g.SetNextWindowCollapsedCond) { if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); g.SetNextWindowCollapsedCond = 0; } if (g.SetNextWindowFocus) { ImGui::SetWindowFocus(); g.SetNextWindowFocus = false; } // Update known root window (if we are a child window, otherwise window == window->RootWindow) int root_idx, root_non_popup_idx; for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) break; for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) break; window->ParentWindow = parent_window; window->RootWindow = g.CurrentWindowStack[root_idx]; window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. // When reusing window again multiple times a frame, just append content (don't need to setup again) if (first_begin_of_the_frame) { window->Active = true; window->IndexWithinParent = 0; window->BeginCount = 0; window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->LastFrameActive = current_frame; window->IDStack.resize(1); // Clear draw list, setup texture, outer clipping rectangle window->DrawList->Clear(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); ImRect fullscreen_rect(GetVisibleRect()); if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); else PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); if (!window_was_active) { // Popup first latch mouse position, will position itself when it appears next frame window->AutoPosLastDirection = -1; if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) window->PosFloat = g.IO.MousePos; } // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { ImRect title_bar_rect = window->TitleBarRect(); if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) { window->Collapsed = !window->Collapsed; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); FocusWindow(window); } } else { window->Collapsed = false; } // SIZE // Save contents size from last frame for auto-fitting (unless explicitly specified) window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) if (window->HiddenFrames > 0) window->HiddenFrames--; if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) { window->HiddenFrames = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_set_by_api) window->Size = window->SizeFull = ImVec2(0.f, 0.f); window->SizeContents = ImVec2(0.f, 0.f); } } // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; // Calculate auto-fit size ImVec2 size_auto_fit; if ((flags & ImGuiWindowFlags_Tooltip) != 0) { // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); } else { size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) size_auto_fit.x += style.ScrollbarSize; size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); } // Handle automatic resize if (window->Collapsed) { // We still process initial auto-fit on collapsed windows to get a window width, // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (window->AutoFitFramesX > 0) window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (window->AutoFitFramesY > 0) window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; } else { if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) { window->SizeFull = size_auto_fit; } else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) { // Auto-fit only grows during the first few frames if (window->AutoFitFramesX > 0) window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (window->AutoFitFramesY > 0) window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); } } // Apply minimum/maximum window size constraints and final size ApplySizeFullWithConstraint(window, window->SizeFull); window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; // POSITION // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { window->IndexWithinParent = parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); } if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) { window->Pos = window->PosFloat = parent_window->DC.CursorPos; window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). } bool window_pos_center = false; window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); if (window_pos_center) { // Center (any sort of window) SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0); } else if (flags & ImGuiWindowFlags_ChildMenu) { // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(window_pos_set_by_api); float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value). ImRect rect_to_avoid; if (parent_window->DC.MenuBarAppending) rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); else rect_to_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) { ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); } // Position tooltip (always follows mouse) if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) { ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); if (window->AutoPosLastDirection == -1) window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. } // Clamp position so it stays visible if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding); } } window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Prepare for focus requests window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; // Apply scrolling if (window->ScrollTarget.x < FLT_MAX) { window->Scroll.x = window->ScrollTarget.x; window->ScrollTarget.x = FLT_MAX; } if (window->ScrollTarget.y < FLT_MAX) { float center_ratio = window->ScrollTargetCenterRatio.y; window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y); window->ScrollTarget.y = FLT_MAX; } window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); // Modal window darkens what is behind them if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); // Draw window + handle manual resize ImRect title_bar_rect = window->TitleBarRect(); const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; if (window->Collapsed) { // Draw title bar only RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); } else { ImU32 resize_col = 0; const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) { // Manual resize const ImVec2 br = window->Rect().GetBR(); const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); const ImGuiID resize_id = window->GetID("#RESIZE"); bool hovered, held; ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) { // Manual auto-fit when double-clicking ApplySizeFullWithConstraint(window, size_auto_fit); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); ClearActiveID(); } else if (held) { // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkIniSettingsDirty(); } window->Size = window->SizeFull; title_bar_rect = window->TitleBarRect(); } // Scrollbars window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; // Window background, Default Alpha ImGuiCol bg_color_idx = ImGuiCol_WindowBg; if ((flags & ImGuiWindowFlags_ComboBox) != 0) bg_color_idx = ImGuiCol_ComboBg; else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) bg_color_idx = ImGuiCol_PopupBg; else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) bg_color_idx = ImGuiCol_ChildWindowBg; ImVec4 bg_color = style.Colors[bg_color_idx]; if (bg_alpha >= 0.0f) bg_color.w = bg_alpha; bg_color.w *= style.Alpha; if (bg_color.w > 0.0f) window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight); // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); if (flags & ImGuiWindowFlags_ShowBorders) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border)); window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); } // Scrollbars if (window->ScrollbarX) Scrollbar(window, true); if (window->ScrollbarY) Scrollbar(window, false); // Render resize grip // (after the input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { const ImVec2 br = window->Rect().GetBR(); window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); window->DrawList->PathFill(resize_col); } // Borders if (flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); if (!(flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); } } // Update ContentsRegionMax. All the variable it depends on are set above in this function. window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); // Setup drawing context window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.GroupOffsetX = 0.0f; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.MenuBarAppending = false; window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.AllowKeyboardFocus = true; window->DC.ButtonRepeat = false; window->DC.ItemWidthStack.resize(0); window->DC.AllowKeyboardFocusStack.resize(0); window->DC.ButtonRepeatStack.resize(0); window->DC.TextWrapPosStack.resize(0); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = 1; window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; window->DC.TreeDepth = 0; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; if (window->AutoFitFramesY > 0) window->AutoFitFramesY--; // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) FocusWindow(window); // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { if (p_open != NULL) { const float pad = 2.0f; const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) *p_open = false; } const ImVec2 text_size = CalcTextSize(name, NULL, true); if (!(flags & ImGuiWindowFlags_NoCollapse)) RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f); ImVec2 text_min = window->Pos; ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y); ImRect clip_rect; clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); text_min.x += pad_left; text_max.x -= pad_right; clip_rect.Min = ImVec2(text_min.x, window->Pos.y); RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->WindowRectClipped = window->Rect(); window->WindowRectClipped.Clip(window->ClipRect); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) ImGui::LogToClipboard(); */ } // Inner clipping rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); const float border_size = window->BorderSize; ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); PushClipRect(clip_rect.Min, clip_rect.Max, true); // Clear 'accessed' flag last thing if (first_begin_of_the_frame) window->Accessed = false; window->BeginCount++; g.SetNextWindowSizeConstraint = false; // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); // We also hide the window from rendering because we've already added its border to the command list. // (we could perform the check earlier in the function but it is simpler at this point) if (window->Collapsed) window->Active = false; } if (style.Alpha <= 0.0f) window->Active = false; // Return false if we don't intend to display anything to allow user to perform an early out optimization window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; return !window->SkipItems; } void ImGui::End() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; Columns(1, "#CloseColumns"); PopClipRect(); // inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging LogFinish(); // Pop // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). g.CurrentWindowStack.pop_back(); if (window->Flags & ImGuiWindowFlags_Popup) g.CurrentPopupStack.pop_back(); CheckStacksSize(window, false); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } // Vertical scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. static void Scrollbar(ImGuiWindow* window, bool horizontal) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; const ImRect window_rect = window->Rect(); const float border_size = window->BorderSize; ImRect bb = horizontal ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); if (!horizontal) bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; int window_rounding_corners; if (horizontal) window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); else window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); // V denote the main axis of the scrollbar float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // The grabable box size generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); ImGui::ButtonBehavior(bb, id, &hovered, &held); float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); float scroll_ratio = ImSaturate(scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; if (held && grab_h_norm < 1.0f) { float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; // Click position in scrollbar normalized space (0.0f->1.0f) const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); ImGui::SetHoveredID(id); bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); if (horizontal) window->Scroll.x = scroll_v; else window->Scroll.y = scroll_v; // Update values for rendering scroll_ratio = ImSaturate(scroll_v / scroll_max); grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); if (horizontal) window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); else window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); } // Moving window to front of display (which happens to be back of our sorted list) void ImGui::FocusWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. g.FocusedWindow = window; // Passing NULL allow to disable keyboard focus if (!window) return; // And move its root window to the top of the pile if (window->RootWindow) window = window->RootWindow; // Steal focus on active widgets if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) ClearActiveID(); // Bring to front if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) return; for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { g.Windows.erase(g.Windows.begin() + i); break; } g.Windows.push_back(window); } void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); } static void PushMultiItemsWidths(int components, float w_full) { ImGuiWindow* window = ImGui::GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; if (w_full <= 0.0f) w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components-1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } float ImGui::CalcItemWidth() { ImGuiWindow* window = GetCurrentWindowRead(); float w = window->DC.ItemWidth; if (w < 0.0f) { // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. float width_to_right_edge = GetContentRegionAvail().x; w = ImMax(1.0f, width_to_right_edge + w); } w = (float)(int)w; return w; } static ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } static void SetCurrentFont(ImFont* font) { ImGuiContext& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel; } void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; if (!font) font = GetDefaultFont(); SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocus = allow_keyboard_focus; window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocusStack.pop_back(); window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); } void ImGui::PushButtonRepeat(bool repeat) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ButtonRepeat = repeat; window->DC.ButtonRepeatStack.push_back(repeat); } void ImGui::PopButtonRepeat() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ButtonRepeatStack.pop_back(); window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); } void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos = wrap_pos_x; window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; } } struct ImGuiStyleVarInfo { ImGuiDataType Type; ImU32 Offset; void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); } }; static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] = { { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float) { float* pvar = (float*)var_info->GetVarPtr(); GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float2) { ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(); GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. } void ImGui::PopStyleVar(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0]; else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0]; g.StyleModifiers.pop_back(); count--; } } const char* ImGui::GetStyleColName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_TitleBgActive: return "TitleBgActive"; case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_ComboBg: return "ComboBg"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Column: return "Column"; case ImGuiCol_ColumnHovered: return "ColumnHovered"; case ImGuiCol_ColumnActive: return "ColumnActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_CloseButton: return "CloseButton"; case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; } IM_ASSERT(0); return "Unknown"; } bool ImGui::IsWindowHovered() { ImGuiContext& g = *GImGui; return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); } bool ImGui::IsWindowFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow == g.CurrentWindow; } bool ImGui::IsRootWindowFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildFocused() { ImGuiContext& g = *GImGui; return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildHovered() { ImGuiContext& g = *GImGui; return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); } float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return window->Pos; } static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { window->DC.CursorMaxPos.y += window->Scroll.y; window->Scroll.y = new_scroll_y; window->DC.CursorMaxPos.y -= window->Scroll.y; } static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); window->SetWindowPosCenterWanted = false; // Set const ImVec2 old_pos = window->Pos; window->PosFloat = pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiWindow* window = GetCurrentWindowRead(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set if (size.x > 0.0f) { window->AutoFitFramesX = 0; window->SizeFull.x = size.x; } else { window->AutoFitFramesX = 2; window->AutoFitOnlyGrows = false; } if (size.y > 0.0f) { window->AutoFitFramesY = 0; window->SizeFull.y = size.y; } else { window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) { SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowSize(window, size, cond); } static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set window->Collapsed = collapsed; } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } bool ImGui::IsWindowCollapsed() { return GImGui->CurrentWindow->Collapsed; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = pos; g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowSizeVal = size; g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; g.SetNextWindowSizeConstraint = true; g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); g.SetNextWindowSizeConstraintCallback = custom_callback; g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; } void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.SetNextWindowContentSizeVal = size; g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; } void ImGui::SetNextWindowContentWidth(float width) { ImGuiContext& g = *GImGui; g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextWindowCollapsedVal = collapsed; g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; g.SetNextWindowFocus = true; } // In window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.ColumnsCount != 1) mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; return mx; } ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GetCurrentWindowRead(); return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); } float ImGui::GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Min; } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Max; } float ImGui::GetWindowContentRegionWidth() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; } float ImGui::GetTextLineHeight() { ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetItemsLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } ImFont* ImGui::GetFont() { return GImGui->Font; } float ImGui::GetFontSize() { return GImGui->FontSize; } ImVec2 ImGui::GetFontTexUvWhitePixel() { return GImGui->FontTexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = window->CalcFontSize(); } // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorStartPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = screen_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } float ImGui::GetScrollX() { return GImGui->CurrentWindow->Scroll.x; } float ImGui::GetScrollY() { return GImGui->CurrentWindow->Scroll.y; } float ImGui::GetScrollMaxX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; } float ImGui::GetScrollMaxY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; } void ImGui::SetScrollX(float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; } void ImGui::SetScrollY(float scroll_y) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY window->ScrollTargetCenterRatio.y = 0.0f; } void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) window->ScrollTarget.y = 0.0f; window->ScrollTargetCenterRatio.y = center_y_ratio; } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHere(float center_y_ratio) { ImGuiWindow* window = GetCurrentWindow(); float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); } void ImGui::SetKeyboardFocusHere(int offset) { ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; window->FocusIdxTabRequestNext = INT_MAX; } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GetCurrentWindow(); window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextUnformatted(g.TempBuffer, text_end); } void ImGui::Text(const char* fmt, ...) { va_list args; va_start(args, fmt); TextV(fmt, args); va_end(args); } void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); TextColoredV(col, fmt, args); va_end(args); } void ImGui::TextDisabledV(const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); TextV(fmt, args); PopStyleColor(); } void ImGui::TextDisabled(const char* fmt, ...) { va_list args; va_start(args, fmt); TextDisabledV(fmt, args); va_end(args); } void ImGui::TextWrappedV(const char* fmt, va_list args) { bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set if (need_wrap) PushTextWrapPos(0.0f); TextV(fmt, args); if (need_wrap) PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); TextWrappedV(fmt, args); va_end(args); } void ImGui::TextUnformatted(const char* text, const char* text_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = wrap_pos_x >= 0.0f; if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. const char* line = text; const float line_height = GetTextLineHeight(); const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); if (text_pos.y <= clip_rect.Max.y) { ImVec2 pos = text_pos; // Lines to skip (can't skip when logging text) if (!g.LogEnabled) { int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } } // Lines to render if (line < text_end) { ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); if (IsClippedEx(line_rect, NULL, false)) break; const ImVec2 line_size = CalcTextSize(line, line_end, false); text_size.x = ImMax(text_size.x, line_size.x); RenderText(pos, line, line_end, false); if (!line_end) line_end = text_end; line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; pos.y += line_height; } // Count remaining lines int lines_skipped = 0; while (line < text_end) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } text_size.y += (pos - text_pos).y; } ImRect bb(text_pos, text_pos + text_size); ItemSize(bb); ItemAdd(bb, NULL); } else { const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); // Account of baseline offset ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, NULL)) return; // Render (we don't hide text after ## in this end-user function) RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); } } void ImGui::AlignFirstTextHeightToWidgets() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. ImGuiContext& g = *GImGui; ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); SameLine(0, 0); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Render const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); LabelTextV(label, fmt, args); va_end(args); } static inline bool IsWindowContentHoverable(ImGuiWindow* window) { // An active popup disable hovering on other windows (apart from its own children) ImGuiContext& g = *GImGui; if (ImGuiWindow* focused_window = g.FocusedWindow) if (ImGuiWindow* focused_root_window = focused_window->RootWindow) if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) return false; return true; } bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (flags & ImGuiButtonFlags_Disabled) { if (out_hovered) *out_hovered = false; if (out_held) *out_held = false; if (g.ActiveId == id) ClearActiveID(); return false; } if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) flags |= ImGuiButtonFlags_PressedOnClickRelease; bool pressed = false; bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); if (hovered) { SetHoveredID(id); if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> .. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release) // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> .. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { SetActiveID(id, window); // Hold on ID FocusWindow(window); g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; } if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; ClearActiveID(); FocusWindow(window); } if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) { if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> pressed = true; ClearActiveID(); } // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) pressed = true; } } bool held = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { held = true; } else { if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> pressed = true; ClearActiveID(); } } // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) hovered = pressed = held = false; if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); return pressed; } bool ImGui::Button(const char* label, const ImVec2& size_arg) { return ButtonEx(label, size_arg, 0); } // Small buttons fits within text without additional vertical spacing. bool ImGui::SmallButton(const char* label) { ImGuiContext& g = *GImGui; float backup_padding_y = g.Style.FramePadding.y; g.Style.FramePadding.y = 0.0f; bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); g.Style.FramePadding.y = backup_padding_y; return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiID id = window->GetID(str_id); ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } // Upper-right button to close a window. bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiWindow* window = GetCurrentWindow(); const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); const ImVec2 center = bb.GetCenter(); window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); const float cross_extent = (radius * 0.7071f) - 1.0f; if (hovered) { window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); } return pressed; } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); if (border_col.w > 0.0f) bb.Max += ImVec2(2,2); ItemSize(bb); if (!ItemAdd(bb, NULL)) return; if (border_col.w > 0.0f) { window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); } else { window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); } } // frame_padding < 0: uses FramePadding from style (default) // frame_padding = 0: no framing // frame_padding > 0: set framing size // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = stdout; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); if (!filename) { filename = g.IO.LogFilename; if (!filename) return; } g.LogFile = ImFileOpen(filename, "ab"); if (!g.LogFile) { IM_ASSERT(g.LogFile != NULL); // Consider this an error return; } g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = NULL; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } void ImGui::LogFinish() { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; LogText(IM_NEWLINE); g.LogEnabled = false; if (g.LogFile != NULL) { if (g.LogFile == stdout) fflush(g.LogFile); else fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard->size() > 1) { SetClipboardText(g.LogClipboard->begin()); g.LogClipboard->clear(); } } // Helper to display logging buttons void ImGui::LogButtons() { ImGuiContext& g = *GImGui; PushID("LogButtons"); const bool log_to_tty = Button("Log To TTY"); SameLine(); const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushItemWidth(80.0f); PushAllowKeyboardFocus(false); SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); PopAllowKeyboardFocus(); PopItemWidth(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) LogToTTY(g.LogAutoExpandMaxDepth); if (log_to_file) LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); if (log_to_clipboard) LogToClipboard(g.LogAutoExpandMaxDepth); } bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { if (flags & ImGuiTreeNodeFlags_Leaf) return true; // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; bool is_open; if (g.SetNextTreeNodeOpenCond != 0) { if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) { is_open = g.SetNextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently. const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { is_open = g.SetNextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { is_open = stored_value != 0; } } g.SetNextTreeNodeOpenCond = 0; } else { is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). // NB- If we are above max depth we still allow manually opened nodes to be logged. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) is_open = true; return is_open; } bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); if (!label_end) label_end = FindRenderedTextEnd(label); const ImVec2 label_size = CalcTextSize(label, label_end, false); // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); bool is_open = TreeNodeBehaviorIsOpen(id, flags); if (!ItemAdd(interact_bb, &id)) { if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // Flags that affects opening behavior: // - 0(default) ..................... single-click anywhere to open // - OpenOnDoubleClick .............. double-click anywhere to open // - OpenOnArrow .................... single-click on arrow to open // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) { bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) toggled |= g.IO.MouseDoubleClicked[0]; if (toggled) { is_open = !is_open; window->DC.StateStorage->SetInt(id, is_open); } } if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) SetItemAllowOverlap(); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); if (display_frame) { // Framed type RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; const char log_suffix[] = "##"; LogRenderedText(text_pos, log_prefix, log_prefix+3); RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); LogRenderedText(text_pos, log_suffix+1, log_suffix+3); } else { RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) RenderFrame(bb.Min, bb.Max, col, false); if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); else if (!(flags & ImGuiTreeNodeFlags_Leaf)) RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f); if (g.LogEnabled) LogRenderedText(text_pos, ">"); RenderText(text_pos, label, label_end, false); } if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); return is_open; } // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); } bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (p_open && !*p_open) return false; ImGuiID id = window->GetID(label); bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); if (p_open) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. ImGuiContext& g = *GImGui; float button_sz = g.FontSize * 0.5f; if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) *p_open = false; } return is_open; } bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags, label, NULL); } bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) { return TreeNodeExV(str_id, 0, fmt, args); } bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { return TreeNodeExV(ptr_id, 0, fmt, args); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), 0, label, NULL); } void ImGui::TreeAdvanceToLabelPos() { ImGuiContext& g = *GImGui; g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); } // Horizontal distance preceding label when using TreeNode() or Bullet() float ImGui::GetTreeNodeToLabelSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + (g.Style.FramePadding.x * 2.0f); } void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) { ImGuiContext& g = *GImGui; g.SetNextTreeNodeOpenVal = is_open; g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::PushID(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PopID() { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* str_id) { return GImGui->CurrentWindow->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) { return GImGui->CurrentWindow->GetID(ptr_id); } void ImGui::Bullet() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); ItemSize(bb); if (!ItemAdd(bb, NULL)) { SameLine(0, style.FramePadding.x*2); return; } // Render and stay on same line RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); SameLine(0, style.FramePadding.x*2); } // Text with a little bullet aligned to the typical tree node. void ImGui::BulletTextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const char* text_begin = g.TempBuffer; const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding ItemSize(bb); if (!ItemAdd(bb, NULL)) return; // Render RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); } void ImGui::BulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); BulletTextV(fmt, args); va_end(args); } static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) { if (data_type == ImGuiDataType_Int) ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); else if (data_type == ImGuiDataType_Float) ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); } static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) { if (data_type == ImGuiDataType_Int) { if (decimal_precision < 0) ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); else ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); } else if (data_type == ImGuiDataType_Float) { if (decimal_precision < 0) ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? else ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); } } static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 { if (data_type == ImGuiDataType_Int) { if (op == '+') *(int*)value1 = *(int*)value1 + *(const int*)value2; else if (op == '-') *(int*)value1 = *(int*)value1 - *(const int*)value2; } else if (data_type == ImGuiDataType_Float) { if (op == '+') *(float*)value1 = *(float*)value1 + *(const float*)value2; else if (op == '-') *(float*)value1 = *(float*)value1 - *(const float*)value2; } } // User can input math operators (e.g. +100) to edit a numerical values. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) { while (ImCharIsSpace(*buf)) buf++; // We don't support '-' op because it would conflict with inputing negative value. // Instead you can use +-100 to subtract from an existing value char op = buf[0]; if (op == '+' || op == '*' || op == '/') { buf++; while (ImCharIsSpace(*buf)) buf++; } else { op = 0; } if (!buf[0]) return false; if (data_type == ImGuiDataType_Int) { if (!scalar_format) scalar_format = "%d"; int* v = (int*)data_ptr; const int old_v = *v; int arg0 = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) return false; // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision float arg1 = 0.0f; if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant return (old_v != *v); } else if (data_type == ImGuiDataType_Float) { // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in scalar_format = "%f"; float* v = (float*)data_ptr; const float old_v = *v; float arg0 = *v; if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) return false; float arg1 = 0.0f; if (sscanf(buf, scalar_format, &arg1) < 1) return false; if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) else if (op == '*') { *v = arg0 * arg1; } // Multiply else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide else { *v = arg1; } // Assign constant return (old_v != *v); } return false; } // Create text input in place of a slider (when CTRL+Clicking on slider) bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) SetActiveID(g.ScalarAsInputTextId, window); SetHoveredID(0); FocusableItemUnregister(window); char buf[32]; DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); if (g.ScalarAsInputTextId == 0) { // First frame IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) g.ScalarAsInputTextId = g.ActiveId; SetHoveredID(id); } else if (g.ActiveId != g.ScalarAsInputTextId) { // Release g.ScalarAsInputTextId = 0; } if (text_value_changed) return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); return false; } // Parse display precision back from the display format string int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) { int precision = default_precision; while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" while (*fmt >= '0' && *fmt <= '9') fmt++; if (*fmt == '.') { precision = atoi(fmt + 1); if (precision < 0 || precision > 10) precision = default_precision; } break; } return precision; } float ImGui::RoundScalar(float value, int decimal_precision) { // Round past decimal precision // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 // FIXME: Investigate better rounding methods static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); bool negative = value < 0.0f; value = fabsf(value); float remainder = fmodf(value, min_step); if (remainder <= min_step*0.5f) value -= remainder; else value += (min_step - remainder); return negative ? -value : value; } static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos) { if (v_min == v_max) return 0.0f; const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_non_linear) { if (v_clamped < 0.0f) { const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; } else { const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); } } // Linear slider return (v_clamped - v_min) / (v_max - v_min); } bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; const float grab_padding = 2.0f; const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); float grab_sz; if (decimal_precision > 0) grab_sz = ImMin(style.GrabMinSize, slider_sz); else grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f float linear_zero_pos = 0.0f; // 0.0->1.0f if (v_min * v_max < 0.0f) { // Different sign const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); } else { // Same sign linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } // Process clicking on the slider bool value_changed = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; if (!is_horizontal) clicked_t = 1.0f - clicked_t; float new_value; if (is_non_linear) { // Account for logarithmic scale on both sides of the zero if (clicked_t < linear_zero_pos) { // Negative: rescale to the negative range before powering float a = 1.0f - (clicked_t / linear_zero_pos); a = powf(a, power); new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); } else { // Positive: rescale to the positive range before powering float a; if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); else a = clicked_t; a = powf(a, power); new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); } } else { // Linear slider new_value = ImLerp(v_min, v_max, clicked_t); } // Round past decimal precision new_value = RoundScalar(new_value, decimal_precision); if (*v != new_value) { *v = new_value; value_changed = true; } } else { ClearActiveID(); } } // Calculate slider grab positioning float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); // Draw if (!is_horizontal) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); ImRect grab_bb; if (is_horizontal) grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); else grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); return value_changed; } // Use power!=1.0 for logarithmic sliders. // Adjust display_format to decorate the value with a prefix or a suffix. // "%.3f" 1.234 // "%5.2f secs" 01.23 secs // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) { SetActiveID(id, window); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual slider behavior + render grab const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(frame_bb, &id)) return false; const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); if (hovered && g.IO.MouseClicked[0]) { SetActiveID(id, window); FocusWindow(window); } // Actual slider behavior + render grab bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) { float v_deg = (*v_rad) * 360.0f / (2*IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); } bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); } bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 2, v_min, v_max, display_format); } bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 3, v_min, v_max, display_format); } bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 4, v_min, v_max, display_format); } bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; // Process clicking on the drag if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { if (g.ActiveIdIsJustActivated) { // Lock current value on click g.DragCurrentValue = *v; g.DragLastMouseDelta = ImVec2(0.f, 0.f); } float v_cur = g.DragCurrentValue; const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) { float speed = v_speed; if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) speed = (v_max - v_min) * g.DragSpeedDefaultRatio; if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) speed = speed * g.DragSpeedScaleFast; if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) speed = speed * g.DragSpeedScaleSlow; float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; if (fabsf(power - 1.0f) > 0.001f) { // Logarithmic curve on both side of 0.0 float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); float v1_abs = v1 >= 0.0f ? v1 : -v1; float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign } else { v_cur += delta; } g.DragLastMouseDelta.x = mouse_drag_delta.x; // Clamp if (v_min < v_max) v_cur = ImClamp(v_cur, v_min, v_max); g.DragCurrentValue = v_cur; } // Round to user desired precision, then apply v_cur = RoundScalar(v_cur, decimal_precision); if (*v != v_cur) { *v = v_cur; value_changed = true; } } else { ClearActiveID(); } } return value_changed; } bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) SetHoveredID(id); if (!display_format) display_format = "%.3f"; int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) { SetActiveID(id, window); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual drag behavior ItemSize(total_bb, style.FramePadding.y); const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); return value_changed; } bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); } bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); if (values_count > 0) { int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; if (IsHovered(inner_bb, 0)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); const int v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; const int v1_idx = (int)(t0 * item_count + 0.5f); IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); if (plot_type == ImGuiPlotType_Lines) { window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } else if (plot_type == ImGuiPlotType_Histogram) { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } t0 = t1; tp0 = tp1; } } // Text overlay if (overlay_text) RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; int Stride; ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, NULL)) return; // Render fraction = ImSaturate(fraction); RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); // Default displaying the fraction as percentage string, but user can override it char overlay_buf[32]; if (!overlay) { ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); overlay = overlay_buf; } ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); } bool ImGui::Checkbox(const char* label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); } if (!ItemAdd(total_bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding); } if (g.LogEnabled) LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = ((*flags & flags_value) == flags_value); bool pressed = Checkbox(label, &v); if (pressed) { if (v) *flags |= flags_value; else *flags &= ~flags_value; } return pressed; } bool ImGui::RadioButton(const char* label, bool active) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb.Add(text_bb); } if (!ItemAdd(total_bb, &id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (window->Flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); } if (g.LogEnabled) LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); if (label_size.x > 0.0f) RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); if (pressed) { *v = v_button; } return pressed; } static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) { int line_count = 0; const char* s = text_begin; while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding if (c == '\n') line_count++; s--; if (s[0] != '\n' && s[0] != '\r') line_count++; *out_text_end = s; return line_count; } static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) { ImFont* font = GImGui->Font; const float line_height = GImGui->FontSize; const float scale = line_height / font->FontSize; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const ImWchar* s = text_begin; while (s < text_end) { unsigned int c = (unsigned int)(*s++); if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; if (stop_on_new_line) break; continue; } if (c == '\r') continue; const float char_width = font->GetCharAdvance((unsigned short)c) * scale; line_width += char_width; } if (text_size.x < line_width) text_size.x = line_width; if (out_offset) *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n text_size.y += line_height; if (remaining) *remaining = s; return text_size; } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) namespace ImGuiStb { static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { const ImWchar* text = obj->Text.Data; const ImWchar* text_remaining = NULL; const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; r->num_chars = (int)(text_remaining - (text + line_start_idx)); } static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } #ifdef __APPLE__ // FIXME: Move setting to IO structure static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } #endif #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { ImWchar* dst = obj->Text.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text const ImWchar* src = obj->Text.Data + pos + n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { const int text_len = obj->CurLenW; IM_ASSERT(pos <= text_len); if (new_text_len + text_len + 1 > obj->Text.Size) return false; const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; ImWchar* text = obj->Text.Data; if (pos != text_len) memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->Text[obj->CurLenW] = '\0'; return true; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 #define STB_TEXTEDIT_IMPLEMENTATION #include "../stb/stb_textedit.h" } void ImGuiTextEditState::OnKeyPressed(int key) { stb_textedit_key(this, &StbState, key); CursorFollow = true; CursorAnimReset(); } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) // FIXME: The existence of this rarely exercised code path is a bit of a nuisance. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) { IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen -= bytes_count; } void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); if (new_text_len + BufTextLen + 1 >= BufSize) return; if (BufTextLen != pos) memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); Buf[BufTextLen + new_text_len] = '\0'; if (CursorPos >= pos) CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen += new_text_len; } // Return false to discard a character. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) { bool pass = false; pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); if (!pass) return false; } if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) { if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsSpace(c)) return false; } if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; *p_char = callback_data.EventChar; if (!callback_data.EventChar) return false; } return true; } // Edit a string of text // NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. // FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) ImGuiContext& g = *GImGui; const ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); ImGuiWindow* draw_window = window; if (is_multiline) { if (!BeginChildFrame(id, frame_bb.GetSize())) { EndChildFrame(); EndGroup(); return false; } draw_window = GetCurrentWindow(); size.x -= draw_window->ScrollbarSizes.x; } else { ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; } // Password pushes a temporary font with only a fallback glyph if (is_password) { const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); ImFont* password_font = &g.InputTextPasswordFont; password_font->FontSize = g.Font->FontSize; password_font->Scale = g.Font->Scale; password_font->DisplayOffset = g.Font->DisplayOffset; password_font->Ascent = g.Font->Ascent; password_font->Descent = g.Font->Descent; password_font->ContainerAtlas = g.Font->ContainerAtlas; password_font->FallbackGlyph = glyph; password_font->FallbackXAdvance = glyph->XAdvance; IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); PushFont(password_font); } // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiTextEditState& edit_state = g.InputTextState; const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; if (focus_requested || user_clicked || user_scrolled) { if (g.ActiveId != id) { // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) const int prev_len_w = edit_state.CurLenW; edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size); const char* buf_end = NULL; edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. edit_state.CursorAnimReset(); // Preserve cursor position and undo/redo stack if we come back to same widget // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. edit_state.CursorClamp(); } else { edit_state.Id = id; edit_state.ScrollX = 0.0f; stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); if (!is_multiline && focus_requested_by_code) select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) edit_state.StbState.insert_mode = true; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } SetActiveID(id, window); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) ClearActiveID(); } bool value_changed = false; bool enter_pressed = false; if (g.ActiveId == id) { if (!is_editable && !g.ActiveIdIsJustActivated) { // When read-only we always use the live data passed to the function edit_state.Text.resize(buf_size+1); const char* buf_end = NULL; edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); edit_state.CurLenA = (int)(buf_end - buf); edit_state.CursorClamp(); } edit_state.BufSizeA = buf_size; // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = !io.MouseDown[0]; // Edit in progress const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0])) { edit_state.SelectAll(); edit_state.SelectedAllMouseLock = true; } else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0]) { // Select a word only, OS X style (by simulating keystrokes) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); } else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) { stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); } else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); edit_state.CursorFollow = true; } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; if (io.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. if (!(io.KeyCtrl && !io.KeyAlt) && is_editable) { for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) if (unsigned int c = (unsigned int)io.InputCharacters[n]) { // Insert character if they pass filtering if (!InputTextFilterCharacter(&c, flags, callback, user_data)) continue; edit_state.OnKeyPressed((int)c); } } // Consume characters memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } // Handle various key-presses bool cancel_edit = false; const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) { if (!edit_state.HasSelection()) { if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); } edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Enter)) { bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) { ClearActiveID(); enter_pressed = true; } else if (is_editable) { unsigned int c = '\n'; // Insert new line if (InputTextFilterCharacter(&c, flags, callback, user_data)) edit_state.OnKeyPressed((int)c); } } else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&c, flags, callback, user_data)) edit_state.OnKeyPressed((int)c); } else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) { // Cut, Copy const bool cut = IsKeyPressedMap(ImGuiKey_X); if (cut && !edit_state.HasSelection()) edit_state.SelectAll(); if (io.SetClipboardTextFn) { const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); SetClipboardText(edit_state.TempTextBuffer.Data); } if (cut) { edit_state.CursorFollow = true; stb_textedit_cut(&edit_state, &edit_state.StbState); } } else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) { // Paste if (const char* clipboard = GetClipboardText()) { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { unsigned int c; s += ImTextCharFromUtf8(&c, s, NULL); if (c == 0) break; if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) continue; clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; } clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); edit_state.CursorFollow = true; } ImGui::MemFree(clipboard_filtered); } } if (cancel_edit) { // Restore initial value if (is_editable) { ImStrncpy(buf, edit_state.InitialText.Data, buf_size); value_changed = true; } } else { // Apply new value immediately - copy modified buffer back // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (is_editable) { edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); } // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. ImGuiInputTextFlags event_flag = 0; ImGuiKey event_key = ImGuiKey_COUNT; if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) { event_flag = ImGuiInputTextFlags_CallbackCompletion; event_key = ImGuiKey_Tab; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_UpArrow; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } else if (flags & ImGuiInputTextFlags_CallbackAlways) event_flag = ImGuiInputTextFlags_CallbackAlways; if (event_flag) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = event_flag; callback_data.Flags = flags; callback_data.UserData = user_data; callback_data.ReadOnly = !is_editable; callback_data.EventKey = event_key; callback_data.Buf = edit_state.TempTextBuffer.Data; callback_data.BufTextLen = edit_state.CurLenA; callback_data.BufSize = edit_state.BufSizeA; callback_data.BufDirty = false; // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) ImWchar* text = edit_state.Text.Data; const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); // Call user code callback(&callback_data); // Read back what user may have modified IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); if (callback_data.BufDirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() edit_state.CursorAnimReset(); } } } // Copy back to user buffer if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) { ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); value_changed = true; } } } // Render // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL; if (!is_multiline) RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.f, 0.f); const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); if (g.ActiveId == id || is_currently_scrolling) { edit_state.CursorAnim += io.DeltaTime; // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. const ImWchar* text_begin = edit_state.Text.Data; ImVec2 cursor_offset, select_start_offset; { // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. const ImWchar* searches_input_ptr[2]; searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; searches_input_ptr[1] = NULL; int searches_remaining = 1; int searches_result_line_number[2] = { -1, -999 }; if (edit_state.StbState.select_start != edit_state.StbState.select_end) { searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); searches_result_line_number[1] = -1; searches_remaining++; } // Iterate all lines to find our line numbers // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. searches_remaining += is_multiline ? 1 : 0; int line_count = 0; for (const ImWchar* s = text_begin; *s != 0; s++) if (*s == '\n') { line_count++; if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; cursor_offset.y = searches_result_line_number[0] * g.FontSize; if (searches_result_line_number[1] >= 0) { select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; select_start_offset.y = searches_result_line_number[1] * g.FontSize; } // Calculate text height if (is_multiline) text_size = ImVec2(size.x, line_count * g.FontSize); } // Scroll if (edit_state.CursorFollow) { // Horizontal scroll in chunks of quarter width if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) { const float scroll_increment_x = size.x * 0.25f; if (cursor_offset.x < edit_state.ScrollX) edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); else if (cursor_offset.x - size.x >= edit_state.ScrollX) edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); } else { edit_state.ScrollX = 0.0f; } // Vertical scroll if (is_multiline) { float scroll_y = draw_window->Scroll.y; if (cursor_offset.y - g.FontSize < scroll_y) scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - size.y >= scroll_y) scroll_y = cursor_offset.y - size.y; draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag draw_window->Scroll.y = scroll_y; render_pos.y = draw_window->DC.CursorPos.y; } } edit_state.CursorFollow = false; const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); // Draw selection if (edit_state.StbState.select_start != edit_state.StbState.select_end) { const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) { if (rect_pos.y > clip_rect.w + g.FontSize) break; if (rect_pos.y < clip_rect.y) { while (p < text_selected_end) if (*p++ == '\n') break; } else { ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); rect.Clip(clip_rect); if (rect.Overlaps(clip_rect)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } rect_pos.x = render_pos.x - render_scroll.x; rect_pos.y += g.FontSize; } } draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) if (is_editable) g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); } else { // Render text only const char* buf_end = NULL; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); } if (is_multiline) { Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line EndChildFrame(); EndGroup(); } if (is_password) PopFont(); // Log as text if (g.LogEnabled && !is_password) LogRenderedText(render_pos, buf_display, NULL); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else return value_changed; } bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); } bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); } // NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImVec2 label_size = CalcTextSize(label, NULL, true); BeginGroup(); PushID(label); const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; if (step_ptr) PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); char buf[64]; DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); bool value_changed = false; if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) extra_flags |= ImGuiInputTextFlags_CharsDecimal; extra_flags |= ImGuiInputTextFlags_AutoSelectAll; if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); // Step buttons if (step_ptr) { PopItemWidth(); SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) { DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); value_changed = true; } SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) { DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); value_changed = true; } } PopID(); if (label_size.x > 0) { SameLine(0, style.ItemInnerSpacing.x); RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); ItemSize(label_size, style.FramePadding.y); } EndGroup(); return value_changed; } bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) { char display_format[16]; if (decimal_precision < 0) strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 else ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision); return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); } bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); } bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 2, decimal_precision, extra_flags); } bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 3, decimal_precision, extra_flags); } bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) { return InputFloatN(label, v, 4, decimal_precision, extra_flags); } bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { PushID(i); value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); } PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); TextUnformatted(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 2, extra_flags); } bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 3, extra_flags); } bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) { return InputIntN(label, v, 4, extra_flags); } static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { const char* const* items = (const char* const*)data; if (out_text) *out_text = items[idx]; return true; } static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. const char* items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) { if (idx == items_count) break; p += strlen(p) + 1; items_count++; } if (!*p) return false; if (out_text) *out_text = p; return true; } // Combo box helper allowing to pass an array of strings. bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items) { const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); return value_changed; } // Combo box helper allowing to pass all items in a single string. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { p += strlen(p) + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); return value_changed; } // Combo box function. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); const bool hovered = IsHovered(frame_bb, id); bool popup_open = IsPopupOpen(id); bool popup_opened_now = false; const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); if (*current_item >= 0 && *current_item < items_count) { const char* item_text; if (items_getter(data, *current_item, &item_text)) RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f)); } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if (hovered) { SetHoveredID(id); if (g.IO.MouseClicked[0]) { ClearActiveID(); if (IsPopupOpen(id)) { ClosePopup(id); } else { FocusWindow(window); OpenPopup(label); popup_open = popup_opened_now = true; } } } bool value_changed = false; if (IsPopupOpen(id)) { // Size default to hold ~7 items if (height_in_items < 0) height_in_items = 7; float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); float popup_y1 = frame_bb.Max.y; float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) { // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); popup_y2 = frame_bb.Min.y; } ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); SetNextWindowPos(popup_rect.Min); SetNextWindowSize(popup_rect.GetSize()); PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); if (BeginPopupEx(label, flags)) { // Display items Spacing(); for (int i = 0; i < items_count; i++) { PushID((void*)(intptr_t)i); const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; if (Selectable(item_text, item_selected)) { ClearActiveID(); value_changed = true; *current_item = i; } if (item_selected && popup_opened_now) SetScrollHere(); PopID(); } EndPopup(); } PopStyleVar(); } return value_changed; } // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) PopClipRect(); ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb(pos, pos + size); ItemSize(bb); // Fill horizontal space. ImVec2 window_padding = window->WindowPadding; float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); ImRect bb_with_spacing(pos, pos + size_draw); if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) bb_with_spacing.Max.x += window_padding.x; // Selectables are tightly packed together, we extend the box to cover spacing between selectable. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); float spacing_R = style.ItemSpacing.x - spacing_L; float spacing_D = style.ItemSpacing.y - spacing_U; bb_with_spacing.Min.x -= spacing_L; bb_with_spacing.Min.y -= spacing_U; bb_with_spacing.Max.x += spacing_R; bb_with_spacing.Max.y += spacing_D; if (!ItemAdd(bb_with_spacing, &id)) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) PushColumnClipRect(); return false; } ImGuiButtonFlags button_flags = 0; if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; bool hovered, held; bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); if (flags & ImGuiSelectableFlags_Disabled) selected = false; // Render if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); } if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) { PushColumnClipRect(); bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); } if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) CloseCurrentPopup(); return pressed; } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; } return false; } // Helper to calculate the size of a listbox and display a label on the right. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = GetStyle(); const ImGuiID id = GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); BeginChildFrame(id, frame_bb.GetSize()); return true; } bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) { // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. if (height_in_items < 0) height_in_items = ImMin(items_count, 7); float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; return ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetParentWindow(); const ImRect bb = parent_window->DC.LastItemRect; const ImGuiStyle& style = GetStyle(); EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items) { const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); return value_changed; } bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { if (!ListBoxHeader(label, items_count, height_in_items)) return false; // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. bool value_changed = false; ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; PushID(i); if (Selectable(item_text, item_selected)) { *current_item = i; value_changed = true; } PopID(); } ListBoxFooter(); return value_changed; } bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImVec2 pos = window->DC.CursorPos; ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); if (shortcut_size.x > 0.0f) { PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); PopStyleColor(); } if (selected) RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); return pressed; } bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) { if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) { if (p_selected) *p_selected = !*p_selected; return true; } return false; } bool ImGui::BeginMainMenuBar() { ImGuiContext& g = *GImGui; SetNextWindowPos(ImVec2(0.0f, 0.0f)); SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) || !BeginMenuBar()) { End(); PopStyleVar(2); return false; } g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; return true; } void ImGui::EndMainMenuBar() { EndMenuBar(); End(); PopStyleVar(2); } bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (!(window->Flags & ImGuiWindowFlags_MenuBar)) return false; IM_ASSERT(!window->DC.MenuBarAppending); BeginGroup(); // Save position PushID("##menubar"); ImRect rect = window->MenuBarRect(); PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.MenuBarAppending = true; AlignFirstTextHeightToWidgets(); return true; } void ImGui::EndMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); IM_ASSERT(window->DC.MenuBarAppending); PopClipRect(); PopID(); window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; window->DC.GroupStack.back().AdvanceCursor = false; EndGroup(); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.MenuBarAppending = false; } bool ImGui::BeginMenu(const char* label, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); ImGuiWindow* backed_focused_window = g.FocusedWindow; bool pressed; bool menu_is_open = IsPopupOpen(id); bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); if (menuset_is_open) g.FocusedWindow = window; // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos). ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); float w = label_size.x; pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); PopStyleVar(); SameLine(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); } else { popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); if (!enabled) PopStyleColor(); } bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); if (menuset_is_open) g.FocusedWindow = backed_focused_window; bool want_open = false, want_close = false; if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) { // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. bool moving_within_opened_triangle = false; if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) { if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) { ImRect next_window_rect = next_window->Rect(); ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug } } want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); } else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close { want_close = true; want_open = menu_is_open = false; } else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others want_open = true; if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true; if (want_close && IsPopupOpen(id)) ClosePopupToLevel(GImGui->CurrentPopupStack.Size); if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) { // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. OpenPopup(label); return false; } menu_is_open |= want_open; if (want_open) OpenPopup(label); if (menu_is_open) { SetNextWindowPos(popup_pos, ImGuiSetCond_Always); ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) } return menu_is_open; } void ImGui::EndMenu() { EndPopup(); } // A little colored square. Return true when clicked. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#colorbutton"); const float square_size = g.FontSize; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); if (hovered) SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.w)); return pressed; } bool ImGui::ColorEdit3(const char* label, float col[3]) { float col4[4]; col4[0] = col[0]; col4[1] = col[1]; col4[2] = col[2]; col4[3] = 1.0f; const bool value_changed = ColorEdit4(label, col4, false); col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; return value_changed; } // Edit colors components (each component in 0.0f..1.0f range // Use CTRL-Click to input value and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w_full = CalcItemWidth(); const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; float f[4] = { col[0], col[1], col[2], col[3] }; if (edit_mode == ImGuiColorEditMode_HSV) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; int components = alpha ? 4 : 3; bool value_changed = false; BeginGroup(); PushID(label); const bool hsv = (edit_mode == 1); switch (edit_mode) { case ImGuiColorEditMode_RGB: case ImGuiColorEditMode_HSV: { // RGB/HSV 0..255 Sliders const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; const char* fmt_table[3][4] = { { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } }; const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) PushItemWidth(w_item_last); value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); } PopItemWidth(); PopItemWidth(); } break; case ImGuiColorEditMode_HEX: { // RGB Hexadecimal Input const float w_slider_all = w_full - square_sz; char buf[64]; if (alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed |= true; char* p = buf; while (*p == '#' || ImCharIsSpace(*p)) p++; i[0] = i[1] = i[2] = i[3] = 0; if (alpha) sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) else sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } PopItemWidth(); } break; } SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_display(col[0], col[1], col[2], 1.0f); if (ColorButton(col_display)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here if (IsItemHovered()) SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3])); if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) { SameLine(0, style.ItemInnerSpacing.x); const char* button_titles[3] = { "RGB", "HSV", "HEX" }; if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! } const char* label_display_end = FindRenderedTextEnd(label); if (label != label_display_end) { SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); TextUnformatted(label, label_display_end); } // Convert back for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (edit_mode == 1) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { col[0] = f[0]; col[1] = f[1]; col[2] = f[2]; if (alpha) col[3] = f[3]; } PopID(); EndGroup(); return value_changed; } void ImGui::ColorEditMode(ImGuiColorEditMode mode) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ColorEditMode = mode; } // Horizontal separating line. void ImGui::Separator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.ColumnsCount > 1) PopClipRect(); float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; if (!window->DC.GroupStack.empty()) x1 += window->DC.IndentX; const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. if (!ItemAdd(bb, NULL)) { if (window->DC.ColumnsCount > 1) PushColumnClipRect(); return; } window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border)); ImGuiContext& g = *GImGui; if (g.LogEnabled) LogText(IM_NEWLINE "--------------------------------"); if (window->DC.ColumnsCount > 1) { PushColumnClipRect(); window->DC.ColumnsCellMinY = window->DC.CursorPos.y; } } void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); } void ImGui::Dummy(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); ItemAdd(bb, NULL); } bool ImGui::IsRectVisible(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) void ImGui::BeginGroup() { ImGuiWindow* window = GetCurrentWindow(); window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndentX = window->DC.IndentX; group_data.BackupGroupOffsetX = window->DC.GroupOffsetX; group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupLogLinePosY = window->DC.LogLinePosY; group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive; group_data.AdvanceCursor = true; window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; window->DC.IndentX = window->DC.GroupOffsetX; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineHeight = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. group_bb.Max = ImMax(group_bb.Min, group_bb.Max); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; window->DC.IndentX = group_data.BackupIndentX; window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; if (group_data.AdvanceCursor) { window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); ItemAdd(group_bb, NULL); } // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context. const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow); if (active_id_within_group) window->DC.LastItemId = g.ActiveId; if (active_id_within_group && g.HoveredId == g.ActiveId) window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true; window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug } // Gets back to previous line and continue with horizontal layout // pos_x == 0 : follow right after previous item // pos_x != 0 : align to specified x position (relative to window/group left) // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 // spacing_w >= 0 : enforce spacing amount void ImGui::SameLine(float pos_x, float spacing_w) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; if (pos_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineHeight = window->DC.PrevLineHeight; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; } void ImGui::NewLine() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ItemSize(ImVec2(0,0)); else ItemSize(ImVec2(0.0f, GImGui->FontSize)); } void ImGui::NextColumn() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems || window->DC.ColumnsCount <= 1) return; ImGuiContext& g = *GImGui; PopItemWidth(); PopClipRect(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) { // Columns 1+ cancel out IndentX window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); } else { window->DC.ColumnsCurrent = 0; window->DC.ColumnsOffsetX = 0.0f; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; window->DrawList->ChannelsSetCurrent(0); } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); window->DC.CursorPos.y = window->DC.ColumnsCellMinY; window->DC.CurrentLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(); PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup } int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCurrent; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCount; } static float GetDraggedColumnOffset(int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. ImGuiContext& g = *GImGui; ImGuiWindow* window = ImGui::GetCurrentWindowRead(); IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index)); float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); return (float)(int)x; } float ImGui::GetColumnOffset(int column_index) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; if (g.ActiveId) { const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); if (g.ActiveId == column_id) return GetDraggedColumnOffset(column_index); } IM_ASSERT(column_index < window->DC.ColumnsData.Size); const float t = window->DC.ColumnsData[column_index].OffsetNorm; const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); return (float)(int)x_offset; } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; IM_ASSERT(column_index < window->DC.ColumnsData.Size); const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); window->DC.ColumnsData[column_index].OffsetNorm = t; const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); window->DC.StateStorage->SetFloat(column_id, t); } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); return w; } static void PushColumnClipRect(int column_index) { ImGuiWindow* window = ImGui::GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); } void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); if (window->DC.ColumnsCount != 1) { if (window->DC.ColumnsCurrent != 0) ItemSize(ImVec2(0,0)); // Advance to column 0 PopItemWidth(); PopClipRect(); window->DrawList->ChannelsMerge(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; } // Draw columns borders and handle resize at the time of "closing" a columns set if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) { const float y1 = window->DC.ColumnsStartPosY; const float y2 = window->DC.CursorPos.y; for (int i = 1; i < window->DC.ColumnsCount; i++) { float x = window->Pos.x + GetColumnOffset(i); const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i); const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); if (IsClippedEx(column_rect, &column_id, false)) continue; bool hovered, held; ButtonBehavior(column_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; // Draw before resize so our items positioning are in sync with the line being drawn const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); if (held) { if (g.ActiveIdIsJustActivated) g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking) x = GetDraggedColumnOffset(i); SetColumnOffset(i, x); } } } // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. PushID(0x11223347 + (id ? 0 : columns_count)); window->DC.ColumnsSetId = window->GetID(id ? id : "columns"); PopID(); // Set state for first column window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = columns_count; window->DC.ColumnsShowBorders = border; const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); if (window->DC.ColumnsCount != 1) { // Cache column offsets window->DC.ColumnsData.resize(columns_count + 1); for (int column_index = 0; column_index < columns_count + 1; column_index++) { const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); KeepAliveID(column_id); const float default_t = column_index / (float)window->DC.ColumnsCount; const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?) window->DC.ColumnsData[column_index].OffsetNorm = t; } window->DrawList->ChannelsSplit(window->DC.ColumnsCount); PushColumnClipRect(); PushItemWidth(GetColumnWidth() * 0.65f); } else { window->DC.ColumnsData.resize(0); } } void ImGui::Indent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::Unindent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } void ImGui::TreePushRawID(ImGuiID id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; window->IDStack.push_back(id); } void ImGui::TreePop() { ImGuiWindow* window = GetCurrentWindow(); Unindent(); window->DC.TreeDepth--; PopID(); } void ImGui::Value(const char* prefix, bool b) { Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) { if (float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); Text(fmt, prefix, v); } else { Text("%s: %.3f", prefix, v); } } // FIXME: May want to remove those helpers? void ImGui::ValueColor(const char* prefix, const ImVec4& v) { Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); SameLine(); ColorButton(v, true); } void ImGui::ValueColor(const char* prefix, ImU32 v) { Text("%s: %08X", prefix, v); SameLine(); ColorButton(ColorConvertU32ToFloat4(v), true); } //----------------------------------------------------------------------------- // PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) #undef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // Win32 API clipboard implementation #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector<char> buf_local; buf_local.clear(); if (!OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) return NULL; if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) { int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local.resize(buf_len); ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } GlobalUnlock(wbuf_handle); CloseClipboard(); return buf_local.Data; } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) return; ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); GlobalUnlock(wbuf_handle); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, wbuf_handle); CloseClipboard(); } #else // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static const char* GetClipboardTextFn_DefaultImpl(void*) { return GImGui->PrivateClipboard; } // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } const char* text_end = text + strlen(text); g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) #include <imm.h> #ifdef _MSC_VER #pragma comment(lib, "imm32") #endif static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) if (HIMC himc = ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ImmSetCompositionWindow(himc, &cf); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- void ImGui::ShowMetricsWindow(bool* p_open) { if (ImGui::Begin("ImGui Metrics", p_open)) { ImGui::Text("ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); static bool show_clip_rects = true; ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) ImGui::TreePop(); return; } if (!node_open) return; ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list overlay_draw_list->PushClipRectFullScreen(); int elem_offset = 0; for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) { if (pcmd->UserCallback) { ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); if (show_clip_rects && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); } if (!pcmd_node_open) continue; ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { char buf[300], *buf_p = buf; ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, vtx_i++) { ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; triangles_pos[n] = v.pos; buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (ImGui::IsItemHovered()) overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle } ImGui::TreePop(); } overlay_draw_list->PopClipRect(); ImGui::TreePop(); } static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; for (int i = 0; i < windows.Size; i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) return; NodeDrawList(window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y); ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); ImGui::TreePop(); } }; ImGuiContext& g = *GImGui; // Access private state Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) { for (int i = 0; i < g.RenderDrawLists[0].Size; i++) Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); ImGui::TreePop(); } if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } ImGui::TreePop(); } if (ImGui::TreeNode("Basic state")) { ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); ImGui::TreePop(); } } ImGui::End(); } //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif //-----------------------------------------------------------------------------
[ "charles.mailly@free.fr" ]
charles.mailly@free.fr
bcce85db6fe9a57928d011bb51d3c758d4f38a5a
19845af1616d5b81aedf7917a32cb44f61e02401
/ProblemSet/TSOJ/1199最简真分数(最大公约数/源.cpp
8cef25fe5469436c3cd5251efe8ceeaa3878e71b
[]
no_license
gsy3761/Pile
560c78d471c70f69324984703cf01cd7680a3fca
e6217be03679d978a7a41b01dbb0baa159c0deec
refs/heads/master
2020-12-21T04:04:31.661608
2020-01-23T13:16:05
2020-01-23T13:16:05
236,300,410
1
0
null
2020-01-26T11:05:01
2020-01-26T11:05:00
null
UTF-8
C++
false
false
2,347
cpp
#define _CRT_SECURE_NO_WARNINGS // shut up MS//NOT fo CPP//scanf VS. scanf_s //#define DEBUG #include <algorithm> #include <ctype.h> #include <fstream> //file #include <iostream> //stream #include <math.h> #include <sstream> //stringstream #include <stdio.h> #include <string.h> #include <string> // STL #include <map> #include <queue> #include <set> #include <stack> #include <vector> // STL #ifdef DEBUG # include <Windows.h> //sleep() # include <stdlib.h> //system("pause") #endif // DEBUG #define C(a) std::cout << #a << ":" << (a) << std::endl; // template <typename T> void swap(T &a, T &b) //{ // T t = a; // a = b; // b = t; //} using namespace std; using LL = long long; using ULL = unsigned long long; const int MAX_N = 999983; int n, m, a, b, j, k; ULL buffer[607]; ULL Q_pow(ULL a, ULL b) { ULL ans = 1; while(b != 0) { if(b & 1) { ans *= a; } a *= a; b >>= 1; } ans %= MAX_N; return ans; } ULL gcd(ULL a, ULL b) { while(a != b) { if(a > b) { a = (a - 1) % b + 1; } else { b = (b - 1) % a + 1; } } return b; } bool primeToEach(ULL a, ULL b) { if(a == b) { return false; } if(a > b) { swap(a, b); } return gcd(a, b) == 1; } int main(void) { #ifdef DEBUG std::fstream fin; fin.open("./in.txt", std::ios::in); std::cin.rdbuf(fin.rdbuf()); #endif // DEBUG while(std::cin >> n) { if(n == 0) return 0; int count = 0; for(int i = 0; i < n; i++) { std::cin >> buffer[i]; } sort(buffer, buffer + n); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { if(primeToEach(buffer[i], buffer[j])) { count++; // cout << "yes:"; } // else //{ // cout << "no:"; //} // cout << buffer[i] << " " << buffer[j] << std::endl; } } std::cout << count << std::endl; } #ifdef DEBUG system("pause"); Sleep(-1); #endif // DEBUG return 0; }
[ "1395943920@qq.com" ]
1395943920@qq.com
b1027528a4e5ec2a6b3aeddbf28fdb9d89296ae4
6f49cc2d5112a6b97f82e7828f59b201ea7ec7b9
/wdbecmbd/CrdWdbeUnt/PnlWdbeUntHk1NVector_blks.cpp
0f9b14f87cf3498a329eca053a2e2591a478f8cc
[ "MIT" ]
permissive
mpsitech/wdbe-WhizniumDBE
d3702800d6e5510e41805d105228d8dd8b251d7a
89ef36b4c86384429f1e707e5fa635f643e81240
refs/heads/master
2022-09-28T10:27:03.683192
2022-09-18T22:04:37
2022-09-18T22:04:37
282,705,449
5
0
null
null
null
null
UTF-8
C++
false
false
18,710
cpp
/** * \file PnlWdbeUntHk1NVector_blks.cpp * job handler for job PnlWdbeUntHk1NVector (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWdbeUntHk1NVector::VecVDo ******************************************************************************/ uint PnlWdbeUntHk1NVector::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butviewclick") return BUTVIEWCLICK; if (s == "butnewclick") return BUTNEWCLICK; if (s == "butdeleteclick") return BUTDELETECLICK; if (s == "butrefreshclick") return BUTREFRESHCLICK; return(0); }; string PnlWdbeUntHk1NVector::VecVDo::getSref( const uint ix ) { if (ix == BUTVIEWCLICK) return("ButViewClick"); if (ix == BUTNEWCLICK) return("ButNewClick"); if (ix == BUTDELETECLICK) return("ButDeleteClick"); if (ix == BUTREFRESHCLICK) return("ButRefreshClick"); return(""); }; /****************************************************************************** class PnlWdbeUntHk1NVector::ContInf ******************************************************************************/ PnlWdbeUntHk1NVector::ContInf::ContInf( const uint numFCsiQst ) : Block() { this->numFCsiQst = numFCsiQst; mask = {NUMFCSIQST}; }; void PnlWdbeUntHk1NVector::ContInf::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfWdbeUntHk1NVector"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["numFCsiQst"] = numFCsiQst; }; void PnlWdbeUntHk1NVector::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfWdbeUntHk1NVector"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfWdbeUntHk1NVector"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFCsiQst", numFCsiQst); xmlTextWriterEndElement(wr); }; set<uint> PnlWdbeUntHk1NVector::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST); return(items); }; set<uint> PnlWdbeUntHk1NVector::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFCSIQST}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntHk1NVector::StatApp ******************************************************************************/ void PnlWdbeUntHk1NVector::StatApp::writeJSON( Json::Value& sup , string difftag , const uint ixWdbeVExpstate ) { if (difftag.length() == 0) difftag = "StatAppWdbeUntHk1NVector"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["srefIxWdbeVExpstate"] = VecWdbeVExpstate::getSref(ixWdbeVExpstate); }; void PnlWdbeUntHk1NVector::StatApp::writeXML( xmlTextWriter* wr , string difftag , bool shorttags , const uint ixWdbeVExpstate ) { if (difftag.length() == 0) difftag = "StatAppWdbeUntHk1NVector"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemAppWdbeUntHk1NVector"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "srefIxWdbeVExpstate", VecWdbeVExpstate::getSref(ixWdbeVExpstate)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWdbeUntHk1NVector::StatShr ******************************************************************************/ PnlWdbeUntHk1NVector::StatShr::StatShr( const bool ButViewAvail , const bool ButViewActive , const bool ButNewAvail , const bool ButDeleteAvail , const bool ButDeleteActive ) : Block() { this->ButViewAvail = ButViewAvail; this->ButViewActive = ButViewActive; this->ButNewAvail = ButNewAvail; this->ButDeleteAvail = ButDeleteAvail; this->ButDeleteActive = ButDeleteActive; mask = {BUTVIEWAVAIL, BUTVIEWACTIVE, BUTNEWAVAIL, BUTDELETEAVAIL, BUTDELETEACTIVE}; }; void PnlWdbeUntHk1NVector::StatShr::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrWdbeUntHk1NVector"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["ButViewAvail"] = ButViewAvail; me["ButViewActive"] = ButViewActive; me["ButNewAvail"] = ButNewAvail; me["ButDeleteAvail"] = ButDeleteAvail; me["ButDeleteActive"] = ButDeleteActive; }; void PnlWdbeUntHk1NVector::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrWdbeUntHk1NVector"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrWdbeUntHk1NVector"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ButViewAvail", ButViewAvail); writeBoolAttr(wr, itemtag, "sref", "ButViewActive", ButViewActive); writeBoolAttr(wr, itemtag, "sref", "ButNewAvail", ButNewAvail); writeBoolAttr(wr, itemtag, "sref", "ButDeleteAvail", ButDeleteAvail); writeBoolAttr(wr, itemtag, "sref", "ButDeleteActive", ButDeleteActive); xmlTextWriterEndElement(wr); }; set<uint> PnlWdbeUntHk1NVector::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButViewAvail == comp->ButViewAvail) insert(items, BUTVIEWAVAIL); if (ButViewActive == comp->ButViewActive) insert(items, BUTVIEWACTIVE); if (ButNewAvail == comp->ButNewAvail) insert(items, BUTNEWAVAIL); if (ButDeleteAvail == comp->ButDeleteAvail) insert(items, BUTDELETEAVAIL); if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE); return(items); }; set<uint> PnlWdbeUntHk1NVector::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTVIEWAVAIL, BUTVIEWACTIVE, BUTNEWAVAIL, BUTDELETEAVAIL, BUTDELETEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntHk1NVector::StgIac ******************************************************************************/ PnlWdbeUntHk1NVector::StgIac::StgIac( const uint TcoRefWidth ) : Block() { this->TcoRefWidth = TcoRefWidth; mask = {TCOREFWIDTH}; }; bool PnlWdbeUntHk1NVector::StgIac::readJSON( const Json::Value& sup , bool addbasetag ) { clear(); bool basefound; const Json::Value& me = [&]{if (!addbasetag) return sup; return sup["StgIacWdbeUntHk1NVector"];}(); basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("TcoRefWidth")) {TcoRefWidth = me["TcoRefWidth"].asUInt(); add(TCOREFWIDTH);}; }; return basefound; }; bool PnlWdbeUntHk1NVector::StgIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacWdbeUntHk1NVector"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StgitemIacWdbeUntHk1NVector"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoRefWidth", TcoRefWidth)) add(TCOREFWIDTH); }; return basefound; }; void PnlWdbeUntHk1NVector::StgIac::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StgIacWdbeUntHk1NVector"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["TcoRefWidth"] = TcoRefWidth; }; void PnlWdbeUntHk1NVector::StgIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StgIacWdbeUntHk1NVector"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StgitemIacWdbeUntHk1NVector"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "TcoRefWidth", TcoRefWidth); xmlTextWriterEndElement(wr); }; set<uint> PnlWdbeUntHk1NVector::StgIac::comm( const StgIac* comp ) { set<uint> items; if (TcoRefWidth == comp->TcoRefWidth) insert(items, TCOREFWIDTH); return(items); }; set<uint> PnlWdbeUntHk1NVector::StgIac::diff( const StgIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TCOREFWIDTH}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWdbeUntHk1NVector::Tag ******************************************************************************/ void PnlWdbeUntHk1NVector::Tag::writeJSON( const uint ixWdbeVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagWdbeUntHk1NVector"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWdbeVLocale == VecWdbeVLocale::ENUS) { me["Cpt"] = "Vectors"; me["TcoRef"] = "Vector"; }; me["TxtRecord1"] = StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::REC, ixWdbeVLocale)); me["TxtRecord2"] = StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::EMPLONG, ixWdbeVLocale)); me["Trs"] = StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::GOTO, ixWdbeVLocale)) + " ..."; me["TxtShowing1"] = VecWdbeVTag::getTitle(VecWdbeVTag::SHOWSHORT, ixWdbeVLocale); me["TxtShowing2"] = VecWdbeVTag::getTitle(VecWdbeVTag::EMPSHORT, ixWdbeVLocale); }; void PnlWdbeUntHk1NVector::Tag::writeXML( const uint ixWdbeVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagWdbeUntHk1NVector"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemWdbeUntHk1NVector"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWdbeVLocale == VecWdbeVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Vectors"); writeStringAttr(wr, itemtag, "sref", "TcoRef", "Vector"); }; writeStringAttr(wr, itemtag, "sref", "TxtRecord1", StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::REC, ixWdbeVLocale))); writeStringAttr(wr, itemtag, "sref", "TxtRecord2", StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::EMPLONG, ixWdbeVLocale))); writeStringAttr(wr, itemtag, "sref", "Trs", StrMod::cap(VecWdbeVTag::getTitle(VecWdbeVTag::GOTO, ixWdbeVLocale)) + " ..."); writeStringAttr(wr, itemtag, "sref", "TxtShowing1", VecWdbeVTag::getTitle(VecWdbeVTag::SHOWSHORT, ixWdbeVLocale)); writeStringAttr(wr, itemtag, "sref", "TxtShowing2", VecWdbeVTag::getTitle(VecWdbeVTag::EMPSHORT, ixWdbeVLocale)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWdbeUntHk1NVector::DpchAppData ******************************************************************************/ PnlWdbeUntHk1NVector::DpchAppData::DpchAppData() : DpchAppWdbe(VecWdbeVDpch::DPCHAPPWDBEUNTHK1NVECTORDATA) { }; string PnlWdbeUntHk1NVector::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeUntHk1NVector::DpchAppData::readJSON( const Json::Value& sup , bool addbasetag ) { clear(); bool basefound; const Json::Value& me = [&]{if (!addbasetag) return sup; return sup["DpchAppWdbeUntHk1NVectorData"];}(); basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (stgiac.readJSON(me, true)) add(STGIAC); if (stgiacqry.readJSON(me, true)) add(STGIACQRY); } else { stgiac = StgIac(); stgiacqry = QryWdbeUntHk1NVector::StgIac(); }; }; void PnlWdbeUntHk1NVector::DpchAppData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWdbeUntHk1NVectorData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC); if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY); } else { stgiac = StgIac(); stgiacqry = QryWdbeUntHk1NVector::StgIac(); }; }; /****************************************************************************** class PnlWdbeUntHk1NVector::DpchAppDo ******************************************************************************/ PnlWdbeUntHk1NVector::DpchAppDo::DpchAppDo() : DpchAppWdbe(VecWdbeVDpch::DPCHAPPWDBEUNTHK1NVECTORDO) { ixVDo = 0; }; string PnlWdbeUntHk1NVector::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeUntHk1NVector::DpchAppDo::readJSON( const Json::Value& sup , bool addbasetag ) { clear(); bool basefound; const Json::Value& me = [&]{if (!addbasetag) return sup; return sup["DpchAppWdbeUntHk1NVectorDo"];}(); basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (me.isMember("srefIxVDo")) {ixVDo = VecVDo::getIx(me["srefIxVDo"].asString()); add(IXVDO);}; } else { }; }; void PnlWdbeUntHk1NVector::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWdbeUntHk1NVectorDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlWdbeUntHk1NVector::DpchEngData ******************************************************************************/ PnlWdbeUntHk1NVector::DpchEngData::DpchEngData( const ubigint jref , ContInf* continf , Feed* feedFCsiQst , StatShr* statshr , StgIac* stgiac , ListWdbeQUntHk1NVector* rst , QryWdbeUntHk1NVector::StatShr* statshrqry , QryWdbeUntHk1NVector::StgIac* stgiacqry , const set<uint>& mask ) : DpchEngWdbe(VecWdbeVDpch::DPCHENGWDBEUNTHK1NVECTORDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTINF, FEEDFCSIQST, STATAPP, STATSHR, STGIAC, TAG, RST, STATAPPQRY, STATSHRQRY, STGIACQRY}; else this->mask = mask; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, FEEDFCSIQST) && feedFCsiQst) this->feedFCsiQst = *feedFCsiQst; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac; if (find(this->mask, RST) && rst) this->rst = *rst; if (find(this->mask, STATSHRQRY) && statshrqry) this->statshrqry = *statshrqry; if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry; }; string PnlWdbeUntHk1NVector::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(TAG)) ss.push_back("tag"); if (has(RST)) ss.push_back("rst"); if (has(STATAPPQRY)) ss.push_back("statappqry"); if (has(STATSHRQRY)) ss.push_back("statshrqry"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWdbeUntHk1NVector::DpchEngData::merge( DpchEngWdbe* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(FEEDFCSIQST)) {feedFCsiQst = src->feedFCsiQst; add(FEEDFCSIQST);}; if (src->has(STATAPP)) add(STATAPP); if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(STGIAC)) {stgiac = src->stgiac; add(STGIAC);}; if (src->has(TAG)) add(TAG); if (src->has(RST)) {rst = src->rst; add(RST);}; if (src->has(STATAPPQRY)) add(STATAPPQRY); if (src->has(STATSHRQRY)) {statshrqry = src->statshrqry; add(STATSHRQRY);}; if (src->has(STGIACQRY)) {stgiacqry = src->stgiacqry; add(STGIACQRY);}; }; void PnlWdbeUntHk1NVector::DpchEngData::writeJSON( const uint ixWdbeVLocale , Json::Value& sup ) { Json::Value& me = sup["DpchEngWdbeUntHk1NVectorData"] = Json::Value(Json::objectValue); if (has(JREF)) me["scrJref"] = Scr::scramble(jref); if (has(CONTINF)) continf.writeJSON(me); if (has(FEEDFCSIQST)) feedFCsiQst.writeJSON(me); if (has(STATAPP)) StatApp::writeJSON(me); if (has(STATSHR)) statshr.writeJSON(me); if (has(STGIAC)) stgiac.writeJSON(me); if (has(TAG)) Tag::writeJSON(ixWdbeVLocale, me); if (has(RST)) rst.writeJSON(me); if (has(STATAPPQRY)) QryWdbeUntHk1NVector::StatApp::writeJSON(me); if (has(STATSHRQRY)) statshrqry.writeJSON(me); if (has(STGIACQRY)) stgiacqry.writeJSON(me); }; void PnlWdbeUntHk1NVector::DpchEngData::writeXML( const uint ixWdbeVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngWdbeUntHk1NVectorData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wdbe"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTINF)) continf.writeXML(wr); if (has(FEEDFCSIQST)) feedFCsiQst.writeXML(wr); if (has(STATAPP)) StatApp::writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(STGIAC)) stgiac.writeXML(wr); if (has(TAG)) Tag::writeXML(ixWdbeVLocale, wr); if (has(RST)) rst.writeXML(wr); if (has(STATAPPQRY)) QryWdbeUntHk1NVector::StatApp::writeXML(wr); if (has(STATSHRQRY)) statshrqry.writeXML(wr); if (has(STGIACQRY)) stgiacqry.writeXML(wr); xmlTextWriterEndElement(wr); };
[ "aw@mpsitech.com" ]
aw@mpsitech.com
8850d9d4aed871bf1a4beae0244e23aff77e62b2
4fee08e558e77d16ab915f629df74a0574709e8b
/cpsc585/Havok/Physics/Dynamics/Action/hkpUnaryAction.h
feb0a84faffb49bbadedd8f3aae746f9a30bb1c4
[]
no_license
NinjaMeTimbers/CPSC-585-Game-Project
c6fe97818ffa69b26e6e4dce622079068f5831cc
27a0ce3ef6daabb79e7bdfbe7dcd5635bafce390
refs/heads/master
2021-01-21T00:55:51.915184
2012-04-16T20:06:05
2012-04-16T20:06:05
3,392,986
1
0
null
null
null
null
UTF-8
C++
false
false
3,228
h
/* * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2011 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. */ #ifndef HK_DYNAMICS2_UNARY_ACTION_H #define HK_DYNAMICS2_UNARY_ACTION_H #include <Physics/Dynamics/Action/hkpAction.h> #include <Physics/Dynamics/Entity/hkpRigidBody.h> extern const hkClass hkpUnaryActionClass; /// You can use this as a base class for hkpActions that operate on a single hkpEntity. /// In addition to the hkpAction interface, this class provides /// some useful basic functionality for actions, such as a callback that /// removes the action from the simulation if its hkpEntity is removed. class hkpUnaryAction : public hkpAction { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE); HK_DECLARE_REFLECTION(); /// Constructor creates a hkpUnaryAction that operates on the specified hkpEntity. hkpUnaryAction(hkpEntity* entity = HK_NULL, hkUlong userData = 0); /// Deconstructor. ~hkpUnaryAction(); /// hkpAction interface implementation. virtual void getEntities( hkArray<hkpEntity*>& entitiesOut ); /// Remove self from the hkpWorld when the hkpEntity is removed. virtual void entityRemovedCallback(hkpEntity* entity); /// Sets m_entity, adds a reference to it and adds the action as a listener. /// NB: Only intended to be called pre-simulation i.e., before hkpUnaryAction /// is added to an hkpWorld. void setEntity(hkpEntity* entity); /// Returns m_entity. inline hkpEntity* getEntity(); /// Returns m_entity cast to hkpRigidBody. inline hkpRigidBody* getRigidBody(); /// The applyAction() method does the actual work of the action, and is called at every simulation step. virtual void applyAction( const hkStepInfo& stepInfo ) = 0; virtual const hkClass* getClassType( ) const { return &hkpUnaryActionClass; } protected: /// The hkpEntity. hkpEntity* m_entity; //+hk.Link("PARENT_NAME") public: hkpUnaryAction( class hkFinishLoadedObjectFlag flag ) : hkpAction(flag) {} }; #include <Physics/Dynamics/Action/hkpUnaryAction.inl> #endif // HK_DYNAMICS2_UNARY_ACTION_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20110913) * * Confidential Information of Havok. (C) Copyright 1999-2011 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "cdebavel@ucalgary.ca" ]
cdebavel@ucalgary.ca
ffe4bf70a78f55030ef603d263b024c4cca5816d
3c5f7a82a8c6e29529bc0b585728752aa4f8b560
/OpenCL Array Multiply, Multiply-Add, and Multiply-Reduce/first.cpp
6428ecae8108451686b6b0b8f46875f0ff170999
[]
no_license
wxxMIng/parallel-programming
96b03baa3398fccd5dc0b7f8cb99494a34506766
4698dd0d7f3984f3b342b045d7f909a8e1f84faa
refs/heads/main
2023-06-03T01:42:25.355595
2021-06-21T07:42:14
2021-06-21T07:42:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,256
cpp
// 1. Program header #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #ifdef WIN32 #include <windows.h> #else #include <unistd.h> #endif #include <omp.h> #include "cl.h" #include "cl_platform.h" #ifndef NMB #define NMB 8192 #endif // 1K~8M #define NUM_ELEMENTS NMB*1024 // 32~256 #ifndef LOCAL_SIZE #define LOCAL_SIZE 128 #endif #define NUM_WORK_GROUPS NUM_ELEMENTS/LOCAL_SIZE const char * CL_FILE_NAME = { "first.cl" }; const float TOL = 0.0001f; void Wait( cl_command_queue ); int LookAtTheBits( float ); void PrintOpenclInfo(); void SelectOpenclDevice(); char* Vendor(cl_uint); char* Type(cl_device_type); // globals: cl_platform_id Platform; cl_device_id Device; // opencl vendor ids: #define ID_AMD 0x1002 #define ID_INTEL 0x8086 #define ID_NVIDIA 0x10de #ifdef MAIN_PROGRAM_TO_TEST // compile with: // g++ -o printinfo printinfo.cpp /usr/local/apps/cuda/10.1/lib64/libOpenCL.so.1.1 -lm -fopenmp int main(int argc, char* argv[]) { PrintOpenclInfo(); SelectOpenclDevice(); return 0; } #endif int main( int argc, char *argv[ ] ) { // see if we can even open the opencl kernel program // (no point going on if we can't): FILE *fp; #ifdef WIN32 errno_t err = fopen_s( &fp, CL_FILE_NAME, "r" ); if( err != 0 ) #else fp = fopen( CL_FILE_NAME, "r" ); if( fp == NULL ) #endif { fprintf( stderr, "Cannot open OpenCL source file '%s'\n", CL_FILE_NAME ); return 1; } cl_int status; // returned status from opencl calls // test against CL_SUCCESS // get the platform id: cl_platform_id platform; status = clGetPlatformIDs( 1, &platform, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clGetPlatformIDs failed (2)\n" ); // get the device id: cl_device_id device; status = clGetDeviceIDs( platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clGetDeviceIDs failed (2)\n" ); // 2. allocate the host memory buffers: float *hA = new float[ NUM_ELEMENTS ]; float *hB = new float[ NUM_ELEMENTS ]; float *hC = new float[ NUM_ELEMENTS ]; //float *hD = new float[ NUM_ELEMENTS ]; float* hD = new float[ NUM_WORK_GROUPS ]; size_t dSize = NUM_WORK_GROUPS * sizeof(float); // fill the host memory buffers: for( int i = 0; i < NUM_ELEMENTS; i++ ) { hA[i] = hB[i] = hC[i] = (float) sqrt( (double)i ); } size_t dataSize = NUM_ELEMENTS * sizeof(float); // 3. create an opencl context: cl_context context = clCreateContext( NULL, 1, &device, NULL, NULL, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateContext failed\n" ); // 4. create an opencl command queue: cl_command_queue cmdQueue = clCreateCommandQueue( context, device, 0, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateCommandQueue failed\n" ); // 5. allocate the device memory buffers: cl_mem dA = clCreateBuffer( context, CL_MEM_READ_ONLY, dataSize, NULL, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateBuffer failed (1)\n" ); cl_mem dB = clCreateBuffer( context, CL_MEM_READ_ONLY, dataSize, NULL, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateBuffer failed (2)\n" ); cl_mem dC = clCreateBuffer( context, CL_MEM_READ_ONLY, dataSize, NULL, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateBuffer failed (3)\n" ); cl_mem dD = clCreateBuffer( context, CL_MEM_WRITE_ONLY, dSize, NULL, &status ); if ( status != CL_SUCCESS ) fprintf( stderr, "clCreateBuffer failed (4)\n" ); // 6. enqueue the 3 commands to write the data from the host buffers to the device buffers: status = clEnqueueWriteBuffer( cmdQueue, dA, CL_FALSE, 0, dataSize, hA, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueWriteBuffer failed (1)\n" ); status = clEnqueueWriteBuffer( cmdQueue, dB, CL_FALSE, 0, dataSize, hB, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueWriteBuffer failed (2)\n" ); status = clEnqueueWriteBuffer( cmdQueue, dC, CL_FALSE, 0, dataSize, hC, 0, NULL, NULL ); if ( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueWriteBuffer failed (3)\n" ); Wait( cmdQueue ); // 7. read the kernel code from a file: fseek( fp, 0, SEEK_END ); size_t fileSize = ftell( fp ); fseek( fp, 0, SEEK_SET ); char *clProgramText = new char[ fileSize+1 ]; // leave room for '\0' size_t n = fread( clProgramText, 1, fileSize, fp ); clProgramText[fileSize] = '\0'; fclose( fp ); if( n != fileSize ) fprintf( stderr, "Expected to read %d bytes read from '%s' -- actually read %d.\n", fileSize, CL_FILE_NAME, n ); // create the text for the kernel program: char *strings[1]; strings[0] = clProgramText; cl_program program = clCreateProgramWithSource( context, 1, (const char **)strings, NULL, &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateProgramWithSource failed\n" ); delete [ ] clProgramText; // 8. compile and link the kernel code: char *options = { "" }; status = clBuildProgram( program, 1, &device, options, NULL, NULL ); if( status != CL_SUCCESS ) { size_t size; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &size ); cl_char *log = new cl_char[ size ]; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, size, log, NULL ); fprintf( stderr, "clBuildProgram failed:\n%s\n", log ); delete [ ] log; } // 9. create the kernel object: cl_kernel kernel = clCreateKernel( program, "ArrayMultReduce", &status ); if( status != CL_SUCCESS ) fprintf( stderr, "clCreateKernel failed\n" ); // 10. setup the arguments to the kernel object: status = clSetKernelArg( kernel, 0, sizeof(cl_mem), &dA ); if( status != CL_SUCCESS ) fprintf( stderr, "clSetKernelArg failed (1)\n" ); status = clSetKernelArg( kernel, 1, sizeof(cl_mem), &dB ); if( status != CL_SUCCESS ) fprintf( stderr, "clSetKernelArg failed (2)\n" ); status = clSetKernelArg( kernel, 2, sizeof(cl_mem), &dC ); if( status != CL_SUCCESS ) fprintf( stderr, "clSetKernelArg failed (3)\n" ); status = clSetKernelArg( kernel, 3, LOCAL_SIZE * sizeof(float), NULL ); // tell OpenCL that this is a local array status = clSetKernelArg( kernel, 4, sizeof(cl_mem), &dD ); if ( status != CL_SUCCESS ) fprintf( stderr, "clSetKernelArg failed (4)\n" ); // 11. enqueue the kernel object for execution: size_t globalWorkSize[3] = { NUM_ELEMENTS, 1, 1 }; size_t localWorkSize[3] = { LOCAL_SIZE, 1, 1 }; Wait( cmdQueue ); double time0 = omp_get_wtime( ); time0 = omp_get_wtime( ); status = clEnqueueNDRangeKernel( cmdQueue, kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueNDRangeKernel failed: %d\n", status ); Wait( cmdQueue ); double time1 = omp_get_wtime(); // 12. read the results buffer back from the device to the host: status = clEnqueueReadBuffer( cmdQueue, dD, CL_TRUE, 0, NUM_WORK_GROUPS * sizeof(float), hD, 0, NULL, NULL ); if( status != CL_SUCCESS ) fprintf( stderr, "clEnqueueReadBuffer failed\n" ); // add up float sum = 0.; for (int i = 0; i < NUM_WORK_GROUPS; i++) { sum += hD[i]; } // did it work? /* float sum1 = 0.; for (int i = 0; i < NUM_ELEMENTS; i++) { sum1 += hA[i] * hB[i]; } fprintf(stderr, "sum = %10.3lf\tsum1 = %10.3lf\n", sum, sum1); /* for( int i = 0; i < NUM_ELEMENTS; i++ ) { float expected = (hA[i] * hB[i]) + hC[i]; if( fabs( (long)(hD[i] - expected) ) > TOL ) { fprintf( stderr, "%4d: %13.6f * %13.6f + %13.6f wrongly produced %13.6f instead of %13.6f (%13.8f)\n", i, hA[i], hB[i], hC[i], hD[i], expected, fabs(hD[i]-expected) ); fprintf( stderr, "%4d: 0x%08x * 0x%08x wrongly produced 0x%08x instead of 0x%08x\n", i, LookAtTheBits(hA[i]), LookAtTheBits(hB[i]), LookAtTheBits(hD[i]), LookAtTheBits(expected) ); } } */ fprintf( stderr, "%8d\t%4d\t%10d\t%10.3lf GigaMultsPerSecond\n", NMB, LOCAL_SIZE, NUM_WORK_GROUPS, (double)NUM_ELEMENTS/(time1-time0)/1000000000. ); #ifdef WIN32 Sleep( 2000 ); #endif // 13. clean everything up: clReleaseKernel( kernel ); clReleaseProgram( program ); clReleaseCommandQueue( cmdQueue ); clReleaseMemObject( dA ); clReleaseMemObject( dB ); clReleaseMemObject( dC ); clReleaseMemObject( dD ); delete [ ] hA; delete [ ] hB; delete [ ] hC; delete [ ] hD; return 0; } int LookAtTheBits( float fp ) { int *ip = (int *)&fp; return *ip; } // wait until all queued tasks have taken place: void Wait( cl_command_queue queue ) { cl_event wait; cl_int status; status = clEnqueueMarker( queue, &wait ); if( status != CL_SUCCESS ) fprintf( stderr, "Wait: clEnqueueMarker failed\n" ); status = clWaitForEvents( 1, &wait ); if( status != CL_SUCCESS ) fprintf( stderr, "Wait: clWaitForEvents failed\n" ); } void PrintOpenclInfo() { cl_int status; // returned status from opencl calls // test against CL_SUCCESS fprintf(stderr, "PrintInfo:\n"); // find out how many platforms are attached here and get their ids: cl_uint numPlatforms; status = clGetPlatformIDs(0, NULL, &numPlatforms); if (status != CL_SUCCESS) fprintf(stderr, "clGetPlatformIDs failed (1)\n"); fprintf(stderr, "Number of Platforms = %d\n", numPlatforms); cl_platform_id* platforms = new cl_platform_id[numPlatforms]; status = clGetPlatformIDs(numPlatforms, platforms, NULL); if (status != CL_SUCCESS) fprintf(stderr, "clGetPlatformIDs failed (2)\n"); for (int p = 0; p < (int)numPlatforms; p++) { fprintf(stderr, "Platform #%d:\n", p); size_t size; char* str; clGetPlatformInfo(platforms[p], CL_PLATFORM_NAME, 0, NULL, &size); str = new char[size]; clGetPlatformInfo(platforms[p], CL_PLATFORM_NAME, size, str, NULL); fprintf(stderr, "\tName = '%s'\n", str); delete[] str; clGetPlatformInfo(platforms[p], CL_PLATFORM_VENDOR, 0, NULL, &size); str = new char[size]; clGetPlatformInfo(platforms[p], CL_PLATFORM_VENDOR, size, str, NULL); fprintf(stderr, "\tVendor = '%s'\n", str); delete[] str; clGetPlatformInfo(platforms[p], CL_PLATFORM_VERSION, 0, NULL, &size); str = new char[size]; clGetPlatformInfo(platforms[p], CL_PLATFORM_VERSION, size, str, NULL); fprintf(stderr, "\tVersion = '%s'\n", str); delete[] str; clGetPlatformInfo(platforms[p], CL_PLATFORM_PROFILE, 0, NULL, &size); str = new char[size]; clGetPlatformInfo(platforms[p], CL_PLATFORM_PROFILE, size, str, NULL); fprintf(stderr, "\tProfile = '%s'\n", str); delete[] str; // find out how many devices are attached to each platform and get their ids: cl_uint numDevices; status = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices); if (status != CL_SUCCESS) fprintf(stderr, "clGetDeviceIDs failed (2)\n"); fprintf(stderr, "\tNumber of Devices = %d\n", numDevices); cl_device_id* devices = new cl_device_id[numDevices]; status = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, numDevices, devices, NULL); if (status != CL_SUCCESS) fprintf(stderr, "clGetDeviceIDs failed (2)\n"); for (int d = 0; d < (int)numDevices; d++) { fprintf(stderr, "\tDevice #%d:\n", d); size_t size; cl_device_type type; cl_uint ui; size_t sizes[3] = { 0, 0, 0 }; clGetDeviceInfo(devices[d], CL_DEVICE_TYPE, sizeof(type), &type, NULL); fprintf(stderr, "\t\tType = 0x%04x = ", (unsigned int)type); switch (type) { case CL_DEVICE_TYPE_CPU: fprintf(stderr, "CL_DEVICE_TYPE_CPU\n"); break; case CL_DEVICE_TYPE_GPU: fprintf(stderr, "CL_DEVICE_TYPE_GPU\n"); break; case CL_DEVICE_TYPE_ACCELERATOR: fprintf(stderr, "CL_DEVICE_TYPE_ACCELERATOR\n"); break; default: fprintf(stderr, "Other...\n"); break; } clGetDeviceInfo(devices[d], CL_DEVICE_VENDOR_ID, sizeof(ui), &ui, NULL); fprintf(stderr, "\t\tDevice Vendor ID = 0x%04x ", ui); switch (ui) { case ID_AMD: fprintf(stderr, "(AMD)\n"); break; case ID_INTEL: fprintf(stderr, "(Intel)\n"); break; case ID_NVIDIA: fprintf(stderr, "(NVIDIA)\n"); break; default: fprintf(stderr, "(?)\n"); } clGetDeviceInfo(devices[d], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(ui), &ui, NULL); fprintf(stderr, "\t\tDevice Maximum Compute Units = %d\n", ui); clGetDeviceInfo(devices[d], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(ui), &ui, NULL); fprintf(stderr, "\t\tDevice Maximum Work Item Dimensions = %d\n", ui); clGetDeviceInfo(devices[d], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(sizes), sizes, NULL); fprintf(stderr, "\t\tDevice Maximum Work Item Sizes = %d x %d x %d\n", sizes[0], sizes[1], sizes[2]); clGetDeviceInfo(devices[d], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size), &size, NULL); fprintf(stderr, "\t\tDevice Maximum Work Group Size = %d\n", size); clGetDeviceInfo(devices[d], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(ui), &ui, NULL); fprintf(stderr, "\t\tDevice Maximum Clock Frequency = %d MHz\n", ui); size_t extensionSize; clGetDeviceInfo(devices[d], CL_DEVICE_EXTENSIONS, 0, NULL, &extensionSize); char* extensions = new char[extensionSize]; clGetDeviceInfo(devices[d], CL_DEVICE_EXTENSIONS, extensionSize, extensions, NULL); fprintf(stderr, "\nDevice #%d's Extensions:\n", d); for (int e = 0; e < (int)strlen(extensions); e++) { if (extensions[e] == ' ') extensions[e] = '\n'; } fprintf(stderr, "%s\n", extensions); delete[] extensions; } delete[] devices; } delete[] platforms; fprintf(stderr, "\n\n"); } void SelectOpenclDevice() { // select which opencl device to use: // priority order: // 1. a gpu // 2. an nvidia or amd gpu // 3. an intel gpu // 4. an intel cpu int bestPlatform = -1; int bestDevice = -1; cl_device_type bestDeviceType; cl_uint bestDeviceVendor; cl_int status; // returned status from opencl calls // test against CL_SUCCESS fprintf(stderr, "\nSelecting the OpenCL Platform and Device:\n"); // find out how many platforms are attached here and get their ids: cl_uint numPlatforms; status = clGetPlatformIDs(0, NULL, &numPlatforms); if (status != CL_SUCCESS) fprintf(stderr, "clGetPlatformIDs failed (1)\n"); cl_platform_id* platforms = new cl_platform_id[numPlatforms]; status = clGetPlatformIDs(numPlatforms, platforms, NULL); if (status != CL_SUCCESS) fprintf(stderr, "clGetPlatformIDs failed (2)\n"); for (int p = 0; p < (int)numPlatforms; p++) { // find out how many devices are attached to each platform and get their ids: cl_uint numDevices; status = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices); if (status != CL_SUCCESS) fprintf(stderr, "clGetDeviceIDs failed (2)\n"); cl_device_id* devices = new cl_device_id[numDevices]; status = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, numDevices, devices, NULL); if (status != CL_SUCCESS) fprintf(stderr, "clGetDeviceIDs failed (2)\n"); for (int d = 0; d < (int)numDevices; d++) { cl_device_type type; cl_uint vendor; size_t sizes[3] = { 0, 0, 0 }; clGetDeviceInfo(devices[d], CL_DEVICE_TYPE, sizeof(type), &type, NULL); clGetDeviceInfo(devices[d], CL_DEVICE_VENDOR_ID, sizeof(vendor), &vendor, NULL); // select: if (bestPlatform < 0) // not yet holding anything -- we'll accept anything { bestPlatform = p; bestDevice = d; Platform = platforms[bestPlatform]; Device = devices[bestDevice]; bestDeviceType = type; bestDeviceVendor = vendor; } else // holding something already -- can we do better? { if (bestDeviceType == CL_DEVICE_TYPE_CPU) // holding a cpu already -- switch to a gpu if possible { if (type == CL_DEVICE_TYPE_GPU) // found a gpu { // switch to the gpu we just found bestPlatform = p; bestDevice = d; Platform = platforms[bestPlatform]; Device = devices[bestDevice]; bestDeviceType = type; bestDeviceVendor = vendor; } } else // holding a gpu -- is a better gpu available? { if (bestDeviceVendor == ID_INTEL) // currently holding an intel gpu { // we are assuming we just found a bigger, badder nvidia or amd gpu bestPlatform = p; bestDevice = d; Platform = platforms[bestPlatform]; Device = devices[bestDevice]; bestDeviceType = type; bestDeviceVendor = vendor; } } } } delete[] devices; } delete[] platforms; if (bestPlatform < 0) { fprintf(stderr, "Found no OpenCL devices!\n"); } else { fprintf(stderr, "I have selected Platform #%d, Device #%d\n", bestPlatform, bestDevice); fprintf(stderr, "Vendor = %s, Type = %s\n", Vendor(bestDeviceVendor), Type(bestDeviceType)); } } char* Vendor(cl_uint v) { switch (v) { case ID_AMD: return (char*)"AMD"; case ID_INTEL: return (char*)"Intel"; case ID_NVIDIA: return (char*)"NVIDIA"; } return (char*)"Unknown"; } char* Type(cl_device_type t) { switch (t) { case CL_DEVICE_TYPE_CPU: return (char*)"CL_DEVICE_TYPE_CPU"; case CL_DEVICE_TYPE_GPU: return (char*)"CL_DEVICE_TYPE_GPU"; case CL_DEVICE_TYPE_ACCELERATOR: return (char*)"CL_DEVICE_TYPE_ACCELERATOR"; } return (char*)"Unknown"; }
[ "55899847+wxxMIng@users.noreply.github.com" ]
55899847+wxxMIng@users.noreply.github.com
e185e6154bf212fa6b74fe8294cf20f50e8a462a
b725ba18b99398ce8459b8877691135e0cdf4d51
/rbutil/rbutilqt/test/test-compareversion.cpp
c075c2af129f7fc6efd01ef0b10e86a7043db1e5
[ "BSD-3-Clause" ]
permissive
Rockbox-Chinese-Community/Rockbox-RCC
8d3069271d14144281a40694c60128cac852cd3a
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
refs/heads/lab-general
2020-12-01T22:59:14.427025
2017-04-29T06:17:24
2017-04-29T06:17:24
1,565,842
29
16
NOASSERTION
2019-03-21T03:45:53
2011-04-04T06:19:32
C
UTF-8
C++
false
false
5,159
cpp
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * * Copyright (C) 2010 Dominik Riebeling * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include <QtTest/QtTest> #include <QObject> #include "utils.h" class TestVersionCompare : public QObject { Q_OBJECT private slots: void testCompare(); void testTrim(); }; struct compvector { const char* first; const char* second; const int expected; }; const struct compvector compdata[] = { { "1.2.3", "1.2.3 ", 0 }, { "1.2.3", " 1.2.3", 0 }, { "1.2.3", "1.2.4", 1 }, { "1.2.3", "1.3.0", 1 }, { "1.2.3", "2.0.0", 1 }, { "10.22.33", "10.22.33", 0 }, { "10.22.33", "10.23.0", 1 }, { "10.22.33", "11.0.0", 1 }, { "1.2.3", "1.2.3.1", 1 }, { "1.2.3", "1.2.3-1", 1 }, { "1.2.3-1", "1.2.3.1", 1 }, { "1.2.3-10", "1.2.3.0", 1 }, { "1.2.3-1", "1.2.3.10", 1 }, { "1.2.3-1", "1.2.3a", 1 }, { "1.2.3", "1.2.3a", 1 }, { "1.2.3a", "1.2.3b", 1 }, { "1.2.3", "1.2.3b", 1 }, { "1.2.3.0", "2.0.0", 1 }, { "1.2.3b", "2.0.0", 1 }, { "1.2.3", "2.0.0.1", 1 }, { "test-1.2.3", "test-1.2.3.tar.gz", 0 }, { "1.2.3", "test-1.2.3.tar.bz2", 0 }, { "test-1.2.3.tar.gz", "test-1.2.3.tar.bz2", 0 }, { "test-1.2.3.tar.gz", "program-1.2.3.1.tar.bz2", 1 }, { "program-1.2.3.zip", "program-1.2.3a.zip", 1 }, { "program-1.2.3.tar.bz2", "2.0.0", 1 }, { "prog-1.2-64bit.tar.bz2", "prog-1.2.3.tar.bz2", 1 }, { "prog-1.2-64bit.tar.bz2", "prog-1.2-64bit.tar.bz2", 0 }, { "prog-1.2-64bit.tar.bz2", "prog-1.2.3-64bit.tar.bz2", 1 }, { "prog-1.2a-64bit.tar.bz2","prog-1.2b-64bit.tar.bz2", 1 }, { "prog-1.2-64bit.tar.bz2", "prog-1.2.3a-64bit.tar.bz2", 1 }, { "prog-1.2a-64bit.tar.bz2","prog-1.2.3-64bit.tar.bz2", 1 }, }; struct trimvector { const char* input; const QString expected; }; const struct trimvector trimdata[] = { { "prog-1.2-64bit.tar.bz2", "1.2" }, { "prog-1.2.tar.bz2", "1.2" }, { "1.2.3", "1.2.3" }, { " 1.2.3", "1.2.3" }, { "1.2.3 ", "1.2.3" }, { "10.22.33", "10.22.33" }, { "test-1.2.3", "1.2.3" }, { "1.2.3", "1.2.3" }, { "test-1.2.3.tar.gz", "1.2.3" }, { "prog-1.2-64bit.tar.bz2", "1.2" }, { "prog-1.2a.tar.bz2", "1.2a" }, { "prog-1.2a-64bit.tar.bz2","1.2a" }, }; void TestVersionCompare::testCompare() { unsigned int i; for(i = 0; i < sizeof(compdata) / sizeof(struct compvector); i++) { QCOMPARE(Utils::compareVersionStrings(compdata[i].first, compdata[i].second), compdata[i].expected); // inverse test possible because function return values are symmetrical. if(compdata[i].expected != 0) QCOMPARE(Utils::compareVersionStrings(compdata[i].second, compdata[i].first), -compdata[i].expected); } } void TestVersionCompare::testTrim() { for(int i = 0; i < sizeof(trimdata) / sizeof(struct trimvector); i++) { QCOMPARE(Utils::trimVersionString(trimdata[i].input), trimdata[i].expected); } } QTEST_MAIN(TestVersionCompare) // this include is needed because we don't use a separate header file for the // test class. It also needs to be at the end. #include "test-compareversion.moc"
[ "Dominik.Riebeling@gmail.com" ]
Dominik.Riebeling@gmail.com
000d2d1c5a6cfcf3a1c908fadd92fcdd2593ecb8
49c2492d91789b3c2def7d654a7396e8c6ce6d9f
/cpp_archive/PointerThis.cpp
d76473b22d8dc27909102a10e8674a5aa3d107b6
[]
no_license
DavidHan008/lockdpwn
edd571165f9188e0ee93da7222c0155abb427927
5078a1b08916b84c5c3723fc61a1964d7fb9ae20
refs/heads/master
2021-01-23T14:10:53.209406
2017-09-02T18:02:50
2017-09-02T18:02:50
102,670,531
0
2
null
2017-09-07T00:11:33
2017-09-07T00:11:33
null
UHC
C++
false
false
679
cpp
/* 열혈 c++ p196 this 포인터의 이해 */ #include "stdafx.h" #include <iostream> using namespace std; class simple { private: int num; public: simple(int n) : num(n) { cout << "num = " << num << ", "; cout << "address = " << this << endl; } void ShowSimpleData() { cout << num << endl; } simple *GetThisPointer() { return this; } }; int main() { simple sim1(100); simple *ptr1 = sim1.GetThisPointer(); cout << ptr1 << ", "; ptr1->ShowSimpleData(); simple sim2(200); simple *ptr2 = sim2.GetThisPointer(); cout << ptr2 << ", "; ptr2->ShowSimpleData(); return 0; }
[ "gyurse@gmail.com" ]
gyurse@gmail.com
57a09b34551afc3c005d3b738b0b9b082fb52331
1a5a3b9f8675000cf94b1a6797a909e1a0fcc40e
/src/client/src/Util/CDSound.cpp
6dc8961cd260fbe26aa04e99b94b6b463e80c305
[]
no_license
Davidixx/client
f57e0d82b4aeec75394b453aa4300e3dd022d5d7
4c0c1c0106c081ba9e0306c14607765372d6779c
refs/heads/main
2023-07-29T19:10:20.011837
2021-08-11T20:40:39
2021-08-11T20:40:39
403,916,993
0
0
null
2021-09-07T09:21:40
2021-09-07T09:21:39
null
UHC
C++
false
false
23,965
cpp
#include "StdAfx.h" #include <dsound.h> #include <dxerr9.h> #include "CDSound.h" #include "CWaveFILE.h" #include "CCamera.h" #include "OBJECT.h" #include "CObjCHAR.h" LPDIRECTSOUND3DLISTENER CD3DSOUND::m_pDSListener = nullptr; DS3DLISTENER CD3DSOUND::m_dsListenerParams; //------------------------------------------------------------------------------------------------- #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } //------------------------------------------------------------------------------------------------- struct tagWAVEDATA { WAVEFORMATEX m_sWaveFormat; BYTE* m_pWaveData; DWORD m_dwDataSize; }; static t_wavedata* WaveData_Load(LPSTR szFileName, long lFilePtr); static void WaveData_Free(t_wavedata* pWave); //------------------------------------------------------------------------------------------------- // // WAVE File I/O // static t_wavedata* WaveData_Load(LPSTR szFileName, long lFilePtr) { FILE* fpWAV; ULONG lFPos; DWORD dwLength; t_wavedata* pWave; union { DWORD dwFOURCC; char cFOURCC[ 4 ]; }; if ( lFilePtr >= 0 ) lFPos = lFilePtr + sizeof( long ); else lFPos = 0; if ( (fpWAV = fopen( szFileName, "rb" )) == nullptr ) return nullptr; fseek( fpWAV, lFPos, SEEK_SET ); fread( &dwFOURCC, sizeof( DWORD ), 1, fpWAV ); // rID if ( dwFOURCC != mmioFOURCC('R', 'I', 'F', 'F') ) goto _ExitLoadWaveFile; // not even RIFF fread( &dwLength, sizeof( DWORD ), 1, fpWAV ); // rLen fread( &dwFOURCC, sizeof( DWORD ), 1, fpWAV ); // wID if ( dwFOURCC != mmioFOURCC('W', 'A', 'V', 'E') ) goto _ExitLoadWaveFile; // not a WAV fread( &dwFOURCC, sizeof( DWORD ), 1, fpWAV ); // fID if ( dwFOURCC != mmioFOURCC('f', 'm', 't', ' ') ) goto _ExitLoadWaveFile; // not a WAV fread( &dwLength, sizeof( DWORD ), 1, fpWAV ); // fLen pWave = (t_wavedata *)new t_wavedata; if ( pWave == nullptr ) return nullptr; pWave->m_pWaveData = nullptr; fread( &pWave->m_sWaveFormat, sizeof( WAVEFORMATEX ), 1, fpWAV ); fseek( fpWAV, dwLength - 18, SEEK_CUR ); dwLength = 0; do { if ( dwLength ) fseek( fpWAV, dwLength, SEEK_CUR ); fread( &dwFOURCC, sizeof( DWORD ), 1, fpWAV ); // fID if ( fread( &dwLength, sizeof( DWORD ), 1, fpWAV ) < 1 ) // block size goto _ExitLoadWaveFile; } while ( dwFOURCC != mmioFOURCC('d', 'a', 't', 'a') ); pWave->m_dwDataSize = dwLength; pWave->m_pWaveData = (BYTE *)new BYTE [ pWave->m_dwDataSize ]; if ( pWave->m_pWaveData == nullptr ) { delete pWave; return nullptr; } fread( pWave->m_pWaveData, sizeof( BYTE ), pWave->m_dwDataSize, fpWAV ); _ExitLoadWaveFile: fclose( fpWAV ); return pWave; } //------------------------------------------------------------------------------------------------- static void WaveData_Free(t_wavedata* pWave) { if ( pWave->m_pWaveData != nullptr ) delete[] pWave->m_pWaveData; if ( pWave != nullptr ) delete pWave; } //------------------------------------------------------------------------------------------------- CDSOUND::CDSOUND() { m_pDS = nullptr; } //------------------------------------------------------------------------------------------------- CDSOUND::~CDSOUND() { this->_Free(); } //------------------------------------------------------------------------------------------------- bool CDSOUND::_Init(HWND hWnd, DWORD dwCoopLevel, DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate) { // Create IDirectSound using the primary sound device m_hR = DirectSoundCreate8( nullptr, &m_pDS, nullptr ); if ( FAILED( m_hR ) ) { OutputDebugString( "ERROR : DirectSoundCreate8\n" ); return false; } // Set DirectSound coop level m_hR = m_pDS->SetCooperativeLevel( hWnd, dwCoopLevel ); if ( FAILED( m_hR ) ) { OutputDebugString( "ERROR : SetCooperativeLevel\n" ); return false; } // Set primary buffer format return SetPrimaryBufferFormat( dwPrimaryChannels, dwPrimaryFreq, dwPrimaryBitRate ); } //------------------------------------------------------------------------------------------------- void CDSOUND::_Free() { if ( m_pDS ) { m_pDS->Release(); m_pDS = nullptr; } } //------------------------------------------------------------------------------------------------- bool CDSOUND::SetPrimaryBufferFormat(DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate) { LPDIRECTSOUNDBUFFER pDSBPrimary = nullptr; if ( m_pDS == nullptr ) return false; // Get the primary buffer DSBUFFERDESC dsbd; ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) ); dsbd.dwSize = sizeof( DSBUFFERDESC ); dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER; dsbd.dwBufferBytes = 0; dsbd.lpwfxFormat = nullptr; m_hR = m_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, nullptr ); if ( FAILED( m_hR ) ) { OutputDebugString( "ERROR : CreateSoundBuffer\n" ); return false; } WAVEFORMATEX wfx; ZeroMemory( &wfx, sizeof(WAVEFORMATEX) ); wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nChannels = (WORD)dwPrimaryChannels; wfx.nSamplesPerSec = dwPrimaryFreq; wfx.wBitsPerSample = (WORD)dwPrimaryBitRate; wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels; wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign; m_hR = pDSBPrimary->SetFormat( &wfx ); if ( FAILED( m_hR ) ) { pDSBPrimary->Release(); OutputDebugString( "ERROR : DSoundBuffer SetFormat\n" ); return false; } SAFE_RELEASE( pDSBPrimary ) return true; } //------------------------------------------------------------------------------------------------- t_sounddata* CDSOUND::CreateSoundData(t_wavedata* pWave, DWORD dwCreationFlags, GUID guid3DAlgorithm) { if ( m_pDS == nullptr ) return nullptr; DSBUFFERDESC dsbd; LPDIRECTSOUNDBUFFER lpDSB; LPVOID pMem1, pMem2; DWORD dwSize1, dwSize2; ::ZeroMemory (&dsbd, sizeof (dsbd)); dsbd.dwSize = sizeof( DSBUFFERDESC ); // DSBCAPS_CTRLPAN | DSBCAPS_GETCURRENTPOSITION2 // DSBCAPS_CTRLFREQUENCY // DSBCAPS_STATIC | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN // DSBCAPS_CTRL3D; dsbd.dwFlags = dwCreationFlags; dsbd.lpwfxFormat = &pWave->m_sWaveFormat; dsbd.dwBufferBytes = pWave->m_dwDataSize; dsbd.guid3DAlgorithm = guid3DAlgorithm; m_hR = m_pDS->CreateSoundBuffer( &dsbd, &lpDSB, nullptr ); if ( m_hR != DS_OK ) return nullptr; m_hR = lpDSB->Lock( 0, dsbd.dwBufferBytes, &pMem1, &dwSize1, &pMem2, &dwSize2, 0 ); if ( m_hR == DS_OK ) { ::CopyMemory (pMem1, pWave->m_pWaveData, dwSize1); if ( dwSize2 != 0 ) ::CopyMemory (pMem2, (pWave->m_pWaveData+dwSize1), dwSize2); lpDSB->Unlock( pMem1, dwSize1, pMem2, dwSize2 ); if ( dsbd.dwFlags & DSBCAPS_CTRLVOLUME ) lpDSB->SetVolume( DSBVOLUME_MIN/*DSBVOLUME_MAX*/ ); // 초기 묵음으로.. if ( dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY ) lpDSB->SetFrequency( DSBFREQUENCY_ORIGINAL ); if ( dsbd.dwFlags & DSBCAPS_CTRLPAN ) lpDSB->SetPan( DSBPAN_CENTER ); // return lpDSB; t_sounddata* pSound; pSound = new t_sounddata; if ( pSound ) { pSound->m_pDSB = lpDSB; return pSound; } } lpDSB->Release(); lpDSB = nullptr; return nullptr; } //------------------------------------------------------------------------------------------------- t_sounddata* CDSOUND::CreateSoundData(CWaveFile* pCWave, DWORD dwCreationFlags, GUID guid3DAlgorithm) { if ( m_pDS == nullptr ) return nullptr; DSBUFFERDESC dsbd; LPDIRECTSOUNDBUFFER lpDSB; LPVOID pMem1, pMem2; DWORD dwSize1, dwSize2; ::ZeroMemory (&dsbd, sizeof (dsbd)); dsbd.dwSize = sizeof( DSBUFFERDESC ); // DSBCAPS_CTRLPAN | DSBCAPS_GETCURRENTPOSITION2 // DSBCAPS_CTRLFREQUENCY // DSBCAPS_STATIC | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN // DSBCAPS_CTRL3D; dsbd.dwFlags = dwCreationFlags; dsbd.lpwfxFormat = pCWave->m_pwfx; dsbd.dwBufferBytes = pCWave->m_dwSize; //m_dwDataSize; dsbd.guid3DAlgorithm = guid3DAlgorithm; m_hR = m_pDS->CreateSoundBuffer( &dsbd, &lpDSB, nullptr ); if ( m_hR != DS_OK ) return nullptr; m_hR = lpDSB->Lock( 0, dsbd.dwBufferBytes, &pMem1, &dwSize1, &pMem2, &dwSize2, 0 ); pCWave->ResetFile(); DWORD dwWavDataRead = 0; // Amount of data read from the wav file if ( m_hR == DS_OK ) { // ::CopyMemory (pMem1, pWave->m_pWaveData, dwSize1); if ( FAILED( pCWave->Read( (BYTE*)pMem1, dwSize1, &dwWavDataRead ) ) ) goto _RET_ERROR; if ( dwWavDataRead == 0 ) { // Wav is blank, so just fill with silence ::FillMemory( (BYTE*) pMem1, dwSize1, (BYTE)(pCWave->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) ); } else if ( dwSize2 != 0 ) { // ::CopyMemory (pMem2, (pWave->m_pWaveData+dwSize1), dwSize2); if ( FAILED( pCWave->Read( (BYTE*)pMem2, dwSize2, &dwWavDataRead ) ) ) goto _RET_ERROR; if ( dwWavDataRead == 0 ) // Wav is blank, so just fill with silence ::FillMemory( (BYTE*) pMem2, dwSize2, (BYTE)(pCWave->m_pwfx->wBitsPerSample == 8 ? 128 : 0 ) ); } lpDSB->Unlock( pMem1, dwSize1, pMem2, dwSize2 ); if ( dsbd.dwFlags & DSBCAPS_CTRLVOLUME ) lpDSB->SetVolume( DSBVOLUME_MIN/*DSBVOLUME_MAX*/ ); // 초기 묵음으로.. if ( dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY ) lpDSB->SetFrequency( DSBFREQUENCY_ORIGINAL ); if ( dsbd.dwFlags & DSBCAPS_CTRLPAN ) lpDSB->SetPan( DSBPAN_CENTER ); // return lpDSB; t_sounddata* pSound; pSound = new t_sounddata; if ( pSound ) { pSound->m_pDSB = lpDSB; return pSound; } } _RET_ERROR: lpDSB->Release(); lpDSB = nullptr; return nullptr; } //------------------------------------------------------------------------------------------------- t_sounddata* CDSOUND::DuplicateSoundData(LPDIRECTSOUNDBUFFER lpDSBSour) { LPDIRECTSOUNDBUFFER lpDSBDest; m_hR = m_pDS->DuplicateSoundBuffer( lpDSBSour, &lpDSBDest ); if ( FAILED( m_hR ) ) { ::OutputDebugString( "DuplicateSoundBuffer\n" ); return nullptr; } t_sounddata* pSound; pSound = new t_sounddata; pSound->m_pDSB = lpDSBDest; return pSound; } //------------------------------------------------------------------------------------------------- // #define __USE_CWAVE_CLASS t_sounddata* CDSOUND::LoadSoundData(LPSTR szFileName, short nMaxMixCnt, DWORD dwCreationFlags, GUID guid3DAlgorithm, long lFilePtr) { if ( m_pDS == nullptr ) return nullptr; t_sounddata* pSound; #ifndef __USE_CWAVE_CLASS t_wavedata* pWave; pWave = WaveData_Load( szFileName, lFilePtr ); if ( pWave == nullptr ) return nullptr; pSound = this->CreateSoundData( pWave, dwCreationFlags, guid3DAlgorithm ); WaveData_Free( pWave ); #else CWaveFile *pWaveFile = NULL; pWaveFile = new CWaveFile(); if( pWaveFile == NULL ) { return NULL; } pWaveFile->Open( szFileName, NULL, WAVEFILE_READ ); if ( pWaveFile->GetSize() == 0 ) { // Wave is blank, so don't create it. return NULL; } pSound = this->CreateSoundData (pWaveFile, dwCreationFlags, guid3DAlgorithm); SAFE_DELETE( pWaveFile ); #endif if ( pSound ) { pSound->m_pNext = nullptr; pSound->m_nMaxMixCnt = nMaxMixCnt; } return pSound; } //------------------------------------------------------------------------------------------------- void CDSOUND::FreeSoundData(t_sounddata* pData) { t_sounddata* pNext; while ( pData != nullptr ) { pNext = pData->m_pNext; SAFE_DELETE( pData ); pData = pNext; } } //------------------------------------------------------------------------------------------------- DWORD CDSOUND::GetStatus(t_sounddata* pData) { DWORD dwStatus; pData->m_pDSB->GetStatus( &dwStatus ); return dwStatus; } //------------------------------------------------------------------------------------------------- void CDSOUND::SetMaxMixCount(t_sounddata* pData, short nMaxMinCnt) { if ( pData ) { pData->m_nMaxMixCnt = nMaxMinCnt; } } //------------------------------------------------------------------------------------------------- short CDSOUND::GetMaxMixCount(t_sounddata* pData) { if ( pData ) { return pData->m_nMaxMixCnt; } return -1; } //------------------------------------------------------------------------------------------------- void CDSOUND::PlaySound(t_sounddata* pData, long lVolume, long lPan, DWORD dwFlags) { static DWORD dwStatus; static t_sounddata* pSound; static short nMixCnt; if ( m_pDS == nullptr ) return; if ( pData == nullptr || pData->m_pDSB == nullptr ) return; pSound = pData; nMixCnt = 0; while ( true ) { pSound->m_pDSB->GetStatus( &dwStatus ); if ( dwStatus == DSBSTATUS_PLAYING || dwStatus == DSBSTATUS_LOOPING ) { if ( ++nMixCnt >= pData->m_nMaxMixCnt ) return; if ( pSound->m_pNext == nullptr ) { pSound->m_pNext = this->DuplicateSoundData( pData->m_pDSB ); if ( nullptr == pSound->m_pNext ) return; pSound->m_pNext->m_pNext = nullptr; /* pSound->m_pNext = (t_sounddata*) new t_sounddata; pSound = pSound->m_pNext; pSound->m_pDSB = this->DuplicateSoundData (pData->m_pDSB); pSound->m_pNext = NULL; if ( pSound->m_pDSB == NULL ) return; */ } else { pSound = pSound->m_pNext; continue; } } break; } pSound->m_pDSB->SetVolume( lVolume ); pSound->m_pDSB->SetPan( lPan ); m_hR = pSound->m_pDSB->Play( 0, 0, dwFlags ); } //------------------------------------------------------------------------------------------------- void CDSOUND::StopSound(t_sounddata* pData) { t_sounddata* pNext; while ( pData != nullptr ) { pNext = pData->m_pNext; if ( pData->m_pDSB != nullptr ) pData->m_pDSB->Stop(); pData = pNext; } } //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- CD3DSOUND::CD3DSOUND() { m_pDSListener = nullptr; /* DS3DALG_NO_VIRTUALIZATION; DS3DALG_HRTF_FULL; DS3DALG_HRTF_LIGHT; */ m_guid3DAlgorithm = DS3DALG_DEFAULT; } CD3DSOUND::~CD3DSOUND() { SAFE_RELEASE( m_pDSListener ); _Free(); } //------------------------------------------------------------------------------------------------- HRESULT CD3DSOUND::Get3DListenerInterface(LPDIRECTSOUND3DLISTENER* ppDSListener) { DSBUFFERDESC dsbdesc; LPDIRECTSOUNDBUFFER pDSBPrimary = nullptr; if ( ppDSListener == nullptr ) return E_INVALIDARG; if ( m_pDS == nullptr ) return CO_E_NOTINITIALIZED; *ppDSListener = nullptr; // Obtain primary buffer, asking it for 3D control ZeroMemory( &dsbdesc, sizeof(DSBUFFERDESC) ); dsbdesc.dwSize = sizeof( DSBUFFERDESC ); dsbdesc.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME | DSBCAPS_PRIMARYBUFFER; if ( FAILED( m_hR = m_pDS->CreateSoundBuffer( &dsbdesc, &pDSBPrimary, NULL ) ) ) return DXTRACE_ERR( TEXT("CreateSoundBuffer"), m_hR ); if ( FAILED( m_hR = pDSBPrimary->QueryInterface( IID_IDirectSound3DListener, (VOID**)ppDSListener ) ) ) { SAFE_RELEASE( pDSBPrimary ); return DXTRACE_ERR( TEXT("QueryInterface"), m_hR ); } // Release the primary buffer, since it is not need anymore SAFE_RELEASE( pDSBPrimary ); return S_OK; } //------------------------------------------------------------------------------------------------- bool CD3DSOUND::_Init(HWND hWnd, DWORD dwCoopLevel, DWORD dwPrimaryChannels, DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate) { if ( !CDSOUND::_Init( hWnd, dwCoopLevel, dwPrimaryChannels, dwPrimaryFreq, dwPrimaryBitRate ) ) return false; m_hR = this->Get3DListenerInterface( &m_pDSListener ); if ( FAILED( m_hR ) ) { return false; } // Get listener parameters m_dsListenerParams.dwSize = sizeof( DS3DLISTENER ); m_pDSListener->GetAllParameters( &m_dsListenerParams ); // Set distance factor float fDistanceFactor = 0.01f; // engine space(cm) => dsound space(meter) if ( FAILED(m_pDSListener->SetDistanceFactor(fDistanceFactor, DS3D_DEFERRED)) ) { return false; } //if (FAILED(m_pDSListener->SetRolloffFactor(fGlobal3DVolume * (DS3D_MAXROLLOFFFACTOR - DS3D_MINROLLOFFFACTOR), DS3D_DEFERRED))) { // return false; //} // return true; } //------------------------------------------------------------------------------------------------- t_sounddata* CD3DSOUND::CreateSoundData(t_wavedata* pWave, DWORD dwCreationFlags, GUID guid3DAlgorithm) { t_sounddata* pSound; pSound = CDSOUND::CreateSoundData( pWave, dwCreationFlags, guid3DAlgorithm ); if ( pSound ) { m_hR = pSound->m_pDSB->QueryInterface( IID_IDirectSound3DBuffer, (VOID**)&pSound->m_pDS3DBuffer ); if ( FAILED( m_hR ) ) { this->FreeSoundData( pSound ); DXTRACE_ERR( TEXT("3DS->QueryInterface"), m_hR ); return nullptr; } // Get the 3D buffer parameters m_dsBufferParams.dwSize = sizeof( DS3DBUFFER ); pSound->m_pDS3DBuffer->GetAllParameters( &m_dsBufferParams ); // Set new 3D buffer parameters m_dsBufferParams.flMaxDistance = SOUND_DEFAULT_MAX_DISTANCE; // 여기까지만 볼륨적용 m_dsBufferParams.flMinDistance = SOUND_DEFAULT_MIN_DISTANCE; // 여기까지는 최대 볼륨 적용 m_dsBufferParams.dwMode = DS3DMODE_NORMAL; pSound->m_pDS3DBuffer->SetAllParameters( &m_dsBufferParams, DS3D_DEFERRED ); } return pSound; } t_sounddata* CD3DSOUND::LoadSoundData(LPSTR szFileName, short nMaxMixCnt, GUID guid3DAlgorithm, long lFilePtr) { DWORD dwCreationFlags = DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME; return CDSOUND::LoadSoundData( szFileName, nMaxMixCnt, dwCreationFlags, guid3DAlgorithm, lFilePtr ); } //------------------------------------------------------------------------------------------------- void CD3DSOUND::Set3DBufferParam(t_sounddata* pSound, DS3DBUFFER& dsBufferParam) { pSound->m_pDS3DBuffer->SetAllParameters( &dsBufferParam, DS3D_DEFERRED ); } //------------------------------------------------------------------------------------------------- void CD3DSOUND::SetListenerParam(void) { /* typedef struct _DS3DLISTENER { DWORD dwSize; D3DVECTOR vPosition; D3DVECTOR vVelocity; D3DVECTOR vOrientFront; D3DVECTOR vOrientTop; D3DVALUE flDistanceFactor; D3DVALUE flRolloffFactor; D3DVALUE flDopplerFactor; } DS3DLISTENER, *LPDS3DLISTENER; */ if ( !m_pDSListener ) return; // m_dsListenerParams. // DS3D_DEFERRED : 애플리케이션이 IDirectSound3DListener8::CommitDeferredSettings 메서드를 호출할 때까지, 설정은 적용되지 않는다. 복수의 설정을 변경한 후, 1 회의 재계산으로 그것들을 적용할 수 있다. // DS3D_DEFERRED : 설정을 즉시 적용해, 시스템은 모든 3D 사운드 버퍼의 3D 좌표를 재계산한다. m_pDSListener->SetAllParameters( &m_dsListenerParams, DS3D_DEFERRED ); } //------------------------------------------------------------------------------------------------- void CD3DSOUND::ConvertToSoundSpace(D3DXVECTOR3& posSoundSpace, const D3DXVECTOR3& posWorldSpace) { posSoundSpace.x = posWorldSpace.x; posSoundSpace.y = posWorldSpace.z; // swap y-z posSoundSpace.z = posWorldSpace.y; } //------------------------------------------------------------------------------------------------- bool CD3DSOUND::SetListenerPosition(const D3DXVECTOR3& PosWorld) { if ( !m_pDSListener ) return false; D3DXVECTOR3 PosSound; ConvertToSoundSpace( PosSound, PosWorld ); if ( FAILED(m_pDSListener->SetPosition(PosSound.x, PosSound.y, PosSound.z, DS3D_DEFERRED)) ) { return false; } return true; } //------------------------------------------------------------------------------------------------- bool CD3DSOUND::SetListenerOrientation(const D3DXVECTOR3& PosFront, const D3DXVECTOR3& PosTop) { if ( !m_pDSListener ) return false; if ( FAILED(m_pDSListener->SetOrientation(PosFront.x, PosFront.z, PosFront.y, PosTop.x, PosTop.z, PosTop.y, DS3D_DEFERRED)) ) { return false; } return true; } bool CD3DSOUND::SetListenerRolloffFactor(float fRolloffFactor) { if ( !m_pDSListener ) return false; if ( FAILED(m_pDSListener->SetRolloffFactor( fRolloffFactor, DS3D_DEFERRED)) ) { return false; } return true; } //------------------------------------------------------------------------------------------------- bool CD3DSOUND::UpdateListener(const CCamera* pCamera) { if ( !m_pDSListener ) return false; D3DXVECTOR3 posEye, dirFront, dirTop; HNODE hCamera = pCamera->GetZHANDLE(); if ( 0 == getCameraEye( hCamera, posEye ) ) return false; if ( 0 == getCameraDir( hCamera, dirFront ) ) return false; if ( 0 == getCameraUp( hCamera, dirTop ) ) return false; // 아바타의 위치로 리스너 위치 세팅 //if ( FAILED( SetListenerPosition( g_pAVATAR->Get_CurPOS() ) ) ) { // return false; //} if ( FAILED( SetListenerPosition( posEye ) ) ) { return false; } if ( FAILED( SetListenerOrientation( dirFront, dirTop ) ) ) { return false; } if ( FAILED ( m_pDSListener->CommitDeferredSettings() ) ) { return false; } return true; } bool CD3DSOUND::Set3D(t_sounddata* pData, bool b3DMode) { if ( !pData || !pData->m_pDS3DBuffer ) return false; DWORD dwMode = (b3DMode) ? DS3DMODE_NORMAL : DS3DMODE_DISABLE; return !FAILED( pData->m_pDS3DBuffer->SetMode( dwMode, DS3D_DEFERRED ) ); } bool CD3DSOUND::SetPosition(t_sounddata* pData, const D3DXVECTOR3& posWorld) { if ( !pData || !pData->m_pDS3DBuffer ) return false; D3DXVECTOR3 posSound; ConvertToSoundSpace( posSound, posWorld ); return !FAILED(pData->m_pDS3DBuffer->SetPosition( posSound.x, posSound.y, posSound.z, DS3D_DEFERRED)); } bool CD3DSOUND::SetVelocity(t_sounddata* pData, const D3DXVECTOR3& posVelocity) { if ( !pData || !pData->m_pDS3DBuffer ) return false; D3DXVECTOR3 posSound; ConvertToSoundSpace( posSound, posVelocity ); return !FAILED(pData->m_pDS3DBuffer->SetVelocity( posSound.x, posSound.y, posSound.z, DS3D_DEFERRED)); } bool CD3DSOUND::SetMinDistance(t_sounddata* pData, float fMinDistance) { if ( !pData || !pData->m_pDS3DBuffer ) return false; return !FAILED(pData->m_pDS3DBuffer->SetMinDistance( fMinDistance, DS3D_DEFERRED)); } bool CD3DSOUND::SetMaxDistance(t_sounddata* pData, float fMaxDistance) { if ( !pData || !pData->m_pDS3DBuffer ) return false; return !FAILED(pData->m_pDS3DBuffer->SetMaxDistance( fMaxDistance, DS3D_DEFERRED)); }
[ "ralphminderhoud@gmail.com" ]
ralphminderhoud@gmail.com
681930c0eef10330fc81f6416f6b1cd23e60d40a
8b47f3f365d0176c229190726fefbcdee5157adf
/source/include/Algorithm/Efficiency.h
5394f1db3f59eb1f831a7b83ec81248358c58149
[]
no_license
arnaudsteen/CaloSoftWare
ba1016384f0acd90409c237abaa6b197d9f383b1
d4cd3b25e974e5f6ceacf84152a09df8e9badc71
refs/heads/master
2020-12-13T11:37:24.991298
2017-03-27T13:19:59
2017-03-27T13:19:59
50,678,442
0
4
null
2016-04-05T14:01:17
2016-01-29T17:23:15
C++
UTF-8
C++
false
false
1,159
h
#ifndef EFFICIENCY_HH #define EFFICIENCY_HH #include <iostream> #include <cmath> #include <vector> #include "CaloObject/CaloLayer.h" #include "CaloObject/CaloCluster.h" #include "CaloObject/CaloGeom.h" #include "Algorithm/Tracking.h" #include "Algorithm/Distance.h" namespace algorithm{ struct EfficiencyParameterSetting{ float maxRadius; bool semiDigitalReadout; bool printDebug; caloobject::GeomParameterSetting geometry; algorithm::TrackingParameterSetting trackingParams; EfficiencyParameterSetting() : maxRadius(25.0) , semiDigitalReadout(true) , printDebug(false) {;} }; class Efficiency { public: Efficiency(){;} ~Efficiency(){;} inline void SetEfficiencyParameterSetting(EfficiencyParameterSetting params){settings=params;} inline CLHEP::Hep3Vector &getExpectedPosition(){return expectedPos;} void Run(caloobject::CaloLayer *layer, std::vector<caloobject::CaloCluster2D*> &clusters); private: EfficiencyParameterSetting settings; CLHEP::Hep3Vector expectedPos; }; } #endif
[ "arnaudsteen2.0@gmail.com" ]
arnaudsteen2.0@gmail.com
38809a4cca40d37ccc35bb95b46de9c9f6775bb7
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_repos_function_5496_git-2.12.3.cpp
174a1672fe0195da4399b5c407a6b51cca4bd1c1
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map, const char *raw_url) { int url_len, i, result = 0; struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map); char *url; int summary_width = transport_summary_width(stale_refs); const char *dangling_msg = dry_run ? _(" (%s will become dangling)") : _(" (%s has become dangling)"); if (raw_url) url = transport_anonymize_url(raw_url); else url = xstrdup("foreign"); url_len = strlen(url); for (i = url_len - 1; url[i] == '/' && 0 <= i; i--) ; url_len = i + 1; if (4 < i && !strncmp(".git", url + i - 3, 4)) url_len = i - 3; if (!dry_run) { struct string_list refnames = STRING_LIST_INIT_NODUP; for (ref = stale_refs; ref; ref = ref->next) string_list_append(&refnames, ref->name); result = delete_refs(&refnames, 0); string_list_clear(&refnames, 0); } if (verbosity >= 0) { for (ref = stale_refs; ref; ref = ref->next) { struct strbuf sb = STRBUF_INIT; if (!shown_url) { fprintf(stderr, _("From %.*s\n"), url_len, url); shown_url = 1; } format_display(&sb, '-', _("[deleted]"), NULL, _("(none)"), prettify_refname(ref->name), summary_width); fprintf(stderr, " %s\n",sb.buf); strbuf_release(&sb); warn_dangling_symref(stderr, dangling_msg, ref->name); } } free(url); free_refs(stale_refs); return result; }
[ "993273596@qq.com" ]
993273596@qq.com
285f78aaf757ce28cc6c2d504157614e09462a30
afc255608753ab472bb0c8d953fb0361bc4ab635
/BLUE_ENGINE/JSONWRITER.h
9adc97a895ed80981be74f264dd27445575c2049
[]
no_license
Nero-TheThrill/-Game-waybackhome_built-with-customengine
23e8e9866c5e822ed6c507232a9ca25e4a7746ad
70beab0fb81c203701a143244d65aff89b08d104
refs/heads/master
2023-08-21T03:02:28.904343
2021-11-02T11:01:50
2021-11-02T11:01:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
h
/* * File Name : JSONWRITER.h * Primary Author : Choi Jinwoo * Secondary Author : * Brief: Make easy to load/save objects. * * Copyright (C) 2019 DigiPen Institute of Technology. */ #pragma once #include <string> #include <vector> #include<fstream> namespace rapidjson { class JSONwriter { public: JSONwriter(); ~JSONwriter(); void WriteToFile(const std::string& path); void ClearFile(const std::string& path); const char* GetString() const; operator bool() const { return true; } JSONwriter& StartObject(); JSONwriter& Member(const char* name); bool HasMember(const char* name) const; JSONwriter& EndObject(); JSONwriter& StartArray(size_t* size = 0); JSONwriter& EndArray(); JSONwriter& operator&(bool& b); JSONwriter& operator&(unsigned& u); JSONwriter& operator&(int& i); JSONwriter& operator&(double d); JSONwriter& operator&(std::string s); JSONwriter& SetNull(); static const bool IsReader = false; static const bool IsWriter = !IsReader; private: JSONwriter(const JSONwriter&); JSONwriter& operator=(const JSONwriter&); void* Writer; void* Stream; }; }
[ "imjinwoo98@gmail.com" ]
imjinwoo98@gmail.com
2702f89f09657e4fc8375b63b44cdbc9fa4de463
9e3415355ca51d30d3f33f668ba2d4d721192877
/Cpp/Controls/Common.h
b22229687bd72dc317c709e5cf1633ec4c3ec2e4
[]
no_license
neugen86/TimeLineReworked
286e272d4b4e44bd57807d82bcbc35cabef1a8d3
3c0850c76fdb84f65c1ee515f5e4a754bdf07d5e
refs/heads/master
2020-03-21T23:35:35.697313
2018-07-01T09:54:16
2018-07-01T09:54:16
139,196,398
1
0
null
null
null
null
UTF-8
C++
false
false
2,530
h
#pragma once #include <QList> #include <QColor> #include "TimeUtils.h" const double MIN_ITEM_WIDTH = 3; const QColor SINGLE_ITEM_COLOR(Qt::cyan); const QColor GROUP_ITEM_COLOR(Qt::green); template <typename T> class IDataProvider { public: virtual ~IDataProvider() {} virtual T getData() = 0; }; struct TimeInterval { std::time_t from = 0; std::time_t duration = 0; TimeInterval() = default; TimeInterval(std::time_t from, std::time_t duration) : from(std::max(std::time_t(0), from)) , duration(std::max(std::time_t(500), std::min(std::time_t(3153600000), duration))) {} ///Note: disabled until no dynamic types // virtual ~TimeInterval() {} bool contains(const TimeInterval& other) const { return (other.duration > 0) && (other.from >= from) && (other.from < till()); } std::time_t till() const { return (from + duration); } }; struct NamedInterval : public TimeInterval { QString title; NamedInterval(const QString& title, std::time_t from, std::time_t duration) : TimeInterval(from, duration) , title(title) {} }; using NamedIntervalList = QList<NamedInterval>; struct TimeLineItem { struct Segment { double start = 0; double width = 0; Segment() = default; }; Segment segment; QColor color; QString title; QString description; TimeLineItem() = default; TimeLineItem(const QString& title, const Segment& segment, const QColor& color) : segment(segment) , color(color) , title(title) , description(title) { this->segment.width = std::max(this->segment.width, MIN_ITEM_WIDTH); } TimeLineItem(const QString& title, const QString& description, const Segment& segment, const QColor& color) : TimeLineItem(title, segment, color) { this->description = description; } static TimeLineItem single(const QString& title, const Segment& segment) { return TimeLineItem(title, segment, SINGLE_ITEM_COLOR); } static TimeLineItem group(int count, const QString& description, const Segment& segment) { return TimeLineItem(QString::number(count), description, segment, GROUP_ITEM_COLOR); } }; using TimeLineItemList = QList<TimeLineItem>; inline bool operator <(const TimeInterval& lhv, const TimeInterval& rhv) { return lhv.from < rhv.from; }
[ "neugen86@gmail.com" ]
neugen86@gmail.com
50e78379d6ac8329018af18552dd48d0810edcdd
5989c871781855a835f3c6727c7abf409c6f16db
/Video_Input_and_Output/Video_Input_and_Output/Video_Input_and_Output.cpp
b2a4622c1af1af6bb6d86445f76b849e32487145
[]
no_license
linmonsv/OpenCV_Tutorials
a8bf63972b4f3dde53e9a0d87f56aa8dacdca497
3c18669450014f22e2bcb8048159b9549944ba2b
refs/heads/master
2023-01-19T22:22:22.741619
2020-11-27T09:41:34
2020-11-27T09:41:34
266,031,866
1
0
null
null
null
null
UTF-8
C++
false
false
6,266
cpp
#include <iostream> // for standard I/O #include <string> // for strings #include <iomanip> // for controlling float print precision #include <sstream> // string to number conversion #include <opencv2/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar) #include <opencv2/imgproc.hpp> // Gaussian Blur #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> // OpenCV window I/O using namespace std; using namespace cv; double getPSNR(const Mat& I1, const Mat& I2); Scalar getMSSIM(const Mat& I1, const Mat& I2); static void help() { cout << "------------------------------------------------------------------------------" << endl << "This program shows how to read a video file with OpenCV. In addition, it " << "tests the similarity of two input videos first with PSNR, and for the frames " << "below a PSNR trigger value, also with MSSIM." << endl << "Usage:" << endl << "./video-input-psnr-ssim <referenceVideo> <useCaseTestVideo> <PSNR_Trigger_Value> <Wait_Between_Frames> " << endl << "--------------------------------------------------------------------------" << endl << endl; } int main(int argc, char* argv[]) { help(); if (argc != 5) { cout << "Not enough parameters" << endl; //return -1; } stringstream conv; const string sourceReference = "../../data/Megamind.avi", sourceCompareWith = "../../data/Megamind_bugy.avi"; int psnrTriggerValue, delay; conv << 35 << endl << 10; // put in the strings conv >> psnrTriggerValue >> delay; // take out the numbers int frameNum = -1; // Frame counter VideoCapture captRefrnc(sourceReference), captUndTst(sourceCompareWith); if (!captRefrnc.isOpened()) { cout << "Could not open reference " << sourceReference << endl; return -1; } if (!captUndTst.isOpened()) { cout << "Could not open case test " << sourceCompareWith << endl; return -1; } Size refS = Size((int)captRefrnc.get(CAP_PROP_FRAME_WIDTH), (int)captRefrnc.get(CAP_PROP_FRAME_HEIGHT)), uTSi = Size((int)captUndTst.get(CAP_PROP_FRAME_WIDTH), (int)captUndTst.get(CAP_PROP_FRAME_HEIGHT)); if (refS != uTSi) { cout << "Inputs have different size!!! Closing." << endl; return -1; } const char* WIN_UT = "Under Test"; const char* WIN_RF = "Reference"; // Windows namedWindow(WIN_RF, WINDOW_AUTOSIZE); namedWindow(WIN_UT, WINDOW_AUTOSIZE); moveWindow(WIN_RF, 400, 0); //750, 2 (bernat =0) moveWindow(WIN_UT, refS.width, 0); //1500, 2 cout << "Reference frame resolution: Width=" << refS.width << " Height=" << refS.height << " of nr#: " << captRefrnc.get(CAP_PROP_FRAME_COUNT) << endl; cout << "PSNR trigger value " << setiosflags(ios::fixed) << setprecision(3) << psnrTriggerValue << endl; Mat frameReference, frameUnderTest; double psnrV; Scalar mssimV; for (;;) //Show the image captured in the window and repeat { captRefrnc >> frameReference; captUndTst >> frameUnderTest; if (frameReference.empty() || frameUnderTest.empty()) { cout << " < < < Game over! > > > "; break; } ++frameNum; cout << "Frame: " << frameNum << "# "; psnrV = getPSNR(frameReference, frameUnderTest); cout << setiosflags(ios::fixed) << setprecision(3) << psnrV << "dB"; if (psnrV < psnrTriggerValue && psnrV) { mssimV = getMSSIM(frameReference, frameUnderTest); cout << " MSSIM: " << " R " << setiosflags(ios::fixed) << setprecision(2) << mssimV.val[2] * 100 << "%" << " G " << setiosflags(ios::fixed) << setprecision(2) << mssimV.val[1] * 100 << "%" << " B " << setiosflags(ios::fixed) << setprecision(2) << mssimV.val[0] * 100 << "%"; } cout << endl; imshow(WIN_RF, frameReference); imshow(WIN_UT, frameUnderTest); char c = (char)waitKey(delay); if (c == 27) break; } return 0; } double getPSNR(const Mat& I1, const Mat& I2) { Mat s1; absdiff(I1, I2, s1); // |I1 - I2| s1.convertTo(s1, CV_32F); // cannot make a square on 8 bits s1 = s1.mul(s1); // |I1 - I2|^2 Scalar s = sum(s1); // sum elements per channel double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels if (sse <= 1e-10) // for small values return zero return 0; else { double mse = sse / (double)(I1.channels() * I1.total()); double psnr = 10.0 * log10((255 * 255) / mse); return psnr; } } Scalar getMSSIM(const Mat& i1, const Mat& i2) { const double C1 = 6.5025, C2 = 58.5225; /***************************** INITS **********************************/ int d = CV_32F; Mat I1, I2; i1.convertTo(I1, d); // cannot calculate on one byte large values i2.convertTo(I2, d); Mat I2_2 = I2.mul(I2); // I2^2 Mat I1_2 = I1.mul(I1); // I1^2 Mat I1_I2 = I1.mul(I2); // I1 * I2 /*************************** END INITS **********************************/ Mat mu1, mu2; // PRELIMINARY COMPUTING GaussianBlur(I1, mu1, Size(11, 11), 1.5); GaussianBlur(I2, mu2, Size(11, 11), 1.5); Mat mu1_2 = mu1.mul(mu1); Mat mu2_2 = mu2.mul(mu2); Mat mu1_mu2 = mu1.mul(mu2); Mat sigma1_2, sigma2_2, sigma12; GaussianBlur(I1_2, sigma1_2, Size(11, 11), 1.5); sigma1_2 -= mu1_2; GaussianBlur(I2_2, sigma2_2, Size(11, 11), 1.5); sigma2_2 -= mu2_2; GaussianBlur(I1_I2, sigma12, Size(11, 11), 1.5); sigma12 -= mu1_mu2; Mat t1, t2, t3; t1 = 2 * mu1_mu2 + C1; t2 = 2 * sigma12 + C2; t3 = t1.mul(t2); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2)) t1 = mu1_2 + mu2_2 + C1; t2 = sigma1_2 + sigma2_2 + C2; t1 = t1.mul(t2); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2)) Mat ssim_map; divide(t3, t1, ssim_map); // ssim_map = t3./t1; Scalar mssim = mean(ssim_map); // mssim = average of ssim map return mssim; }
[ "qin2@qq.com" ]
qin2@qq.com
f3b27ff2c77cb867cbfe622abab84a93a61a48a3
c3b728c62524fea69352a12b1a5a80010dd250d9
/src/xml/XmlParser.cpp
a09448397e428af09b2ccaa0f304097618aac6b1
[]
no_license
hushouguo/libbundle
b96ccb1d3b2fa3b94809eea7e67dead46ee83b5d
7abaf37c6081f17b85bfca5bd7ee72fd690ea641
refs/heads/master
2020-03-28T20:17:10.649431
2018-11-30T07:03:57
2018-11-30T07:03:57
149,056,079
0
0
null
null
null
null
UTF-8
C++
false
false
4,120
cpp
/* * \file: XmlParser.cpp * \brief: Created by hushouguo at 09:54:48 Jan 22 2018 */ #include "bundle.h" BEGIN_NAMESPACE_BUNDLE { XmlParser::XmlParser() { } XmlParser::~XmlParser() { } bool XmlParser::open(std::string xmlfile) { return this->open(xmlfile.c_str()); } bool XmlParser::open(const char* xmlfile) { try { rapidxml::file<> fileDoc(xmlfile); doc.parse<0>(fileDoc.data()); } catch (std::exception& e) { Error.cout("xmlParser exception: %s, filename: %s", e.what(), xmlfile); return false; } //file content: doc.name() return true; } void XmlParser::final() { } XmlParser::XML_NODE XmlParser::getRootNode() { return doc.first_node(); } XmlParser::XML_NODE XmlParser::getChildNode(XML_NODE xmlNode, const char* name) { if (name != nullptr) { return xmlNode->first_node(name); } return xmlNode->first_node(); } XmlParser::XML_NODE XmlParser::getNextNode(XML_NODE xmlNode, const char* name) { if (name != nullptr) { return xmlNode->next_sibling(name); } return xmlNode->next_sibling(); } const char* XmlParser::getValueByString(XML_NODE xmlNode, const char* name, const char* defaultValue) { rapidxml::xml_attribute<char> * attr = nullptr; if (name != nullptr) { attr = xmlNode->first_attribute(name); } else { attr = xmlNode->first_attribute(); } return attr == nullptr ? defaultValue : attr->value(); } const uint32_t XmlParser::getValueByInteger(XML_NODE xmlNode, const char* name, uint32_t defaultValue) { rapidxml::xml_attribute<char> * attr = nullptr; if (name != nullptr) { attr = xmlNode->first_attribute(name); } else { attr = xmlNode->first_attribute(); } return attr == nullptr ? defaultValue : strtoul((char*)attr->value(), (char**)nullptr, 10); } void XmlParser::getValues(XML_NODE xmlNode, std::map<std::string, std::string> values) { for (rapidxml::xml_attribute<char> * attr = xmlNode->first_attribute(); attr != NULL; attr = attr->next_attribute()) { values.insert(std::make_pair((const char*)attr->name(), (const char*)attr->value())); } } void XmlParser::makeRegistry(Registry* registry, const char* prefix) { this->makeRegistry(registry, this->getRootNode(), prefix); } void XmlParser::makeRegistry(Registry* registry, XML_NODE xmlNode, std::string name) { if (!xmlNode) { return; } for (rapidxml::xml_attribute<char> * attr = xmlNode->first_attribute(); attr; attr = attr->next_attribute()) { //if (xmlNode == this->getRootNode()) { if (name.length() > 0) { char buf[1024]; snprintf(buf, sizeof(buf), "%s.%s.%s", name.c_str(), xmlNode->name(), attr->name()); if (!registry->set(buf, attr->value())) { Error << "duplicate key: " << buf; } } else { char buf[1024]; snprintf(buf, sizeof(buf), "%s.%s", xmlNode->name(), attr->name()); if (!registry->set(buf, attr->value())) { Error << "duplicate key: " << buf; } } } if (xmlNode == this->getRootNode()) { this->makeRegistry(registry, this->getChildNode(xmlNode), ""); } else { if (name.length() > 0) { this->makeRegistry(registry, this->getChildNode(xmlNode), name + "." + xmlNode->name()); } else { this->makeRegistry(registry, this->getChildNode(xmlNode), xmlNode->name()); } } this->makeRegistry(registry, this->getNextNode(xmlNode), name); } void XmlParser::dump() { dump(getRootNode(), 0); } void XmlParser::dump(XML_NODE xmlNode, int depth) { if (!xmlNode) { return; } for (int i = 0; i < depth; ++i) { Trace.cout("\t"); } Trace.cout("<%s", xmlNode->name()); for (rapidxml::xml_attribute<char> * attr = xmlNode->first_attribute(); attr != nullptr; attr = attr->next_attribute()) { Trace.cout(" %s=\"%s\"", attr->name(), attr->value()); } if (!getChildNode(xmlNode)) { Trace.cout(" />\n"); } else { Trace.cout(">\n"); } dump(getChildNode(xmlNode), depth + 1); if (getChildNode(xmlNode)) { for (int i = 0; i < depth; ++i) { Trace.cout("\t"); } Trace.cout("</%s>\n", xmlNode->name()); } dump(getNextNode(xmlNode), depth); } }
[ "kilimajaro@gmail.com" ]
kilimajaro@gmail.com
c89ce6a0f2f9d7f4a49c4f95bd30c98b31acc309
3ae963293c0d6302ff71762dbd1760d8c605f98f
/Time-Varying Volume-graphInfo/proj/src/tf/1dtf/Ref/IntensityHistogram.h
8e8894c7c1a3a17a1d80fac0acb00772399e33ae
[]
no_license
Smlience/Tracking-TimeVarying-Data
b8bda6609d722aa1f2a47c773b8cd2d9101c072e
3c2ab3e9069dbe9c5ae919aea5d0d80f96a0c57e
refs/heads/master
2021-01-20T23:17:22.145255
2014-08-22T04:41:58
2014-08-22T04:41:58
23,099,760
1
0
null
null
null
null
GB18030
C++
false
false
1,981
h
#ifndef INTENSITYHISTOGRAM_H #define INTENSITYHISTOGRAM_H #include "util/Vector3.h" #include "util/Vector4.h" #include "dm/Volume.h" #include <vector> typedef struct IntensityEntry { int featureLabel; int scalar; int voxelCount; Vector3d baryCenter; double variance; double size; double weight;//在聚类时用于存放entry与Feature之间的差异 bool isSeed; } IntensityEntry; typedef struct IntensityFeature { int label; int entryCount; int voxelCount; Vector3d baryCenter; double variance; double maxSize; double weight;//用于Feature的排序 Color4 color; std::vector<int> vEntry; } IntensityFeature; class IntensityHistogram { public: IntensityHistogram(); ~IntensityHistogram(); void calcHistogram(Volume* pVolume); void setThreshold(double delta); void colorAt(int sv, unsigned char& r, unsigned char& g, unsigned char& b, unsigned char& a); std::vector<IntensityFeature*> getFeatureList(); void setFeatureSelected(int label); void setFeatureSelected(std::vector<int> vLabel); float getNormalized(int entry); float getLogNormalized(int entry); void setSortWeight( float a, float b, float c ); void addUserSpecifiedOpacity(int label, int opacity); void removeUserSpecifiedOpacity(int label); void setTao(double t); private: void clear(); void clearEntry(IntensityEntry* pEntry); void cluster(); void clusterRG(); void addToEntry(int sv, Vector3d& pos); double calcDistance(IntensityEntry* pEntry, IntensityFeature* pFeature); void calcOpacityForSelectedFeatures(); void measureFeature(IntensityFeature* pFeature); private: IntensityEntry* m_entry; std::vector<IntensityFeature*> m_vFeature; std::vector<int> m_vSelected; std::vector<std::pair<int, int>> m_vUserSpecified; double m_threshold; int m_iMaxVoxelCount; int m_iMinVoxelCount; double m_maxEntrySize; double m_minEntrySize; Volume* m_pVolume; int m_growSpan; float m_alpha; float m_beta; float m_gamma; double m_tao; }; #endif // INTENSITYHISTOGRAM_H
[ "smilence@zju.edu.cn" ]
smilence@zju.edu.cn
b3d6f772d7e0d323f53c2d3a156cded04de3caad
c74f84e03d6fe4d28a1bb2e5d9c52632335d0fe7
/OShomework/file.h
7118f871649c1af87a2d6c32c9efcedfe4746f13
[]
no_license
Athenezhuyin/OS
4b74171cd320e7f61eac8a5eab63eee03018b577
04b542940a1dd43c4e257a9dfbcf9dd955a113a4
refs/heads/master
2020-04-19T10:10:40.407077
2016-08-23T03:31:37
2016-08-23T03:31:37
66,329,564
0
0
null
null
null
null
UTF-8
C++
false
false
2,521
h
#ifndef FILE_H #define FILE_H #include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> #include<string> using namespace std; //文件元素可供操作的权限 typedef enum { readonly, //只读 readwrite //可写 }FileAccess; typedef enum { file, //文件 dir //目录 }FileType; typedef enum { closed, opened, writing }FileState; //一个文件索引的结构 typedef struct { int indexnum; //索引序号 char filename[20]; //文件名 char parentfilename[20]; //父节点文件名 int filelevel; //文件所在层级 int effect; //文件有效性 int filetype; //文件属性 struct fse* fcb; //指向自身的FCB } FileIndexElement; //文件系统索引结构 typedef struct { FileIndexElement index[100]; //索引数组 int indexcount; //现有的索引数量 } FileIndex; //文件系统中的元素结构,包括文件和目录 typedef struct fse { int flevel; //文件所在的层次,层+文件元素名为一个文件的逻辑位置 char fname[20]; //文件名 char parent[20]; //父文件名 int blocknum[50]; //文件所在的物理块编号 int flen; //文件长度 FileType ftype; //文件类型 FileAccess facc; //文件权限 int feffect; //表征文件是否被删除,0表示无效文件,1表示有效 char createtime[20]; //创建时间 char lastmodtime[20]; //最后一次修改时间 FileState fstate; //文件当前状态 char child[10][20]; //如果该文件为目录,则数组中存放其后继的子文件;如果是普通文件,则该数组为空 int childnum; //子文件数目 } FCB; //系统当前状态 typedef struct { int filelevel; //当前所在文件系统层 FCB* currparent; //当前层的父节点 char* currentpath; //当前路径 } CState; const int FileSysSize = 1024*512; //文件系统物理空间大小 512K const int BlockSize = 1024; //块大小1K const int BlockCount = 512; //块数量512,物理空间512K const int BitMapLen = 512; //位示图长度 const int CommandLen = 50; //用户命令最大长度 const int CommandCount = 8; //预设用户命令数 extern int bitmap[512]; //位示图,0表示空闲,1表示占用 extern char* filesys ; //文件系统物理空间地址 extern CState CS; //当前系统状态 extern FileIndex FI; //系统索引 extern FILE* fmlog; //日志文件 extern char logtime[20]; //日志时间 #endif // FILE_H
[ "?? ?" ]
?? ?
94231a302aa1875c194d2a39fa72b89d6baa3eb2
c0fa1b924f715268a0113e0067994c92a96f75cd
/UTS/Ans/D.cpp
fe67a0c2df1c650338b284b9c864b8cfa16a1101
[]
no_license
temptedwithouta/socs1.binus.ac.id
93183deff6719ed578999bdb9bd1bef330e06da1
2b38c36a5faa621bdf08febc75dd89f8ade3298d
refs/heads/main
2023-03-08T03:47:09.723409
2021-02-15T15:14:41
2021-02-15T15:14:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
#include <stdio.h> #include <math.h> int main(){ int tc; scanf("%d", &tc); for (int q = 1; q <= tc; q++) { int a, b, c, i = 1, time = 0; scanf ("%d %d %d", &a, &b, &c); while (1) { int red = b, black = c; i % 4 == 0 ? red -= floor(red/3) : red *= 2; i % 3 == 0 ? black -= floor(0.8 * black) : black *= 3; if (red + black <= a) { b = red; c = black; time++; i++; } else break; } printf("Case #%d: ", q); printf ("%d ", time); b > c ? printf ("Red %d\n", b - c) : c > b ? printf ("Black %d\n", c - b) : printf ("None 0\n"); } return 0; }
[ "qbin.hermawan@gmail.com" ]
qbin.hermawan@gmail.com
9ec7e1d633e555d4048cb926ec94a42aa7fc91e1
45f66fbc4e9af69c35757b8977ce274b805c4075
/0.9.0.0/base/API.cpp
bb82cc343564fbf47682ced3e0fbff99e69c466e
[]
no_license
qualityking/clarice
5c7760b16dd620c5e68d7d71ddcd1baa9c40b6c0
c2435e10a4633545475820eb0b8530b86d6ed942
refs/heads/master
2021-05-11T05:56:46.102665
2017-05-20T02:29:06
2017-05-20T02:29:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,920
cpp
#include "base/API.h" #include "base/Line.h" #include "base/LineGroup.h" #include "base/FeedHandler.h" using namespace base; extern "C" CallBacks getCallback(const std::string updateType) { if(updateType == "ORDER") { return ORDER; } else if(updateType == "BOOK") { return BOOK; } else if(updateType == "STATUS") { return STATUS; } else if(updateType == "QUOTE") { return QUOTE; } else if(updateType == "CUSTOM") { return CUSTOM; } else if(updateType == "ALL") { return ALL_CALLBACKS; } else { return NO_CALLBACK; } } void FeedAPI::onFeedStarted(const FeedHandler *feedHandler) { } void FeedAPI::onFeedStopped(const FeedHandler *feedHandler) { } FeedAPI::FeedAPI() : LineGroupAPI() , _onFeedStarted(&FeedAPI::onFeedStarted) , _onFeedStopped(&FeedAPI::onFeedStopped) { } FeedAPI::FeedAPI(OnFeedStarted onFeedStarted, OnFeedStopped onFeedStopped, OnLineGroupStarted onLineGroupStarted, OnLineGroupStopped onLineGroupStopped, OnLineStarted onLineStarted, OnLineStopped onLineStopped, OnPacketStart onPacketStart, OnPacketEnd onPacketEnd, OnOrder onOrder, OnBook onBook, OnQuote onQuote, OnTrade onTrade, OnStatus onStatus, OnCustom onCustom, OnProductInfo onProductInfo) : LineGroupAPI(onLineGroupStarted, onLineGroupStopped, onLineStarted, onLineStopped, onPacketStart, onPacketEnd, onOrder , onBook , onQuote , onTrade , onStatus , onCustom , onProductInfo) , _onFeedStarted(onFeedStarted) , _onFeedStopped(onFeedStopped) { } void LineGroupAPI::onLineGroupStarted(const LineGroup *lineGroup) { } void LineGroupAPI::onLineGroupStopped(const LineGroup *lineGroup) { } LineGroupAPI::LineGroupAPI() : LineAPI() , _onLineGroupStarted(&LineGroupAPI::onLineGroupStarted) , _onLineGroupStopped(&LineGroupAPI::onLineGroupStopped) { } LineGroupAPI::LineGroupAPI(OnLineGroupStarted onLineGroupStarted, OnLineGroupStopped onLineGroupStopped, OnLineStarted onLineStarted, OnLineStopped onLineStopped, OnPacketStart onPacketStart, OnPacketEnd onPacketEnd, OnOrder onOrder, OnBook onBook, OnQuote onQuote, OnTrade onTrade, OnStatus onStatus, OnCustom onCustom, OnProductInfo onProductInfo) : LineAPI(onLineStarted, onLineStopped, onPacketStart, onPacketEnd, onOrder , onBook , onQuote , onTrade , onStatus , onCustom , onProductInfo) , _onLineGroupStarted(onLineGroupStarted) , _onLineGroupStopped(onLineGroupStopped) { } void LineAPI::onLineStarted(const Line *pLine) { } void LineAPI::onLineStopped(const Line *pLine) { } void LineAPI::onPacketStart(const Line *pLine) { } void LineAPI::onPacketEnd(const Line *pLine) { } void LineAPI::onProductInfo(const ProductInfo *product) { } void LineAPI::onOrder(const Order *order) { } void LineAPI::onBook(const Book *book) { } void LineAPI::onQuote(const Quote *quote) { } void LineAPI::onTrade(const Trade *trade, const Order *order) { } void LineAPI::onStatus(const Status *status) { } void LineAPI::onCustom(const Custom *custom) { } LineAPI::LineAPI() : _onLineStarted(&LineAPI::onLineStarted) , _onLineStopped(&LineAPI::onLineStopped) , _onPacketStart(&LineAPI::onPacketStart) , _onPacketEnd(&LineAPI::onPacketEnd) , _onOrder(&LineAPI::onOrder) , _onBook(&LineAPI::onBook) , _onQuote(&LineAPI::onQuote) , _onTrade(&LineAPI::onTrade) , _onStatus(&LineAPI::onStatus) , _onCustom(&LineAPI::onCustom) , _onProductInfo(&LineAPI::onProductInfo) { } LineAPI::LineAPI(OnLineStarted onLineStarted, OnLineStopped onLineStopped, OnPacketStart onPacketStart, OnPacketEnd onPacketEnd, OnOrder onOrder, OnBook onBook, OnQuote onQuote, OnTrade onTrade, OnStatus onStatus, OnCustom onCustom, OnProductInfo onProductInfo) : _onLineStarted(onLineStarted) , _onLineStopped(onLineStopped) , _onPacketStart(onPacketStart) , _onPacketEnd(onPacketEnd) , _onOrder(onOrder) , _onBook(onBook) , _onQuote(onQuote) , _onTrade(onTrade) , _onStatus(onStatus) , _onCustom(onCustom) , _onProductInfo(onProductInfo) { }
[ "rahul.deshmukhpatil@gmail.com" ]
rahul.deshmukhpatil@gmail.com
edf1e3731e29712bc9a38066444ba91484a6ca0a
21b7d8820a0fbf8350d2d195f711c35ce9865a21
/HDD is Outdated Technology.cpp
58193e161962c1a60575e70e8e74befef3af64fd
[]
no_license
HarshitCd/Codeforces-Solutions
16e20619971c08e036bb19186473e3c77b9c4634
d8966129b391875ecf93bc3c03fc7b0832a2a542
refs/heads/master
2022-12-25T22:00:17.077890
2020-10-12T16:18:20
2020-10-12T16:18:20
286,409,002
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
#include<bits/stdc++.h> using namespace std; int main(){ long long n, ans=0; cin>>n; vector<pair<int, int>> v(n); for(int i=0; i<n; i++){ cin>>v[i].first; v[i].second = i; } sort(v.begin(), v.end()); for(int i=0; i<n-1; i++){ ans+=abs(v[i].second-v[i+1].second); } cout<<ans; return 0; }
[ "harshitcd@gmail.com" ]
harshitcd@gmail.com
803451215e8bd8aa33b859e1128a1ea4d2b28bbc
991f950cc9096522cc8d1442e7689edca6288179
/Codeforces/1000~1999/1091/C.cpp
ac6b97595c44b0240c75edc9aa1ad3777efb5efc
[ "MIT" ]
permissive
tiger0132/code-backup
1a767e8debeddc8054caa018f648c5e74ff9d6e4
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
refs/heads/master
2021-06-18T04:58:31.395212
2021-04-25T15:23:16
2021-04-25T15:23:16
160,021,239
3
0
null
null
null
null
UTF-8
C++
false
false
398
cpp
#include <algorithm> #include <cstdio> #include <set> #define int long long const int N = 1e3+31; std::set<int> s; int n; signed main() { scanf("%lld", &n); for (int i = 1; i*i <= n; i++) { if (n % i) continue; s.insert((2 + (n / i - 1) * i) * (n / i) / 2); i = n / i; s.insert((2 + (n / i - 1) * i) * (n / i) / 2); i = n / i; } for (const auto& i : s) { printf("%lld ", i); } }
[ "4c5948@gmail.com" ]
4c5948@gmail.com
c1be8d557b0c253e081bfa79967aa6401986aa00
64058e1019497fbaf0f9cbfab9de4979d130416b
/c++/include/objects/seqset/Bioseq_set.hpp
867f66698a6b84b6ddfbefacdefd28888ca64555
[ "MIT" ]
permissive
OpenHero/gblastn
31e52f3a49e4d898719e9229434fe42cc3daf475
1f931d5910150f44e8ceab81599428027703c879
refs/heads/master
2022-10-26T04:21:35.123871
2022-10-20T02:41:06
2022-10-20T02:41:06
12,407,707
38
21
null
2020-12-08T07:14:32
2013-08-27T14:06:00
C++
UTF-8
C++
false
false
3,728
hpp
/* $Id: Bioseq_set.hpp 132506 2008-06-30 18:09:32Z kans $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: ....... * * File Description: * ....... * * Remark: * This code was originally generated by application DATATOOL * using specifications from the ASN data definition file * 'seqset.asn'. * */ #ifndef OBJECTS_SEQSET_BIOSEQ_SET_HPP #define OBJECTS_SEQSET_BIOSEQ_SET_HPP // generated includes #include <objects/seqset/Bioseq_set_.hpp> // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: class CSeq_entry; class CBioseq; class NCBI_SEQSET_EXPORT CBioseq_set : public CBioseq_set_Base { typedef CBioseq_set_Base Tparent; public: // constructor CBioseq_set(void); // destructor ~CBioseq_set(void); // Manage Seq-entry tree structure // get parent Seq-entry. // NULL means that either there is no parent Seq-entry, // or CSeq_entry::Parentize() was never called. CSeq_entry* GetParentEntry(void) const; // Convenience function to directly get reference to parent Bioseq-set. // 0 means that either there is no parent Seq-entry or Bioseq-set, // or CSeq_entry::Parentize() was never called. CConstRef<CBioseq_set> GetParentSet(void) const; enum ELabelType { eType, eContent, eBoth }; // Append a label to label based on type or content of CBioseq_set void GetLabel(string* label, ELabelType type) const; // Class specific methods // methods will throw if called on an object with the wrong TClass value. const CBioseq& GetNucFromNucProtSet(void) const; const CBioseq& GetGenomicFromGenProdSet(void) const; const CBioseq& GetMasterFromSegSet(void) const; private: // Prohibit copy constructor & assignment operator CBioseq_set(const CBioseq_set&); CBioseq_set& operator= (const CBioseq_set&); // Seq-entry containing the Bioseq void SetParentEntry(CSeq_entry* entry); CSeq_entry* m_ParentEntry; friend class CSeq_entry; }; /////////////////// CBioseq_set inline methods // constructor inline CBioseq_set::CBioseq_set(void) : m_ParentEntry(0) { } inline void CBioseq_set::SetParentEntry(CSeq_entry* entry) { m_ParentEntry = entry; } inline CSeq_entry* CBioseq_set::GetParentEntry(void) const { return m_ParentEntry; } /////////////////// end of CBioseq_set inline methods END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_SEQSET_BIOSEQ_SET_HPP
[ "zhao.kaiyong@gmail.com" ]
zhao.kaiyong@gmail.com
80bc2823f56eeb4f58db806feed7eb5fed127a53
9fe8a99d8f3ab04419ee1545fb69833a600c4a6e
/Others/BRW2/src/rdp.h
a68993a41e9cb87e5d69f9fa115901a800b4cae7
[]
no_license
javad-zarrin/HARD
aadec2a356886a8054433df223bade77c81ff366
454e2f0f8c33787fe440c8ad7abeac6667cec029
refs/heads/master
2021-05-03T07:15:15.335939
2018-02-07T12:11:56
2018-02-07T12:11:56
120,604,903
0
0
null
null
null
null
UTF-8
C++
false
false
39,132
h
/* * File: rdp.h * Author: jzarrin * * Created on 28 November 2012, 15:37 */ #ifndef RDP_H #define RDP_H #include <stdio.h> #include <iostream> #include <stdlib.h> #include <fstream> #include <sstream> #include <bitset> #include <cstdlib> #include <string.h> #include <strings.h> #include <string> #include <vector> #include <map> #include "query.h" using namespace std; typedef std::vector<std::string> conditions; // At_ID:Op_ID:At_VA:La_ID:At_TY , At_ID:Op_ID$ typedef std::pair<int,conditions> HO_Resource_Collection; // Number of Homegenous Resources$ typedef std::vector<HO_Resource_Collection> HE_Resource_Collection; static const int key_size=64;//bits - 160 bits; 4 attributes , 16 chars - 16 bytes key static const int id_char_size=16;//40;//key_size\4 //convert the binary string to a hexadecimal string; static const unsigned int type_ids_length=10; //maximum number of predefined sq-types static const unsigned int CCR=6; static const unsigned int L1S=7; static const unsigned int L1L=8; static const unsigned int L2S=9; static const unsigned int PC=30; //Processor Type CPU=0, GPU=1, FPGA=2, N/A=4 static const unsigned int NC=34; //number of cores static const unsigned int INT=25; //Interconnection Network Bus=0, Ring=1, NOC=2, Crossbar=3, PointToPoint=4, HierarchicalNOC=5, Hypercube=6, Mesh=7, QsNet(Quadrics)=8 , // Infiniband=9, Myrinet=10, SCI(Scalable Coherent Interface)=11, GE( Gigabit Ethernet)=12, NUMAlink=13, SP Switch=13, Proprietary=14, Cray Interconnect=15, Mixed=16, N/A=17 static const unsigned int ISA=23;// X86=0, SPARC=1, ARM=2, XCORE=3, RISC=4, CISC=5, Legacy=6 , N/A=7 , Instruction Set Architecture static const unsigned int DC=38; //Die Count static const unsigned int MS=36 ; // Memory Size static const unsigned int NB=39 ; // Network Bandwidth MBits/s static const unsigned int TNC=37 ; // total number of cores in the node //static const unsigned int RH_DRQ=1; //rate_of_homogeneity_for_the_desired_resources_in_each_query; 1-5 //static const unsigned int Min_Number_of_Members_in_SGroup=2; // ----------VP--------------------- map<string, char> hexcharmap; void initMap() { hexcharmap.insert(std::pair<string, char>("1111", 'F')); hexcharmap.insert(std::pair<string, char>("1110", 'E')); hexcharmap.insert(std::pair<string, char>("1101", 'D')); hexcharmap.insert(std::pair<string, char>("1100", 'C')); hexcharmap.insert(std::pair<string, char>("1011", 'B')); hexcharmap.insert(std::pair<string, char>("1010", 'A')); hexcharmap.insert(std::pair<string, char>("1001", '9')); hexcharmap.insert(std::pair<string, char>("1000", '8')); hexcharmap.insert(std::pair<string, char>("0111", '7')); hexcharmap.insert(std::pair<string, char>("0110", '6')); hexcharmap.insert(std::pair<string, char>("0101", '5')); hexcharmap.insert(std::pair<string, char>("0100", '4')); hexcharmap.insert(std::pair<string, char>("0011", '3')); hexcharmap.insert(std::pair<string, char>("0010", '2')); hexcharmap.insert(std::pair<string, char>("0001", '1')); hexcharmap.insert(std::pair<string, char>("0000", '0')); hexcharmap.insert(std::pair<string, char>("111", '7')); hexcharmap.insert(std::pair<string, char>("110", '6')); hexcharmap.insert(std::pair<string, char>("101", '5')); hexcharmap.insert(std::pair<string, char>("100", '4')); hexcharmap.insert(std::pair<string, char>("011", '3')); hexcharmap.insert(std::pair<string, char>("010", '2')); hexcharmap.insert(std::pair<string, char>("001", '1')); hexcharmap.insert(std::pair<string, char>("000", '0')); hexcharmap.insert(std::pair<string, char>("11", '3')); hexcharmap.insert(std::pair<string, char>("10", '2')); hexcharmap.insert(std::pair<string, char>("01", '1')); hexcharmap.insert(std::pair<string, char>("00", '0')); hexcharmap.insert(std::pair<string, char>("1", '1')); hexcharmap.insert(std::pair<string, char>("0", '0')); } char getHexCharacter(std::string str) { return hexcharmap.find(str)->second; } std::string getHexRowFails(string input) { string rowresult; rowresult.assign(""); std::string endresult = ""; int m=input.size() % 4; int e=4-m; if (m != 0) { rowresult.append(e , '0'); rowresult.append(input); }else rowresult.append(input); for(unsigned int i = 4; i<= rowresult.size() ; i = i+4) { string s=rowresult.substr(rowresult.size()-i,4); endresult = getHexCharacter(s)+endresult; } return endresult; } std::pair<int,string> find_successor(vector<pair<int,string> > w , string s) { pair<int,string> result; for(unsigned int i=0; i < w.size(); i++) { result=w[i]; if ( s <= result.second) return result; } return w[0]; } string hex_str_2pown(int n, int fixed_size){ initMap(); string resultp,resultf, resultm; resultp.assign("1"); resultp.append(n,'0'); resultm= getHexRowFails(resultp); int st= fixed_size - resultm.size(); if (st>0){ resultf.append(st,'0'); resultf.append(resultm); } else resultf.append(resultm); return resultf; } int hex_char_to_dec( char c ){ switch (c) { case '0' : {return 0; break;} case '1' : {return 1; break;} case '2' : {return 2; break;} case '3' : {return 3; break;} case '4' : {return 4; break;} case '5' : {return 5; break;} case '6' : {return 6; break;} case '7' : {return 7; break;} case '8' : {return 8; break;} case '9' : {return 9; break;} case 'A' : {return 10; break;} case 'B' : {return 11; break;} case 'C' : {return 12; break;} case 'D' : {return 13; break;} case 'E' : {return 14; break;} case 'F' : {return 15; break;} } return -1; } char dec_to_hex_char( int d ){ switch (d) { case 0 : {return '0'; break;} case 1 : {return '1'; break;} case 2 : {return '2'; break;} case 3 : {return '3'; break;} case 4 : {return '4'; break;} case 5 : {return '5'; break;} case 6 : {return '6'; break;} case 7 : {return '7'; break;} case 8 : {return '8'; break;} case 9 : {return '9'; break;} case 10 : {return 'A'; break;} case 11 : {return 'B'; break;} case 12 : {return 'C'; break;} case 13 : {return 'D'; break;} case 14 : {return 'E'; break;} case 15 : {return 'F'; break;} } return 'X'; } string hex_str_add2str( string str1, string str2, int fixed_size) { string res1,res2; res1.assign(""); res2.assign(""); int st= fixed_size - str1.size(); if (st>0){ res1.append(st,'0'); res1.append(str1); } else res1.append(str1); st= fixed_size - str2.size(); if (st>0){ res2.append(st,'0'); res2.append(str2); } else res2.append(str2); int value, overhead=0; string result; div_t divresult; for (int i= fixed_size -1 ; i>=0 ; i--) { value=overhead+ hex_char_to_dec(res1[i]) + hex_char_to_dec(res2[i]); divresult = div (value,16); overhead= divresult.quot; value=divresult.rem; result=dec_to_hex_char(value) + result; } int dif=result.size() - fixed_size; if (dif > 0) return result.substr(dif,fixed_size); else return result; } //-----------VP-------------------------- //--------------------SR------------ struct nodeID { std::string networkIP; unsigned int cpuID; unsigned int coreID; }; typedef std::string MCAST_ADDR; typedef std::pair<nodeID,int> found_t; class subQueryTemp { public: subQueryTemp() { query_id=0; NumberOfRequestedResources=0; NumberOfDiscoveredResources=0; QID=0; TST=0; UWT=0; UPT=0; ls.assign(""); as.assign(""); ss.assign(""); }; unsigned int message_type; unsigned int query_id; std::string ls; std::string as; std::string ss; unsigned int NumberOfRequestedResources; unsigned int NumberOfDiscoveredResources; unsigned int QID; unsigned int TST; unsigned int UWT; unsigned int UPT; nodeID DiscoveredResourceID; std::vector<found_t> resources; int signal_int; }; struct probability_table { probability_table(): count() {} unsigned count; }; struct neigbour_table { neigbour_table(): count() {} unsigned count; }; /* class QueryRegistery { public: QueryRegistery(); ~QueryRegistery(); void QRegister(subQueryTemp){}; bool isTheQueryRegistered(int) {} bool isTheDiscoveryCompleted(int) {} void removeEntry(int) {}; std::vector<found_t> get_discovered_resourcesIDs(int){}; void add_to_discovered_resources(int ,nodeID, int){}; }; */ class QueryRouter { private: std::vector<qr_type> q_router; public: QueryRouter(){}; ~QueryRouter(){}; void add_entry(long main_query_id, unsigned int sub_query_id, int parent_sender, int destination){ qr_type temp; temp.main_query_id=main_query_id; temp.sub_query_id=sub_query_id; temp.parent_sender=parent_sender; temp.destination=destination; if (!the_route_is_existed_for(main_query_id, sub_query_id)) q_router.push_back(temp); return; } bool the_route_is_existed_for(long main_query_id, unsigned int sub_query_id){ bool result=false; for(unsigned int i=0;i<q_router.size();i++){ if ((q_router[i].main_query_id==main_query_id)&& (q_router[i].sub_query_id==sub_query_id)) { result=true; return result;} } return result; } void print_qrout(){ EV << "j-debug code 61 "<< endl; for(unsigned int i=0;i<q_router.size();i++){ EV << q_router[i].main_query_id << "," << q_router[i].sub_query_id << "," << q_router[i].parent_sender <<endl; } EV << "j-debug code 81"<< endl; } int get_parent_sender_id (long main_query_id, unsigned int sub_query_id){ int result=-1; EV << "j-debug code 6 "<< "qid="<< main_query_id<< ":"<< sub_query_id<< endl; for(unsigned int i=0;i<q_router.size();i++){ EV << q_router[i].main_query_id << "," << q_router[i].sub_query_id << "," << q_router[i].parent_sender <<endl; } EV << "j-debug code 8"<< endl; for(unsigned int i=0;i<q_router.size();i++){ if ((q_router[i].main_query_id==main_query_id)&& (q_router[i].sub_query_id==sub_query_id)) { result=q_router[i].parent_sender; EV << "j-debug code 7 result="<< result<< endl; return result; } } EV <<"j-debug code 55"<< endl; return result; } int get_destination_id (long main_query_id, unsigned int sub_query_id){ int result=-1; for(unsigned int i=0;i<q_router.size();i++){ if ((q_router[i].main_query_id==main_query_id)&& (q_router[i].sub_query_id==sub_query_id)) { result=q_router[i].destination; return result;} } return result; } void remove_mq_entry(long main_query_id){ for(unsigned int i=0;i<q_router.size();i++){ if (q_router[i].main_query_id==main_query_id) { q_router.erase(q_router.begin()+i); return;} } return; } void remove_entry(long main_query_id, unsigned int sub_query_id){ for(unsigned int i=0;i<q_router.size();i++){ if ((q_router[i].main_query_id==main_query_id)&& (q_router[i].sub_query_id==sub_query_id)) { q_router.erase(q_router.begin()+i); return;} } return; } }; std::vector<subQueryTemp> QueryBroker(subQueryTemp) { std::vector<subQueryTemp> result; //.... return result; }; bool checkQueryValidation(int) { bool result; result=true; //.... return result; }; void IgnoreTheEvent() { } void stop_discovery() { } double ctimer() { double ftimer=5.33; return ftimer; } int listening(int *message_type, nodeID *sender_coreID){ int flg=1; return flg; }; subQueryTemp receive(nodeID sender, int message_type){ subQueryTemp messageStr; return messageStr; } void send(subQueryTemp msg, nodeID receiver, int message_type){ //.. } void forward( subQueryTemp msg, nodeID original_sender_id, nodeID destination_id, int message_type) { //.. }; void broadcast( subQueryTemp msg, MCAST_ADDR multicast_address, int message_type) { //.. return ; }; MCAST_ADDR create_multicast_group(std::vector<nodeID> group_of_nodes) { MCAST_ADDR result; //create a multicast address return result; }; void sync(){ } // ------------SR---------- HE_Resource_Collection translateQuery(string input) {HE_Resource_Collection hecol; return hecol;} //----------------------DHT---------- class finger_table { private: struct finger_record { std::string start_id; // int successor_rank_id; // }; finger_record ft[key_size] ; public: finger_table(){ }; void put (int i, std::string sta_id , int suc_rank_id ){//char sta_id[id_char_size],char suc_id[id_char_size] ){ ft[i].start_id.assign(sta_id); ft[i].successor_rank_id=suc_rank_id; }; int get_successor_id(int i){ return ft[i].successor_rank_id; }; string get_start_id(int i){ return ft[i].start_id; }; int get_entry_index1(char local_id[id_char_size],char sta_id[id_char_size]){ // sta_id (hex) = local_id (hex) + 2 pow ( index ) int index=0; char temp1[id_char_size], temp2[id_char_size]; strcpy(temp1, sta_id); strcpy(temp2, local_id); return index; }; int get_entry_index2(string msg){ string key=msg; int index; for(int i=0; i< key_size ; i++ ) { if (ft[i].start_id==key) { index= i; return index; }; }; for(int i=0; i< key_size ; i++ ) { index=i-1; if (key < ft[i].start_id ) { return index; }; }; return key_size -1 ; }; }; //-----------------DHT------------- typedef struct { unsigned int first; unsigned int second; unsigned int third; unsigned int fourth; } Specific_QL1P; typedef struct { unsigned int first; unsigned int second; } Specific_QL3P; Specific_QL3P get_specific_anycast_query_parameters(unsigned int specific_type){ Specific_QL3P result; // Type A=1300,128,15,1024---Type B=1500,64,20,512 // Type C=2800,16,1,2048------Type D=2000,32,5,256 -------Type E=2600,16,10,128 switch (specific_type) { case 1: { // Type A=1300,128,15,1024 result.first=8; result.second=100; return result; break; } case 2: { //Type B=1500,64,20,512 result.first=16; result.second=1000; return result; break; } case 3: { //Type C=2800,16,1,2048 result.first=32; result.second=10000; return result; break; } } result.first=64; result.second=100; return result; } Specific_QL1P get_specific_query_parameters(unsigned int specific_type){ Specific_QL1P result; // Type A=1300,128,15,1024---Type B=1500,64,20,512 // Type C=2800,16,1,2048------Type D=2000,32,5,256 -------Type E=2600,16,10,128 switch (specific_type) { case 1: { // Type A=1300,128,15,1024 result.first=1300; result.second=128; result.third=15; result.fourth=1024; return result; break; } case 2: { //Type B=1500,64,20,512 result.first=1500; result.second=64; result.third=20; result.fourth=512; return result; break; } case 3: { //Type C=2800,16,1,2048 result.first=2800; result.second=16; result.third=1; result.fourth=2048; return result; break; } case 4: { //Type D=2000,32,5,256 result.first=2000; result.second=32; result.third=5; result.fourth=256; return result; break; } case 5: { //Type E=2600,16,10,128 result.first=2600; result.second=16; result.third=10; result.fourth=128; return result; break; } } result.first=1300; result.second=128; result.third=15; result.fourth=1024; return result; } unsigned int set_random_value(unsigned int attribute_id, unsigned int rndcore, unsigned int RH_DRQ){ srand(rndcore); // if (((rndcore==33)||(rndcore==63)||(rndcore==93)||(rndcore==22)||(rndcore==52)||(rndcore==82)||(rndcore==11)||(rndcore==41)||(rndcore==71)||(rndcore==0))&&(attribute_id<10)){ //type A Type A=1300,128,15,1024 if ((rndcore>=0)&& (rndcore<30) &&(attribute_id<10)){ switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return 1300 ; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return 128; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return 15; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return 1024; break;} //L2S by KB } } //type B Type B=1500,64,20,512 if ((rndcore>=30)&& (rndcore<60) &&(attribute_id<10) &&(RH_DRQ>=2) ){ switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return 1500 ; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return 64; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return 20; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return 512; break;} //L2S by KB } } //type C Type C=2800,16,1,2048 if ((rndcore>=60)&& (rndcore<90) &&(attribute_id<10)&&(RH_DRQ>=3)){ switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return 2800 ; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return 16; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return 1; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return 2048; break;} //L2S by KB } } //type D Type D=2000,32,5,256 if ((rndcore>=90)&& (rndcore<120) &&(attribute_id<10)&&(RH_DRQ>=4)){ switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return 2000 ; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return 32; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return 5; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return 256; break;} //L2S by KB } } //type E Type E=2600,16,10,128 if ((rndcore>=120)&& (rndcore<150) &&(attribute_id<10)&&(RH_DRQ>=5)){ switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return 2600 ; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return 16; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return 10; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return 128; break;} //L2S by KB } } //type E Type E=2600,16,10,128 for(unsigned int k=0;k<=20 ; k+=4){ if ((rndcore>=k*50)&& (rndcore<((k+1)*50)) &&(attribute_id>35)){ switch (attribute_id) { case 36: { return 8 ; break;} //MS {8,16,32,64,128} case 39: { return 100; break;} //NB {10, 100, 1000, 10000, 20000} } } } for(unsigned int k=1;k<=20 ; k+=4){ if ((rndcore>=k*50)&& (rndcore<((k+1)*50)) &&(attribute_id>35)){ switch (attribute_id) { case 36: { return 16 ; break;} //MS {8,16,32,64,128} case 39: { return 1000; break;} //NB {10, 100, 1000, 10000, 20000} } } } for(unsigned int k=2;k<=20 ; k+=4){ if ((rndcore>=k*50)&& (rndcore<((k+1)*50)) &&(attribute_id>35)){ switch (attribute_id) { case 36: { return 32 ; break;} //MS {8,16,32,64,128} case 39: { return 10000; break;} //NB {10, 100, 1000, 10000, 20000} } } } switch (attribute_id) { // case 6: { return ((unsigned int[]) {1000, 1200, 1500, 1800, 2000, 2200, 2400, 2500, 2600, 2800, 3000})[rand() % 11]; break;} //CCR by MHz case 6: { return ((unsigned int[]) {1000, 1800, 2500})[rand() % 3]; break;} //CCR by MHz // case 7: { return ((unsigned int[]) {16, 32, 64, 128})[rand() % 4]; break;} //L1S by KB case 7: { return ((unsigned int[]) {32, 128})[rand() % 2]; break;} //L1S by KB // case 8: { return ((unsigned int[]) {1, 2, 5, 10, 20})[rand() % 5]; break;} //L1L by NS case 8: { return ((unsigned int[]) {1, 10, 20})[rand() % 3]; break;} //L1L by NS // case 9: { return ((unsigned int[]) {128, 256, 512, 1024, 2048})[rand() % 5]; break;} //L2S by KB case 9: { return ((unsigned int[]) {128, 512, 2048})[rand() % 3]; break;} //L2S by KB case 30: { return ((unsigned int[]) {1, 2, 3, 4})[rand() % 4]; break;} //Processor Type CPU=1, GPU=2, FPGA=3, N/A=4 // case 30: { return ((unsigned int[]) { 4})[rand() % 1]; break;} //Processor Type CPU=1, GPU=2, FPGA=3, N/A=4 case 34: { return ((unsigned int[]) {8, 16, 32, 64, 128})[rand() % 5]; break;} //number of cores case 25: { return ((unsigned int[]) {1, 2, 3, 4, 5, 6 , 7, 8 , 9, 10, 11, 12, 13, 14, 15, 16, 17,18,19})[rand() % 19]; break;} //Interconnection Network // case 25: { return ((unsigned int[]) {10})[rand() % 1]; break;} //Interconnection Network Bus=1, Ring=2, NOC=3, Crossbar=4, PointToPoint=5, HierarchicalNOC=6, Hypercube=7, Mesh=8, QsNet(Quadrics)=9 , // Infiniband=10, Myrinet=11, SCI(Scalable Coherent Interface)=12, GE( Gigabit Ethernet)=13, NUMAlink=14, SP Switch=15, Proprietary=16, Cray Interconnect=17, Mixed=18, N/A=19 case 23: { return ((unsigned int[]) {1, 2, 3, 4,5,6,7,8})[rand() % 8]; break;} // SPARC=1, ARM=2, XCORE=3, RISC=4, CISC=5, Legacy=6 , N/A=7 ,X86=8 , Instruction Set Architecture // case 23: { return ((unsigned int[]) {8})[rand() % 1]; break;} // SPARC=1, ARM=2, XCORE=3, RISC=4, CISC=5, Legacy=6 , N/A=7 ,X86=8 , Instruction Set Architecture case 38: { return ((unsigned int[]) {1,2, 4, 8,16,24})[rand() % 6]; break;} //Die Count case 36: { return ((unsigned int[]) {8,16,32,64,128})[rand() % 5]; break;}// Memory Size by GB case 39: { return ((unsigned int[]) {10, 100, 1000, 10000, 20000})[rand() % 5]; break;}// Network Bandwidth MBits/s case 37: { return ((unsigned int[]) {200, 1000, 2000, 10000,20000})[rand() % 5]; break;} // total number of cores in the node } return 1; } std::vector<unsigned int> get_sub_query_type_ids( std::string ls, std::string as){ std::vector<unsigned int> type_ids; //PC-- Processor Type CPU=1, GPU=2, FPGA=3, N/A=4 //INT --//Interconnection Network Bus=1, Ring=2, NOC=3, Crossbar=4, PointToPoint=5, HierarchicalNOC=6, Hypercube=7, Mesh=8, QsNet(Quadrics)=9 , // Infiniband=10, Myrinet=11, SCI(Scalable Coherent Interface)=12, GE( Gigabit Ethernet)=13, NUMAlink=14, SP Switch=15, Proprietary=16, Cray Interconnect=17, Mixed=18, N/A=19 // ISA -- SPARC=1, ARM=2, XCORE=3, RISC=4, CISC=5, Legacy=6 , X86=7 ,N/A=8 , Instruction Set Architecture // type_id=0 CCR < 1500 // type_id=1 1500 <=CCR < 2500 // type_id=2 2500 <= CCR // type_id=3 L1S < 64 // type_id=4 64 <= L1S // type_id=5 L1L <10 // type_id=6 10<= L1L // type_id=7 L2S < 512 // type_id=8 512 <= L2S < 2048 // type_id=9 2048 <= L2S //type_id=10 PC< 3 //type_id=11 3 <= PC //type_id=12 INT <7 //type_id=13 7 <= INT < 13 //type_id=14 13 <= INT //type_id=15 ISA < 5 //type_id=16 5<= ISA string CCR, L1S,L1L,L2S; CCR=ls.substr(0,4); L1S=ls.substr(4,4); L1L=ls.substr(8,4); L2S=ls.substr(12,4); unsigned int CCRi, L1Si,L1Li,L2Si; std::istringstream iss1, iss2, iss3, iss4; iss1.str(CCR); iss1 >> std::hex >> CCRi; iss2.str(L1S); iss2 >> std::hex >> L1Si; iss3.str(L1L); iss3 >> std::hex >> L1Li; iss4.str(L2S); iss4 >> std::hex >> L2Si; if (CCRi>0){ if (CCRi<1500) type_ids.push_back(0);// type_id=0 CCR < 1500 else if ((CCRi>=1500)&&(CCRi<2500)) type_ids.push_back(1); // type_id=1 1500 <=CCR < 2500 else type_ids.push_back(2); // type_id=2 2500 <= CCR } if (L1Si>0){ if (L1Si<64) type_ids.push_back(3);// type_id=3 L1S < 64 else type_ids.push_back(4); // type_id=4 64 <= L1S } if (L1Li>0){ if (L1Li<10) type_ids.push_back(5);// type_id=5 L1L <10 else type_ids.push_back(6);// type_id=6 10<= L1L } if (L2Si>0){ if (L2Si<512) type_ids.push_back(7);// type_id=7 L2S < 512 else if ((L2Si>=512)&&(L2Si<2048)) type_ids.push_back(8); // type_id=8 512 <= L2S < 2048 else type_ids.push_back(9); // type_id=9 2048 <= L2S } std::string tempstr; tempstr.assign("n"); if (as!=tempstr){ string PC, INT,ISA; PC=as.substr(0,4); INT=as.substr(4,4); ISA=as.substr(8,4); unsigned int PCi, INTi,ISAi; std::istringstream iss5, iss6, iss7; iss5.str(PC); iss5 >> std::hex >> PCi; iss6.str(INT); iss6 >> std::hex >> INTi; iss7.str(ISA); iss7 >> std::hex >> ISAi; if (PCi>0){ if (PCi<3) type_ids.push_back(10); //type_id=10 PC< 3 else type_ids.push_back(11); //type_id=11 3 <= PC } if (INTi>0){ if (INTi<7) type_ids.push_back(12); //type_id=12 INT <7 else if ((INTi>=7)&&(INTi<13)) type_ids.push_back(13); //type_id=13 7 <= INT < 13 else type_ids.push_back(14); //type_id=14 13 <= INT } if (ISAi>0){ if (ISAi<5) type_ids.push_back(15); //type_id=15 ISA < 5 else type_ids.push_back(16); //type_id=16 5<= ISA } EV<< "Values for "<< as << "(" << PC<<INT<<ISA<<")"<< " = "<< PCi<< ", "<< INTi<< ", " << ISAi << endl; } EV<< "Values for "<< ls << "(" << CCR<<L1S<<L1L<<L2S<< ")"<< " = "<< CCRi<< ", "<< L1Si<< ", " << L1Li << ", " << L2Si << endl; return type_ids; } std::string set_ln_key(int rdcore, unsigned int RH_DRQ){ unsigned int CCR_value, L1S_value, L1L_value, L2S_value; CCR_value=set_random_value(CCR,rdcore, RH_DRQ ); L1S_value=set_random_value(L1S, rdcore, RH_DRQ); L1L_value=set_random_value(L1L, rdcore, RH_DRQ); L2S_value=set_random_value(L2S, rdcore, RH_DRQ); EV << "CCR="<<CCR_value << " L1S="<<L1S_value << " L2S="<<L2S_value << " L1L="<<L1L_value << endl; size_t st; string strResult,temp; strResult.clear(); ostringstream str; char buf[3]; std::bitset<16> CCRb,L1Sb,L1Lb,L2Sb; CCRb=CCR_value; L1Sb=L1S_value; L1Lb=L1L_value; L2Sb=L2S_value; sprintf(buf,"%lX",CCRb.to_ulong()); //str << hex ; //str << CCRb.to_ulong(); //temp=str.str(); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; //cout << s1 << "=" << CCR << endl; //cout << s2 << "=" << L1S << endl; //cout << s3 << "=" << L1L << endl; //cout << s4 << "=" << L2S << endl; sprintf(buf,"%lX",L1Sb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",L1Lb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); // cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",L2Sb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; return strResult; } std::string set_an_key(int rdcore, unsigned int nc, unsigned int RH_DRQ){ unsigned int PC_value, INT_value, ISA_value, NC_value; PC_value=set_random_value(PC,rdcore, RH_DRQ ); INT_value=set_random_value(INT, rdcore, RH_DRQ); ISA_value=set_random_value(ISA, rdcore, RH_DRQ); NC_value=nc; EV << "PC="<<PC_value << " INT="<<INT_value << " ISA="<<ISA_value << " NC="<<NC_value << endl; size_t st; string strResult,temp; strResult.clear(); ostringstream str; char buf[3]; std::bitset<16> PCb,INTb,ISAb,NCb; PCb=PC_value; INTb=INT_value; ISAb=ISA_value; NCb=NC_value; sprintf(buf,"%lX",PCb.to_ulong()); //str << hex ; //str << CCRb.to_ulong(); //temp=str.str(); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; //cout << s1 << "=" << CCR << endl; //cout << s2 << "=" << L1S << endl; //cout << s3 << "=" << L1L << endl; //cout << s4 << "=" << L2S << endl; sprintf(buf,"%lX",INTb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",ISAb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); // cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",NCb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; return strResult; } std::string set_sn_key(int rdcore, unsigned int dc, unsigned int tnc, unsigned int RH_DRQ){ unsigned int MS_value, NB_value, DC_value, TNC_value; MS_value=set_random_value(MS,rdcore , RH_DRQ); NB_value=set_random_value(NB, rdcore, RH_DRQ); DC_value=dc; TNC_value=tnc; EV << "MS="<<MS_value << " NB="<<NB_value << " DC="<<DC_value << " TNC="<<TNC_value << endl; size_t st; string strResult,temp; strResult.clear(); ostringstream str; char buf[3]; std::bitset<16> MSb,NBb,DCb,TNCb; MSb=MS_value; NBb=NB_value; DCb=DC_value; TNCb=TNC_value; sprintf(buf,"%lX",MSb.to_ulong()); //str << hex ; //str << CCRb.to_ulong(); //temp=str.str(); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; //cout << s1 << "=" << CCR << endl; //cout << s2 << "=" << L1S << endl; //cout << s3 << "=" << L1L << endl; //cout << s4 << "=" << L2S << endl; sprintf(buf,"%lX",NBb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",DCb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); // cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",TNCb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; return strResult; } string convert_args_qstring(unsigned int CCR, unsigned int L1S, unsigned int L1L, unsigned int L2S ) { size_t st; string strResult,temp; strResult.clear(); ostringstream str; char buf[4]; std::bitset<16> CCRb,L1Sb,L1Lb,L2Sb; CCRb=CCR; L1Sb=L1S; L1Lb=L1L; L2Sb=L2S; sprintf(buf,"%lX",CCRb.to_ulong()); //str << hex ; //str << CCRb.to_ulong(); //temp=str.str(); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; //cout << s1 << "=" << CCR << endl; //cout << s2 << "=" << L1S << endl; //cout << s3 << "=" << L1L << endl; //cout << s4 << "=" << L2S << endl; sprintf(buf,"%lX",L1Sb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",L1Lb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); // cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; sprintf(buf,"%lX",L2Sb.to_ulong()); temp.assign(buf); st= 4- temp.size(); strResult.append(st,'0'); strResult.append(temp); //cout << "-" << temp << "-" << strResult << "-" << strResult.size() << endl; return strResult; } HOGroup create_ho_group(long int thread_group_id, unsigned int nRR, unsigned int ccr, unsigned int l1s, unsigned int l1l, unsigned int l2s, unsigned int pc, unsigned int intp, unsigned int isa, unsigned int nc, unsigned int ms, unsigned int nb, unsigned int dc, unsigned int tnc, unsigned int mil, unsigned int mal, unsigned int mib, unsigned int mab ){ HOGroup hog_temp; string qlstr = convert_args_qstring(ccr, l1s, l1l, l2s); string qastr = convert_args_qstring(pc, intp, isa, nc); if ((pc==0) && (intp==0) && (isa==0) && (nc==0)) qastr="n"; string qsstr = convert_args_qstring(ms, nb, dc, tnc); if ((ms==0) && (nb==0) && (dc==0) && (tnc==0)) qsstr="n"; string inconst = convert_args_qstring(mil, mal, mib, mab); hog_temp.homog_id=thread_group_id; hog_temp.nRR=nRR; hog_temp.qls=qlstr; hog_temp.qas=qastr; hog_temp.qss=qsstr; hog_temp.inconst=inconst; return hog_temp; } #endif /* RDP_H */
[ "jz461@cl.cam.ac.uk" ]
jz461@cl.cam.ac.uk
c0561e6feecf51efe32f603cb9cf68c06bc0bc82
ae629d6766db069646148c3e0d1050ca1ccfcbe1
/source/input.cpp
1711baeb0c287533a52f89b37fc5ea13eebf17c6
[ "BSD-3-Clause" ]
permissive
Samake/reshade
c3ac4f89111afa557879348ebe344a766950c848
9c28e95854e7f0ed47bfe2d915041de7d6324fc4
refs/heads/master
2021-05-12T06:51:38.037522
2018-01-06T18:36:32
2018-01-06T18:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,092
cpp
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #include "log.hpp" #include "input.hpp" #include "hook_manager.hpp" #include <Windows.h> #include <assert.h> #include <mutex> #include <unordered_map> namespace reshade { static std::mutex s_mutex; static std::unordered_map<HWND, unsigned int> s_raw_input_windows; static std::unordered_map<HWND, std::weak_ptr<input>> s_windows; input::input(window_handle window) : _window(window) { assert(window != nullptr); } void input::register_window_with_raw_input(window_handle window, bool no_legacy_keyboard, bool no_legacy_mouse) { const std::lock_guard<std::mutex> lock(s_mutex); const auto flags = (no_legacy_keyboard ? 0x1 : 0u) | (no_legacy_mouse ? 0x2 : 0u); const auto insert = s_raw_input_windows.emplace(static_cast<HWND>(window), flags); if (!insert.second) { insert.first->second |= flags; } } std::shared_ptr<input> input::register_window(window_handle window) { const HWND parent = GetParent(static_cast<HWND>(window)); if (parent != nullptr) { window = parent; } const std::lock_guard<std::mutex> lock(s_mutex); const auto insert = s_windows.emplace(static_cast<HWND>(window), std::weak_ptr<input>()); if (insert.second || insert.first->second.expired()) { LOG(INFO) << "Starting input capture for window " << window << " ..."; const auto instance = std::make_shared<input>(window); insert.first->second = instance; return instance; } else { return insert.first->second.lock(); } } void input::uninstall() { s_windows.clear(); s_raw_input_windows.clear(); } bool input::handle_window_message(const void *message_data) { assert(message_data != nullptr); MSG details = *static_cast<const MSG *>(message_data); bool is_mouse_message = details.message >= WM_MOUSEFIRST && details.message <= WM_MOUSELAST; bool is_keyboard_message = details.message >= WM_KEYFIRST && details.message <= WM_KEYLAST; // Ignore messages that are not related to mouse or keyboard input if (details.message != WM_INPUT && !is_mouse_message && !is_keyboard_message) { return false; } // Some games process input on a child window of the swapchain window so make sure input is handled on the parent window const HWND parent = GetParent(details.hwnd); if (parent != nullptr) { details.hwnd = parent; } const std::lock_guard<std::mutex> lock(s_mutex); // Remove any expired entry from the list for (auto it = s_windows.begin(); it != s_windows.end();) it->second.expired() ? it = s_windows.erase(it) : ++it; // Look up the window in the list of known input windows auto input_window = s_windows.find(details.hwnd); const auto raw_input_window = s_raw_input_windows.find(details.hwnd); if (input_window == s_windows.end() && raw_input_window != s_raw_input_windows.end()) { // Reroute this raw input message to the window with the most rendering input_window = std::max_element(s_windows.begin(), s_windows.end(), [](auto lhs, auto rhs) { return lhs.second.lock()->_frame_count < rhs.second.lock()->_frame_count; }); } if (input_window == s_windows.end()) { return false; } RAWINPUT raw_data = {}; UINT raw_data_size = sizeof(raw_data); const auto input_lock = input_window->second.lock(); input &input = *input_lock; // Calculate window client mouse position ScreenToClient(static_cast<HWND>(input._window), &details.pt); input._mouse_position[0] = details.pt.x; input._mouse_position[1] = details.pt.y; switch (details.message) { case WM_INPUT: if (GET_RAWINPUT_CODE_WPARAM(details.wParam) != RIM_INPUT || GetRawInputData(reinterpret_cast<HRAWINPUT>(details.lParam), RID_INPUT, &raw_data, &raw_data_size, sizeof(raw_data.header)) == UINT(-1)) { break; } switch (raw_data.header.dwType) { case RIM_TYPEMOUSE: is_mouse_message = true; if (raw_input_window != s_raw_input_windows.end() && (raw_input_window->second & 0x2) == 0) break; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN) input._mouse_buttons[0] = 0x88; else if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP) input._mouse_buttons[0] = 0x08; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN) input._mouse_buttons[1] = 0x88; else if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP) input._mouse_buttons[1] = 0x08; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN) input._mouse_buttons[2] = 0x88; else if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_UP) input._mouse_buttons[2] = 0x08; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_BUTTON_4_DOWN) input._mouse_buttons[3] = 0x88; else if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_BUTTON_4_UP) input._mouse_buttons[3] = 0x08; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_BUTTON_5_DOWN) input._mouse_buttons[4] = 0x88; else if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_BUTTON_5_UP) input._mouse_buttons[4] = 0x08; if (raw_data.data.mouse.usButtonFlags & RI_MOUSE_WHEEL) input._mouse_wheel_delta += static_cast<short>(raw_data.data.mouse.usButtonData) / WHEEL_DELTA; break; case RIM_TYPEKEYBOARD: is_keyboard_message = true; if (raw_input_window != s_raw_input_windows.end() && (raw_input_window->second & 0x1) == 0) break; if (raw_data.data.keyboard.VKey != 0xFF) input._keys[raw_data.data.keyboard.VKey] = (raw_data.data.keyboard.Flags & RI_KEY_BREAK) == 0 ? 0x88 : 0x08; break; } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: input._keys[details.wParam] = 0x88; break; case WM_KEYUP: case WM_SYSKEYUP: input._keys[details.wParam] = 0x08; break; case WM_LBUTTONDOWN: input._mouse_buttons[0] = 0x88; break; case WM_LBUTTONUP: input._mouse_buttons[0] = 0x08; break; case WM_RBUTTONDOWN: input._mouse_buttons[1] = 0x88; break; case WM_RBUTTONUP: input._mouse_buttons[1] = 0x08; break; case WM_MBUTTONDOWN: input._mouse_buttons[2] = 0x88; break; case WM_MBUTTONUP: input._mouse_buttons[2] = 0x08; break; case WM_MOUSEWHEEL: input._mouse_wheel_delta += GET_WHEEL_DELTA_WPARAM(details.wParam) / WHEEL_DELTA; break; case WM_XBUTTONDOWN: assert(HIWORD(details.wParam) < 3); input._mouse_buttons[2 + HIWORD(details.wParam)] = 0x88; break; case WM_XBUTTONUP: assert(HIWORD(details.wParam) < 3); input._mouse_buttons[2 + HIWORD(details.wParam)] = 0x08; break; } return (is_mouse_message && input._block_mouse) || (is_keyboard_message && input._block_keyboard); } bool input::is_key_down(unsigned int keycode) const { assert(keycode < 256); return (_keys[keycode] & 0x80) == 0x80; } bool input::is_key_down(unsigned int keycode, bool ctrl, bool shift, bool alt) const { return is_key_down(keycode) && (!ctrl || is_key_down(VK_CONTROL)) && (!shift || is_key_down(VK_SHIFT)) && (!alt || is_key_down(VK_MENU)); } bool input::is_key_pressed(unsigned int keycode) const { assert(keycode < 256); return (_keys[keycode] & 0x88) == 0x88; } bool input::is_key_pressed(unsigned int keycode, bool ctrl, bool shift, bool alt) const { return is_key_pressed(keycode) && (!ctrl || is_key_down(VK_CONTROL)) && (!shift || is_key_down(VK_SHIFT)) && (!alt || is_key_down(VK_MENU)); } bool input::is_key_released(unsigned int keycode) const { assert(keycode < 256); return (_keys[keycode] & 0x88) == 0x08; } bool input::is_any_key_down() const { for (unsigned int i = 0; i < 256; i++) { if (is_key_down(i)) { return true; } } return false; } bool input::is_any_key_pressed() const { return last_key_pressed() != 0; } bool input::is_any_key_released() const { return last_key_released() != 0; } unsigned int input::last_key_pressed() const { for (unsigned int i = 0; i < 256; i++) { if (is_key_pressed(i)) { return i; } } return 0; } unsigned int input::last_key_released() const { for (unsigned int i = 0; i < 256; i++) { if (is_key_released(i)) { return i; } } return 0; } bool input::is_mouse_button_down(unsigned int button) const { assert(button < 5); return (_mouse_buttons[button] & 0x80) == 0x80; } bool input::is_mouse_button_pressed(unsigned int button) const { assert(button < 5); return (_mouse_buttons[button] & 0x88) == 0x88; } bool input::is_mouse_button_released(unsigned int button) const { assert(button < 5); return (_mouse_buttons[button] & 0x88) == 0x08; } bool input::is_any_mouse_button_down() const { for (unsigned int i = 0; i < 5; i++) { if (is_mouse_button_down(i)) { return true; } } return false; } bool input::is_any_mouse_button_pressed() const { for (unsigned int i = 0; i < 5; i++) { if (is_mouse_button_pressed(i)) { return true; } } return false; } bool input::is_any_mouse_button_released() const { for (unsigned int i = 0; i < 5; i++) { if (is_mouse_button_released(i)) { return true; } } return false; } unsigned short input::key_to_text(unsigned int keycode) const { WORD ch = 0; return ToAscii(keycode, MapVirtualKey(keycode, MAPVK_VK_TO_VSC), _keys, &ch, 0) ? ch : 0; } void input::block_mouse_input(bool enable) { _block_mouse = enable; if (enable) { ClipCursor(nullptr); } } void input::block_keyboard_input(bool enable) { _block_keyboard = enable; } static inline bool is_blocking_mouse_input() { const auto predicate = [](auto input_window) { return !input_window.second.expired() && input_window.second.lock()->is_blocking_mouse_input(); }; return std::any_of(reshade::s_windows.cbegin(), reshade::s_windows.cend(), predicate); } static inline bool is_blocking_keyboard_input() { const auto predicate = [](auto input_window) { return !input_window.second.expired() && input_window.second.lock()->is_blocking_keyboard_input(); }; return std::any_of(reshade::s_windows.cbegin(), reshade::s_windows.cend(), predicate); } void input::next_frame() { _frame_count++; for (auto &state : _keys) { state &= ~0x8; } for (auto &state : _mouse_buttons) { state &= ~0x8; } _mouse_wheel_delta = 0; // Update caps lock state _keys[VK_CAPITAL] |= GetKeyState(VK_CAPITAL) & 0x1; // Update modifier key state if ((_keys[VK_MENU] & 0x88) != 0 && (GetKeyState(VK_MENU) & 0x8000) == 0) { _keys[VK_MENU] = 0x08; } // Update print screen state if ((_keys[VK_SNAPSHOT] & 0x80) == 0 && (GetAsyncKeyState(VK_SNAPSHOT) & 0x8000) != 0) { _keys[VK_SNAPSHOT] = 0x88; } } } HOOK_EXPORT BOOL WINAPI HookGetMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax) { static const auto trampoline = reshade::hooks::call(&HookGetMessageA); if (!trampoline(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax)) { return FALSE; } assert(lpMsg != nullptr); if (lpMsg->hwnd != nullptr && reshade::input::handle_window_message(lpMsg)) { // Change message so it is ignored by the recipient window lpMsg->message = WM_NULL; } return TRUE; } HOOK_EXPORT BOOL WINAPI HookGetMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax) { static const auto trampoline = reshade::hooks::call(&HookGetMessageW); if (!trampoline(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax)) { return FALSE; } assert(lpMsg != nullptr); if (lpMsg->hwnd != nullptr && reshade::input::handle_window_message(lpMsg)) { // Change message so it is ignored by the recipient window lpMsg->message = WM_NULL; } return TRUE; } HOOK_EXPORT BOOL WINAPI HookPeekMessageA(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) { static const auto trampoline = reshade::hooks::call(&HookPeekMessageA); if (!trampoline(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg)) { return FALSE; } assert(lpMsg != nullptr); if (lpMsg->hwnd != nullptr && (wRemoveMsg & PM_REMOVE) != 0 && reshade::input::handle_window_message(lpMsg)) { // Change message so it is ignored by the recipient window lpMsg->message = WM_NULL; } return TRUE; } HOOK_EXPORT BOOL WINAPI HookPeekMessageW(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) { static const auto trampoline = reshade::hooks::call(&HookPeekMessageW); if (!trampoline(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg)) { return FALSE; } assert(lpMsg != nullptr); if (lpMsg->hwnd != nullptr && (wRemoveMsg & PM_REMOVE) != 0 && reshade::input::handle_window_message(lpMsg)) { // Change message so it is ignored by the recipient window lpMsg->message = WM_NULL; } return TRUE; } HOOK_EXPORT BOOL WINAPI HookRegisterRawInputDevices(PCRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize) { LOG(INFO) << "Redirecting '" << "RegisterRawInputDevices" << "(" << pRawInputDevices << ", " << uiNumDevices << ", " << cbSize << ")' ..."; for (UINT i = 0; i < uiNumDevices; ++i) { const auto &device = pRawInputDevices[i]; LOG(INFO) << "> Dumping device registration at index " << i << ":"; LOG(INFO) << " +-----------------------------------------+-----------------------------------------+"; LOG(INFO) << " | Parameter | Value |"; LOG(INFO) << " +-----------------------------------------+-----------------------------------------+"; LOG(INFO) << " | UsagePage | " << std::setw(39) << std::hex << device.usUsagePage << std::dec << " |"; LOG(INFO) << " | Usage | " << std::setw(39) << std::hex << device.usUsage << std::dec << " |"; LOG(INFO) << " | Flags | " << std::setw(39) << std::hex << device.dwFlags << std::dec << " |"; LOG(INFO) << " | TargetWindow | " << std::setw(39) << device.hwndTarget << " |"; LOG(INFO) << " +-----------------------------------------+-----------------------------------------+"; if (device.usUsagePage != 1 || device.hwndTarget == nullptr) { continue; } reshade::input::register_window_with_raw_input(device.hwndTarget, device.usUsage == 0x06 && (device.dwFlags & RIDEV_NOLEGACY) != 0, device.usUsage == 0x02 && (device.dwFlags & RIDEV_NOLEGACY) != 0); } if (!reshade::hooks::call(&HookRegisterRawInputDevices)(pRawInputDevices, uiNumDevices, cbSize)) { LOG(WARNING) << "> 'RegisterRawInputDevices' failed with error code " << GetLastError() << "!"; return FALSE; } return TRUE; } HOOK_EXPORT BOOL WINAPI HookPostMessageA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { if (reshade::is_blocking_mouse_input() && Msg == WM_MOUSEMOVE) { return TRUE; } static const auto trampoline = reshade::hooks::call(&HookPostMessageA); return trampoline(hWnd, Msg, wParam, lParam); } HOOK_EXPORT BOOL WINAPI HookPostMessageW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { if (reshade::is_blocking_mouse_input() && Msg == WM_MOUSEMOVE) { return TRUE; } static const auto trampoline = reshade::hooks::call(&HookPostMessageW); return trampoline(hWnd, Msg, wParam, lParam); } POINT last_cursor_position = { }; HOOK_EXPORT BOOL WINAPI HookSetCursorPosition(int X, int Y) { if (reshade::is_blocking_mouse_input()) { last_cursor_position.x = X; last_cursor_position.y = Y; return TRUE; } static const auto trampoline = reshade::hooks::call(&HookSetCursorPosition); return trampoline(X, Y); } HOOK_EXPORT BOOL WINAPI HookGetCursorPosition(LPPOINT lpPoint) { if (reshade::is_blocking_mouse_input()) { assert(lpPoint != nullptr); *lpPoint = last_cursor_position; return TRUE; } static const auto trampoline = reshade::hooks::call(&HookGetCursorPosition); return trampoline(lpPoint); }
[ "crosiredev@gmail.com" ]
crosiredev@gmail.com
3b9cfcde94fd1165c8f58e2d6ec2050892e68a93
68e963093a4e101e7e4b29f304911ba6f7a7f57e
/binario_to-decimale/esercizi_laboratorio_01/prova.cpp
2121ab794cf47ed8e9ecc0fbfe53b8b8959efb2d
[]
no_license
TheOfficialDragone/CPP
fd6776e0b1cef351f4e0ec8818a1b09091816a1a
8e433985f4cde3e06450716e348e228a4e2ff5a4
refs/heads/main
2023-07-18T13:02:11.410981
2021-09-01T21:46:57
2021-09-01T21:46:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
113
cpp
// // prova.cpp // esercizi_laboratorio_01 // // Created by Rocco Carpi on 13/05/21. // #include "prova.hpp"
[ "rocco.carpi122@gmail.com" ]
rocco.carpi122@gmail.com
5a7429198569ee16bb7d9aaad7a5e4491f9f91bf
ebc815aeba8a74801d7cb79daef836a908b2243c
/StGenFactoryScript/StCheckBase.cpp
21c9a14c41054024cae8470050c64192d84fba51
[]
no_license
anryu/StGenFactoryScript
9050c2a3883c04b5b60f919cf70f0cfbd4c9a43b
8016ec47f48c443ab727b5edaf20c3bdfc7c70c4
refs/heads/master
2020-04-05T02:47:28.821834
2018-11-13T10:01:21
2018-11-13T10:01:21
156,490,372
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
76,440
cpp
#include "StdAfx.h" #include "StCheckBase.h" #include <math.h> #include "StBufferInfo.h" #include "../CommonHeader/StTransformsImage.h" #include <afx.h> //▼1.0.0.1039 #include "../CommonHeader/StSaveFileImage.h" //▲1.0.0.1039 //▼1.0.0.1044 #include "StDeviceEBus.h" #include "StDeviceMultiCam.h" //▲1.0.0.1044 StCheckBase::StCheckBase(void) : m_iJudge(-1) , m_Buffer(NULL) , m_DeviceBase(NULL) , m_pDialog(NULL) { memset( m_nColorIndex, 0, sizeof(m_nColorIndex) ); //▼1.0.0.1062 m_nScriptCheckMode = 0; //▲1.0.0.1062 } StCheckBase::StCheckBase(LPCTSTR szClassName, LPCTSTR szVarName, StDeviceBase *aDeviceBase, void *aDialogEx) : m_iJudge(-1) , m_Buffer(NULL) , m_ClassName(szClassName) , m_VarName(szVarName) , m_DeviceBase(aDeviceBase) , m_pDialog(aDialogEx) { memset( m_nColorIndex, 0, sizeof(m_nColorIndex) ); //▼1.0.0.1062 m_nScriptCheckMode = 0; //▲1.0.0.1062 } StCheckBase::~StCheckBase(void) { if( m_Buffer ) { delete m_Buffer; m_Buffer = NULL; } } //▼1.0.0.1044 BOOL StCheckBase::WriteDataEBus(BYTE byteDeviceCode, BYTE bytePage, BYTE byteAddress, BYTE byteData) { StDeviceEBus *aDevice = (StDeviceEBus *)m_DeviceBase; if( !aDevice->IsConnected() ) return FALSE; BYTE byteSendData[6]; byteSendData[0] = 0x02; byteSendData[1] = (byteDeviceCode<<2) | 0x02 | (bytePage&1); byteSendData[2] = byteAddress; byteSendData[3] = 1; byteSendData[4] = byteData; byteSendData[5] = 0x03; BYTE byteRcvData[4] = {2,0,1,3}; //Write時の正常リード値 //▼1.0.0.1060 //BYTE GetRcvData[4+2]; BYTE GetRcvData[4]; //▲1.0.0.1060 size_t getRcvSize = sizeof(GetRcvData); BOOL bRevCtrl = aDevice->SerialControl( _T("UART0"), byteSendData, sizeof(byteSendData), GetRcvData, &getRcvSize ); if( bRevCtrl ) { if( getRcvSize!=sizeof(byteRcvData) ) { bRevCtrl = FALSE; } } if( bRevCtrl ) { if( memcmp(GetRcvData,byteRcvData,getRcvSize)!=0 ) bRevCtrl = FALSE; } return bRevCtrl; } BOOL StCheckBase::WriteDataMultiCamAscii(StString &szCommand, BYTE byteData) { StDeviceMultiCam *aDevice = (StDeviceMultiCam *)m_DeviceBase; if( !aDevice->IsOpened() ) return FALSE; StSerialComm *aSerialComm = aDevice->GetSerialComm(); if( !aSerialComm ) return FALSE; TCHAR szSendText[256]; TCHAR szRcvText[256]; CString szCommandText(szCommand.GetAscii()); _stprintf_s( szSendText, _countof(szSendText), _T("%s=%u"), szCommandText, byteData ); BOOL bReval = aSerialComm->SendText( szSendText, szRcvText, _countof(szRcvText) ); TCHAR *szRcvCmpText = {_T("OK")}; if( bReval ) { if( _tcscmp(szRcvText,szRcvCmpText)!=0 ) bReval = FALSE; } return bReval; } BOOL StCheckBase::WriteDataMultiCamAscii(StString &szCommand) { StDeviceMultiCam *aDevice = (StDeviceMultiCam *)m_DeviceBase; if( !aDevice->IsOpened() ) return FALSE; StSerialComm *aSerialComm = aDevice->GetSerialComm(); if( !aSerialComm ) return FALSE; TCHAR szSendText[256]; TCHAR szRcvText[256]; CString szCommandText(szCommand.GetAscii()); _stprintf_s( szSendText, _countof(szSendText), _T("%s"), szCommandText ); BOOL bReval = aSerialComm->SendText( szSendText, szRcvText, _countof(szRcvText) ); TCHAR *szRcvCmpText = {_T("OK")}; if( bReval ) { if( _tcscmp(szRcvText,szRcvCmpText)!=0 ) bReval = FALSE; } return bReval; } BOOL StCheckBase::WriteDataMultiCamBinary(BYTE byteDeviceCode, BYTE bytePage, BYTE byteAddress, BYTE byteData) { StDeviceMultiCam *aDevice = (StDeviceMultiCam *)m_DeviceBase; if( !aDevice->IsOpened() ) return FALSE; StSerialComm *aSerialComm = aDevice->GetSerialComm(); if( !aSerialComm ) return FALSE; BYTE byteSendData[6]; byteSendData[0] = 0x02; byteSendData[1] = (byteDeviceCode<<2) | 0x02 | (bytePage&1); byteSendData[2] = byteAddress; byteSendData[3] = 1; byteSendData[4] = byteData; byteSendData[5] = 0x03; BYTE byteRcvData[4] = {2,0,1,3}; //Write時の正常リード値 BYTE GetRcvData[4+2]; size_t getRcvSize = sizeof(GetRcvData); BOOL bRevCtrl = aSerialComm->SendBin(byteSendData,sizeof(byteSendData),GetRcvData,&getRcvSize); if( bRevCtrl ) { if( getRcvSize!=sizeof(byteRcvData) ) { bRevCtrl = FALSE; } } if( bRevCtrl ) { if( memcmp(GetRcvData,byteRcvData,getRcvSize)!=0 ) bRevCtrl = FALSE; } return bRevCtrl; } //▲1.0.0.1044 //----------------------------------------------------------------------------- //ビットマップ形式で保存 //----------------------------------------------------------------------------- BOOL bSaveBitmapFile( DWORD dwWidth,DWORD dwHeight,DWORD dwSize, INT iColor, PBYTE pbyteSrcData, LPCTSTR fileName ) { LPBITMAPFILEHEADER bmFileHeader; LPBITMAPINFOHEADER bmInfoHeader; PBYTE pbyteBuffer; DWORD dwHeaderSize; DWORD dwImageSize; DWORD dwBufferSize; BOOL bReval = FALSE; //4の倍数 //DWORD dwBufferWidthLine = (dwWidth+3)&(~3); if( iColor==0 ) { dwHeaderSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (sizeof(RGBQUAD) << 8); } else { dwHeaderSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); //dwBufferWidthLine = (dwWidth*3+3)&(~3); } //dwImageSize = dwBufferWidthLine * dwHeight; dwImageSize = dwSize; dwBufferSize = dwHeaderSize + dwImageSize; //バッファ作成 pbyteBuffer = (PBYTE)malloc(sizeof(BYTE) * (dwBufferSize)); if(pbyteBuffer == NULL) { return(FALSE); } //ヘッダー部を0で初期化 memset(pbyteBuffer, 0, dwHeaderSize); //画像データをコピー memcpy(pbyteBuffer + dwHeaderSize,pbyteSrcData,dwImageSize); //ファイルヘッダーをセット bmFileHeader = (LPBITMAPFILEHEADER)pbyteBuffer; bmFileHeader->bfType = (((WORD)'M') << 8) | (WORD)'B'; bmFileHeader->bfSize = dwBufferSize; bmFileHeader->bfOffBits = dwHeaderSize; //インフォヘッダーをセット bmInfoHeader = (LPBITMAPINFOHEADER)(pbyteBuffer + sizeof(BITMAPFILEHEADER)); bmInfoHeader->biSize = sizeof(BITMAPINFOHEADER); bmInfoHeader->biWidth = dwWidth; bmInfoHeader->biHeight = (-1)*(INT)dwHeight; bmInfoHeader->biPlanes = 1; bmInfoHeader->biSizeImage = dwBufferSize; if(iColor==0) { //インフォヘッダーをセット bmInfoHeader->biBitCount = 8; bmInfoHeader->biClrUsed = 256; bmInfoHeader->biClrImportant = 256; //▼2007/01/24(0.0.3.4) 8ビットビットマップ用カラーテーブル作成を高速化 //カラーテーブルをセット DWORD dwCurPixelValue = 256; //モノクロテーブル作成用 PDWORD pdwPosRGBTable = (PDWORD)((PBYTE)bmInfoHeader + sizeof(BITMAPINFOHEADER)); do{ dwCurPixelValue--; pdwPosRGBTable[dwCurPixelValue] = (dwCurPixelValue << 16) | (dwCurPixelValue << 8) | (dwCurPixelValue); }while(dwCurPixelValue); } else { //インフォヘッダーをセット bmInfoHeader->biBitCount = 24; } FILE *fp=NULL; //fp = _tfopen(fileName,_T("wb")); _tfopen_s(&fp,fileName,_T("wb")); if(fp) { fwrite(pbyteBuffer,sizeof(BYTE),dwBufferSize,fp); bReval = TRUE; fclose(fp); } if( pbyteBuffer ) delete [] pbyteBuffer; return(bReval); } BOOL StCheckBase::SaveBitmapFile(StBuffer *pBuffer, LPCTSTR szFileFullName) { UINT uiWidth = pBuffer->GetWidth(); UINT uiHeight = pBuffer->GetHeight(); INT iDestLinePitch = uiWidth; INT nElement = GetElementFromBuffer(pBuffer); //if( nElement==0 ) //{ // StPixelType aType; // pBuffer->GetPixelType(aType); // TRACE(TEXT("GetPixelType(0x%x)\n"), aType); //} if( nElement==3 ) { iDestLinePitch *= 3; } //4の倍数に切り上げ iDestLinePitch = (iDestLinePitch + 3) & (~0x3); INT iDestBufferSize = iDestLinePitch * uiHeight; char *pDispBuffer = new char [iDestBufferSize]; if( pDispBuffer==NULL ) return FALSE; //画像変換 StBuffer dstBuffer; dstBuffer.Attach( pDispBuffer, iDestBufferSize ); dstBuffer.SetWidth(uiWidth); dstBuffer.SetHeight(uiHeight); dstBuffer.SetLinePitch(iDestLinePitch); dstBuffer.SetPixelType(nElement==1?StPixelMono8:StPixelBGR8); StResult aTransformResult = StTransformsImage::Transform( pBuffer, &dstBuffer); dstBuffer.Detach(); BOOL bReval = FALSE; if( aTransformResult.IsOK() ) { bReval = bSaveBitmapFile( uiWidth, uiHeight, iDestBufferSize, nElement==3?1:0, (PBYTE)pDispBuffer, szFileFullName ); } delete [] pDispBuffer; return bReval; } //▼1.0.0.1039 //PNG or Jpeg 拡張子で判断 BOOL StCheckBase::SaveImageFile(StBuffer *aBuffer, LPCTSTR szFileFullName) { BOOL bReval = FALSE; StBuffer dstBuffer; INT nDestLinePitch = aBuffer->GetWidth() * 3; nDestLinePitch = (nDestLinePitch + 3) & (~0x3); dstBuffer.Alloc( nDestLinePitch * aBuffer->GetHeight() ); dstBuffer.SetWidth(aBuffer->GetWidth()); dstBuffer.SetHeight(aBuffer->GetHeight()); dstBuffer.SetLinePitch(nDestLinePitch); dstBuffer.SetPixelType(StPixelBGR8); // Converter bReval = StTransformsImage::Transform( aBuffer, &dstBuffer).IsOK(); if( bReval ) { StSaveFileImage aSaveFileImage; bReval = aSaveFileImage.executeFileSave(szFileFullName, (const unsigned char *)dstBuffer.GetDataPointer(), aBuffer->GetWidth(), aBuffer->GetHeight(), 1.0, 1.0); } dstBuffer.Free(); return bReval; } //▲1.0.0.1039 //=============================================================================== //dblOutAverage:全画面のレベル平均 //dblOutSDAve:縦方向1ラインの標準偏差の平均 //dblOutSDMax:縦方向1ラインの標準偏差の最大値 //dblOutSDMPix:縦方向1ラインの標準偏差の最大値の位置 //=============================================================================== template <class X> BOOL GetSNAverageValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, DWORD dwStartLine, DWORD dwEndLine , double *dblOutAverage, double *dblOutSDAve, double *dblOutSDMax, int *nOutSDMPix, double **ppdblOutAverage, double **ppdblOutSDAve, size_t buffersize ) { if( dwEndLine<dwStartLine ) return FALSE; if( dwHeight==0 ) return FALSE; if( dwStartLine>=dwWidth ) return FALSE; if( dwEndLine>=dwWidth ) return FALSE; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { double *pdblOutAverage = NULL; double *pdblOutSDAve = NULL; if( ppdblOutAverage ) pdblOutAverage = ppdblOutAverage[i]; if( ppdblOutSDAve ) pdblOutSDAve = ppdblOutSDAve[i]; double dblSDAve = 0.0; double dblSDMax = 0.0; int nSDMPix = 0; double sumData=0.0; X *pImgTop = ptRaw + i; pImgTop += dwStartLine * wElementsPerPixel; for( DWORD x=dwStartLine; x<=dwEndLine; x++ ) { double dblSigXn = 0.0; double dblSigXn2 = 0.0; X *pImg = pImgTop; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSigXn += *pImg; dblSigXn2 += (*pImg)*(*pImg); PBYTE pbImg = (PBYTE)pImg; pImg = (X *)(pbImg + nSrcLinePitch); } if( buffersize>x-dwStartLine ) { if( pdblOutAverage ) pdblOutAverage[x-dwStartLine] = dblSigXn / dwHeight; } double dSD = sqrt( (double)(dwHeight*dblSigXn2-dblSigXn*dblSigXn)/(dwHeight*(dwHeight-1)) ); //縦方向の標準偏差 if( buffersize>x-dwStartLine ) { if( pdblOutSDAve ) pdblOutSDAve[x-dwStartLine] = dSD; } if( dSD > dblSDMax ) //最大標準偏差 { dblSDMax = dSD; nSDMPix = x; } dblSDAve += dSD; //平均用 sumData += dblSigXn; pImgTop += wElementsPerPixel; } double dblAverage = sumData / ( dwHeight * (dwEndLine - dwStartLine + 1) ); dblSDAve /= (dwEndLine - dwStartLine + 1); //代入 dblOutAverage[i] = dblAverage; dblOutSDAve[i] = dblSDAve; dblOutSDMax[i] = dblSDMax; nOutSDMPix[i] = nSDMPix; } return TRUE; } BOOL StCheckBase::SaveCSVFile(StBuffer *aBuffer, LPCTSTR szFilePath, LPCTSTR szFileName, INT nScopeLeft, INT nScopeRight ) { UINT uiWidth = aBuffer->GetWidth(); UINT uiHeight = aBuffer->GetHeight(); //INT iDestLinePitch = uiWidth; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nScopeLeft<0 ) nScopeLeft = 0; if( nScopeRight<0 ) nScopeRight = uiWidth-1; BOOL bReval = TRUE; //数値解析 double *dblCalcAve = NULL; double *dblCalcSDAve = NULL; double *dblCalcSDMax = NULL; int *nCalcSDMaxPix = NULL; double **ppdblCalcAve = NULL; double **ppdblCalcSDMax = NULL; do { //バッファ作成//--------------------------- dblCalcAve = new double [nElement]; if( !dblCalcAve ) break; dblCalcSDAve = new double [nElement]; if( !dblCalcSDAve ) break; dblCalcSDMax = new double [nElement]; if( !dblCalcSDMax ) break; nCalcSDMaxPix = new int [nElement]; if( !nCalcSDMaxPix ) break; ppdblCalcAve = new double *[nElement]; if( !ppdblCalcAve ) break; memset( ppdblCalcAve, 0, sizeof(double *) * nElement); ppdblCalcSDMax = new double *[nElement]; if( !ppdblCalcSDMax ) break; memset( ppdblCalcSDMax, 0, sizeof(double *) * nElement); size_t bufferSize = nScopeRight - nScopeLeft + 1; for( int i=0; i<nElement; i++ ) { ppdblCalcAve[i] = new double [bufferSize]; if( !ppdblCalcAve[i] ) { bReval = FALSE; break; } ppdblCalcSDMax[i] = new double [bufferSize]; if( !ppdblCalcSDMax[i] ) { bReval = FALSE; break; } } if( !bReval ) break; //--------------------------- if( (nPixelSize/nElement)==8 ) { bReval = GetSNAverageValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), nScopeLeft, nScopeRight , dblCalcAve, dblCalcSDAve, dblCalcSDMax, nCalcSDMaxPix, ppdblCalcAve, ppdblCalcSDMax, bufferSize ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetSNAverageValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), nScopeLeft, nScopeRight , dblCalcAve, dblCalcSDAve, dblCalcSDMax, nCalcSDMaxPix, ppdblCalcAve, ppdblCalcSDMax, bufferSize ); } if( !bReval ) break; CString szFileFullName = szFilePath; szFileFullName += szFileName; CStdioFile aFile; if( !aFile.Open( szFileFullName, CFile::modeCreate|CFile::modeWrite|CFile::typeText, NULL ) ) { bReval = FALSE; break; } aFile.SeekToBegin(); CString szTmp; //Line No.1 szTmp = _T("FileName=["); szTmp += szFileName; szTmp += _T("]"); aFile.WriteString(szTmp + _T("\n")); //Line No.2 szTmp.Format(_T("ImageSize=(%u/%u) AverageRange=(%d/%d)"),uiWidth, uiHeight, nScopeLeft, nScopeRight ); aFile.WriteString(szTmp + _T("\n")); LPCTSTR szColor[] = {_T("Red"),_T("Green"),_T("Blue")}; for( int i=0; i<nElement; i++ ) { CString aColor(_T("")); if( nElement==3 ) { aColor = szColor[i]; aColor += _T(":"); } szTmp.Format(_T("%sAverage=[%.02f]/SDAve=[%.06f]/SDMax=[%.06f]at[%d]pix"), aColor, dblCalcAve[i], dblCalcSDAve[i], dblCalcSDMax[i], nCalcSDMaxPix[i] ); aFile.WriteString(szTmp + _T("\n")); } if( nElement==3 ) { szTmp.Format(_T("No.,%s:Average,%s:SD,%s:Average,%s:SD,%s:Average,%s:SD"), szColor[0], szColor[0], szColor[1], szColor[1], szColor[2], szColor[2] ); aFile.WriteString(szTmp + _T("\n")); for( int x=0; x< (int)bufferSize; x++ ) { szTmp.Format(_T("%d,%.02f,%.06f,%.02f,%.06f,%.02f,%.06f") , x + nScopeLeft, ppdblCalcAve[0][x], ppdblCalcSDMax[0][x], ppdblCalcAve[1][x], ppdblCalcSDMax[1][x], ppdblCalcAve[2][x], ppdblCalcSDMax[2][x] ); aFile.WriteString(szTmp + _T("\n")); } } else { szTmp.Format(_T("No.,Average,SD")); aFile.WriteString(szTmp + _T("\n")); for( int x=0; x< (int)bufferSize; x++ ) { szTmp.Format(_T("%d,%.02f,%.06f") , x + nScopeLeft, ppdblCalcAve[0][x], ppdblCalcSDMax[0][x] ); aFile.WriteString(szTmp + _T("\n")); } } aFile.Close(); bReval = TRUE; }while(0); if( dblCalcAve ) delete [] dblCalcAve; if( dblCalcSDAve ) delete [] dblCalcSDAve; if( dblCalcSDMax ) delete [] dblCalcSDMax; if( nCalcSDMaxPix ) delete [] nCalcSDMaxPix; if( ppdblCalcAve ) { for( int i=0; i<nElement; i++ ) { delete [] ppdblCalcAve[i]; } delete [] ppdblCalcAve; } if( ppdblCalcSDMax ) { for( int i=0; i<nElement; i++ ) { delete [] ppdblCalcSDMax[i]; } delete [] ppdblCalcSDMax; } return bReval; } //▼1.0.0.1055 //=============================================================================== //ppHistogramData:ヒストグラムデータ出力[wElementsPerPixel][nDataSize] //=============================================================================== template <class X> BOOL GetHistogramValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, DWORD dwStartLine, DWORD dwEndLine , INT nDataSize, PINT *ppHistogramData ) { if( dwEndLine<dwStartLine ) return FALSE; if( dwHeight==0 ) return FALSE; if( dwStartLine>=dwWidth ) return FALSE; if( dwEndLine>=dwWidth ) return FALSE; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { PINT pHistogramData = ppHistogramData[i]; memset( pHistogramData, 0, sizeof(INT)*nDataSize ); X *ptLineTop = ptRaw + i; for( int y=0; y<dwHeight; y++ ) { X *ptData = ptLineTop; for( int x=0; x<dwWidth; x++ ) { if( x>=dwStartLine && x<=dwEndLine ) { if( *ptData>=0 && *ptData<nDataSize ) { pHistogramData[*ptData]++; } } ptData += wElementsPerPixel; } PBYTE pbyteLineTop = (PBYTE)ptLineTop; ptLineTop = (X *)(pbyteLineTop + nSrcLinePitch); } } return TRUE; } BOOL StCheckBase::SaveHistogramFile(StBuffer *aBuffer, LPCTSTR szFilePath, LPCTSTR szFileName, INT nScopeLeft, INT nScopeRight ) { UINT uiWidth = aBuffer->GetWidth(); UINT uiHeight = aBuffer->GetHeight(); //INT iDestLinePitch = uiWidth; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); INT nPixelBits = GetPixelBits(aBuffer); INT nDataSize = (1<<nPixelBits); if( nScopeLeft<0 ) nScopeLeft = 0; if( nScopeRight<0 ) nScopeRight = uiWidth-1; BOOL bReval = FALSE; //数値解析 //double *dblCalcAve = NULL; //double *dblCalcSDAve = NULL; //double *dblCalcSDMax = NULL; //int *nCalcSDMaxPix = NULL; //double **ppdblCalcAve = NULL; //double **ppdblCalcSDMax = NULL; PINT *ppHistogramData = NULL; do { //バッファ作成//--------------------------- ppHistogramData = new PINT [nElement]; if( !ppHistogramData ) break; bReval = TRUE; for( int i=0; i<nElement; i++ ) { ppHistogramData[i] = new INT [nDataSize]; if( ppHistogramData[i]==NULL ) { bReval = FALSE; break; } memset( ppHistogramData[i], 0, sizeof(INT)*nDataSize ); } if( !bReval ) break; //--------------------------- if( (nPixelSize/nElement)==8 ) { bReval = GetHistogramValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, uiWidth, uiHeight, aBuffer->GetLinePitch(), nScopeLeft, nScopeRight , nDataSize, ppHistogramData ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetHistogramValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, uiWidth, uiHeight, aBuffer->GetLinePitch(), nScopeLeft, nScopeRight , nDataSize, ppHistogramData ); } if( !bReval ) break; CString szFileFullName = szFilePath; szFileFullName += szFileName; CStdioFile aFile; if( !aFile.Open( szFileFullName, CFile::modeCreate|CFile::modeWrite|CFile::typeText, NULL ) ) { bReval = FALSE; break; } aFile.SeekToBegin(); CString szText; CString szTmp; //Line No.1 //szTmp = _T("FileName=["); //szTmp += szFileName; //szTmp += _T("]"); // //aFile.WriteString(szTmp + _T("\n")); //Line No.2 //szTmp.Format(_T("ImageSize=(%u/%u) HistogramRange=(%d/%d)"),uiWidth, uiHeight, nScopeLeft, nScopeRight ); //aFile.WriteString(szTmp + _T("\n")); if( nElement==3 ) { szText = "\"data\",\"Red count\",\"Green count\",\"Blue count\"\n"; } else if( nElement==1 ) { szText = "\"data\",\"count\"\n"; } else { szText.Format(_T("\"data\"")); for( int j=0; j<nElement; j++ ) { szTmp.Format(_T(",\"count%i\""), j ); szText+=szTmp; } szText+=(_T("\n")); } aFile.WriteString(szText); for( int i=0; i<nDataSize; i++ ) { szText.Format(_T("%i"),i); for( int j=0; j<nElement; j++ ) { szTmp.Format(_T(",%i"), ppHistogramData[j][i] ); szText+=szTmp; } szText+=(_T("\n")); aFile.WriteString(szText); } aFile.Close(); bReval = TRUE; }while(0); if( ppHistogramData ) { for( int i=0; i<nElement; i++ ) { if( ppHistogramData[i] ) { delete [] ppHistogramData[i]; } } delete [] ppHistogramData; } return bReval; } //▲1.0.0.1055 //StBufferからElement取得 INT StCheckBase::GetElementFromBuffer(StBuffer *pBuffer) { StBufferInfo aInfo(pBuffer); return aInfo.GetElement(); } //StBufferからBitsPerPixel取得 INT StCheckBase::GetPixelSize(StBuffer *pBuffer) { StBufferInfo aInfo(pBuffer); return aInfo.GetPixelSize(); } //▼1.0.0.1055 //StBufferからPixelBits取得 INT StCheckBase::GetPixelBits(StBuffer *pBuffer) { StBufferInfo aInfo(pBuffer); return aInfo.GetPixelBits(); } //▲1.0.0.1055 //StBufferからColorIndex取得しセット INT StCheckBase::SetElementColorIndexFromBuffer(StBuffer *pBuffer) { StBufferInfo aInfo(pBuffer); for( int i=0; i<_countof(m_nColorIndex); i++ ) { m_nColorIndex[i] = aInfo.GetElementColorIndex(i); } return TRUE; } INT StCheckBase::GetElementColorIndex(INT iPos) { return m_nColorIndex[iPos]; } //StBufferからColorIndex取得 //0:R 1:G 2:B 3:A -1:Mono INT StCheckBase::GetElementColorIndexFromBuffer(StBuffer *pBuffer, INT iPos) { StBufferInfo aInfo(pBuffer); return aInfo.GetElementColorIndex(iPos); } //=============================================================================== //dblOutAverage:全画面のレベル平均 //dblOutSDAve:縦方向1ラインの標準偏差の平均 //dblOutSDMax:縦方向1ラインの標準偏差の最大値 //dblOutSDMPix:縦方向1ラインの標準偏差の最大値の位置 //=============================================================================== /* template <class X> BOOL GetSNAverageValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, DWORD dwStartLine, DWORD dwEndLine , double *dblOutAverage, double *dblOutSDAve, double *dblOutSDMax, int *nOutSDMPix ) { if( dwEndLine<dwStartLine ) return FALSE; if( dwHeight==0 ) return FALSE; if( dwStartLine>=dwWidth ) return FALSE; if( dwEndLine>=dwWidth ) return FALSE; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { double dblSDAve = 0.0; double dblSDMax = 0.0; int nSDMPix = 0; double sumData=0.0; X *pImgTop = ptRaw + i; pImgTop += dwStartLine * wElementsPerPixel; for( DWORD x=dwStartLine; x<=dwEndLine; x++ ) { double dblSigXn = 0.0; double dblSigXn2 = 0.0; X *pImg = pImgTop; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSigXn += *pImg; dblSigXn2 += (*pImg)*(*pImg); PBYTE pbImg = (PBYTE)pImg; pImg = (X *)(pbImg + nSrcLinePitch); } double dSD = sqrt( (double)(dwHeight*dblSigXn2-dblSigXn*dblSigXn)/(dwHeight*(dwHeight-1)) ); //縦方向の標準偏差 if( dSD > dblSDMax ) //最大標準偏差 { dblSDMax = dSD; nSDMPix = x; } dblSDAve += dSD; //平均用 sumData += dblSigXn; pImgTop += wElementsPerPixel; } double dblAverage = sumData / ( dwHeight * (dwEndLine - dwStartLine + 1) ); dblSDAve /= (dwEndLine - dwStartLine + 1); //代入 dblOutAverage[i] = dblAverage; dblOutSDAve[i] = dblSDAve; dblOutSDMax[i] = dblSDMax; nOutSDMPix[i] = nSDMPix; } return TRUE; } */ //------------------------------------------------------------------------------- //標準偏差および平均取得 // //------------------------------------------------------------------------------- //▼1.0.0.1028 //BOOL StCheckBase::GetSNAverage( StBuffer *aBuffer, INT iStart, INT iEnd, double *dblOutAverage, double *dblOutSDAve, double *dblOutSDMax, PINT nOutSDMPix ) BOOL StCheckBase::GetSNAverage( StBuffer *aBuffer, INT iStart, INT iEnd, double *dblOutAverage, double *dblOutSDAve, double *dblOutSDMax, PINT nOutSDMPix , double *pdblOutLineAverageMin, double *pdblOutLineAverageMax, PINT pnOutLineAverageMinPos, PINT pnOutLineAverageMaxPos ) //▲1.0.0.1028 { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; double *dblAverage = NULL; double *dblSDAve = NULL; double *dblSDMax = NULL; int *nSDMPix = NULL; //▼1.0.0.1028 double *pdblLineAverageMin = NULL; double *pdblLineAverageMax = NULL; int *pnLineAverageMinPos = NULL; int *pnLineAverageMaxPos = NULL; double **ppdblCalcAve = NULL; //▲1.0.0.1028 do { dblAverage = new double [nElement]; if( !dblAverage ) break; dblSDAve = new double [nElement]; if( !dblSDAve ) break; dblSDMax = new double [nElement]; if( !dblSDMax ) break; nSDMPix = new int [nElement]; if( !nSDMPix ) break; //▼1.0.0.1028 ppdblCalcAve = new double *[nElement]; if( !ppdblCalcAve ) break; memset( ppdblCalcAve, 0, sizeof(double *) * nElement); bReval = TRUE; size_t bufferSize = iEnd - iStart + 1; for( int i=0; i<nElement; i++ ) { ppdblCalcAve[i] = new double [bufferSize]; if( !ppdblCalcAve[i] ) { bReval = FALSE; break; } } if( !bReval ) break; //▲1.0.0.1028 if( (nPixelSize/nElement)==8 ) { bReval = GetSNAverageValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd //▼1.0.0.1028 //, dblAverage, dblSDAve, dblSDMax, nSDMPix, NULL, NULL, 0 ); , dblAverage, dblSDAve, dblSDMax, nSDMPix, ppdblCalcAve, NULL, bufferSize ); //▲1.0.0.1028 } else if( (nPixelSize/nElement)==16 ) { bReval = GetSNAverageValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd //▼1.0.0.1028 // , dblAverage, dblSDAve, dblSDMax, nSDMPix, NULL, NULL, 0 ); , dblAverage, dblSDAve, dblSDMax, nSDMPix, ppdblCalcAve, NULL, bufferSize ); //▲1.0.0.1028 } if( bReval ) { for( int i=0; i<nElement; i++ ) { if( dblOutAverage ) dblOutAverage[i] = dblAverage[i]; if( dblOutSDAve ) dblOutSDAve[i] = dblSDAve[i]; if( dblOutSDMax ) dblOutSDMax[i] = dblSDMax[i]; if( nOutSDMPix ) nOutSDMPix[i] = nSDMPix[i]; //▼1.0.0.1028 double *pdblAve = ppdblCalcAve[i]; double dblMax=pdblAve[0]; double dblMin=dblMax; INT nMaxPos = iStart; INT nMinPos = iStart; for( int j=1; j<(int)bufferSize; j++ ) { if( dblMax<pdblAve[j] ) { dblMax = pdblAve[j]; nMaxPos = j + iStart; } else if( dblMin>pdblAve[j] ) { dblMin = pdblAve[j]; nMinPos = j + iStart; } } if( pdblOutLineAverageMin ) pdblOutLineAverageMin[i] = dblMin; if( pdblOutLineAverageMax ) pdblOutLineAverageMax[i] = dblMax; if( pnOutLineAverageMinPos ) pnOutLineAverageMinPos[i] = nMinPos; if( pnOutLineAverageMaxPos ) pnOutLineAverageMaxPos[i] = nMaxPos; //▲1.0.0.1028 } } }while(0); if( dblAverage ) delete dblAverage; if( dblSDAve ) delete dblSDAve; if( dblSDMax ) delete dblSDMax; if( nSDMPix ) delete nSDMPix; //▼1.0.0.1028 if( ppdblCalcAve ) { for( int i=0; i<nElement; i++ ) { delete [] ppdblCalcAve[i]; } delete [] ppdblCalcAve; } //▲1.0.0.1028 return bReval; } //=============================================================================== //piContinuous:最大連続数 //piLine:最大連続数の位置 //piColor:最大連続数の色0:Red 1:Green 2:Blue -1:BW //=============================================================================== template <class X> BOOL GetSpecialBehaviorValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, DWORD dwStartLine, DWORD dwEndLine //▼1.0.0.1044 // , INT iMinLevel, INT iMaxLevel, INT iInOutMode, INT iColorMode, PINT piContinuous, PINT piLine, PINT piColor ) , INT iMinLevel, INT iMaxLevel, INT iInOutMode, INT iColorMode, PINT piContinuous, PINT piLine, PINT piColor, double *pdblLineAverage ) //▲1.0.0.1044 { if( dwEndLine<dwStartLine ) return FALSE; if( dwHeight==0 ) return FALSE; if( dwStartLine>=dwWidth ) return FALSE; if( dwEndLine>=dwWidth ) return FALSE; INT nMaxContinueCount = 0; INT nLine = -1; INT nColor = -1; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { if( ((iColorMode>>i)&1)==0 ) continue; X *pImgTop = ptRaw + i; pImgTop += dwStartLine * wElementsPerPixel; for( DWORD x=dwStartLine; x<=dwEndLine; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { INT iIO = 0; //外 if( *pImgData>=iMinLevel && *pImgData<=iMaxLevel ) { iIO = 1; //内 } if( iInOutMode!=iIO ) { nContinueCount++; if( nMaxContinueCount < nContinueCount ) { nMaxContinueCount=nContinueCount; nLine = x; if( wElementsPerPixel==3 ) nColor = i; } } else { nContinueCount=0; } pImgData = (X *)((char *)pImgData + nSrcLinePitch); } pImgTop += wElementsPerPixel; } } *piContinuous = nMaxContinueCount; *piLine = nLine; *piColor = nColor; //▼1.0.0.1044 if( pdblLineAverage && nLine>=0 ) { double dblLineAverage = 0.0; X *pImgTop = ptRaw + (nColor<0?0:nColor); pImgTop += nLine * wElementsPerPixel; X *pImgData = pImgTop; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblLineAverage += *pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } dblLineAverage /= dwHeight; *pdblLineAverage = dblLineAverage; } //▲1.0.0.1044 return TRUE; } //------------------------------------------------------------------------------- //特定挙動検査用 // //1)StartLineとEndLine内で、縦1ラインのそれぞれの画素レベルがMaxLevel-MinLevelの範囲(あるいは範囲外)にあるかどうかを調べる。 //2)規格外の画素が連続している数が一番多いライン位置および色を取得する。 //------------------------------------------------------------------------------- BOOL StCheckBase::GetSpecialBehavior( StBuffer *aBuffer, INT iStart, INT iEnd, INT iMinLevel, INT iMaxLevel, INT iInOutMode //▼1.0.0.1044 //, INT iColorMode, PINT piContinuous, PINT piLine, PINT piColor ) , INT iColorMode, PINT piContinuous, PINT piLine, PINT piColor, double *pdblLineAverage ) //▲1.0.0.1044 { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; INT iContinuous = 0; INT iLine = -1; INT iColor = -1; //▼1.0.0.1044 double dblLineAverage = -1.0; //▲1.0.0.1044 if( (nPixelSize/nElement)==8 ) { bReval = GetSpecialBehaviorValue( (unsigned char *)aBuffer->GetDataPointer(), nElement,aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd //▼1.0.0.1044 //, iMinLevel, iMaxLevel, iInOutMode, iColorMode, &iContinuous, &iLine, &iColor ); , iMinLevel, iMaxLevel, iInOutMode, iColorMode, &iContinuous, &iLine, &iColor, &dblLineAverage ); //▲1.0.0.1044 } else if( (nPixelSize/nElement)==16 ) { bReval = GetSpecialBehaviorValue( (unsigned short *)aBuffer->GetDataPointer(), nElement,aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd //▼1.0.0.1044 //, iMinLevel, iMaxLevel, iInOutMode, iColorMode, &iContinuous, &iLine, &iColor ); , iMinLevel, iMaxLevel, iInOutMode, iColorMode, &iContinuous, &iLine, &iColor, &dblLineAverage ); //▲1.0.0.1044 } *piContinuous = iContinuous; *piLine = iLine; *piColor = iColor; //▼1.0.0.1044 *pdblLineAverage = dblLineAverage; //▲1.0.0.1044 return bReval; } //=============================================================================== //pdblDifference:最大差分 //piHighLow:上か下か //piLine:最大連続数の位置 //pdblLineAverage:各ラインの平均値 //piLineMin:各ラインの最小画素値 //piLineMax 各ラインの最大画素値 //bufferSize :バッファサイズ 0の場合無視 //=============================================================================== template <class X> BOOL GetLineAverageDifferenceValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, double * pdblDifference, PINT piHighLow, PINT piLine , double **pdblLineAverage, INT **piLineMin, INT **piLineMax, size_t bufferSize ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; if( iStart>=(INT)dwWidth ) return FALSE; if( iEnd>=(INT)dwWidth ) return FALSE; INT nLines = iEnd - iStart + 1; if( bufferSize>0 && bufferSize<(DWORD)nLines ) return FALSE; double *pdblLineAverageValue = NULL; PINT piLineMinValue = NULL; PINT piLineMaxValue = NULL; do { pdblLineAverageValue = new double [nLines]; if( !pdblLineAverageValue ) break; piLineMinValue = new INT [nLines]; if( !piLineMinValue ) break; piLineMaxValue = new INT [nLines]; if( !piLineMaxValue ) break; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { double dblMaxDifference = 0.0; INT nLinePos = -1; INT nHighLow = -1; X *pImgTop = ptRaw + i; pImgTop += iStart * wElementsPerPixel; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; INT nMax = 0; INT nMin = 0x7FFFFFFF; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { //if( *pImgData==0 ) //TRACE(TEXT("@@@@@@@@@ pImgData[%d:%d]=0 "), x,y ); nMax = nMax>*pImgData?nMax:*pImgData; nMin = nMin<*pImgData?nMin:*pImgData; dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- pdblLineAverageValue[x] = dblSum / dwHeight; piLineMinValue[x] = nMin; piLineMaxValue[x] = nMax; double dblDifferenceValue = (double)nMax - pdblLineAverageValue[x]; if( dblDifferenceValue>dblMaxDifference ) { dblMaxDifference = dblDifferenceValue; nLinePos = x; nHighLow = 1; } dblDifferenceValue = pdblLineAverageValue[x] - (double)nMin; if( dblDifferenceValue>dblMaxDifference ) { dblMaxDifference = dblDifferenceValue; nLinePos = x; nHighLow = 0; } pImgTop += wElementsPerPixel; } pdblDifference[i] = dblMaxDifference; piHighLow[i] = nHighLow; piLine[i] = nLinePos; //代入 //TRACE(TEXT("@@@@@@@@@ in pdblLineAverage=0x%x\n"), pdblLineAverage ); //TRACE(TEXT("@@@@@@@@@ in pdblLineAverage[%d]=0x%x\n"), 0, pdblLineAverage[0] ); if( pdblLineAverage ) memcpy( pdblLineAverage[i], pdblLineAverageValue, sizeof(double) * nLines ); //TRACE(TEXT("@@@@@@@@@ out pdblLineAverage=0x%x\n"), pdblLineAverage ); //TRACE(TEXT("@@@@@@@@@ out pdblLineAverage[%d]=0x%x\n"), 0, pdblLineAverage[0] ); if( piLineMin ) memcpy( piLineMin[i], piLineMinValue, sizeof(INT) * nLines ); if( piLineMax ) memcpy( piLineMax[i], piLineMaxValue, sizeof(INT) * nLines ); } }while(0); if( pdblLineAverageValue ) delete [] pdblLineAverageValue; if( piLineMinValue ) delete [] piLineMinValue; if( piLineMaxValue ) delete [] piLineMaxValue; return TRUE; } //------------------------------------------------------------------------------- //デジタルデータ取りこぼし検査用 // //1)StartLineとEndLine内で、各縦ラインごとに画素値の最大最小平均を取得する。 //2)各ラインの平均と最大、最小の差分を求め、最大差分を規格と比較する。 //------------------------------------------------------------------------------- BOOL StCheckBase::GetLineAverageDifference( StBuffer *aBuffer, INT iStart, INT iEnd, double * pdblDifference, PINT piHighLow, PINT piLine, size_t *pElementSize , double **pdblLineAverage, INT **piLineMin, INT **piLineMax, size_t bufferSize ) { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; if( *pElementSize<(DWORD)nElement ) return FALSE; if( (nPixelSize/nElement)==8 ) { bReval = GetLineAverageDifferenceValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, pdblDifference, piHighLow, piLine , pdblLineAverage, piLineMin, piLineMax, bufferSize ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetLineAverageDifferenceValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, pdblDifference, piHighLow, piLine , pdblLineAverage, piLineMin, piLineMax, bufferSize ); } if( bReval ) *pElementSize = nElement; return bReval; } //=============================================================================== //wElementsPerPixel:1画素の要素(BW:1 Color:3) //dwWidth:横サイズ(全画像のサイズ、セパレート考慮なし) //dwHeight:縦サイズ //nSrcLinePitch:1ラインのサイズ //iStart:スタート位置(各セパレートごと) //iEnd:エンド位置(各セパレートごと) //iCheckWidth:検査の横サイズ //iSeparate:分割数 //pdblDifference:最大差分 //piLine:最大差分の位置 //pdblDifferenceRatio:最大差分比率 //piLineRatio:最大差分比率の位置 //画像の縦方向を平均化する。(1ライン分のデータにする。) //iCheckWidthの幅で最大-最小が一番大きい位置を求める。 //求めた位置で平均取得し、平均値から一番はなれた画素値、位置をもとめ、%化する。 //=============================================================================== template <class X> BOOL GetWidthLineAverageDifferenceValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, INT iCheckWidth, INT iSeparate , double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double * pdblAverage ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; INT nSeparateWidth = dwWidth / iSeparate; if( iEnd >= nSeparateWidth ) return FALSE; INT nLines = iEnd - iStart + 1; double *pdblLineAverageValue = NULL; do { pdblLineAverageValue = new double [nLines * iSeparate]; if( !pdblLineAverageValue ) break; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { //▼1.0.0.1015 //double dblMaxDiff = 0.0; double dblMaxDiff = -1.0; //▲1.0.0.1015 INT nMaxElement = -1; INT nMaxSeparate = -1; INT nMaxLine = -1; double dblAllAverage = 0.0; for( int j=0; j< iSeparate; j++ ) { INT nStart = ( nSeparateWidth * j + iStart ) * wElementsPerPixel; X *pImgTop = ptRaw + i; pImgTop += nStart; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- pdblLineAverageValue[x + j * nLines] = dblSum / dwHeight; dblAllAverage += dblSum; pImgTop += wElementsPerPixel; } for( INT x=0; x<nLines - iCheckWidth; x++ ) { double dblMin = 9999.0; double dblMax = 0.0; for( INT wd=0; wd<iCheckWidth; wd++ ) { dblMin = min(dblMin,pdblLineAverageValue[x + wd + j * nLines]); dblMax = max(dblMax,pdblLineAverageValue[x + wd + j * nLines]); } double dblDiff = dblMax - dblMin; if( dblMaxDiff < dblDiff ) { dblMaxDiff = dblDiff; nMaxElement = i; nMaxSeparate = j; nMaxLine = x; } } } //画像の平均、ゴミ検査用---------- if( pdblAverage ) //▼1.0.0.1043 //*pdblAverage = dblAllAverage / (iSeparate * nLines * dwHeight); pdblAverage[i] = dblAllAverage / (iSeparate * nLines * dwHeight); //▲1.0.0.1043 if( pdblDifference ) { pdblDifference[i] = dblMaxDiff; } if( piLine ) { piLine[i] = nMaxSeparate * nSeparateWidth + nMaxLine + iStart; } //-----求めた位置から再取得------------ double dblAverage = 0.0; for( INT wd=0; wd<iCheckWidth; wd++ ) { dblAverage += pdblLineAverageValue[nMaxLine + wd + nMaxSeparate * nLines]; } dblAverage /= iCheckWidth; //▼1.0.0.1015 //double dblMaxDiffRatio = 0.0; double dblMaxDiffRatio = -1.0; //▲1.0.0.1015 INT nMaxPos = -1; for( INT wd=0; wd<iCheckWidth; wd++ ) { double dblDiff = fabs( dblAverage - pdblLineAverageValue[nMaxLine + wd + nMaxSeparate * nLines] ); if( dblMaxDiffRatio < dblDiff ) { dblMaxDiffRatio = dblDiff; nMaxPos = nMaxSeparate * nSeparateWidth + wd + nMaxLine + iStart; } } if( dblAverage>0.0 ) { if( pdblDifferenceRatio ) pdblDifferenceRatio[i] = dblMaxDiffRatio / dblAverage * 100; } if( piLineRatio ) piLineRatio[i] = nMaxPos; } }while(0); if( pdblLineAverageValue ) delete [] pdblLineAverageValue; return TRUE; } //▼1.0.0.1041 //=============================================================================== //wElementsPerPixel:1画素の要素(BW:1 Color:3) //dwWidth:横サイズ(全画像のサイズ、セパレート考慮なし) //dwHeight:縦サイズ //nSrcLinePitch:1ラインのサイズ //iStart:スタート位置(各セパレートごと) //iEnd:エンド位置(各セパレートごと) //iCheckWidth:検査の横サイズ //iSeparate:分割数 //pdblDifference:最大差分 //piLine:最大差分の位置 //pdblDifferenceRatio:最大差分比率 //piLineRatio:最大差分比率の位置 //画像の縦方向を平均化する。(1ライン分のデータにする。) //iCheckWidthの幅で最大-平均,平均-最小が一番大きい位置を求める。 //求めた位置で平均取得し、平均値から一番はなれた画素値、位置をもとめ、%化する。 //=============================================================================== template <class X> BOOL GetWidthLineAverageDifferenceValue2( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, INT iCheckWidth, INT iSeparate , double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double * pdblAverage ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; INT nSeparateWidth = dwWidth / iSeparate; if( iEnd >= nSeparateWidth ) return FALSE; INT nLines = iEnd - iStart + 1; double *pdblLineAverageValue = NULL; do { pdblLineAverageValue = new double [nLines * iSeparate]; if( !pdblLineAverageValue ) break; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { double dblMaxDiff = -1.0; //INT nMaxElement = -1; INT nMaxSeparate = -1; INT nMaxLine = -1; double dblMaxDiffRatio = -1.0; //INT nMaxElement = -1; INT nMaxSeparateRatio = -1; INT nMaxLineRatio = -1; double dblAllAverage = 0.0; for( int j=0; j< iSeparate; j++ ) { INT nStart = ( nSeparateWidth * j + iStart ) * wElementsPerPixel; X *pImgTop = ptRaw + i; pImgTop += nStart; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- pdblLineAverageValue[x + j * nSeparateWidth] = dblSum / dwHeight; dblAllAverage += dblSum; pImgTop += wElementsPerPixel; } INT nMaxDifferencePos = -1; for( INT x=0; x<nLines - iCheckWidth; x++ ) { double dblMin = 9999.0; double dblMax = 0.0; double dblAreaAverage = 0.0; INT nPoxMin = -1; INT nPoxMax = -1; //平均取得 for( INT wd=0; wd<iCheckWidth; wd++ ) { if( dblMin>pdblLineAverageValue[x + wd + j * nSeparateWidth] ) { dblMin = pdblLineAverageValue[x + wd + j * nSeparateWidth]; nPoxMin = x + wd + j * nSeparateWidth; } if( dblMax<pdblLineAverageValue[x + wd + j * nSeparateWidth] ) { dblMax = pdblLineAverageValue[x + wd + j * nSeparateWidth]; nPoxMax = x + wd + j * nSeparateWidth; } dblAreaAverage += pdblLineAverageValue[x + wd + j * nSeparateWidth]; } dblAreaAverage /= iCheckWidth; if( dblMaxDiff<dblAreaAverage-dblMin ) { dblMaxDiff = dblAreaAverage-dblMin; //nMaxElement = i; nMaxSeparate = j; nMaxLine = nPoxMin; } if( dblMaxDiff<dblMax-dblAreaAverage ) { dblMaxDiff = dblMax-dblAreaAverage; //nMaxElement = i; nMaxSeparate = j; nMaxLine = nPoxMax; } if( dblAreaAverage>0.0 ) { if( dblMaxDiffRatio<(dblAreaAverage-dblMin)/dblAreaAverage ) { dblMaxDiffRatio = (dblAreaAverage-dblMin)/dblAreaAverage; //nMaxElement = i; nMaxSeparateRatio = j; nMaxLineRatio = nPoxMin; } if( dblMaxDiffRatio<(dblMax-dblAreaAverage)/dblAreaAverage ) { dblMaxDiffRatio = (dblMax-dblAreaAverage)/dblAreaAverage; //nMaxElement = i; nMaxSeparateRatio = j; nMaxLineRatio = nPoxMax; } } } } //画像の平均、ゴミ検査用---------- if( pdblAverage ) *pdblAverage = dblAllAverage / (iSeparate * nLines * dwHeight); if( pdblDifference ) { pdblDifference[i] = dblMaxDiff; } if( piLine ) { piLine[i] = nMaxLine; } if( pdblDifferenceRatio ) //▼1.0.0.1042 //pdblDifferenceRatio[i] = dblMaxDiffRatio; pdblDifferenceRatio[i] = dblMaxDiffRatio * 100; //%変換 //▲1.0.0.1042 if( piLineRatio ) piLineRatio[i] = nMaxLineRatio; } }while(0); if( pdblLineAverageValue ) delete [] pdblLineAverageValue; return TRUE; } //▲1.0.0.1041 //▼1.0.0.1043 //=============================================================================== //wElementsPerPixel:1画素の要素(BW:1 Color:3) //dwWidth:横サイズ(全画像のサイズ、セパレート考慮なし) //dwHeight:縦サイズ //nSrcLinePitch:1ラインのサイズ //iStart:スタート位置(各セパレートごと) //iEnd:エンド位置(各セパレートごと) //iCheckWidth:検査の横サイズ //iSeparate:分割数 //pdblDifference:最大差分 //piLine:最大差分の位置 //pdblDifferenceRatio:最大差分比率 //piLineRatio:最大差分比率の位置 //画像の縦方向を平均化する。(1ライン分のデータにする。) //iCheckWidthの幅で最大-平均,平均-最小が一番大きい位置を求める。 //求めた位置で平均取得し、平均値から一番はなれた画素値、位置をもとめ、%化する。 //=============================================================================== template <class X> BOOL GetWidthLineAverageDifferenceLineValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, INT iCheckWidth, INT iSeparate , double dblLimitDiffRatio, double * pdblDifferenceRatio, PINT piLineRatio, double * pdblAverage, PINT piLineContinuousCount, PINT piLineContinuousStart, PINT piLineContinuousEnd ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; INT nSeparateWidth = dwWidth / iSeparate; if( iEnd >= nSeparateWidth ) return FALSE; INT nLines = iEnd - iStart + 1; double *pdblLineAverageValue = NULL; do { pdblLineAverageValue = new double [nLines * iSeparate]; if( !pdblLineAverageValue ) break; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { double dblMaxDiff = -1.0; INT nMaxSeparate = -1; INT nMaxLine = -1; double dblMaxDiffRatio = -1.0; INT nMaxSeparateRatio = -1; INT nMaxLineRatio = -1; INT nMaxLineCount = 0; double dblTemporaryMaxDiffRatio = -1.0; INT nTemporaryMaxLineRatio = -1; INT nMaxLineStart = -1; INT nMaxLineEnd = -1; INT nLineStart = -1; INT nLineEnd = -1; double dblAllAverage = 0.0; for( int j=0; j< iSeparate; j++ ) { INT nStart = ( nSeparateWidth * j + iStart ) * wElementsPerPixel; X *pImgTop = ptRaw + i; pImgTop += nStart; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- pdblLineAverageValue[x + j * nSeparateWidth] = dblSum / dwHeight; dblAllAverage += dblSum; pImgTop += wElementsPerPixel; } INT nMaxDifferencePos = -1; INT nOverLimitCountMax=0; for( INT x=0; x<nLines - iCheckWidth; x++ ) { //double dblMin = 9999.0; //double dblMax = 0.0; double dblAreaAverage = 0.0; INT nPoxMin = -1; INT nPoxMax = -1; //平均取得 for( INT wd=0; wd<iCheckWidth; wd++ ) { //if( dblMin>pdblLineAverageValue[x + wd + j * nSeparateWidth] ) //{ // dblMin = pdblLineAverageValue[x + wd + j * nSeparateWidth]; // nPoxMin = x + wd + j * nSeparateWidth; //} //if( dblMax<pdblLineAverageValue[x + wd + j * nSeparateWidth] ) //{ // dblMax = pdblLineAverageValue[x + wd + j * nSeparateWidth]; // nPoxMax = x + wd + j * nSeparateWidth; //} dblAreaAverage += pdblLineAverageValue[x + wd + j * nSeparateWidth]; } dblAreaAverage /= iCheckWidth; //------------------- //dblPerLimit INT nContinuousOverCount=0; INT nContinuousOverCountMax=0; //if( x==16015 || x==nLines - iCheckWidth - 1 ) // Sleep(1); double dblMaxPer = 0.0; INT nPerPosMax = -1; INT nTemporaryLineStart = -1; INT nTemporaryLineEnd = -1; //double dblMinPer = 0; for( INT wd=0; wd<iCheckWidth && dblAreaAverage>0.0; wd++ ) { //if( x==nLines - iCheckWidth - 1 && x + wd + j * nSeparateWidth==16015 ) // Sleep(1); double dblPer = fabs(dblAreaAverage-pdblLineAverageValue[x + wd + j * nSeparateWidth])/dblAreaAverage; dblPer *= 100; //%変換 if( dblLimitDiffRatio<dblPer ) { if( nContinuousOverCount==0 ) nTemporaryLineStart = x + wd + j * nSeparateWidth; nTemporaryLineEnd = x + wd + j * nSeparateWidth; nContinuousOverCount++; if( dblMaxPer<dblPer ) { dblMaxPer = dblPer; nPoxMax = x + wd + j * nSeparateWidth; } } else { if( nContinuousOverCountMax<nContinuousOverCount ) { nContinuousOverCountMax=nContinuousOverCount; dblMaxDiff = dblMaxPer; nPerPosMax = nPoxMax; nLineStart = nTemporaryLineStart; nLineEnd = nTemporaryLineEnd; } nContinuousOverCount = 0; dblMaxPer = 0.0; nPoxMax = -1; } if( dblTemporaryMaxDiffRatio<dblPer ) { dblTemporaryMaxDiffRatio = dblPer; nTemporaryMaxLineRatio = x + wd + j * nSeparateWidth; } } BOOL bUpdate = FALSE; if( nMaxLineCount<nContinuousOverCountMax ) { bUpdate = TRUE; } else if( nMaxLineCount==nContinuousOverCountMax ) { if( dblMaxDiffRatio < dblMaxDiff ) { bUpdate = TRUE; } } if( bUpdate ) { dblMaxDiffRatio = dblMaxDiff; nMaxSeparateRatio = j; nMaxLineRatio = nPerPosMax; nMaxLineCount = nContinuousOverCountMax; nMaxLineStart = nLineStart; nMaxLineEnd = nLineEnd; } //------------------- //if( dblMaxDiff<dblAreaAverage-dblMin ) //{ // dblMaxDiff = dblAreaAverage-dblMin; // //nMaxElement = i; // nMaxSeparate = j; // nMaxLine = nPoxMin; //} //if( dblMaxDiff<dblMax-dblAreaAverage ) //{ // dblMaxDiff = dblMax-dblAreaAverage; // //nMaxElement = i; // nMaxSeparate = j; // nMaxLine = nPoxMax; //} //if( dblAreaAverage>0.0 ) //{ // if( dblMaxDiffRatio<(dblAreaAverage-dblMin)/dblAreaAverage ) // { // dblMaxDiffRatio = (dblAreaAverage-dblMin)/dblAreaAverage; // //nMaxElement = i; // nMaxSeparateRatio = j; // nMaxLineRatio = nPoxMin; // } // if( dblMaxDiffRatio<(dblMax-dblAreaAverage)/dblAreaAverage ) // { // dblMaxDiffRatio = (dblMax-dblAreaAverage)/dblAreaAverage; // //nMaxElement = i; // nMaxSeparateRatio = j; // nMaxLineRatio = nPoxMax; // } //} } } //Separete LoopEnd //画像の平均、ゴミ検査用---------- if( pdblAverage ) pdblAverage[i] = dblAllAverage / (iSeparate * nLines * dwHeight); //if( pdblDifference ) //{ // pdblDifference[i] = dblMaxDiff; //} //if( piLine ) //{ // piLine[i] = nMaxLine; //} if( dblMaxDiffRatio<0.0 ) { dblMaxDiffRatio = dblTemporaryMaxDiffRatio; nMaxLineRatio = nTemporaryMaxLineRatio; } if( pdblDifferenceRatio ) pdblDifferenceRatio[i] = dblMaxDiffRatio; if( piLineRatio ) piLineRatio[i] = nMaxLineRatio; if( piLineContinuousCount ) piLineContinuousCount[i] = nMaxLineCount; if( piLineContinuousStart ) piLineContinuousStart[i] = nMaxLineStart; if( piLineContinuousEnd ) piLineContinuousEnd[i] = nMaxLineEnd; } }while(0); if( pdblLineAverageValue ) delete [] pdblLineAverageValue; return TRUE; } //▲1.0.0.1043 //------------------------------------------------------------------------------- //画素欠陥検査用 //ゴミ検査用 // //1)StartLineとEndLine内で、各縦ラインごとに画素値の平均を取得する。 //2)検査開始ラインから検査幅分、最大最小の平均値を取得し、差分を求める。 //3)求めた差分が一番大きいライン値、および差分値を取得する。 //4)3で求めたライン値からSetWidthLines分、平均取得し、SetWidthLines分の各ライン平均との差分を取得する。 //5)4で求めた最大差分を規格と比較し、最大差分および位置を取得する。 //6)4で求めた最大差分の位置からSetWidthLines分、平均を求め、各ラインの平均との差分を求め比率および位置を取得する //------------------------------------------------------------------------------- //▼1.0.0.1041 //BOOL StCheckBase::GetWidthLineAverageDifference( StBuffer *aBuffer, INT iStart, INT iEnd, INT iWidth, INT iSeparate, size_t *pElementSize BOOL StCheckBase::GetWidthLineAverageDifference( StBuffer *aBuffer, INT iStart, INT iEnd, INT iWidth, INT iSeparate, INT nMode, size_t *pElementSize //▲1.0.0.1041 //▼1.0.0.1043 //, double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double *pdblAverage ) , double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double *pdblAverage, double dblLimitDiffRatio, PINT piLineContinuousCount, PINT piLineContinuousStart, PINT piLineContinuousEnd ) //▲1.0.0.1043 { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; if( *pElementSize<(DWORD)nElement ) return FALSE; //▼1.0.0.1041 //if( (nPixelSize/nElement)==8 ) //{ // bReval = GetWidthLineAverageDifferenceValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate // , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); //} //else //if( (nPixelSize/nElement)==16 ) //{ // bReval = GetWidthLineAverageDifferenceValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate // , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); //} if( nMode== 0 ) { if( (nPixelSize/nElement)==8 ) { bReval = GetWidthLineAverageDifferenceValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetWidthLineAverageDifferenceValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } } else //▼1.0.0.1043 if( nMode==1 ) //▲1.0.0.1043 { if( (nPixelSize/nElement)==8 ) { bReval = GetWidthLineAverageDifferenceValue2( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetWidthLineAverageDifferenceValue2( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } } //▲1.0.0.1041 //▼1.0.0.1043 else if( nMode==2 ) { if( (nPixelSize/nElement)==8 ) { bReval = GetWidthLineAverageDifferenceLineValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , dblLimitDiffRatio, pdblDifferenceRatio, piLineRatio, pdblAverage, piLineContinuousCount, piLineContinuousStart, piLineContinuousEnd ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetWidthLineAverageDifferenceLineValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iWidth, iSeparate , dblLimitDiffRatio, pdblDifferenceRatio, piLineRatio, pdblAverage, piLineContinuousCount, piLineContinuousStart, piLineContinuousEnd ); } } //▲1.0.0.1043 if( bReval ) *pElementSize = nElement; return bReval; } //=============================================================================== //pdblDifference:最大差分 //piLine:最大差分の位置 //pdblDifferenceRatio:最大差分比率 //piLineRatio:最大差分比率の位置 //=============================================================================== template <class X> BOOL GetMinimumLineAverageValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, double * pdblMinAverage, PINT piLine, PINT piElement ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; if( iEnd >= (INT)dwWidth ) return FALSE; INT nLines = iEnd - iStart + 1; do { double dblMin = 9999.0; INT nMinPos = -1; INT nMinElement = -1; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { //double dblMaxDiff = 0.0; //INT nMaxElement = -1; //INT nMaxSeparate = -1; //INT nMaxLine = -1; INT nStart = iStart * wElementsPerPixel; X *pImgTop = ptRaw + i; pImgTop += nStart; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- double dblLineAverageValue = dblSum / dwHeight; if( dblMin>dblLineAverageValue ) { dblMin = dblLineAverageValue; nMinPos = x; nMinElement = i; } pImgTop += wElementsPerPixel; } } if( pdblMinAverage ) *pdblMinAverage = dblMin; if( piLine ) *piLine = nMinPos; if( piElement ) *piElement = nMinElement; }while(0); return TRUE; } //------------------------------------------------------------------------------- //Linetoline用 //各縦ラインの平均を求め、最小値が規格内かどうか判定する。 // //1)StartLineとEndLine内で、各縦ラインごとに画素値の平均を取得する。 //2)各ラインの平均値の最小値および位置を取得する。 //------------------------------------------------------------------------------- BOOL StCheckBase::GetMinimumLineAverage( StBuffer *aBuffer, INT iStart, INT iEnd, size_t *pElementSize, double * pdblMinAverage, PINT piLine, PINT piElement ) { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; if( *pElementSize<(DWORD)nElement ) return FALSE; if( (nPixelSize/nElement)==8 ) { bReval = GetMinimumLineAverageValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, pdblMinAverage, piLine, piElement ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetMinimumLineAverageValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, pdblMinAverage, piLine, piElement ); } if( bReval ) *pElementSize = nElement; return bReval; } //=============================================================================== //pdblDifference:最大差分 //piLine:最大差分の位置 //pdblDifferenceRatio:最大差分比率 //piLineRatio:最大差分比率の位置 //=============================================================================== template <class X> BOOL GetEffectivePixelValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, INT iStart, INT iEnd, INT iLevel, PINT piEffectiveStart, PINT piEffectiveEnd ) { if( iEnd<iStart ) return FALSE; if( dwHeight==0 ) return FALSE; if( iEnd >= (INT)dwWidth ) return FALSE; INT nLines = iEnd - iStart + 1; do { double dblMin = 9999.0; INT nMinPos = -1; INT nMinElement = -1; for( int i=0; i< wElementsPerPixel; i++ ) //0:Blue 1:Greeeen 2:Red 0:BW { INT nHighLowFlag = 0; INT nEffectiveStart = -1; INT nEffectiveEnd = -1; INT nStart = iStart * wElementsPerPixel; X *pImgTop = ptRaw + i; pImgTop += nStart; for( INT x=0; x<nLines; x++ ) { INT nContinueCount = 0; X *pImgData = pImgTop; double dblSum = 0.0; for( DWORD y=0; y<dwHeight; y++ ) //縦方向の合計 { dblSum += (double)*pImgData; pImgData = (X *)((char *)pImgData + nSrcLinePitch); } //代入------- double dblLineAverageValue = dblSum / dwHeight; if( nHighLowFlag == 0 ) //レベルより上の時 { if( dblLineAverageValue>=(double)iLevel ) { nEffectiveStart = x + nStart; nHighLowFlag = 1; } } else //レベルより下の時 { if( dblLineAverageValue<(double)iLevel ) { nEffectiveEnd = x - 1 + nStart; } } pImgTop += wElementsPerPixel; } if( nHighLowFlag==1 && nEffectiveEnd<0 ) nEffectiveEnd = iEnd; if( piEffectiveStart ) piEffectiveStart[i] = nEffectiveStart; if( piEffectiveEnd ) piEffectiveEnd[i] = nEffectiveEnd; } }while(0); return TRUE; } //------------------------------------------------------------------------------- //有効画素検査用 //有効画素位置を求め、規格と同じかどうか判定する。 // //1)設定範囲内で縦ラインの平均を取得する。 //2)取得した平均が設定レベル以上の最初、最後のライン位置を取得する。 //3)取得した最初、最後のライン位置が規格と同じ場合OKとする。違う場合NGとする。 //------------------------------------------------------------------------------- BOOL StCheckBase::GetEffectivePixel( StBuffer *aBuffer, INT iStart, INT iEnd, INT iLevel, size_t *pElementSize, PINT piEffectiveStart, PINT piEffectiveEnd ) { BOOL bReval = FALSE; INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( iStart>iEnd ) return FALSE; if( iEnd>=(INT)aBuffer->GetWidth() ) return FALSE; if( *pElementSize<(DWORD)nElement ) return FALSE; if( (nPixelSize/nElement)==8 ) { bReval = GetEffectivePixelValue( (unsigned char *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iLevel, piEffectiveStart, piEffectiveEnd ); } else if( (nPixelSize/nElement)==16 ) { bReval = GetEffectivePixelValue( (unsigned short *)aBuffer->GetDataPointer(), nElement, aBuffer->GetWidth(), aBuffer->GetHeight(), aBuffer->GetLinePitch(), iStart, iEnd, iLevel, piEffectiveStart, piEffectiveEnd ); } if( bReval ) *pElementSize = nElement; return bReval; } //▼1.0.0.1040 //------------------------------------------------------------------------------- //CSVゴミ検査用 // //1)検査開始ラインから検査幅分、最大最小の値を取得し、差分を求める。 //2)求めた差分が一番大きいライン値、および差分値を取得する。 //3)2で求めたライン値からiWidth分、平均取得し、iWidth分の各ライン平均との差分を取得する。 //4)3で求めた最大差分を規格と比較し、最大差分および位置を取得する。 //5)3で求めた最大差分の位置からiWidth分、平均を求め、各ラインの平均との差分を求め比率および位置を取得する //------------------------------------------------------------------------------- //▼1.0.0.1041 //BOOL StCheckBase::GetWidthLineAverageDifference( double *pdblBuffer, INT iSize, INT iStart, INT iEnd, INT iWidth, INT iSeparate, size_t *pElementSize BOOL StCheckBase::GetWidthLineAverageDifference( double *pdblBuffer, INT iSize, INT iStart, INT iEnd, INT iWidth, INT iSeparate, INT nMode, size_t *pElementSize //▲1.0.0.1041 //▼1.0.0.1043 //, double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double *pdblAverage ) , double * pdblDifference, PINT piLine, double * pdblDifferenceRatio, PINT piLineRatio, double *pdblAverage, double dblLimitDiffRatio, PINT piLineContinuousCount, PINT piLineContinuousStart, PINT piLineContinuousEnd ) //▲1.0.0.1043 { BOOL bReval = FALSE; if( iStart>iEnd ) return FALSE; //▼1.0.0.1041 //bReval = GetWidthLineAverageDifferenceValue( pdblBuffer, 1, iSize, 1, iSize, iStart, iEnd, iWidth, iSeparate // , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); if( nMode==0 ) { bReval = GetWidthLineAverageDifferenceValue( pdblBuffer, 1, iSize, 1, iSize, iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } else //▼1.0.0.1043 if( nMode==1 ) //▲1.0.0.1043 { bReval = GetWidthLineAverageDifferenceValue2( pdblBuffer, 1, iSize, 1, iSize, iStart, iEnd, iWidth, iSeparate , pdblDifference, piLine, pdblDifferenceRatio, piLineRatio, pdblAverage ); } //▲1.0.0.1041 //▼1.0.0.1043 else if( nMode==2 ) { bReval = GetWidthLineAverageDifferenceLineValue( pdblBuffer, 1, iSize, 1, iSize, iStart, iEnd, iWidth, iSeparate , dblLimitDiffRatio, pdblDifferenceRatio, piLineRatio, pdblAverage, piLineContinuousCount, piLineContinuousStart, piLineContinuousEnd ); } //▲1.0.0.1043 return bReval; } //▲1.0.0.1040 //▼1.0.0.1044 template <class X> BOOL GetMinLevelValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwWidth, DWORD dwHeight, DWORD nSrcLinePitch, DWORD dwStartLine, DWORD dwEndLine //▼1.0.0.1067b ////▼1.0.0.1058 // //, INT *pnMin ) // , INT *pnMin, INT *pnMinLine ) ////▲1.0.0.1058 , INT *pnMin, INT *pnMinLine, INT nBunch ) //nBunch: Even Oddの束数 //▲1.0.0.1067b { //▼1.0.0.1067b if( nBunch<=0 ) nBunch=1; INT nPos; //▲1.0.0.1067b X *pImg, *pImgData; for( int k=0; k<wElementsPerPixel; k++) // 0:BW { pImg = ptRaw + k; for( int i=0; i<dwWidth; i++ ) { if(dwStartLine<=i && i<=dwEndLine) { pImgData = pImg; for(int j=0; j<dwHeight; j++) { //▼1.0.0.1067b //if( pnMin[i&1]>(*pImgData) ) //{ // pnMin[i&1]=(*pImgData); // //▼1.0.0.1058 // pnMinLine[i&1]= (j<<16) + i; // //▲1.0.0.1058 //} nPos = (i/nBunch)&1; if( pnMin[nPos]>(*pImgData) ) { pnMin[nPos]=(*pImgData); pnMinLine[nPos]= (j<<16) + i; } //▲1.0.0.1067b pImgData = (X *)((char *)pImgData + nSrcLinePitch); } } pImg += 1; } } return TRUE; } //EOの最小レベル取得 //dataWidth 1画素のビット数 //モノクロのみで対応 //オフセット設定中 //▼1.0.0.1067b //▼1.0.0.1058 //BOOL StCheckBase::GetMinLevel( StBuffer *aBuffer, INT nStart, INT nEnd, int *pnMin ) BOOL StCheckBase::GetMinLevel( StBuffer *aBuffer, INT nStart, INT nEnd, int *pnMin, int *pnMinLine, int nBunch ) //▲1.0.0.1058 //▲1.0.0.1067b { INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); if( nElement==0 ) return FALSE; if( nPixelSize%8 ) return FALSE; if( nStart>nEnd ) return FALSE; if( nEnd>=(INT)aBuffer->GetWidth() ) return FALSE; INT nWidth = aBuffer->GetWidth(); //画像高さ INT nHeight = aBuffer->GetHeight(); //画像高さ INT nLinePitch = aBuffer->GetLinePitch(); //画像高さ INT nMinData[2] = {9999,9999}; //▼1.0.0.1058 INT nMinLine[2] = {-1,-1}; //▲1.0.0.1058 unsigned char *pInImg = (unsigned char *)aBuffer->GetDataPointer(); BOOL bReval = FALSE; if( nPixelSize==8 ) //8bit 1byte { //▼1.0.0.1067b ////▼1.0.0.1058 ////bReval = GetMinLevelValue( pInImg, nElement, nWidth, nHeight, nLinePitch, nStart, nEnd, &nMinData[0] ); //bReval = GetMinLevelValue( pInImg, nElement, nWidth, nHeight, nLinePitch, nStart, nEnd, &nMinData[0], &nMinLine[0] ); ////▲1.0.0.1058 bReval = GetMinLevelValue( pInImg, nElement, nWidth, nHeight, nLinePitch, nStart, nEnd, &nMinData[0], &nMinLine[0], nBunch ); //▲1.0.0.1067b } else { //2byte //▼1.0.0.1067b ////▼1.0.0.1058 //bReval = GetMinLevelValue( (unsigned short *)pInImg, nElement, nWidth, nHeight, nLinePitch, nStart, nEnd, &nMinData[0], &nMinLine[0] ); ////▲1.0.0.1058 bReval = GetMinLevelValue( (unsigned short *)pInImg, nElement, nWidth, nHeight, nLinePitch, nStart, nEnd, &nMinData[0], &nMinLine[0], nBunch ); //▲1.0.0.1067b } if( bReval ) { if( pnMin ) { for( INT i=0; i<2; i++ ) { pnMin[i] = nMinData[i]; //Even Odd } } //▼1.0.0.1058 if( pnMinLine ) { for( INT i=0; i<2; i++ ) { pnMinLine[i] = nMinLine[i]; //Even Odd } } //▲1.0.0.1058 } return bReval; } //▲1.0.0.1044 //▼1.0.0.1048 template <class X> BOOL GetChannelAverageValue( X *ptRaw, WORD wElementsPerPixel, DWORD dwImageWidth, DWORD dwImageHeight, INT nChannel, PINT pnStartLine, INT nWidth , double *pAverage ) { PINT64 pSum = new INT64 [nChannel]; if( pSum==NULL ) return FALSE; for( int c=0; c<wElementsPerPixel; c++ ) { memset( pSum, 0, sizeof(INT64)*nChannel ); for( int i=0; i<nChannel/2; i++ ) { X *pImgX = ptRaw + pnStartLine[i] * wElementsPerPixel; for( int y=0; y<dwImageHeight; y++ ) { X *pImg = pImgX; for( int x=0; x<nWidth; x++ ) { pSum[(x&1)+i*2] += *pImg; pImg += wElementsPerPixel; } pImgX += dwImageWidth * wElementsPerPixel; } } INT nCount = dwImageHeight * nWidth / 2; for( int i=0; i<nChannel/2; i++ ) { pAverage[ i + c * nChannel ] = double (pSum[i]) / nCount; } } return TRUE; } BOOL StCheckBase::GetChannelAverage( StBuffer *aBuffer, PINT pnStart, INT nWidth, INT nChannel, double *pAverage ) { INT nElement = GetElementFromBuffer(aBuffer); INT nPixelSize = GetPixelSize(aBuffer); INT nImageWidth = aBuffer->GetWidth(); //画像 INT nImageHeight = aBuffer->GetHeight(); //画像 INT nLinePitch = aBuffer->GetLinePitch(); //画像 if( nElement==0 ) return FALSE; //if( nPixelSize%8 ) // return FALSE; for( int i=0; i<nChannel/2; i++ ) { if( pnStart[i]+nWidth>nImageWidth ) return FALSE; } unsigned char *pInImg = (unsigned char *)aBuffer->GetDataPointer(); BOOL bReval = FALSE; if( nPixelSize==8 ) //8bit 1byte { bReval = GetChannelAverageValue( (unsigned char *)pInImg, nElement, nImageWidth, nImageHeight, nChannel, pnStart, nWidth, pAverage ); } else { //2byte bReval = GetChannelAverageValue( (unsigned short *)pInImg, nElement, nImageWidth, nImageHeight, nChannel, pnStart, nWidth, pAverage ); } return bReval; } //▲1.0.0.1048
[ "anryu@sentech.co.jp" ]
anryu@sentech.co.jp
3d80689b61b433be474fe952b0954525a48ecfd0
f41b872f0dcace92c28a4f6cf3193fabe9a237b0
/Bachelor/999_Backup/6_Software/Eclipse_WS/CuBa_BBB_TCPSocket/Control/States/CEdgeBalance.h
da1f507fbdd0b9a6c20ae58e7e56baf956529a0b
[]
no_license
MichaelMMMMM/Bachelor
acd5806ebf60879e14d19092cb261b628c193c53
c0b3a9a25163042082a05376ac5d9ca1f838d8b3
refs/heads/master
2021-01-12T14:36:26.518106
2017-05-29T19:05:05
2017-05-29T19:05:05
72,037,486
1
0
null
null
null
null
UTF-8
C++
false
false
1,057
h
/** * @file CEdgeBalance.h * @author Michael Meindl * @date 18.04.2017 * @brief State to handle the edge balancing. */ #ifndef CEDGEBALANCE_H #define CEDGEBALANCE_H #include "AState.h" #include "CEdgeBalanceAction.h" class CEdgeBalance : public AState { public: bool dispatch(CMessage& msg) override; bool tryEntry(CMessage& msg, AState*& statePtr) override; void onEntry() override; void onExit() override; bool onInitial(CMessage& msg); bool onIdle(CMessage& msg); bool onBalance(CMessage& msg); public: CEdgeBalance(); CEdgeBalance(const CEdgeBalance&) = delete; CEdgeBalance& operator=(const CEdgeBalance&) = delete; ~CEdgeBalance() = default; private: using StatePtr = bool(CEdgeBalance::*)(CMessage&); private: static constexpr StatePtr sInitial = static_cast<StatePtr>(&CEdgeBalance::onInitial); static constexpr StatePtr sIdle = static_cast<StatePtr>(&CEdgeBalance::onIdle); static constexpr StatePtr sBalance = static_cast<StatePtr>(&CEdgeBalance::onBalance); StatePtr mState; CEdgeBalanceAction mAction; }; #endif
[ "michaelmeindl@web.de" ]
michaelmeindl@web.de
daf431bcd4388d4e35c5afbaea1c618a1c947763
912343d48f250eedec0fa5953dc5e94e0b06458b
/some FYP source code/PlayerInformationSet.cpp
1f0286ef72c810dea6d7eb5b5ea6ffaa0c963b84
[]
no_license
Conor-Harney/PortfolioSourceCode
e96e8e716cb3dd64c74bd67b028f216605038db4
b29f115ca96d81f470c1f4bf61fdb12340f8e2b4
refs/heads/master
2021-01-10T17:39:57.805713
2016-09-28T00:21:37
2016-09-28T00:21:37
51,406,505
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
#include "stdafx.h" #include "PlayerInformationSet.h" PlayerInformationSet::PlayerInformationSet() { } PlayerInformationSet::PlayerInformationSet(int p_id, string p_name, int p_score): m_id(p_id), m_name(p_name), m_score(p_score) { } PlayerInformationSet::~PlayerInformationSet(void) { } int PlayerInformationSet::getId() { return m_id; } string PlayerInformationSet::getName() { return m_name; } int PlayerInformationSet::getScore() { return m_score; } void PlayerInformationSet::setId(int p_id) { m_id = p_id; } void PlayerInformationSet::setScore(int p_score) { m_score = p_score; } void PlayerInformationSet::setName(string p_name) { m_name = p_name; }
[ "cw208kccgdbc00155687@gmail.com" ]
cw208kccgdbc00155687@gmail.com
11ecb9fc8c7c5d9eb67a5471ecab636f11059554
62221ec379c905956b3ca91d9b4508d6cc7a85a7
/Tudat/Astrodynamics/EarthOrientation/shortPeriodEarthOrientationCorrectionCalculator.h
0dab1458b23dad09050de2548cbe8bbcd8abca40
[]
permissive
rodyo/tudat
b581e8dcbc5fe0cb37e0276cb5fe4185eac2e385
318d168e01580c15ac17ed72172c8b214c146475
refs/heads/master
2021-07-18T10:06:02.483754
2020-05-11T07:37:05
2020-05-11T07:37:05
252,571,897
0
0
BSD-3-Clause
2020-04-02T21:48:58
2020-04-02T21:48:57
null
UTF-8
C++
false
false
6,719
h
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * */ #ifndef TUDAT_SHORTPERIODEARTHORIENTATIONCORRECTIONCALCULATOR_H #define TUDAT_SHORTPERIODEARTHORIENTATIONCORRECTIONCALCULATOR_H #include <string> #include <functional> #include <boost/bind.hpp> #include <boost/make_shared.hpp> #include <Eigen/Core> #include "Tudat/Basics/basicTypedefs.h" #include "Tudat/InputOutput/basicInputOutput.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h" #include "Tudat/Astrodynamics/EarthOrientation/readAmplitudeAndArgumentMultipliers.h" #include "Tudat/External/SofaInterface/fundamentalArguments.h" #include "Tudat/InputOutput/basicInputOutput.h" namespace tudat { namespace earth_orientation { //! Object to calculate the short period variations in Earth orientaion parameters /*! * Object to calculate the short period variations in Earth orientaion parameters, e.g. taking into account * variations due to both libration and ocean tides. */ template< typename OutputType > class ShortPeriodEarthOrientationCorrectionCalculator { public: //! Constructor, requires files defining the amplitudes and fundamental argument multipliers of the variations. /*! * Constructor, requires files defining the sine and cosine amplitudes and fundamental argument multipliers numbers * of the variations for both ocean tide and libration variations. A cut-off amplitude (taken as * the RSS of the amplitudes) below which amplitudes in the files are ignored can be provided. * \param conversionFactor Conversion factor to be used for amplitudes, used to multiply input values, typically for unit * conversion purposes. * \param minimumAmplitude Minimum amplitude that is read from files and considered in calculations. * \param amplitudesFiles List of files with amplitudes for corrections * \param argumentMultipliersFile Fundamental argument multiplier for corrections * \param argumentFunction Fundamental argument functions associated with multipliers, default Delaunay arguments with GMST */ ShortPeriodEarthOrientationCorrectionCalculator( const double conversionFactor, const double minimumAmplitude, const std::vector< std::string >& amplitudesFiles, const std::vector< std::string >& argumentMultipliersFile , const std::function< Eigen::Vector6d( const double ) > argumentFunction = std::bind( &sofa_interface::calculateApproximateDelaunayFundamentalArgumentsWithGmst, std::placeholders::_1 ) ): argumentFunction_( argumentFunction ) { if( amplitudesFiles.size( ) != argumentMultipliersFile.size( ) ) { throw std::runtime_error( "Error when calling ShortPeriodEarthOrientationCorrectionCalculator, input size is inconsistent" ); } // Read data from files std::pair< Eigen::MatrixXd, Eigen::MatrixXd > dataFromFile; for( unsigned int i = 0; i < amplitudesFiles.size( ); i++ ) { dataFromFile = readAmplitudesAndFundamentalArgumentMultipliers( amplitudesFiles.at( i ), argumentMultipliersFile.at( i ), minimumAmplitude ); argumentAmplitudes_.push_back( conversionFactor * dataFromFile.first ); argumentMultipliers_.push_back( dataFromFile.second ); } } //! Function to obtain short period corrections. /*! * Function to obtain short period corrections, using time as input. Fundamental arguments are calculated internally. * \param ephemerisTime Time (TDB seconds since J2000) at which corretions are to be determined * \return Short period corrections */ OutputType getCorrections( const double& ephemerisTime ) { return sumCorrectionTerms( argumentFunction_( ephemerisTime ) ); } //! Function to obtain short period corrections. /*! * Function to obtain short period corrections, using fundamental arguments as input. * \param fundamentalArguments Fundamental arguments from which corretions are to be determined * \return Short period corrections */ OutputType getCorrections( const Eigen::Vector6d& fundamentalArguments ) { return sumCorrectionTerms( fundamentalArguments ); } private: //! Function to sum all the corrcetion terms. /*! * Function to sum all the corrcetion terms. * \param arguments Values of fundamental arguments * \return Total correction at current fundamental arguments */ OutputType sumCorrectionTerms( const Eigen::Vector6d& arguments ); //! Amplitudes of libration-induced variations std::vector< Eigen::MatrixXd > argumentAmplitudes_; //! Fundamental argument multipliers of libration-induced variations. std::vector< Eigen::MatrixXd > argumentMultipliers_; //! Fundamental argument functions associated with multipliers. std::function< Eigen::Vector6d( const double ) > argumentFunction_; }; //! Function to retrieve the default UT1 short-period correction calculator /*! * Function to retrieve the default UT1 short-period correction calculator, from Tables 5.1, 8.2 and 8.2. of IERS 2010 * Conventions. An amplitude cutoff may be provided. * \param minimumAmplitude Variation amplitude below which corrections are not taken into account. * \return Default UT1 short-period correction calculator */ std::shared_ptr< ShortPeriodEarthOrientationCorrectionCalculator< double > > getDefaultUT1CorrectionCalculator( const double minimumAmplitude = 0.0 ); //! Function to retrieve the default polar motion short-period correction calculator /*! * Function to retrieve the default polar motion short-period correction calculator, from Tables 5.1, 8.2 and 8.2. of IERS 2010 * Conventions. An amplitude cutoff may be provided. * \param minimumAmplitude Variation amplitude below which corrections are not taken into account. * \return Default polar motion short-period correction calculator */ std::shared_ptr< ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > > getDefaultPolarMotionCorrectionCalculator( const double minimumAmplitude = 0.0 ); } } #endif //TUDAT_SHORTPERIODEARTHORIENTATIONCORRECTIONCALCULATOR_H
[ "d.dirkx@tudelft.nl" ]
d.dirkx@tudelft.nl
0772dbc05a051b7d0eb4eacbe509ca430722c5c6
64505206b174a88642833be436aa5fc2bdf8f777
/dist/Mesa/src/glu/sgi/libnurbs/interface/incurveeval.cc
b289b42104dd4f07ccafe31936cb0f16b0a7f661
[]
no_license
noud/mouse-bsd-4.0.1-x
3a51529924f50dcca4b1e923b2f9922d7c33d496
86c082b577d5fa54f056f9abb7dd0eb8b07c3bb6
refs/heads/master
2023-02-27T11:56:52.742306
2020-02-18T13:02:55
2020-02-18T13:02:55
334,542,495
0
0
null
null
null
null
UTF-8
C++
false
false
5,993
cc
/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** ** $Date: 2006/04/22 15:22:47 $ $Revision: 1.1.1.1 $ */ /* ** $Header: /cvsroot/xsrc/dist/Mesa/src/glu/sgi/libnurbs/interface/incurveeval.cc,v 1.1.1.1 2006/04/22 15:22:47 macallan Exp $ */ #include <stdlib.h> #include <stdio.h> #include "glcurveval.h" /* *compute the Bezier polynomials C[n,j](v) for all j at v with *return values stored in coeff[], where * C[n,j](v) = (n,j) * v^j * (1-v)^(n-j), * j=0,1,2,...,n. *order : n+1 *vprime: v *coeff : coeff[j]=C[n,j](v), this array store the returned values. *The algorithm is a recursive scheme: * C[0,0]=1; * C[n,j](v) = (1-v)*C[n-1,j](v) + v*C[n-1,j-1](v), n>=1 *This code is copied from opengl/soft/so_eval.c:PreEvaluate */ void OpenGLCurveEvaluator::inPreEvaluate(int order, REAL vprime, REAL *coeff) { int i, j; REAL oldval, temp; REAL oneMinusvprime; /* * Minor optimization * Compute orders 1 and 2 outright, and set coeff[0], coeff[1] to * their i==1 loop values to avoid the initialization and the i==1 loop. */ if (order == 1) { coeff[0] = 1.0; return; } oneMinusvprime = 1-vprime; coeff[0] = oneMinusvprime; coeff[1] = vprime; if (order == 2) return; for (i = 2; i < order; i++) { oldval = coeff[0] * vprime; coeff[0] = oneMinusvprime * coeff[0]; for (j = 1; j < i; j++) { temp = oldval; oldval = coeff[j] * vprime; coeff[j] = temp + oneMinusvprime * coeff[j]; } coeff[j] = oldval; } } void OpenGLCurveEvaluator::inMap1f(int which, //0: vert, 1: norm, 2: color, 3: tex int k, //dimension REAL ulower, REAL uupper, int ustride, int uorder, REAL *ctlpoints) { int i,x; curveEvalMachine *temp_em; switch(which){ case 0: //vertex vertex_flag = 1; temp_em = &em_vertex; break; case 1: //normal normal_flag = 1; temp_em = &em_normal; break; case 2: //color color_flag = 1; temp_em = &em_color; break; default: texcoord_flag = 1; temp_em = &em_texcoord; break; } REAL *data = temp_em->ctlpoints; temp_em->uprime = -1; //initialized temp_em->k = k; temp_em->u1 = ulower; temp_em->u2 = uupper; temp_em->ustride = ustride; temp_em->uorder = uorder; /*copy the control points*/ for(i=0; i<uorder; i++){ for(x=0; x<k; x++){ data[x] = ctlpoints[x]; } ctlpoints += ustride; data += k; } } void OpenGLCurveEvaluator::inDoDomain1(curveEvalMachine *em, REAL u, REAL *retPoint) { int j, row; REAL the_uprime; REAL *data; if(em->u2 == em->u1) return; the_uprime = (u-em->u1) / (em->u2-em->u1); /*use already cached values if possible*/ if(em->uprime != the_uprime){ inPreEvaluate(em->uorder, the_uprime, em->ucoeff); em->uprime = the_uprime; } for(j=0; j<em->k; j++){ data = em->ctlpoints+j; retPoint[j] = 0.0; for(row=0; row<em->uorder; row++) { retPoint[j] += em->ucoeff[row] * (*data); data += em->k; } } } void OpenGLCurveEvaluator::inDoEvalCoord1(REAL u) { REAL temp_vertex[4]; REAL temp_normal[3]; REAL temp_color[4]; REAL temp_texcoord[4]; if(texcoord_flag) //there is a texture map { inDoDomain1(&em_texcoord, u, temp_texcoord); texcoordCallBack(temp_texcoord, userData); } #ifdef DEBUG printf("color_flag = %i\n", color_flag); #endif if(color_flag) //there is a color map { inDoDomain1(&em_color, u, temp_color); colorCallBack(temp_color, userData); } if(normal_flag) //there is a normal map { inDoDomain1(&em_normal, u, temp_normal); normalCallBack(temp_normal, userData); } if(vertex_flag) { inDoDomain1(&em_vertex, u, temp_vertex); vertexCallBack(temp_vertex, userData); } } void OpenGLCurveEvaluator::inMapMesh1f(int umin, int umax) { REAL du, u; int i; if(global_grid_nu == 0) return; //no points to output du = (global_grid_u1 - global_grid_u0) / (REAL) global_grid_nu; bgnline(); for(i=umin; i<= umax; i++){ u = (i==global_grid_nu)? global_grid_u1: global_grid_u0 + i*du; inDoEvalCoord1(u); } endline(); }
[ "mouse@Rodents-Montreal.ORG" ]
mouse@Rodents-Montreal.ORG
e1b73751facac830fb708ac52041c883d6bdf37f
77a091c62781f6aefeebdfd6efd4bab9caa51465
/Done/Codeforces/407/C.cpp
02279699142ef19ba648a4ca2bc5c8bf37f78526
[]
no_license
breno-helf/Maratona
55ab11264f115592e1bcfd6056779a3cf27e44dc
c6970bc554621746cdb9ce53815b8276a4571bb3
refs/heads/master
2021-01-23T21:31:05.267974
2020-05-05T23:25:23
2020-05-05T23:25:23
57,412,343
1
2
null
2017-01-25T14:58:46
2016-04-29T20:54:08
C++
UTF-8
C++
false
false
843
cpp
#include <bits/stdc++.h> using namespace std; #define debug(args...) fprintf(stderr,args) #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const int MAX = 112345; const int INF = 0x3f3f3f3f; const ll MOD = 1000000007; ll a[MAX], d[MAX], q[MAX], w[MAX], resp; int n; int main () { scanf ("%d", &n); for (int i = 1; i <= n; i++) { scanf ("%lld", a + i); if (i > 1) d[i - 1] = abs(a[i - 1] - a[i]); } for (int i = 1; i < n; i++) { q[i] = w[i] = d[i]; if (i % 2) q[i] *= -1; else w[i] *= -1; } q[1] = 0; resp = -INF; ll cur1 = 0, cur2 = 0; for (int i = 1; i < n; i++) { cur1 += q[i]; cur2 += w[i]; resp = max(resp, max(cur1, cur2)); if (cur1 < 0) cur1 = 0; if (cur2 < 0) cur2 = 0; } printf("%lld\n", resp); }
[ "breno.moura@hotmail.com" ]
breno.moura@hotmail.com
99b3d996eac5746b5070ab3ba5dab0430ded96eb
0c8b9eb55d24b20da2bdd02e9ee39c9a5d4477a7
/src/configd-tool/LS2Comparator.cpp
8a92bd5e81b9516867d5d29d88f53b0ce5dc5edf
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
webosce/configd
c267b1a03254ec2f80e2b0dda650a5a5ccf419f4
c09654deaa3a257d63c47a6af52ed40834e3ca1e
refs/heads/webosce
2023-04-27T07:27:58.978688
2018-03-08T03:58:38
2018-03-08T03:58:38
145,512,693
0
0
null
2023-04-25T20:48:26
2018-08-21T05:46:04
C++
UTF-8
C++
false
false
1,725
cpp
// Copyright (c) 2017-2018 LG Electronics, 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. // // SPDX-License-Identifier: Apache-2.0 #include "LS2Comparator.h" #include <fstream> #include "util/Platform.h" JValue LS2Comparator::convertFileToJValue(const string &filename) { if (!Platform::isFileExist(filename.c_str())) return nullptr; JValue array = pbnjson::Array(); ifstream in(filename); string line; while (std::getline(in, line)) { JValue message = JDomParser::fromString(line); if (message.isNull()) // Invalid File format return nullptr; array.append(message); } in.close(); return array; } LS2Comparator::LS2Comparator() { } LS2Comparator::LS2Comparator(const string& a, const string& b) { m_jsonA = convertFileToJValue(a); m_jsonB = convertFileToJValue(b); if (m_jsonA.isNull() || m_jsonB.isNull()) return; m_filenameA = a; m_filenameB = b; } LS2Comparator::~LS2Comparator() { } bool LS2Comparator::isEqual() { return true; } bool LS2Comparator::isLoaded(const string& filename) { if (filename == m_filenameA || filename == m_filenameB) return true; return false; }
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
3f05b504672388040c951347fd0b30c09efd6879
0181ae1d3af970fffa7d15216f39d606c7dfba1f
/printlib/include/HDF5printer.hpp
8694742bbd7bae100f3ef2825d493606e7567e7d
[]
no_license
CLGS-AVGL/Projet-GLCS-2020-2021
6aa832392b00502b104973451d84a8dda559e880
d417a7691b140484eb19708dbe90d8f0f61682f6
refs/heads/main
2023-02-25T18:55:22.382518
2021-01-28T14:35:03
2021-01-28T14:35:03
327,850,252
0
0
null
2021-01-08T09:00:17
2021-01-08T09:00:16
null
UTF-8
C++
false
false
299
hpp
#pragma once // headers #include <hdf5.h> #include <hdf5_hl.h> #include <mpi.h> #include <printer.hpp> // classe printer HDF5 class HDF5printer : public Printer { public: void simulation_updated(const Distributed2DField &data, const Configuration &config) override; };
[ "alan.vaquet@gmail.com" ]
alan.vaquet@gmail.com
76a14311fe560d9a1ce4a773f58cc14a5a2b227b
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/winui/printer/ptpcmxdw/PrintJobMultiplePT.cpp
ba9ed15909cbe404a052e3801e10ecca6efea78a
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
17,896
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" HRESULT XPathQueryOnPrintCaps( __in PPTPC_STATE_INFO psi, __in IXMLDOMDocument2 *pPrintCapsDOM, __in BSTR bstrXPathQuery, __out IXMLDOMNodeList **ppIXMLDOMNodeList ) { HRESULT hr = S_OK; BSTR bstrSelectionLanguage = SysAllocString(L"SelectionLanguage"); BSTR bstrXPath = SysAllocString(L"XPath"); BSTR bstrSelectionNamespaces = SysAllocString(L"SelectionNamespaces"); BSTR bstrNS = SysAllocString(L" \ xmlns:psf=\"http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework\" \ xmlns:psk=\"http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords\" \ "); if ( NULL == pPrintCapsDOM || NULL == bstrXPathQuery || NULL == ppIXMLDOMNodeList) { hr = E_INVALIDARG; } *ppIXMLDOMNodeList = NULL; if ( NULL == bstrSelectionLanguage || NULL == bstrXPath || NULL == bstrSelectionNamespaces|| NULL == bstrNS ) { hr = E_OUTOFMEMORY; } if ( SUCCEEDED(hr) ) { VARIANT var; VariantInit (&var); var.vt = VT_BSTR; var.bstrVal = bstrXPath; hr = pPrintCapsDOM->setProperty(bstrSelectionLanguage, var); } if ( SUCCEEDED(hr) ) { VARIANT var; VariantInit (&var); var.vt = VT_BSTR; var.bstrVal = bstrNS; hr = pPrintCapsDOM->setProperty(bstrSelectionNamespaces, var); } // // Select all the options for PageMediaSize // if ( SUCCEEDED(hr) ) { hr = pPrintCapsDOM->selectNodes(bstrXPathQuery, ppIXMLDOMNodeList); } if ( NULL != bstrSelectionLanguage ) { SysFreeString(bstrSelectionLanguage); } if ( NULL != bstrXPath ) { SysFreeString(bstrXPath); } if ( NULL != bstrSelectionNamespaces) { SysFreeString(bstrSelectionNamespaces); } if ( NULL != bstrNS) { SysFreeString(bstrNS); } return hr; } #define XPATHQUERYFORPRINTCAPS(FeatureName, OptionName) \ L"psf:PrintCapabilities/psf:Feature[substring-after(@name,':')='" FeatureName L"']" \ L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]" \ L"/psf:Option" \ L"[substring-after(@name,':')='" OptionName L"']" \ L"[name(namespace::*[.='http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords'])=substring-before(@name,':')]" HRESULT GetNodeWithA4PaperSize( __in PPTPC_STATE_INFO psi, __in IXMLDOMDocument2 *pPrintCapsDOM, __out IXMLDOMNode **ppPaperSizeNode ) { HRESULT hr = S_OK; IXMLDOMNodeList *pPaperSizeNodeList = NULL; BSTR bstrXPathQuery = SysAllocString(XPATHQUERYFORPRINTCAPS(L"PageMediaSize", L"ISOA4") ); if ( NULL == ppPaperSizeNode ) { *ppPaperSizeNode = NULL; } if ( NULL == bstrXPathQuery ) { hr = E_OUTOFMEMORY; } if ( SUCCEEDED(hr) ) { hr = XPathQueryOnPrintCaps(psi, pPrintCapsDOM, bstrXPathQuery, &pPaperSizeNodeList); } if ( SUCCEEDED(hr) ) { hr = pPaperSizeNodeList->nextNode(ppPaperSizeNode); } if ( NULL != bstrXPathQuery) { SysFreeString(bstrXPathQuery); } if ( NULL != pPaperSizeNodeList ) { pPaperSizeNodeList->Release(); } return hr; } HRESULT CreateNewPrintTicketWithA4PaperSize( __in PPTPC_STATE_INFO psi, __in IXMLDOMDocument2 *pPrintCapsDOM, __in IStream *pBasePrintTicketStream, __in IXMLDOMDocument2 *pBasePrintTicketDOM, __out IStream **ppPrintTicketA4Stream) { IStream *pDeltaPrintTicketStream = NULL; IXMLDOMDocument2 *pDeltaPrintTicket = NULL; IXMLDOMNode *pPrintCapsA4Node = NULL; IXMLDOMNode *pPrintTicketA4Node = NULL; HRESULT hr = S_OK; if ( NULL != ppPrintTicketA4Stream ) { *ppPrintTicketA4Stream = NULL; } else { hr = E_INVALIDARG; } if ( SUCCEEDED(hr) ) { hr = GetNodeWithA4PaperSize(psi, pPrintCapsDOM, &pPrintCapsA4Node); } if ( SUCCEEDED(hr) ) { hr = CreatePTFeatureOptionNodeFromPrintCapOptionNode(psi, pPrintCapsA4Node, &pPrintTicketA4Node); } // Create a duplicate print ticket from the same print ticket stream as the base print ticket. if ( SUCCEEDED(hr) ) { hr = ConvertPTPCStreamToDOM(pBasePrintTicketStream, &pDeltaPrintTicket); } // From the Cloned Print Ticket, take away all off feature-option pairs // so that only a minimal (or you may call it sparse) print ticket remains. if ( SUCCEEDED(hr) ) { hr = ConvertFullPrintTicketToMinimalPrintTicket(pDeltaPrintTicket); } if ( SUCCEEDED(hr) ) { hr = MergeNodeIntoMinimalPrintTicket(pDeltaPrintTicket, pPrintTicketA4Node); } // The API PTMergeAndValidatePrintTicket() takes in a base PrintTicket, a Delta or a New PrintTicket // and returns the merged print ticket. We already have a stream for Base PT. We create a // stream for Delta PT and also prepare an empty stream where the merged PT can be written. if ( SUCCEEDED(hr) ) { hr = CreateStreamOnHGlobal(NULL, TRUE, &pDeltaPrintTicketStream); } if ( SUCCEEDED(hr) ) { hr = DOMDocumentToIStream(pDeltaPrintTicket, pDeltaPrintTicketStream); } if ( SUCCEEDED(hr) ) { hr = CreateStreamOnHGlobal(NULL, TRUE, ppPrintTicketA4Stream); } // // Make sure printticket stream points to the begining // if ( SUCCEEDED(hr) ) { LARGE_INTEGER li = {0,0}; hr = pBasePrintTicketStream->Seek(li, STREAM_SEEK_SET, NULL); if ( SUCCEEDED(hr) ) { hr = pDeltaPrintTicketStream->Seek(li, STREAM_SEEK_SET, NULL); } } if ( SUCCEEDED(hr) ) { hr = PTMergeAndValidatePrintTicket(psi->hProvider, pBasePrintTicketStream, pDeltaPrintTicketStream, kPTPageScope, *ppPrintTicketA4Stream, NULL); } // If operation succeeded, the returned hr can be either // S_PT_NO_CONFLICT (0x00040001) OR // S_PT_CONFLICT_RESOLVED (0x00040002) // as defined in prntvpt.h. // These codes are ALSO defined as "Success but static" or "Macintosh clipboard format" in winerror.h where // they have a different meaning. So do not get confused. if ( pPrintCapsA4Node ) { pPrintCapsA4Node->Release(); pPrintCapsA4Node = NULL; } if ( pPrintTicketA4Node ) { pPrintTicketA4Node->Release(); pPrintTicketA4Node = NULL; } if ( pDeltaPrintTicket ) { pDeltaPrintTicket->Release(); pDeltaPrintTicket = NULL; } if ( pDeltaPrintTicketStream ) { pDeltaPrintTicketStream->Release(); pDeltaPrintTicketStream = NULL; } return hr; } HRESULT CreateJobWith2PrintTickets( __in PPTPC_STATE_INFO psi, __in_bcount(cbPTBuf1) PBYTE pbPTBuf1, __in DWORD cbPTBuf1, __in_bcount(cbPTBuf2) PBYTE pbPTBuf2, __in DWORD cbPTBuf2 ) { HRESULT hr = S_OK; HDC hdcMXDW = NULL; PBYTE pEscData = NULL; DWORD cbEscData = 0; BOOL bStartDocSent = FALSE; BOOL bStartPageSent = FALSE; // Make sure the printer is installed and we can create its DC. if (SUCCEEDED (hr) ) { hdcMXDW = CreateDC( NULL, psi->szPrinterName, NULL, NULL); if(NULL == hdcMXDW) { DWORD dwLastError = GetLastError(); vFormatAndPrint(IDS_APP_CREATEDC_FAILED); if ( ERROR_INVALID_PRINTER_NAME == dwLastError ) { vFormatAndPrint(IDS_APP_MXDWPRINTER_NOTINSTALLED); } hr = HRESULT_FROM_WIN32(dwLastError); } } // Make sure driver is a XPSDrv driver. i.e. it can accept XPS content. if (SUCCEEDED (hr) ) { hr = IsXPSCapableDriver(hdcMXDW); // Only a return value of S_OK from IsXPSCapableDriver() means driver is XPS capable // while we were querying the driver. // A return value of S_FALSE means driver is not XPS capable if ( S_FALSE == hr ) { vFormatAndPrint(IDS_APP_XPS_CAPABLE_PRINTER_NOTINSTALLED); hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } } if ( SUCCEEDED(hr) ) { DOCINFO DocInfo = { sizeof(DOCINFO), L"Multiple PrintTickets Sample", // Title of the print job NULL, // Not specifying output file. Determined by Printer NULL, // Not specifying data type. 0 }; //Send the Escape if( StartDoc(hdcMXDW, &DocInfo) > 0) { bStartDocSent = TRUE; } else { // Sometimes StartDoc fails if the specified output file cannot be opened. // Sometimes that happens when a viewer is viewing the file, while the driver // is trying to write to it. hr = HRESULT_FROM_WIN32(GetLastError()); } } if ( SUCCEEDED (hr) ) { if( StartPage(hdcMXDW) > 0) { bStartPageSent = TRUE; } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } // Create Escape for first Print Ticket if ( SUCCEEDED(hr) ) { hr = PutTogetherEscapeStructureForPrintTicket( MXDCOP_PRINTTICKET_FIXED_DOC, pbPTBuf1, cbPTBuf1, &pEscData, &cbEscData); } // Send Print Ticket for the first page if ( SUCCEEDED (hr) ) { if( ExtEscape(hdcMXDW, MXDC_ESCAPE, cbEscData, (LPCSTR) pEscData, 0, NULL) <= 0 ) { vFormatAndPrint(IDS_APP_EXTESCAPE_FAILED); hr = HRESULT_FROM_WIN32(GetLastError()); } } if ( SUCCEEDED (hr) ) { WCHAR szText[] = L"First Page with User Default PrintTicket"; if ( FALSE == TextOut(hdcMXDW, 200, 200, szText, (int) wcslen(szText) ) ) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if ( bStartPageSent ) { if( EndPage(hdcMXDW) > 0) { bStartPageSent = FALSE; } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } // Free the pEscData allocated in PutTogetherEscapeStructureForPrintTicket if(pEscData != NULL) { MemFree (pEscData); pEscData = NULL; } // Start new page and use a different print ticket. if ( SUCCEEDED(hr) ) { if( StartPage(hdcMXDW) > 0) { bStartPageSent = TRUE; } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } // Create Escape for second Print Ticket if ( SUCCEEDED(hr) ) { hr = PutTogetherEscapeStructureForPrintTicket( MXDCOP_PRINTTICKET_FIXED_PAGE, pbPTBuf2, cbPTBuf2, &pEscData, &cbEscData); } // Send Print Ticket for the above page if ( SUCCEEDED (hr) ) { if( ExtEscape(hdcMXDW, MXDC_ESCAPE, cbEscData, (LPCSTR) pEscData, 0, NULL) <= 0 ) { vFormatAndPrint(IDS_APP_EXTESCAPE_FAILED); hr = HRESULT_FROM_WIN32(GetLastError()); } } if ( SUCCEEDED (hr) ) { WCHAR szText[] = L"Second Page with Modified Print Ticket"; if ( FALSE == TextOut(hdcMXDW, 200, 200, szText, (int)wcslen(szText)) ) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if( bStartPageSent ) { EndPage(hdcMXDW); } if( bStartDocSent ) { EndDoc(hdcMXDW); } if(hdcMXDW != NULL) { DeleteDC(hdcMXDW); hdcMXDW = NULL; } if(pEscData != NULL) { MemFree (pEscData); pEscData = NULL; } return hr; } /*++ Routine Name: CreateJobWith2PrintTickets Routine Description: --*/ HRESULT CreateJobWith2PrintTickets( __in PPTPC_STATE_INFO psi, __in IStream *pPTStream1, __in IStream *pPTStream2) { HRESULT hr = S_OK; PBYTE pbPTBuf1 = NULL; DWORD cbPTBuf1 = 0; PBYTE pbPTBuf2 = NULL; DWORD cbPTBuf2 = 0; if ( SUCCEEDED(hr) ) { hr = ConvertPTStreamToBuffer(pPTStream1, &pbPTBuf1, &cbPTBuf1 ); } if ( SUCCEEDED(hr) ) { hr = ConvertPTStreamToBuffer(pPTStream2, &pbPTBuf2, &cbPTBuf2 ); } if (SUCCEEDED(hr) ) { hr = CreateJobWith2PrintTickets(psi, pbPTBuf1, cbPTBuf1, pbPTBuf2, cbPTBuf2); } CoTaskMemFree(pbPTBuf1); CoTaskMemFree(pbPTBuf2); return hr; } /*++ Routine Name: CreateMultiplePrintTicketJob Routine Description: This routine creates a print job for the "Microsoft XPS Document Writer" printer. The job has multiple print tickets. A different print ticket for each page. One print ticket is the full user default print ticket. Second print ticket is a full print ticket with a media size A4. First page has a simple line of text and an embedded image. Second page has a simple line of text. Arguments: <None> Return Value: S_OK if successful, E_* if there is an error --*/ HRESULT CreatePrintJobMultiplePrintTicket( VOID ) { HRESULT hr = S_OK; PTPC_STATE_INFO si = {0}; IStream *pPrintCapsStream = NULL; IXMLDOMDocument2 *pPrintCapsDOM = NULL; IStream *pBasePrintTicketStream = NULL; IXMLDOMDocument2 *pBasePrintTicketDOM = NULL; IStream *pPrintTicketA4Stream = NULL; hr = StringCchCopy(si.szPrinterName, CCHOF(si.szPrinterName), gszPrinterName); if ( SUCCEEDED(hr) ) { hr = GetUserPrintTicketStream(&si, &pBasePrintTicketStream); } if ( SUCCEEDED(hr) ) { hr = ConvertPTPCStreamToDOM(pBasePrintTicketStream, &pBasePrintTicketDOM); } // Use the PrintTicket to get the print capabilities. If you want to get // the print ticket based on the default print ticket, you don't need to // pass the default print ticket stream to the API. But we are doing it // here just to show how it can be done. // ConvertPTPCStreamToDOM may have moved the stream pointer. // So make sure printticket stream points to the begining if ( SUCCEEDED(hr) ) { LARGE_INTEGER li = {0,0}; hr = pBasePrintTicketStream->Seek(li, STREAM_SEEK_SET, NULL); } if ( SUCCEEDED(hr) ) { hr = GetPrintCapabilitiesBasedOnPrintTicket(&si, pBasePrintTicketStream, &pPrintCapsStream); } if ( SUCCEEDED(hr) ) { hr = ConvertPTPCStreamToDOM(pPrintCapsStream, &pPrintCapsDOM); } // Now we have the default PT and the Print Capabilities. Use them to create a new PrintTicket with A4 paper size // instead of the default "Letter" ("Letter" is default on U.S. systems. It may or may not be default on your system). if ( SUCCEEDED(hr) ) { hr = CreateNewPrintTicketWithA4PaperSize(&si, pPrintCapsDOM, pBasePrintTicketStream, pBasePrintTicketDOM, &pPrintTicketA4Stream); } if ( SUCCEEDED(hr) ) { hr = CreateJobWith2PrintTickets(&si, pBasePrintTicketStream, pPrintTicketA4Stream); } // Cleanup if ( NULL != pPrintCapsDOM ) { pPrintCapsDOM->Release(); pPrintCapsDOM = NULL; } if ( NULL != pPrintCapsStream ) { pPrintCapsStream->Release(); pPrintCapsStream = NULL; } if ( NULL != pBasePrintTicketDOM ) { pBasePrintTicketDOM->Release(); pBasePrintTicketDOM = NULL; } if ( NULL != pBasePrintTicketStream ) { pBasePrintTicketStream->Release(); pBasePrintTicketStream = NULL; } if ( NULL != pPrintTicketA4Stream ) { pPrintTicketA4Stream->Release(); pPrintTicketA4Stream = NULL; } RelaseStateInfoContents(&si); return hr; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
5cea0f5ae78659c75c7bb6117d2933ee0c50555a
039a30b5db53c7f828ea87b9f305f51be4d7e6cc
/2018夏/6.25/6.25-A.cpp
fbf029fbff5a949a05ebf47c96869c28f542ea9c
[]
no_license
1092772959/My-ACM-code
cd5af7cebc04c3252ed880686759257237b63b34
87109a0a98e6ea49f8726927cc4357a9155ba3f2
refs/heads/master
2021-07-03T01:31:39.173353
2020-08-25T13:48:49
2020-08-25T13:48:49
151,587,646
0
0
null
null
null
null
UTF-8
C++
false
false
466
cpp
#include<bits/stdc++.h> using namespace std; const int mod = 1e9+7; typedef long long ll; ll fpow(ll base,ll n) { ll res=1; while(n){ if(n&1) res=res*base%mod; base=base*base%mod; n>>=1; } return res; } int main() { int T,n,k; scanf("%d",&T); while(T--){ ll res=0; scanf("%d%d",&n,&k); for(int i=1;i<=n;++i) res=(res+fpow(i,k))%mod; printf("%lld\n",res); } return 0; }
[ "32030091+1092772959@users.noreply.github.com" ]
32030091+1092772959@users.noreply.github.com
ed4af1e990d909cf8392ee755405bb22dfa059a3
8dc84558f0058d90dfc4955e905dab1b22d12c08
/ppapi/proxy/gamepad_resource.h
eceb908cbb2af637c4093a6d0e6260c2c608b5cc
[ "BSD-3-Clause", "LicenseRef-scancode-khronos", "LicenseRef-scancode-unknown-license-reference" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
1,775
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PPAPI_PROXY_GAMEPAD_RESOURCE_H_ #define PPAPI_PROXY_GAMEPAD_RESOURCE_H_ #include <memory> #include "base/compiler_specific.h" #include "base/macros.h" #include "device/gamepad/gamepad_shared_buffer.h" #include "ppapi/c/ppb_gamepad.h" #include "ppapi/proxy/plugin_resource.h" #include "ppapi/proxy/ppapi_proxy_export.h" #include "ppapi/thunk/ppb_gamepad_api.h" struct PP_GamepadsSampleData; namespace base { class SharedMemory; } namespace ppapi { namespace proxy { // This class is a bit weird. It isn't a true resource from the plugin's // perspective. But we need to make requests to the browser and get replies. // It's more convenient to do this as a resource, so the instance just // maintains an internal lazily instantiated copy of this resource. class PPAPI_PROXY_EXPORT GamepadResource : public PluginResource, public thunk::PPB_Gamepad_API { public: GamepadResource(Connection connection, PP_Instance instance); ~GamepadResource() override; // Resource implementation. thunk::PPB_Gamepad_API* AsPPB_Gamepad_API() override; // PPB_Gamepad_API. void Sample(PP_Instance instance, PP_GamepadsSampleData* data) override; private: void OnPluginMsgSendMemory(const ResourceMessageReplyParams& params); std::unique_ptr<base::SharedMemory> shared_memory_; const device::GamepadHardwareBuffer* buffer_; // Last data returned so we can use this in the event of a read failure. PP_GamepadsSampleData last_read_; DISALLOW_COPY_AND_ASSIGN(GamepadResource); }; } // namespace proxy } // namespace ppapi #endif // PPAPI_PROXY_GAMEPAD_RESOURCE_H_
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
4c0b56c28630811c1e0dbba28ca5e3a49fb2498f
86b881ba691421587c150d835631ac373f80d3d1
/CheatSheets/Stringh/RAW.cpp
97e73397e3dbcd20696912bba77009f04469a164
[]
no_license
Marchusky/Programming-I
aef05134ed8330997b01359114b3e49590952349
626e2f0e113c087cd49ad2d05fda928403729784
refs/heads/master
2020-04-07T12:59:36.000903
2019-06-12T07:15:42
2019-06-12T07:15:42
158,388,918
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
#define _CRT_SECURE_NO_WARNINGS #include <cstring> // //int main() //{ // // Declaration // char str1[10]; // char str2[10]; // // Copy // strcpy(str1, "Cloud"); // strcpy(str2, "Barret"); // // Compare // bool equals = strcmp(str1, str2) == 0; // // Copy and concat // char str3[20]; // strcpy(str3, str1); // strcat(str3, str2); //}
[ "45201955+Marchusky@users.noreply.github.com" ]
45201955+Marchusky@users.noreply.github.com
53039d3b5a106b9a2f089d9b4681f951c2deea8d
a383c8d5f8f50d617af8b1e5cd6d211c6012d888
/design-pattern/Memento/Main.cpp
b657c0f2b6c85d8b010d85f0ee532dd29cb61e4a
[]
no_license
qxj/jqian
ff15711ba4e5b17eb7d5a5b1e1d5d2d591b7d645
1e16fd46a6a0c633d9c7d9819238c98d479edfd3
refs/heads/master
2020-05-21T22:17:49.829583
2017-02-09T03:52:57
2017-02-09T03:52:57
32,244,698
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
/******************************************************************** created: 2006/08/09 filename: Main.cpp author: 李创 http://www.cppblog.com/converse/ purpose: Memento模式的测试代码 *********************************************************************/ #include "Memento.h" int main() { // 创建一个原发器 Originator* pOriginator = new Originator("old state"); pOriginator->PrintState(); // 创建一个备忘录存放这个原发器的状态 Memento *pMemento = pOriginator->CreateMemento(); // 更改原发器的状态 pOriginator->SetState("new state"); pOriginator->PrintState(); // 通过备忘录把原发器的状态还原到之前的状态 pOriginator->RestoreState(pMemento); pOriginator->PrintState(); delete pOriginator; delete pMemento; return 0; }
[ "jqian@jqian.net" ]
jqian@jqian.net
4618b6b5dd08d3d42c8c206cec88156a0cc89daf
f1bd4d38d8a279163f472784c1ead12920b70be2
/AlexRR_Editor/MSC_ScaleObject.cpp
1237aa2fc4513073353773ada6102d08935acd5c
[]
no_license
YURSHAT/stk_2005
49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83
b68bbf136688d57740fd9779423459ef5cbfbdbb
refs/heads/master
2023-04-05T16:08:44.658227
2021-04-18T09:08:18
2021-04-18T18:35:59
361,129,668
1
0
null
null
null
null
UTF-8
C++
false
false
1,485
cpp
//---------------------------------------------------- // file: MSC_ScaleObject.cpp //---------------------------------------------------- #include "Pch.h" #pragma hdrstop #include "NetDeviceLog.h" #include "UI_Main.h" #include "MSC_List.h" #include "MSC_ScaleObject.h" #include "Scene.h" #include "SceneClassList.h" //---------------------------------------------------- MouseCallback_ScaleObject::MouseCallback_ScaleObject() :MouseCallback( TARGET_OBJECT, ACTION_SCALE ) { m_Center.set(0,0,0); m_AxisEnable[0] = true; m_AxisEnable[1] = true; m_AxisEnable[2] = true; } MouseCallback_ScaleObject::~MouseCallback_ScaleObject(){ } //---------------------------------------------------- bool MouseCallback_ScaleObject::Start(){ if( Scene.SelectionCount( OBJCLASS_SOBJECT2, true ) == 0 ) return false; Scene.UndoPrepare(); m_Center.set( UI.pivot() ); return true; } bool MouseCallback_ScaleObject::End(){ return true; } void MouseCallback_ScaleObject::Move(){ float dy = - m_DeltaCpH.y * g_MouseScaleSpeed; IVector amount; amount.set( 1.f+dy, 1.f+dy, 1.f+dy ); for(int i=0;i<3;i++) if(!m_AxisEnable[i]) amount.a[i] = 1.f; ObjectIt _F = Scene.FirstObj(); for(;_F!=Scene.LastObj();_F++) if( (*_F)->ClassID() == OBJCLASS_SOBJECT2 && (*_F)->Visible() ) if( (*_F)->Selected() ){ if( m_Local ){ (*_F)->LocalScale( amount ); } else { (*_F)->Scale( m_Center, amount ); } } } //----------------------------------------------------
[ "loxotron@bk.ru" ]
loxotron@bk.ru
06f8f43af144da031e58982d4725c362baa31631
5044badd060c95c7d19e56ab253a9089214d97a9
/cpp/conc.cpp
2c75b482656ea955853022bd2b7862b671bc426d
[]
no_license
jerdmann/thesoulforge
37abcc07e349e647fa84d9e5938f6d7d1df0cc81
73c40da14437b17f00fd00de46da1d0efcd6065c
refs/heads/master
2022-06-18T07:45:36.198457
2022-05-24T03:27:05
2022-05-24T03:27:05
121,191,538
0
0
null
null
null
null
UTF-8
C++
false
false
2,258
cpp
#include <atomic> #include <chrono> #include <functional> #include <iostream> #include <thread> #include <vector> #include <cassert> #include <mutex> #include <stdio.h> #include <unistd.h> using namespace std; using namespace std::chrono; class spinlock { atomic_bool lock_ { false }; public: void lock() { while (lock_.exchange(true)); } void unlock() { lock_ = false; } }; using lock_t = lock_guard<spinlock>; template <typename T> class freelist { struct node { T data; node* next; }; atomic<node*> head_; spinlock lock_; public: freelist() : head_(nullptr) {} void push_v1(T d) { lock_t lock(lock_); node* n = new node{d, nullptr}; node* prev = head_.load(); n->next = prev; head_ = n; } void push_v2(T d) { node* n = new node{d, nullptr}; n->next = head_.load(); while (!head_.compare_exchange_weak(n->next, n)); } size_t size() { lock_t lock(lock_); node* n = head_.load(); size_t num = 0; while (n) { ++num; n = n->next; } return num; } }; void timeit(std::function<void()> fn, const char* tag) { using cl = high_resolution_clock; auto start = cl::now(); fn(); auto d = duration_cast<microseconds>(cl::now() - start); cout << tag << ": " << d.count() << endl; } int main() { size_t num_threads = thread::hardware_concurrency(); size_t pushes = 10000; timeit([=]() { freelist<int> f; vector<thread> threads; for (int i=0; i<num_threads; ++i) { threads.push_back(std::thread([&f, i, pushes]() { for (int j=0; j<pushes; ++j) f.push_v1(i); })); } for (auto& t : threads) t.join(); assert(f.size() == num_threads * pushes); }, "v1"); timeit([=]() { freelist<int> f; vector<thread> threads; for (int i=0; i<num_threads; ++i) { threads.push_back(std::thread([&f, i, pushes]() { for (int j=0; j<pushes; ++j) f.push_v2(i); })); } for (auto& t : threads) t.join(); assert(f.size() == num_threads * pushes); }, "v2"); }
[ "jerdmann83@gmail.com" ]
jerdmann83@gmail.com
d66f207674e2eb6b8a8e57adbfe858dba2b76b5b
c76c758fac4714ad10ab8b73881d9636c5e8302d
/CPP04/ex02/Squad.hpp
b3650fcdc7076f465bf3836ce8dbd63048d88ea5
[]
no_license
42esoulard/42_CPP
c5ff1de1bc1335e9f5b34cb9efcbff3ecf68c1bd
aa00e105ef2e9d7bc31f2276bc6751a5c4043873
refs/heads/main
2023-02-23T14:17:39.886711
2021-01-25T12:51:14
2021-01-25T12:51:14
324,603,523
0
1
null
null
null
null
UTF-8
C++
false
false
1,481
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Squad.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: esoulard <esoulard@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/29 10:23:31 by esoulard #+# #+# */ /* Updated: 2021/01/05 20:20:37 by esoulard ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef SQUAD_HPP #define SQUAD_HPP #include <iostream> #include "ISquad.hpp" #include "ISpaceMarine.hpp" typedef struct t_Unit { ISpaceMarine *cur; t_Unit *next; } Unit; class Squad : public ISquad { public: Squad(void); Squad(Squad const &src); virtual ~Squad(void); Squad & operator=(Squad const &rhs); virtual int getCount(void) const; virtual ISpaceMarine* getUnit(int) const; virtual int push(ISpaceMarine*); Unit &copyUnitList(void) const; void deleteUnitList(void); private: int _unitCount; Unit *_unitList; }; #endif
[ "estelle.slrd@gmail.com" ]
estelle.slrd@gmail.com
c368a50e9fa68d6d2da6bd7e930588b26aa3d516
f6ab96101246c8764dc16073cbea72a188a0dc1a
/contest/PTC/PTC201403/PC.cpp
1a1e1e37e1ffe109b6970e10fecea6ed27f04db6
[]
no_license
nealwu/UVa
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
10ddd83a00271b0c9c259506aa17d03075850f60
refs/heads/master
2020-09-07T18:52:19.352699
2019-05-01T09:41:55
2019-05-01T09:41:55
220,883,015
3
2
null
2019-11-11T02:14:54
2019-11-11T02:14:54
null
UTF-8
C++
false
false
841
cpp
#include <stdio.h> #include <string.h> #include <sstream> #include <iostream> #include <vector> #include <set> #include <map> using namespace std; int g[35][35], n; int used[35] = {}, flag; void dfs(int nd, int dep, int st) { if(flag || dep >= 4) return; if(dep == 3) { if(g[nd][st]) flag = 1; return; } used[nd] = 1; for(int i = 0; i < n; i++) { if(used[i] == 0 && g[nd][i]) { dfs(i, dep+1, st); } } used[nd] = 0; } int main() { while(scanf("%d", &n) == 1 && n) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { scanf("%d", &g[i][j]); } } flag = 0; for(int i = 0; i < n; i++) { memset(used, 0, sizeof(used)); dfs(i, 0, i); } puts(flag ? "yes" : "no"); } return 0; } /* 5 0 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 0 1 1 0 0 1 0 5 0 1 0 0 1 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 1 0 0 1 0 */
[ "morris821028@gmail.com" ]
morris821028@gmail.com
6d5b41782fd1d04789be379b3a464c34297a05c9
a589fafb7bd7d147fd7ca37902e3ea55118477c0
/codeforces/1279/D.cpp
a13c9767dfe2cbeeed150a8a25e7a50757dc838e
[]
no_license
fextivity/codeforces-submissions
01bd05fe868525e625b40068b8e1e99858b1c765
d7d09395a8f914aaa45f450a4c1acf4e378d6bc5
refs/heads/master
2023-02-03T17:23:10.906023
2017-11-10T14:17:00
2020-12-23T02:56:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,651
cpp
#include<bits/stdc++.h> using namespace std; // Optimization //#pragma GCC optimize("O3") #define endl '\n' // Shortcut #define int long long #define eb emplace_back #define pb push_back #define pob pop_back #define mp make_pair #define upb upper_bound #define lwb lower_bound #define fi first #define se second #define For(i, l, r) for (int i = l; i < r; i++) #define ForE(i, l, r) for (int i = l; i <= r; i++) #define Ford(i, r, l) for (int i = r; i > l; i--) #define FordE(i, r, l) for (int i = r; i >= l; i--) #define Fora(i, a) for (auto i : a) // I/O & Debug #define PrintV(a) for (int iiii = 0; iiii < a.size(); iiii++) cout << a[iiii] << ' '; #define PrintVl(a) for (int iiii = 0; iiii < a.size(); iiii++) cout << a[iiii] << endl; #define PrintA(a, n) for (int iiii = 0; iiii < n; iiii++) cout << a[iiii] << ' '; #define PrintAl(a, n) for (int iiii = 0; iiii < n; iiii++) cout << a[iiii] << endl; #define Ptest(x) return cout << x, 0; #define gl(s) getline(cin, s); #define setpre(x) fixed << setprecision(x) /* #define debug(args...){ string _sDEB = #args; replace(_sDEB.begin(), _sDEB.end(), ',', ' '); stringstream _ssDEB(_sDEB); istream_iterator<string> _itDEB(_ssDEB); DEB(_itDEB, args); } void DEB(istream_iterator<string> it) {} template<typename T, typename... Args> void DEB(istream_iterator<string> it, T a, Args... args){ cout << *it << " = " << a << endl; DEB(++it, args...); } */ // Functions //#define isvowel(a) (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') #define bend(a) a.begin(), a.end() #define rbend(a) a.rbegin(), a.rend() #define mset(a) memset(a, 0, sizeof(a)) #define mset1(a) memset(a, 1, sizeof(a)) #define msetn1(a) memset(a, -1, sizeof(a)) #define msetinf(a) memset(a, 0x3f, sizeof(a)) #define gcd __gcd #define __builtin_popcount __builtin_popcountll //mt19937 rando(chrono::steady_clock::now().time_since_epoch().count()); // Data Structure #define pque priority_queue #define mts multiset #define y0 _y0_ #define y1 _y1_ #define div divi typedef long long ll; typedef long double ld; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <ld> vld; typedef vector <string> vs; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <vi > vvi; typedef vector <vll > vvll; typedef vector <pii > vpii; typedef vector <pll > vpll; const int N = 1e6 + 5, mod = 998244353, mod1 = 998244353, mod2 = 1e9 + 9, inf = 1e9 + 7; const ll infll = 1e18 + 7; int n, ans; vi a[N], b[N]; int sza[N], szb[N]; int binpow(int x, int y){ int ans = 1; while (y){ if (y & 1) ans = (ans * x) % mod; x = (x * x) % mod; y >>= 1; } return ans; } signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; int tmp1 = binpow(n, mod - 2); ForE(i, 1, n){ cin >> sza[i]; ForE(j, 1, sza[i]){ int x; cin >> x; a[i].pb(x); b[x].pb(i); } } For(i, 1, N){ szb[i] = b[i].size(); } ForE(i, 1, n){ int tmp2 = binpow(sza[i], mod - 2); int tmp3 = (tmp1 * tmp2) % mod; ForE(j, 1, sza[i]){ int tmp4 = (szb[a[i][j - 1]] * tmp1) % mod; int tmp5 = (tmp3 * tmp4) % mod; ans = (ans + tmp5) % mod; } } cout << ans; } /* ==================================+ INPUT: | ------------------------------ | ------------------------------ | ==================================+ OUTPUT: | ------------------------------ | ------------------------------ | ==================================+ */
[ "trxbach135@gmail.com" ]
trxbach135@gmail.com
d4dcce98b7f68766ec56990b037ed08ec55eb68c
0314bb79687b29d5ca2a9c42c0b44aea864c090e
/server/cstrike/addons/amxmodx/scripting/include/amxbans/check_player.inl
11477fbe37ede4c0da02c815b8da6a5a75aba5af
[]
no_license
roulis2844sasha/half-life
19a542ce5be7006892ec3d83893a747496d6c0f6
004ae79009d40e3b608e0962028c0dbc5966a469
refs/heads/master
2021-01-10T04:26:38.684545
2015-11-24T14:44:45
2015-11-24T14:44:45
45,735,441
3
0
null
null
null
null
UTF-8
C++
false
false
7,974
inl
#if defined _check_player_included #endinput #endif #define _check_player_included #include <amxmodx> #include <amxmisc> #include <sqlx> public prebanned_check(id) { id -= 204 if(!get_user_state(id, PDATA_CONNECTED) || get_user_state(id, PDATA_BOT) || get_user_state(id, PDATA_IMMUNITY) || !get_pcvar_num(pcvar_show_prebanned)) { return PLUGIN_HANDLED } new pquery[512] formatex(pquery, 511, "SELECT COUNT(*) FROM `%s%s` WHERE ((`player_id` = '%s' AND `ban_type` = 'S') OR (`player_ip` = '%s' AND `ban_type` = 'SI')) AND `expired` = '1';", g_dbPrefix, TBL_BANS, playerData[id][playerSteamid], playerData[id][playerIp]) new data[1] data[0] = id return SQL_ThreadQuery(g_SqlX, "prebanned_check_", pquery, data, 1) } public prebanned_check_(failstate, Handle:query, const error[], errornum, const data[], size, Float:queuetime) { if(failstate) { return SQL_Error(query, error, errornum, failstate) } new id = data[0] new ban_count = SQL_ReadResult(query, 0) SQL_FreeHandle(query) if(!get_user_state(id, PDATA_CONNECTED) || ban_count < get_pcvar_num(pcvar_show_prebanned_num)) { return PLUGIN_HANDLED } for(new i = 1; i <= plnum; i++) { if(get_user_state(i, PDATA_BOT) || get_user_state(i, PDATA_HLTV) || !get_user_state(i, PDATA_CONNECTED) || i == id) { continue } if(get_user_flags(i) & ADMIN_CHAT) { ColorChat(i, RED, "%s %L", PREFIX, i, "PLAYER_BANNED_BEFORE", playerData[id][playerName], playerData[id][playerIp], playerData[id][playerSteamid], ban_count) } } return log_amx("[AMXBans] %L", LANG_SERVER, "PLAYER_BANNED_BEFORE", playerData[id][playerName], playerData[id][playerSteamid], ban_count) } public check_player(id) { id -= 203 if(is_user_disconnected(id) || get_user_state(id, PDATA_IMMUNITY)) { return PLUGIN_HANDLED } new data[1], pquery[1024] #if defined SET_NAMES_UTF8 formatex(pquery, 1023, "SELECT `bid`, `ban_created`, `ban_length`, `cs_ban_reason`, `admin_nick`, `admin_id`, `admin_ip`, `player_nick`, `player_id`, `player_ip`, `server_name`, `server_ip`, `ban_type` FROM `%s%s` WHERE ((`player_id` = '%s' AND `ban_type` = 'S') OR (`player_ip` = '%s' AND `ban_type` = 'SI')) AND `expired` = '0';", g_dbPrefix, TBL_BANS, playerData[id][playerSteamid], playerData[id][playerIp]) #else formatex(pquery, 1023, "SELECT `bid`, `ban_created`, `ban_length`, `ban_reason`, `admin_nick`, `admin_id`, `admin_ip`, `player_nick`, `player_id`, `player_ip`, `server_name`, `server_ip`, `ban_type` FROM `%s%s` WHERE ((`player_id` = '%s' AND `ban_type` = 'S') OR (`player_ip` = '%s' AND `ban_type` = 'SI')) AND `expired` = '0';", g_dbPrefix, TBL_BANS, playerData[id][playerSteamid], playerData[id][playerIp]) #endif data[0] = id return SQL_ThreadQuery(g_SqlX, "check_player_", pquery, data, 1) } public check_player_(failstate, Handle:query, const error[], errornum, const data[], size, Float:queuetime) { if(failstate) { return SQL_Error(query, error, errornum, failstate) } new id = data[0] if(!SQL_NumResults(query) || is_user_disconnected(id)) { return SQL_FreeHandle(query) } new ban_reason[128], admin_nick[100], admin_steamid[50], admin_ip[30], ban_type[4] new player_nick[50], player_steamid[50], player_ip[30], server_name[100], server_ip[30] new bid = SQL_ReadResult(query, 0) new ban_created = SQL_ReadResult(query, 1) new ban_length_int = SQL_ReadResult(query, 2) * 60 SQL_ReadResult(query, 3, ban_reason, 127) SQL_ReadResult(query, 4, admin_nick, 99) SQL_ReadResult(query, 5, admin_steamid, 49) SQL_ReadResult(query, 6, admin_ip, 29) SQL_ReadResult(query, 7, player_nick, 49) SQL_ReadResult(query, 8, player_steamid, 49) SQL_ReadResult(query, 9, player_ip, 29) SQL_ReadResult(query, 10, server_name, 99) SQL_ReadResult(query, 11, server_ip, 29) SQL_ReadResult(query, 12, ban_type, 3) SQL_FreeHandle(query) if(get_pcvar_num(pcvar_debug) >= 1) { log_amx("[AMXBans] Player Check on Connect:^nbid: %d ^nwhen: %d ^nlenght: %d ^nreason: %s ^nadmin: %s ^nadminsteamID: %s ^nPlayername %s ^nserver: %s ^nserverip: %s ^nbantype: %s",\ bid, ban_created, ban_length_int, ban_reason, admin_nick, admin_steamid, player_nick, server_name, server_ip, ban_type) } new current_time_int = get_systime(get_pcvar_num(pcvar_offset)) if((ban_length_int == 0) || (ban_created == 0) || ((ban_created + ban_length_int) > current_time_int)) { new complain_url[256] get_pcvar_string(pcvar_complainurl, complain_url, 255) client_cmd(id, "echo ^"[AMXBans] ===============================================^"") new show_activity = get_pcvar_num(pcvar_activity) if(get_user_flags(id) & get_admin_mole_access_flag() || id == 0) { show_activity = 1 } switch(show_activity) { case 1: { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_9") } case 2: { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_8", admin_nick) } case 3: { if(is_user_admin(id)) { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_8", admin_nick) } else { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_9") } } case 4: { if(is_user_admin(id)) { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_8", admin_nick) } } case 5: { if(is_user_admin(id)) { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_9") } } } if(ban_length_int == 0) { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_10") } else { new cTimeLength[128] new iSecondsLeft = (ban_created + ban_length_int - current_time_int) get_time_length(id, iSecondsLeft, timeunit_seconds, cTimeLength, 127) client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_12", cTimeLength) } replace_all(complain_url, 255, "http://", "") client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_13", player_nick) client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_2", ban_reason) client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_7", complain_url) client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_4", player_steamid) client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_5", player_ip) client_cmd(id, "echo ^"[AMXBans] ===============================================^"") if(get_pcvar_num(pcvar_debug) >= 1) { log_amx("[AMXBans] BID:<%d> Player:<%s> <%s> connected and got kicked, because of an active ban", bid, player_nick, player_steamid) } if(get_pcvar_num(pcvar_debug) >= 1) { new id_str[3] num_to_str(id, id_str, 3) log_amx("[AMXBans] Delayed Kick-TASK ID1: <%d> ID2: <%s>", id, id_str) } add_kick_to_db(bid) set_task(1.0, "delayed_kick", id + 200) return PLUGIN_HANDLED } else { client_cmd(id, "echo ^"[AMXBans] %L^"", id, "MSG_11") new pquery[256] formatex(pquery, 255, "UPDATE `%s%s` SET `expired` = '1' WHERE `bid` = '%d';", g_dbPrefix, TBL_BANS, bid) SQL_ThreadQuery(g_SqlX, "insert_to_banhistory", pquery) if(get_pcvar_num(pcvar_debug) >= 1) { log_amx("[AMXBans] PRUNE BAN: %s", pquery) } } return PLUGIN_HANDLED } public insert_to_banhistory(failstate, Handle:query, const error[], errornum, const data[], size, Float:queuetime) { if(failstate) { return SQL_Error(query, error, errornum, failstate) } return SQL_FreeHandle(query) } public add_kick_to_db(bid) { new pquery[256] formatex(pquery, 255, "UPDATE `%s%s` SET `ban_kicks` = `ban_kicks` + 1 WHERE `bid` = '%d';", g_dbPrefix, TBL_BANS, bid) return SQL_ThreadQuery(g_SqlX, "_add_kick_to_db", pquery) } public _add_kick_to_db(failstate, Handle:query, const error[], errornum, const data[], size, Float:queuetime) { if(failstate) { return SQL_Error(query, error, errornum, failstate) } return SQL_FreeHandle(query) }
[ "roulis2844sasha@gmail.com" ]
roulis2844sasha@gmail.com
017b653fa17f7737e136f275fc085d7ffcb9dbb5
48a2f1eb694e5a09f600412d828d0501e5cff57e
/src/lib/xml_compiler/include/pqrs/xml_compiler/detail/remapclasses_initialize_vector.hpp
5e8784060c5ad099f64f37894fdc9adbe4ca05e3
[]
no_license
old9/KeyRemap4MacBook
c3bb93821ec2b266ca4c239d8fd88f4aee4dcc75
6123d32fc6b56acad30cfb0afeb1bd362603cc1a
refs/heads/master
2021-01-17T22:34:10.062845
2013-01-09T03:33:23
2013-01-09T03:33:23
7,517,445
5
0
null
null
null
null
UTF-8
C++
false
false
2,277
hpp
// This header intentionally has no include guards. class remapclasses_initialize_vector { public: remapclasses_initialize_vector(void); void clear(void); const std::vector<uint32_t>& get(void) const; uint32_t get_config_count(void) const; void start(uint32_t config_index, const std::string& raw_identifier); void push_back(uint32_t v) { // increment size ++(data_[start_index_]); data_.push_back(v); } void end(void); size_t size(void) const { return data_.size(); } void update(size_t index, uint32_t v) { data_[index] = v; } void freeze(void); private: void cleanup_(void); enum { INDEX_OF_FORMAT_VERSION = 0, INDEX_OF_CONFIG_COUNT = 1, }; std::vector<uint32_t> data_; std::tr1::unordered_map<uint32_t, bool> is_config_index_added_; uint32_t max_config_index_; bool freezed_; // variables for start() and end() size_t start_index_; bool ended_; }; class remapclasses_initialize_vector_loader { public: remapclasses_initialize_vector_loader(const xml_compiler& xml_compiler, symbol_map& symbol_map, remapclasses_initialize_vector& remapclasses_initialize_vector, std::tr1::unordered_map<uint32_t, std::string>& identifier_map) : xml_compiler_(xml_compiler), symbol_map_(symbol_map), remapclasses_initialize_vector_(remapclasses_initialize_vector), identifier_map_(identifier_map), simultaneous_keycode_index_(0), filter_vector_(symbol_map) {} void traverse(const extracted_ptree& pt, const std::string& parent_tag_name); private: void traverse_autogen_(const extracted_ptree& pt, const std::string& identifier); void handle_autogen(const std::string& autogen, const std::string& raw_autogen); void add_to_initialize_vector(const std::string& params, uint32_t type) const; const xml_compiler& xml_compiler_; symbol_map& symbol_map_; remapclasses_initialize_vector& remapclasses_initialize_vector_; std::tr1::unordered_map<uint32_t, std::string>& identifier_map_; uint32_t simultaneous_keycode_index_; filter_vector filter_vector_; };
[ "tekezo@pqrs.org" ]
tekezo@pqrs.org
25ad15a7d1d4b8b569e7de2748e7156ed265ea98
3d424a8d682d4e056668b5903206ccc603f6e997
/NeoScriptTools/debugging/qscriptbreakpointdata_p.h
3389aad7d9ba45b824fc7597abd8790d551b431d
[]
no_license
markus851/NeoLoader
515e238b385354b83bbc4f7399a85524d5b03d12
67c9b642054ead500832406a9c301a7b4cbfffd3
refs/heads/master
2022-04-22T07:51:15.418184
2015-05-08T11:37:53
2015-05-08T11:37:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,112
h
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtSCriptTools module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QSCRIPTBREAKPOINTDATA_P_H #define QSCRIPTBREAKPOINTDATA_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/qobjectdefs.h> #include <QtCore/qscopedpointer.h> #include <QtCore/qmap.h> #include <QtCore/qvariant.h> QT_BEGIN_NAMESPACE class QDataStream; class QScriptBreakpointDataPrivate; class Q_AUTOTEST_EXPORT QScriptBreakpointData { public: friend Q_AUTOTEST_EXPORT QDataStream &operator<<(QDataStream &, const QScriptBreakpointData &); friend Q_AUTOTEST_EXPORT QDataStream &operator>>(QDataStream &, QScriptBreakpointData &); //> NeoScriptTools void fromVariant(const QVariantMap& in); QVariantMap toVariant() const; //< NeoScriptTools QScriptBreakpointData(); QScriptBreakpointData(qint64 scriptId, int lineNumber); QScriptBreakpointData(const QString &fileName, int lineNumber); QScriptBreakpointData(const QScriptBreakpointData &other); ~QScriptBreakpointData(); QScriptBreakpointData &operator=(const QScriptBreakpointData &other); bool isValid() const; // location qint64 scriptId() const; void setScriptId(qint64 id); QString fileName() const; void setFileName(const QString &fileName); int lineNumber() const; void setLineNumber(int lineNumber); // data bool isEnabled() const; void setEnabled(bool enabled); bool isSingleShot() const; void setSingleShot(bool singleShot); int ignoreCount() const; void setIgnoreCount(int count); QString condition() const; void setCondition(const QString &condition); QVariant data() const; void setData(const QVariant &data); bool hit(); // statistics int hitCount() const; bool operator==(const QScriptBreakpointData &other) const; bool operator!=(const QScriptBreakpointData &other) const; private: QScopedPointer<QScriptBreakpointDataPrivate> d_ptr; Q_DECLARE_PRIVATE(QScriptBreakpointData) }; typedef QMap<int, QScriptBreakpointData> QScriptBreakpointMap; Q_AUTOTEST_EXPORT QDataStream &operator<<(QDataStream &, const QScriptBreakpointData &); Q_AUTOTEST_EXPORT QDataStream &operator>>(QDataStream &, QScriptBreakpointData &); QT_END_NAMESPACE #endif
[ "David@X.com" ]
David@X.com
867ab3ceb0f4bf3c35f82d6a3748039c9b758556
74f84fb04f641f352b482b32696a6536b0b43b33
/FiniteElementAnalysis/toolpath_RibMould.cpp
cf46ba0c34897e6eafd8f9cf9c9194e4d45f0f06
[]
no_license
RMAReader/FiniteElementAnalysis
23333ee76f05c699f7406e3bd89df383a844abad
1e4d24b33e77d0162d6a85a8ba987881398ec216
refs/heads/master
2020-02-26T15:03:52.550866
2017-05-29T20:34:25
2017-05-29T20:34:25
83,332,823
0
1
null
null
null
null
UTF-8
C++
false
false
7,150
cpp
#include "toolpath_base.h" void toolpath_RibMould::calculate() { //zero z is set to top of rib mould base float safe_z = parameters["safe_z"]; float mould_top_z = parameters["mould_top_z"]; float mould_bottom_z = parameters["mould_bottom_z"]; float step_z = parameters["step_z"]; //bore location holes for (int i = 0; i < violin->ribs.rib_mould_locator_holes.size(); i++) { geoVEC2F c; c[0] = violin->ribs.rib_mould_locator_holes[i].centre[0]; c[1] = violin->ribs.rib_mould_locator_holes[i].centre[1]; float d = violin->ribs.rib_mould_locator_holes[i].radius*2; bore_hole(c, d, safe_z, mould_top_z, mould_bottom_z, step_z); } float resolution = 1.0; //cut out central clamping hole std::vector<geoVEC3F> clamp_hole_layer; std::unordered_map<std::string, geoCURVE2F>& c = violin->ribs.curves; cut_curve_const_z(&clamp_hole_layer, tool->diameter, c["clamp_hole"], 0, c["clamp_hole"].minParam(), c["clamp_hole"].maxParam(), resolution); points.push_back(geoVEC3F(std::array < float, 3 > {{clamp_hole_layer[0][0], clamp_hole_layer[0][1], safe_z}})); float z = mould_top_z; while (z > mould_bottom_z) { z -= step_z; if (z < mould_bottom_z){ z = mould_bottom_z; } for (int i = 0; i < clamp_hole_layer.size(); i++){ points.push_back(geoVEC3F(std::array < float, 3 > {{clamp_hole_layer[i][0], clamp_hole_layer[i][1], z}})); } } int n = clamp_hole_layer.size() - 1; points.push_back(geoVEC3F(std::array < float, 3 > {{clamp_hole_layer[n][0], clamp_hole_layer[n][1], safe_z}})); //cut outline - clockwise from lower bout treble corner float error = 1E-4; //lower bout bool intersect1, intersect2, intersect3, intersect4, intersect5, intersect6; bool intersect7, intersect8, intersect9, intersect10, intersect11, intersect12; geoVEC2D param1, param2, param3, param4; intersect1 = IntersectParam(c["rib_internal_lower_bout"], c["block_trbl_lower_bout"], error, param1, false); intersect2 = IntersectParam(c["rib_internal_lower_bout"], c["centre_line"], error, param2, false); intersect4 = IntersectParam(c["rib_internal_lower_bout"], c["block_bass_lower_bout"], error, param4, false); if (intersect1 && intersect2 && intersect4){ geoCURVE2F rib_lower_trbl = c["rib_internal_lower_bout"]; rib_lower_trbl.trim_curve(param1[0], param2[0]); geoCURVE2F rib_lower_bass = c["rib_internal_lower_bout"]; rib_lower_bass.trim_curve(param2[0], param4[0]); intersect2 = IntersectParam(rib_lower_trbl, c["block_bottom"], error, param2, false); intersect3 = IntersectParam(rib_lower_bass, c["block_bottom"], error, param3, false); } //centre bout bass geoVEC2D param5, param6; intersect5 = IntersectParam(c["rib_internal_centre_bout_bass"], c["block_bass_lower_bout"], error, param5, false); intersect6 = IntersectParam(c["rib_internal_centre_bout_bass"], c["block_bass_upper_bout"], error, param6, false); //upper bout geoVEC2D param7, param8, param9, param10; intersect7 = IntersectParam(c["rib_internal_upper_bout"], c["block_bass_upper_bout"], error, param7, false); intersect8 = IntersectParam(c["rib_internal_upper_bout"], c["centre_line"], error, param8, false); intersect10 = IntersectParam(c["rib_internal_upper_bout"], c["block_trbl_upper_bout"], error, param10, false); if (intersect7 && intersect8 && intersect10){ geoCURVE2F rib_upper_bass = c["rib_internal_upper_bout"]; rib_upper_bass.trim_curve(param7[0], param8[0]); geoCURVE2F rib_upper_trbl = c["rib_internal_upper_bout"]; rib_upper_trbl.trim_curve(param8[0], param10[0]); intersect8 = IntersectParam(rib_upper_bass, c["block_neck"], error, param8, false); intersect9 = IntersectParam(rib_upper_trbl, c["block_neck"], error, param9, false); } //centre bout treble geoVEC2D param11, param12; intersect11 = IntersectParam(c["rib_internal_centre_bout_trbl"], c["block_trbl_upper_bout"], error, param11, false); intersect12 = IntersectParam(c["rib_internal_centre_bout_trbl"], c["block_trbl_lower_bout"], error, param12, false); if (intersect1 && intersect2 && intersect3 && intersect4 && intersect5 && intersect6 && intersect7 && intersect8 && intersect9 && intersect10 && intersect11 && intersect12) { std::vector<geoVEC3F> layer1, layer2, layer3, layer4, layer5, layer6, layer7, layer8, layer9, layer10, layer11, layer12; cut_curve_const_z(&layer1, 0, c["rib_internal_lower_bout"], 0, param1[0], param2[0], resolution); cut_polyline_const_z(&layer2, c["block_bottom"], 0, param2[1], param3[1]); cut_curve_const_z(&layer3, 0, c["rib_internal_lower_bout"], 0, param3[0], param4[0], resolution); cut_polyline_const_z(&layer4, c["block_bass_lower_bout"], 0, param4[1], param5[1]); cut_curve_const_z(&layer5, 0, c["rib_internal_centre_bout_bass"], 0, param5[0], param6[0], resolution); cut_polyline_const_z(&layer6, c["block_bass_upper_bout"], 0, param6[1], param7[1]); cut_curve_const_z(&layer7, 0, c["rib_internal_upper_bout"], 0, param7[0], param8[0], resolution); cut_polyline_const_z(&layer8, c["block_neck"], 0, param8[1], param9[1]); cut_curve_const_z(&layer9, 0, c["rib_internal_upper_bout"], 0, param9[0], param10[0], resolution); cut_polyline_const_z(&layer10, c["block_trbl_upper_bout"], 0, param10[1], param11[1]); cut_curve_const_z(&layer11, 0, c["rib_internal_centre_bout_trbl"], 0, param11[0], param12[0], resolution); cut_polyline_const_z(&layer12, c["block_trbl_lower_bout"], 0, param12[1], param1[1]); //rib outlines bool deep_corners = false; offset_curve(&layer1, tool->diameter, deep_corners); offset_curve(&layer3, tool->diameter, deep_corners); offset_curve(&layer5, tool->diameter, deep_corners); offset_curve(&layer7, tool->diameter, deep_corners); offset_curve(&layer9, tool->diameter, deep_corners); offset_curve(&layer11, tool->diameter, deep_corners); //block pockets deep_corners = true; offset_curve(&layer2, tool->diameter, deep_corners); offset_curve(&layer4, tool->diameter, deep_corners); offset_curve(&layer6, tool->diameter, deep_corners); offset_curve(&layer8, tool->diameter, deep_corners); offset_curve(&layer10, tool->diameter, deep_corners); offset_curve(&layer12, tool->diameter, deep_corners); std::vector<geoVEC3F> layer; join_curves_external(layer, layer1); join_curves_external(layer, layer2); join_curves_external(layer, layer3); join_curves_external(layer, layer4); join_curves_external(layer, layer5); join_curves_external(layer, layer6); join_curves_external(layer, layer7); join_curves_external(layer, layer8); join_curves_external(layer, layer9); join_curves_external(layer, layer10); join_curves_external(layer, layer11); join_curves_external(layer, layer12); close_curve_external(layer); points.push_back(geoVEC3F(std::array < float, 3 > {{layer.front()[0], layer.front()[1], safe_z}})); z = mould_top_z; while (z > mould_bottom_z) { z -= step_z; if (z < mould_bottom_z){ z = mould_bottom_z; } for (int i = 0; i < layer.size(); i++){ points.push_back(geoVEC3F(std::array < float, 3 > {{layer[i][0], layer[i][1], z}})); } } points.push_back(geoVEC3F(std::array < float, 3 > {{layer.back()[0], layer.back()[1], safe_z}})); } }
[ "richardreader@hotmail.co.uk" ]
richardreader@hotmail.co.uk
160546704fe581e972410a4883b844a22e99bdac
934a5b1535ca9bc6641658ae371026834d841e03
/src/qt/castvotesdialog.h
5f98a807693ed0f47241ae2f9bdb344c68207951
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
OckhamConsulting/smartcore
dde083000e0087729e4d0412a2037aaec97812ff
b95d8ce9f76988fe0146994ac8c040937ea54ac9
refs/heads/master
2020-04-24T10:06:49.834919
2019-02-05T19:44:58
2019-02-05T19:44:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,510
h
// Copyright (c) 2018 - The SmartCash Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SMARTCASH_QT_CASTVOTESDIALOG_H #define SMARTCASH_QT_CASTVOTESDIALOG_H #include <QAbstractButton> #include <QAction> #include <QDialog> #include <QList> #include <QMenu> #include <QPoint> #include <QString> #include <QTableWidgetItem> #include "primitives/transaction.h" #include "smartvoting/proposal.h" #include "smartvoting/proposal.h" #include "smartproposal.h" class PlatformStyle; namespace Ui { class CastVotesDialog; } class CastVotesDialog : public QDialog { Q_OBJECT public: explicit CastVotesDialog(const PlatformStyle *platformStyle, WalletModel *model, const std::map<uint256, std::pair<vote_signal_enum_t, vote_outcome_enum_t>> &mapVotings, QWidget *parent = 0); ~CastVotesDialog(); private: Ui::CastVotesDialog *ui; const PlatformStyle *platformStyle; WalletModel *walletModel; std::map<uint256, std::pair<vote_signal_enum_t, vote_outcome_enum_t>> mapVotings; bool castVote(const CVoteKeySecret &voteKeySecret, const uint256 &hash, const vote_signal_enum_t eVoteSignal, const vote_outcome_enum_t eVoteOutcome, QString &strError); public Q_SLOTS: int exec() final; private Q_SLOTS: void start(); void close(); }; #endif // SMARTCASH_QT_CASTVOTESDIALOG_H
[ "xdustinfacex@gmail.com" ]
xdustinfacex@gmail.com
6d64bf1bf978d439297393a3f375f023062a19c1
8eb917afb460041b0d068eca3f17b3845122c73b
/graph.h
d84ed51ff09adcd3b31219ccfac6202031dd2905
[]
no_license
Bananalove/dijkstra
5275a20f453596016c1fae98afc5d111ebd279bf
2272b5fb530078cac77ceeea488c50b81ba6444e
refs/heads/master
2021-01-13T00:56:56.583170
2015-05-20T23:44:49
2015-05-20T23:44:49
35,968,533
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
8,565
h
#ifndef GRAPH_H #define GRAPH_H #include <list> #include <tuple>// w tym moze byc wiecej niz 4 elementy, ale jest ok :) #include <utility> #include <queue> #include <iostream> #include <string> #include <exception> #include <memory> #include <vector> #include <limits> #include <algorithm> //min_elem //#include "compare.h" bool operator==(std::tuple<int, int, int>& elem1, int elem2); bool operator==(int elem2, std::tuple<int, int, int>& elem1); namespace constants { const int no_edge = -1; const char no_elem = '.'; const int no_v = -1; const int infinit = std::numeric_limits<int>::max(); //const double infinit = std::numeric_limits<double>::infinity(); } /* * Funktor do sortowania kolejki krotkow - wyznaczenie najmniejszego z elementow */ class Compare_tuples { public: bool operator() (std::tuple<int, int, int>& tp1, std::tuple<int, int, int>& tp2) { return std::get<2>(tp1) > std::get<2>(tp2); } }; class Compare_tuples_cost { public: bool operator() (std::tuple<int, int>& tp1, std::tuple<int, int>& tp2) { return std::get<1>(tp1) > std::get<1>(tp2); } }; /* klasa wyjątkowa */ class Directed { std::string error; public: Directed (std::string err = "Wystapil blad\n") : error(err) { } std::string what() const { return error; } }; bool find_i(const std::vector<std::tuple<int, int, int> >& vec, int i); class Graph { int numE; int numV; int Vstart; int Vend; std::list < std::tuple<int, int, int> > edge_list; int** adj_matrix; std::list<std::tuple<int, int> >* neigh_list; bool directed; // pole decyduje, czy klasa moze wykonywac algorytm Prima lub Kruskala std::list <std::tuple<int, int, int> > mst; // minimal spinning tree //std::shared_ptr<std::vector <std::tuple<int, int, int> > > mst_ptr; public: Graph(int nE = 0, int nV = 0, int Vs = 0, int Ve = 0, bool dir = false) : numE(nE), numV(nV), Vstart(Vs), Vend(Ve), adj_matrix(nullptr), neigh_list(nullptr), directed(dir) {} ~Graph() { delete_adj_matrix(); delete_neigh_list(); } /********************************** access to basic values ***************************************/ void change_set(int nE, int nV, int Vs, int Ve); void Graph::change_directed(bool dir); int show_numE() const { return numE; } int show_numV() const { return numV; } int show_Vstart() const { return Vstart; } int show_Vend() const { return Vend; } void add_edge(int vert1, int vert2, int edge_l); // should add numE or add next variable ? int find_egde_edge_list(int v1, int v2) { for (auto iter = edge_list.begin(), stop = edge_list.end(); iter != stop; ++iter) { if (std::get<0>(*iter) == v1 && std::get<1>(*iter) == v2) { return std::get<2>(*iter); } } return constants::no_edge; } /******************************************** neighbourhood list ****************************************/ void make_neigh_list(); void fill_neigh_list(); void delete_neigh_list(); int find_edge_list(int v1, int v2); std::ostream& print_neigh_list(std::ostream& out) const; /**************************************** Generowanie grafow ********************************************/ void fill_full(); void fill( double level); void spanning_tree(); /**************************************** Algorytm Dijkstry *******************************************/ void Dij_alg_matrix() { std::vector<bool> counted(numV, false); std::vector<bool> uncounted(numV, true); // if true - present std::vector<int> cost(numV, constants::infinit); std::vector<int> previous(numV, constants::no_v); std::priority_queue<std::tuple<int, int>, std::vector<std::tuple<int, int>>, Compare_tuples_cost> cost_q; // index, cost cost[Vstart] = 0; cost_q.push(std::make_tuple(Vstart,cost[Vstart])); for (int k = 0; k < numV ; ++k) { auto closest = cost_q.top(); cost_q.pop(); auto closest_ind = std::get<0>(closest); auto closest_cost = std::get<1>(closest); counted[closest_ind] = true; uncounted[closest_ind] = false; for (int i = 0; i < numV; ++i) { if (adj_matrix[closest_ind][i] != constants::no_edge) { if (uncounted[i] == true) // if present in uncounted { if (cost[i] > cost[closest_ind] + adj_matrix[closest_ind][i]) { cost[i] = cost[closest_ind] + adj_matrix[closest_ind][i]; cost_q.push(std::make_tuple(i, cost[i])); previous[i] = closest_ind; } } } } } std::cout << "Wektor indeksow "; // warto posortowac? for (auto iter : counted) { std::cout << iter << " "; } std::cout << "Wektor kosztow "; for (auto iter : cost) { std::cout << iter << " "; } std::cout << "\n"; std::cout << "Wektor poprzednikow "; for (auto iter : previous) { std::cout << iter << " "; } std::cout << "\n"; } /*void Dij_alg_matrix() { std::vector<int> counted; std::vector<int> uncounted(numV, 0); std::cout << "Tutaj jestem!\n"; std::vector<int> cost(numV, constants::infinit); std::vector<int> previous(numV, constants::no_v); std::vector<std::tuple<int, int, int>> uncount_v(numV); std::vector<std::tuple<int, int, int>> count_v; { int fill = 0; for (auto iter = uncount_v.begin(), stop = uncount_v.end(); iter != stop; ++iter, ++fill) { *iter = std::make_tuple(fill, constants::infinit, constants::no_v); } }*/ /* for (int i = 0; i < numV; ++i) { uncount_v[i] = i; } for (auto iter : uncounted) { std::cout << iter << " "; }*/ //std::get<1>(uncount_v[Vstart]) = 0; //cost[Vstart] = 0; //std::cout << "Tutaj jeszcze jest ok!\n"; /* for (auto iter = uncounted.begin(), stop = uncounted.end(); iter != stop; ++iter) { *iter = } */ /*while (!uncounted.empty()) { // *std::min_element(cost.begin(), cost.end()); //iterator auto minim = std::min_element(uncount_v.begin(), uncount_v.end(), Compare_tuples_cost()); auto added = *minim; std::cout << "added " << std::get<1>(added) << "\n"; count_v.push_back(added); //uncounted.erase(minim); //std::swap(uncounted[added], uncounted[uncounted.size()-1]); std::swap(added, uncount_v.back()); uncount_v.pop_back(); std::cout << "Tutaj jeszcze jest ok!\n"; // counted.back(); for (int i = 0; i < numV; ++i) { if (adj_matrix[std::get<0>(added)][i] != constants::no_edge) { std::cout << "Tutaj jeszcze jest ok!\n"; //if (std::find(uncount_v.begin(), uncount_v.end(), i) != uncount_v.end()) if (find_i(uncount_v, i) ) { std::cout << "Tutaj jeszcze jest ok!\n"; if (std::get<1>(uncount_v[i]) > std::get<1>(added) + adj_matrix[std::get<0>(added)][i]) { std::cout << "Tutaj jeszcze jest ok!\n"; //std::cout << "i " << i << "\n"; //std::cout << "matrix " << adj_matrix[added][i] << "\n"; //std::cout << "cost " << cost[i] << "\n"; //std::cout << "cost added " << cost[added] << "\n"; std::get<1>(uncount_v[i]) = std::get<1>(added) +adj_matrix[std::get<0>(added)][i]; std::cout << "Tutaj jeszcze jest ok!\n"; //cost[i] = cost[added] + adj_matrix[added][i]; // std::cout << "cost po zmianie " << cost[i] << "\n"; std::get<2>(uncount_v[i]) = std::get<2>(added); std::cout << "Tutaj jeszcze jest ok!\n"; } } } } }*/ /* std::cout << "Wektor indeksow "; // warto posortowac? for (auto iter : count_v) { std::cout << std::get<0>(iter) << " "; } std::cout << "Wektor kosztow "; for (auto iter : count_v) { std::cout << std::get<1>(iter) << " "; } std::cout << "\n"; std::cout << "Wektor poprzednikow "; for (auto iter : count_v) { std::cout << std::get<2>(iter) << " "; } std::cout << "\n";*/ //} /**************************************** Algorytm Prima *********************************************/ void Prim_alg_list(); void Prim_alg_matrix(); /**************************************** Algorytm Kruskala ******************************************/ void Kruskal_alg_matrix(); void Kruskal_alg_list(); std::ostream& print_mst(std::ostream& out) const; int min_span_tree_weight(); /*************************************** Adjacency matrix ********************************************/ void make_adj_matrix(); void fill_adj_matrix(); int find_edge_matrix(int v1, int v2); std::ostream& print_adj_matrix(std::ostream& out) const; void delete_adj_matrix(); friend std::ostream& operator<< (std::ostream& out, Graph graph); }; #endif
[ "alicja.majewska94@o2.pl" ]
alicja.majewska94@o2.pl
4f26744c3ed59ac98c321c6a43324885c63c65ab
3e79056f6c3ab04fd84806737c324a16562870c2
/baekjoon/previous/1926/main.cpp
d522a58ecf9d8b5772bb3895323145f20febb83a
[]
no_license
seunghyukcho/algorithm-problems-solved
ce52f11a12b532c51547fd215e53e1f60915f52a
04e78a4b41a8b13c1d00e231dd79114fb8360c9a
refs/heads/master
2023-07-14T11:37:33.763943
2021-08-20T15:09:50
2021-08-20T15:09:50
125,701,552
6
0
null
null
null
null
UTF-8
C++
false
false
1,459
cpp
#include<iostream> #include<vector> #include<queue> using namespace std; int main(){ int n, m; int painting = 0; int ans = 0; cin >> n >> m; vector<vector<int> > map(n, vector<int>(m, 0)); int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) cin >> map[i][j]; } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map[i][j]){ queue<pair<int, int> > q; int size = 0; q.push({i, j}); painting++; map[i][j] = 0; while(!q.empty()){ int x = q.front().first; int y = q.front().second; size++; q.pop(); for(int k = 0; k < 4; k++){ int newx = x + dir[k][0]; int newy = y + dir[k][1]; if(newx < 0 || newy < 0 || newx >= n || newy >= m || !map[newx][newy]) continue; q.push({newx, newy}); map[newx][newy] = 0; } } ans = ans > size ? ans : size; } } } cout << painting << '\n' << ans << '\n'; return 0; }
[ "choseunghyek@gmail.com" ]
choseunghyek@gmail.com
e3d43e7bc9a9c2dfd65ab7d597a024b9be8c2cc2
3478ccef99c85458a9043a1040bc91e6817cc136
/HFrame/HModule/audio_basics/utilities/IIRFilter.h
8ccfe1a010d8effefbc1f8cbc3848654c5315e19
[]
no_license
gybing/Hackett
a1183dada6eff28736ebab52397c282809be0e7b
f2b47d8cc3d8fa9f0d9cd9aa71b707c2a01b8a50
refs/heads/master
2020-07-25T22:58:59.712615
2019-07-09T09:40:00
2019-07-09T09:40:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,132
h
class IIRFilter; //============================================================================== /** A set of coefficients for use in an IIRFilter object. @see IIRFilter @tags{Audio} */ class API IIRCoefficients { public: //============================================================================== /** Creates a null set of coefficients (which will produce silence). */ IIRCoefficients() noexcept; /** Directly constructs an object from the raw coefficients. Most people will want to use the static methods instead of this, but the constructor is public to allow tinkerers to create their own custom filters! */ IIRCoefficients (double c1, double c2, double c3, double c4, double c5, double c6) noexcept; /** Creates a copy of another filter. */ IIRCoefficients (const IIRCoefficients&) noexcept; /** Creates a copy of another filter. */ IIRCoefficients& operator= (const IIRCoefficients&) noexcept; /** Destructor. */ ~IIRCoefficients() noexcept; //============================================================================== /** Returns the coefficients for a low-pass filter. */ static IIRCoefficients makeLowPass (double sampleRate, double frequency) noexcept; /** Returns the coefficients for a low-pass filter with variable Q. */ static IIRCoefficients makeLowPass (double sampleRate, double frequency, double Q) noexcept; //============================================================================== /** Returns the coefficients for a high-pass filter. */ static IIRCoefficients makeHighPass (double sampleRate, double frequency) noexcept; /** Returns the coefficients for a high-pass filter with variable Q. */ static IIRCoefficients makeHighPass (double sampleRate, double frequency, double Q) noexcept; //============================================================================== /** Returns the coefficients for a band-pass filter. */ static IIRCoefficients makeBandPass (double sampleRate, double frequency) noexcept; /** Returns the coefficients for a band-pass filter with variable Q. */ static IIRCoefficients makeBandPass (double sampleRate, double frequency, double Q) noexcept; //============================================================================== /** Returns the coefficients for a notch filter. */ static IIRCoefficients makeNotchFilter (double sampleRate, double frequency) noexcept; /** Returns the coefficients for a notch filter with variable Q. */ static IIRCoefficients makeNotchFilter (double sampleRate, double frequency, double Q) noexcept; //============================================================================== /** Returns the coefficients for an all-pass filter. */ static IIRCoefficients makeAllPass (double sampleRate, double frequency) noexcept; /** Returns the coefficients for an all-pass filter with variable Q. */ static IIRCoefficients makeAllPass (double sampleRate, double frequency, double Q) noexcept; //============================================================================== /** Returns the coefficients for a low-pass shelf filter with variable Q and gain. The gain is a scale factor that the low frequencies are multiplied by, so values greater than 1.0 will boost the low frequencies, values less than 1.0 will attenuate them. */ static IIRCoefficients makeLowShelf (double sampleRate, double cutOffFrequency, double Q, float gainFactor) noexcept; /** Returns the coefficients for a high-pass shelf filter with variable Q and gain. The gain is a scale factor that the high frequencies are multiplied by, so values greater than 1.0 will boost the high frequencies, values less than 1.0 will attenuate them. */ static IIRCoefficients makeHighShelf (double sampleRate, double cutOffFrequency, double Q, float gainFactor) noexcept; /** Returns the coefficients for a peak filter centred around a given frequency, with a variable Q and gain. The gain is a scale factor that the centre frequencies are multiplied by, so values greater than 1.0 will boost the centre frequencies, values less than 1.0 will attenuate them. */ static IIRCoefficients makePeakFilter (double sampleRate, double centreFrequency, double Q, float gainFactor) noexcept; //============================================================================== /** The raw coefficients. You should leave these numbers alone unless you really know what you're doing. */ float coefficients[5]; }; //============================================================================== /** An IIR filter that can perform low, high, or band-pass filtering on an audio signal. @see IIRCoefficient, IIRFilterAudioSource @tags{Audio} */ class API IIRFilter { public: //============================================================================== /** Creates a filter. Initially the filter is inactive, so will have no effect on samples that you process with it. Use the setCoefficients() method to turn it into the type of filter needed. */ IIRFilter() noexcept; /** Creates a copy of another filter. */ IIRFilter (const IIRFilter&) noexcept; /** Destructor. */ ~IIRFilter() noexcept; //============================================================================== /** Clears the filter so that any incoming data passes through unchanged. */ void makeInactive() noexcept; /** Applies a set of coefficients to this filter. */ void setCoefficients (const IIRCoefficients& newCoefficients) noexcept; /** Returns the coefficients that this filter is using. */ IIRCoefficients getCoefficients() const noexcept { return coefficients; } //============================================================================== /** Resets the filter's processing pipeline, ready to start a new stream of data. Note that this clears the processing state, but the type of filter and its coefficients aren't changed. To put a filter into an inactive state, use the makeInactive() method. */ void reset() noexcept; /** Performs the filter operation on the given set of samples. */ void processSamples (float* samples, int numSamples) noexcept; /** Processes a single sample, without any locking or checking. Use this if you need fast processing of a single value, but be aware that this isn't thread-safe in the way that processSamples() is. */ float processSingleSampleRaw (float sample) noexcept; protected: //============================================================================== SpinLock processLock; IIRCoefficients coefficients; float v1 = 0, v2 = 0; bool active = false; // The exact meaning of an assignment operator would be ambiguous since the filters are // stateful. If you want to copy the coefficients, then just use setCoefficients(). IIRFilter& operator= (const IIRFilter&) = delete; HLEAK_DETECTOR (IIRFilter) };
[ "23925493@qq.com" ]
23925493@qq.com
ec68f540f564485c77fb255706ed28c0da57b912
545c33b959ad8e7985ed2bf879e41004433929d8
/capture.cc
c7496ed0f37ddaf1d75b159872eb68263cac68fe
[]
no_license
simmonmt/pixy-motion
9e559f47da789b4f16496409f3b34129eb24087d
bc5e0f8c57234d8b244328b65cb117b5290516d7
refs/heads/master
2021-01-05T08:59:26.907359
2017-08-06T22:21:41
2017-08-06T22:21:41
99,516,007
0
0
null
null
null
null
UTF-8
C++
false
false
2,921
cc
// example of using libpixyusb to grab a 1280x40 block (maximum camera // resolution) #include <fcntl.h> #include <iostream> #include <mach/clock.h> #include <mach/mach.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include "opencv2/core/mat.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "pixy.h" void current_utc_time(struct timespec *ts) { clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; } int main(int argc, char *argv[]) { int pixy_init_status; // Connect to Pixy // pixy_init_status = pixy_init(); printf("initialized Pixy - %d\n", pixy_init_status); if (pixy_init_status != 0) { pixy_error(pixy_init_status); return pixy_init_status; } unsigned char current_frame[72000]; // ~largest possible unsigned char *pixels; // returned pointer to video frame buffer int32_t response, fourcc; int8_t renderflags; int return_value, res; uint16_t width, height; uint32_t numPixels; // stop blob processing return_value = pixy_command("stop", END_OUT_ARGS, &response, END_IN_ARGS); printf("STOP returned %d response %d\n", return_value, response); struct timespec start; current_utc_time(&start); response = 0; return_value = pixy_command("cam_getFrame", // String id for remote procedure 0x01, 0x21, // 0x02, 0, // xoffset 0x02, 0, // yoffset 0x02, 320, // width 0x02, 200, // height 0, // separator &response, // pointer to mem address for return value &fourcc, // contrary to docs, the next 5 args are needed &renderflags, &width, &height, &numPixels, &pixels, // pointer to mem address for returned frame 0); struct timespec end; current_utc_time(&end); printf("getFrame returned %d response %d\n", return_value, response); printf("returned w %d h %d npix %d\n", width, height, numPixels); printf("took %f ms\n", static_cast<double>(end.tv_nsec - start.tv_nsec) / 1000000); // quit now if not successful: if (return_value != 0) { fprintf(stderr, "pixy_command returned %d; exiting\n", return_value); exit(1); } cv::Mat bayer_image = cv::Mat(200, 320, CV_8UC1, pixels).clone(); cv::Mat rgb_image; cv::cvtColor(bayer_image, rgb_image, CV_BayerBG2RGB); cv::namedWindow("Display window", CV_WINDOW_AUTOSIZE); cv::imshow("Display window", rgb_image); printf("waiting...\n"); cv::waitKey(0); }
[ "simmonmt@acm.org" ]
simmonmt@acm.org
af0d7543d29736faa843a94b7f40e531f251757a
a552fa3577a2ae8d827e2f6b5630043bf859c841
/Prog2/elvis/CppBolt/kassza.cpp
afc01ce211ef8e0613d713b16d2cbd91c1825a23
[]
no_license
Kabor42/Suli
bb29f62a4c83e170fd714dbd34b72f5dbdf533d8
23380db29f41cb2eeaa56c3b2780c525e634bbdb
refs/heads/master
2021-10-16T00:40:10.049586
2019-02-07T15:08:41
2019-02-07T15:08:41
106,914,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,329
cpp
/** * \file kassza.cpp * * Kassza osztály tagfüggvényeinek megvalósítása (definíciója) */ #include <iostream> #include <iomanip> #include "memtrace.h" #include "kassza.h" using std::setw; /// Eladás. /// @param mennyi - eladott mennyiség /// @param mit - referencia az eladott árura (Kompatibilitás kihasználása) /// @param mikor - eladás dátuma /// @return kivételt dob, ha nem fér be void Kassza::elad(double mennyi, const Aru& mit, const Datum& mikor) { tetelek[db++] = Tetel(mennyi, &mit, mikor); } /// Kassza tartalmának kilistázása /// @param os - output stream void Kassza::list(std::ostream& os) const { for (size_t i = 0; i < db; i++) { os << tetelek[i].datum << ": " << setw(4) << tetelek[i].mennyiseg * tetelek[i].aru->getAr() << "Ft" << " -- " << tetelek[i].mennyiseg << " " << tetelek[i].aru->getEgys() << " " << *tetelek[i].aru << std::endl; } } /// Eladások listázása egy adott napon /// @param os - output stream /// @param mikor - melyik nap void Kassza::list(std::ostream& os, const Datum& mikor) const { } /// Eladások összege egy adott napra /// @param mikor - melyik nap /// @return - összeg double Kassza::napiOsszeg(const Datum& mikor) { return 0; }
[ "n.dominik@zoho.com" ]
n.dominik@zoho.com
6ca7cdbdd86696290021ea388f544bda604376c6
945c5035949b008fa81461b352456101978c8519
/programmers/level2/12909.cpp
fed111cad1d8b2de1f7f0ea02850013b2a336509
[]
no_license
leehayeong/Algorithm
816daffbb0c0e0587d57c29c271f3bc92822bcd3
442bce796459e4e2f33a0d500ee1c02a15f7bca4
refs/heads/master
2020-07-31T05:28:54.733205
2020-05-16T15:32:14
2020-05-16T15:32:14
205,650,927
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
#include<string> #include <iostream> #include <stack> using namespace std; // 올바른 괄호 bool solution(string s) { bool answer = true; int length = s.length(); stack<char> st; for (int i = 0; i < length; i++) { if (s[i] == '(') { st.push(s[i]); } else { if (st.empty()) { answer = false; break; } st.pop(); } } if (!st.empty()) answer = false; return answer; }
[ "lhaayyy@naver.com" ]
lhaayyy@naver.com
f89b0357fe6c663ed7f20274af2f2c5157ca440d
c350494e6f0ee0c5ad492692c57d9212509eaa1e
/src/lib/filters/aead_filt.h
c86739fc8460c4940c7bf7192ff11cf91e5d5bef
[ "BSD-2-Clause" ]
permissive
FollowMyVote/botan
82539d086f5b569e3da9f25451e834f2b17b5faf
ab2842d6f28680b1cac18d5ff6b70b395d1ffb65
refs/heads/master
2021-01-12T18:06:36.669369
2016-10-02T18:14:44
2016-10-02T18:14:44
69,909,772
1
1
null
2016-10-03T20:49:23
2016-10-03T20:49:23
null
UTF-8
C++
false
false
905
h
/* * Filter interface for AEAD Modes * (C) 2013 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #ifndef BOTAN_AEAD_FILTER_H__ #define BOTAN_AEAD_FILTER_H__ #include <botan/cipher_filter.h> #include <botan/aead.h> namespace Botan { /** * Filter interface for AEAD Modes */ class AEAD_Filter : public Cipher_Mode_Filter { public: AEAD_Filter(AEAD_Mode* aead) : Cipher_Mode_Filter(aead) {} /** * Set associated data that is not included in the ciphertext but * that should be authenticated. Must be called after set_key * and before end_msg. * * @param ad the associated data * @param ad_len length of add in bytes */ void set_associated_data(const byte ad[], size_t ad_len) { dynamic_cast<AEAD_Mode&>(get_transform()).set_associated_data(ad, ad_len); } }; } #endif
[ "lloyd@randombit.net" ]
lloyd@randombit.net
bdc6f1a71b347068013bcef44127c6bed591fe16
e697022772b1464775893c8f24295844df77e371
/myNodes.cpp
b998fc4df56953788905a7cbeff74f436f891b68
[]
no_license
BoningLiang/COMP-6360-project-3-spring-2017
2f98f7e79d64d5fc232f7814092fa1096c7921ec
d17fe21e142eef4f1f99543f92d427ef70a23dff
refs/heads/master
2021-01-20T06:17:44.077691
2017-05-01T00:44:21
2017-05-01T00:44:21
89,861,220
0
0
null
null
null
null
UTF-8
C++
false
false
4,750
cpp
#include <stdlib.h> #include <cstdlib> #include <iostream> #include <vector> #include <string> #include <string.h> #include <fstream> #include <sstream> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <ctime> #include <math.h> #include "config.h" using namespace std; #define TIME 10000 typedef struct{ int nodeNum; string IP; int port; int x; int y; vector <int> links; } node; typedef struct{ string packageContent; int previousNodeNumber; } package_struct; vector <node> nodes; vector <package_struct> packageTable; int thisX; int thisY; int global_port = 0; int sequence = 1; struct sockaddr_in myAddress; struct sockaddr_in priorAddress; struct sockaddr_in terminalAddress; struct sockaddr_in sourceAddress; struct sockaddr_in nextAddress; string previousAddressString; string localIP; int localPort; int sequenceCache = 0; int ackCache = 0; int fdSend; int fdRecv; vector <int> broadcastList; // node numbers to broadcast int heartRate = -1; int location_x = 999; int location_y = 999; int oxygen = -1; int toxic = -1; int stoi(string args) { return atoi(args.c_str()); } string to_string(int i) { stringstream ss; ss << i; return ss.str(); } string getRealIP(string tux_name) { string str; ifstream referenceStringFile(REAL_IP_FILE); if (!referenceStringFile) { cout<<"No real ip file found!"<<endl; } else { char line[100]; while (referenceStringFile.getline(line, sizeof(line))) { stringstream stream(line); string item; int i=0; // cout<<"line: "<<line<<endl; string tuxName; while(getline(stream, item, ' ')) { if (i==0) { tuxName = item; // cout<<"tuxName:"<<tuxName<<"."<<endl; // cout<<"tux_name:"<<tux_name<<"."<<endl; } if (i==1) { // cout<<"tuxName:"<<tuxName<<"."<<endl; // cout<<"tux_name:"<<tux_name<<"."<<endl; // cout<<(tuxName==tux_name)<<endl; if (tuxName == tux_name) { return item; } } i++; } } } return "0"; } int init_setup(string thisTux) { string str; int count = 0; ifstream referenceStringFile(MANET_FILE); if (!referenceStringFile) { cout<<"No reference string file found!"<<endl; return 0; } else { char line[100]; while (referenceStringFile.getline(line, sizeof(line))) { node myNode; // sscanf(line, // "Node %d %[^,], %d %d %d links %[^*]", // &myNode.nodeNum, myNode.IP, &myNode.port, &myNode.x, &myNode.y, myNode.links); stringstream stream(line); string item; int i = 0; int nodeNumInt; string currentTux; while(getline(stream, item, ' ')) { //cout<<item<<endl; if (i == 1) { nodeNumInt = stoi(item); // cout<<myNode.nodeNum<<endl; } if (i==2) { item.erase(item.end()-1); // remove ',' at the end of the 'tux78,' for example. currentTux = item; if (thisTux == item) { myNode.nodeNum = nodeNumInt; cout<<myNode.nodeNum<<endl; } } i++; } //cout<<endl; if (currentTux == thisTux) { nodes.push_back(myNode); } } } return 0; } int main(int argc, char const *argv[]) { string thisTux = argv[1]; cout<<thisTux<<endl; init_setup(thisTux); system("gcc myNode.cpp -o myNode -lstdc++ -lpthread -lm"); for (int i = 0; i < nodes.size(); ++i) { int myNodeNumber = nodes.at(i).nodeNum; string myNodeNumStr = to_string(myNodeNumber); if ((myNodeNumber != SOURCE_NODE) && (myNodeNumber != DESTINATION_NODE)) { string command = "gnome-terminal -e './myNode "+myNodeNumStr+"' -t 'Node "+myNodeNumStr+"'"; cout<<command<<endl; system(command.c_str()); //cout<<"gnome-terminal -e './myNode "+myNodeNumStr+"' -t 'Node "+myNodeNumStr+"'"<<endl; } } return 0; }
[ "boningliang@users.noreply.github.com" ]
boningliang@users.noreply.github.com
3203db2a89dd7cacb9d4135f77d24ad66439d29a
b2dcdaf29f21f3abfe15fd27ebf8731dc419ae22
/esp_udp_rtt/esp_code/testESP_UDP.ino
fc1626d2c0e29df1609df3febc7d59893b0e60f2
[ "BSD-2-Clause" ]
permissive
felipeville/linux-espnow-trenes
2806090af54b52d50931f9230897347070c6071e
be376086bf6bfb262662392239b72c056599a8de
refs/heads/master
2023-01-29T08:16:48.805742
2020-12-17T00:50:07
2020-12-17T00:50:07
299,772,342
1
0
BSD-2-Clause
2020-10-24T22:53:38
2020-09-30T00:44:56
C++
UTF-8
C++
false
false
6,819
ino
/* Name: testESP_UDP.ino Created: 10/31/2020 6:52:51 PM Author: Felipe Villenas */ #include <esp_now.h> #include <esp_wifi_types.h> #include <esp_wifi_internal.h> #include <esp_wifi.h> #include <PubSubClient.h> #include <WiFi.h> #include <WiFiUDP.h> #define PAYLOAD_SIZE 8 #define CHANNEL 8 #define DATA_RATE WIFI_PHY_RATE_6M #define CUSTOM_WIFI_CFG true #define SET_ACTION(action, name) if(action == ESP_OK) { Serial.println(String(name) + " OK!"); } else{ Serial.println("Error with: "+String(name)); } static uint8_t mac_broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; //static uint8_t mac_A[] = { 0xc4, 0x4f, 0x33, 0x15, 0xb0, 0x99 }; uint32_t T_MS = 20; uint32_t TOTAL_PACKETS = 500; uint32_t t0, t1; // para controlar la tasa de envio uint32_t timestamp; String esp_mqtt_id = "ESP"; bool resend = true; int N_packets = 0; int N_rcv = 0; float rtt_sum = 0; esp_now_peer_info_t peer_info; /* UDP Settings */ WiFiUDP udp; uint32_t udp_port = 3333; uint8_t udp_buffer[32]; /* MQTT Settings */ const char* ssid = "VTR-6351300"; const char* password = "zkd2bxhcHqHm"; const char* mqtt_server = "192.168.0.7"; // laptop local IPv4 String topic[] = { "ESP_command", "ESP_ts", "ESP_tpackets" }; WiFiClient espClient; PubSubClient client(espClient); /* ESPNOW functions */ void setup_custom_wifi(); void setup_espnow(); void add_peer(uint8_t* mac, int channel, bool encrypt); void OnDataSent(const uint8_t* mac, esp_now_send_status_t status) { /* nothing for now */ }; /* MQTT functions */ void setup_wifi_mqtt(); void mqtt_reconnect(); void mqtt_callback(char* ftopic, uint8_t* msg, uint32_t len); // the setup function runs once when you press reset or power the board void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); /* ---------- Setup ESP NOW ------------ */ /*if (CUSTOM_WIFI_CFG) { WiFi.disconnect(); setup_custom_wifi(); esp_wifi_set_ps(WIFI_PS_NONE); // power saving mode none } setup_espnow(); add_peer(mac_broadcast, CHANNEL, false); /* ------------------------------------- */ /* ----------- Setup MQTT -------------- */ setup_wifi_mqtt(); client.setServer(mqtt_server, 1883); client.setCallback(mqtt_callback); if (!client.connected()) { mqtt_reconnect(); Serial.println("Sub a los topicos: "); for (int i = 0; i < sizeof(topic) / sizeof(String); i++) Serial.println("> " + topic[i]); } /* ------------------------------------- */ udp.begin(WiFi.localIP(), udp_port); uint8_t ch; wifi_second_chan_t ch2; esp_wifi_get_channel(&ch, &ch2); float freq = 2.407 + 0.005 * (int)ch; Serial.printf("Conectado al canal Wi-Fi: %d (%.3f GHz)\n", ch, freq); Serial.println("------ Setup Completado! ------"); t0 = millis(); } // the loop function runs over and over again until power down or reset void loop() { if (resend) { client.disconnect(); } if (N_packets < TOTAL_PACKETS) { t1 = millis(); if (t1 - t0 >= T_MS) { timestamp = micros(); udp.beginPacket(mqtt_server, udp_port); udp.write((uint8_t*)&timestamp, 4); udp.endPacket(); //esp_now_send(mac_broadcast, (uint8_t*)&timestamp, sizeof(timestamp)); N_packets++; t0 = millis(); } } else if (N_packets == TOTAL_PACKETS) { Serial.println("------ Finished Sending " + String(TOTAL_PACKETS) + " Packets -------"); mqtt_reconnect(); Serial.println("MQTT restored"); resend = false; N_packets++; } int packetSize = udp.parsePacket(); if(packetSize){ int len = udp.read(udp_buffer, 32); if(len > 0){ uint32_t tx = 0; uint32_t tv = micros(); memcpy(&tx, udp_buffer, 4); rtt_sum += (tv - tx); N_rcv++; } } client.loop(); } ////////////////////////////////////////////////////////////////////////// /* Custom WiFi Settings for 'better' ESPNOW */ void setup_custom_wifi() { SET_ACTION(esp_wifi_stop(), "Stop WiFi"); SET_ACTION(esp_wifi_deinit(), "De-init WiFi"); wifi_init_config_t wifi_cfg = WIFI_INIT_CONFIG_DEFAULT(); wifi_cfg.ampdu_tx_enable = 0; SET_ACTION(esp_wifi_init(&wifi_cfg), "Setting custom config"); SET_ACTION(esp_wifi_start(), "Starting WiFi"); SET_ACTION(esp_wifi_set_promiscuous(true), "Setting promiscuous mode"); SET_ACTION(esp_wifi_set_channel(CHANNEL, WIFI_SECOND_CHAN_NONE), "Setting channel"); SET_ACTION(esp_wifi_internal_set_fix_rate(ESP_IF_WIFI_STA, true, DATA_RATE), "Setting datarate"); } void setup_espnow() { SET_ACTION(esp_now_init(), "Initializing ESPNOW"); esp_now_register_send_cb(OnDataSent); esp_now_register_recv_cb(OnDataRecv); } void add_peer(uint8_t* mac, int channel, bool encrypt) { memcpy(peer_info.peer_addr, mac, 6); peer_info.channel = channel; peer_info.encrypt = encrypt; if (esp_now_add_peer(&peer_info) != ESP_OK) Serial.println("Failed to add peer"); else Serial.println("Peer added successfully"); } void OnDataRecv(const uint8_t* mac, const uint8_t* incomingData, int len) { uint32_t t1 = micros(); uint32_t t0; memcpy(&t0, incomingData, 4); rtt_sum += (t1 - t0); N_rcv++; } ////////////////////////////////////////////////////////////////////////// /* MQTT Setup */ void setup_wifi_mqtt() { Serial.println("Connecting to " + String(ssid)); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(3000); Serial.print("."); WiFi.begin(ssid, password); } Serial.print("\nWi-Fi Connected!, IP Address: "); Serial.println(WiFi.localIP()); } void mqtt_reconnect() { while (!client.connected()) { if (client.connect(esp_mqtt_id.c_str())) { for (int i = 0; i < sizeof(topic) / sizeof(String); i++) client.subscribe(topic[i].c_str()); } else { delay(500); } } } void mqtt_callback(char* ftopic, uint8_t* msg, uint32_t len) { char* rcv_msg = (char*)malloc(len + 1); memcpy(rcv_msg, msg, len); rcv_msg[len] = '\0'; if (String(ftopic) == topic[0]) { if (String(rcv_msg) == "resend") { N_packets = 0; N_rcv = 0; rtt_sum = 0; bzero(udp_buffer,32); resend = true; Serial.println("Resending packets..."); } else if (String(rcv_msg) == "rcv") { Serial.println("Packets received from other ESPs: " + String(N_rcv)); } else if (String(rcv_msg) == "reset rcv") { Serial.println("Resetting 'rcv' counter."); N_rcv = 0; } else if (String(rcv_msg) == "rtt") { float rtt_avg = rtt_sum / N_rcv; Serial.println("Recovered " + String(N_rcv) + " packets."); Serial.println("Average RTT = " + String(rtt_avg) + " [us], Average Latency = " + String(rtt_avg / 2) + " [us]"); } } else if (String(ftopic) == topic[1]) { T_MS = atoi(rcv_msg); Serial.println("T_MS changed to = " + String(T_MS)); } else if (String(ftopic) == topic[2]) { TOTAL_PACKETS = atoi(rcv_msg); Serial.println("TOTAL_PACKETS changed to = " + String(TOTAL_PACKETS)); } free(rcv_msg); }
[ "felipe.villenas@sansano.usm.cl" ]
felipe.villenas@sansano.usm.cl
cdb2a948f62fc4702f56c00cec286f62161f4f08
9a1b1aed12d3cfd9d52f21bf1a77f26cf99cc01b
/RayTracers/pixelbuffer.cpp
bef8df44ae76505cb4ed50f7b1256443d177322f
[]
no_license
bhbosman/raytracer
41d4767318f3a6e625206131e2b11fc7f663987b
3882c4619e76e2f61dfdf2c745d9522edea02d37
refs/heads/master
2021-01-03T12:52:10.023435
2020-07-06T09:17:31
2020-07-06T09:17:31
39,560,985
0
0
null
null
null
null
UTF-8
C++
false
false
940
cpp
#include <QImage> #include "pixelbuffer.h" PixelBuffer::PixelBuffer(int width, int height): m_Image(width, height, QImage::Format_RGB32) { } int PixelBuffer::height() const { return m_Image.height(); } int PixelBuffer::width()const { return m_Image.width(); } int PixelBuffer::bytesPerLine() { return m_Image.bytesPerLine(); } uchar *PixelBuffer::scanLine(int lineNumber) { return m_Image.scanLine(lineNumber); } uchar *PixelBuffer::scanLine(int lineNumber, int linePos) { uchar *result = scanLine(lineNumber); result += linePos * bytesPerPixel(); return result; } int PixelBuffer::bytesPerPixel() { return bytesPerLine() / width(); } void PixelBuffer::fill(uint color) { m_Image.fill(color); } QImage PixelBuffer::image() { return m_Image; } void PixelBuffer::clear() { m_Image.fill(0); } void PixelBuffer::save(QString filename) const { m_Image.save(filename, 0, 100); }
[ "bhbosman@gmail.com" ]
bhbosman@gmail.com
093aea2542c009f59282b73f673a4d6c00764ebf
cdbfd8891cde8e11bd15b9d00e677e20e75f93aa
/riegeli/bytes/writer_ostream.h
19d4b6deccf4f5216fe1fe5510ea1b8b32edfdef
[ "Apache-2.0" ]
permissive
micahcc/riegeli
dbe317a8f8183f9a8a8c63b21702e0406e6452dd
d8cc64857253037d4f022e860b7b86cbe7d4b8d8
refs/heads/master
2023-06-24T21:36:14.894457
2021-07-20T16:07:49
2021-07-21T08:18:02
265,888,704
0
0
Apache-2.0
2020-05-21T15:47:47
2020-05-21T15:47:46
null
UTF-8
C++
false
false
12,628
h
// Copyright 2019 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 RIEGELI_BYTES_WRITER_OSTREAM_H_ #define RIEGELI_BYTES_WRITER_OSTREAM_H_ #include <ostream> #include <streambuf> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "riegeli/base/base.h" #include "riegeli/base/dependency.h" #include "riegeli/base/object.h" #include "riegeli/bytes/writer.h" namespace riegeli { namespace internal { class WriterStreambuf : public std::streambuf { public: explicit WriterStreambuf(ObjectState::InitiallyClosed) noexcept : state_(ObjectState::kInitiallyClosed) {} explicit WriterStreambuf(ObjectState::InitiallyOpen) noexcept : state_(ObjectState::kInitiallyOpen) {} WriterStreambuf(WriterStreambuf&& that) noexcept; WriterStreambuf& operator=(WriterStreambuf&& that) noexcept; void Initialize(Writer* dest); void MoveBegin(); void MoveEnd(Writer* dest); void Done(); bool healthy() const { return state_.healthy(); } bool is_open() const { return state_.is_open(); } absl::Status status() const { return state_.status(); } void MarkClosed() { state_.MarkClosed(); } ABSL_ATTRIBUTE_COLD void Fail(); protected: int sync() override; int overflow(int ch) override; std::streamsize xsputn(const char* src, std::streamsize length) override; std::streampos seekoff(std::streamoff off, std::ios_base::seekdir dir, std::ios_base::openmode which) override; std::streampos seekpos(std::streampos pos, std::ios_base::openmode which) override; private: class BufferSync; ObjectState state_; Writer* dest_ = nullptr; // Invariants: // `is_open() ? pbase() >= dest_->start() : pbase() == nullptr` // `epptr() == (is_open() ? dest_->limit() : nullptr)` }; } // namespace internal // Template parameter independent part of `WriterOstream`. class WriterOstreamBase : public std::ostream { public: // Returns the `Writer`. Unchanged by `close()`. virtual Writer* dest_writer() = 0; virtual const Writer* dest_writer() const = 0; // If `!is_open()`, does nothing. Otherwise: // * Synchronizes the current `WriterOstream` position to the `Writer`. // * Closes the `Writer` if it is owned. // // Returns `*this` for convenience of checking for failures. // // Destroying or assigning to a `WriterOstream` closes it implicitly, but an // explicit `close()` call allows to detect failures (use `status()` for // failure details). virtual WriterOstreamBase& close() = 0; // Returns `true` if the `WriterOstream` is healthy, i.e. open and not failed. bool healthy() const { return streambuf_.healthy(); } // Returns `true` if the `WriterOstream` is open, i.e. not closed. bool is_open() const { return streambuf_.is_open(); } // Returns an `absl::Status` describing the failure if the `WriterOstream` // is failed, or an `absl::FailedPreconditionError()` if the `WriterOstream` // is closed, or `absl::OkStatus()` if the `WriterOstream` is healthy. absl::Status status() const { return streambuf_.status(); } protected: explicit WriterOstreamBase(ObjectState::InitiallyClosed) noexcept : std::ostream(&streambuf_), streambuf_(ObjectState::kInitiallyClosed) {} explicit WriterOstreamBase(ObjectState::InitiallyOpen) noexcept : std::ostream(&streambuf_), streambuf_(ObjectState::kInitiallyOpen) {} WriterOstreamBase(WriterOstreamBase&& that) noexcept; WriterOstreamBase& operator=(WriterOstreamBase&& that) noexcept; void Reset(ObjectState::InitiallyClosed); void Reset(ObjectState::InitiallyOpen); void Initialize(Writer* dest); internal::WriterStreambuf streambuf_; // Invariant: `rdbuf() == &streambuf_` }; // Adapts a `Writer` to a `std::ostream`. // // The `Dest` template parameter specifies the type of the object providing and // possibly owning the `Writer`. `Dest` must support // `Dependency<Writer*, Dest>`, e.g. `Writer*` (not owned, default), // `std::unique_ptr<Writer>` (owned), `ChainWriter<>` (owned). // // By relying on CTAD the template argument can be deduced as the value type of // the first constructor argument. This requires C++17. // // The `Writer` must not be accessed until the `WriterOstream` is closed or no // longer used, except that it is allowed to read the destination of the // `Writer` immediately after `flush()`. // // Destroying or assigning to a `WriterOstream` closes it first. template <typename Dest = Writer*> class WriterOstream : public WriterOstreamBase { public: // Creates a closed `WriterOstream`. WriterOstream() noexcept : WriterOstreamBase(ObjectState::kInitiallyClosed) {} // Will write to the `Writer` provided by `dest`. explicit WriterOstream(const Dest& dest); explicit WriterOstream(Dest&& dest); // Will write to the `Writer` provided by a `Dest` constructed from elements // of `dest_args`. This avoids constructing a temporary `Dest` and moving from // it. template <typename... DestArgs> explicit WriterOstream(std::tuple<DestArgs...> dest_args); WriterOstream(WriterOstream&& that) noexcept; WriterOstream& operator=(WriterOstream&& that) noexcept; ~WriterOstream() override { close(); } // Makes `*this` equivalent to a newly constructed `WriterOstream`. This // avoids constructing a temporary `WriterOstream` and moving from it. void Reset(); void Reset(const Dest& dest); void Reset(Dest&& dest); template <typename... DestArgs> void Reset(std::tuple<DestArgs...> dest_args); // Returns the object providing and possibly owning the `Writer`. Unchanged by // `close()`. Dest& dest() { return dest_.manager(); } const Dest& dest() const { return dest_.manager(); } Writer* dest_writer() override { return dest_.get(); } const Writer* dest_writer() const override { return dest_.get(); } WriterOstream& close() override; private: void MoveDest(WriterOstream&& that); // The object providing and possibly owning the `Writer`. Dependency<Writer*, Dest> dest_; }; // Support CTAD. #if __cpp_deduction_guides WriterOstream()->WriterOstream<DeleteCtad<>>; template <typename Dest> explicit WriterOstream(const Dest& dest) -> WriterOstream<std::decay_t<Dest>>; template <typename Dest> explicit WriterOstream(Dest&& dest) -> WriterOstream<std::decay_t<Dest>>; template <typename... DestArgs> explicit WriterOstream(std::tuple<DestArgs...> dest_args) -> WriterOstream<DeleteCtad<std::tuple<DestArgs...>>>; #endif // Implementation details follow. namespace internal { inline WriterStreambuf::WriterStreambuf(WriterStreambuf&& that) noexcept : std::streambuf(that), state_(std::move(that.state_)), dest_(that.dest_) { that.setp(nullptr, nullptr); } inline WriterStreambuf& WriterStreambuf::operator=( WriterStreambuf&& that) noexcept { if (ABSL_PREDICT_TRUE(&that != this)) { std::streambuf::operator=(that); state_ = std::move(that.state_); dest_ = that.dest_; that.setp(nullptr, nullptr); } return *this; } inline void WriterStreambuf::Initialize(Writer* dest) { RIEGELI_ASSERT(dest != nullptr) << "Failed precondition of WriterStreambuf: null Writer pointer"; dest_ = dest; setp(dest_->cursor(), dest_->limit()); if (ABSL_PREDICT_FALSE(!dest_->healthy())) Fail(); } inline void WriterStreambuf::MoveBegin() { // In a closed `WriterOstream`, `WriterOstream::dest_.get() != nullptr` // does not imply `WriterStreamBuf::dest_ != nullptr`, because // `WriterOstream::streambuf_` can be left uninitialized. if (dest_ == nullptr) return; dest_->set_cursor(pptr()); } inline void WriterStreambuf::MoveEnd(Writer* dest) { // In a closed `WriterOstream`, `WriterOstream::dest_.get() != nullptr` // does not imply `WriterStreamBuf::dest_ != nullptr`, because // `WriterOstream::streambuf_` can be left uninitialized. if (dest_ == nullptr) return; dest_ = dest; setp(dest_->cursor(), dest_->limit()); } inline void WriterStreambuf::Done() { dest_->set_cursor(pptr()); setp(nullptr, nullptr); } } // namespace internal inline WriterOstreamBase::WriterOstreamBase(WriterOstreamBase&& that) noexcept : std::ostream(std::move(that)), // Using `that` after it was moved is correct because only the base class // part was moved. streambuf_(std::move(that.streambuf_)) { set_rdbuf(&streambuf_); } inline WriterOstreamBase& WriterOstreamBase::operator=( WriterOstreamBase&& that) noexcept { std::ostream::operator=(std::move(that)); // Using `that` after it was moved is correct because only the base class part // was moved. streambuf_ = std::move(that.streambuf_); return *this; } inline void WriterOstreamBase::Reset(ObjectState::InitiallyClosed) { streambuf_ = internal::WriterStreambuf(ObjectState::kInitiallyClosed); init(&streambuf_); } inline void WriterOstreamBase::Reset(ObjectState::InitiallyOpen) { streambuf_ = internal::WriterStreambuf(ObjectState::kInitiallyOpen); init(&streambuf_); } inline void WriterOstreamBase::Initialize(Writer* dest) { streambuf_.Initialize(dest); if (ABSL_PREDICT_FALSE(!streambuf_.healthy())) { setstate(std::ios_base::badbit); } } template <typename Dest> inline WriterOstream<Dest>::WriterOstream(const Dest& dest) : WriterOstreamBase(ObjectState::kInitiallyOpen), dest_(dest) { Initialize(dest_.get()); } template <typename Dest> inline WriterOstream<Dest>::WriterOstream(Dest&& dest) : WriterOstreamBase(ObjectState::kInitiallyOpen), dest_(std::move(dest)) { Initialize(dest_.get()); } template <typename Dest> template <typename... DestArgs> inline WriterOstream<Dest>::WriterOstream(std::tuple<DestArgs...> dest_args) : WriterOstreamBase(ObjectState::kInitiallyOpen), dest_(std::move(dest_args)) { Initialize(dest_.get()); } template <typename Dest> inline WriterOstream<Dest>::WriterOstream(WriterOstream&& that) noexcept : WriterOstreamBase(std::move(that)) { // Using `that` after it was moved is correct because only the base class part // was moved. MoveDest(std::move(that)); } template <typename Dest> inline WriterOstream<Dest>& WriterOstream<Dest>::operator=( WriterOstream&& that) noexcept { if (ABSL_PREDICT_TRUE(&that != this)) { close(); WriterOstreamBase::operator=(std::move(that)); // Using `that` after it was moved is correct because only the base class // part was moved. MoveDest(std::move(that)); } return *this; } template <typename Dest> inline void WriterOstream<Dest>::Reset() { close(); WriterOstreamBase::Reset(ObjectState::kInitiallyClosed); dest_.Reset(); } template <typename Dest> inline void WriterOstream<Dest>::Reset(const Dest& dest) { close(); WriterOstreamBase::Reset(ObjectState::kInitiallyOpen); dest_.Reset(dest); Initialize(dest_.get()); } template <typename Dest> inline void WriterOstream<Dest>::Reset(Dest&& dest) { close(); WriterOstreamBase::Reset(ObjectState::kInitiallyOpen); dest_.Reset(std::move(dest)); Initialize(dest_.get()); } template <typename Dest> template <typename... DestArgs> inline void WriterOstream<Dest>::Reset(std::tuple<DestArgs...> dest_args) { close(); WriterOstreamBase::Reset(ObjectState::kInitiallyOpen); dest_.Reset(std::move(dest_args)); Initialize(dest_.get()); } template <typename Dest> inline void WriterOstream<Dest>::MoveDest(WriterOstream&& that) { if (dest_.kIsStable()) { dest_ = std::move(that.dest_); } else { streambuf_.MoveBegin(); dest_ = std::move(that.dest_); streambuf_.MoveEnd(dest_.get()); } } template <typename Dest> inline WriterOstream<Dest>& WriterOstream<Dest>::close() { if (ABSL_PREDICT_TRUE(is_open())) { streambuf_.Done(); if (dest_.is_owning()) { if (ABSL_PREDICT_FALSE(!dest_->Close())) streambuf_.Fail(); } if (ABSL_PREDICT_FALSE(!streambuf_.healthy())) { setstate(std::ios_base::badbit); } streambuf_.MarkClosed(); } return *this; } } // namespace riegeli #endif // RIEGELI_BYTES_WRITER_OSTREAM_H_
[ "qrczak@google.com" ]
qrczak@google.com
bd2fa21a6c78fd6d94d7df4962211ed287879c51
28f0925e01102460276b5a0124851ec9ec1c1b19
/renderer/cocos2d-x-2.x/CCDragonBones.h
880d8d594783b4e523aa9723815071b0d0383c86
[ "MIT" ]
permissive
gameview/DragonBonesCPP
d36e72d05c998a8f801994e05da68e1034ba5158
564486c3cda145a63970094ed2580860d5b465d4
refs/heads/master
2021-01-17T22:40:52.116067
2014-04-23T01:48:33
2014-04-23T01:48:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,895
h
// // CCDragonBones.h // // // Created by Wayne Dimart on 14-4-18. // Copyright (c) 2014 . All rights reserved. // Modified by zrong(zengrong.net) on 2014-04-22 // #ifndef __QUICKCOCOS2DX__CCDRAGONBONES__ #define __QUICKCOCOS2DX__CCDRAGONBONES__ #include <iostream> #include "cocos2d.h" #include "preDB.h" #include "Animation.h" #include "Event.h" namespace dragonBones { class Armature; class CCDragonBones:public cocos2d::CCNode { public: // create static Armature* buildArmature( const char* skeletonXMLFile, const char* textureXMLFile, const char* dragonBonesName, const char* armatureName, const char* animationName = ""); static CCDragonBones* create(Armature*arm); static CCDragonBones* create( const char* skeletonXMLFile, const char* dragonBonesName, const char* armatureName); static CCDragonBones* create( const char* skeletonXMLFile, const char* textureXMLFile, const char* dragonBonesName, const char* armatureName, const char* animationName = ""); CCNode* getDisplayNode(); Armature* getArmature(); void gotoAndPlay( const String &animationName, Number fadeInTime = -1, Number duration = -1, Number loop = NaN, uint layer = 0, const String &group = "", const String &fadeOutMode = Animation::SAME_LAYER_AND_GROUP, bool displayControl = true, bool pauseFadeOut = true, bool pauseFadeIn = true ); void addEventListener( const String &type, const String &key, cocos2d::CCObject*pObj, cocos2d::SEL_CallFuncND callback); bool hasEventListener(const String &type); void removeEventListener(const String &type, const std::string &key); void dispatchEvent(Event *event); // Methods for cocos2d-x users. void setBoneTexture(const char* boneName, const char* textureName, const char* textureAtlasName); // Override cocos2d-x method. virtual void onExit(); private: void initWithArmature(Armature*arm); void update(float dt); Armature* m_Armature; cocos2d::SEL_CallFuncND m_Callback; cocos2d::CCObject* m_Caller; void eventBridge(Event*e); Animation* getAnimation(); }; } #endif // __QUICKCOCOS2DX__CCDRAGONBONES__
[ "zrongzrong@gmail.com" ]
zrongzrong@gmail.com
9c1e81f16240ae610022604e138eda6e23c656d7
e09682e57b06807d156849f628c14aa707f53010
/UnitTesting/UFHUnitTesting/TaskList.h
e2496581b39a0dffd273b3f70c3243d325164c19
[]
no_license
franklingu/Tasky
2dfde2eaa588eb80a14d8cd4237f098788c5d435
8dce5dd7657dbe4585f15362ad72596773b37d26
refs/heads/master
2020-05-20T15:55:53.301735
2014-11-17T07:47:28
2014-11-17T07:47:28
16,256,259
1
0
null
null
null
null
UTF-8
C++
false
false
3,292
h
#ifndef _TASKLIST_H_ #define _TASKLIST_H_ /* *This class is mainly to store tasks and manipulate tasks according to processor's command. * *Main author: Kai Wen */ #include "Essential.h" #include "Task.h" class TaskList{ private: vector<Task> _taskList; public: TaskList(); /** * Purpose: * adds the task to the taskList. Pushes any tasks that clashes into the referenced vector * @param toAdd the task to be added into _taskList * @param _temp for Logic to push in tasks that clash * @return status code */ int add(Task toAdd, vector<Task>& _temp); /** * Purpose: * finds a task in the vector that isEqual to the task to be removed and removes it. * @param toRemove task to be removed * @return status code */ int remove(Task toRemove); /** * Purpose: * pushes tasks that that has the same title as searchLine into temp. * @param searchLine title of task being searched * @param _temp for Logic to push in tasks that match * @return status code */ int search(string searchLine, vector<Task>& _temp); /** * Purpose: * searches for tasks corresponding to the keywords and pushes those tasks by relevance into referenced vector. * @param keywords * @param _temp for Logic to push in tasks that match * @return status code */ int searchKeywords(vector<string> keywords, vector<Task>& _temp); /** * Purpose: * same as searchKeywords but only searches for tasks that are in range. * @param keywords * @param _temp for Logic to push in tasks that match * @param start * @param end * @return status code */ int searchKeywordsInRange(vector<string> keywords, vector<Task>& _temp, BasicDateTime start, BasicDateTime end); /** * Purpose: * pushes all tasks into referenced vector * @param _temp for Logic to put in all tasks * @return status code */ int displayAll(vector<Task>& _temp); /** * Purpose: * pushes tasks that are done/pending accordingly into referenced vector; done: true, pending:false; * @param done for Logic to search either done/pending tasks * @param _temp for Logic to put in matching tasks * @return status code */ int displayStatus(bool done, vector<Task>& _temp); /** * Purpose: * pushes tasks in range into referenced vector * @param start * @param end * @param _temp for Logic to put in tasks within the range * @return status code */ int displayInRange(BasicDateTime start, BasicDateTime end, vector<Task>& _temp); /** * Purpose: * updates the existing task into the new task. any tasks that clashes will be pushed into referenced vector. * @param exisitngTask old task * @param newTask task with new details * @param _temp for Logic to put in tasks that clash * @return status code */ int update(Task existingTask, Task newTask, vector<Task>& _temp); /** * Purpose: * marks the task as done or pending * @param mark to mark the status of the task as * @param task task to be marked * @return status code */ int mark(bool mark, Task task); /** * Purpose: * pushes BasicDateTimes that are used into the referenced vector * @param vector<BasicDateTime> to push in the BasicDateTimes that are used */ void getOccupiedDates(vector<BasicDateTime>& usedDates); }; #endif
[ "franklingujunchao@gmail.com" ]
franklingujunchao@gmail.com
e86baf8e266ce5c91b68be8c9ae31b6575b66ebd
f8c0dfc8ac97de89c11bdefc3d3de86996da4a97
/Recursion/Combinations II.cpp
2cc7d2e046b6d8457fe8d23c23471d4b08316a58
[]
no_license
gourab-sinha/Interview-Prep
e822f8e491264185ffa9d09ee3d0e6917e7748b8
6118eda91d850eb077e236ac3e9f0e1ef15b6ed5
refs/heads/master
2022-07-01T23:28:36.427828
2020-05-13T21:39:51
2020-05-13T21:39:51
263,372,122
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
cpp
/* Combinations Problem Description Given two integers A and B, return all possible combinations of B numbers out of 1 2 3 ... A . Make sure the combinations are sorted. To elaborate, Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not. Entries should be sorted within themselves. WARNING: DO NOT USE LIBRARY FUNCTION FOR GENERATING COMBINATIONS. Problem Constraints 1 <= A, B <= 10 Input Format First argument is an integer A. Second argument is an integer B. Output Format Return a 2-D vector denoting all possible combinations. Example Input A = 4 B = 2 Example Output [ [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], ] Example Explanation All the possible combinations of size 2 in sorted order. Intuition: This problem as same as the finding all the subsets from a given array with just added two condition 1. Elements will be from 1 to A and size of each subset will be B. In subset problem we have two to choices to for each element. They are we can add to subset or not add to subset. We start first element and we can add or we ignore and we keep doing it until our subset size matches with B or we left with no elements. Initial Step - Create one array of size A with elements in increasing order till A. Like A = 4 then [1,2,3,4] as array. Added Base Condition - subset.size()==B */ void getCombination(vector<int>& numbers,int index,int B,vector<int> subset,vector<vector<int>> &result) { if(subset.size()==B) { result.push_back(subset); return; } if(index==numbers.size()) { return; } subset.push_back(numbers[index]); getCombination(numbers,index+1,B,subset,result); subset.pop_back(); getCombination(numbers,index+1,B,subset,result); } vector<vector<int> > Solution::combine(int A, int B) { vector<int> numbers(A,0); for(int i=1;i<=A;i++) { numbers[i-1] = i; } vector<vector<int> > result; getCombination(numbers,0,B,{},result); return result; }
[ "gourab19964u@gmail.com" ]
gourab19964u@gmail.com
0b9be3af53a273b143326b36541f09966f0e20d1
cc239167212370eb2251528d9edce7e255a48ef9
/src/blpwtk2/private/blpwtk2_networkdelegateimpl.h
65ae0eba57e0e364f2c859ec9de3d3e2c9af45ed
[ "BSD-3-Clause", "MIT" ]
permissive
jun-zhang/chromium.bb
45242c26bfa392a286a82a99c6698a87f517bfc4
977221a39d6e18da7ede0325453dcbcef27825f6
refs/heads/master
2021-01-02T09:22:05.267168
2017-05-01T18:06:32
2017-05-01T18:06:32
99,195,952
0
1
null
2017-08-03T05:55:54
2017-08-03T05:55:54
null
UTF-8
C++
false
false
1,956
h
/* * Copyright (C) 2013 Bloomberg Finance L.P. * * 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 INCLUDED_BLPWTK2_NETWORKDELEGATEIMPL_H #define INCLUDED_BLPWTK2_NETWORKDELEGATEIMPL_H #include <blpwtk2_config.h> #include <net/base/network_delegate_impl.h> namespace blpwtk2 { // This is our implementation of chromium's NetworkDelegate interface. We need // this in order to allow access to the file system using "file://" urls by overriding // the OnCanAccessFile method. class NetworkDelegateImpl : public net::NetworkDelegateImpl { public: NetworkDelegateImpl(); virtual ~NetworkDelegateImpl(); // net::NetworkDelegateImpl overrides bool OnCanAccessFile(const net::URLRequest& request, const base::FilePath& path) const override; DISALLOW_COPY_AND_ASSIGN(NetworkDelegateImpl); }; } // close namespace blpwtk2 #endif // INCLUDED_BLPWTK2_NETWORKDELEGATEIMPL_H
[ "sbaig1@bloomberg.net" ]
sbaig1@bloomberg.net
c38f4180e6bee8d4f5fd96e3e54a0a1200db1378
0d653408de7c08f1bef4dfba5c43431897097a4a
/cmajor/cmsvc/Message.hpp
62e5ad3f01683d1114ea8215524aac4f9b7b99ee
[]
no_license
slaakko/cmajorm
948268634b8dd3e00f86a5b5415bee894867b17c
1f123fc367d14d3ef793eefab56ad98849ee0f25
refs/heads/master
2023-08-31T14:05:46.897333
2023-08-11T11:40:44
2023-08-11T11:40:44
166,633,055
7
2
null
null
null
null
UTF-8
C++
false
false
2,286
hpp
// ================================= // Copyright (c) 2022 Seppo Laakko // Distributed under the MIT license // ================================= #ifndef CMAJOR_SERVICE_MESSAGE_INCLUDED #define CMAJOR_SERVICE_MESSAGE_INCLUDED #include <cmajor/cmsvc/ServiceApi.hpp> #include <cmajor/wing/Window.hpp> #include <string> namespace cmajor { namespace service { const int SM_SERVICE_MESSAGE_AVAILABLE = WM_USER + 1; enum class ServiceMessageKind : int { clearOutput = 0, outputMessage = 1, buildReply = 2, buildError = 3, stopBuild = 4, getDefinitionReply = 5, getDefinitionError = 6, startDebugReply = 7, startError = 8, continueReply = 9, nextReply = 10, stepReply = 11, finishReply = 12, untilReply = 13, breakReply = 14, deleteReply = 15, depthReply = 16, framesReply = 17, evaluateReply = 18, countReply = 19, evaluateChildReply = 20, targetRunning = 21, targetInput = 22, targetOutput = 23, debugServiceStopped = 24, processTerminated = 25, runServiceStopped = 26, loadEditModuleReply = 27, loadEditModuleError = 28, parseSourceReply = 29, parseSourceError = 30, resetEditModuleCacheReply = 31, resetEditModuleCacheError = 32, getCCListReply = 33, getCCListError = 34, getParamHelpListReply = 35, getParamHelpListError = 36 }; class CMSVC_API ServiceMessage { public: ServiceMessage(ServiceMessageKind kind_); virtual ~ServiceMessage(); ServiceMessageKind Kind() const { return kind; } private: ServiceMessageKind kind; }; class CMSVC_API ClearOutputServiceMessage : public ServiceMessage { public: ClearOutputServiceMessage(); }; class CMSVC_API OutputServiceMessage : public ServiceMessage { public: OutputServiceMessage(const std::string& text_); const std::string& Text() const { return text; } private: std::string text; }; CMSVC_API void SetServiceMessageHandlerView(wing::Window* view); CMSVC_API void PutServiceMessage(ServiceMessage* message); CMSVC_API void PutClearOutputServiceMessage(); CMSVC_API void PutOutputServiceMessage(const std::string& messageText); CMSVC_API bool ServiceMessageQueueEmpty(); CMSVC_API std::unique_ptr<ServiceMessage> GetServiceMessage(); CMSVC_API void InitServiceMessage(); CMSVC_API void DoneServiceMessage(); } } // namespace cmajor::service #endif // CMAJOR_SVC_MESSAGE_INCLUDED
[ "slaakko@gmail.com" ]
slaakko@gmail.com
66bef7b8177c7b5fb60e4374a6df9ba30990dd98
73499efc27bac47cd9d077642d5797e68f8d6607
/8_Console_Create_UWP_Package/MyApp.cpp
c96172a3b4d09ca0a7da0036013b71792da8dfeb
[]
no_license
lihas/Win32CodingAssignments
46bc8af8804987c79a88d0957822e823f46659b1
e13f09600c0519b4671c036cc5e1ee642645c614
refs/heads/master
2020-04-15T02:12:04.639110
2019-01-06T12:57:05
2019-01-06T12:57:05
164,305,967
5
2
null
null
null
null
UTF-8
C++
false
false
3,095
cpp
/*Read README.txt*/ using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Core; using namespace Windows::Foundation; using namespace Windows::UI; using namespace Platform; using namespace Windows::UI::Xaml; using Windows::UI::Xaml::ApplicationInitializationCallback; using Windows::UI::Color; ref class MyPage sealed : public Page { private: TextBlock^ textBlock; public: MyPage(); void OnKeyDown(CoreWindow^ sender, KeyEventArgs^ args); void OnButtonClick(Object^ sender, RoutedEventArgs^ args); }; MyPage::MyPage() { Window::Current->CoreWindow->KeyDown += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &MyPage::OnKeyDown); Grid^ grid = ref new Grid; textBlock = ref new TextBlock(); textBlock->Text = "Hello World"; textBlock->FontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Segoe UI"); textBlock->FontSize = 120; textBlock->FontWeight = Text::FontWeight(Text::FontWeights::Bold); textBlock->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Gold); textBlock->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center; textBlock->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center; grid->Children->Append(textBlock); Button^ button = ref new Button; button->Content = "Press Me"; button->Width = 400; button->Height = 200; button->BorderThickness = 12; button->BorderBrush = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Gold); button->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red); button->FontFamily = ref new Windows::UI::Xaml::Media::FontFamily("Segoe UI"); button->FontWeight = Windows::UI::Text::FontWeight(Windows::UI::Text::FontWeights::Bold); button->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center; button->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Bottom; button->Click += ref new RoutedEventHandler(this, &MyPage::OnButtonClick); grid->Children->Append(button); this->Content = grid; } void MyPage::OnKeyDown(CoreWindow^ sender, KeyEventArgs^ args) { textBlock->Text = "KeyPressed"; } void MyPage::OnButtonClick(Object^ sender, RoutedEventArgs^ args) { textBlock->Text = "Button Clicked"; } ref class App sealed : public Windows::UI::Xaml::Application { public: void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) override; }; void MyCallbackMethod(Windows::UI::Xaml::ApplicationInitializationCallbackParams^ params) { App^ app = ref new App; } int main(Array<String^>^ args) { Windows::UI::Xaml::ApplicationInitializationCallback^ callback = ref new Windows::UI::Xaml::ApplicationInitializationCallback(MyCallbackMethod); Application::Start(callback); return 0; } void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) { MyPage^ page = ref new MyPage(); Window::Current->Content = page; Window::Current->Activate(); }
[ "sahils@sahils-lt.nvidia.com" ]
sahils@sahils-lt.nvidia.com
6bbd5c597f3eb7db222f207078c2686e2bbbc0b5
1c167daf725d9d7368a4d8e69654b8a4749b2fe9
/tests/catch.hpp
2a7146a7f9cbe9c020603e983be04bf5e13e4882
[ "MIT", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
syoyo/tinygltf
427470a39f7c0feb073900ff65f2dc7a8f4cf4b6
3d445cc65d9d54fc8e708b9159c5b522dbf77687
refs/heads/release
2023-09-04T09:27:15.295859
2023-09-02T17:20:35
2023-09-02T17:20:35
92,255,456
1,758
470
MIT
2023-09-12T11:28:36
2017-05-24T05:59:28
C++
UTF-8
C++
false
false
376,913
hpp
/* * Catch v1.4.0 * Generated: 2016-03-15 07:23:12.623111 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_CATCH_HPP_INCLUDED #ifdef __clang__ # pragma clang system_header #elif defined __GNUC__ # pragma GCC system_header #endif // #included from: internal/catch_suppress_warnings.h #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(push) # pragma warning(disable: 161 1682) # else // __ICC # pragma clang diagnostic ignored "-Wglobal-constructors" # pragma clang diagnostic ignored "-Wvariadic-macros" # pragma clang diagnostic ignored "-Wc99-extensions" # pragma clang diagnostic ignored "-Wunused-variable" # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wpadded" # pragma clang diagnostic ignored "-Wc++98-compat" # pragma clang diagnostic ignored "-Wc++98-compat-pedantic" # pragma clang diagnostic ignored "-Wswitch-enum" # pragma clang diagnostic ignored "-Wcovered-switch-default" # endif #elif defined __GNUC__ # pragma GCC diagnostic ignored "-Wvariadic-macros" # pragma GCC diagnostic ignored "-Wunused-variable" # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpadded" #endif #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) # define CATCH_IMPL #endif #ifdef CATCH_IMPL # ifndef CLARA_CONFIG_MAIN # define CLARA_CONFIG_MAIN_NOT_DEFINED # define CLARA_CONFIG_MAIN # endif #endif // #included from: internal/catch_notimplemented_exception.h #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED // #included from: catch_common.h #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #ifdef CATCH_CONFIG_COUNTER # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) #else # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #endif #define INTERNAL_CATCH_STRINGIFY2( expr ) #expr #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) #include <sstream> #include <stdexcept> #include <algorithm> // #included from: catch_compiler_capabilities.h #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED // Detect a number of compiler features - mostly C++11/14 conformance - by compiler // The following features are defined: // // CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? // CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? // CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods // CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? // CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? // CATCH_CONFIG_CPP11_OVERRIDE : is override supported? // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_<feature name> form // (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 #if defined(__cplusplus) && __cplusplus >= 201103L # define CATCH_CPP11_OR_GREATER #endif #ifdef __clang__ # if __has_feature(cxx_nullptr) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # if __has_feature(cxx_noexcept) # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif # if defined(CATCH_CPP11_OR_GREATER) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) # endif #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Borland #ifdef __BORLANDC__ #endif // __BORLANDC__ //////////////////////////////////////////////////////////////////////////////// // EDG #ifdef __EDG_VERSION__ #endif // __EDG_VERSION__ //////////////////////////////////////////////////////////////////////////////// // Digital Mars #ifdef __DMC__ #endif // __DMC__ //////////////////////////////////////////////////////////////////////////////// // GCC #ifdef __GNUC__ # if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_CPP11_OR_GREATER) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" ) # endif // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below #endif // __GNUC__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if (_MSC_VER >= 1600) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Use variadic macros if the compiler supports them #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ ( defined __GNUC__ && __GNUC__ >= 3 ) || \ ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) #define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS #endif // Use __COUNTER__ if the compiler supports it #if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \ ( defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3 ) || \ ( defined __clang__ && __clang_major__ >= 3 ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif //////////////////////////////////////////////////////////////////////////////// // C++ language feature support // catch all support for C++11 #if defined(CATCH_CPP11_OR_GREATER) # if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE # define CATCH_INTERNAL_CONFIG_CPP11_TUPLE # endif # ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) # define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) # define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR # endif #endif // __cplusplus >= 201103L // Now set the actual defines based on the above + anything the user has configured #if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NULLPTR #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NOEXCEPT #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_GENERATED_METHODS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_IS_ENUM #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_TUPLE #endif #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) # define CATCH_CONFIG_VARIADIC_MACROS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_LONG_LONG #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_OVERRIDE #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_UNIQUE_PTR #endif #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #endif // noexcept support: #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) # define CATCH_NOEXCEPT noexcept # define CATCH_NOEXCEPT_IS(x) noexcept(x) #else # define CATCH_NOEXCEPT throw() # define CATCH_NOEXCEPT_IS(x) #endif // nullptr support #ifdef CATCH_CONFIG_CPP11_NULLPTR # define CATCH_NULL nullptr #else # define CATCH_NULL NULL #endif // override support #ifdef CATCH_CONFIG_CPP11_OVERRIDE # define CATCH_OVERRIDE override #else # define CATCH_OVERRIDE #endif // unique_ptr support #ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR # define CATCH_AUTO_PTR( T ) std::unique_ptr<T> #else # define CATCH_AUTO_PTR( T ) std::auto_ptr<T> #endif namespace Catch { struct IConfig; struct CaseSensitive { enum Choice { Yes, No }; }; class NonCopyable { #ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable && ) = delete; NonCopyable& operator = ( NonCopyable const& ) = delete; NonCopyable& operator = ( NonCopyable && ) = delete; #else NonCopyable( NonCopyable const& info ); NonCopyable& operator = ( NonCopyable const& ); #endif protected: NonCopyable() {} virtual ~NonCopyable(); }; class SafeBool { public: typedef void (SafeBool::*type)() const; static type makeSafe( bool value ) { return value ? &SafeBool::trueValue : 0; } private: void trueValue() const {} }; template<typename ContainerT> inline void deleteAll( ContainerT& container ) { typename ContainerT::const_iterator it = container.begin(); typename ContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete *it; } template<typename AssociativeContainerT> inline void deleteAllValues( AssociativeContainerT& container ) { typename AssociativeContainerT::const_iterator it = container.begin(); typename AssociativeContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete it->second; } bool startsWith( std::string const& s, std::string const& prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); std::string trim( std::string const& str ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; struct SourceLineInfo { SourceLineInfo(); SourceLineInfo( char const* _file, std::size_t _line ); SourceLineInfo( SourceLineInfo const& other ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SourceLineInfo( SourceLineInfo && ) = default; SourceLineInfo& operator = ( SourceLineInfo const& ) = default; SourceLineInfo& operator = ( SourceLineInfo && ) = default; # endif bool empty() const; bool operator == ( SourceLineInfo const& other ) const; bool operator < ( SourceLineInfo const& other ) const; std::string file; std::size_t line; }; std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); // This is just here to avoid compiler warnings with macro constants and boolean literals inline bool isTrue( bool value ){ return value; } inline bool alwaysTrue() { return true; } inline bool alwaysFalse() { return false; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); void seedRng( IConfig const& config ); unsigned int rngSeed(); // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { std::string operator+() { return std::string(); } }; template<typename T> T const& operator + ( T const& value, StreamEndStop ) { return value; } } #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); #include <ostream> namespace Catch { class NotImplementedException : public std::exception { public: NotImplementedException( SourceLineInfo const& lineInfo ); NotImplementedException( NotImplementedException const& ) {} virtual ~NotImplementedException() CATCH_NOEXCEPT {} virtual const char* what() const CATCH_NOEXCEPT; private: std::string m_what; SourceLineInfo m_lineInfo; }; } // end namespace Catch /////////////////////////////////////////////////////////////////////////////// #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) // #included from: internal/catch_context.h #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED // #included from: catch_interfaces_generators.h #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED #include <string> namespace Catch { struct IGeneratorInfo { virtual ~IGeneratorInfo(); virtual bool moveNext() = 0; virtual std::size_t getCurrentIndex() const = 0; }; struct IGeneratorsForTest { virtual ~IGeneratorsForTest(); virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; virtual bool moveNext() = 0; }; IGeneratorsForTest* createGeneratorsForTest(); } // end namespace Catch // #included from: catch_ptr.hpp #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { // An intrusive reference counting smart pointer. // T must implement addRef() and release() methods // typically implementing the IShared interface template<typename T> class Ptr { public: Ptr() : m_p( CATCH_NULL ){} Ptr( T* p ) : m_p( p ){ if( m_p ) m_p->addRef(); } Ptr( Ptr const& other ) : m_p( other.m_p ){ if( m_p ) m_p->addRef(); } ~Ptr(){ if( m_p ) m_p->release(); } void reset() { if( m_p ) m_p->release(); m_p = CATCH_NULL; } Ptr& operator = ( T* p ){ Ptr temp( p ); swap( temp ); return *this; } Ptr& operator = ( Ptr const& other ){ Ptr temp( other ); swap( temp ); return *this; } void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } T* get() const{ return m_p; } T& operator*() const { return *m_p; } T* operator->() const { return m_p; } bool operator !() const { return m_p == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); } private: T* m_p; }; struct IShared : NonCopyable { virtual ~IShared(); virtual void addRef() const = 0; virtual void release() const = 0; }; template<typename T = IShared> struct SharedImpl : T { SharedImpl() : m_rc( 0 ){} virtual void addRef() const { ++m_rc; } virtual void release() const { if( --m_rc == 0 ) delete this; } mutable unsigned int m_rc; }; } // end namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif #include <memory> #include <vector> #include <stdlib.h> namespace Catch { class TestCase; class Stream; struct IResultCapture; struct IRunner; struct IGeneratorsForTest; struct IConfig; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; virtual bool advanceGeneratorsForCurrentTest() = 0; virtual Ptr<IConfig const> getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( Ptr<IConfig const> const& config ) = 0; }; IContext& getCurrentContext(); IMutableContext& getCurrentMutableContext(); void cleanUpContext(); Stream createStream( std::string const& streamName ); } // #included from: internal/catch_test_registry.hpp #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED // #included from: catch_interfaces_testcase.h #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED #include <vector> namespace Catch { class TestSpec; struct ITestCase : IShared { virtual void invoke () const = 0; protected: virtual ~ITestCase(); }; class TestCase; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector<TestCase> const& getAllTests() const = 0; virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); } namespace Catch { template<typename C> class MethodTestCase : public SharedImpl<ITestCase> { public: MethodTestCase( void (C::*method)() ) : m_method( method ) {} virtual void invoke() const { C obj; (obj.*m_method)(); } private: virtual ~MethodTestCase() {} void (C::*m_method)(); }; typedef void(*TestFunction)(); struct NameAndDesc { NameAndDesc( const char* _name = "", const char* _description= "" ) : name( _name ), description( _description ) {} const char* name; const char* description; }; void registerTestCase ( ITestCase* testCase, char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ); struct AutoReg { AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); template<typename C> AutoReg ( void (C::*method)(), char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { registerTestCase ( new MethodTestCase<C>( method ), className, nameAndDesc, lineInfo ); } ~AutoReg(); private: AutoReg( AutoReg const& ); void operator= ( AutoReg const& ); }; void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ namespace{ \ struct TestName : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ } \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); #else /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \ static void TestName(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ static void TestName() #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\ namespace{ \ struct TestCaseName : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ } \ void TestCaseName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); #endif // #included from: internal/catch_capture.hpp #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED // #included from: catch_result_builder.h #define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED // #included from: catch_result_type.h #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; inline bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } inline bool isJustInfo( int flags ) { return flags == ResultWas::Info; } // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) ); } inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch // #included from: catch_assertionresult.h #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED #include <string> namespace Catch { struct AssertionInfo { AssertionInfo() {} AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ); std::string macroName; SourceLineInfo lineInfo; std::string capturedExpression; ResultDisposition::Flags resultDisposition; }; struct AssertionResultData { AssertionResultData() : resultType( ResultWas::Unknown ) {} std::string reconstructedExpression; std::string message; ResultWas::OfType resultType; }; class AssertionResult { public: AssertionResult(); AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); ~AssertionResult(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionResult( AssertionResult const& ) = default; AssertionResult( AssertionResult && ) = default; AssertionResult& operator = ( AssertionResult const& ) = default; AssertionResult& operator = ( AssertionResult && ) = default; # endif bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; std::string getTestMacroName() const; protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch // #included from: catch_matchers.hpp #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED namespace Catch { namespace Matchers { namespace Impl { namespace Generic { template<typename ExpressionT> class AllOf; template<typename ExpressionT> class AnyOf; template<typename ExpressionT> class Not; } template<typename ExpressionT> struct Matcher : SharedImpl<IShared> { typedef ExpressionT ExpressionType; virtual ~Matcher() {} virtual Ptr<Matcher> clone() const = 0; virtual bool match( ExpressionT const& expr ) const = 0; virtual std::string toString() const = 0; Generic::AllOf<ExpressionT> operator && ( Matcher<ExpressionT> const& other ) const; Generic::AnyOf<ExpressionT> operator || ( Matcher<ExpressionT> const& other ) const; Generic::Not<ExpressionT> operator ! () const; }; template<typename DerivedT, typename ExpressionT> struct MatcherImpl : Matcher<ExpressionT> { virtual Ptr<Matcher<ExpressionT> > clone() const { return Ptr<Matcher<ExpressionT> >( new DerivedT( static_cast<DerivedT const&>( *this ) ) ); } }; namespace Generic { template<typename ExpressionT> class Not : public MatcherImpl<Not<ExpressionT>, ExpressionT> { public: explicit Not( Matcher<ExpressionT> const& matcher ) : m_matcher(matcher.clone()) {} Not( Not const& other ) : m_matcher( other.m_matcher ) {} virtual bool match( ExpressionT const& expr ) const CATCH_OVERRIDE { return !m_matcher->match( expr ); } virtual std::string toString() const CATCH_OVERRIDE { return "not " + m_matcher->toString(); } private: Ptr< Matcher<ExpressionT> > m_matcher; }; template<typename ExpressionT> class AllOf : public MatcherImpl<AllOf<ExpressionT>, ExpressionT> { public: AllOf() {} AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} AllOf& add( Matcher<ExpressionT> const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( !m_matchers[i]->match( expr ) ) return false; return true; } virtual std::string toString() const { std::ostringstream oss; oss << "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << " and "; oss << m_matchers[i]->toString(); } oss << " )"; return oss.str(); } AllOf operator && ( Matcher<ExpressionT> const& other ) const { AllOf allOfExpr( *this ); allOfExpr.add( other ); return allOfExpr; } private: std::vector<Ptr<Matcher<ExpressionT> > > m_matchers; }; template<typename ExpressionT> class AnyOf : public MatcherImpl<AnyOf<ExpressionT>, ExpressionT> { public: AnyOf() {} AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} AnyOf& add( Matcher<ExpressionT> const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( m_matchers[i]->match( expr ) ) return true; return false; } virtual std::string toString() const { std::ostringstream oss; oss << "( "; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << " or "; oss << m_matchers[i]->toString(); } oss << " )"; return oss.str(); } AnyOf operator || ( Matcher<ExpressionT> const& other ) const { AnyOf anyOfExpr( *this ); anyOfExpr.add( other ); return anyOfExpr; } private: std::vector<Ptr<Matcher<ExpressionT> > > m_matchers; }; } // namespace Generic template<typename ExpressionT> Generic::AllOf<ExpressionT> Matcher<ExpressionT>::operator && ( Matcher<ExpressionT> const& other ) const { Generic::AllOf<ExpressionT> allOfExpr; allOfExpr.add( *this ); allOfExpr.add( other ); return allOfExpr; } template<typename ExpressionT> Generic::AnyOf<ExpressionT> Matcher<ExpressionT>::operator || ( Matcher<ExpressionT> const& other ) const { Generic::AnyOf<ExpressionT> anyOfExpr; anyOfExpr.add( *this ); anyOfExpr.add( other ); return anyOfExpr; } template<typename ExpressionT> Generic::Not<ExpressionT> Matcher<ExpressionT>::operator ! () const { return Generic::Not<ExpressionT>( *this ); } namespace StdString { inline std::string makeString( std::string const& str ) { return str; } inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } struct CasedString { CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_str( adjustString( str ) ) {} std::string adjustString( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } std::string toStringSuffix() const { return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : ""; } CaseSensitive::Choice m_caseSensitivity; std::string m_str; }; struct Equals : MatcherImpl<Equals, std::string> { Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( str, caseSensitivity ) {} Equals( Equals const& other ) : m_data( other.m_data ){} virtual ~Equals(); virtual bool match( std::string const& expr ) const { return m_data.m_str == m_data.adjustString( expr );; } virtual std::string toString() const { return "equals: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct Contains : MatcherImpl<Contains, std::string> { Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} Contains( Contains const& other ) : m_data( other.m_data ){} virtual ~Contains(); virtual bool match( std::string const& expr ) const { return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos; } virtual std::string toString() const { return "contains: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct StartsWith : MatcherImpl<StartsWith, std::string> { StartsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} StartsWith( StartsWith const& other ) : m_data( other.m_data ){} virtual ~StartsWith(); virtual bool match( std::string const& expr ) const { return startsWith( m_data.adjustString( expr ), m_data.m_str ); } virtual std::string toString() const { return "starts with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; struct EndsWith : MatcherImpl<EndsWith, std::string> { EndsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} EndsWith( EndsWith const& other ) : m_data( other.m_data ){} virtual ~EndsWith(); virtual bool match( std::string const& expr ) const { return endsWith( m_data.adjustString( expr ), m_data.m_str ); } virtual std::string toString() const { return "ends with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); } CasedString m_data; }; } // namespace StdString } // namespace Impl // The following functions create the actual matcher objects. // This allows the types to be inferred template<typename ExpressionT> inline Impl::Generic::Not<ExpressionT> Not( Impl::Matcher<ExpressionT> const& m ) { return Impl::Generic::Not<ExpressionT>( m ); } template<typename ExpressionT> inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2 ) { return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ); } template<typename ExpressionT> inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2, Impl::Matcher<ExpressionT> const& m3 ) { return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 ); } template<typename ExpressionT> inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2 ) { return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ); } template<typename ExpressionT> inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1, Impl::Matcher<ExpressionT> const& m2, Impl::Matcher<ExpressionT> const& m3 ) { return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 ); } inline Impl::StdString::Equals Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( str, caseSensitivity ); } inline Impl::StdString::Equals Equals( const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( Impl::StdString::makeString( str ), caseSensitivity ); } inline Impl::StdString::Contains Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( substr, caseSensitivity ); } inline Impl::StdString::Contains Contains( const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( Impl::StdString::makeString( substr ), caseSensitivity ); } inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { return Impl::StdString::StartsWith( substr ); } inline Impl::StdString::StartsWith StartsWith( const char* substr ) { return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); } inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { return Impl::StdString::EndsWith( substr ); } inline Impl::StdString::EndsWith EndsWith( const char* substr ) { return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); } } // namespace Matchers using namespace Matchers; } // namespace Catch namespace Catch { struct TestFailureException{}; template<typename T> class ExpressionLhs; struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; struct CopyableStream { CopyableStream() {} CopyableStream( CopyableStream const& other ) { oss << other.oss.str(); } CopyableStream& operator=( CopyableStream const& other ) { oss.str(""); oss << other.oss.str(); return *this; } std::ostringstream oss; }; class ResultBuilder { public: ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg = "" ); template<typename T> ExpressionLhs<T const&> operator <= ( T const& operand ); ExpressionLhs<bool> operator <= ( bool value ); template<typename T> ResultBuilder& operator << ( T const& value ) { m_stream.oss << value; return *this; } template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); ResultBuilder& setResultType( ResultWas::OfType result ); ResultBuilder& setResultType( bool result ); ResultBuilder& setLhs( std::string const& lhs ); ResultBuilder& setRhs( std::string const& rhs ); ResultBuilder& setOp( std::string const& op ); void endExpression(); std::string reconstructExpression() const; AssertionResult build() const; void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); void captureResult( ResultWas::OfType resultType ); void captureExpression(); void captureExpectedException( std::string const& expectedMessage ); void captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ); void handleResult( AssertionResult const& result ); void react(); bool shouldDebugBreak() const; bool allowThrows() const; private: AssertionInfo m_assertionInfo; AssertionResultData m_data; struct ExprComponents { ExprComponents() : testFalse( false ) {} bool testFalse; std::string lhs, rhs, op; } m_exprComponents; CopyableStream m_stream; bool m_shouldDebugBreak; bool m_shouldThrow; }; } // namespace Catch // Include after due to circular dependency: // #included from: catch_expression_lhs.hpp #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED // #included from: catch_evaluate.hpp #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #endif #include <cstddef> namespace Catch { namespace Internal { enum Operator { IsEqualTo, IsNotEqualTo, IsLessThan, IsGreaterThan, IsLessThanOrEqualTo, IsGreaterThanOrEqualTo }; template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } }; template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } }; template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } }; template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } }; template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } }; template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } }; template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } }; template<typename T> inline T& opCast(T const& t) { return const_cast<T&>(t); } // nullptr_t support based on pull request #154 from Konstantin Baumann #ifdef CATCH_CONFIG_CPP11_NULLPTR inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } #endif // CATCH_CONFIG_CPP11_NULLPTR // So the compare overloads can be operator agnostic we convey the operator as a template // enum, which is used to specialise an Evaluator for doing the comparison. template<typename T1, typename T2, Operator Op> class Evaluator{}; template<typename T1, typename T2> struct Evaluator<T1, T2, IsEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs) { return bool( opCast( lhs ) == opCast( rhs ) ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsNotEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) != opCast( rhs ) ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsLessThan> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) < opCast( rhs ) ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsGreaterThan> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) > opCast( rhs ) ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) >= opCast( rhs ) ); } }; template<typename T1, typename T2> struct Evaluator<T1, T2, IsLessThanOrEqualTo> { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) <= opCast( rhs ) ); } }; template<Operator Op, typename T1, typename T2> bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { return Evaluator<T1, T2, Op>::evaluate( lhs, rhs ); } // This level of indirection allows us to specialise for integer types // to avoid signed/ unsigned warnings // "base" overload template<Operator Op, typename T1, typename T2> bool compare( T1 const& lhs, T2 const& rhs ) { return Evaluator<T1, T2, Op>::evaluate( lhs, rhs ); } // unsigned X to int template<Operator Op> bool compare( unsigned int lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } template<Operator Op> bool compare( unsigned long lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } template<Operator Op> bool compare( unsigned char lhs, int rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) ); } // unsigned X to long template<Operator Op> bool compare( unsigned int lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } template<Operator Op> bool compare( unsigned long lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } template<Operator Op> bool compare( unsigned char lhs, long rhs ) { return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) ); } // int to unsigned X template<Operator Op> bool compare( int lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } template<Operator Op> bool compare( int lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } template<Operator Op> bool compare( int lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs ); } // long to unsigned X template<Operator Op> bool compare( long lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } // pointer to long (when comparing against NULL) template<Operator Op, typename T> bool compare( long lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, long rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } // pointer to int (when comparing against NULL) template<Operator Op, typename T> bool compare( int lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, int rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG // long long to unsigned X template<Operator Op> bool compare( long long lhs, unsigned int rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned long long rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } template<Operator Op> bool compare( long long lhs, unsigned char rhs ) { return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs ); } // unsigned long long to X template<Operator Op> bool compare( unsigned long long lhs, int rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, long rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, long long rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } template<Operator Op> bool compare( unsigned long long lhs, char rhs ) { return applyEvaluator<Op>( static_cast<long>( lhs ), rhs ); } // pointer to long long (when comparing against NULL) template<Operator Op, typename T> bool compare( long long lhs, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs ); } template<Operator Op, typename T> bool compare( T* lhs, long long rhs ) { return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) ); } #endif // CATCH_CONFIG_CPP11_LONG_LONG #ifdef CATCH_CONFIG_CPP11_NULLPTR // pointer to nullptr_t (when comparing against nullptr) template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) { return Evaluator<T*, T*, Op>::evaluate( nullptr, rhs ); } template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) { return Evaluator<T*, T*, Op>::evaluate( lhs, nullptr ); } #endif // CATCH_CONFIG_CPP11_NULLPTR } // end of namespace Internal } // end of namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif // #included from: catch_tostring.h #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED #include <sstream> #include <iomanip> #include <limits> #include <vector> #include <cstddef> #ifdef __OBJC__ // #included from: catch_objc_arc.hpp #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED #import <Foundation/Foundation.h> #ifdef __has_feature #define CATCH_ARC_ENABLED __has_feature(objc_arc) #else #define CATCH_ARC_ENABLED 0 #endif void arcSafeRelease( NSObject* obj ); id performOptionalSelector( id obj, SEL sel ); #if !CATCH_ARC_ENABLED inline void arcSafeRelease( NSObject* obj ) { [obj release]; } inline id performOptionalSelector( id obj, SEL sel ) { if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else inline void arcSafeRelease( NSObject* ){} inline id performOptionalSelector( id obj, SEL sel ) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" #endif if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif return nil; } #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained #define CATCH_ARC_STRONG __strong #endif #endif #ifdef CATCH_CONFIG_CPP11_TUPLE #include <tuple> #endif #ifdef CATCH_CONFIG_CPP11_IS_ENUM #include <type_traits> #endif namespace Catch { // Why we're here. template<typename T> std::string toString( T const& value ); // Built in overloads std::string toString( std::string const& value ); std::string toString( std::wstring const& value ); std::string toString( const char* const value ); std::string toString( char* const value ); std::string toString( const wchar_t* const value ); std::string toString( wchar_t* const value ); std::string toString( int value ); std::string toString( unsigned long value ); std::string toString( unsigned int value ); std::string toString( const double value ); std::string toString( const float value ); std::string toString( bool value ); std::string toString( char value ); std::string toString( signed char value ); std::string toString( unsigned char value ); #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ); std::string toString( unsigned long long value ); #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ); #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ); std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); std::string toString( NSObject* const& nsObject ); #endif namespace Detail { extern const std::string unprintableString; struct BorgType { template<typename T> BorgType( T const& ); }; struct TrueType { char sizer[1]; }; struct FalseType { char sizer[2]; }; TrueType& testStreamable( std::ostream& ); FalseType testStreamable( FalseType ); FalseType operator<<( std::ostream const&, BorgType const& ); template<typename T> struct IsStreamInsertable { static std::ostream &s; static T const&t; enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; }; #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template<typename T, bool IsEnum = std::is_enum<T>::value > struct EnumStringMaker { static std::string convert( T const& ) { return unprintableString; } }; template<typename T> struct EnumStringMaker<T,true> { static std::string convert( T const& v ) { return ::Catch::toString( static_cast<typename std::underlying_type<T>::type>(v) ); } }; #endif template<bool C> struct StringMakerBase { #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template<typename T> static std::string convert( T const& v ) { return EnumStringMaker<T>::convert( v ); } #else template<typename T> static std::string convert( T const& ) { return unprintableString; } #endif }; template<> struct StringMakerBase<true> { template<typename T> static std::string convert( T const& _value ) { std::ostringstream oss; oss << _value; return oss.str(); } }; std::string rawMemoryToString( const void *object, std::size_t size ); template<typename T> inline std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } } // end namespace Detail template<typename T> struct StringMaker : Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {}; template<typename T> struct StringMaker<T*> { template<typename U> static std::string convert( U* p ) { if( !p ) return "NULL"; else return Detail::rawMemoryToString( p ); } }; template<typename R, typename C> struct StringMaker<R C::*> { static std::string convert( R C::* p ) { if( !p ) return "NULL"; else return Detail::rawMemoryToString( p ); } }; namespace Detail { template<typename InputIterator> std::string rangeToString( InputIterator first, InputIterator last ); } //template<typename T, typename Allocator> //struct StringMaker<std::vector<T, Allocator> > { // static std::string convert( std::vector<T,Allocator> const& v ) { // return Detail::rangeToString( v.begin(), v.end() ); // } //}; template<typename T, typename Allocator> std::string toString( std::vector<T,Allocator> const& v ) { return Detail::rangeToString( v.begin(), v.end() ); } #ifdef CATCH_CONFIG_CPP11_TUPLE // toString for tuples namespace TupleDetail { template< typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value) > struct ElementPrinter { static void print( const Tuple& tuple, std::ostream& os ) { os << ( N ? ", " : " " ) << Catch::toString(std::get<N>(tuple)); ElementPrinter<Tuple,N+1>::print(tuple,os); } }; template< typename Tuple, std::size_t N > struct ElementPrinter<Tuple,N,false> { static void print( const Tuple&, std::ostream& ) {} }; } template<typename ...Types> struct StringMaker<std::tuple<Types...>> { static std::string convert( const std::tuple<Types...>& tuple ) { std::ostringstream os; os << '{'; TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os ); os << " }"; return os.str(); } }; #endif // CATCH_CONFIG_CPP11_TUPLE namespace Detail { template<typename T> std::string makeString( T const& value ) { return StringMaker<T>::convert( value ); } } // end namespace Detail /// \brief converts any type to a string /// /// The default template forwards on to ostringstream - except when an /// ostringstream overload does not exist - in which case it attempts to detect /// that and writes {?}. /// Overload (not specialise) this template for custom typs that you don't want /// to provide an ostream overload for. template<typename T> std::string toString( T const& value ) { return StringMaker<T>::convert( value ); } namespace Detail { template<typename InputIterator> std::string rangeToString( InputIterator first, InputIterator last ) { std::ostringstream oss; oss << "{ "; if( first != last ) { oss << Catch::toString( *first ); for( ++first ; first != last ; ++first ) oss << ", " << Catch::toString( *first ); } oss << " }"; return oss.str(); } } } // end namespace Catch namespace Catch { // Wraps the LHS of an expression and captures the operator and RHS (if any) - // wrapping them all in a ResultBuilder object template<typename T> class ExpressionLhs { ExpressionLhs& operator = ( ExpressionLhs const& ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs& operator = ( ExpressionLhs && ) = delete; # endif public: ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs( ExpressionLhs const& ) = default; ExpressionLhs( ExpressionLhs && ) = default; # endif template<typename RhsT> ResultBuilder& operator == ( RhsT const& rhs ) { return captureExpression<Internal::IsEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator != ( RhsT const& rhs ) { return captureExpression<Internal::IsNotEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator < ( RhsT const& rhs ) { return captureExpression<Internal::IsLessThan>( rhs ); } template<typename RhsT> ResultBuilder& operator > ( RhsT const& rhs ) { return captureExpression<Internal::IsGreaterThan>( rhs ); } template<typename RhsT> ResultBuilder& operator <= ( RhsT const& rhs ) { return captureExpression<Internal::IsLessThanOrEqualTo>( rhs ); } template<typename RhsT> ResultBuilder& operator >= ( RhsT const& rhs ) { return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs ); } ResultBuilder& operator == ( bool rhs ) { return captureExpression<Internal::IsEqualTo>( rhs ); } ResultBuilder& operator != ( bool rhs ) { return captureExpression<Internal::IsNotEqualTo>( rhs ); } void endExpression() { bool value = m_lhs ? true : false; m_rb .setLhs( Catch::toString( value ) ) .setResultType( value ) .endExpression(); } // Only simple binary expressions are allowed on the LHS. // If more complex compositions are required then place the sub expression in parentheses template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); private: template<Internal::Operator Op, typename RhsT> ResultBuilder& captureExpression( RhsT const& rhs ) { return m_rb .setResultType( Internal::compare<Op>( m_lhs, rhs ) ) .setLhs( Catch::toString( m_lhs ) ) .setRhs( Catch::toString( rhs ) ) .setOp( Internal::OperatorTraits<Op>::getName() ); } private: ResultBuilder& m_rb; T m_lhs; }; } // end namespace Catch namespace Catch { template<typename T> inline ExpressionLhs<T const&> ResultBuilder::operator <= ( T const& operand ) { return ExpressionLhs<T const&>( *this, operand ); } inline ExpressionLhs<bool> ResultBuilder::operator <= ( bool value ) { return ExpressionLhs<bool>( *this, value ); } } // namespace Catch // #included from: catch_message.h #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED #include <string> namespace Catch { struct MessageInfo { MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); std::string macroName; SourceLineInfo lineInfo; ResultWas::OfType type; std::string message; unsigned int sequence; bool operator == ( MessageInfo const& other ) const { return sequence == other.sequence; } bool operator < ( MessageInfo const& other ) const { return sequence < other.sequence; } private: static unsigned int globalCount; }; struct MessageBuilder { MessageBuilder( std::string const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ) : m_info( macroName, lineInfo, type ) {} template<typename T> MessageBuilder& operator << ( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; std::ostringstream m_stream; }; class ScopedMessage { public: ScopedMessage( MessageBuilder const& builder ); ScopedMessage( ScopedMessage const& other ); ~ScopedMessage(); MessageInfo m_info; }; } // end namespace Catch // #included from: catch_interfaces_capture.h #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED #include <string> namespace Catch { class TestCase; class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; class ScopedMessageBuilder; struct Counts; struct IResultCapture { virtual ~IResultCapture(); virtual void assertionEnded( AssertionResult const& result ) = 0; virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void handleFatalErrorCondition( std::string const& message ) = 0; }; IResultCapture& getResultCapture(); } // #included from: catch_debugger.h #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED // #included from: catch_platform.h #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_MAC #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_IPHONE #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) #define CATCH_PLATFORM_WINDOWS #endif #include <string> namespace Catch{ bool isDebuggerActive(); void writeToDebugConsole( std::string const& text ); } #ifdef CATCH_PLATFORM_MAC // The following code snippet based on: // http://cocoawithlove.com/2008/03/break-into-debugger.html #ifdef DEBUG #if defined(__ppc64__) || defined(__ppc__) #define CATCH_BREAK_INTO_DEBUGGER() \ if( Catch::isDebuggerActive() ) { \ __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ : : : "memory","r0","r3","r4" ); \ } #else #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );} #endif #endif #elif defined(_MSC_VER) #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } #elif defined(__MINGW32__) extern "C" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } #endif #ifndef CATCH_BREAK_INTO_DEBUGGER #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); #endif // #included from: catch_interfaces_runner.h #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED namespace Catch { class TestCase; struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } /////////////////////////////////////////////////////////////////////////////// // In the event of a failure works out if the debugger needs to be invoked // and/or an exception thrown and takes appropriate action. // This needs to be done as a macro so the debugger will stop in the user // source code rather than in Catch library code #define INTERNAL_CATCH_REACT( resultBuilder ) \ if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ resultBuilder.react(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ ( __catchResult <= expr ).endExpression(); \ } \ catch( ... ) { \ __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::isTrue( false && static_cast<bool>(expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( !Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( expr, resultDisposition, matcher, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( ... ) { \ __catchResult.captureExpectedException( matcher ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( exceptionType ) { \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #else #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ __catchResult << log + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( log, macroName ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ try { \ std::string matcherAsString = (matcher).toString(); \ __catchResult \ .setLhs( Catch::toString( arg ) ) \ .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \ .setOp( "matches" ) \ .setResultType( (matcher).match( arg ) ); \ __catchResult.captureExpression(); \ } catch( ... ) { \ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) // #included from: internal/catch_section.h #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED // #included from: catch_section_info.h #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED // #included from: catch_totals.hpp #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED #include <cstddef> namespace Catch { struct Counts { Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} Counts operator - ( Counts const& other ) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; diff.failedButOk = failedButOk - other.failedButOk; return diff; } Counts& operator += ( Counts const& other ) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } std::size_t total() const { return passed + failed + failedButOk; } bool allPassed() const { return failed == 0 && failedButOk == 0; } bool allOk() const { return failed == 0; } std::size_t passed; std::size_t failed; std::size_t failedButOk; }; struct Totals { Totals operator - ( Totals const& other ) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } Totals delta( Totals const& prevTotals ) const { Totals diff = *this - prevTotals; if( diff.assertions.failed > 0 ) ++diff.testCases.failed; else if( diff.assertions.failedButOk > 0 ) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } Totals& operator += ( Totals const& other ) { assertions += other.assertions; testCases += other.testCases; return *this; } Counts assertions; Counts testCases; }; } namespace Catch { struct SectionInfo { SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description = std::string() ); std::string name; std::string description; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) {} SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch // #included from: catch_timer.h #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED #ifdef CATCH_PLATFORM_WINDOWS typedef unsigned long long uint64_t; #else #include <stdint.h> #endif namespace Catch { class Timer { public: Timer() : m_ticks( 0 ) {} void start(); unsigned int getElapsedMicroseconds() const; unsigned int getElapsedMilliseconds() const; double getElapsedSeconds() const; private: uint64_t m_ticks; }; } // namespace Catch #include <string> namespace Catch { class Section : NonCopyable { public: Section( SectionInfo const& info ); ~Section(); // This indicates whether the section should be executed or not operator bool() const; private: SectionInfo m_info; std::string m_name; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_SECTION( ... ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) #else #define INTERNAL_CATCH_SECTION( name, desc ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) #endif // #included from: internal/catch_generators.hpp #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED #include <iterator> #include <vector> #include <string> #include <stdlib.h> namespace Catch { template<typename T> struct IGenerator { virtual ~IGenerator() {} virtual T getValue( std::size_t index ) const = 0; virtual std::size_t size () const = 0; }; template<typename T> class BetweenGenerator : public IGenerator<T> { public: BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} virtual T getValue( std::size_t index ) const { return m_from+static_cast<int>( index ); } virtual std::size_t size() const { return static_cast<std::size_t>( 1+m_to-m_from ); } private: T m_from; T m_to; }; template<typename T> class ValuesGenerator : public IGenerator<T> { public: ValuesGenerator(){} void add( T value ) { m_values.push_back( value ); } virtual T getValue( std::size_t index ) const { return m_values[index]; } virtual std::size_t size() const { return m_values.size(); } private: std::vector<T> m_values; }; template<typename T> class CompositeGenerator { public: CompositeGenerator() : m_totalSize( 0 ) {} // *** Move semantics, similar to auto_ptr *** CompositeGenerator( CompositeGenerator& other ) : m_fileInfo( other.m_fileInfo ), m_totalSize( 0 ) { move( other ); } CompositeGenerator& setFileInfo( const char* fileInfo ) { m_fileInfo = fileInfo; return *this; } ~CompositeGenerator() { deleteAll( m_composed ); } operator T () const { size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin(); typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end(); for( size_t index = 0; it != itEnd; ++it ) { const IGenerator<T>* generator = *it; if( overallIndex >= index && overallIndex < index + generator->size() ) { return generator->getValue( overallIndex-index ); } index += generator->size(); } CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so } void add( const IGenerator<T>* generator ) { m_totalSize += generator->size(); m_composed.push_back( generator ); } CompositeGenerator& then( CompositeGenerator& other ) { move( other ); return *this; } CompositeGenerator& then( T value ) { ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( value ); add( valuesGen ); return *this; } private: void move( CompositeGenerator& other ) { std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); m_totalSize += other.m_totalSize; other.m_composed.clear(); } std::vector<const IGenerator<T>*> m_composed; std::string m_fileInfo; size_t m_totalSize; }; namespace Generators { template<typename T> CompositeGenerator<T> between( T from, T to ) { CompositeGenerator<T> generators; generators.add( new BetweenGenerator<T>( from, to ) ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3 ){ CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); generators.add( valuesGen ); return generators; } template<typename T> CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) { CompositeGenerator<T> generators; ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); valuesGen->add( val4 ); generators.add( valuesGen ); return generators; } } // end namespace Generators using namespace Generators; } // end namespace Catch #define INTERNAL_CATCH_LINESTR2( line ) #line #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) // #included from: internal/catch_interfaces_exception.h #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED #include <string> #include <vector> // #included from: catch_interfaces_registry_hub.h #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED #include <string> namespace Catch { class TestCase; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) = 0; virtual void registerListener( Ptr<IReporterFactory> const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; }; IRegistryHub& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } namespace Catch { typedef std::string(*exceptionTranslateFunction)(); struct IExceptionTranslator; typedef std::vector<const IExceptionTranslator*> ExceptionTranslators; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; class ExceptionTranslatorRegistrar { template<typename T> class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string(*translateFunction)( T& ) ) : m_translateFunction( translateFunction ) {} virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE { try { if( it == itEnd ) throw; else return (*it)->translate( it+1, itEnd ); } catch( T& ex ) { return m_translateFunction( ex ); } } protected: std::string(*m_translateFunction)( T& ); }; public: template<typename T> ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { getMutableRegistryHub().registerTranslator ( new ExceptionTranslator<T>( translateFunction ) ); } }; } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ static std::string translatorName( signature ); \ namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\ static std::string translatorName( signature ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // #included from: internal/catch_approx.hpp #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED #include <cmath> #include <limits> namespace Catch { namespace Detail { class Approx { public: explicit Approx ( double value ) : m_epsilon( std::numeric_limits<float>::epsilon()*100 ), m_scale( 1.0 ), m_value( value ) {} Approx( Approx const& other ) : m_epsilon( other.m_epsilon ), m_scale( other.m_scale ), m_value( other.m_value ) {} static Approx custom() { return Approx( 0 ); } Approx operator()( double value ) { Approx approx( value ); approx.epsilon( m_epsilon ); approx.scale( m_scale ); return approx; } friend bool operator == ( double lhs, Approx const& rhs ) { // Thanks to Richard Harris for his help refining this formula return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); } friend bool operator == ( Approx const& lhs, double rhs ) { return operator==( rhs, lhs ); } friend bool operator != ( double lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } friend bool operator != ( Approx const& lhs, double rhs ) { return !operator==( rhs, lhs ); } Approx& epsilon( double newEpsilon ) { m_epsilon = newEpsilon; return *this; } Approx& scale( double newScale ) { m_scale = newScale; return *this; } std::string toString() const { std::ostringstream oss; oss << "Approx( " << Catch::toString( m_value ) << " )"; return oss.str(); } private: double m_epsilon; double m_scale; double m_value; }; } template<> inline std::string toString<Detail::Approx>( Detail::Approx const& value ) { return value.toString(); } } // end namespace Catch // #included from: internal/catch_interfaces_tag_alias_registry.h #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED // #included from: catch_tag_alias.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED #include <string> namespace Catch { struct TagAlias { TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} std::string tag; SourceLineInfo lineInfo; }; struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } // #included from: catch_option.hpp #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED namespace Catch { // An optional type template<typename T> class Option { public: Option() : nullableValue( CATCH_NULL ) {} Option( T const& _value ) : nullableValue( new( storage ) T( _value ) ) {} Option( Option const& _other ) : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL ) {} ~Option() { reset(); } Option& operator= ( Option const& _other ) { if( &_other != this ) { reset(); if( _other ) nullableValue = new( storage ) T( *_other ); } return *this; } Option& operator = ( T const& _value ) { reset(); nullableValue = new( storage ) T( _value ); return *this; } void reset() { if( nullableValue ) nullableValue->~T(); nullableValue = CATCH_NULL; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != CATCH_NULL; } bool none() const { return nullableValue == CATCH_NULL; } bool operator !() const { return nullableValue == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( some() ); } private: T* nullableValue; char storage[sizeof(T)]; }; } // end namespace Catch namespace Catch { struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); virtual Option<TagAlias> find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections // #included from: internal/catch_test_case_info.h #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED #include <string> #include <set> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct ITestCase; struct TestCaseInfo { enum SpecialProperties{ None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4 }; TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set<std::string> const& _tags, SourceLineInfo const& _lineInfo ); TestCaseInfo( TestCaseInfo const& other ); friend void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags ); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; std::string name; std::string className; std::string description; std::set<std::string> tags; std::set<std::string> lcaseTags; std::string tagsAsString; SourceLineInfo lineInfo; SpecialProperties properties; }; class TestCase : public TestCaseInfo { public: TestCase( ITestCase* testCase, TestCaseInfo const& info ); TestCase( TestCase const& other ); TestCase withName( std::string const& _newName ) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; void swap( TestCase& other ); bool operator == ( TestCase const& other ) const; bool operator < ( TestCase const& other ) const; TestCase& operator = ( TestCase const& other ); private: Ptr<ITestCase> test; }; TestCase makeTestCase( ITestCase* testCase, std::string const& className, std::string const& name, std::string const& description, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __OBJC__ // #included from: internal/catch_objc.hpp #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED #import <objc/runtime.h> #include <string> // NB. Any general catch headers included here must be included // in catch.hpp first to make sure they are included by the single // header for non obj-usage /////////////////////////////////////////////////////////////////////////////// // This protocol is really only here for (self) documenting purposes, since // all its methods are optional. @protocol OcFixture @optional -(void) setUp; -(void) tearDown; @end namespace Catch { class OcMethod : public SharedImpl<ITestCase> { public: OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} virtual void invoke() const { id obj = [[m_cls alloc] init]; performOptionalSelector( obj, @selector(setUp) ); performOptionalSelector( obj, m_sel ); performOptionalSelector( obj, @selector(tearDown) ); arcSafeRelease( obj ); } private: virtual ~OcMethod() {} Class m_cls; SEL m_sel; }; namespace Detail{ inline std::string getAnnotation( Class cls, std::string const& annotationName, std::string const& testCaseName ) { NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; SEL sel = NSSelectorFromString( selStr ); arcSafeRelease( selStr ); id value = performOptionalSelector( cls, sel ); if( value ) return [(NSString*)value UTF8String]; return ""; } } inline size_t registerTestMethods() { size_t noTestMethods = 0; int noClasses = objc_getClassList( CATCH_NULL, 0 ); Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); objc_getClassList( classes, noClasses ); for( int c = 0; c < noClasses; c++ ) { Class cls = classes[c]; { u_int count; Method* methods = class_copyMethodList( cls, &count ); for( u_int m = 0; m < count ; m++ ) { SEL selector = method_getName(methods[m]); std::string methodName = sel_getName(selector); if( startsWith( methodName, "Catch_TestCase_" ) ) { std::string testCaseName = methodName.substr( 15 ); std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); const char* className = class_getName( cls ); getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); noTestMethods++; } } free(methods); } } return noTestMethods; } namespace Matchers { namespace Impl { namespace NSStringMatchers { template<typename MatcherT> struct StringHolder : MatcherImpl<MatcherT, NSString*>{ StringHolder( NSString* substr ) : m_substr( [substr copy] ){} StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} StringHolder() { arcSafeRelease( m_substr ); } NSString* m_substr; }; struct Equals : StringHolder<Equals> { Equals( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } virtual std::string toString() const { return "equals string: " + Catch::toString( m_substr ); } }; struct Contains : StringHolder<Contains> { Contains( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } virtual std::string toString() const { return "contains string: " + Catch::toString( m_substr ); } }; struct StartsWith : StringHolder<StartsWith> { StartsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } virtual std::string toString() const { return "starts with: " + Catch::toString( m_substr ); } }; struct EndsWith : StringHolder<EndsWith> { EndsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } virtual std::string toString() const { return "ends with: " + Catch::toString( m_substr ); } }; } // namespace NSStringMatchers } // namespace Impl inline Impl::NSStringMatchers::Equals Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } inline Impl::NSStringMatchers::Contains Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } inline Impl::NSStringMatchers::StartsWith StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } inline Impl::NSStringMatchers::EndsWith EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } } // namespace Matchers using namespace Matchers; } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define OC_TEST_CASE( name, desc )\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ {\ return @ name; \ }\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ { \ return @ desc; \ } \ -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) #endif #ifdef CATCH_IMPL // #included from: internal/catch_impl.hpp #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED // Collect all the implementation files together here // These are the equivalent of what would usually be cpp files #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #endif // #included from: ../catch_session.hpp #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED // #included from: internal/catch_commandline.hpp #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED // #included from: catch_config.hpp #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED // #included from: catch_test_spec_parser.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // #included from: catch_test_spec.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // #included from: catch_wildcard_pattern.hpp #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_wildcard( NoWildcard ), m_pattern( adjustCase( pattern ) ) { if( startsWith( m_pattern, "*" ) ) { m_pattern = m_pattern.substr( 1 ); m_wildcard = WildcardAtStart; } if( endsWith( m_pattern, "*" ) ) { m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); } } virtual ~WildcardPattern(); virtual bool matches( std::string const& str ) const { switch( m_wildcard ) { case NoWildcard: return m_pattern == adjustCase( str ); case WildcardAtStart: return endsWith( adjustCase( str ), m_pattern ); case WildcardAtEnd: return startsWith( adjustCase( str ), m_pattern ); case WildcardAtBothEnds: return contains( adjustCase( str ), m_pattern ); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #endif throw std::logic_error( "Unknown enum" ); #ifdef __clang__ #pragma clang diagnostic pop #endif } private: std::string adjustCase( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard; std::string m_pattern; }; } #include <string> #include <vector> namespace Catch { class TestSpec { struct Pattern : SharedImpl<> { virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; }; class NamePattern : public Pattern { public: NamePattern( std::string const& name ) : m_wildcardPattern( toLower( name ), CaseSensitive::No ) {} virtual ~NamePattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return m_wildcardPattern.matches( toLower( testCase.name ) ); } private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} virtual ~TagPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); } private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: ExcludedPattern( Ptr<Pattern> const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} virtual ~ExcludedPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } private: Ptr<Pattern> m_underlyingPattern; }; struct Filter { std::vector<Ptr<Pattern> > m_patterns; bool matches( TestCaseInfo const& testCase ) const { // All patterns in a filter must match for the filter to be a match for( std::vector<Ptr<Pattern> >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) if( !(*it)->matches( testCase ) ) return false; return true; } }; public: bool hasFilters() const { return !m_filters.empty(); } bool matches( TestCaseInfo const& testCase ) const { // A TestSpec matches if any filter matches for( std::vector<Filter>::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) if( it->matches( testCase ) ) return true; return false; } private: std::vector<Filter> m_filters; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif namespace Catch { class TestSpecParser { enum Mode{ None, Name, QuotedName, Tag }; Mode m_mode; bool m_exclusion; std::size_t m_start, m_pos; std::string m_arg; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases; public: TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} TestSpecParser& parse( std::string const& arg ) { m_mode = None; m_exclusion = false; m_start = std::string::npos; m_arg = m_tagAliases->expandAliases( arg ); for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) visitChar( m_arg[m_pos] ); if( m_mode == Name ) addPattern<TestSpec::NamePattern>(); return *this; } TestSpec testSpec() { addFilter(); return m_testSpec; } private: void visitChar( char c ) { if( m_mode == None ) { switch( c ) { case ' ': return; case '~': m_exclusion = true; return; case '[': return startNewMode( Tag, ++m_pos ); case '"': return startNewMode( QuotedName, ++m_pos ); default: startNewMode( Name, m_pos ); break; } } if( m_mode == Name ) { if( c == ',' ) { addPattern<TestSpec::NamePattern>(); addFilter(); } else if( c == '[' ) { if( subString() == "exclude:" ) m_exclusion = true; else addPattern<TestSpec::NamePattern>(); startNewMode( Tag, ++m_pos ); } } else if( m_mode == QuotedName && c == '"' ) addPattern<TestSpec::NamePattern>(); else if( m_mode == Tag && c == ']' ) addPattern<TestSpec::TagPattern>(); } void startNewMode( Mode mode, std::size_t start ) { m_mode = mode; m_start = start; } std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } template<typename T> void addPattern() { std::string token = subString(); if( startsWith( token, "exclude:" ) ) { m_exclusion = true; token = token.substr( 8 ); } if( !token.empty() ) { Ptr<TestSpec::Pattern> pattern = new T( token ); if( m_exclusion ) pattern = new TestSpec::ExcludedPattern( pattern ); m_currentFilter.m_patterns.push_back( pattern ); } m_exclusion = false; m_mode = None; } void addFilter() { if( !m_currentFilter.m_patterns.empty() ) { m_testSpec.m_filters.push_back( m_currentFilter ); m_currentFilter = TestSpec::Filter(); } } }; inline TestSpec parseTestSpec( std::string const& arg ) { return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_interfaces_config.h #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED #include <iostream> #include <string> #include <vector> namespace Catch { struct Verbosity { enum Level { NoOutput = 0, Quiet, Normal }; }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01 }; }; struct ShowDurations { enum OrNot { DefaultForReporter, Always, Never }; }; struct RunTests { enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder }; }; struct UseColour { enum YesOrNo { Auto, Yes, No }; }; class TestSpec; struct IConfig : IShared { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations::OrNot showDurations() const = 0; virtual TestSpec const& testSpec() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual UseColour::YesOrNo useColour() const = 0; }; } // #included from: catch_stream.h #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED // #included from: catch_streambuf.h #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED #include <streambuf> namespace Catch { class StreamBufBase : public std::streambuf { public: virtual ~StreamBufBase() CATCH_NOEXCEPT; }; } #include <streambuf> #include <ostream> #include <fstream> namespace Catch { std::ostream& cout(); std::ostream& cerr(); struct IStream { virtual ~IStream() CATCH_NOEXCEPT; virtual std::ostream& stream() const = 0; }; class FileStream : public IStream { mutable std::ofstream m_ofs; public: FileStream( std::string const& filename ); virtual ~FileStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class CoutStream : public IStream { mutable std::ostream m_os; public: CoutStream(); virtual ~CoutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class DebugOutStream : public IStream { std::auto_ptr<StreamBufBase> m_streamBuf; mutable std::ostream m_os; public: DebugOutStream(); virtual ~DebugOutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; } #include <memory> #include <vector> #include <string> #include <iostream> #include <ctime> #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { struct ConfigData { ConfigData() : listTests( false ), listTags( false ), listReporters( false ), listTestNamesOnly( false ), showSuccessfulTests( false ), shouldDebugBreak( false ), noThrow( false ), showHelp( false ), showInvisibles( false ), filenamesAsTags( false ), abortAfter( -1 ), rngSeed( 0 ), verbosity( Verbosity::Normal ), warnings( WarnAbout::Nothing ), showDurations( ShowDurations::DefaultForReporter ), runOrder( RunTests::InDeclarationOrder ), useColour( UseColour::Auto ) {} bool listTests; bool listTags; bool listReporters; bool listTestNamesOnly; bool showSuccessfulTests; bool shouldDebugBreak; bool noThrow; bool showHelp; bool showInvisibles; bool filenamesAsTags; int abortAfter; unsigned int rngSeed; Verbosity::Level verbosity; WarnAbout::What warnings; ShowDurations::OrNot showDurations; RunTests::InWhatOrder runOrder; UseColour::YesOrNo useColour; std::string outputFilename; std::string name; std::string processName; std::vector<std::string> reporterNames; std::vector<std::string> testsOrTags; }; class Config : public SharedImpl<IConfig> { private: Config( Config const& other ); Config& operator = ( Config const& other ); virtual void dummy(); public: Config() {} Config( ConfigData const& data ) : m_data( data ), m_stream( openStream() ) { if( !data.testsOrTags.empty() ) { TestSpecParser parser( ITagAliasRegistry::get() ); for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) parser.parse( data.testsOrTags[i] ); m_testSpec = parser.testSpec(); } } virtual ~Config() { } std::string const& getFilename() const { return m_data.outputFilename ; } bool listTests() const { return m_data.listTests; } bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool listTags() const { return m_data.listTags; } bool listReporters() const { return m_data.listReporters; } std::string getProcessName() const { return m_data.processName; } bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } std::vector<std::string> getReporterNames() const { return m_data.reporterNames; } int abortAfter() const { return m_data.abortAfter; } TestSpec const& testSpec() const { return m_testSpec; } bool showHelp() const { return m_data.showHelp; } bool showInvisibles() const { return m_data.showInvisibles; } // IConfig interface virtual bool allowThrows() const { return !m_data.noThrow; } virtual std::ostream& stream() const { return m_stream->stream(); } virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } virtual unsigned int rngSeed() const { return m_data.rngSeed; } virtual UseColour::YesOrNo useColour() const { return m_data.useColour; } private: IStream const* openStream() { if( m_data.outputFilename.empty() ) return new CoutStream(); else if( m_data.outputFilename[0] == '%' ) { if( m_data.outputFilename == "%debug" ) return new DebugOutStream(); else throw std::domain_error( "Unrecognised stream: " + m_data.outputFilename ); } else return new FileStream( m_data.outputFilename ); } ConfigData m_data; std::auto_ptr<IStream const> m_stream; TestSpec m_testSpec; }; } // end namespace Catch // #included from: catch_clara.h #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED // Use Catch's value for console width (store Clara's off to the side, if present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH #undef CLARA_CONFIG_CONSOLE_WIDTH #endif #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH // Declare Clara inside the Catch namespace #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { // #included from: ../external/clara.h // Version 0.0.1.1 // Only use header guard if we are not using an outer namespace #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) #ifndef STITCH_CLARA_OPEN_NAMESPACE #define TWOBLUECUBES_CLARA_H_INCLUDED #define STITCH_CLARA_OPEN_NAMESPACE #define STITCH_CLARA_CLOSE_NAMESPACE #else #define STITCH_CLARA_CLOSE_NAMESPACE } #endif #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE // ----------- #included from tbc_text_format.h ----------- // Only use header guard if we are not using an outer namespace #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE #define TBC_TEXT_FORMAT_H_INCLUDED #endif #include <string> #include <vector> #include <sstream> #include <algorithm> // Use optional outer namespace #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = " [({.,/|\\-"; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( "... message truncated due to excessive size" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += "-"; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector<std::string>::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << "\n"; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector<std::string> lines; }; } // end namespace Tbc #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TBC_TEXT_FORMAT_H_INCLUDED // ----------- end of #include from tbc_text_format.h ----------- // ........... back in clara.h #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE // ----------- #included from clara_compilers.h ----------- #ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED #define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED // Detect a number of compiler features - mostly C++11/14 conformance - by compiler // The following features are defined: // // CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported? // CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported? // CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods // CLARA_CONFIG_CPP11_OVERRIDE : is override supported? // CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported? // In general each macro has a _NO_<feature name> form // (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11 #ifdef __clang__ #if __has_feature(cxx_nullptr) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif #if __has_feature(cxx_noexcept) #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #endif #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // GCC #ifdef __GNUC__ #if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below #endif // __GNUC__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if (_MSC_VER >= 1600) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // C++ language feature support // catch all support for C++11 #if defined(__cplusplus) && __cplusplus >= 201103L #define CLARA_CPP11_OR_GREATER #if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif #ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #endif #ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) #define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE #endif #if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #endif // __cplusplus >= 201103L // Now set the actual defines based on the above + anything the user has configured #if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_NULLPTR #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_NOEXCEPT #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_GENERATED_METHODS #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_OVERRIDE #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_UNIQUE_PTR #endif // noexcept support: #if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT) #define CLARA_NOEXCEPT noexcept # define CLARA_NOEXCEPT_IS(x) noexcept(x) #else #define CLARA_NOEXCEPT throw() # define CLARA_NOEXCEPT_IS(x) #endif // nullptr support #ifdef CLARA_CONFIG_CPP11_NULLPTR #define CLARA_NULL nullptr #else #define CLARA_NULL NULL #endif // override support #ifdef CLARA_CONFIG_CPP11_OVERRIDE #define CLARA_OVERRIDE override #else #define CLARA_OVERRIDE #endif // unique_ptr support #ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR # define CLARA_AUTO_PTR( T ) std::unique_ptr<T> #else # define CLARA_AUTO_PTR( T ) std::auto_ptr<T> #endif #endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED // ----------- end of #include from clara_compilers.h ----------- // ........... back in clara.h #include <map> #include <stdexcept> #include <memory> // Use optional outer namespace #ifdef STITCH_CLARA_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE #endif namespace Clara { struct UnpositionalTag {}; extern UnpositionalTag _; #ifdef CLARA_CONFIG_MAIN UnpositionalTag _; #endif namespace Detail { #ifdef CLARA_CONSOLE_WIDTH const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif // Use this to try and stop compiler from warning about unreachable code inline bool isTrue( bool value ) { return value; } using namespace Tbc; inline bool startsWith( std::string const& str, std::string const& prefix ) { return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; } template<typename T> struct RemoveConstRef{ typedef T type; }; template<typename T> struct RemoveConstRef<T&>{ typedef T type; }; template<typename T> struct RemoveConstRef<T const&>{ typedef T type; }; template<typename T> struct RemoveConstRef<T const>{ typedef T type; }; template<typename T> struct IsBool { static const bool value = false; }; template<> struct IsBool<bool> { static const bool value = true; }; template<typename T> void convertInto( std::string const& _source, T& _dest ) { std::stringstream ss; ss << _source; ss >> _dest; if( ss.fail() ) throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); } inline void convertInto( std::string const& _source, std::string& _dest ) { _dest = _source; } inline void convertInto( std::string const& _source, bool& _dest ) { std::string sourceLC = _source; std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower ); if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) _dest = true; else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) _dest = false; else throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); } inline void convertInto( bool _source, bool& _dest ) { _dest = _source; } template<typename T> inline void convertInto( bool, T& ) { if( isTrue( true ) ) throw std::runtime_error( "Invalid conversion" ); } template<typename ConfigT> struct IArgFunction { virtual ~IArgFunction() {} #ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS IArgFunction() = default; IArgFunction( IArgFunction const& ) = default; #endif virtual void set( ConfigT& config, std::string const& value ) const = 0; virtual void setFlag( ConfigT& config ) const = 0; virtual bool takesArg() const = 0; virtual IArgFunction* clone() const = 0; }; template<typename ConfigT> class BoundArgFunction { public: BoundArgFunction() : functionObj( CLARA_NULL ) {} BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {} BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {} BoundArgFunction& operator = ( BoundArgFunction const& other ) { IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL; delete functionObj; functionObj = newFunctionObj; return *this; } ~BoundArgFunction() { delete functionObj; } void set( ConfigT& config, std::string const& value ) const { functionObj->set( config, value ); } void setFlag( ConfigT& config ) const { functionObj->setFlag( config ); } bool takesArg() const { return functionObj->takesArg(); } bool isSet() const { return functionObj != CLARA_NULL; } private: IArgFunction<ConfigT>* functionObj; }; template<typename C> struct NullBinder : IArgFunction<C>{ virtual void set( C&, std::string const& ) const {} virtual void setFlag( C& ) const {} virtual bool takesArg() const { return true; } virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); } }; template<typename C, typename M> struct BoundDataMember : IArgFunction<C>{ BoundDataMember( M C::* _member ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { convertInto( stringValue, p.*member ); } virtual void setFlag( C& p ) const { convertInto( true, p.*member ); } virtual bool takesArg() const { return !IsBool<M>::value; } virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); } M C::* member; }; template<typename C, typename M> struct BoundUnaryMethod : IArgFunction<C>{ BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { typename RemoveConstRef<M>::type value; convertInto( stringValue, value ); (p.*member)( value ); } virtual void setFlag( C& p ) const { typename RemoveConstRef<M>::type value; convertInto( true, value ); (p.*member)( value ); } virtual bool takesArg() const { return !IsBool<M>::value; } virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); } void (C::*member)( M ); }; template<typename C> struct BoundNullaryMethod : IArgFunction<C>{ BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) (p.*member)(); } virtual void setFlag( C& p ) const { (p.*member)(); } virtual bool takesArg() const { return false; } virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); } void (C::*member)(); }; template<typename C> struct BoundUnaryFunction : IArgFunction<C>{ BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) function( obj ); } virtual void setFlag( C& p ) const { function( p ); } virtual bool takesArg() const { return false; } virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); } void (*function)( C& ); }; template<typename C, typename T> struct BoundBinaryFunction : IArgFunction<C>{ BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { typename RemoveConstRef<T>::type value; convertInto( stringValue, value ); function( obj, value ); } virtual void setFlag( C& obj ) const { typename RemoveConstRef<T>::type value; convertInto( true, value ); function( obj, value ); } virtual bool takesArg() const { return !IsBool<T>::value; } virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); } void (*function)( C&, T ); }; } // namespace Detail struct Parser { Parser() : separators( " \t=:" ) {} struct Token { enum Type { Positional, ShortOpt, LongOpt }; Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} Type type; std::string data; }; void parseIntoTokens( int argc, char const* const argv[], std::vector<Parser::Token>& tokens ) const { const std::string doubleDash = "--"; for( int i = 1; i < argc && argv[i] != doubleDash; ++i ) parseIntoTokens( argv[i] , tokens); } void parseIntoTokens( std::string arg, std::vector<Parser::Token>& tokens ) const { while( !arg.empty() ) { Parser::Token token( Parser::Token::Positional, arg ); arg = ""; if( token.data[0] == '-' ) { if( token.data.size() > 1 && token.data[1] == '-' ) { token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) ); } else { token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) ); if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) { arg = "-" + token.data.substr( 1 ); token.data = token.data.substr( 0, 1 ); } } } if( token.type != Parser::Token::Positional ) { std::size_t pos = token.data.find_first_of( separators ); if( pos != std::string::npos ) { arg = token.data.substr( pos+1 ); token.data = token.data.substr( 0, pos ); } } tokens.push_back( token ); } } std::string separators; }; template<typename ConfigT> struct CommonArgProperties { CommonArgProperties() {} CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {} Detail::BoundArgFunction<ConfigT> boundField; std::string description; std::string detail; std::string placeholder; // Only value if boundField takes an arg bool takesArg() const { return !placeholder.empty(); } void validate() const { if( !boundField.isSet() ) throw std::logic_error( "option not bound" ); } }; struct OptionArgProperties { std::vector<std::string> shortNames; std::string longName; bool hasShortName( std::string const& shortName ) const { return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); } bool hasLongName( std::string const& _longName ) const { return _longName == longName; } }; struct PositionalArgProperties { PositionalArgProperties() : position( -1 ) {} int position; // -1 means non-positional (floating) bool isFixedPositional() const { return position != -1; } }; template<typename ConfigT> class CommandLine { struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties { Arg() {} Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {} using CommonArgProperties<ConfigT>::placeholder; // !TBD std::string dbgName() const { if( !longName.empty() ) return "--" + longName; if( !shortNames.empty() ) return "-" + shortNames[0]; return "positional args"; } std::string commands() const { std::ostringstream oss; bool first = true; std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); for(; it != itEnd; ++it ) { if( first ) first = false; else oss << ", "; oss << "-" << *it; } if( !longName.empty() ) { if( !first ) oss << ", "; oss << "--" << longName; } if( !placeholder.empty() ) oss << " <" << placeholder << ">"; return oss.str(); } }; typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr; friend void addOptName( Arg& arg, std::string const& optName ) { if( optName.empty() ) return; if( Detail::startsWith( optName, "--" ) ) { if( !arg.longName.empty() ) throw std::logic_error( "Only one long opt may be specified. '" + arg.longName + "' already specified, now attempting to add '" + optName + "'" ); arg.longName = optName.substr( 2 ); } else if( Detail::startsWith( optName, "-" ) ) arg.shortNames.push_back( optName.substr( 1 ) ); else throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); } friend void setPositionalArg( Arg& arg, int position ) { arg.position = position; } class ArgBuilder { public: ArgBuilder( Arg* arg ) : m_arg( arg ) {} // Bind a non-boolean data member (requires placeholder string) template<typename C, typename M> void bind( M C::* field, std::string const& placeholder ) { m_arg->boundField = new Detail::BoundDataMember<C,M>( field ); m_arg->placeholder = placeholder; } // Bind a boolean data member (no placeholder required) template<typename C> void bind( bool C::* field ) { m_arg->boundField = new Detail::BoundDataMember<C,bool>( field ); } // Bind a method taking a single, non-boolean argument (requires a placeholder string) template<typename C, typename M> void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod ); m_arg->placeholder = placeholder; } // Bind a method taking a single, boolean argument (no placeholder string required) template<typename C> void bind( void (C::* unaryMethod)( bool ) ) { m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod ); } // Bind a method that takes no arguments (will be called if opt is present) template<typename C> void bind( void (C::* nullaryMethod)() ) { m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod ); } // Bind a free function taking a single argument - the object to operate on (no placeholder string required) template<typename C> void bind( void (* unaryFunction)( C& ) ) { m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction ); } // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) template<typename C, typename T> void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction ); m_arg->placeholder = placeholder; } ArgBuilder& describe( std::string const& description ) { m_arg->description = description; return *this; } ArgBuilder& detail( std::string const& detail ) { m_arg->detail = detail; return *this; } protected: Arg* m_arg; }; class OptBuilder : public ArgBuilder { public: OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} OptBuilder& operator[]( std::string const& optName ) { addOptName( *ArgBuilder::m_arg, optName ); return *this; } }; public: CommandLine() : m_boundProcessName( new Detail::NullBinder<ConfigT>() ), m_highestSpecifiedArgPosition( 0 ), m_throwOnUnrecognisedTokens( false ) {} CommandLine( CommandLine const& other ) : m_boundProcessName( other.m_boundProcessName ), m_options ( other.m_options ), m_positionalArgs( other.m_positionalArgs ), m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) { if( other.m_floatingArg.get() ) m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); } CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { m_throwOnUnrecognisedTokens = shouldThrow; return *this; } OptBuilder operator[]( std::string const& optName ) { m_options.push_back( Arg() ); addOptName( m_options.back(), optName ); OptBuilder builder( &m_options.back() ); return builder; } ArgBuilder operator[]( int position ) { m_positionalArgs.insert( std::make_pair( position, Arg() ) ); if( position > m_highestSpecifiedArgPosition ) m_highestSpecifiedArgPosition = position; setPositionalArg( m_positionalArgs[position], position ); ArgBuilder builder( &m_positionalArgs[position] ); return builder; } // Invoke this with the _ instance ArgBuilder operator[]( UnpositionalTag ) { if( m_floatingArg.get() ) throw std::logic_error( "Only one unpositional argument can be added" ); m_floatingArg.reset( new Arg() ); ArgBuilder builder( m_floatingArg.get() ); return builder; } template<typename C, typename M> void bindProcessName( M C::* field ) { m_boundProcessName = new Detail::BoundDataMember<C,M>( field ); } template<typename C, typename M> void bindProcessName( void (C::*_unaryMethod)( M ) ) { m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod ); } void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; std::size_t maxWidth = 0; for( it = itBegin; it != itEnd; ++it ) maxWidth = (std::max)( maxWidth, it->commands().size() ); for( it = itBegin; it != itEnd; ++it ) { Detail::Text usage( it->commands(), Detail::TextAttributes() .setWidth( maxWidth+indent ) .setIndent( indent ) ); Detail::Text desc( it->description, Detail::TextAttributes() .setWidth( width - maxWidth - 3 ) ); for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { std::string usageCol = i < usage.size() ? usage[i] : ""; os << usageCol; if( i < desc.size() && !desc[i].empty() ) os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) << desc[i]; os << "\n"; } } } std::string optUsage() const { std::ostringstream oss; optUsage( oss ); return oss.str(); } void argSynopsis( std::ostream& os ) const { for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { if( i > 1 ) os << " "; typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i ); if( it != m_positionalArgs.end() ) os << "<" << it->second.placeholder << ">"; else if( m_floatingArg.get() ) os << "<" << m_floatingArg->placeholder << ">"; else throw std::logic_error( "non consecutive positional arguments with no floating args" ); } // !TBD No indication of mandatory args if( m_floatingArg.get() ) { if( m_highestSpecifiedArgPosition > 1 ) os << " "; os << "[<" << m_floatingArg->placeholder << "> ...]"; } } std::string argSynopsis() const { std::ostringstream oss; argSynopsis( oss ); return oss.str(); } void usage( std::ostream& os, std::string const& procName ) const { validate(); os << "usage:\n " << procName << " "; argSynopsis( os ); if( !m_options.empty() ) { os << " [options]\n\nwhere options are: \n"; optUsage( os, 2 ); } os << "\n"; } std::string usage( std::string const& procName ) const { std::ostringstream oss; usage( oss, procName ); return oss.str(); } ConfigT parse( int argc, char const* const argv[] ) const { ConfigT config; parseInto( argc, argv, config ); return config; } std::vector<Parser::Token> parseInto( int argc, char const* argv[], ConfigT& config ) const { std::string processName = argv[0]; std::size_t lastSlash = processName.find_last_of( "/\\" ); if( lastSlash != std::string::npos ) processName = processName.substr( lastSlash+1 ); m_boundProcessName.set( config, processName ); std::vector<Parser::Token> tokens; Parser parser; parser.parseIntoTokens( argc, argv, tokens ); return populate( tokens, config ); } std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { validate(); std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config ); unusedTokens = populateFixedArgs( unusedTokens, config ); unusedTokens = populateFloatingArgs( unusedTokens, config ); return unusedTokens; } std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { std::vector<Parser::Token> unusedTokens; std::vector<std::string> errors; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end(); for(; it != itEnd; ++it ) { Arg const& arg = *it; try { if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { if( arg.takesArg() ) { if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) errors.push_back( "Expected argument to option: " + token.data ); else arg.boundField.set( config, tokens[++i].data ); } else { arg.boundField.setFlag( config ); } break; } } catch( std::exception& ex ) { errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); } } if( it == itEnd ) { if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) unusedTokens.push_back( token ); else if( errors.empty() && m_throwOnUnrecognisedTokens ) errors.push_back( "unrecognised option: " + token.data ); } } if( !errors.empty() ) { std::ostringstream oss; for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end(); it != itEnd; ++it ) { if( it != errors.begin() ) oss << "\n"; oss << *it; } throw std::runtime_error( oss.str() ); } return unusedTokens; } std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { std::vector<Parser::Token> unusedTokens; int position = 1; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position ); if( it != m_positionalArgs.end() ) it->second.boundField.set( config, token.data ); else unusedTokens.push_back( token ); if( token.type == Parser::Token::Positional ) position++; } return unusedTokens; } std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const { if( !m_floatingArg.get() ) return tokens; std::vector<Parser::Token> unusedTokens; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; if( token.type == Parser::Token::Positional ) m_floatingArg->boundField.set( config, token.data ); else unusedTokens.push_back( token ); } return unusedTokens; } void validate() const { if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) throw std::logic_error( "No options or arguments specified" ); for( typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end(); it != itEnd; ++it ) it->validate(); } private: Detail::BoundArgFunction<ConfigT> m_boundProcessName; std::vector<Arg> m_options; std::map<int, Arg> m_positionalArgs; ArgAutoPtr m_floatingArg; int m_highestSpecifiedArgPosition; bool m_throwOnUnrecognisedTokens; }; } // end namespace Clara STITCH_CLARA_CLOSE_NAMESPACE #undef STITCH_CLARA_OPEN_NAMESPACE #undef STITCH_CLARA_CLOSE_NAMESPACE #endif // TWOBLUECUBES_CLARA_H_INCLUDED #undef STITCH_CLARA_OPEN_NAMESPACE // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif #include <fstream> namespace Catch { inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } inline void abortAfterX( ConfigData& config, int x ) { if( x < 1 ) throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); config.abortAfter = x; } inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } inline void addWarning( ConfigData& config, std::string const& _warning ) { if( _warning == "NoAssertions" ) config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions ); else throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" ); } inline void setOrder( ConfigData& config, std::string const& order ) { if( startsWith( "declared", order ) ) config.runOrder = RunTests::InDeclarationOrder; else if( startsWith( "lexical", order ) ) config.runOrder = RunTests::InLexicographicalOrder; else if( startsWith( "random", order ) ) config.runOrder = RunTests::InRandomOrder; else throw std::runtime_error( "Unrecognised ordering: '" + order + "'" ); } inline void setRngSeed( ConfigData& config, std::string const& seed ) { if( seed == "time" ) { config.rngSeed = static_cast<unsigned int>( std::time(0) ); } else { std::stringstream ss; ss << seed; ss >> config.rngSeed; if( ss.fail() ) throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" ); } } inline void setVerbosity( ConfigData& config, int level ) { // !TBD: accept strings? config.verbosity = static_cast<Verbosity::Level>( level ); } inline void setShowDurations( ConfigData& config, bool _showDurations ) { config.showDurations = _showDurations ? ShowDurations::Always : ShowDurations::Never; } inline void setUseColour( ConfigData& config, std::string const& value ) { std::string mode = toLower( value ); if( mode == "yes" ) config.useColour = UseColour::Yes; else if( mode == "no" ) config.useColour = UseColour::No; else if( mode == "auto" ) config.useColour = UseColour::Auto; else throw std::runtime_error( "colour mode must be one of: auto, yes or no" ); } inline void forceColour( ConfigData& config ) { config.useColour = UseColour::Yes; } inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { std::ifstream f( _filename.c_str() ); if( !f.is_open() ) throw std::domain_error( "Unable to load input file: " + _filename ); std::string line; while( std::getline( f, line ) ) { line = trim(line); if( !line.empty() && !startsWith( line, "#" ) ) addTestOrTags( config, "\"" + line + "\"," ); } } inline Clara::CommandLine<ConfigData> makeCommandLineParser() { using namespace Clara; CommandLine<ConfigData> cli; cli.bindProcessName( &ConfigData::processName ); cli["-?"]["-h"]["--help"] .describe( "display usage information" ) .bind( &ConfigData::showHelp ); cli["-l"]["--list-tests"] .describe( "list all/matching test cases" ) .bind( &ConfigData::listTests ); cli["-t"]["--list-tags"] .describe( "list all/matching tags" ) .bind( &ConfigData::listTags ); cli["-s"]["--success"] .describe( "include successful tests in output" ) .bind( &ConfigData::showSuccessfulTests ); cli["-b"]["--break"] .describe( "break into debugger on failure" ) .bind( &ConfigData::shouldDebugBreak ); cli["-e"]["--nothrow"] .describe( "skip exception tests" ) .bind( &ConfigData::noThrow ); cli["-i"]["--invisibles"] .describe( "show invisibles (tabs, newlines)" ) .bind( &ConfigData::showInvisibles ); cli["-o"]["--out"] .describe( "output filename" ) .bind( &ConfigData::outputFilename, "filename" ); cli["-r"]["--reporter"] // .placeholder( "name[:filename]" ) .describe( "reporter to use (defaults to console)" ) .bind( &addReporterName, "name" ); cli["-n"]["--name"] .describe( "suite name" ) .bind( &ConfigData::name, "name" ); cli["-a"]["--abort"] .describe( "abort at first failure" ) .bind( &abortAfterFirst ); cli["-x"]["--abortx"] .describe( "abort after x failures" ) .bind( &abortAfterX, "no. failures" ); cli["-w"]["--warn"] .describe( "enable warnings" ) .bind( &addWarning, "warning name" ); // - needs updating if reinstated // cli.into( &setVerbosity ) // .describe( "level of verbosity (0=no output)" ) // .shortOpt( "v") // .longOpt( "verbosity" ) // .placeholder( "level" ); cli[_] .describe( "which test or tests to use" ) .bind( &addTestOrTags, "test name, pattern or tags" ); cli["-d"]["--durations"] .describe( "show test durations" ) .bind( &setShowDurations, "yes|no" ); cli["-f"]["--input-file"] .describe( "load test names to run from a file" ) .bind( &loadTestNamesFromFile, "filename" ); cli["-#"]["--filenames-as-tags"] .describe( "adds a tag for the filename" ) .bind( &ConfigData::filenamesAsTags ); // Less common commands which don't have a short form cli["--list-test-names-only"] .describe( "list all/matching test cases names only" ) .bind( &ConfigData::listTestNamesOnly ); cli["--list-reporters"] .describe( "list all reporters" ) .bind( &ConfigData::listReporters ); cli["--order"] .describe( "test case order (defaults to decl)" ) .bind( &setOrder, "decl|lex|rand" ); cli["--rng-seed"] .describe( "set a specific seed for random numbers" ) .bind( &setRngSeed, "'time'|number" ); cli["--force-colour"] .describe( "force colourised output (deprecated)" ) .bind( &forceColour ); cli["--use-colour"] .describe( "should output be colourised" ) .bind( &setUseColour, "yes|no" ); return cli; } } // end namespace Catch // #included from: internal/catch_list.hpp #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED // #included from: catch_text.h #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch // #included from: ../external/tbc_text_format.h // Only use header guard if we are not using an outer namespace #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # endif # else # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # endif #endif #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #include <string> #include <vector> #include <sstream> // Use optional outer namespace #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = " [({.,/|\\-"; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( "... message truncated due to excessive size" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += "-"; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector<std::string>::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << "\n"; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector<std::string> lines; }; } // end namespace Tbc #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace Catch { using Tbc::Text; using Tbc::TextAttributes; } // #included from: catch_console_colour.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, // By intention FileName = LightGrey, Warning = Yellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = Yellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour const& other ); ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved; }; inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } } // end namespace Catch // #included from: catch_interfaces_reporter.h #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED #include <string> #include <ostream> #include <map> #include <assert.h> namespace Catch { struct ReporterConfig { explicit ReporterConfig( Ptr<IConfig const> const& _fullConfig ) : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} ReporterConfig( Ptr<IConfig const> const& _fullConfig, std::ostream& _stream ) : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} std::ostream& stream() const { return *m_stream; } Ptr<IConfig const> fullConfig() const { return m_fullConfig; } private: std::ostream* m_stream; Ptr<IConfig const> m_fullConfig; }; struct ReporterPreferences { ReporterPreferences() : shouldRedirectStdOut( false ) {} bool shouldRedirectStdOut; }; template<typename T> struct LazyStat : Option<T> { LazyStat() : used( false ) {} LazyStat& operator=( T const& _value ) { Option<T>::operator=( _value ); used = false; return *this; } void reset() { Option<T>::reset(); used = false; } bool used; }; struct TestRunInfo { TestRunInfo( std::string const& _name ) : name( _name ) {} std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ) : name( _name ), groupIndex( _groupIndex ), groupsCounts( _groupsCount ) {} std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ) : assertionResult( _assertionResult ), infoMessages( _infoMessages ), totals( _totals ) { if( assertionResult.hasMessage() ) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); infoMessages.push_back( builder.m_info ); } } virtual ~AssertionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = default; AssertionStats& operator = ( AssertionStats && ) = default; # endif AssertionResult assertionResult; std::vector<MessageInfo> infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ) : sectionInfo( _sectionInfo ), assertions( _assertions ), durationInSeconds( _durationInSeconds ), missingAssertions( _missingAssertions ) {} virtual ~SectionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SectionStats( SectionStats const& ) = default; SectionStats( SectionStats && ) = default; SectionStats& operator = ( SectionStats const& ) = default; SectionStats& operator = ( SectionStats && ) = default; # endif SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ) : testInfo( _testInfo ), totals( _totals ), stdOut( _stdOut ), stdErr( _stdErr ), aborting( _aborting ) {} virtual ~TestCaseStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestCaseStats( TestCaseStats const& ) = default; TestCaseStats( TestCaseStats && ) = default; TestCaseStats& operator = ( TestCaseStats const& ) = default; TestCaseStats& operator = ( TestCaseStats && ) = default; # endif TestCaseInfo testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ) : groupInfo( _groupInfo ), totals( _totals ), aborting( _aborting ) {} TestGroupStats( GroupInfo const& _groupInfo ) : groupInfo( _groupInfo ), aborting( false ) {} virtual ~TestGroupStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestGroupStats( TestGroupStats const& ) = default; TestGroupStats( TestGroupStats && ) = default; TestGroupStats& operator = ( TestGroupStats const& ) = default; TestGroupStats& operator = ( TestGroupStats && ) = default; # endif GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ) : runInfo( _runInfo ), totals( _totals ), aborting( _aborting ) {} virtual ~TestRunStats(); # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS TestRunStats( TestRunStats const& _other ) : runInfo( _other.runInfo ), totals( _other.totals ), aborting( _other.aborting ) {} # else TestRunStats( TestRunStats const& ) = default; TestRunStats( TestRunStats && ) = default; TestRunStats& operator = ( TestRunStats const& ) = default; TestRunStats& operator = ( TestRunStats && ) = default; # endif TestRunInfo runInfo; Totals totals; bool aborting; }; struct IStreamingReporter : IShared { virtual ~IStreamingReporter(); // Implementing class must also provide the following static method: // static std::string getDescription(); virtual ReporterPreferences getPreferences() const = 0; virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; }; struct IReporterFactory : IShared { virtual ~IReporterFactory(); virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; struct IReporterRegistry { typedef std::map<std::string, Ptr<IReporterFactory> > FactoryMap; typedef std::vector<Ptr<IReporterFactory> > Listeners; virtual ~IReporterRegistry(); virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ); } #include <limits> #include <algorithm> namespace Catch { inline std::size_t listTests( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << "Matching test cases:\n"; else { Catch::cout() << "All available test cases:\n"; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); } std::size_t matchedTests = 0; TextAttributes nameAttr, tagsAttr; nameAttr.setInitialIndent( 2 ).setIndent( 4 ); tagsAttr.setIndent( 6 ); std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; Colour colourGuard( colour ); Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; if( !testCaseInfo.tags.empty() ) Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; } if( !config.testSpec().hasFilters() ) Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl; else Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl; return matchedTests; } inline std::size_t listTestsNamesOnly( Config const& config ) { TestSpec testSpec = config.testSpec(); if( !config.testSpec().hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); std::size_t matchedTests = 0; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Catch::cout() << testCaseInfo.name << std::endl; } return matchedTests; } struct TagInfo { TagInfo() : count ( 0 ) {} void add( std::string const& spelling ) { ++count; spellings.insert( spelling ); } std::string all() const { std::string out; for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end(); it != itEnd; ++it ) out += "[" + *it + "]"; return out; } std::set<std::string> spellings; std::size_t count; }; inline std::size_t listTags( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << "Tags for matching test cases:\n"; else { Catch::cout() << "All available tags:\n"; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); } std::map<std::string, TagInfo> tagCounts; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), tagItEnd = it->getTestCaseInfo().tags.end(); tagIt != tagItEnd; ++tagIt ) { std::string tagName = *tagIt; std::string lcaseTagName = toLower( tagName ); std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName ); if( countIt == tagCounts.end() ) countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; countIt->second.add( tagName ); } } for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(), countItEnd = tagCounts.end(); countIt != countItEnd; ++countIt ) { std::ostringstream oss; oss << " " << std::setw(2) << countIt->second.count << " "; Text wrapper( countIt->second.all(), TextAttributes() .setInitialIndent( 0 ) .setIndent( oss.str().size() ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); Catch::cout() << oss.str() << wrapper << "\n"; } Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl; return tagCounts.size(); } inline std::size_t listReporters( Config const& /*config*/ ) { Catch::cout() << "Available reporters:\n"; IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; std::size_t maxNameLen = 0; for(it = itBegin; it != itEnd; ++it ) maxNameLen = (std::max)( maxNameLen, it->first.size() ); for(it = itBegin; it != itEnd; ++it ) { Text wrapper( it->second->getDescription(), TextAttributes() .setInitialIndent( 0 ) .setIndent( 7+maxNameLen ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); Catch::cout() << " " << it->first << ":" << std::string( maxNameLen - it->first.size() + 2, ' ' ) << wrapper << "\n"; } Catch::cout() << std::endl; return factories.size(); } inline Option<std::size_t> list( Config const& config ) { Option<std::size_t> listedCount; if( config.listTests() ) listedCount = listedCount.valueOr(0) + listTests( config ); if( config.listTestNamesOnly() ) listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); if( config.listTags() ) listedCount = listedCount.valueOr(0) + listTags( config ); if( config.listReporters() ) listedCount = listedCount.valueOr(0) + listReporters( config ); return listedCount; } } // end namespace Catch // #included from: internal/catch_run_context.hpp #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED // #included from: catch_test_case_tracker.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #include <map> #include <string> #include <assert.h> #include <vector> namespace Catch { namespace TestCaseTracking { struct ITracker : SharedImpl<> { virtual ~ITracker(); // static queries virtual std::string name() const = 0; // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasChildren() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; virtual void addChild( Ptr<ITracker> const& child ) = 0; virtual ITracker* findChild( std::string const& name ) = 0; virtual void openChild() = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; Ptr<ITracker> m_rootTracker; ITracker* m_currentTracker; RunState m_runState; public: static TrackerContext& instance() { static TrackerContext s_instance; return s_instance; } TrackerContext() : m_currentTracker( CATCH_NULL ), m_runState( NotStarted ) {} ITracker& startRun(); void endRun() { m_rootTracker.reset(); m_currentTracker = CATCH_NULL; m_runState = NotStarted; } void startCycle() { m_currentTracker = m_rootTracker.get(); m_runState = Executing; } void completeCycle() { m_runState = CompletedCycle; } bool completedCycle() const { return m_runState == CompletedCycle; } ITracker& currentTracker() { return *m_currentTracker; } void setCurrentTracker( ITracker* tracker ) { m_currentTracker = tracker; } }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; class TrackerHasName { std::string m_name; public: TrackerHasName( std::string const& name ) : m_name( name ) {} bool operator ()( Ptr<ITracker> const& tracker ) { return tracker->name() == m_name; } }; typedef std::vector<Ptr<ITracker> > Children; std::string m_name; TrackerContext& m_ctx; ITracker* m_parent; Children m_children; CycleState m_runState; public: TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent ) : m_name( name ), m_ctx( ctx ), m_parent( parent ), m_runState( NotStarted ) {} virtual ~TrackerBase(); virtual std::string name() const CATCH_OVERRIDE { return m_name; } virtual bool isComplete() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully || m_runState == Failed; } virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully; } virtual bool isOpen() const CATCH_OVERRIDE { return m_runState != NotStarted && !isComplete(); } virtual bool hasChildren() const CATCH_OVERRIDE { return !m_children.empty(); } virtual void addChild( Ptr<ITracker> const& child ) CATCH_OVERRIDE { m_children.push_back( child ); } virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE { Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) ); return( it != m_children.end() ) ? it->get() : CATCH_NULL; } virtual ITracker& parent() CATCH_OVERRIDE { assert( m_parent ); // Should always be non-null except for root return *m_parent; } virtual void openChild() CATCH_OVERRIDE { if( m_runState != ExecutingChildren ) { m_runState = ExecutingChildren; if( m_parent ) m_parent->openChild(); } } void open() { m_runState = Executing; moveToThis(); if( m_parent ) m_parent->openChild(); } virtual void close() CATCH_OVERRIDE { // Close any still open children (e.g. generators) while( &m_ctx.currentTracker() != this ) m_ctx.currentTracker().close(); switch( m_runState ) { case NotStarted: case CompletedSuccessfully: case Failed: throw std::logic_error( "Illogical state" ); case NeedsAnotherRun: break;; case Executing: m_runState = CompletedSuccessfully; break; case ExecutingChildren: if( m_children.empty() || m_children.back()->isComplete() ) m_runState = CompletedSuccessfully; break; default: throw std::logic_error( "Unexpected state" ); } moveToParent(); m_ctx.completeCycle(); } virtual void fail() CATCH_OVERRIDE { m_runState = Failed; if( m_parent ) m_parent->markAsNeedingAnotherRun(); moveToParent(); m_ctx.completeCycle(); } virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { m_runState = NeedsAnotherRun; } private: void moveToParent() { assert( m_parent ); m_ctx.setCurrentTracker( m_parent ); } void moveToThis() { m_ctx.setCurrentTracker( this ); } }; class SectionTracker : public TrackerBase { public: SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent ) : TrackerBase( name, ctx, parent ) {} virtual ~SectionTracker(); static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) { SectionTracker* section = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { section = dynamic_cast<SectionTracker*>( childTracker ); assert( section ); } else { section = new SectionTracker( name, ctx, &currentTracker ); currentTracker.addChild( section ); } if( !ctx.completedCycle() && !section->isComplete() ) { section->open(); } return *section; } }; class IndexTracker : public TrackerBase { int m_size; int m_index; public: IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size ) : TrackerBase( name, ctx, parent ), m_size( size ), m_index( -1 ) {} virtual ~IndexTracker(); static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) { IndexTracker* tracker = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { tracker = dynamic_cast<IndexTracker*>( childTracker ); assert( tracker ); } else { tracker = new IndexTracker( name, ctx, &currentTracker, size ); currentTracker.addChild( tracker ); } if( !ctx.completedCycle() && !tracker->isComplete() ) { if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) tracker->moveNext(); tracker->open(); } return *tracker; } int index() const { return m_index; } void moveNext() { m_index++; m_children.clear(); } virtual void close() CATCH_OVERRIDE { TrackerBase::close(); if( m_runState == CompletedSuccessfully && m_index < m_size-1 ) m_runState = Executing; } }; inline ITracker& TrackerContext::startRun() { m_rootTracker = new SectionTracker( "{root}", *this, CATCH_NULL ); m_currentTracker = CATCH_NULL; m_runState = Executing; return *m_rootTracker; } } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; using TestCaseTracking::IndexTracker; } // namespace Catch // #included from: catch_fatal_condition.hpp #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED namespace Catch { // Report the error condition then exit the process inline void fatal( std::string const& message, int exitCode ) { IContext& context = Catch::getCurrentContext(); IResultCapture* resultCapture = context.getResultCapture(); resultCapture->handleFatalErrorCondition( message ); if( Catch::alwaysTrue() ) // avoids "no return" warnings exit( exitCode ); } } // namespace Catch #if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// namespace Catch { struct FatalConditionHandler { void reset() {} }; } // namespace Catch #else // Not Windows - assumed to be POSIX compatible ////////////////////////// #include <signal.h> namespace Catch { struct SignalDefs { int id; const char* name; }; extern SignalDefs signalDefs[]; SignalDefs signalDefs[] = { { SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGILL, "SIGILL - Illegal instruction signal" }, { SIGFPE, "SIGFPE - Floating point error signal" }, { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, { SIGTERM, "SIGTERM - Termination request signal" }, { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } }; struct FatalConditionHandler { static void handleSignal( int sig ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) if( sig == signalDefs[i].id ) fatal( signalDefs[i].name, -sig ); fatal( "<unknown signal>", -sig ); } FatalConditionHandler() : m_isSet( true ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, handleSignal ); } ~FatalConditionHandler() { reset(); } void reset() { if( m_isSet ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, SIG_DFL ); m_isSet = false; } } bool m_isSet; }; } // namespace Catch #endif // not Windows #include <set> #include <string> namespace Catch { class StreamRedirect { public: StreamRedirect( std::ostream& stream, std::string& targetString ) : m_stream( stream ), m_prevBuf( stream.rdbuf() ), m_targetString( targetString ) { stream.rdbuf( m_oss.rdbuf() ); } ~StreamRedirect() { m_targetString += m_oss.str(); m_stream.rdbuf( m_prevBuf ); } private: std::ostream& m_stream; std::streambuf* m_prevBuf; std::ostringstream m_oss; std::string& m_targetString; }; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { RunContext( RunContext const& ); void operator =( RunContext const& ); public: explicit RunContext( Ptr<IConfig const> const& _config, Ptr<IStreamingReporter> const& reporter ) : m_runInfo( _config->name() ), m_context( getCurrentMutableContext() ), m_activeTestCase( CATCH_NULL ), m_config( _config ), m_reporter( reporter ) { m_context.setRunner( this ); m_context.setConfig( m_config ); m_context.setResultCapture( this ); m_reporter->testRunStarting( m_runInfo ); } virtual ~RunContext() { m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); } void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); } void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); } Totals runTest( TestCase const& testCase ) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; TestCaseInfo testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting( testInfo ); m_activeTestCase = &testCase; do { m_trackerContext.startRun(); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name ); runCurrentTest( redirectedCout, redirectedCerr ); } while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); } // !TBD: deprecated - this will be replaced by indexed trackers while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); Totals deltaTotals = m_totals.delta( prevTotals ); if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { deltaTotals.assertions.failed++; deltaTotals.testCases.passed--; deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting() ) ); m_activeTestCase = CATCH_NULL; m_testCaseTracker = CATCH_NULL; return deltaTotals; } Ptr<IConfig const> config() const { return m_config; } private: // IResultCapture virtual void assertionEnded( AssertionResult const& result ) { if( result.getResultType() == ResultWas::Ok ) { m_totals.assertions.passed++; } else if( !result.isOk() ) { m_totals.assertions.failed++; } if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) m_messages.clear(); // Reset working state m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); m_lastResult = result; } virtual bool sectionStarted ( SectionInfo const& sectionInfo, Counts& assertions ) { std::ostringstream oss; oss << sectionInfo.name << "@" << sectionInfo.lineInfo; ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() ); if( !sectionTracker.isOpen() ) return false; m_activeSections.push_back( &sectionTracker ); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting( sectionInfo ); assertions = m_totals.assertions; return true; } bool testForMissingAssertions( Counts& assertions ) { if( assertions.total() != 0 ) return false; if( !m_config->warnAboutMissingAssertions() ) return false; if( m_trackerContext.currentTracker().hasChildren() ) return false; m_totals.assertions.failed++; assertions.failed++; return true; } virtual void sectionEnded( SectionEndInfo const& endInfo ) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( !m_activeSections.empty() ) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); m_messages.clear(); } virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { if( m_unfinishedSections.empty() ) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back( endInfo ); } virtual void pushScopedMessage( MessageInfo const& message ) { m_messages.push_back( message ); } virtual void popScopedMessage( MessageInfo const& message ) { m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); } virtual std::string getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : ""; } virtual const AssertionResult* getLastResult() const { return &m_lastResult; } virtual void handleFatalErrorCondition( std::string const& message ) { ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); resultBuilder.setResultType( ResultWas::FatalErrorCondition ); resultBuilder << message; resultBuilder.captureExpression(); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); m_reporter->sectionEnded( testCaseSectionStats ); TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, "", "", false ) ); m_totals.testCases.failed++; testGroupEnded( "", m_totals, 1, 1 ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); } public: // !TBD We need to do this another way! bool aborting() const { return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() ); } private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; try { m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); seedRng( *m_config ); Timer timer; timer.start(); if( m_reporter->getPreferences().shouldRedirectStdOut ) { StreamRedirect coutRedir( Catch::cout(), redirectedCout ); StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); invokeActiveTestCase(); } else { invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } catch( TestFailureException& ) { // This just means the test was aborted due to failure } catch(...) { makeUnexpectedResultBuilder().useActiveException(); } m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( testCaseInfo.okToFail() ) { std::swap( assertions.failedButOk, assertions.failed ); m_totals.assertions.failed -= assertions.failedButOk; m_totals.assertions.failedButOk += assertions.failedButOk; } SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } void invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } private: ResultBuilder makeUnexpectedResultBuilder() const { return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), m_lastAssertionInfo.lineInfo, m_lastAssertionInfo.capturedExpression.c_str(), m_lastAssertionInfo.resultDisposition ); } void handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it ) sectionEnded( *it ); m_unfinishedSections.clear(); } TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase; ITracker* m_testCaseTracker; ITracker* m_currentSectionTracker; AssertionResult m_lastResult; Ptr<IConfig const> m_config; Totals m_totals; Ptr<IStreamingReporter> m_reporter; std::vector<MessageInfo> m_messages; AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; }; IResultCapture& getResultCapture() { if( IResultCapture* capture = getCurrentContext().getResultCapture() ) return *capture; else throw std::logic_error( "No result capture instance" ); } } // end namespace Catch // #included from: internal/catch_version.h #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED namespace Catch { // Versioning information struct Version { Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null std::string const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); private: void operator=( Version const& ); }; extern Version libraryVersion; } #include <fstream> #include <stdlib.h> #include <limits> namespace Catch { Ptr<IStreamingReporter> createReporter( std::string const& reporterName, Ptr<Config> const& config ) { Ptr<IStreamingReporter> reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() ); if( !reporter ) { std::ostringstream oss; oss << "No reporter registered with name: '" << reporterName << "'"; throw std::domain_error( oss.str() ); } return reporter; } Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) { std::vector<std::string> reporters = config->getReporterNames(); if( reporters.empty() ) reporters.push_back( "console" ); Ptr<IStreamingReporter> reporter; for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end(); it != itEnd; ++it ) reporter = addReporter( reporter, createReporter( *it, config ) ); return reporter; } Ptr<IStreamingReporter> addListeners( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> reporters ) { IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); it != itEnd; ++it ) reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) ); return reporters; } Totals runTests( Ptr<Config> const& config ) { Ptr<IConfig const> iconfig = config.get(); Ptr<IStreamingReporter> reporter = makeReporter( config ); reporter = addListeners( iconfig, reporter ); RunContext context( iconfig, reporter ); Totals totals; context.testGroupStarting( config->name(), 1, 1 ); TestSpec testSpec = config->testSpec(); if( !testSpec.hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests std::vector<TestCase> const& allTestCases = getAllTestCasesSorted( *iconfig ); for( std::vector<TestCase>::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); it != itEnd; ++it ) { if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) ) totals += context.runTest( *it ); else reporter->skipTest( *it ); } context.testGroupEnded( iconfig->name(), totals, 1, 1 ); return totals; } void applyFilenamesAsTags( IConfig const& config ) { std::vector<TestCase> const& tests = getAllTestCasesSorted( config ); for(std::size_t i = 0; i < tests.size(); ++i ) { TestCase& test = const_cast<TestCase&>( tests[i] ); std::set<std::string> tags = test.tags; std::string filename = test.lineInfo.file; std::string::size_type lastSlash = filename.find_last_of( "\\/" ); if( lastSlash != std::string::npos ) filename = filename.substr( lastSlash+1 ); std::string::size_type lastDot = filename.find_last_of( "." ); if( lastDot != std::string::npos ) filename = filename.substr( 0, lastDot ); tags.insert( "#" + filename ); setTags( test, tags ); } } class Session : NonCopyable { static bool alreadyInstantiated; public: struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; Session() : m_cli( makeCommandLineParser() ) { if( alreadyInstantiated ) { std::string msg = "Only one instance of Catch::Session can ever be used"; Catch::cerr() << msg << std::endl; throw std::logic_error( msg ); } alreadyInstantiated = true; } ~Session() { Catch::cleanUp(); } void showHelp( std::string const& processName ) { Catch::cout() << "\nCatch v" << libraryVersion << "\n"; m_cli.usage( Catch::cout(), processName ); Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; } int applyCommandLine( int argc, char const* argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { try { m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); m_unusedTokens = m_cli.parseInto( argc, argv, m_configData ); if( m_configData.showHelp ) showHelp( m_configData.processName ); m_config.reset(); } catch( std::exception& ex ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << "\nError(s) in input:\n" << Text( ex.what(), TextAttributes().setIndent(2) ) << "\n\n"; } m_cli.usage( Catch::cout(), m_configData.processName ); return (std::numeric_limits<int>::max)(); } return 0; } void useConfigData( ConfigData const& _configData ) { m_configData = _configData; m_config.reset(); } int run( int argc, char const* argv[] ) { int returnCode = applyCommandLine( argc, argv ); if( returnCode == 0 ) returnCode = run(); return returnCode; } int run( int argc, char* argv[] ) { return run( argc, const_cast<char const**>( argv ) ); } int run() { if( m_configData.showHelp ) return 0; try { config(); // Force config to be constructed seedRng( *m_config ); if( m_configData.filenamesAsTags ) applyFilenamesAsTags( *m_config ); // Handle list request if( Option<std::size_t> listed = list( config() ) ) return static_cast<int>( *listed ); return static_cast<int>( runTests( m_config ).assertions.failed ); } catch( std::exception& ex ) { Catch::cerr() << ex.what() << std::endl; return (std::numeric_limits<int>::max)(); } } Clara::CommandLine<ConfigData> const& cli() const { return m_cli; } std::vector<Clara::Parser::Token> const& unusedTokens() const { return m_unusedTokens; } ConfigData& configData() { return m_configData; } Config& config() { if( !m_config ) m_config = new Config( m_configData ); return *m_config; } private: Clara::CommandLine<ConfigData> m_cli; std::vector<Clara::Parser::Token> m_unusedTokens; ConfigData m_configData; Ptr<Config> m_config; }; bool Session::alreadyInstantiated = false; } // end namespace Catch // #included from: catch_registry_hub.hpp #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED // #included from: catch_test_case_registry_impl.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #include <vector> #include <set> #include <sstream> #include <iostream> #include <algorithm> namespace Catch { struct LexSort { bool operator() (TestCase i,TestCase j) const { return (i<j);} }; struct RandomNumberGenerator { int operator()( int n ) const { return std::rand() % n; } }; inline std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) { std::vector<TestCase> sorted = unsortedTestCases; switch( config.runOrder() ) { case RunTests::InLexicographicalOrder: std::sort( sorted.begin(), sorted.end(), LexSort() ); break; case RunTests::InRandomOrder: { seedRng( config ); RandomNumberGenerator rng; std::random_shuffle( sorted.begin(), sorted.end(), rng ); } break; case RunTests::InDeclarationOrder: // already in declaration order break; } return sorted; } bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); } void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) { std::set<TestCase> seenFunctions; for( std::vector<TestCase>::const_iterator it = functions.begin(), itEnd = functions.end(); it != itEnd; ++it ) { std::pair<std::set<TestCase>::const_iterator, bool> prev = seenFunctions.insert( *it ); if( !prev.second ){ Catch::cerr() << Colour( Colour::Red ) << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; exit(1); } } } std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) { std::vector<TestCase> filtered; filtered.reserve( testCases.size() ); for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end(); it != itEnd; ++it ) if( matchTest( *it, testSpec, config ) ) filtered.push_back( *it ); return filtered; } std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) { return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); } class TestRegistry : public ITestCaseRegistry { public: TestRegistry() : m_currentSortOrder( RunTests::InDeclarationOrder ), m_unnamedCount( 0 ) {} virtual ~TestRegistry(); virtual void registerTest( TestCase const& testCase ) { std::string name = testCase.getTestCaseInfo().name; if( name == "" ) { std::ostringstream oss; oss << "Anonymous test case " << ++m_unnamedCount; return registerTest( testCase.withName( oss.str() ) ); } m_functions.push_back( testCase ); } virtual std::vector<TestCase> const& getAllTests() const { return m_functions; } virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const { if( m_sortedFunctions.empty() ) enforceNoDuplicateTestCases( m_functions ); if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { m_sortedFunctions = sortTests( config, m_functions ); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } private: std::vector<TestCase> m_functions; mutable RunTests::InWhatOrder m_currentSortOrder; mutable std::vector<TestCase> m_sortedFunctions; size_t m_unnamedCount; std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class FreeFunctionTestCase : public SharedImpl<ITestCase> { public: FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} virtual void invoke() const { m_fun(); } private: virtual ~FreeFunctionTestCase(); TestFunction m_fun; }; inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { std::string className = classOrQualifiedMethodName; if( startsWith( className, "&" ) ) { std::size_t lastColons = className.rfind( "::" ); std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); if( penultimateColons == std::string::npos ) penultimateColons = 1; className = className.substr( penultimateColons, lastColons-penultimateColons ); } return className; } void registerTestCase ( ITestCase* testCase, char const* classOrQualifiedMethodName, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { getMutableRegistryHub().registerTest ( makeTestCase ( testCase, extractClassName( classOrQualifiedMethodName ), nameAndDesc.name, nameAndDesc.description, lineInfo ) ); } void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); } /////////////////////////////////////////////////////////////////////////// AutoReg::AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCaseFunction( function, lineInfo, nameAndDesc ); } AutoReg::~AutoReg() {} } // end namespace Catch // #included from: catch_reporter_registry.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED #include <map> namespace Catch { class ReporterRegistry : public IReporterRegistry { public: virtual ~ReporterRegistry() CATCH_OVERRIDE {} virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const CATCH_OVERRIDE { FactoryMap::const_iterator it = m_factories.find( name ); if( it == m_factories.end() ) return CATCH_NULL; return it->second->create( ReporterConfig( config ) ); } void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) { m_factories.insert( std::make_pair( name, factory ) ); } void registerListener( Ptr<IReporterFactory> const& factory ) { m_listeners.push_back( factory ); } virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { return m_factories; } virtual Listeners const& getListeners() const CATCH_OVERRIDE { return m_listeners; } private: FactoryMap m_factories; Listeners m_listeners; }; } // #included from: catch_exception_translator_registry.hpp #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #ifdef __OBJC__ #import "Foundation/Foundation.h" #endif namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry() { deleteAll( m_translators ); } virtual void registerTranslator( const IExceptionTranslator* translator ) { m_translators.push_back( translator ); } virtual std::string translateActiveException() const { try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first @try { return tryTranslators(); } @catch (NSException *exception) { return Catch::toString( [exception description] ); } #else return tryTranslators(); #endif } catch( TestFailureException& ) { throw; } catch( std::exception& ex ) { return ex.what(); } catch( std::string& msg ) { return msg; } catch( const char* msg ) { return msg; } catch(...) { return "Unknown exception"; } } std::string tryTranslators() const { if( m_translators.empty() ) throw; else return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() ); } private: std::vector<const IExceptionTranslator*> m_translators; }; } namespace Catch { namespace { class RegistryHub : public IRegistryHub, public IMutableRegistryHub { RegistryHub( RegistryHub const& ); void operator=( RegistryHub const& ); public: // IRegistryHub RegistryHub() { } virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { return m_reporterRegistry; } virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { return m_testCaseRegistry; } virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { return m_exceptionTranslatorRegistry; } public: // IMutableRegistryHub virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerReporter( name, factory ); } virtual void registerListener( Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerListener( factory ); } virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE { m_testCaseRegistry.registerTest( testInfo ); } virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { m_exceptionTranslatorRegistry.registerTranslator( translator ); } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; }; // Single, global, instance inline RegistryHub*& getTheRegistryHub() { static RegistryHub* theRegistryHub = CATCH_NULL; if( !theRegistryHub ) theRegistryHub = new RegistryHub(); return theRegistryHub; } } IRegistryHub& getRegistryHub() { return *getTheRegistryHub(); } IMutableRegistryHub& getMutableRegistryHub() { return *getTheRegistryHub(); } void cleanUp() { delete getTheRegistryHub(); getTheRegistryHub() = CATCH_NULL; cleanUpContext(); } std::string translateActiveException() { return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); } } // end namespace Catch // #included from: catch_notimplemented_exception.hpp #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED #include <ostream> namespace Catch { NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) : m_lineInfo( lineInfo ) { std::ostringstream oss; oss << lineInfo << ": function "; oss << "not implemented"; m_what = oss.str(); } const char* NotImplementedException::what() const CATCH_NOEXCEPT { return m_what.c_str(); } } // end namespace Catch // #included from: catch_context_impl.hpp #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED // #included from: catch_stream.hpp #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED #include <stdexcept> #include <cstdio> #include <iostream> namespace Catch { template<typename WriterF, size_t bufferSize=256> class StreamBufImpl : public StreamBufBase { char data[bufferSize]; WriterF m_writer; public: StreamBufImpl() { setp( data, data + sizeof(data) ); } ~StreamBufImpl() CATCH_NOEXCEPT { sync(); } private: int overflow( int c ) { sync(); if( c != EOF ) { if( pbase() == epptr() ) m_writer( std::string( 1, static_cast<char>( c ) ) ); else sputc( static_cast<char>( c ) ); } return 0; } int sync() { if( pbase() != pptr() ) { m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); setp( pbase(), epptr() ); } return 0; } }; /////////////////////////////////////////////////////////////////////////// FileStream::FileStream( std::string const& filename ) { m_ofs.open( filename.c_str() ); if( m_ofs.fail() ) { std::ostringstream oss; oss << "Unable to open file: '" << filename << "'"; throw std::domain_error( oss.str() ); } } std::ostream& FileStream::stream() const { return m_ofs; } struct OutputDebugWriter { void operator()( std::string const&str ) { writeToDebugConsole( str ); } }; DebugOutStream::DebugOutStream() : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ), m_os( m_streamBuf.get() ) {} std::ostream& DebugOutStream::stream() const { return m_os; } // Store the streambuf from cout up-front because // cout may get redirected when running tests CoutStream::CoutStream() : m_os( Catch::cout().rdbuf() ) {} std::ostream& CoutStream::stream() const { return m_os; } #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } #endif } namespace Catch { class Context : public IMutableContext { Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {} Context( Context const& ); void operator=( Context const& ); public: // IContext virtual IResultCapture* getResultCapture() { return m_resultCapture; } virtual IRunner* getRunner() { return m_runner; } virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { return getGeneratorsForCurrentTest() .getGeneratorInfo( fileInfo, totalSize ) .getCurrentIndex(); } virtual bool advanceGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); return generators && generators->moveNext(); } virtual Ptr<IConfig const> getConfig() const { return m_config; } public: // IMutableContext virtual void setResultCapture( IResultCapture* resultCapture ) { m_resultCapture = resultCapture; } virtual void setRunner( IRunner* runner ) { m_runner = runner; } virtual void setConfig( Ptr<IConfig const> const& config ) { m_config = config; } friend IMutableContext& getCurrentMutableContext(); private: IGeneratorsForTest* findGeneratorsForCurrentTest() { std::string testName = getResultCapture()->getCurrentTestName(); std::map<std::string, IGeneratorsForTest*>::const_iterator it = m_generatorsByTestName.find( testName ); return it != m_generatorsByTestName.end() ? it->second : CATCH_NULL; } IGeneratorsForTest& getGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); if( !generators ) { std::string testName = getResultCapture()->getCurrentTestName(); generators = createGeneratorsForTest(); m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); } return *generators; } private: Ptr<IConfig const> m_config; IRunner* m_runner; IResultCapture* m_resultCapture; std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName; }; namespace { Context* currentContext = CATCH_NULL; } IMutableContext& getCurrentMutableContext() { if( !currentContext ) currentContext = new Context(); return *currentContext; } IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext() { delete currentContext; currentContext = CATCH_NULL; } } // #included from: catch_console_colour_impl.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED namespace Catch { namespace { struct IColourImpl { virtual ~IColourImpl() {} virtual void use( Colour::Code _colourCode ) = 0; }; struct NoColourImpl : IColourImpl { void use( Colour::Code ) {} static IColourImpl* instance() { static NoColourImpl s_instance; return &s_instance; } }; } // anon namespace } // namespace Catch #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) # ifdef CATCH_PLATFORM_WINDOWS # define CATCH_CONFIG_COLOUR_WINDOWS # else # define CATCH_CONFIG_COLOUR_ANSI # endif #endif #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// #ifndef NOMINMAX #define NOMINMAX #endif #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif namespace Catch { namespace { class Win32ColourImpl : public IColourImpl { public: Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); } virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: return setTextAttribute( originalForegroundAttributes ); case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Red: return setTextAttribute( FOREGROUND_RED ); case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Grey: return setTextAttribute( 0 ); case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Bright: throw std::logic_error( "not a colour" ); } } private: void setTextAttribute( WORD _textAttribute ) { SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); } HANDLE stdoutHandle; WORD originalForegroundAttributes; WORD originalBackgroundAttributes; }; IColourImpl* platformColourInstance() { static Win32ColourImpl s_instance; Ptr<IConfig const> config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = !isDebuggerActive() ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// #include <unistd.h> namespace Catch { namespace { // use POSIX/ ANSI console terminal codes // Thanks to Adam Strzelecki for original contribution // (http://github.com/nanoant) // https://github.com/philsquared/Catch/pull/131 class PosixColourImpl : public IColourImpl { public: virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: case Colour::White: return setColour( "[0m" ); case Colour::Red: return setColour( "[0;31m" ); case Colour::Green: return setColour( "[0;32m" ); case Colour::Blue: return setColour( "[0:34m" ); case Colour::Cyan: return setColour( "[0;36m" ); case Colour::Yellow: return setColour( "[0;33m" ); case Colour::Grey: return setColour( "[1;30m" ); case Colour::LightGrey: return setColour( "[0;37m" ); case Colour::BrightRed: return setColour( "[1;31m" ); case Colour::BrightGreen: return setColour( "[1;32m" ); case Colour::BrightWhite: return setColour( "[1;37m" ); case Colour::Bright: throw std::logic_error( "not a colour" ); } } static IColourImpl* instance() { static PosixColourImpl s_instance; return &s_instance; } private: void setColour( const char* _escapeCode ) { Catch::cout() << '\033' << _escapeCode; } }; IColourImpl* platformColourInstance() { Ptr<IConfig const> config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) ) ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } } // end namespace Catch #endif // Windows/ ANSI/ None namespace Catch { Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast<Colour&>( _other ).m_moved = true; } Colour::~Colour(){ if( !m_moved ) use( None ); } void Colour::use( Code _colourCode ) { static IColourImpl* impl = platformColourInstance(); impl->use( _colourCode ); } } // end namespace Catch // #included from: catch_generators_impl.hpp #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED #include <vector> #include <string> #include <map> namespace Catch { struct GeneratorInfo : IGeneratorInfo { GeneratorInfo( std::size_t size ) : m_size( size ), m_currentIndex( 0 ) {} bool moveNext() { if( ++m_currentIndex == m_size ) { m_currentIndex = 0; return false; } return true; } std::size_t getCurrentIndex() const { return m_currentIndex; } std::size_t m_size; std::size_t m_currentIndex; }; /////////////////////////////////////////////////////////////////////////// class GeneratorsForTest : public IGeneratorsForTest { public: ~GeneratorsForTest() { deleteAll( m_generatorsInOrder ); } IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo ); if( it == m_generatorsByName.end() ) { IGeneratorInfo* info = new GeneratorInfo( size ); m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); m_generatorsInOrder.push_back( info ); return *info; } return *it->second; } bool moveNext() { std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin(); std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end(); for(; it != itEnd; ++it ) { if( (*it)->moveNext() ) return true; } return false; } private: std::map<std::string, IGeneratorInfo*> m_generatorsByName; std::vector<IGeneratorInfo*> m_generatorsInOrder; }; IGeneratorsForTest* createGeneratorsForTest() { return new GeneratorsForTest(); } } // end namespace Catch // #included from: catch_assertionresult.hpp #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED namespace Catch { AssertionInfo::AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ) : macroName( _macroName ), lineInfo( _lineInfo ), capturedExpression( _capturedExpression ), resultDisposition( _resultDisposition ) {} AssertionResult::AssertionResult() {} AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) : m_info( info ), m_resultData( data ) {} AssertionResult::~AssertionResult() {} // Result was a success bool AssertionResult::succeeded() const { return Catch::isOk( m_resultData.resultType ); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); } ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; } bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } std::string AssertionResult::getExpression() const { if( isFalseTest( m_info.resultDisposition ) ) return "!" + m_info.capturedExpression; else return m_info.capturedExpression; } std::string AssertionResult::getExpressionInMacro() const { if( m_info.macroName.empty() ) return m_info.capturedExpression; else return m_info.macroName + "( " + m_info.capturedExpression + " )"; } bool AssertionResult::hasExpandedExpression() const { return hasExpression() && getExpandedExpression() != getExpression(); } std::string AssertionResult::getExpandedExpression() const { return m_resultData.reconstructedExpression; } std::string AssertionResult::getMessage() const { return m_resultData.message; } SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; } std::string AssertionResult::getTestMacroName() const { return m_info.macroName; } } // end namespace Catch // #included from: catch_test_case_info.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED namespace Catch { inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { if( startsWith( tag, "." ) || tag == "hide" || tag == "!hide" ) return TestCaseInfo::IsHidden; else if( tag == "!throws" ) return TestCaseInfo::Throws; else if( tag == "!shouldfail" ) return TestCaseInfo::ShouldFail; else if( tag == "!mayfail" ) return TestCaseInfo::MayFail; else return TestCaseInfo::None; } inline bool isReservedTag( std::string const& tag ) { return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); } inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { if( isReservedTag( tag ) ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << "Tag name [" << tag << "] not allowed.\n" << "Tag names starting with non alpha-numeric characters are reserved\n"; } { Colour colourGuard( Colour::FileName ); Catch::cerr() << _lineInfo << std::endl; } exit(1); } } TestCase makeTestCase( ITestCase* _testCase, std::string const& _className, std::string const& _name, std::string const& _descOrTags, SourceLineInfo const& _lineInfo ) { bool isHidden( startsWith( _name, "./" ) ); // Legacy support // Parse out tags std::set<std::string> tags; std::string desc, tag; bool inTag = false; for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { char c = _descOrTags[i]; if( !inTag ) { if( c == '[' ) inTag = true; else desc += c; } else { if( c == ']' ) { TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); if( prop == TestCaseInfo::IsHidden ) isHidden = true; else if( prop == TestCaseInfo::None ) enforceNotReservedTag( tag, _lineInfo ); tags.insert( tag ); tag.clear(); inTag = false; } else tag += c; } } if( isHidden ) { tags.insert( "hide" ); tags.insert( "." ); } TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); return TestCase( _testCase, info ); } void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags ) { testCaseInfo.tags = tags; testCaseInfo.lcaseTags.clear(); std::ostringstream oss; for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { oss << "[" << *it << "]"; std::string lcaseTag = toLower( *it ); testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.lcaseTags.insert( lcaseTag ); } testCaseInfo.tagsAsString = oss.str(); } TestCaseInfo::TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set<std::string> const& _tags, SourceLineInfo const& _lineInfo ) : name( _name ), className( _className ), description( _description ), lineInfo( _lineInfo ), properties( None ) { setTags( *this, _tags ); } TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) : name( other.name ), className( other.className ), description( other.description ), tags( other.tags ), lcaseTags( other.lcaseTags ), tagsAsString( other.tagsAsString ), lineInfo( other.lineInfo ), properties( other.properties ) {} bool TestCaseInfo::isHidden() const { return ( properties & IsHidden ) != 0; } bool TestCaseInfo::throws() const { return ( properties & Throws ) != 0; } bool TestCaseInfo::okToFail() const { return ( properties & (ShouldFail | MayFail ) ) != 0; } bool TestCaseInfo::expectedToFail() const { return ( properties & (ShouldFail ) ) != 0; } TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} TestCase::TestCase( TestCase const& other ) : TestCaseInfo( other ), test( other.test ) {} TestCase TestCase::withName( std::string const& _newName ) const { TestCase other( *this ); other.name = _newName; return other; } void TestCase::swap( TestCase& other ) { test.swap( other.test ); name.swap( other.name ); className.swap( other.className ); description.swap( other.description ); tags.swap( other.tags ); lcaseTags.swap( other.lcaseTags ); tagsAsString.swap( other.tagsAsString ); std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties ); std::swap( lineInfo, other.lineInfo ); } void TestCase::invoke() const { test->invoke(); } bool TestCase::operator == ( TestCase const& other ) const { return test.get() == other.test.get() && name == other.name && className == other.className; } bool TestCase::operator < ( TestCase const& other ) const { return name < other.name; } TestCase& TestCase::operator = ( TestCase const& other ) { TestCase temp( other ); swap( temp ); return *this; } TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // #included from: catch_version.hpp #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED namespace Catch { Version::Version ( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ), minorVersion( _minorVersion ), patchNumber( _patchNumber ), branchName( _branchName ), buildNumber( _buildNumber ) {} std::ostream& operator << ( std::ostream& os, Version const& version ) { os << version.majorVersion << "." << version.minorVersion << "." << version.patchNumber; if( !version.branchName.empty() ) { os << "-" << version.branchName << "." << version.buildNumber; } return os; } Version libraryVersion( 1, 4, 0, "", 0 ); } // #included from: catch_message.hpp #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED namespace Catch { MessageInfo::MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ) : macroName( _macroName ), lineInfo( _lineInfo ), type( _type ), sequence( ++globalCount ) {} // This may need protecting if threading support is added unsigned int MessageInfo::globalCount = 0; //////////////////////////////////////////////////////////////////////////// ScopedMessage::ScopedMessage( MessageBuilder const& builder ) : m_info( builder.m_info ) { m_info.message = builder.m_stream.str(); getResultCapture().pushScopedMessage( m_info ); } ScopedMessage::ScopedMessage( ScopedMessage const& other ) : m_info( other.m_info ) {} ScopedMessage::~ScopedMessage() { getResultCapture().popScopedMessage( m_info ); } } // end namespace Catch // #included from: catch_legacy_reporter_adapter.hpp #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED // #included from: catch_legacy_reporter_adapter.h #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED namespace Catch { // Deprecated struct IReporter : IShared { virtual ~IReporter(); virtual bool shouldRedirectStdout() const = 0; virtual void StartTesting() = 0; virtual void EndTesting( Totals const& totals ) = 0; virtual void StartGroup( std::string const& groupName ) = 0; virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; virtual void Aborted() = 0; virtual void Result( AssertionResult const& result ) = 0; }; class LegacyReporterAdapter : public SharedImpl<IStreamingReporter> { public: LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter ); virtual ~LegacyReporterAdapter(); virtual ReporterPreferences getPreferences() const; virtual void noMatchingTestCases( std::string const& ); virtual void testRunStarting( TestRunInfo const& ); virtual void testGroupStarting( GroupInfo const& groupInfo ); virtual void testCaseStarting( TestCaseInfo const& testInfo ); virtual void sectionStarting( SectionInfo const& sectionInfo ); virtual void assertionStarting( AssertionInfo const& ); virtual bool assertionEnded( AssertionStats const& assertionStats ); virtual void sectionEnded( SectionStats const& sectionStats ); virtual void testCaseEnded( TestCaseStats const& testCaseStats ); virtual void testGroupEnded( TestGroupStats const& testGroupStats ); virtual void testRunEnded( TestRunStats const& testRunStats ); virtual void skipTest( TestCaseInfo const& ); private: Ptr<IReporter> m_legacyReporter; }; } namespace Catch { LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter ) : m_legacyReporter( legacyReporter ) {} LegacyReporterAdapter::~LegacyReporterAdapter() {} ReporterPreferences LegacyReporterAdapter::getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); return prefs; } void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { m_legacyReporter->StartTesting(); } void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { m_legacyReporter->StartGroup( groupInfo.name ); } void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { m_legacyReporter->StartTestCase( testInfo ); } void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); } void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { // Not on legacy interface } bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); rb << it->message; rb.setResultType( ResultWas::Info ); AssertionResult result = rb.build(); m_legacyReporter->Result( result ); } } } m_legacyReporter->Result( assertionStats.assertionResult ); return true; } void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { if( sectionStats.missingAssertions ) m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); } void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { m_legacyReporter->EndTestCase ( testCaseStats.testInfo, testCaseStats.totals, testCaseStats.stdOut, testCaseStats.stdErr ); } void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { if( testGroupStats.aborting ) m_legacyReporter->Aborted(); m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); } void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { m_legacyReporter->EndTesting( testRunStats.totals ); } void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { } } // #included from: catch_timer.hpp #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif #ifdef CATCH_PLATFORM_WINDOWS #include <windows.h> #else #include <sys/time.h> #endif namespace Catch { namespace { #ifdef CATCH_PLATFORM_WINDOWS uint64_t getCurrentTicks() { static uint64_t hz=0, hzo=0; if (!hz) { QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) ); QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) ); } uint64_t t; QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) ); return ((t-hzo)*1000000)/hz; } #else uint64_t getCurrentTicks() { timeval t; gettimeofday(&t,CATCH_NULL); return static_cast<uint64_t>( t.tv_sec ) * 1000000ull + static_cast<uint64_t>( t.tv_usec ); } #endif } void Timer::start() { m_ticks = getCurrentTicks(); } unsigned int Timer::getElapsedMicroseconds() const { return static_cast<unsigned int>(getCurrentTicks() - m_ticks); } unsigned int Timer::getElapsedMilliseconds() const { return static_cast<unsigned int>(getElapsedMicroseconds()/1000); } double Timer::getElapsedSeconds() const { return getElapsedMicroseconds()/1000000.0; } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_common.hpp #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ) { return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; } bool endsWith( std::string const& s, std::string const& suffix ) { return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; } bool contains( std::string const& s, std::string const& infix ) { return s.find( infix ) != std::string::npos; } void toLowerInPlace( std::string& s ) { std::transform( s.begin(), s.end(), s.begin(), ::tolower ); } std::string toLower( std::string const& s ) { std::string lc = s; toLowerInPlace( lc ); return lc; } std::string trim( std::string const& str ) { static char const* whitespaceChars = "\n\r\t "; std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars ); return start != std::string::npos ? str.substr( start, 1+end-start ) : ""; } bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaced = false; std::size_t i = str.find( replaceThis ); while( i != std::string::npos ) { replaced = true; str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); if( i < str.size()-withThis.size() ) i = str.find( replaceThis, i+withThis.size() ); else i = std::string::npos; } return replaced; } pluralise::pluralise( std::size_t count, std::string const& label ) : m_count( count ), m_label( label ) {} std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { os << pluraliser.m_count << " " << pluraliser.m_label; if( pluraliser.m_count != 1 ) os << "s"; return os; } SourceLineInfo::SourceLineInfo() : line( 0 ){} SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) : file( _file ), line( _line ) {} SourceLineInfo::SourceLineInfo( SourceLineInfo const& other ) : file( other.file ), line( other.line ) {} bool SourceLineInfo::empty() const { return file.empty(); } bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { return line == other.line && file == other.file; } bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { return line < other.line || ( line == other.line && file < other.file ); } void seedRng( IConfig const& config ) { if( config.rngSeed() != 0 ) std::srand( config.rngSeed() ); } unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); } std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { #ifndef __GNUG__ os << info.file << "(" << info.line << ")"; #else os << info.file << ":" << info.line; #endif return os; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { std::ostringstream oss; oss << locationInfo << ": Internal Catch error: '" << message << "'"; if( alwaysTrue() ) throw std::logic_error( oss.str() ); } } // #included from: catch_section.hpp #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED namespace Catch { SectionInfo::SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description ) : name( _name ), description( _description ), lineInfo( _lineInfo ) {} Section::Section( SectionInfo const& info ) : m_info( info ), m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) { m_timer.start(); } Section::~Section() { if( m_sectionIncluded ) { SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); if( std::uncaught_exception() ) getResultCapture().sectionEndedEarly( endInfo ); else getResultCapture().sectionEnded( endInfo ); } } // This indicates whether the section should be executed or not Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // #included from: catch_debugger.hpp #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED #include <iostream> #ifdef CATCH_PLATFORM_MAC #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> namespace Catch{ // The following function is taken directly from the following technical note: // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive(){ int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) { Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; return false; } // We're being debugged if the P_TRACED flag is set. return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); } } // namespace Catch #elif defined(_MSC_VER) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #elif defined(__MINGW32__) extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #else namespace Catch { inline bool isDebuggerActive() { return false; } } #endif // Platform #ifdef CATCH_PLATFORM_WINDOWS extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* ); namespace Catch { void writeToDebugConsole( std::string const& text ) { ::OutputDebugStringA( text.c_str() ); } } #else namespace Catch { void writeToDebugConsole( std::string const& text ) { // !TBD: Need a version for Mac/ XCode and other IDEs Catch::cout() << text; } } #endif // Platform // #included from: catch_tostring.hpp #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED namespace Catch { namespace Detail { const std::string unprintableString = "{?}"; namespace { const int hexThreshold = 255; struct Endianness { enum Arch { Big, Little }; static Arch which() { union _{ int asInt; char asChar[sizeof (int)]; } u; u.asInt = 1; return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; } }; } std::string rawMemoryToString( const void *object, std::size_t size ) { // Reverse order for little endian architectures int i = 0, end = static_cast<int>( size ), inc = 1; if( Endianness::which() == Endianness::Little ) { i = end-1; end = inc = -1; } unsigned char const *bytes = static_cast<unsigned char const *>(object); std::ostringstream os; os << "0x" << std::setfill('0') << std::hex; for( ; i != end; i += inc ) os << std::setw(2) << static_cast<unsigned>(bytes[i]); return os.str(); } } std::string toString( std::string const& value ) { std::string s = value; if( getCurrentContext().getConfig()->showInvisibles() ) { for(size_t i = 0; i < s.size(); ++i ) { std::string subs; switch( s[i] ) { case '\n': subs = "\\n"; break; case '\t': subs = "\\t"; break; default: break; } if( !subs.empty() ) { s = s.substr( 0, i ) + subs + s.substr( i+1 ); ++i; } } } return "\"" + s + "\""; } std::string toString( std::wstring const& value ) { std::string s; s.reserve( value.size() ); for(size_t i = 0; i < value.size(); ++i ) s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?'; return Catch::toString( s ); } std::string toString( const char* const value ) { return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); } std::string toString( char* const value ) { return Catch::toString( static_cast<const char*>( value ) ); } std::string toString( const wchar_t* const value ) { return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); } std::string toString( wchar_t* const value ) { return Catch::toString( static_cast<const wchar_t*>( value ) ); } std::string toString( int value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned int value ) { return Catch::toString( static_cast<unsigned long>( value ) ); } template<typename T> std::string fpToString( T value, int precision ) { std::ostringstream oss; oss << std::setprecision( precision ) << std::fixed << value; std::string d = oss.str(); std::size_t i = d.find_last_not_of( '0' ); if( i != std::string::npos && i != d.size()-1 ) { if( d[i] == '.' ) i++; d = d.substr( 0, i+1 ); } return d; } std::string toString( const double value ) { return fpToString( value, 10 ); } std::string toString( const float value ) { return fpToString( value, 5 ) + "f"; } std::string toString( bool value ) { return value ? "true" : "false"; } std::string toString( char value ) { return value < ' ' ? toString( static_cast<unsigned int>( value ) ) : Detail::makeString( value ); } std::string toString( signed char value ) { return toString( static_cast<char>( value ) ); } std::string toString( unsigned char value ) { return toString( static_cast<char>( value ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } std::string toString( unsigned long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << " (0x" << std::hex << value << ")"; return oss.str(); } #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ) { return "nullptr"; } #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ) { if( !nsstring ) return "nil"; return "@" + toString([nsstring UTF8String]); } std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { if( !nsstring ) return "nil"; return "@" + toString([nsstring UTF8String]); } std::string toString( NSObject* const& nsObject ) { return toString( [nsObject description] ); } #endif } // end namespace Catch // #included from: catch_result_builder.hpp #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED namespace Catch { std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) { return secondArg.empty() || secondArg == "\"\"" ? capturedExpression : capturedExpression + ", " + secondArg; } ResultBuilder::ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg ) : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ), m_shouldDebugBreak( false ), m_shouldThrow( false ) {} ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { m_data.resultType = result; return *this; } ResultBuilder& ResultBuilder::setResultType( bool result ) { m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; return *this; } ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) { m_exprComponents.lhs = lhs; return *this; } ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) { m_exprComponents.rhs = rhs; return *this; } ResultBuilder& ResultBuilder::setOp( std::string const& op ) { m_exprComponents.op = op; return *this; } void ResultBuilder::endExpression() { m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); captureExpression(); } void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { m_assertionInfo.resultDisposition = resultDisposition; m_stream.oss << Catch::translateActiveException(); captureResult( ResultWas::ThrewException ); } void ResultBuilder::captureResult( ResultWas::OfType resultType ) { setResultType( resultType ); captureExpression(); } void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { if( expectedMessage.empty() ) captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() ); else captureExpectedException( Matchers::Equals( expectedMessage ) ); } void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) { assert( m_exprComponents.testFalse == false ); AssertionResultData data = m_data; data.resultType = ResultWas::Ok; data.reconstructedExpression = m_assertionInfo.capturedExpression; std::string actualMessage = Catch::translateActiveException(); if( !matcher.match( actualMessage ) ) { data.resultType = ResultWas::ExpressionFailed; data.reconstructedExpression = actualMessage; } AssertionResult result( m_assertionInfo, data ); handleResult( result ); } void ResultBuilder::captureExpression() { AssertionResult result = build(); handleResult( result ); } void ResultBuilder::handleResult( AssertionResult const& result ) { getResultCapture().assertionEnded( result ); if( !result.isOk() ) { if( getCurrentContext().getConfig()->shouldDebugBreak() ) m_shouldDebugBreak = true; if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) m_shouldThrow = true; } } void ResultBuilder::react() { if( m_shouldThrow ) throw Catch::TestFailureException(); } bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } AssertionResult ResultBuilder::build() const { assert( m_data.resultType != ResultWas::Unknown ); AssertionResultData data = m_data; // Flip bool results if testFalse is set if( m_exprComponents.testFalse ) { if( data.resultType == ResultWas::Ok ) data.resultType = ResultWas::ExpressionFailed; else if( data.resultType == ResultWas::ExpressionFailed ) data.resultType = ResultWas::Ok; } data.message = m_stream.oss.str(); data.reconstructedExpression = reconstructExpression(); if( m_exprComponents.testFalse ) { if( m_exprComponents.op == "" ) data.reconstructedExpression = "!" + data.reconstructedExpression; else data.reconstructedExpression = "!(" + data.reconstructedExpression + ")"; } return AssertionResult( m_assertionInfo, data ); } std::string ResultBuilder::reconstructExpression() const { if( m_exprComponents.op == "" ) return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; else if( m_exprComponents.op == "matches" ) return m_exprComponents.lhs + " " + m_exprComponents.rhs; else if( m_exprComponents.op != "!" ) { if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && m_exprComponents.lhs.find("\n") == std::string::npos && m_exprComponents.rhs.find("\n") == std::string::npos ) return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs; else return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs; } else return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}"; } } // end namespace Catch // #included from: catch_tag_alias_registry.hpp #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED // #included from: catch_tag_alias_registry.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED #include <map> namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: virtual ~TagAliasRegistry(); virtual Option<TagAlias> find( std::string const& alias ) const; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); static TagAliasRegistry& get(); private: std::map<std::string, TagAlias> m_registry; }; } // end namespace Catch #include <map> #include <iostream> namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} Option<TagAlias> TagAliasRegistry::find( std::string const& alias ) const { std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias ); if( it != m_registry.end() ) return it->second; else return Option<TagAlias>(); } std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { std::string expandedTestSpec = unexpandedTestSpec; for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); it != itEnd; ++it ) { std::size_t pos = expandedTestSpec.find( it->first ); if( pos != std::string::npos ) { expandedTestSpec = expandedTestSpec.substr( 0, pos ) + it->second.tag + expandedTestSpec.substr( pos + it->first.size() ); } } return expandedTestSpec; } void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) { std::ostringstream oss; oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; throw std::domain_error( oss.str().c_str() ); } if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { std::ostringstream oss; oss << "error: tag alias, \"" << alias << "\" already registered.\n" << "\tFirst seen at " << find(alias)->lineInfo << "\n" << "\tRedefined at " << lineInfo; throw std::domain_error( oss.str().c_str() ); } } TagAliasRegistry& TagAliasRegistry::get() { static TagAliasRegistry instance; return instance; } ITagAliasRegistry::~ITagAliasRegistry() {} ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { try { TagAliasRegistry::get().add( alias, tag, lineInfo ); } catch( std::exception& ex ) { Colour colourGuard( Colour::Red ); Catch::cerr() << ex.what() << std::endl; exit(1); } } } // end namespace Catch // #included from: ../reporters/catch_reporter_multi.hpp #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED namespace Catch { class MultipleReporters : public SharedImpl<IStreamingReporter> { typedef std::vector<Ptr<IStreamingReporter> > Reporters; Reporters m_reporters; public: void add( Ptr<IStreamingReporter> const& reporter ) { m_reporters.push_back( reporter ); } public: // IStreamingReporter virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporters[0]->getPreferences(); } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->noMatchingTestCases( spec ); } virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunStarting( testRunInfo ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupStarting( groupInfo ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseStarting( testInfo ); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionStarting( sectionInfo ); } virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->assertionStarting( assertionInfo ); } // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { bool clearBuffer = false; for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) clearBuffer |= (*it)->assertionEnded( assertionStats ); return clearBuffer; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionEnded( sectionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupEnded( testGroupStats ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunEnded( testRunStats ); } virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->skipTest( testInfo ); } }; Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) { Ptr<IStreamingReporter> resultingReporter; if( existingReporter ) { MultipleReporters* multi = dynamic_cast<MultipleReporters*>( existingReporter.get() ); if( !multi ) { multi = new MultipleReporters; resultingReporter = Ptr<IStreamingReporter>( multi ); if( existingReporter ) multi->add( existingReporter ); } else resultingReporter = existingReporter; multi->add( additionalReporter ); } else resultingReporter = additionalReporter; return resultingReporter; } } // end namespace Catch // #included from: ../reporters/catch_reporter_xml.hpp #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED // #included from: catch_reporter_bases.hpp #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED #include <cstring> namespace Catch { struct StreamingReporterBase : SharedImpl<IStreamingReporter> { StreamingReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual ~StreamingReporterBase() CATCH_OVERRIDE; virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE { currentTestRunInfo = _testRunInfo; } virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE { currentGroupInfo = _groupInfo; } virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE { currentTestCaseInfo = _testInfo; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_sectionStack.push_back( _sectionInfo ); } virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE { m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); } virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE { currentGroupInfo.reset(); } virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); currentGroupInfo.reset(); currentTestRunInfo.reset(); } virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } Ptr<IConfig const> m_config; std::ostream& stream; LazyStat<TestRunInfo> currentTestRunInfo; LazyStat<GroupInfo> currentGroupInfo; LazyStat<TestCaseInfo> currentTestCaseInfo; std::vector<SectionInfo> m_sectionStack; ReporterPreferences m_reporterPrefs; }; struct CumulativeReporterBase : SharedImpl<IStreamingReporter> { template<typename T, typename ChildNodeT> struct Node : SharedImpl<> { explicit Node( T const& _value ) : value( _value ) {} virtual ~Node() {} typedef std::vector<Ptr<ChildNodeT> > ChildNodes; T value; ChildNodes children; }; struct SectionNode : SharedImpl<> { explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} virtual ~SectionNode(); bool operator == ( SectionNode const& other ) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } bool operator == ( Ptr<SectionNode> const& other ) const { return operator==( *other ); } SectionStats stats; typedef std::vector<Ptr<SectionNode> > ChildSections; typedef std::vector<AssertionStats> Assertions; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; struct BySectionInfo { BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} bool operator() ( Ptr<SectionNode> const& node ) const { return node->stats.sectionInfo.lineInfo == m_other.lineInfo; } private: void operator=( BySectionInfo const& ); SectionInfo const& m_other; }; typedef Node<TestCaseStats, SectionNode> TestCaseNode; typedef Node<TestGroupStats, TestCaseNode> TestGroupNode; typedef Node<TestRunStats, TestGroupNode> TestRunNode; CumulativeReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } ~CumulativeReporterBase(); virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {} virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {} virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {} virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); Ptr<SectionNode> node; if( m_sectionStack.empty() ) { if( !m_rootSection ) m_rootSection = new SectionNode( incompleteStats ); node = m_rootSection; } else { SectionNode& parentNode = *m_sectionStack.back(); SectionNode::ChildSections::const_iterator it = std::find_if( parentNode.childSections.begin(), parentNode.childSections.end(), BySectionInfo( sectionInfo ) ); if( it == parentNode.childSections.end() ) { node = new SectionNode( incompleteStats ); parentNode.childSections.push_back( node ); } else node = *it; } m_sectionStack.push_back( node ); m_deepestSection = node; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& assertionStats ) { assert( !m_sectionStack.empty() ); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back( assertionStats ); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { assert( !m_sectionStack.empty() ); SectionNode& node = *m_sectionStack.back(); node.stats = sectionStats; m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats ); assert( m_sectionStack.size() == 0 ); node->children.push_back( m_rootSection ); m_testCases.push_back( node ); m_rootSection.reset(); assert( m_deepestSection ); m_deepestSection->stdOut = testCaseStats.stdOut; m_deepestSection->stdErr = testCaseStats.stdErr; } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats ); node->children.swap( m_testCases ); m_testGroups.push_back( node ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { Ptr<TestRunNode> node = new TestRunNode( testRunStats ); node->children.swap( m_testGroups ); m_testRuns.push_back( node ); testRunEndedCumulative(); } virtual void testRunEndedCumulative() = 0; virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} Ptr<IConfig const> m_config; std::ostream& stream; std::vector<AssertionStats> m_assertions; std::vector<std::vector<Ptr<SectionNode> > > m_sections; std::vector<Ptr<TestCaseNode> > m_testCases; std::vector<Ptr<TestGroupNode> > m_testGroups; std::vector<Ptr<TestRunNode> > m_testRuns; Ptr<SectionNode> m_rootSection; Ptr<SectionNode> m_deepestSection; std::vector<Ptr<SectionNode> > m_sectionStack; ReporterPreferences m_reporterPrefs; }; template<char C> char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; if( !*line ) { memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; } return line; } struct TestEventListenerBase : StreamingReporterBase { TestEventListenerBase( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE { return false; } }; } // end namespace Catch // #included from: ../internal/catch_reporter_registrars.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED namespace Catch { template<typename T> class LegacyReporterRegistrar { class ReporterFactory : public IReporterFactory { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new LegacyReporterAdapter( new T( config ) ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: LegacyReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template<typename T> class ReporterRegistrar { class ReporterFactory : public SharedImpl<IReporterFactory> { // *** Please Note ***: // - If you end up here looking at a compiler error because it's trying to register // your custom reporter class be aware that the native reporter interface has changed // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. // However please consider updating to the new interface as the old one is now // deprecated and will probably be removed quite soon! // Please contact me via github if you have any questions at all about this. // In fact, ideally, please contact me anyway to let me know you've hit this - as I have // no idea who is actually using custom reporters at all (possibly no-one!). // The new interface is designed to minimise exposure to interface changes in the future. virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template<typename T> class ListenerRegistrar { class ListenerFactory : public SharedImpl<IReporterFactory> { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return ""; } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( new ListenerFactory() ); } }; } #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } // #included from: ../internal/catch_xmlwriter.hpp #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED #include <sstream> #include <string> #include <vector> #include <iomanip> namespace Catch { class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ) : m_str( str ), m_forWhat( forWhat ) {} void encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: http://www.w3.org/TR/xml/#syntax) for( std::size_t i = 0; i < m_str.size(); ++ i ) { char c = m_str[i]; switch( c ) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: http://www.w3.org/TR/xml/#syntax if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) os << "&gt;"; else os << c; break; case '\"': if( m_forWhat == ForAttributes ) os << "&quot;"; else os << c; break; default: // Escape control chars - based on contribution by @espenalb in PR #465 if ( ( c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) os << "&#x" << std::uppercase << std::hex << static_cast<int>( c ); else os << c; } } } friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} ScopedElement( ScopedElement const& other ) : m_writer( other.m_writer ){ other.m_writer = CATCH_NULL; } ~ScopedElement() { if( m_writer ) m_writer->endElement(); } ScopedElement& writeText( std::string const& text, bool indent = true ) { m_writer->writeText( text, indent ); return *this; } template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer; }; XmlWriter() : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &Catch::cout() ) {} XmlWriter( std::ostream& os ) : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &os ) {} ~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); stream() << m_indent << "<" << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } ScopedElement scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { stream() << "/>\n"; m_tagIsOpen = false; } else { stream() << m_indent << "</" << m_tags.back() << ">\n"; } m_tags.pop_back(); return *this; } XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) stream() << " " << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << "\""; return *this; } XmlWriter& writeAttribute( std::string const& name, bool attribute ) { stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\""; return *this; } template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { std::ostringstream oss; oss << attribute; return writeAttribute( name, oss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) stream() << m_indent; stream() << XmlEncode( text ); m_needsNewline = true; } return *this; } XmlWriter& writeComment( std::string const& text ) { ensureTagClosed(); stream() << m_indent << "<!--" << text << "-->"; m_needsNewline = true; return *this; } XmlWriter& writeBlankLine() { ensureTagClosed(); stream() << "\n"; return *this; } void setStream( std::ostream& os ) { m_os = &os; } private: XmlWriter( XmlWriter const& ); void operator=( XmlWriter const& ); std::ostream& stream() { return *m_os; } void ensureTagClosed() { if( m_tagIsOpen ) { stream() << ">\n"; m_tagIsOpen = false; } } void newlineIfNecessary() { if( m_needsNewline ) { stream() << "\n"; m_needsNewline = false; } } bool m_tagIsOpen; bool m_needsNewline; std::vector<std::string> m_tags; std::string m_indent; std::ostream* m_os; }; } // #included from: catch_reenable_warnings.h #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(pop) # else # pragma clang diagnostic pop # endif #elif defined __GNUC__ # pragma GCC diagnostic pop #endif namespace Catch { class XmlReporter : public StreamingReporterBase { public: XmlReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_sectionDepth( 0 ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~XmlReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results as an XML document"; } public: // StreamingReporterBase virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { StreamingReporterBase::noMatchingTestCases( s ); } virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testRunStarting( testInfo ); m_xml.setStream( stream ); m_xml.startElement( "Catch" ); if( !m_config->name().empty() ) m_xml.writeAttribute( "name", m_config->name() ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { StreamingReporterBase::testGroupStarting( groupInfo ); m_xml.startElement( "Group" ) .writeAttribute( "name", groupInfo.name ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testCaseStarting(testInfo); m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) ); if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { StreamingReporterBase::sectionStarting( sectionInfo ); if( m_sectionDepth++ > 0 ) { m_xml.startElement( "Section" ) .writeAttribute( "name", trim( sectionInfo.name ) ) .writeAttribute( "description", sectionInfo.description ); } } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { const AssertionResult& assertionResult = assertionStats.assertionResult; // Print any info messages in <Info> tags. if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { m_xml.scopedElement( "Info" ) .writeText( it->message ); } else if ( it->type == ResultWas::Warning ) { m_xml.scopedElement( "Warning" ) .writeText( it->message ); } } } // Drop out if result was successful but we're not printing them. if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) return true; // Print the expression if there is one. if( assertionResult.hasExpression() ) { m_xml.startElement( "Expression" ) .writeAttribute( "success", assertionResult.succeeded() ) .writeAttribute( "type", assertionResult.getTestMacroName() ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ); m_xml.scopedElement( "Original" ) .writeText( assertionResult.getExpression() ); m_xml.scopedElement( "Expanded" ) .writeText( assertionResult.getExpandedExpression() ); } // And... Print a result applicable to each result type. switch( assertionResult.getResultType() ) { case ResultWas::ThrewException: m_xml.scopedElement( "Exception" ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::FatalErrorCondition: m_xml.scopedElement( "Fatal Error Condition" ) .writeAttribute( "filename", assertionResult.getSourceInfo().file ) .writeAttribute( "line", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Info: m_xml.scopedElement( "Info" ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.scopedElement( "Failure" ) .writeText( assertionResult.getMessage() ); break; default: break; } if( assertionResult.hasExpression() ) m_xml.endElement(); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { StreamingReporterBase::sectionEnded( sectionStats ); if( --m_sectionDepth > 0 ) { XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); e.writeAttribute( "successes", sectionStats.assertions.passed ); e.writeAttribute( "failures", sectionStats.assertions.failed ); e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); m_xml.endElement(); } } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( testCaseStats ); XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); m_xml.endElement(); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { StreamingReporterBase::testGroupEnded( testGroupStats ); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); m_xml.endElement(); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { StreamingReporterBase::testRunEnded( testRunStats ); m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testRunStats.totals.assertions.passed ) .writeAttribute( "failures", testRunStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); m_xml.endElement(); } private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth; }; INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_junit.hpp #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED #include <assert.h> namespace Catch { class JunitReporter : public CumulativeReporterBase { public: JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ), xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~JunitReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results in an XML format that looks like Ant's junitreport target"; } virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE { CumulativeReporterBase::testRunStarting( runInfo ); xml.startElement( "testsuites" ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { suiteTimer.start(); stdOutForSuite.str(""); stdErrForSuite.str(""); unexpectedExceptions = 0; CumulativeReporterBase::testGroupStarting( groupInfo ); } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { stdOutForSuite << testCaseStats.stdOut; stdErrForSuite << testCaseStats.stdErr; CumulativeReporterBase::testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { double suiteTime = suiteTimer.getElapsedSeconds(); CumulativeReporterBase::testGroupEnded( testGroupStats ); writeGroup( *m_testGroups.back(), suiteTime ); } virtual void testRunEndedCumulative() CATCH_OVERRIDE { xml.endElement(); } void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); TestGroupStats const& stats = groupNode.value; xml.writeAttribute( "name", stats.groupInfo.name ); xml.writeAttribute( "errors", unexpectedExceptions ); xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); xml.writeAttribute( "tests", stats.totals.assertions.total() ); xml.writeAttribute( "hostname", "tbd" ); // !TBD if( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( "time", "" ); else xml.writeAttribute( "time", suiteTime ); xml.writeAttribute( "timestamp", "tbd" ); // !TBD // Write test cases for( TestGroupNode::ChildNodes::const_iterator it = groupNode.children.begin(), itEnd = groupNode.children.end(); it != itEnd; ++it ) writeTestCase( **it ); xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); } void writeTestCase( TestCaseNode const& testCaseNode ) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections assert( testCaseNode.children.size() == 1 ); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; if( className.empty() ) { if( rootSection.childSections.empty() ) className = "global"; } writeSection( className, "", rootSection ); } void writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if( !rootName.empty() ) name = rootName + "/" + name; if( !sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty() ) { XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); if( className.empty() ) { xml.writeAttribute( "classname", name ); xml.writeAttribute( "name", "root" ); } else { xml.writeAttribute( "classname", className ); xml.writeAttribute( "name", name ); } xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); writeAssertions( sectionNode ); if( !sectionNode.stdOut.empty() ) xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); if( !sectionNode.stdErr.empty() ) xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); } for( SectionNode::ChildSections::const_iterator it = sectionNode.childSections.begin(), itEnd = sectionNode.childSections.end(); it != itEnd; ++it ) if( className.empty() ) writeSection( name, "", **it ); else writeSection( className, name, **it ); } void writeAssertions( SectionNode const& sectionNode ) { for( SectionNode::Assertions::const_iterator it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); it != itEnd; ++it ) writeAssertion( *it ); } void writeAssertion( AssertionStats const& stats ) { AssertionResult const& result = stats.assertionResult; if( !result.isOk() ) { std::string elementName; switch( result.getResultType() ) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = "error"; break; case ResultWas::ExplicitFailure: elementName = "failure"; break; case ResultWas::ExpressionFailed: elementName = "failure"; break; case ResultWas::DidntThrowException: elementName = "failure"; break; // We should never see these here: case ResultWas::Info: case ResultWas::Warning: case ResultWas::Ok: case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: elementName = "internalError"; break; } XmlWriter::ScopedElement e = xml.scopedElement( elementName ); xml.writeAttribute( "message", result.getExpandedExpression() ); xml.writeAttribute( "type", result.getTestMacroName() ); std::ostringstream oss; if( !result.getMessage().empty() ) oss << result.getMessage() << "\n"; for( std::vector<MessageInfo>::const_iterator it = stats.infoMessages.begin(), itEnd = stats.infoMessages.end(); it != itEnd; ++it ) if( it->type == ResultWas::Info ) oss << it->message << "\n"; oss << "at " << result.getSourceInfo(); xml.writeText( oss.str(), false ); } } XmlWriter xml; Timer suiteTimer; std::ostringstream stdOutForSuite; std::ostringstream stdErrForSuite; unsigned int unexpectedExceptions; }; INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_console.hpp #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED namespace Catch { struct ConsoleReporter : StreamingReporterBase { ConsoleReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_headerPrinted( false ) {} virtual ~ConsoleReporter() CATCH_OVERRIDE; static std::string getDescription() { return "Reports test results as plain lines of text"; } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { stream << "No test cases matched '" << spec << "'" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } lazyPrint(); AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_headerPrinted = false; StreamingReporterBase::sectionStarting( _sectionInfo ); } virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE { if( _sectionStats.missingAssertions ) { lazyPrint(); Colour colour( Colour::ResultError ); if( m_sectionStack.size() > 1 ) stream << "\nNo assertions in section"; else stream << "\nNo assertions in test case"; stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; } if( m_headerPrinted ) { if( m_config->showDurations() == ShowDurations::Always ) stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; m_headerPrinted = false; } else { if( m_config->showDurations() == ShowDurations::Always ) stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; } StreamingReporterBase::sectionEnded( _sectionStats ); } virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( _testCaseStats ); m_headerPrinted = false; } virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE { if( currentGroupInfo.used ) { printSummaryDivider(); stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; printTotals( _testGroupStats.totals ); stream << "\n" << std::endl; } StreamingReporterBase::testGroupEnded( _testGroupStats ); } virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE { printTotalsDivider( _testRunStats.totals ); printTotals( _testRunStats.totals ); stream << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ), stats( _stats ), result( _stats.assertionResult ), colour( Colour::None ), message( result.getMessage() ), messages( _stats.infoMessages ), printInfoMessages( _printInfoMessages ) { switch( result.getResultType() ) { case ResultWas::Ok: colour = Colour::Success; passOrFail = "PASSED"; //if( result.hasMessage() ) if( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ExpressionFailed: if( result.isOk() ) { colour = Colour::Success; passOrFail = "FAILED - but was ok"; } else { colour = Colour::Error; passOrFail = "FAILED"; } if( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ThrewException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to unexpected exception with message"; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to a fatal error condition"; break; case ResultWas::DidntThrowException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "because no exception was thrown where one was expected"; break; case ResultWas::Info: messageLabel = "info"; break; case ResultWas::Warning: messageLabel = "warning"; break; case ResultWas::ExplicitFailure: passOrFail = "FAILED"; colour = Colour::Error; if( _stats.infoMessages.size() == 1 ) messageLabel = "explicitly with message"; if( _stats.infoMessages.size() > 1 ) messageLabel = "explicitly with messages"; break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: passOrFail = "** internal error **"; colour = Colour::Error; break; } } void print() const { printSourceInfo(); if( stats.totals.assertions.total() > 0 ) { if( result.isOk() ) stream << "\n"; printResultType(); printOriginalExpression(); printReconstructedExpression(); } else { stream << "\n"; } printMessage(); } private: void printResultType() const { if( !passOrFail.empty() ) { Colour colourGuard( colour ); stream << passOrFail << ":\n"; } } void printOriginalExpression() const { if( result.hasExpression() ) { Colour colourGuard( Colour::OriginalExpression ); stream << " "; stream << result.getExpressionInMacro(); stream << "\n"; } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { stream << "with expansion:\n"; Colour colourGuard( Colour::ReconstructedExpression ); stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n"; } } void printMessage() const { if( !messageLabel.empty() ) stream << messageLabel << ":" << "\n"; for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end(); it != itEnd; ++it ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || it->type != ResultWas::Info ) stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n"; } } void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ": "; } std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; Colour::Code colour; std::string passOrFail; std::string messageLabel; std::string message; std::vector<MessageInfo> messages; bool printInfoMessages; }; void lazyPrint() { if( !currentTestRunInfo.used ) lazyPrintRunInfo(); if( !currentGroupInfo.used ) lazyPrintGroupInfo(); if( !m_headerPrinted ) { printTestCaseAndSectionHeader(); m_headerPrinted = true; } } void lazyPrintRunInfo() { stream << "\n" << getLineOfChars<'~'>() << "\n"; Colour colour( Colour::SecondaryText ); stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion << " host application.\n" << "Run with -? for options\n\n"; if( m_config->rngSeed() != 0 ) stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; currentTestRunInfo.used = true; } void lazyPrintGroupInfo() { if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { printClosedHeader( "Group: " + currentGroupInfo->name ); currentGroupInfo.used = true; } } void printTestCaseAndSectionHeader() { assert( !m_sectionStack.empty() ); printOpenHeader( currentTestCaseInfo->name ); if( m_sectionStack.size() > 1 ) { Colour colourGuard( Colour::Headers ); std::vector<SectionInfo>::const_iterator it = m_sectionStack.begin()+1, // Skip first section (test case) itEnd = m_sectionStack.end(); for( ; it != itEnd; ++it ) printHeaderString( it->name, 2 ); } SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; if( !lineInfo.empty() ){ stream << getLineOfChars<'-'>() << "\n"; Colour colourGuard( Colour::FileName ); stream << lineInfo << "\n"; } stream << getLineOfChars<'.'>() << "\n" << std::endl; } void printClosedHeader( std::string const& _name ) { printOpenHeader( _name ); stream << getLineOfChars<'.'>() << "\n"; } void printOpenHeader( std::string const& _name ) { stream << getLineOfChars<'-'>() << "\n"; { Colour colourGuard( Colour::Headers ); printHeaderString( _name ); } } // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { std::size_t i = _string.find( ": " ); if( i != std::string::npos ) i+=2; else i = 0; stream << Text( _string, TextAttributes() .setIndent( indent+i) .setInitialIndent( indent ) ) << "\n"; } struct SummaryColumn { SummaryColumn( std::string const& _label, Colour::Code _colour ) : label( _label ), colour( _colour ) {} SummaryColumn addRow( std::size_t count ) { std::ostringstream oss; oss << count; std::string row = oss.str(); for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) { while( it->size() < row.size() ) *it = " " + *it; while( it->size() > row.size() ) row = " " + row; } rows.push_back( row ); return *this; } std::string label; Colour::Code colour; std::vector<std::string> rows; }; void printTotals( Totals const& totals ) { if( totals.testCases.total() == 0 ) { stream << Colour( Colour::Warning ) << "No tests ran\n"; } else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { stream << Colour( Colour::ResultSuccess ) << "All tests passed"; stream << " (" << pluralise( totals.assertions.passed, "assertion" ) << " in " << pluralise( totals.testCases.passed, "test case" ) << ")" << "\n"; } else { std::vector<SummaryColumn> columns; columns.push_back( SummaryColumn( "", Colour::None ) .addRow( totals.testCases.total() ) .addRow( totals.assertions.total() ) ); columns.push_back( SummaryColumn( "passed", Colour::Success ) .addRow( totals.testCases.passed ) .addRow( totals.assertions.passed ) ); columns.push_back( SummaryColumn( "failed", Colour::ResultError ) .addRow( totals.testCases.failed ) .addRow( totals.assertions.failed ) ); columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) .addRow( totals.testCases.failedButOk ) .addRow( totals.assertions.failedButOk ) ); printSummaryRow( "test cases", columns, 0 ); printSummaryRow( "assertions", columns, 1 ); } } void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) { for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) { std::string value = it->rows[row]; if( it->label.empty() ) { stream << label << ": "; if( value != "0" ) stream << value; else stream << Colour( Colour::Warning ) << "- none -"; } else if( value != "0" ) { stream << Colour( Colour::LightGrey ) << " | "; stream << Colour( it->colour ) << value << " " << it->label; } } stream << "\n"; } static std::size_t makeRatio( std::size_t number, std::size_t total ) { std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; return ( ratio == 0 && number > 0 ) ? 1 : ratio; } static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { if( i > j && i > k ) return i; else if( j > k ) return j; else return k; } void printTotalsDivider( Totals const& totals ) { if( totals.testCases.total() > 0 ) { std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )++; while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )--; stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); if( totals.testCases.allPassed() ) stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); else stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); } else { stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); } stream << "\n"; } void printSummaryDivider() { stream << getLineOfChars<'-'>() << "\n"; } private: bool m_headerPrinted; }; INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_compact.hpp #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED namespace Catch { struct CompactReporter : StreamingReporterBase { CompactReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual ~CompactReporter(); static std::string getDescription() { return "Reports test results on a single line, suitable for IDEs"; } virtual ReporterPreferences getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = false; return prefs; } virtual void noMatchingTestCases( std::string const& spec ) { stream << "No test cases matched '" << spec << "'" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void testRunEnded( TestRunStats const& _testRunStats ) { printTotals( _testRunStats.totals ); stream << "\n" << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ) , stats( _stats ) , result( _stats.assertionResult ) , messages( _stats.infoMessages ) , itMessage( _stats.infoMessages.begin() ) , printInfoMessages( _printInfoMessages ) {} void print() { printSourceInfo(); itMessage = messages.begin(); switch( result.getResultType() ) { case ResultWas::Ok: printResultType( Colour::ResultSuccess, passedString() ); printOriginalExpression(); printReconstructedExpression(); if ( ! result.hasExpression() ) printRemainingMessages( Colour::None ); else printRemainingMessages(); break; case ResultWas::ExpressionFailed: if( result.isOk() ) printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); else printResultType( Colour::Error, failedString() ); printOriginalExpression(); printReconstructedExpression(); printRemainingMessages(); break; case ResultWas::ThrewException: printResultType( Colour::Error, failedString() ); printIssue( "unexpected exception with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::FatalErrorCondition: printResultType( Colour::Error, failedString() ); printIssue( "fatal error condition with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::DidntThrowException: printResultType( Colour::Error, failedString() ); printIssue( "expected exception, got none" ); printExpressionWas(); printRemainingMessages(); break; case ResultWas::Info: printResultType( Colour::None, "info" ); printMessage(); printRemainingMessages(); break; case ResultWas::Warning: printResultType( Colour::None, "warning" ); printMessage(); printRemainingMessages(); break; case ResultWas::ExplicitFailure: printResultType( Colour::Error, failedString() ); printIssue( "explicitly" ); printRemainingMessages( Colour::None ); break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: printResultType( Colour::Error, "** internal error **" ); break; } } private: // Colour::LightGrey static Colour::Code dimColour() { return Colour::FileName; } #ifdef CATCH_PLATFORM_MAC static const char* failedString() { return "FAILED"; } static const char* passedString() { return "PASSED"; } #else static const char* failedString() { return "failed"; } static const char* passedString() { return "passed"; } #endif void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ":"; } void printResultType( Colour::Code colour, std::string passOrFail ) const { if( !passOrFail.empty() ) { { Colour colourGuard( colour ); stream << " " << passOrFail; } stream << ":"; } } void printIssue( std::string issue ) const { stream << " " << issue; } void printExpressionWas() { if( result.hasExpression() ) { stream << ";"; { Colour colour( dimColour() ); stream << " expression was:"; } printOriginalExpression(); } } void printOriginalExpression() const { if( result.hasExpression() ) { stream << " " << result.getExpression(); } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { { Colour colour( dimColour() ); stream << " for: "; } stream << result.getExpandedExpression(); } } void printMessage() { if ( itMessage != messages.end() ) { stream << " '" << itMessage->message << "'"; ++itMessage; } } void printRemainingMessages( Colour::Code colour = dimColour() ) { if ( itMessage == messages.end() ) return; // using messages.end() directly yields compilation error: std::vector<MessageInfo>::const_iterator itEnd = messages.end(); const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) ); { Colour colourGuard( colour ); stream << " with " << pluralise( N, "message" ) << ":"; } for(; itMessage != itEnd; ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || itMessage->type != ResultWas::Info ) { stream << " '" << itMessage->message << "'"; if ( ++itMessage != itEnd ) { Colour colourGuard( dimColour() ); stream << " and"; } } } } private: std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; std::vector<MessageInfo> messages; std::vector<MessageInfo>::const_iterator itMessage; bool printInfoMessages; }; // Colour, message variants: // - white: No tests ran. // - red: Failed [both/all] N test cases, failed [both/all] M assertions. // - white: Passed [both/all] N test cases (no assertions). // - red: Failed N tests cases, failed M assertions. // - green: Passed [both/all] N tests cases with M assertions. std::string bothOrAll( std::size_t count ) const { return count == 1 ? "" : count == 2 ? "both " : "all " ; } void printTotals( const Totals& totals ) const { if( totals.testCases.total() == 0 ) { stream << "No tests ran."; } else if( totals.testCases.failed == totals.testCases.total() ) { Colour colour( Colour::ResultError ); const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll( totals.assertions.failed ) : ""; stream << "Failed " << bothOrAll( totals.testCases.failed ) << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << qualify_assertions_failed << pluralise( totals.assertions.failed, "assertion" ) << "."; } else if( totals.assertions.total() == 0 ) { stream << "Passed " << bothOrAll( totals.testCases.total() ) << pluralise( totals.testCases.total(), "test case" ) << " (no assertions)."; } else if( totals.assertions.failed ) { Colour colour( Colour::ResultError ); stream << "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << pluralise( totals.assertions.failed, "assertion" ) << "."; } else { Colour colour( Colour::ResultSuccess ); stream << "Passed " << bothOrAll( totals.testCases.passed ) << pluralise( totals.testCases.passed, "test case" ) << " with " << pluralise( totals.assertions.passed, "assertion" ) << "."; } } }; INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) } // end namespace Catch namespace Catch { // These are all here to avoid warnings about not having any out of line // virtual methods NonCopyable::~NonCopyable() {} IShared::~IShared() {} IStream::~IStream() CATCH_NOEXCEPT {} FileStream::~FileStream() CATCH_NOEXCEPT {} CoutStream::~CoutStream() CATCH_NOEXCEPT {} DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} IContext::~IContext() {} IResultCapture::~IResultCapture() {} ITestCase::~ITestCase() {} ITestCaseRegistry::~ITestCaseRegistry() {} IRegistryHub::~IRegistryHub() {} IMutableRegistryHub::~IMutableRegistryHub() {} IExceptionTranslator::~IExceptionTranslator() {} IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} IReporter::~IReporter() {} IReporterFactory::~IReporterFactory() {} IReporterRegistry::~IReporterRegistry() {} IStreamingReporter::~IStreamingReporter() {} AssertionStats::~AssertionStats() {} SectionStats::~SectionStats() {} TestCaseStats::~TestCaseStats() {} TestGroupStats::~TestGroupStats() {} TestRunStats::~TestRunStats() {} CumulativeReporterBase::SectionNode::~SectionNode() {} CumulativeReporterBase::~CumulativeReporterBase() {} StreamingReporterBase::~StreamingReporterBase() {} ConsoleReporter::~ConsoleReporter() {} CompactReporter::~CompactReporter() {} IRunner::~IRunner() {} IMutableContext::~IMutableContext() {} IConfig::~IConfig() {} XmlReporter::~XmlReporter() {} JunitReporter::~JunitReporter() {} TestRegistry::~TestRegistry() {} FreeFunctionTestCase::~FreeFunctionTestCase() {} IGeneratorInfo::~IGeneratorInfo() {} IGeneratorsForTest::~IGeneratorsForTest() {} WildcardPattern::~WildcardPattern() {} TestSpec::Pattern::~Pattern() {} TestSpec::NamePattern::~NamePattern() {} TestSpec::TagPattern::~TagPattern() {} TestSpec::ExcludedPattern::~ExcludedPattern() {} Matchers::Impl::StdString::Equals::~Equals() {} Matchers::Impl::StdString::Contains::~Contains() {} Matchers::Impl::StdString::StartsWith::~StartsWith() {} Matchers::Impl::StdString::EndsWith::~EndsWith() {} void Config::dummy() {} namespace TestCaseTracking { ITracker::~ITracker() {} TrackerBase::~TrackerBase() {} SectionTracker::~SectionTracker() {} IndexTracker::~IndexTracker() {} } } #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #ifdef CATCH_CONFIG_MAIN // #included from: internal/catch_default_main.hpp #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED #ifndef __OBJC__ // Standard C/C++ main entry point int main (int argc, char * argv[]) { return Catch::Session().run( argc, argv ); } #else // __OBJC__ // Objective-C entry point int main (int argc, char * const argv[]) { #if !CATCH_ARC_ENABLED NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); int result = Catch::Session().run( argc, (char* const*)argv ); #if !CATCH_ARC_ENABLED [pool drain]; #endif return result; } #endif // __OBJC__ #endif #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED # undef CLARA_CONFIG_MAIN #endif ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "CATCH_REQUIRE_THROWS" ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "CATCH_REQUIRE_THROWS_WITH" ) #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" ) #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) #else #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) #endif #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" ) #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" ) #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" ) #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" ) #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "REQUIRE_THROWS" ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "REQUIRE_THROWS_WITH" ) #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CHECK_THROWS" ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CHECK_THROWS_WITH" ) #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) #define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) #else #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) #endif #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // "BDD-style" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #else #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) #endif #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" ) #define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" ) #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" ) #define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" ) #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" ) using Catch::Detail::Approx; #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
[ "syoyo@lighttransport.com" ]
syoyo@lighttransport.com