blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
7ed776ef500a726aa8a72d3a9143bcaebae1a792
bf9ca8636584e8112c392d6ca5cd85b6be4f6ebf
/src/PhysicsObject.h
95d6e57eef1a4f45076fe0f2fb575bd1be2c59f8
[]
no_license
RileyA/LD19_Aquatic
34e8e08a450ee9f53365d98ebef505341869dfb5
c30e1f8e3304428e7077cb2042b4169450a35db9
refs/heads/master
2020-05-18T08:49:05.084811
2011-02-17T07:36:14
2011-02-17T07:36:14
1,377,029
0
0
null
null
null
null
UTF-8
C++
false
false
4,545
h
#ifndef PHYSICSOBJECT_H #define PHYSICSOBJECT_H // borrowed from another project of mine... #include "stdafx.h" /** A physics object (either a static or a rigid body) this class functions as a wrapper for bullet functions and does automatic interpolation. */ class PhysicsObject { public: PhysicsObject(btRigidBody* actor,btDynamicsWorld* dynWorld); PhysicsObject(btCollisionObject* actor,btDynamicsWorld* dynWorld); ~PhysicsObject(); /** Returns a pointer the bullet rigid body \returns a pointer to the bullet rigid body */ btRigidBody* getActor(); /** Sets the object's position \param pos the desired position */ void setPosition(Ogre::Vector3 pos); /** Sets the object's orientation \param pos the desired orientation */ void setOrientation(Ogre::Quaternion ori); /** Gets the object's position \returns the object's position */ Ogre::Vector3 getPosition(); /** Gets the object's orientation \returns the object's orientation */ Ogre::Quaternion getOrientation(); /** Adds a force at a position on the body \param dir the force \param pos relative position on the body to apply the force to */ void addForce(Ogre::Vector3 force,Ogre::Vector3 pos=Ogre::Vector3(0,0,0)); /** Adds an impulse at a position on the body \param dir the impulse \param impulse relative position on the body to apply the impulse to */ void addImpulse(Ogre::Vector3 impulse,Ogre::Vector3 pos=Ogre::Vector3(0,0,0)); /** Sets this object's velocity \param velocity the velocity */ void setVelocity(Ogre::Vector3 velocity); /** Gets this object's velocity \returns the object's velocity */ Ogre::Vector3 getVelocity(); /** Sets the object's mass \param mass the desired mass */ void setMass(float mass); /** Forces the object to wake up from a sleep state */ void wakeup(); /** Forces the object into a sleep state */ void toSleep(); /** Sets whether this object will be able to fall asleep due to inactivity \param enabled whether or not sleeping is enabled */ void setSleepingEnabled(bool enabled); /** Sets the linear factor (0 disables motion on an axis entirely) \param factor The factor in the form of a vector */ void setLinearFactor(Ogre::Vector3 factor); /** Sets the angular factor (0 disables rotation on an axis entirely) \param factor The factor in the form of a vector */ void setAngularFactor(Ogre::Vector3 factor); /** Sets the object's collision group (determines which objects will collide with it) \param mask The collision group */ void setCollisionGroup(short group); /** Sets the object's collision mask (what collision groups it will collide with) \param mask The collision mask */ void setCollisionMask(short mask); /** Sets whether or not the body is kinematic \param kinematic whether or not the body is to be kinematic */ void setKinematic(bool kinematic); /** Internal update function \param frame Is it a new simulation frame \param interpolation The current interpolation factor \param gravity The current simulation gravity */ void update(bool frame,float interpolation,Ogre::Vector3 gravity); /** Sets the user pointer, which can be retrieved with getUserData() \param data some data in the form of a void pointer */ void setUserData(void* data); /** Gets the user pointer \returns void pointer to user data */ void* getUserData(); /** Returns whether or not the object will be deleted next frame */ bool readyForDelete(); /** Internal function for killing a physics object @remarks This actually just tells the manager to delete it at the next available frame, rather than immediately deleting it. */ void _kill(); protected: // A pointer to the dynamics world this object belongs to btDynamicsWorld* mDynamicsWorld; // The Bullet Object (may be a rigid body or a plain collision object) btCollisionObject* mActor; // Whether this actor is a rigid body or a plain collision object bool mRigidBody; // The last recorded interpolation factor float mInterpolation; // Position data (1 prior frame is cached for interpolation purposes) Ogre::Vector3 mPos[2]; // Orientation data (1 prior frame is cached for interpolation purposes) Ogre::Quaternion mOrient[2]; // Whether or not this object is ready to be deleted by the PhysicsManager bool mReadyForDelete; // The last frames gravity (to avoid redundant setting of the object's gravity value) Ogre::Vector3 gravLast; }; #endif
[ [ [ 1, 141 ] ] ]
10fc8c8f461b8f4959fd2eb1b63234c798c45153
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/type_traits/is_base_and_derived.hpp
098df8d66aa5cdd45b01aaceaec0ce0eca0db7f0
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
7,423
hpp
// (C) Copyright Rani Sharoni 2003. // Use, modification and distribution are subject to 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). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_IS_BASE_AND_DERIVED_HPP_INCLUDED #define BOOST_TT_IS_BASE_AND_DERIVED_HPP_INCLUDED #include <boost/type_traits/is_class.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/type_traits/detail/ice_and.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/config.hpp> // should be the last #include #include <boost/type_traits/detail/bool_trait_def.hpp> namespace boost { namespace detail { #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581)) \ && !BOOST_WORKAROUND(__SUNPRO_CC , <= 0x540) \ && !BOOST_WORKAROUND(__EDG_VERSION__, <= 243) \ && !BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840)) // The EDG version number is a lower estimate. // It is not currently known which EDG version // exactly fixes the problem. /************************************************************************* This version detects ambiguous base classes and private base classes correctly, and was devised by Rani Sharoni. Explanation by Terje Slettebo and Rani Sharoni. Let's take the multiple base class below as an example, and the following will also show why there's not a problem with private or ambiguous base class: struct B {}; struct B1 : B {}; struct B2 : B {}; struct D : private B1, private B2 {}; is_base_and_derived<B, D>::value; First, some terminology: SC - Standard conversion UDC - User-defined conversion A user-defined conversion sequence consists of an SC, followed by an UDC, followed by another SC. Either SC may be the identity conversion. When passing the default-constructed Host object to the overloaded check_sig() functions (initialization 8.5/14/4/3), we have several viable implicit conversion sequences: For "static no_type check_sig(B const volatile *, int)" we have the conversion sequences: C -> C const (SC - Qualification Adjustment) -> B const volatile* (UDC) C -> D const volatile* (UDC) -> B1 const volatile* / B2 const volatile* -> B const volatile* (SC - Conversion) For "static yes_type check_sig(D const volatile *, T)" we have the conversion sequence: C -> D const volatile* (UDC) According to 13.3.3.1/4, in context of user-defined conversion only the standard conversion sequence is considered when selecting the best viable function, so it only considers up to the user-defined conversion. For the first function this means choosing between C -> C const and C -> C, and it chooses the latter, because it's a proper subset (13.3.3.2/3/2) of the former. Therefore, we have: C -> D const volatile* (UDC) -> B1 const volatile* / B2 const volatile* -> B const volatile* (SC - Conversion) C -> D const volatile* (UDC) Here, the principle of the "shortest subsequence" applies again, and it chooses C -> D const volatile*. This shows that it doesn't even need to consider the multiple paths to B, or accessibility, as that possibility is eliminated before it could possibly cause ambiguity or access violation. If D is not derived from B, it has to choose between C -> C const -> B const volatile* for the first function, and C -> D const volatile* for the second function, which are just as good (both requires a UDC, 13.3.3.2), had it not been for the fact that "static no_type check_sig(B const volatile *, int)" is not templated, which makes C -> C const -> B const volatile* the best choice (13.3.3/1/4), resulting in "no". Also, if Host::operator B const volatile* hadn't been const, the two conversion sequences for "static no_type check_sig(B const volatile *, int)", in the case where D is derived from B, would have been ambiguous. See also http://groups.google.com/groups?selm=df893da6.0301280859.522081f7%40posting. google.com and links therein. *************************************************************************/ template <typename B, typename D> struct bd_helper { // // This VC7.1 specific workaround stops the compiler from generating // an internal compiler error when compiling with /vmg (thanks to // Aleksey Gurtovoy for figuring out the workaround). // #if !BOOST_WORKAROUND(BOOST_MSVC, == 1310) template <typename T> static type_traits::yes_type check_sig(D const volatile *, T); static type_traits::no_type check_sig(B const volatile *, int); #else static type_traits::yes_type check_sig(D const volatile *, long); static type_traits::no_type check_sig(B const volatile * const&, int); #endif }; template<typename B, typename D> struct is_base_and_derived_impl2 { struct Host { #if !BOOST_WORKAROUND(BOOST_MSVC, == 1310) operator B const volatile *() const; #else operator B const volatile * const&() const; #endif operator D const volatile *(); }; BOOST_STATIC_CONSTANT(bool, value = sizeof(bd_helper<B,D>::check_sig(Host(), 0)) == sizeof(type_traits::yes_type)); }; #else // // broken version: // template<typename B, typename D> struct is_base_and_derived_impl2 { BOOST_STATIC_CONSTANT(bool, value = (::boost::is_convertible<D*,B*>::value)); }; #define BOOST_BROKEN_IS_BASE_AND_DERIVED #endif template <typename B, typename D> struct is_base_and_derived_impl3 { BOOST_STATIC_CONSTANT(bool, value = false); }; template <bool ic1, bool ic2, bool iss> struct is_base_and_derived_select { template <class T, class U> struct rebind { typedef is_base_and_derived_impl3<T,U> type; }; }; template <> struct is_base_and_derived_select<true,true,false> { template <class T, class U> struct rebind { typedef is_base_and_derived_impl2<T,U> type; }; }; template <typename B, typename D> struct is_base_and_derived_impl { typedef typename remove_cv<B>::type ncvB; typedef typename remove_cv<D>::type ncvD; typedef is_base_and_derived_select< ::boost::is_class<B>::value, ::boost::is_class<D>::value, ::boost::is_same<B,D>::value> selector; typedef typename selector::template rebind<ncvB,ncvD> binder; typedef typename binder::type bound_type; BOOST_STATIC_CONSTANT(bool, value = bound_type::value); }; } // namespace detail BOOST_TT_AUX_BOOL_TRAIT_DEF2( is_base_and_derived , Base , Derived , (::boost::detail::is_base_and_derived_impl<Base,Derived>::value) ) #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_and_derived,Base&,Derived,false) BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_and_derived,Base,Derived&,false) BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(typename Base,typename Derived,is_base_and_derived,Base&,Derived&,false) #endif } // namespace boost #include <boost/type_traits/detail/bool_trait_undef.hpp> #endif // BOOST_TT_IS_BASE_AND_DERIVED_HPP_INCLUDED
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 223 ] ] ]
566f6207068c9bac7fa189a0b7e6df2e73504723
54849ce1b4b2b4a2de284fc8b2a95443859b2c3e
/iquery/iquery/iquery_wrap.cc
64e7bd632b57857de187e4c297d24a0734c8efcc
[]
no_license
noobdoesre/py-com-tools
5b36f657a3ffaa78fcacd7c90bb0f5fa09b0b733
1be51abf116fba808d10d20ede4f89c80e809844
refs/heads/master
2020-12-24T15:41:36.072582
2011-08-28T00:57:40
2011-08-28T00:57:40
42,154,149
1
2
null
null
null
null
UTF-8
C++
false
false
129,648
cc
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_DIRECTOR_NO_VTABLE #ifdef __cplusplus /* SwigValueWrapper is described in swig.swg */ template<typename T> class SwigValueWrapper { struct SwigMovePointer { T *ptr; SwigMovePointer(T *p) : ptr(p) { } ~SwigMovePointer() { delete ptr; } SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } } pointer; SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); SwigValueWrapper(const SwigValueWrapper<T>& rhs); public: SwigValueWrapper() : pointer(0) { } SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } operator T&() const { return *pointer.ptr; } T *operator&() { return pointer.ptr; } }; template <typename T> T SwigValueInit() { return T(); } #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Python.h has to appear first */ #include <Python.h> /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return an integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Compatibility macros for Python 3 */ #if PY_VERSION_HEX >= 0x03000000 #define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) #define PyInt_Check(x) PyLong_Check(x) #define PyInt_AsLong(x) PyLong_AsLong(x) #define PyInt_FromLong(x) PyLong_FromLong(x) #define PyString_Check(name) PyBytes_Check(name) #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) #define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define PyString_AS_STRING(x) PyUnicode_AS_STRING(x) #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) #endif #ifndef Py_TYPE # define Py_TYPE(op) ((op)->ob_type) #endif /* SWIG APIs for compatibility of both Python 2 & 3 */ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_FromFormat PyUnicode_FromFormat #else # define SWIG_Python_str_FromFormat PyString_FromFormat #endif /* Warning: This function will allocate a new string in Python 3, * so please call SWIG_Python_str_DelForPy3(x) to free the space. */ SWIGINTERN char* SWIG_Python_str_AsChar(PyObject *str) { #if PY_VERSION_HEX >= 0x03000000 char *cstr; char *newstr; Py_ssize_t len; str = PyUnicode_AsUTF8String(str); PyBytes_AsStringAndSize(str, &cstr, &len); newstr = (char *) malloc(len+1); memcpy(newstr, cstr, len+1); Py_XDECREF(str); return newstr; #else return PyString_AsString(str); #endif } #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) #else # define SWIG_Python_str_DelForPy3(x) #endif SWIGINTERN PyObject* SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromString(c); #else return PyString_FromString(c); #endif } /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN typedef inquiry lenfunc; typedef intargfunc ssizeargfunc; typedef intintargfunc ssizessizeargfunc; typedef intobjargproc ssizeobjargproc; typedef intintobjargproc ssizessizeobjargproc; typedef getreadbufferproc readbufferproc; typedef getwritebufferproc writebufferproc; typedef getsegcountproc segcountproc; typedef getcharbufferproc charbufferproc; static long PyNumber_AsSsize_t (PyObject *x, void *SWIGUNUSEDPARM(exc)) { long result = 0; PyObject *i = PyNumber_Int(x); if (i) { result = PyInt_AsLong(i); Py_DECREF(i); } return result; } #endif #if PY_VERSION_HEX < 0x02040000 #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit((op), arg); \ if (vret) \ return vret; \ } \ } while (0) #endif #if PY_VERSION_HEX < 0x02030000 typedef struct { PyTypeObject type; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; PyBufferProcs as_buffer; PyObject *name, *slots; } PyHeapTypeObject; #endif #if PY_VERSION_HEX < 0x02030000 typedef destructor freefunc; #endif #if ((PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 6) || \ (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION > 0) || \ (PY_MAJOR_VERSION > 3)) # define SWIGPY_USE_CAPSULE # define SWIGPY_CAPSULE_NAME ((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION ".type_pointer_capsule" SWIG_TYPE_TABLE_NAME) #endif #if PY_VERSION_HEX < 0x03020000 #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; /* ----------------------------------------------------------------------------- * Wrapper of PyInstanceMethod_New() used in Python 3 * It is exported to the generated module, used for -fastproxy * ----------------------------------------------------------------------------- */ #if PY_VERSION_HEX >= 0x03000000 SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *func) { return PyInstanceMethod_New(func); } #else SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(func)) { return NULL; } #endif #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #ifdef SWIGPYTHON_BUILTIN #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(self, ptr, type, flags) #else #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #endif #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(NULL, ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, (char *) msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ #if defined(SWIGPYTHON_BUILTIN) SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { PyObject *s = PyString_InternFromString(key); PyList_Append(seq, s); Py_DECREF(s); } SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { PyDict_SetItemString(d, (char *)name, obj); Py_DECREF(obj); if (public_interface) SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { PyDict_SetItemString(d, (char *)name, obj); Py_DECREF(obj); } #endif /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { if (min <= 1 && max >= 1) { register int i; objs[0] = args; for (i = 1; i < max; ++i) { objs[i] = 0; } return 2; } PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { register Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { register int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #define SWIG_BUILTIN_TP_INIT (SWIG_POINTER_OWN << 2) #define SWIG_BUILTIN_INIT (SWIG_BUILTIN_TP_INIT | SWIG_POINTER_OWN) #ifdef __cplusplus extern "C" { #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* SwigPyClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; PyTypeObject *pytype; } SwigPyClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME SwigPyClientData * SwigPyClientData_New(PyObject* obj) { if (!obj) { return 0; } else { SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; data->pytype = 0; return data; } } SWIGRUNTIME void SwigPyClientData_Del(SwigPyClientData *data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== SwigPyObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; #ifdef SWIGPYTHON_BUILTIN PyObject *dict; #endif } SwigPyObject; SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * SwigPyObject_format(const char* fmt, SwigPyObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { PyObject *ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 res = PyUnicode_Format(ofmt,args); #else res = PyString_Format(ofmt,args); #endif Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * SwigPyObject_oct(SwigPyObject *v) { return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * SwigPyObject_hex(SwigPyObject *v) { return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS SwigPyObject_repr(SwigPyObject *v) #else SwigPyObject_repr(SwigPyObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *repr = SWIG_Python_str_FromFormat("<Swig Object of type '%s' at %p>", name, (void *)v); if (v->next) { # ifdef METH_NOARGS PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); # else PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); # endif # if PY_VERSION_HEX >= 0x03000000 PyObject *joined = PyUnicode_Concat(repr, nrep); Py_DecRef(repr); Py_DecRef(nrep); repr = joined; # else PyString_ConcatAndDel(&repr,nrep); # endif } return repr; } SWIGRUNTIME int SwigPyObject_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *str; #ifdef METH_NOARGS PyObject *repr = SwigPyObject_repr(v); #else PyObject *repr = SwigPyObject_repr(v, NULL); #endif if (repr) { str = SWIG_Python_str_AsChar(repr); fputs(str, fp); SWIG_Python_str_DelForPy3(str); Py_DECREF(repr); return 0; } else { return 1; } } SWIGRUNTIME PyObject * SwigPyObject_str(SwigPyObject *v) { char result[SWIG_BUFFER_SIZE]; return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? SWIG_Python_str_FromChar(result) : 0; } SWIGRUNTIME int SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ SWIGRUNTIME PyObject* SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { PyObject* res; if( op != Py_EQ && op != Py_NE ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); return res; } SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { #ifdef SWIGPYTHON_BUILTIN PyTypeObject *target_tp = SwigPyObject_type(); if (PyType_IsSubtype(op->ob_type, target_tp)) return 1; return (strcmp(op->ob_type->tp_name, "SwigPyObject") == 0); #else return (Py_TYPE(op) == SwigPyObject_type()) || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); #endif } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void SwigPyObject_dealloc(PyObject *v) { SwigPyObject *sobj = (SwigPyObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporary object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* SwigPyObject_append(PyObject* v, PyObject* next) { SwigPyObject *sobj = (SwigPyObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!SwigPyObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS SwigPyObject_next(PyObject* v) #else SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_disown(PyObject *v) #else SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_acquire(PyObject *v) #else SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* SwigPyObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #else if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #endif { return NULL; } else { SwigPyObject *sobj = (SwigPyObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v); } else { SwigPyObject_disown(v); } #else if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v,args); } else { SwigPyObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * SwigPyObject_getattr(SwigPyObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods SwigPyObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 (binaryfunc)0, /*nb_divide*/ #endif (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 0, /*nb_coerce*/ #endif (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_long, /*nb_long*/ #else 0, /*nb_reserved*/ #endif (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject swigpyobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyObject", /* tp_name */ sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ (printfunc)SwigPyObject_print, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif (reprfunc)SwigPyObject_repr, /* tp_repr */ &SwigPyObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyObject_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpyobject_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpyobject_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpyobject_type) < 0) return NULL; #endif } return &swigpyobject_type; } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } SwigPyPacked; SWIGRUNTIME int SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("<Swig Packed ", fp); if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * SwigPyPacked_repr(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return SWIG_Python_str_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); } else { return SWIG_Python_str_FromFormat("<Swig Packed %s>", v->ty->name); } } SWIGRUNTIME PyObject * SwigPyPacked_str(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); } else { return SWIG_Python_str_FromChar(v->ty->name); } } SWIGRUNTIME int SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { return ((op)->ob_type == SwigPyPacked_TypeOnce()) || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); } SWIGRUNTIME void SwigPyPacked_dealloc(PyObject *v) { if (SwigPyPacked_Check(v)) { SwigPyPacked *sobj = (SwigPyPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject swigpypacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyPacked", /* tp_name */ sizeof(SwigPyPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ (printfunc)SwigPyPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 0, /* tp_reserved in 3.0.1 */ #else (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif (reprfunc)SwigPyPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpypacked_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 swigpypacked_type.ob_type = &PyType_Type; #else if (PyType_Ready(&swigpypacked_type) < 0) return NULL; #endif } return &swigpypacked_type; } SWIGRUNTIME PyObject * SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (SwigPyPacked_Check(obj)) { SwigPyPacked *sobj = (SwigPyPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return SWIG_Python_str_FromChar("this"); } static PyObject *swig_this = NULL; SWIGRUNTIME PyObject * SWIG_This(void) { if (swig_this == NULL) swig_this = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 #define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { PyObject *obj; if (SwigPyObject_Check(pyobj)) return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN (void)obj; # ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { pyobj = PyWeakref_GET_OBJECT(pyobj); if (pyobj && SwigPyObject_Check(pyobj)) return (SwigPyObject*) pyobj; } # endif return NULL; #else obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !SwigPyObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' SwigPyObject from it */ return SWIG_Python_GetSwigThis(obj); } return (SwigPyObject *)obj; #endif } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { int res; SwigPyObject *sobj; if (!obj) return SWIG_ERROR; if (obj == Py_None) { if (ptr) *ptr = 0; return SWIG_OK; } res = SWIG_ERROR; sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (SwigPyObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } res = SWIG_OK; } else { if (flags & SWIG_POINTER_IMPLICIT_CONV) { SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } } return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, without calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { #if PY_VERSION_HEX >= 0x03000000 inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; #else PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); #endif } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst; PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { return NULL; } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { SwigPyObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { SwigPyClientData *clientdata; PyObject * robj; int own; if (!ptr) return SWIG_Py_Void(); clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; if (clientdata && clientdata->pytype) { SwigPyObject *newobj; if (flags & SWIG_BUILTIN_TP_INIT) { newobj = (SwigPyObject*) self; if (newobj->ptr) { PyObject *next_self = clientdata->pytype->tp_alloc(clientdata->pytype, 0); while (newobj->next) newobj = (SwigPyObject *) newobj->next; newobj->next = next_self; newobj = (SwigPyObject *)next_self; } } else { newobj = PyObject_New(SwigPyObject, clientdata->pytype); } if (newobj) { newobj->ptr = ptr; newobj->ty = type; newobj->own = own; newobj->next = 0; #ifdef SWIGPYTHON_BUILTIN newobj->dict = 0; #endif return (PyObject*) newobj; } return SWIG_Py_Void(); } assert(!(flags & SWIG_BUILTIN_TP_INIT)); robj = SwigPyObject_New(ptr, type, own); if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); if (inst) { Py_DECREF(robj); robj = inst; } } return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else # ifdef SWIGPY_USE_CAPSULE type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); # else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); # endif if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void #ifdef SWIGPY_USE_CAPSULE SWIG_Python_DestroyModule(PyObject *obj) #else SWIG_Python_DestroyModule(void *vptr) #endif { #ifdef SWIGPY_USE_CAPSULE swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); #else swig_module_info *swig_module = (swig_module_info *) vptr; #endif swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); swig_this = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 /* Add a dummy module object into sys.modules */ PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); #else static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif #ifdef SWIGPY_USE_CAPSULE PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer_capsule" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #else PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } #endif } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = SWIG_Python_str_FromChar(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { #ifdef SWIGPY_USE_CAPSULE descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); #else descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); #endif } else { swig_module_info *swig_module = SWIG_Python_GetModule(); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { #ifdef SWIGPY_USE_CAPSULE obj = PyCapsule_New((void*) descriptor, NULL, NULL); #else obj = PyCObject_FromVoidPtr(descriptor, NULL); #endif PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { char *tmp; PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); } else { PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); } SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * SwigPyObject_GetDesc(PyObject *self) { SwigPyObject *v = (SwigPyObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : (char*)""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && SwigPyObject_Check(obj)) { const char *otype = (const char *) SwigPyObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); SWIG_Python_str_DelForPy3(cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); #if SWIG_POINTER_EXCEPTION if (flags) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } #endif } return result; } SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { PyTypeObject *tp = obj->ob_type; PyObject *descr; PyObject *encoded_name; descrsetfunc f; int res; #ifdef Py_USING_UNICODE if (PyString_Check(name)) { name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); if (!name) return -1; } else if (!PyUnicode_Check(name)) #else if (!PyString_Check(name)) #endif { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } else { Py_INCREF(name); } if (!tp->tp_dict) { if (PyType_Ready(tp) < 0) goto done; } res = -1; descr = _PyType_Lookup(tp, name); f = NULL; if (descr != NULL) f = descr->ob_type->tp_descr_set; if (!f) { if (PyString_Check(name)) { encoded_name = name; Py_INCREF(name); } else { encoded_name = PyUnicode_AsUTF8String(name); } PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); Py_DECREF(encoded_name); } else { res = f(descr, obj, value); } done: Py_DECREF(name); return res; } #ifdef __cplusplus } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_char swig_types[0] #define SWIGTYPE_p_iQuery swig_types[1] #define SWIGTYPE_p_long swig_types[2] static swig_type_info *swig_types[4]; static swig_module_info swig_module = {swig_types, 3, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif /*----------------------------------------------- @(target):= _iquery.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__iquery #else # define SWIG_init init_iquery #endif #define SWIG_name "_iquery" #define SWIGVERSION 0x020004 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include <stdexcept> namespace swig { class SwigPtr_PyObject { protected: PyObject *_obj; public: SwigPtr_PyObject() :_obj(0) { } SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) { Py_XINCREF(_obj); } SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) { if (initial_ref) { Py_XINCREF(_obj); } } SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) { Py_XINCREF(item._obj); Py_XDECREF(_obj); _obj = item._obj; return *this; } ~SwigPtr_PyObject() { Py_XDECREF(_obj); } operator PyObject *() const { return _obj; } PyObject *operator->() const { return _obj; } }; } namespace swig { struct SwigVar_PyObject : SwigPtr_PyObject { SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } SwigVar_PyObject & operator = (PyObject* obj) { Py_XDECREF(_obj); _obj = obj; return *this; } }; } #include <Windows.h> #include <Objsafe.h> #include <WinDef.h> typedef long PTR; class iQuery{ private: IUnknown *iuk; IUnknown * queryInterfaceWorker(const char *iface); bool safeWorker(const char *iid, DWORD flags); public: iQuery(const char *clsid = NULL) throw(const char *); ~iQuery(); bool isInterfaceSupported(const char *iface) throw(const char *); PTR getIFaceVTOffset(const char *iface) throw(const char *); bool isSafeScript(const char *iid); bool isSafeInit(const char *iid); bool coCreateUnknown(char *file, char *rclsid) throw(const char *); }; SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 if (PyUnicode_Check(obj)) #else if (PyString_Check(obj)) #endif { char *cstr; Py_ssize_t len; #if PY_VERSION_HEX>=0x03000000 if (!alloc && cptr) { /* We can't allow converting without allocation, since the internal representation of string in Python 3 is UCS-2/UCS-4 but we require a UTF-8 representation. TODO(bhy) More detailed explanation */ return SWIG_RuntimeError; } obj = PyUnicode_AsUTF8String(obj); PyBytes_AsStringAndSize(obj, &cstr, &len); if(alloc) *alloc = SWIG_NEWOBJ; #else PyString_AsStringAndSize(obj, &cstr, &len); #endif if (cptr) { if (alloc) { /* In python the user should not be able to modify the inner string representation. To warranty that, if you define SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string buffer is always returned. The default behavior is just to return the pointer value, so, be careful. */ #if defined(SWIG_PYTHON_SAFE_CSTRINGS) if (*alloc != SWIG_OLDOBJ) #else if (*alloc == SWIG_NEWOBJ) #endif { *cptr = reinterpret_cast< char* >(memcpy((new char[len + 1]), cstr, sizeof(char)*(len + 1))); *alloc = SWIG_NEWOBJ; } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { #if PY_VERSION_HEX>=0x03000000 assert(0); /* Should never reach here in Python 3 */ #endif *cptr = SWIG_Python_str_AsChar(obj); } } if (psize) *psize = len + 1; #if PY_VERSION_HEX>=0x03000000 Py_XDECREF(obj); #endif return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } SWIGINTERNINLINE PyObject * SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { if (size > INT_MAX) { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); return pchar_descriptor ? SWIG_InternalNewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); } else { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); #else return PyString_FromStringAndSize(carray, static_cast< int >(size)); #endif } } else { return SWIG_Py_Void(); } } SWIGINTERNINLINE PyObject * SWIG_FromCharPtr(const char *cptr) { return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } SWIGINTERNINLINE PyObject* SWIG_From_bool (bool value) { return PyBool_FromLong(value ? 1 : 0); } #define SWIG_From_long PyInt_FromLong #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_new_iQuery__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; PyObject * obj0 = 0 ; iQuery *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:new_iQuery",&obj0)) SWIG_fail; res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_iQuery" "', argument " "1"" of type '" "char const *""'"); } arg1 = reinterpret_cast< char * >(buf1); try { result = (iQuery *)new iQuery((char const *)arg1); } catch(char const *_e) { SWIG_Python_Raise(SWIG_FromCharPtr(_e), "char const *", 0); SWIG_fail; } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_iQuery, SWIG_POINTER_NEW | 0 ); if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return resultobj; fail: if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return NULL; } SWIGINTERN PyObject *_wrap_new_iQuery__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *result = 0 ; if (!PyArg_ParseTuple(args,(char *)":new_iQuery")) SWIG_fail; try { result = (iQuery *)new iQuery(); } catch(char const *_e) { SWIG_Python_Raise(SWIG_FromCharPtr(_e), "char const *", 0); SWIG_fail; } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_iQuery, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_new_iQuery(PyObject *self, PyObject *args) { int argc; PyObject *argv[2]; int ii; if (!PyTuple_Check(args)) SWIG_fail; argc = args ? (int)PyObject_Length(args) : 0; for (ii = 0; (ii < 1) && (ii < argc); ii++) { argv[ii] = PyTuple_GET_ITEM(args,ii); } if (argc == 0) { return _wrap_new_iQuery__SWIG_1(self, args); } if (argc == 1) { int _v; int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_new_iQuery__SWIG_0(self, args); } } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number or type of arguments for overloaded function 'new_iQuery'.\n" " Possible C/C++ prototypes are:\n" " iQuery::iQuery(char const *)\n" " iQuery::iQuery()\n"); return 0; } SWIGINTERN PyObject *_wrap_delete_iQuery(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_iQuery",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_iQuery" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); delete arg1; resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_iQuery_isInterfaceSupported(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; bool result; if (!PyArg_ParseTuple(args,(char *)"OO:iQuery_isInterfaceSupported",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iQuery_isInterfaceSupported" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "iQuery_isInterfaceSupported" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); try { result = (bool)(arg1)->isInterfaceSupported((char const *)arg2); } catch(char const *_e) { SWIG_Python_Raise(SWIG_FromCharPtr(_e), "char const *", 0); SWIG_fail; } resultobj = SWIG_From_bool(static_cast< bool >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return NULL; } SWIGINTERN PyObject *_wrap_iQuery_getIFaceVTOffset(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PTR result; if (!PyArg_ParseTuple(args,(char *)"OO:iQuery_getIFaceVTOffset",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iQuery_getIFaceVTOffset" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "iQuery_getIFaceVTOffset" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); try { result = (PTR)(arg1)->getIFaceVTOffset((char const *)arg2); } catch(char const *_e) { SWIG_Python_Raise(SWIG_FromCharPtr(_e), "char const *", 0); SWIG_fail; } resultobj = SWIG_From_long(static_cast< long >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return NULL; } SWIGINTERN PyObject *_wrap_iQuery_isSafeScript(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; bool result; if (!PyArg_ParseTuple(args,(char *)"OO:iQuery_isSafeScript",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iQuery_isSafeScript" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "iQuery_isSafeScript" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); result = (bool)(arg1)->isSafeScript((char const *)arg2); resultobj = SWIG_From_bool(static_cast< bool >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return NULL; } SWIGINTERN PyObject *_wrap_iQuery_isSafeInit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; char *arg2 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; bool result; if (!PyArg_ParseTuple(args,(char *)"OO:iQuery_isSafeInit",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iQuery_isSafeInit" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "iQuery_isSafeInit" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); result = (bool)(arg1)->isSafeInit((char const *)arg2); resultobj = SWIG_From_bool(static_cast< bool >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return NULL; } SWIGINTERN PyObject *_wrap_iQuery_coCreateUnknown(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; iQuery *arg1 = (iQuery *) 0 ; char *arg2 = (char *) 0 ; char *arg3 = (char *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; int res3 ; char *buf3 = 0 ; int alloc3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; bool result; if (!PyArg_ParseTuple(args,(char *)"OOO:iQuery_coCreateUnknown",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_iQuery, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iQuery_coCreateUnknown" "', argument " "1"" of type '" "iQuery *""'"); } arg1 = reinterpret_cast< iQuery * >(argp1); res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "iQuery_coCreateUnknown" "', argument " "2"" of type '" "char *""'"); } arg2 = reinterpret_cast< char * >(buf2); res3 = SWIG_AsCharPtrAndSize(obj2, &buf3, NULL, &alloc3); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "iQuery_coCreateUnknown" "', argument " "3"" of type '" "char *""'"); } arg3 = reinterpret_cast< char * >(buf3); try { result = (bool)(arg1)->coCreateUnknown(arg2,arg3); } catch(char const *_e) { SWIG_Python_Raise(SWIG_FromCharPtr(_e), "char const *", 0); SWIG_fail; } resultobj = SWIG_From_bool(static_cast< bool >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; if (alloc3 == SWIG_NEWOBJ) delete[] buf3; return resultobj; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; if (alloc3 == SWIG_NEWOBJ) delete[] buf3; return NULL; } SWIGINTERN PyObject *iQuery_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_iQuery, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"new_iQuery", _wrap_new_iQuery, METH_VARARGS, NULL}, { (char *)"delete_iQuery", _wrap_delete_iQuery, METH_VARARGS, NULL}, { (char *)"iQuery_isInterfaceSupported", _wrap_iQuery_isInterfaceSupported, METH_VARARGS, NULL}, { (char *)"iQuery_getIFaceVTOffset", _wrap_iQuery_getIFaceVTOffset, METH_VARARGS, NULL}, { (char *)"iQuery_isSafeScript", _wrap_iQuery_isSafeScript, METH_VARARGS, NULL}, { (char *)"iQuery_isSafeInit", _wrap_iQuery_isSafeInit, METH_VARARGS, NULL}, { (char *)"iQuery_coCreateUnknown", _wrap_iQuery_coCreateUnknown, METH_VARARGS, NULL}, { (char *)"iQuery_swigregister", iQuery_swigregister, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_iQuery = {"_p_iQuery", "iQuery *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_long = {"_p_long", "long *|PTR *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_char, &_swigt__p_iQuery, &_swigt__p_long, }; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_iQuery[] = { {&_swigt__p_iQuery, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_long[] = { {&_swigt__p_long, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_char, _swigc__p_iQuery, _swigc__p_long, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString("<Swig global variables>"); #else return PyString_FromString("<Swig global variables>"); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"swigvarlink", /* tp_name */ sizeof(swig_varlinkobject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) swig_varlink_dealloc, /* tp_dealloc */ (printfunc) swig_varlink_print, /* tp_print */ (getattrfunc) swig_varlink_getattr, /* tp_getattr */ (setattrfunc) swig_varlink_setattr, /* tp_setattr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc) swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #if PY_VERSION_HEX >= 0x02060000 0, /* tp_version */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; type_init = 1; #if PY_VERSION_HEX < 0x02020000 varlink_type.ob_type = &PyType_Type; #else if (PyType_Ready(&varlink_type) < 0) return NULL; #endif } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 PyObject* #else void #endif SWIG_init(void) { PyObject *m, *d, *md; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef SWIG_module = { # if PY_VERSION_HEX >= 0x03020000 PyModuleDef_HEAD_INIT, # else { PyObject_HEAD_INIT(NULL) NULL, /* m_init */ 0, /* m_index */ NULL, /* m_copy */ }, # endif (char *) SWIG_name, NULL, -1, SwigMethods, NULL, NULL, NULL, NULL }; #endif #if defined(SWIGPYTHON_BUILTIN) static SwigPyClientData SwigPyObject_clientdata = { 0, 0, 0, 0, 0, 0, 0 }; static PyGetSetDef this_getset_def = { (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL }; static SwigPyGetSet thisown_getset_closure = { (PyCFunction) SwigPyObject_own, (PyCFunction) SwigPyObject_own }; static PyGetSetDef thisown_getset_def = { (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure }; PyObject *metatype_args; PyTypeObject *builtin_pytype; int builtin_base_count; swig_type_info *builtin_basetype; PyObject *tuple; PyGetSetDescrObject *static_getset; PyTypeObject *metatype; SwigPyClientData *cd; PyObject *public_interface, *public_symbol; PyObject *this_descr; PyObject *thisown_descr; int i; (void)builtin_pytype; (void)builtin_base_count; (void)builtin_basetype; (void)tuple; (void)static_getset; /* metatype is used to implement static member variables. */ metatype_args = Py_BuildValue("(s(O){})", "SwigPyObjectType", &PyType_Type); assert(metatype_args); metatype = (PyTypeObject *) PyType_Type.tp_call((PyObject *) &PyType_Type, metatype_args, NULL); assert(metatype); Py_DECREF(metatype_args); metatype->tp_setattro = (setattrofunc) &SwigPyObjectType_setattro; assert(PyType_Ready(metatype) >= 0); #endif /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); #if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&SWIG_module); #else m = Py_InitModule((char *) SWIG_name, SwigMethods); #endif md = d = PyModule_GetDict(m); SWIG_InitializeModule(0); #ifdef SWIGPYTHON_BUILTIN SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); assert(SwigPyObject_stype); cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; if (!cd) { SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; SwigPyObject_clientdata.pytype = SwigPyObject_TypeOnce(); } else if (SwigPyObject_TypeOnce()->tp_basicsize != cd->pytype->tp_basicsize) { PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 return NULL; # else return; # endif } /* All objects have a 'this' attribute */ this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); (void)this_descr; /* All objects have a 'thisown' attribute */ thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); (void)thisown_descr; public_interface = PyList_New(0); public_symbol = 0; (void)public_symbol; PyDict_SetItemString(md, "__all__", public_interface); Py_DECREF(public_interface); for (i = 0; SwigMethods[i].ml_name != NULL; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); for (i = 0; swig_const_table[i].name != 0; ++i) SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif SWIG_InstallConstants(d,swig_const_table); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif }
[ [ [ 1, 4232 ] ] ]
b698569ee740a86af41566e943d0c3dbba17ee73
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/PosnEquip/PosnEquip/Octagon.cpp
bfbc97e036c45e232dc0149046e50a883ae73884
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,677
cpp
#include "stdafx.h" #include "Octagon.h" #include <math.h> const double PI = 3.14159; COctagon::COctagon(void) { m_nVerticies = 16; RawVerticies.Init(3,m_nVerticies); Verticies.Init(3,m_nVerticies); m_pOrigin[0] = 0.0; m_pOrigin[1] = 0.0; m_pOrigin[2] = 0.0; m_nEdges = 24; m_nDrawPackets = 1; m_dWidth = 0.0; m_dRadius = 0.0; } COctagon::~COctagon(void) { } void COctagon::SetVerticies(void) { double dl = m_dRadius/cos(PI/8.0); RawVerticies(1,1) = m_dRadius + m_pOrigin[0]; RawVerticies(2,1) = dl*sin(PI/8.0) + m_pOrigin[1]; RawVerticies(3,1) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,2) = dl*cos(3*PI/8.0) + m_pOrigin[0]; RawVerticies(2,2) = dl*sin(3*PI/8.0) + m_pOrigin[1]; RawVerticies(3,2) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,3) = dl*cos(5*PI/8.0) + m_pOrigin[0]; RawVerticies(2,3) = dl*sin(5*PI/8.0) + m_pOrigin[1]; RawVerticies(3,3) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,4) = dl*cos(7*PI/8.0) + m_pOrigin[0]; RawVerticies(2,4) = dl*sin(7*PI/8.0) + m_pOrigin[1]; RawVerticies(3,4) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,5) = dl*cos(9*PI/8.0) + m_pOrigin[0]; RawVerticies(2,5) = dl*sin(9*PI/8.0) + m_pOrigin[1]; RawVerticies(3,5) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,6) = dl*cos(11*PI/8.0) + m_pOrigin[0]; RawVerticies(2,6) = dl*sin(11*PI/8.0) + m_pOrigin[1]; RawVerticies(3,6) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,7) = dl*cos(13*PI/8.0) + m_pOrigin[0]; RawVerticies(2,7) = dl*sin(13*PI/8.0) + m_pOrigin[1]; RawVerticies(3,7) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,8) = dl*cos(15*PI/8.0) + m_pOrigin[0]; RawVerticies(2,8) = dl*sin(15*PI/8.0) + m_pOrigin[1]; RawVerticies(3,8) = m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,9) = m_dRadius + m_pOrigin[0]; RawVerticies(2,9) = dl*sin(PI/8.0) + m_pOrigin[1]; RawVerticies(3,9) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,10) = dl*cos(3*PI/8.0) + m_pOrigin[0]; RawVerticies(2,10) = dl*sin(3*PI/8.0) + m_pOrigin[1]; RawVerticies(3,10) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,11) = dl*cos(5*PI/8.0) + m_pOrigin[0]; RawVerticies(2,11) = dl*sin(5*PI/8.0) + m_pOrigin[1]; RawVerticies(3,11) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,12) = dl*cos(7*PI/8.0) + m_pOrigin[0]; RawVerticies(2,12) = dl*sin(7*PI/8.0) + m_pOrigin[1]; RawVerticies(3,12) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,13) = dl*cos(9*PI/8.0) + m_pOrigin[0]; RawVerticies(2,13) = dl*sin(9*PI/8.0) + m_pOrigin[1]; RawVerticies(3,13) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,14) = dl*cos(11*PI/8.0) + m_pOrigin[0]; RawVerticies(2,14) = dl*sin(11*PI/8.0) + m_pOrigin[1]; RawVerticies(3,14) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,15) = dl*cos(13*PI/8.0) + m_pOrigin[0]; RawVerticies(2,15) = dl*sin(13*PI/8.0) + m_pOrigin[1]; RawVerticies(3,15) = -m_dWidth/2.0 + m_pOrigin[2]; RawVerticies(1,16) = dl*cos(15*PI/8.0) + m_pOrigin[0]; RawVerticies(2,16) = dl*sin(15*PI/8.0) + m_pOrigin[1]; RawVerticies(3,16) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,1) = -dl + m_pOrigin[0]; //RawVerticies(2,1) = m_pOrigin[1]; //RawVerticies(3,1) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,2) = -dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,2) = dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,2) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,3) = m_pOrigin[0]; //RawVerticies(2,3) = dl + m_pOrigin[1]; //RawVerticies(3,3) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,4) = dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,4) = dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,4) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,5) = dl + m_pOrigin[0]; //RawVerticies(2,5) = m_pOrigin[1]; //RawVerticies(3,5) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,6) = dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,6) = -dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,6) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,7) = m_pOrigin[0]; //RawVerticies(2,7) = -dl + m_pOrigin[1]; //RawVerticies(3,7) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,8) = -dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,8) = -dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,8) = m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,9) = -dl + m_pOrigin[0]; //RawVerticies(2,9) = m_pOrigin[1]; //RawVerticies(3,9) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,10) = -dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,10) = dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,10) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,11) = m_pOrigin[0]; //RawVerticies(2,11) = dl + m_pOrigin[1]; //RawVerticies(3,11) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,12) = dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,12) = dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,12) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,13) = dl + m_pOrigin[0]; //RawVerticies(2,13) = m_pOrigin[1]; //RawVerticies(3,13) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,14) = dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,14) = -dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,14) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,15) = m_pOrigin[0]; //RawVerticies(2,15) = -dl + m_pOrigin[1]; //RawVerticies(3,15) = -m_dWidth/2.0 + m_pOrigin[2]; //RawVerticies(1,16) = -dl*cos(PI/4.0) + m_pOrigin[0]; //RawVerticies(2,16) = -dl*sin(PI/4.0) + m_pOrigin[1]; //RawVerticies(3,16) = -m_dWidth/2.0 + m_pOrigin[2]; } void COctagon::SetDims(double dRadius, double dWidth) { m_dWidth = dWidth; m_dRadius = dRadius; } void COctagon::GetEdge(int nEdge,CEdge & edge) { switch(nEdge) { case 1 : GetEdgeFromVerticies(1,2,edge); break; case 2 : GetEdgeFromVerticies(2,3,edge); break; case 3 : GetEdgeFromVerticies(3,4,edge); break; case 4 : GetEdgeFromVerticies(4,5,edge); break; case 5 : GetEdgeFromVerticies(5,6,edge); break; case 6 : GetEdgeFromVerticies(6,7,edge); break; case 7 : GetEdgeFromVerticies(7,8,edge); break; case 8 : GetEdgeFromVerticies(8,1,edge); break; case 9 : GetEdgeFromVerticies(9,10,edge); break; case 10 : GetEdgeFromVerticies(10,11,edge); break; case 11 : GetEdgeFromVerticies(11,12,edge); break; case 12 : GetEdgeFromVerticies(12,13,edge); break; case 13 : GetEdgeFromVerticies(13,14,edge); break; case 14 : GetEdgeFromVerticies(14,15,edge); break; case 15 : GetEdgeFromVerticies(15,16,edge); break; case 16 : GetEdgeFromVerticies(16,9,edge); break; case 17 : GetEdgeFromVerticies(1,9,edge); break; case 18 : GetEdgeFromVerticies(2,10,edge); break; case 19 : GetEdgeFromVerticies(3,11,edge); break; case 20 : GetEdgeFromVerticies(4,12,edge); break; case 21 : GetEdgeFromVerticies(5,13,edge); break; case 22 : GetEdgeFromVerticies(6,14,edge); break; case 23 : GetEdgeFromVerticies(7,15,edge); break; case 24 : GetEdgeFromVerticies(8,16,edge); break; default : ; } } void COctagon::GetDrawingPacket(int nPacket, DRAWING_MODE & nMode, CComSafeArray<double>& sa) { switch(nPacket) { case 1: nMode = COMBO_BLOCK;//POLY_COMBO_BLOCK; sa.Resize(51,1); SetSAColour(sa); SetSAVertex(sa,1,1); SetSAVertex(sa,2,2); SetSAVertex(sa,3,3); SetSAVertex(sa,4,4); SetSAVertex(sa,5,5); SetSAVertex(sa,6,6); SetSAVertex(sa,7,7); SetSAVertex(sa,8,8); SetSAVertex(sa,9,9); SetSAVertex(sa,10,10); SetSAVertex(sa,11,11); SetSAVertex(sa,12,12); SetSAVertex(sa,13,13); SetSAVertex(sa,14,14); SetSAVertex(sa,15,15); SetSAVertex(sa,16,16); default : ; } return; }
[ [ [ 1, 233 ] ] ]
3d1266016c2b24ddea4d1a197d3d10b3040d592b
027eda7f41dc38eddeed50713bc23328c5bab6b4
/PegGame2/PegGame1/BoardPtr.h
d39757c1ed4242c0d8db7abef6ac1b8aeecb8270
[]
no_license
iamjwc/CS438
6e9872c88f639316beff32cc60bd4d5edf9cd037
9ebceb46abe063c3cacff299e0750b608358b216
refs/heads/master
2021-01-04T14:21:34.738661
2011-10-21T23:07:03
2011-10-21T23:07:03
2,623,746
0
0
null
null
null
null
UTF-8
C++
false
false
693
h
#ifndef BOARD_PTR_H #define BOARD_PTR_H #include <iostream> using namespace std; #include "Board.h" struct BoardPtr { BoardPtr( Board* bptr = NULL ) : b(bptr) {} Board* b; Board* operator->() { return this->b; } }; bool operator<( const BoardPtr& lhs, const BoardPtr& rhs ) { return lhs.b->f < rhs.b->f; } bool operator>( const BoardPtr& lhs, const BoardPtr& rhs ) { return lhs.b->f > rhs.b->f; } bool operator==( const BoardPtr& lhs, void* rhs ) { return lhs.b == rhs; } bool operator!=( const BoardPtr& lhs, void* rhs ) { return lhs.b != rhs; } ostream& operator<<( ostream& o, const BoardPtr& b ) { o << *b.b; return o; } #endif
[ [ [ 1, 47 ] ] ]
5ac8528c2d0fdbfa7b55643bf238ee5eee000f1a
7e6c795d359cc4943a7ff311660d2fbacdfe6645
/src/AutoMasonQT3/bbb_BrickPattern.cpp
5dfdce1c3bb28195ba83b92fd25223fb6a65a1be
[]
no_license
keencode/AutomasonMP3
3dc1550a3f506d0d6743df64e337d013c81c8e80
9af3d7668fff252c2c3a6a0432cfaf71e75a326b
refs/heads/master
2020-05-19T13:32:12.522715
2011-09-21T00:13:21
2011-09-21T00:13:21
2,114,357
0
0
null
null
null
null
UTF-8
C++
false
false
132
cpp
#include "bbb_BrickPattern.h" bbb_BrickPattern::bbb_BrickPattern(void) { } bbb_BrickPattern::~bbb_BrickPattern(void) { }
[ [ [ 1, 9 ] ] ]
6142436f2b8a85cee3678c80729f7f2064ddc44b
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qaccessibleobject.h
139d5f4bbbb8508d68febfbb787a2bc6efb14d8f
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,413
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, 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.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QACCESSIBLEOBJECT_H #define QACCESSIBLEOBJECT_H #include <QtGui/qaccessible.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_ACCESSIBILITY class QAccessibleObjectPrivate; class QObject; class Q_GUI_EXPORT QAccessibleObject : public QAccessibleInterface { public: explicit QAccessibleObject(QObject *object); bool isValid() const; QObject *object() const; // properties QRect rect(int child) const; void setText(Text t, int child, const QString &text); // actions int userActionCount(int child) const; bool doAction(int action, int child, const QVariantList &params); QString actionText(int action, Text t, int child) const; protected: virtual ~QAccessibleObject(); private: friend class QAccessibleObjectEx; QAccessibleObjectPrivate *d; Q_DISABLE_COPY(QAccessibleObject) }; class Q_GUI_EXPORT QAccessibleObjectEx : public QAccessibleInterfaceEx { public: explicit QAccessibleObjectEx(QObject *object); bool isValid() const; QObject *object() const; // properties QRect rect(int child) const; void setText(Text t, int child, const QString &text); // actions int userActionCount(int child) const; bool doAction(int action, int child, const QVariantList &params); QString actionText(int action, Text t, int child) const; protected: virtual ~QAccessibleObjectEx(); private: QAccessibleObjectPrivate *d; Q_DISABLE_COPY(QAccessibleObjectEx) }; class Q_GUI_EXPORT QAccessibleApplication : public QAccessibleObject { public: QAccessibleApplication(); // relations int childCount() const; int indexOfChild(const QAccessibleInterface*) const; Relation relationTo(int, const QAccessibleInterface *, int) const; // navigation int childAt(int x, int y) const; int navigate(RelationFlag, int, QAccessibleInterface **) const; // properties and state QString text(Text t, int child) const; Role role(int child) const; State state(int child) const; // actions int userActionCount(int child) const; bool doAction(int action, int child, const QVariantList &params); QString actionText(int action, Text t, int child) const; }; #endif // QT_NO_ACCESSIBILITY QT_END_NAMESPACE QT_END_HEADER #endif // QACCESSIBLEOBJECT_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 140 ] ] ]
997777ab599fde518d28953ab678227fe572d92d
d7b345a8a6b0473c325fab661342de295c33b9c8
/beta/src/Polarizer3/Polarizer3Dlg.h
14bac1cccee73f949f8af62625b31a8b78d83a6a
[]
no_license
raould/Polaris-Open-Source
67ccd647bf40de51a3dae903ab70e8c271f3f448
10d0ca7e2db9e082e1d2ed2e43fa46875f1b07b2
refs/heads/master
2021-01-01T19:19:39.148016
2010-05-10T17:39:26
2010-05-10T17:39:26
631,953
3
2
null
null
null
null
UTF-8
C++
false
false
1,691
h
// Copyright 2010 Hewlett-Packard under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html // Polarizer3Dlg.h : header file // #pragma once #include "afxwin.h" #include "PetModel.h" // CPolarizer3Dlg dialog class CPolarizer3Dlg : public CDialog { // Construction std::vector<std::wstring> getFileExtensions(); std::vector<PetModel*> knownAppModels; PetModel model; void polarizeFromScratch(); void repolarize(); void updateEndowments(); void clearWindow(); void loadDialogFromModel(); /** * returns a status, 0 if success */ int loadModelFromDialog(); public: CPolarizer3Dlg(CWnd* pParent = NULL); // standard constructor ~CPolarizer3Dlg(); // Dialog Data enum { IDD = IDD_POLARIZER3_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CEdit m_path; CEdit m_petname; afx_msg void OnBnClickedButton2(); afx_msg void OnBnClickedButton1(); afx_msg void OnEnChangeEdit3(); CEdit m_fileExtensionsText; afx_msg void OnBnClickedButton3(); afx_msg void OnEnChangeEdit1(); afx_msg void OnLbnSelchangeList1(); CListBox ExistingPetsList; afx_msg void OnBnClickedButton5(); afx_msg void OnBnClickedButton4(); CListBox KnownAppsBox; afx_msg void OnLbnSelchangeList2(); afx_msg void OnBnClickedButton6(); afx_msg void OnBnClickedButton7(); };
[ [ [ 1, 66 ] ] ]
93caff0d318cf5415a2686cea2fd0e93b9f5e8bc
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAIBox2DJoint.cpp
a0a462a3c38e8bbc326d25acd59ecf0d1d60175e
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
10,951
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <Box2D/Box2D.h> #include <moaicore/MOAIBox2DArbiter.h> #include <moaicore/MOAIBox2DBody.h> #include <moaicore/MOAIBox2DJoint.h> #include <moaicore/MOAIBox2DWorld.h> #include <moaicore/MOAILogMessages.h> SUPPRESS_EMPTY_FILE_WARNING #if USE_BOX2D //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name destroy @text Schedule joint for destruction. @in MOAIBox2DBody self @out nil */ int MOAIBox2DJoint::_destroy ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) assert ( self->mWorld ); self->mWorld->ScheduleDestruction ( *self ); return 0; } //----------------------------------------------------------------// /** @name getAnchorA @text See Box2D documentation. @in MOAIBox2DJoint self @out anchorX @out anchorY */ int MOAIBox2DJoint::_getAnchorA ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) float unitsToMeters = self->GetUnitsToMeters (); b2Vec2 anchor = self->mJoint->GetAnchorA (); lua_pushnumber ( state, anchor.x / unitsToMeters ); lua_pushnumber ( state, anchor.y / unitsToMeters ); return 2; } //----------------------------------------------------------------// /** @name getAnchorB @text See Box2D documentation. @in MOAIBox2DJoint self @out anchorX @out anchorY */ int MOAIBox2DJoint::_getAnchorB ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) float unitsToMeters = self->GetUnitsToMeters (); b2Vec2 anchor = self->mJoint->GetAnchorB (); lua_pushnumber ( state, anchor.x / unitsToMeters ); lua_pushnumber ( state, anchor.y / unitsToMeters ); return 2; } //----------------------------------------------------------------// /** @name getBodyA @text See Box2D documentation. @in MOAIBox2DJoint self @out MOAIBox2DBody body */ int MOAIBox2DJoint::_getBodyA ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) MOAIBox2DBody* body = ( MOAIBox2DBody* )self->mJoint->GetBodyA ()->GetUserData ();; body->PushLuaUserdata ( state ); return 1; } //----------------------------------------------------------------// /** @name getBodyB @text See Box2D documentation. @in MOAIBox2DJoint self @out MOAIBox2DBody body */ int MOAIBox2DJoint::_getBodyB ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) MOAIBox2DBody* body = ( MOAIBox2DBody* )self->mJoint->GetBodyB ()->GetUserData ();; body->PushLuaUserdata ( state ); return 1; } //----------------------------------------------------------------// /** @name getReactionForce @text See Box2D documentation. @in MOAIBox2DJoint self @out number forceX @out number forceY */ int MOAIBox2DJoint::_getReactionForce ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) // TODO //b2Vec2 force = self->mJoint->GetReactionForce (); //lua_pushnumber ( state, force.x ); //lua_pushnumber ( state, force.y ); return 2; } //----------------------------------------------------------------// /** @name getReactionForce @text See Box2D documentation. @in MOAIBox2DJoint self @out number reactionTorque In degrees. */ int MOAIBox2DJoint::_getReactionTorque ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) // TODO //float torque = self->mJoint->GetReactionTorque (); //lua_pushnumber ( state, torque ); return 1; } //----------------------------------------------------------------// /** @name setLimit @text See Box2D documentation. @in MOAIBox2DJoint self @opt number lower Default value is 0. @opt number upper Default value is 0. @out nil */ int MOAIBox2DJoint::_setLimit ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) float lower = state.GetValue < float >( 2, 0.0f ); float upper = state.GetValue < float >( 3, 0.0f ); self->SetLimit ( lower, upper ); return 0; } //----------------------------------------------------------------// /** @name setLimitEnabled @text See Box2D documentation. @in MOAIBox2DJoint self @opt boolean enabled Default value is 'true' @out nil */ int MOAIBox2DJoint::_setLimitEnabled ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) bool enabled = state.GetValue < bool >( 2, true ); self->SetLimitEnabled ( enabled ); return 0; } //----------------------------------------------------------------// /** @name setMotor @text See Box2D documentation. @in MOAIBox2DJoint self @opt number speed Default value is 0. @opt number max Default value is 0. @out nil */ int MOAIBox2DJoint::_setMotor ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) float speed = state.GetValue < float >( 2, 0.0f ); float max = state.GetValue < float >( 3, 0.0f ); self->SetMotor ( speed, max ); return 0; } //----------------------------------------------------------------// /** @name setMotorEnabled @text See Box2D documentation. @in MOAIBox2DJoint self @opt boolean enabled Default value is 'true' @out nil */ int MOAIBox2DJoint::_setMotorEnabled ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIBox2DJoint, "U" ) bool enabled = state.GetValue < bool >( 2, true ); self->SetMotorEnabled ( enabled ); return 0; } //================================================================// // MOAIBox2DJoint //================================================================// //----------------------------------------------------------------// void MOAIBox2DJoint::Destroy () { if ( this->mJoint ) { b2World* world = this->mWorld->mWorld; world->DestroyJoint ( this->mJoint ); this->mJoint = 0; this->Release (); } } //----------------------------------------------------------------// MOAIBox2DJoint::MOAIBox2DJoint () : mJoint ( 0 ) { RTTI_BEGIN RTTI_EXTEND ( USLuaObject ) RTTI_END } //----------------------------------------------------------------// MOAIBox2DJoint::~MOAIBox2DJoint () { MOAIBox2DBody* bodyA = ( MOAIBox2DBody* )this->mJoint->GetBodyA (); MOAIBox2DBody* bodyB = ( MOAIBox2DBody* )this->mJoint->GetBodyB (); bodyA->Release (); bodyB->Release (); } //----------------------------------------------------------------// void MOAIBox2DJoint::RegisterLuaClass ( USLuaState& state ) { UNUSED ( state ); } //----------------------------------------------------------------// void MOAIBox2DJoint::RegisterLuaFuncs ( USLuaState& state ) { luaL_Reg regTable [] = { { "destroy", _destroy }, { "getAnchorA", _getAnchorA }, { "getAnchorB", _getAnchorB }, { "getBodyA", _getBodyA }, { "getBodyB", _getBodyB }, { "getReactionForce", _getReactionForce }, { "getReactionTorque", _getReactionTorque }, { "setLimit", _setLimit }, { "setLimitEnabled", _setLimitEnabled }, { "setMotor", _setMotor }, { "setMotorEnabled", _setMotorEnabled }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIBox2DJoint::SetJoint ( b2Joint* joint ) { this->mJoint = joint; joint->SetUserData ( this ); } //----------------------------------------------------------------// void MOAIBox2DJoint::SetLimit ( float lower, float upper ) { float unitsToMeters = this->GetUnitsToMeters (); b2JointType type = this->mJoint->GetType (); switch ( type ) { case e_lineJoint: { b2LineJoint* joint = ( b2LineJoint* )this->mJoint; joint->SetLimits ( lower * unitsToMeters, upper * unitsToMeters ); joint->EnableLimit ( true ); break; } case e_prismaticJoint: { b2PrismaticJoint* joint = ( b2PrismaticJoint* )this->mJoint; joint->SetLimits ( lower * unitsToMeters, upper * unitsToMeters ); joint->EnableLimit ( true ); break; } case e_revoluteJoint: { b2RevoluteJoint* joint = ( b2RevoluteJoint* )this->mJoint; joint->SetLimits ( lower * ( float )D2R, upper * ( float )D2R ); joint->EnableLimit ( true ); break; } default: break; } } //----------------------------------------------------------------// void MOAIBox2DJoint::SetLimitEnabled ( bool enabled ) { b2JointType type = this->mJoint->GetType (); switch ( type ) { case e_lineJoint: { b2LineJoint* joint = ( b2LineJoint* )this->mJoint; joint->EnableLimit ( enabled ); break; } case e_prismaticJoint: { b2PrismaticJoint* joint = ( b2PrismaticJoint* )this->mJoint; joint->EnableLimit ( enabled ); break; } case e_revoluteJoint: { b2RevoluteJoint* joint = ( b2RevoluteJoint* )this->mJoint; joint->EnableLimit ( enabled ); break; } default: break; } } //----------------------------------------------------------------// void MOAIBox2DJoint::SetMotor ( float speed, float max ) { float unitsToMeters = this->GetUnitsToMeters (); b2JointType type = this->mJoint->GetType (); switch ( type ) { case e_lineJoint: { b2LineJoint* joint = ( b2LineJoint* )this->mJoint; joint->SetMotorSpeed ( speed * unitsToMeters ); joint->SetMaxMotorForce ( max * unitsToMeters ); joint->EnableMotor ( speed != 0.0f ); break; } case e_prismaticJoint: { b2PrismaticJoint* joint = ( b2PrismaticJoint* )this->mJoint; joint->SetMotorSpeed ( speed * unitsToMeters ); joint->SetMaxMotorForce ( max * unitsToMeters ); joint->EnableMotor ( speed != 0.0f ); break; } case e_revoluteJoint: { b2RevoluteJoint* joint = ( b2RevoluteJoint* )this->mJoint; joint->SetMotorSpeed ( speed * ( float )D2R ); joint->SetMaxMotorTorque ( max * ( float )D2R ); joint->EnableMotor ( speed != 0.0f ); break; } default: break; } } //----------------------------------------------------------------// void MOAIBox2DJoint::SetMotorEnabled ( bool enabled ) { b2JointType type = this->mJoint->GetType (); switch ( type ) { case e_lineJoint: { b2LineJoint* joint = ( b2LineJoint* )this->mJoint; joint->EnableMotor ( enabled ); break; } case e_prismaticJoint: { b2PrismaticJoint* joint = ( b2PrismaticJoint* )this->mJoint; joint->EnableMotor ( enabled ); break; } case e_revoluteJoint: { b2RevoluteJoint* joint = ( b2RevoluteJoint* )this->mJoint; joint->EnableMotor ( enabled ); break; } default: break; } } //----------------------------------------------------------------// STLString MOAIBox2DJoint::ToString () { STLString repr; return repr; } #endif
[ [ [ 1, 18 ], [ 35, 218 ], [ 230, 257 ], [ 259, 427 ] ], [ [ 19, 34 ], [ 219, 229 ], [ 258, 258 ], [ 428, 428 ] ] ]
5df0bb572ba0f05e0b88ffa50460632ccf0dc96a
2924ffa50aab2caf1daf1b6482e1ca63f51e946e
/videoInputSrcAndDemos/libs/videoInput/videoInput.cpp
f4cedfc9ded5c3aab8130f8a2c3e220807d1322a
[]
no_license
gotomypc/videoInput
14168a5c428a6487d36caf9b1a2555f751127eb8
25838cca0b84a9aef1bca36a4794ec544b64be92
refs/heads/master
2020-12-25T11:52:57.684594
2011-10-11T18:35:46
2011-10-11T18:35:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
75,302
cpp
//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. #define DEBUG 1 #define _DEBUG 1 #include "videoInput.h" #include "tchar.h" //Include Directshow stuff here so we don't worry about needing all the h files. #include "DShow.h" #include "streams.h" #include "qedit.h" #include "vector" #include "Aviriff.h" #include "Windows.h" //for threading #include <process.h> /////////////////////////// HANDY FUNCTIONS ///////////////////////////// void MyFreeMediaType(AM_MEDIA_TYPE& mt){ if (mt.cbFormat != 0) { CoTaskMemFree((PVOID)mt.pbFormat); mt.cbFormat = 0; mt.pbFormat = NULL; } if (mt.pUnk != NULL) { // Unecessary because pUnk should not be used, but safest. mt.pUnk->Release(); mt.pUnk = NULL; } } void MyDeleteMediaType(AM_MEDIA_TYPE *pmt) { if (pmt != NULL) { MyFreeMediaType(*pmt); CoTaskMemFree(pmt); } } ////////////////////////////// CALLBACK //////////////////////////////// //Callback class class SampleGrabberCallback : public ISampleGrabberCB{ public: //------------------------------------------------ SampleGrabberCallback(){ InitializeCriticalSection(&critSection); freezeCheck = 0; bufferSetup = false; newFrame = false; latestBufferLength = 0; hEvent = CreateEvent(NULL, true, false, NULL); } //------------------------------------------------ ~SampleGrabberCallback(){ ptrBuffer = NULL; DeleteCriticalSection(&critSection); CloseHandle(hEvent); if(bufferSetup){ delete pixels; } } //------------------------------------------------ bool setupBuffer(int numBytesIn){ if(bufferSetup){ return false; }else{ numBytes = numBytesIn; pixels = new unsigned char[numBytes]; bufferSetup = true; newFrame = false; latestBufferLength = 0; } return true; } //------------------------------------------------ STDMETHODIMP_(ULONG) AddRef() { return 1; } STDMETHODIMP_(ULONG) Release() { return 2; } //------------------------------------------------ STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject){ *ppvObject = static_cast<ISampleGrabberCB*>(this); return S_OK; } //This method is meant to have less overhead //------------------------------------------------ STDMETHODIMP SampleCB(double Time, IMediaSample *pSample){ if(WaitForSingleObject(hEvent, 0) == WAIT_OBJECT_0) return S_OK; HRESULT hr = pSample->GetPointer(&ptrBuffer); if(hr == S_OK){ latestBufferLength = pSample->GetActualDataLength(); if(latestBufferLength == numBytes){ EnterCriticalSection(&critSection); memcpy(pixels, ptrBuffer, latestBufferLength); newFrame = true; freezeCheck = 1; LeaveCriticalSection(&critSection); SetEvent(hEvent); }else{ printf("ERROR: SampleCB() - buffer sizes do not match\n"); } } return S_OK; } //This method is meant to have more overhead STDMETHODIMP BufferCB(double Time, BYTE *pBuffer, long BufferLen){ return E_NOTIMPL; } int freezeCheck; int latestBufferLength; int numBytes; bool newFrame; bool bufferSetup; unsigned char * pixels; unsigned char * ptrBuffer; CRITICAL_SECTION critSection; HANDLE hEvent; }; ////////////////////////////// VIDEO DEVICE //////////////////////////////// // ---------------------------------------------------------------------- // Should this class also be the callback? // // ---------------------------------------------------------------------- videoDevice::videoDevice(){ pCaptureGraph = NULL; // Capture graph builder object pGraph = NULL; // Graph builder object pControl = NULL; // Media control object pVideoInputFilter = NULL; // Video Capture filter pGrabber = NULL; // Grabs frame pDestFilter = NULL; // Null Renderer Filter pGrabberF = NULL; // Grabber Filter pMediaEvent = NULL; streamConf = NULL; pAmMediaType = NULL; //This is our callback class that processes the frame. sgCallback = new SampleGrabberCallback(); sgCallback->newFrame = false; //Default values for capture type videoType = MEDIASUBTYPE_RGB24; connection = PhysConn_Video_Composite; storeConn = 0; videoSize = 0; width = 0; height = 0; tryWidth = 0; tryHeight = 0; nFramesForReconnect= 10000; nFramesRunning = 0; myID = -1; tryDiffSize = false; useCrossbar = false; readyToCapture = false; sizeSet = false; setupStarted = false; specificFormat = false; autoReconnect = false; requestedFrameTime = -1; memset(wDeviceName, 0, sizeof(WCHAR) * 255); memset(nDeviceName, 0, sizeof(char) * 255); } // ---------------------------------------------------------------------- // The only place we are doing new // // ---------------------------------------------------------------------- void videoDevice::setSize(int w, int h){ if(sizeSet){ if(verbose)printf("SETUP: Error device size should not be set more than once \n"); } else { width = w; height = h; videoSize = w*h*3; sizeSet = true; pixels = new unsigned char[videoSize]; pBuffer = new char[videoSize]; memset(pixels, 0 , videoSize); sgCallback->setupBuffer(videoSize); } } // ---------------------------------------------------------------------- // Borrowed from the SDK, use it to take apart the graph from // the capture device downstream to the null renderer // ---------------------------------------------------------------------- void videoDevice::NukeDownstream(IBaseFilter *pBF){ IPin *pP, *pTo; ULONG u; IEnumPins *pins = NULL; PIN_INFO pininfo; HRESULT hr = pBF->EnumPins(&pins); pins->Reset(); while (hr == NOERROR) { hr = pins->Next(1, &pP, &u); if (hr == S_OK && pP) { pP->ConnectedTo(&pTo); if (pTo) { hr = pTo->QueryPinInfo(&pininfo); if (hr == NOERROR) { if (pininfo.dir == PINDIR_INPUT) { NukeDownstream(pininfo.pFilter); pGraph->Disconnect(pTo); pGraph->Disconnect(pP); pGraph->RemoveFilter(pininfo.pFilter); } pininfo.pFilter->Release(); pininfo.pFilter = NULL; } pTo->Release(); } pP->Release(); } } if (pins) pins->Release(); } // ---------------------------------------------------------------------- // Also from SDK // ---------------------------------------------------------------------- void videoDevice::destroyGraph(){ HRESULT hr = 0; //int FuncRetval=0; //int NumFilters=0; int i = 0; while (hr == NOERROR) { IEnumFilters * pEnum = 0; ULONG cFetched; // We must get the enumerator again every time because removing a filter from the graph // invalidates the enumerator. We always get only the first filter from each enumerator. hr = pGraph->EnumFilters(&pEnum); if (FAILED(hr)) { if(verbose)printf("SETUP: pGraph->EnumFilters() failed. \n"); return; } IBaseFilter * pFilter = NULL; if (pEnum->Next(1, &pFilter, &cFetched) == S_OK) { FILTER_INFO FilterInfo; hr = pFilter->QueryFilterInfo(&FilterInfo); FilterInfo.pGraph->Release(); int count = 0; char buffer[255]; memset(buffer, 0, 255 * sizeof(char)); while( FilterInfo.achName[count] != 0x00 ) { buffer[count] = FilterInfo.achName[count]; count++; } if(verbose)printf("SETUP: removing filter %s...\n", buffer); hr = pGraph->RemoveFilter(pFilter); if (FAILED(hr)) { if(verbose)printf("SETUP: pGraph->RemoveFilter() failed. \n"); return; } if(verbose)printf("SETUP: filter removed %s \n",buffer); pFilter->Release(); pFilter = NULL; } else break; pEnum->Release(); pEnum = NULL; i++; } return; } // ---------------------------------------------------------------------- // Our deconstructor, attempts to tear down graph and release filters etc // Does checking to make sure it only is freeing if it needs to // Probably could be a lot cleaner! :) // ---------------------------------------------------------------------- videoDevice::~videoDevice(){ if(setupStarted){ if(verbose)printf("\nSETUP: Disconnecting device %i\n", myID); } else{ if(sgCallback){ sgCallback->Release(); delete sgCallback; } return; } HRESULT HR = 0; //Stop the callback and free it if( (sgCallback) && (pGrabber) ) { pGrabber->SetCallback(NULL, 1); if(verbose)printf("SETUP: freeing Grabber Callback\n"); sgCallback->Release(); //delete our pixels if(sizeSet){ delete[] pixels; delete[] pBuffer; } delete sgCallback; } //Check to see if the graph is running, if so stop it. if( (pControl) ) { HR = pControl->Pause(); if (FAILED(HR)) if(verbose)printf("ERROR - Could not pause pControl\n"); HR = pControl->Stop(); if (FAILED(HR)) if(verbose)printf("ERROR - Could not stop pControl\n"); } //Disconnect filters from capture device if( (pVideoInputFilter) )NukeDownstream(pVideoInputFilter); //Release and zero pointers to our filters etc if( (pDestFilter) ){ if(verbose)printf("SETUP: freeing Renderer \n"); (pDestFilter)->Release(); (pDestFilter) = 0; } if( (pVideoInputFilter) ){ if(verbose)printf("SETUP: freeing Capture Source \n"); (pVideoInputFilter)->Release(); (pVideoInputFilter) = 0; } if( (pGrabberF) ){ if(verbose)printf("SETUP: freeing Grabber Filter \n"); (pGrabberF)->Release(); (pGrabberF) = 0; } if( (pGrabber) ){ if(verbose)printf("SETUP: freeing Grabber \n"); (pGrabber)->Release(); (pGrabber) = 0; } if( (pControl) ){ if(verbose)printf("SETUP: freeing Control \n"); (pControl)->Release(); (pControl) = 0; } if( (pMediaEvent) ){ if(verbose)printf("SETUP: freeing Media Event \n"); (pMediaEvent)->Release(); (pMediaEvent) = 0; } if( (streamConf) ){ if(verbose)printf("SETUP: freeing Stream \n"); (streamConf)->Release(); (streamConf) = 0; } if( (pAmMediaType) ){ if(verbose)printf("SETUP: freeing Media Type \n"); MyDeleteMediaType(pAmMediaType); } if((pMediaEvent)){ if(verbose)printf("SETUP: freeing Media Event \n"); (pMediaEvent)->Release(); (pMediaEvent) = 0; } //Destroy the graph if( (pGraph) )destroyGraph(); //Release and zero our capture graph and our main graph if( (pCaptureGraph) ){ if(verbose)printf("SETUP: freeing Capture Graph \n"); (pCaptureGraph)->Release(); (pCaptureGraph) = 0; } if( (pGraph) ){ if(verbose)printf("SETUP: freeing Main Graph \n"); (pGraph)->Release(); (pGraph) = 0; } //delete our pointers delete pDestFilter; delete pVideoInputFilter; delete pGrabberF; delete pGrabber; delete pControl; delete streamConf; delete pMediaEvent; delete pCaptureGraph; delete pGraph; if(verbose)printf("SETUP: Device %i disconnected and freed\n\n",myID); } ////////////////////////////// VIDEO INPUT //////////////////////////////// //////////////////////////// PUBLIC METHODS /////////////////////////////// // ---------------------------------------------------------------------- // Constructor - creates instances of videoDevice and adds the various // media subtypes to check. // ---------------------------------------------------------------------- videoInput::videoInput(){ //start com comInit(); devicesFound = 0; callbackSetCount = 0; bCallback = true; //setup a max no of device objects for(int i=0; i<VI_MAX_CAMERAS; i++) VDList[i] = new videoDevice(); if(verbose)printf("\n***** VIDEOINPUT LIBRARY - %2.04f - TFW07 *****\n\n",VI_VERSION); //added for the pixelink firewire camera MEDIASUBTYPE_Y800 = (GUID)FOURCCMap(FCC('Y800')); MEDIASUBTYPE_Y8 = (GUID)FOURCCMap(FCC('Y8')); MEDIASUBTYPE_GREY = (GUID)FOURCCMap(FCC('GREY')); //The video types we support //in order of preference mediaSubtypes[0] = MEDIASUBTYPE_RGB24; mediaSubtypes[1] = MEDIASUBTYPE_RGB32; mediaSubtypes[2] = MEDIASUBTYPE_RGB555; mediaSubtypes[3] = MEDIASUBTYPE_RGB565; mediaSubtypes[4] = MEDIASUBTYPE_YUY2; mediaSubtypes[5] = MEDIASUBTYPE_YVYU; mediaSubtypes[6] = MEDIASUBTYPE_YUYV; mediaSubtypes[7] = MEDIASUBTYPE_IYUV; mediaSubtypes[8] = MEDIASUBTYPE_UYVY; mediaSubtypes[9] = MEDIASUBTYPE_YV12; mediaSubtypes[10] = MEDIASUBTYPE_YVU9; mediaSubtypes[11] = MEDIASUBTYPE_Y411; mediaSubtypes[12] = MEDIASUBTYPE_Y41P; mediaSubtypes[13] = MEDIASUBTYPE_Y211; mediaSubtypes[14] = MEDIASUBTYPE_AYUV; //non standard mediaSubtypes[15] = MEDIASUBTYPE_Y800; mediaSubtypes[16] = MEDIASUBTYPE_Y8; mediaSubtypes[17] = MEDIASUBTYPE_GREY; //The video formats we support formatTypes[VI_NTSC_M] = AnalogVideo_NTSC_M; formatTypes[VI_NTSC_M_J] = AnalogVideo_NTSC_M_J; formatTypes[VI_NTSC_433] = AnalogVideo_NTSC_433; formatTypes[VI_PAL_B] = AnalogVideo_PAL_B; formatTypes[VI_PAL_D] = AnalogVideo_PAL_D; formatTypes[VI_PAL_G] = AnalogVideo_PAL_G; formatTypes[VI_PAL_H] = AnalogVideo_PAL_H; formatTypes[VI_PAL_I] = AnalogVideo_PAL_I; formatTypes[VI_PAL_M] = AnalogVideo_PAL_M; formatTypes[VI_PAL_N] = AnalogVideo_PAL_N; formatTypes[VI_PAL_NC] = AnalogVideo_PAL_N_COMBO; formatTypes[VI_SECAM_B] = AnalogVideo_SECAM_B; formatTypes[VI_SECAM_D] = AnalogVideo_SECAM_D; formatTypes[VI_SECAM_G] = AnalogVideo_SECAM_G; formatTypes[VI_SECAM_H] = AnalogVideo_SECAM_H; formatTypes[VI_SECAM_K] = AnalogVideo_SECAM_K; formatTypes[VI_SECAM_K1] = AnalogVideo_SECAM_K1; formatTypes[VI_SECAM_L] = AnalogVideo_SECAM_L; propBrightness = VideoProcAmp_Brightness; propContrast = VideoProcAmp_Contrast; propHue = VideoProcAmp_Hue; propSaturation = VideoProcAmp_Saturation; propSharpness = VideoProcAmp_Sharpness; propGamma = VideoProcAmp_Gamma; propColorEnable = VideoProcAmp_ColorEnable; propWhiteBalance = VideoProcAmp_WhiteBalance; propBacklightCompensation = VideoProcAmp_BacklightCompensation; propGain = VideoProcAmp_Gain; propPan = CameraControl_Pan; propTilt = CameraControl_Tilt; propRoll = CameraControl_Roll; propZoom = CameraControl_Zoom; propExposure = CameraControl_Exposure; propIris = CameraControl_Iris; propFocus = CameraControl_Focus; } // ---------------------------------------------------------------------- // static - set whether messages get printed to console or not // // ---------------------------------------------------------------------- void videoInput::setVerbose(bool _verbose){ verbose = _verbose; } // ---------------------------------------------------------------------- // change to use callback or regular capture // callback tells you when a new frame has arrived // but non-callback won't - but is single threaded // ---------------------------------------------------------------------- void videoInput::setUseCallback(bool useCallback){ if(callbackSetCount == 0){ bCallback = useCallback; callbackSetCount = 1; }else{ printf("ERROR: setUseCallback can only be called before setup\n"); } } // ---------------------------------------------------------------------- // Set the requested framerate - no guarantee you will get this // // ---------------------------------------------------------------------- void videoInput::setIdealFramerate(int deviceNumber, int idealFramerate){ if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return; if( idealFramerate > 0 ){ VDList[deviceNumber]->requestedFrameTime = (unsigned long)(10000000 / idealFramerate); } } // ---------------------------------------------------------------------- // Set the requested framerate - no guarantee you will get this // // ---------------------------------------------------------------------- void videoInput::setAutoReconnectOnFreeze(int deviceNumber, bool doReconnect, int numMissedFramesBeforeReconnect){ if(deviceNumber >= VI_MAX_CAMERAS) return; VDList[deviceNumber]->autoReconnect = doReconnect; VDList[deviceNumber]->nFramesForReconnect = numMissedFramesBeforeReconnect; } // ---------------------------------------------------------------------- // Setup a device with the default settings // // ---------------------------------------------------------------------- bool videoInput::setupDevice(int deviceNumber){ if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false; if(setup(deviceNumber))return true; return false; } // ---------------------------------------------------------------------- // Setup a device with the default size but specify input type // // ---------------------------------------------------------------------- bool videoInput::setupDevice(int deviceNumber, int connection){ if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false; setPhyCon(deviceNumber, connection); if(setup(deviceNumber))return true; return false; } // ---------------------------------------------------------------------- // Setup a device with the default connection but specify size // // ---------------------------------------------------------------------- bool videoInput::setupDevice(int deviceNumber, int w, int h){ if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false; setAttemptCaptureSize(deviceNumber,w,h); if(setup(deviceNumber))return true; return false; } // ---------------------------------------------------------------------- // Setup a device with specific size and connection // // ---------------------------------------------------------------------- bool videoInput::setupDevice(int deviceNumber, int w, int h, int connection){ if(deviceNumber >= VI_MAX_CAMERAS || VDList[deviceNumber]->readyToCapture) return false; setAttemptCaptureSize(deviceNumber,w,h); setPhyCon(deviceNumber, connection); if(setup(deviceNumber))return true; return false; } // ---------------------------------------------------------------------- // Setup the default video format of the device // Must be called after setup! // See #define formats in header file (eg VI_NTSC_M ) // // ---------------------------------------------------------------------- bool videoInput::setFormat(int deviceNumber, int format){ if(deviceNumber >= VI_MAX_CAMERAS || !VDList[deviceNumber]->readyToCapture) return false; bool returnVal = false; if(format >= 0 && format < VI_NUM_FORMATS){ VDList[deviceNumber]->formatType = formatTypes[format]; VDList[deviceNumber]->specificFormat = true; if(VDList[deviceNumber]->specificFormat){ HRESULT hr = getDevice(&VDList[deviceNumber]->pVideoInputFilter, deviceNumber, VDList[deviceNumber]->wDeviceName, VDList[deviceNumber]->nDeviceName); if(hr != S_OK){ return false; } IAMAnalogVideoDecoder *pVideoDec = NULL; hr = VDList[deviceNumber]->pCaptureGraph->FindInterface(NULL, &MEDIATYPE_Video, VDList[deviceNumber]->pVideoInputFilter, IID_IAMAnalogVideoDecoder, (void **)&pVideoDec); //in case the settings window some how freed them first if(VDList[deviceNumber]->pVideoInputFilter)VDList[deviceNumber]->pVideoInputFilter->Release(); if(VDList[deviceNumber]->pVideoInputFilter)VDList[deviceNumber]->pVideoInputFilter = NULL; if(FAILED(hr)){ printf("SETUP: couldn't set requested format\n"); }else{ long lValue = 0; hr = pVideoDec->get_AvailableTVFormats(&lValue); if( SUCCEEDED(hr) && (lValue & VDList[deviceNumber]->formatType) ) { hr = pVideoDec->put_TVFormat(VDList[deviceNumber]->formatType); if( FAILED(hr) ){ printf("SETUP: couldn't set requested format\n"); }else{ returnVal = true; } } pVideoDec->Release(); pVideoDec = NULL; } } } return returnVal; } // ---------------------------------------------------------------------- // Our static function for returning device names - thanks Peter! // Must call listDevices first. // // ---------------------------------------------------------------------- char videoInput::deviceNames[VI_MAX_CAMERAS][255]={{0}}; char * videoInput::getDeviceName(int deviceID){ if( deviceID >= VI_MAX_CAMERAS ){ return NULL; } return deviceNames[deviceID]; } // ---------------------------------------------------------------------- // Our static function for finding num devices available etc // // ---------------------------------------------------------------------- int videoInput::listDevices(bool silent){ //COM Library Intialization comInit(); if(!silent)printf("\nVIDEOINPUT SPY MODE!\n\n"); ICreateDevEnum *pDevEnum = NULL; IEnumMoniker *pEnum = NULL; int deviceCounter = 0; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>(&pDevEnum)); if (SUCCEEDED(hr)) { // Create an enumerator for the video capture category. hr = pDevEnum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory, &pEnum, 0); if(hr == S_OK){ if(!silent)printf("SETUP: Looking For Capture Devices\n"); IMoniker *pMoniker = NULL; while (pEnum->Next(1, &pMoniker, NULL) == S_OK){ IPropertyBag *pPropBag; hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)(&pPropBag)); if (FAILED(hr)){ pMoniker->Release(); continue; // Skip this one, maybe the next one will work. } // Find the description or friendly name. VARIANT varName; VariantInit(&varName); hr = pPropBag->Read(L"Description", &varName, 0); if (FAILED(hr)) hr = pPropBag->Read(L"FriendlyName", &varName, 0); if (SUCCEEDED(hr)){ hr = pPropBag->Read(L"FriendlyName", &varName, 0); int count = 0; int maxLen = sizeof(deviceNames[0])/sizeof(deviceNames[0][0]) - 2; while( varName.bstrVal[count] != 0x00 && count < maxLen) { deviceNames[deviceCounter][count] = varName.bstrVal[count]; count++; } deviceNames[deviceCounter][count] = 0; if(!silent)printf("SETUP: %i) %s \n",deviceCounter, deviceNames[deviceCounter]); } pPropBag->Release(); pPropBag = NULL; pMoniker->Release(); pMoniker = NULL; deviceCounter++; } pDevEnum->Release(); pDevEnum = NULL; pEnum->Release(); pEnum = NULL; } if(!silent)printf("SETUP: %i Device(s) found\n\n", deviceCounter); } comUnInit(); return deviceCounter; } // ---------------------------------------------------------------------- // // // ---------------------------------------------------------------------- int videoInput::getWidth(int id){ if(isDeviceSetup(id)) { return VDList[id] ->width; } return 0; } // ---------------------------------------------------------------------- // // // ---------------------------------------------------------------------- int videoInput::getHeight(int id){ if(isDeviceSetup(id)) { return VDList[id] ->height; } return 0; } // ---------------------------------------------------------------------- // // // ---------------------------------------------------------------------- int videoInput::getSize(int id){ if(isDeviceSetup(id)) { return VDList[id] ->videoSize; } return 0; } // ---------------------------------------------------------------------- // Uses a supplied buffer // ---------------------------------------------------------------------- bool videoInput::getPixels(int id, unsigned char * dstBuffer, bool flipRedAndBlue, bool flipImage){ bool success = false; if(isDeviceSetup(id)){ if(bCallback){ //callback capture DWORD result = WaitForSingleObject(VDList[id]->sgCallback->hEvent, 1000); if( result != WAIT_OBJECT_0) return false; //double paranoia - mutexing with both event and critical section EnterCriticalSection(&VDList[id]->sgCallback->critSection); unsigned char * src = VDList[id]->sgCallback->pixels; unsigned char * dst = dstBuffer; int height = VDList[id]->height; int width = VDList[id]->width; processPixels(src, dst, width, height, flipRedAndBlue, flipImage); VDList[id]->sgCallback->newFrame = false; LeaveCriticalSection(&VDList[id]->sgCallback->critSection); ResetEvent(VDList[id]->sgCallback->hEvent); success = true; } else{ //regular capture method long bufferSize = VDList[id]->videoSize; HRESULT hr = VDList[id]->pGrabber->GetCurrentBuffer(&bufferSize, (long *)VDList[id]->pBuffer); if(hr==S_OK){ int numBytes = VDList[id]->videoSize; if (numBytes == bufferSize){ unsigned char * src = (unsigned char * )VDList[id]->pBuffer; unsigned char * dst = dstBuffer; int height = VDList[id]->height; int width = VDList[id]->width; processPixels(src, dst, width, height, flipRedAndBlue, flipImage); success = true; }else{ if(verbose)printf("ERROR: GetPixels() - bufferSizes do not match!\n"); } }else{ if(verbose)printf("ERROR: GetPixels() - Unable to grab frame for device %i\n", id); } } } return success; } // ---------------------------------------------------------------------- // Returns a buffer // ---------------------------------------------------------------------- unsigned char * videoInput::getPixels(int id, bool flipRedAndBlue, bool flipImage){ if(isDeviceSetup(id)){ getPixels(id, VDList[id]->pixels, flipRedAndBlue, flipImage); } return VDList[id]->pixels; } // ---------------------------------------------------------------------- // // // ---------------------------------------------------------------------- bool videoInput::isFrameNew(int id){ if(!isDeviceSetup(id)) return false; if(!bCallback)return true; bool result = false; bool freeze = false; //again super paranoia! EnterCriticalSection(&VDList[id]->sgCallback->critSection); result = VDList[id]->sgCallback->newFrame; //we need to give it some time at the begining to start up so lets check after 400 frames if(VDList[id]->nFramesRunning > 400 && VDList[id]->sgCallback->freezeCheck > VDList[id]->nFramesForReconnect ){ freeze = true; } //we increment the freezeCheck var here - the callback resets it to 1 //so as long as the callback is running this var should never get too high. //if the callback is not running then this number will get high and trigger the freeze action below VDList[id]->sgCallback->freezeCheck++; LeaveCriticalSection(&VDList[id]->sgCallback->critSection); VDList[id]->nFramesRunning++; if(freeze && VDList[id]->autoReconnect){ if(verbose)printf("ERROR: Device seems frozen - attempting to reconnect\n"); if( !restartDevice(VDList[id]->myID) ){ if(verbose)printf("ERROR: Unable to reconnect to device\n"); }else{ if(verbose)printf("SUCCESS: Able to reconnect to device\n"); } } return result; } // ---------------------------------------------------------------------- // // // ---------------------------------------------------------------------- bool videoInput::isDeviceSetup(int id){ if(id<devicesFound && VDList[id]->readyToCapture)return true; else return false; } // ---------------------------------------------------------------------- // Gives us a little pop up window to adjust settings // We do this in a seperate thread now! // ---------------------------------------------------------------------- void __cdecl videoInput::basicThread(void * objPtr){ //get a reference to the video device //not a copy as we need to free the filter videoDevice * vd = *( (videoDevice **)(objPtr) ); ShowFilterPropertyPages(vd->pVideoInputFilter); //now we free the filter and make sure it set to NULL if(vd->pVideoInputFilter)vd->pVideoInputFilter->Release(); if(vd->pVideoInputFilter)vd->pVideoInputFilter = NULL; return; } void videoInput::showSettingsWindow(int id){ if(isDeviceSetup(id)){ HANDLE myTempThread; //we reconnect to the device as we have freed our reference to it //why have we freed our reference? because there seemed to be an issue //with some mpeg devices if we didn't HRESULT hr = getDevice(&VDList[id]->pVideoInputFilter, id, VDList[id]->wDeviceName, VDList[id]->nDeviceName); if(hr == S_OK){ myTempThread = (HANDLE)_beginthread(basicThread, 0, (void *)&VDList[id]); } } } // Set a video signal setting using IAMVideoProcAmp bool videoInput::getVideoSettingFilter(int deviceID, long Property, long &min, long &max, long &SteppingDelta, long &currentValue, long &flags, long &defaultValue){ if( !isDeviceSetup(deviceID) )return false; HRESULT hr; //bool isSuccessful = false; videoDevice * VD = VDList[deviceID]; hr = getDevice(&VD->pVideoInputFilter, deviceID, VD->wDeviceName, VD->nDeviceName); if (FAILED(hr)){ printf("setVideoSetting - getDevice Error\n"); return false; } IAMVideoProcAmp *pAMVideoProcAmp = NULL; hr = VD->pVideoInputFilter->QueryInterface(IID_IAMVideoProcAmp, (void**)&pAMVideoProcAmp); if(FAILED(hr)){ printf("setVideoSetting - QueryInterface Error\n"); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return false; } if (verbose) printf("Setting video setting %ld.\n", Property); pAMVideoProcAmp->GetRange(Property, &min, &max, &SteppingDelta, &defaultValue, &flags); if (verbose) printf("Range for video setting %ld: Min:%ld Max:%ld SteppingDelta:%ld Default:%ld Flags:%ld\n", Property, min, max, SteppingDelta, defaultValue, flags); pAMVideoProcAmp->Get(Property, &currentValue, &flags); if(pAMVideoProcAmp)pAMVideoProcAmp->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return true; } // Set a video signal setting using IAMVideoProcAmp bool videoInput::setVideoSettingFilterPct(int deviceID, long Property, float pctValue, long Flags){ if( !isDeviceSetup(deviceID) )return false; long min, max, currentValue, flags, defaultValue, stepAmnt; if( !getVideoSettingFilter(deviceID, Property, min, max, stepAmnt, currentValue, flags, defaultValue) )return false; if(pctValue > 1.0)pctValue = 1.0; else if(pctValue < 0)pctValue = 0.0; float range = (float)max - (float)min; if(range <= 0)return false; if(stepAmnt == 0) return false; long value = (long)( (float)min + range * pctValue ); long rasterValue = value; //if the range is the stepAmnt then it is just a switch //so we either set the value to low or high if( range == stepAmnt ){ if( pctValue < 0.5)rasterValue = min; else rasterValue = max; }else{ //we need to rasterize the value to the stepping amnt long mod = value % stepAmnt; float halfStep = (float)stepAmnt * 0.5; if( mod < halfStep ) rasterValue -= mod; else rasterValue += stepAmnt - mod; printf("RASTER - pctValue is %f - value is %li - step is %li - mod is %li - rasterValue is %li\n", pctValue, value, stepAmnt, mod, rasterValue); } return setVideoSettingFilter(deviceID, Property, rasterValue, Flags, false); } // Set a video signal setting using IAMVideoProcAmp bool videoInput::setVideoSettingFilter(int deviceID, long Property, long lValue, long Flags, bool useDefaultValue){ if( !isDeviceSetup(deviceID) )return false; HRESULT hr; //bool isSuccessful = false; videoDevice * VD = VDList[deviceID]; hr = getDevice(&VD->pVideoInputFilter, deviceID, VD->wDeviceName, VD->nDeviceName); if (FAILED(hr)){ printf("setVideoSetting - getDevice Error\n"); return false; } IAMVideoProcAmp *pAMVideoProcAmp = NULL; hr = VD->pVideoInputFilter->QueryInterface(IID_IAMVideoProcAmp, (void**)&pAMVideoProcAmp); if(FAILED(hr)){ printf("setVideoSetting - QueryInterface Error\n"); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return false; } if (verbose) printf("Setting video setting %ld.\n", Property); long CurrVal, Min, Max, SteppingDelta, Default, CapsFlags, AvailableCapsFlags = 0; pAMVideoProcAmp->GetRange(Property, &Min, &Max, &SteppingDelta, &Default, &AvailableCapsFlags); if (verbose) printf("Range for video setting %ld: Min:%ld Max:%ld SteppingDelta:%ld Default:%ld Flags:%ld\n", Property, Min, Max, SteppingDelta, Default, AvailableCapsFlags); pAMVideoProcAmp->Get(Property, &CurrVal, &CapsFlags); if (verbose) printf("Current value: %ld Flags %ld (%s)\n", CurrVal, CapsFlags, (CapsFlags == 1 ? "Auto" : (CapsFlags == 2 ? "Manual" : "Unknown"))); if (useDefaultValue) { pAMVideoProcAmp->Set(Property, Default, VideoProcAmp_Flags_Auto); } else{ // Perhaps add a check that lValue and Flags are within the range aquired from GetRange above pAMVideoProcAmp->Set(Property, lValue, Flags); } if(pAMVideoProcAmp)pAMVideoProcAmp->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return true; } bool videoInput::setVideoSettingCameraPct(int deviceID, long Property, float pctValue, long Flags){ if( !isDeviceSetup(deviceID) )return false; long min, max, currentValue, flags, defaultValue, stepAmnt; if( !getVideoSettingCamera(deviceID, Property, min, max, stepAmnt, currentValue, flags, defaultValue) )return false; if(pctValue > 1.0)pctValue = 1.0; else if(pctValue < 0)pctValue = 0.0; float range = (float)max - (float)min; if(range <= 0)return false; if(stepAmnt == 0) return false; long value = (long)( (float)min + range * pctValue ); long rasterValue = value; //if the range is the stepAmnt then it is just a switch //so we either set the value to low or high if( range == stepAmnt ){ if( pctValue < 0.5)rasterValue = min; else rasterValue = max; }else{ //we need to rasterize the value to the stepping amnt long mod = value % stepAmnt; float halfStep = (float)stepAmnt * 0.5; if( mod < halfStep ) rasterValue -= mod; else rasterValue += stepAmnt - mod; printf("RASTER - pctValue is %f - value is %li - step is %li - mod is %li - rasterValue is %li\n", pctValue, value, stepAmnt, mod, rasterValue); } return setVideoSettingCamera(deviceID, Property, rasterValue, Flags, false); } bool videoInput::setVideoSettingCamera(int deviceID, long Property, long lValue, long Flags, bool useDefaultValue){ IAMCameraControl *pIAMCameraControl; if(isDeviceSetup(deviceID)) { HRESULT hr; hr = getDevice(&VDList[deviceID]->pVideoInputFilter, deviceID, VDList[deviceID]->wDeviceName, VDList[deviceID]->nDeviceName); if (verbose) printf("Setting video setting %ld.\n", Property); hr = VDList[deviceID]->pVideoInputFilter->QueryInterface(IID_IAMCameraControl, (void**)&pIAMCameraControl); if (FAILED(hr)) { printf("Error\n"); return false; } else { long CurrVal, Min, Max, SteppingDelta, Default, CapsFlags, AvailableCapsFlags; pIAMCameraControl->GetRange(Property, &Min, &Max, &SteppingDelta, &Default, &AvailableCapsFlags); if (verbose) printf("Range for video setting %ld: Min:%ld Max:%ld SteppingDelta:%ld Default:%ld Flags:%ld\n", Property, Min, Max, SteppingDelta, Default, AvailableCapsFlags); pIAMCameraControl->Get(Property, &CurrVal, &CapsFlags); if (verbose) printf("Current value: %ld Flags %ld (%s)\n", CurrVal, CapsFlags, (CapsFlags == 1 ? "Auto" : (CapsFlags == 2 ? "Manual" : "Unknown"))); if (useDefaultValue) { pIAMCameraControl->Set(Property, Default, CameraControl_Flags_Auto); } else { // Perhaps add a check that lValue and Flags are within the range aquired from GetRange above pIAMCameraControl->Set(Property, lValue, Flags); } pIAMCameraControl->Release(); return true; } } return false; } bool videoInput::getVideoSettingCamera(int deviceID, long Property, long &min, long &max, long &SteppingDelta, long &currentValue, long &flags, long &defaultValue){ if( !isDeviceSetup(deviceID) )return false; HRESULT hr; //bool isSuccessful = false; videoDevice * VD = VDList[deviceID]; hr = getDevice(&VD->pVideoInputFilter, deviceID, VD->wDeviceName, VD->nDeviceName); if (FAILED(hr)){ printf("setVideoSetting - getDevice Error\n"); return false; } IAMCameraControl *pIAMCameraControl = NULL; hr = VD->pVideoInputFilter->QueryInterface(IID_IAMCameraControl, (void**)&pIAMCameraControl); if(FAILED(hr)){ printf("setVideoSetting - QueryInterface Error\n"); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return false; } if (verbose) printf("Setting video setting %ld.\n", Property); pIAMCameraControl->GetRange(Property, &min, &max, &SteppingDelta, &defaultValue, &flags); if (verbose) printf("Range for video setting %ld: Min:%ld Max:%ld SteppingDelta:%ld Default:%ld Flags:%ld\n", Property, min, max, SteppingDelta, defaultValue, flags); pIAMCameraControl->Get(Property, &currentValue, &flags); if(pIAMCameraControl)pIAMCameraControl->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter->Release(); if(VD->pVideoInputFilter)VD->pVideoInputFilter = NULL; return true; } // ---------------------------------------------------------------------- // Shutsdown the device, deletes the object and creates a new object // so it is ready to be setup again // ---------------------------------------------------------------------- void videoInput::stopDevice(int id){ if(id < VI_MAX_CAMERAS) { delete VDList[id]; VDList[id] = new videoDevice(); } } // ---------------------------------------------------------------------- // Restarts the device with the same settings it was using // // ---------------------------------------------------------------------- bool videoInput::restartDevice(int id){ if(isDeviceSetup(id)) { int conn = VDList[id]->storeConn; int tmpW = VDList[id]->width; int tmpH = VDList[id]->height; bool bFormat = VDList[id]->specificFormat; long format = VDList[id]->formatType; int nReconnect = VDList[id]->nFramesForReconnect; bool bReconnect = VDList[id]->autoReconnect; unsigned long avgFrameTime = VDList[id]->requestedFrameTime; stopDevice(id); //set our fps if needed if( avgFrameTime != -1UL){ VDList[id]->requestedFrameTime = avgFrameTime; } if( setupDevice(id, tmpW, tmpH, conn) ){ //reapply the format - ntsc / pal etc if( bFormat ){ setFormat(id, format); } if( bReconnect ){ setAutoReconnectOnFreeze(id, true, nReconnect); } return true; } } return false; } // ---------------------------------------------------------------------- // Shuts down all devices, deletes objects and unitializes com if needed // // ---------------------------------------------------------------------- videoInput::~videoInput(){ for(int i = 0; i < VI_MAX_CAMERAS; i++) { delete VDList[i]; } //Unitialize com comUnInit(); } ////////////////////////////// VIDEO INPUT //////////////////////////////// //////////////////////////// PRIVATE METHODS ////////////////////////////// // ---------------------------------------------------------------------- // We only should init com if it hasn't been done so by our apps thread // Use a static counter to keep track of other times it has been inited // (do we need to worry about multithreaded apps?) // ---------------------------------------------------------------------- bool videoInput::comInit(){ HRESULT hr = 0; //no need for us to start com more than once if(comInitCount == 0 ){ // Initialize the COM library. //CoInitializeEx so videoInput can run in another thread #ifdef VI_COM_MULTI_THREADED hr = CoInitializeEx(NULL,COINIT_MULTITHREADED); #else hr = CoInitialize(NULL); #endif //this is the only case where there might be a problem //if another library has started com as single threaded //and we need it multi-threaded - send warning but don't fail if( hr == RPC_E_CHANGED_MODE){ if(verbose)printf("SETUP - COM already setup - threaded VI might not be possible\n"); } } comInitCount++; return true; } // ---------------------------------------------------------------------- // Same as above but to unitialize com, decreases counter and frees com // if no one else is using it // ---------------------------------------------------------------------- bool videoInput::comUnInit(){ if(comInitCount > 0)comInitCount--; //decrease the count of instances using com if(comInitCount == 0){ CoUninitialize(); //if there are no instances left - uninitialize com return true; } return false; } // ---------------------------------------------------------------------- // This is the size we ask for - we might not get it though :) // // ---------------------------------------------------------------------- void videoInput::setAttemptCaptureSize(int id, int w, int h){ VDList[id]->tryWidth = w; VDList[id]->tryHeight = h; VDList[id]->tryDiffSize = true; } // ---------------------------------------------------------------------- // Set the connection type // (maybe move to private?) // ---------------------------------------------------------------------- void videoInput::setPhyCon(int id, int conn){ switch(conn){ case 0: VDList[id]->connection = PhysConn_Video_Composite; break; case 1: VDList[id]->connection = PhysConn_Video_SVideo; break; case 2: VDList[id]->connection = PhysConn_Video_Tuner; break; case 3: VDList[id]->connection = PhysConn_Video_USB; break; case 4: VDList[id]->connection = PhysConn_Video_1394; break; default: return; //if it is not these types don't set crossbar break; } VDList[id]->storeConn = conn; VDList[id]->useCrossbar = true; } // ---------------------------------------------------------------------- // Check that we are not trying to setup a non-existant device // Then start the graph building! // ---------------------------------------------------------------------- bool videoInput::setup(int deviceNumber){ devicesFound = getDeviceCount(); if(deviceNumber>devicesFound-1) { if(verbose)printf("SETUP: device[%i] not found - you have %i devices available\n", deviceNumber, devicesFound); if(devicesFound>=0) if(verbose)printf("SETUP: this means that the last device you can use is device[%i] \n", devicesFound-1); return false; } if(VDList[deviceNumber]->readyToCapture) { if(verbose)printf("SETUP: can't setup, device %i is currently being used\n",VDList[deviceNumber]->myID); return false; } HRESULT hr = start(deviceNumber, VDList[deviceNumber]); if(hr == S_OK)return true; else return false; } // ---------------------------------------------------------------------- // Does both vertical buffer flipping and bgr to rgb swapping // You have any combination of those. // ---------------------------------------------------------------------- void videoInput::processPixels(unsigned char * src, unsigned char * dst, int width, int height, bool bRGB, bool bFlip){ int widthInBytes = width * 3; int numBytes = widthInBytes * height; if(!bRGB){ //int x = 0; //int y = 0; if(bFlip){ for(int y = 0; y < height; y++){ memcpy(dst + (y * widthInBytes), src + ( (height -y -1) * widthInBytes), widthInBytes); } }else{ memcpy(dst, src, numBytes); } }else{ if(bFlip){ int x = 0; int y = (height - 1) * widthInBytes; src += y; for(int i = 0; i < numBytes; i+=3){ if(x >= width){ x = 0; src -= widthInBytes*2; } *dst = *(src+2); dst++; *dst = *(src+1); dst++; *dst = *src; dst++; src+=3; x++; } } else{ for(int i = 0; i < numBytes; i+=3){ *dst = *(src+2); dst++; *dst = *(src+1); dst++; *dst = *src; dst++; src+=3; } } } } //------------------------------------------------------------------------------------------ void videoInput::getMediaSubtypeAsString(GUID type, char * typeAsString){ char tmpStr[8]; if( type == MEDIASUBTYPE_RGB24) sprintf(tmpStr, "RGB24"); else if(type == MEDIASUBTYPE_RGB32) sprintf(tmpStr, "RGB32"); else if(type == MEDIASUBTYPE_RGB555)sprintf(tmpStr, "RGB555"); else if(type == MEDIASUBTYPE_RGB565)sprintf(tmpStr, "RGB565"); else if(type == MEDIASUBTYPE_YUY2) sprintf(tmpStr, "YUY2"); else if(type == MEDIASUBTYPE_YVYU) sprintf(tmpStr, "YVYU"); else if(type == MEDIASUBTYPE_YUYV) sprintf(tmpStr, "YUYV"); else if(type == MEDIASUBTYPE_IYUV) sprintf(tmpStr, "IYUV"); else if(type == MEDIASUBTYPE_UYVY) sprintf(tmpStr, "UYVY"); else if(type == MEDIASUBTYPE_YV12) sprintf(tmpStr, "YV12"); else if(type == MEDIASUBTYPE_YVU9) sprintf(tmpStr, "YVU9"); else if(type == MEDIASUBTYPE_Y411) sprintf(tmpStr, "Y411"); else if(type == MEDIASUBTYPE_Y41P) sprintf(tmpStr, "Y41P"); else if(type == MEDIASUBTYPE_Y211) sprintf(tmpStr, "Y211"); else if(type == MEDIASUBTYPE_AYUV) sprintf(tmpStr, "AYUV"); else if(type == MEDIASUBTYPE_Y800) sprintf(tmpStr, "Y800"); else if(type == MEDIASUBTYPE_Y8) sprintf(tmpStr, "Y8"); else if(type == MEDIASUBTYPE_GREY) sprintf(tmpStr, "GREY"); else sprintf(tmpStr, "OTHER"); memcpy(typeAsString, tmpStr, sizeof(char)*8); } //------------------------------------------------------------------------------------------- static void findClosestSizeAndSubtype(videoDevice * VD, int widthIn, int heightIn, int &widthOut, int &heightOut, GUID & mediatypeOut){ HRESULT hr; //find perfect match or closest size int nearW = 9999999; int nearH = 9999999; bool foundClosestMatch = true; int iCount = 0; int iSize = 0; hr = VD->streamConf->GetNumberOfCapabilities(&iCount, &iSize); if (iSize == sizeof(VIDEO_STREAM_CONFIG_CAPS)) { //For each format type RGB24 YUV2 etc for (int iFormat = 0; iFormat < iCount; iFormat++) { VIDEO_STREAM_CONFIG_CAPS scc; AM_MEDIA_TYPE *pmtConfig; hr = VD->streamConf->GetStreamCaps(iFormat, &pmtConfig, (BYTE*)&scc); if (SUCCEEDED(hr)){ //his is how many diff sizes are available for the format int stepX = scc.OutputGranularityX; int stepY = scc.OutputGranularityY; int tempW = 999999; int tempH = 999999; //Don't want to get stuck in a loop if(stepX < 1 || stepY < 1) continue; //if(verbose)printf("min is %i %i max is %i %i - res is %i %i \n", scc.MinOutputSize.cx, scc.MinOutputSize.cy, scc.MaxOutputSize.cx, scc.MaxOutputSize.cy, stepX, stepY); //if(verbose)printf("min frame duration is %i max duration is %i\n", scc.MinFrameInterval, scc.MaxFrameInterval); bool exactMatch = false; bool exactMatchX = false; bool exactMatchY = false; for(int x = scc.MinOutputSize.cx; x <= scc.MaxOutputSize.cx; x+= stepX){ //If we find an exact match if( widthIn == x ){ exactMatchX = true; tempW = x; } //Otherwise lets find the closest match based on width else if( abs(widthIn-x) < abs(widthIn-tempW) ){ tempW = x; } } for(int y = scc.MinOutputSize.cy; y <= scc.MaxOutputSize.cy; y+= stepY){ //If we find an exact match if( heightIn == y){ exactMatchY = true; tempH = y; } //Otherwise lets find the closest match based on height else if( abs(heightIn-y) < abs(heightIn-tempH) ){ tempH = y; } } //see if we have an exact match! if(exactMatchX && exactMatchY){ foundClosestMatch = false; exactMatch = true; widthOut = widthIn; heightOut = heightIn; mediatypeOut = pmtConfig->subtype; } //otherwise lets see if this filters closest size is the closest //available. the closest size is determined by the sum difference //of the widths and heights else if( abs(widthIn - tempW) + abs(heightIn - tempH) < abs(widthIn - nearW) + abs(heightIn - nearH) ) { nearW = tempW; nearH = tempH; widthOut = nearW; heightOut = nearH; mediatypeOut = pmtConfig->subtype; } MyDeleteMediaType(pmtConfig); //If we have found an exact match no need to search anymore if(exactMatch)break; } } } } //--------------------------------------------------------------------------------------------------- static bool setSizeAndSubtype(videoDevice * VD, int attemptWidth, int attemptHeight, GUID mediatype){ VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(VD->pAmMediaType->pbFormat); //store current size //int tmpWidth = HEADER(pVih)->biWidth; //int tmpHeight = HEADER(pVih)->biHeight; AM_MEDIA_TYPE * tmpType = NULL; HRESULT hr = VD->streamConf->GetFormat(&tmpType); if(hr != S_OK)return false; //set new size: //width and height HEADER(pVih)->biWidth = attemptWidth; HEADER(pVih)->biHeight = attemptHeight; VD->pAmMediaType->formattype = FORMAT_VideoInfo; VD->pAmMediaType->majortype = MEDIATYPE_Video; VD->pAmMediaType->subtype = mediatype; //buffer size VD->pAmMediaType->lSampleSize = attemptWidth*attemptHeight*3; //set fps if requested if( VD->requestedFrameTime != -1){ pVih->AvgTimePerFrame = VD->requestedFrameTime; } //okay lets try new size hr = VD->streamConf->SetFormat(VD->pAmMediaType); if(hr == S_OK){ if( tmpType != NULL )MyDeleteMediaType(tmpType); return true; }else{ VD->streamConf->SetFormat(tmpType); if( tmpType != NULL )MyDeleteMediaType(tmpType); } return false; } // ---------------------------------------------------------------------- // Where all the work happens! // Attempts to build a graph for the specified device // ---------------------------------------------------------------------- int videoInput::start(int deviceID, videoDevice *VD){ HRESULT hr = 0; VD->myID = deviceID; VD->setupStarted = true; CAPTURE_MODE = PIN_CATEGORY_CAPTURE; //Don't worry - it ends up being preview (which is faster) callbackSetCount = 1; //make sure callback method is not changed after setup called if(verbose)printf("SETUP: Setting up device %i\n",deviceID); // CREATE THE GRAPH BUILDER // // Create the filter graph manager and query for interfaces. hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void **)&VD->pCaptureGraph); if (FAILED(hr)) // FAILED is a macro that tests the return value { if(verbose)printf("ERROR - Could not create the Filter Graph Manager\n"); return hr; } //FITLER GRAPH MANAGER// // Create the Filter Graph Manager. hr = CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER,IID_IGraphBuilder, (void**)&VD->pGraph); if (FAILED(hr)) { if(verbose)printf("ERROR - Could not add the graph builder!\n"); stopDevice(deviceID); return hr; } //SET THE FILTERGRAPH// hr = VD->pCaptureGraph->SetFiltergraph(VD->pGraph); if (FAILED(hr)) { if(verbose)printf("ERROR - Could not set filtergraph\n"); stopDevice(deviceID); return hr; } //MEDIA CONTROL (START/STOPS STREAM)// // Using QueryInterface on the graph builder, // Get the Media Control object. hr = VD->pGraph->QueryInterface(IID_IMediaControl, (void **)&VD->pControl); if (FAILED(hr)) { if(verbose)printf("ERROR - Could not create the Media Control object\n"); stopDevice(deviceID); return hr; } //FIND VIDEO DEVICE AND ADD TO GRAPH// //gets the device specified by the second argument. hr = getDevice(&VD->pVideoInputFilter, deviceID, VD->wDeviceName, VD->nDeviceName); if (SUCCEEDED(hr)){ if(verbose)printf("SETUP: %s\n", VD->nDeviceName); hr = VD->pGraph->AddFilter(VD->pVideoInputFilter, VD->wDeviceName); }else{ if(verbose)printf("ERROR - Could not find specified video device\n"); stopDevice(deviceID); return hr; } //LOOK FOR PREVIEW PIN IF THERE IS NONE THEN WE USE CAPTURE PIN AND THEN SMART TEE TO PREVIEW IAMStreamConfig *streamConfTest = NULL; hr = VD->pCaptureGraph->FindInterface(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, VD->pVideoInputFilter, IID_IAMStreamConfig, (void **)&streamConfTest); if(FAILED(hr)){ if(verbose)printf("SETUP: Couldn't find preview pin using SmartTee\n"); }else{ CAPTURE_MODE = PIN_CATEGORY_PREVIEW; streamConfTest->Release(); streamConfTest = NULL; } //CROSSBAR (SELECT PHYSICAL INPUT TYPE)// //my own function that checks to see if the device can support a crossbar and if so it routes it. //webcams tend not to have a crossbar so this function will also detect a webcams and not apply the crossbar if(VD->useCrossbar) { if(verbose)printf("SETUP: Checking crossbar\n"); routeCrossbar(&VD->pCaptureGraph, &VD->pVideoInputFilter, VD->connection, CAPTURE_MODE); } //we do this because webcams don't have a preview mode hr = VD->pCaptureGraph->FindInterface(&CAPTURE_MODE, &MEDIATYPE_Video, VD->pVideoInputFilter, IID_IAMStreamConfig, (void **)&VD->streamConf); if(FAILED(hr)){ if(verbose)printf("ERROR: Couldn't config the stream!\n"); stopDevice(deviceID); return hr; } //NOW LETS DEAL WITH GETTING THE RIGHT SIZE hr = VD->streamConf->GetFormat(&VD->pAmMediaType); if(FAILED(hr)){ if(verbose)printf("ERROR: Couldn't getFormat for pAmMediaType!\n"); stopDevice(deviceID); return hr; } VIDEOINFOHEADER *pVih = reinterpret_cast<VIDEOINFOHEADER*>(VD->pAmMediaType->pbFormat); int currentWidth = HEADER(pVih)->biWidth; int currentHeight = HEADER(pVih)->biHeight; bool customSize = VD->tryDiffSize; bool foundSize = false; if(customSize){ if(verbose) printf("SETUP: Default Format is set to %i by %i \n", currentWidth, currentHeight); char guidStr[8]; for(int i = 0; i < VI_NUM_TYPES; i++){ getMediaSubtypeAsString(mediaSubtypes[i], guidStr); if(verbose)printf("SETUP: trying format %s @ %i by %i\n", guidStr, VD->tryWidth, VD->tryHeight); if( setSizeAndSubtype(VD, VD->tryWidth, VD->tryHeight, mediaSubtypes[i]) ){ VD->setSize(VD->tryWidth, VD->tryHeight); foundSize = true; break; } } //if we didn't find the requested size - lets try and find the closest matching size if( foundSize == false ){ if( verbose )printf("SETUP: couldn't find requested size - searching for closest matching size\n"); int closestWidth = -1; int closestHeight = -1; GUID newMediaSubtype; findClosestSizeAndSubtype(VD, VD->tryWidth, VD->tryHeight, closestWidth, closestHeight, newMediaSubtype); if( closestWidth != -1 && closestHeight != -1){ getMediaSubtypeAsString(newMediaSubtype, guidStr); if(verbose)printf("SETUP: closest supported size is %s @ %i %i\n", guidStr, closestWidth, closestHeight); if( setSizeAndSubtype(VD, closestWidth, closestHeight, newMediaSubtype) ){ VD->setSize(closestWidth, closestHeight); foundSize = true; } } } } //if we didn't specify a custom size or if we did but couldn't find it lets setup with the default settings if(customSize == false || foundSize == false){ if( VD->requestedFrameTime != -1 ){ pVih->AvgTimePerFrame = VD->requestedFrameTime; hr = VD->streamConf->SetFormat(VD->pAmMediaType); } VD->setSize(currentWidth, currentHeight); } //SAMPLE GRABBER (ALLOWS US TO GRAB THE BUFFER)// // Create the Sample Grabber. hr = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,IID_IBaseFilter, (void**)&VD->pGrabberF); if (FAILED(hr)){ if(verbose)printf("Could not Create Sample Grabber - CoCreateInstance()\n"); stopDevice(deviceID); return hr; } hr = VD->pGraph->AddFilter(VD->pGrabberF, L"Sample Grabber"); if (FAILED(hr)){ if(verbose)printf("Could not add Sample Grabber - AddFilter()\n"); stopDevice(deviceID); return hr; } hr = VD->pGrabberF->QueryInterface(IID_ISampleGrabber, (void**)&VD->pGrabber); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not query SampleGrabber\n"); stopDevice(deviceID); return hr; } //Set Params - One Shot should be false unless you want to capture just one buffer hr = VD->pGrabber->SetOneShot(FALSE); if(bCallback){ hr = VD->pGrabber->SetBufferSamples(FALSE); }else{ hr = VD->pGrabber->SetBufferSamples(TRUE); } if(bCallback){ //Tell the grabber to use our callback function - 0 is for SampleCB and 1 for BufferCB //We use SampleCB hr = VD->pGrabber->SetCallback(VD->sgCallback, 0); if (FAILED(hr)){ if(verbose)printf("ERROR: problem setting callback\n"); stopDevice(deviceID); return hr; }else{ if(verbose)printf("SETUP: Capture callback set\n"); } } //MEDIA CONVERSION //Get video properties from the stream's mediatype and apply to the grabber (otherwise we don't get an RGB image) //zero the media type - lets try this :) - maybe this works? AM_MEDIA_TYPE mt; ZeroMemory(&mt,sizeof(AM_MEDIA_TYPE)); mt.majortype = MEDIATYPE_Video; mt.subtype = MEDIASUBTYPE_RGB24; mt.formattype = FORMAT_VideoInfo; //VD->pAmMediaType->subtype = VD->videoType; hr = VD->pGrabber->SetMediaType(&mt); //lets try freeing our stream conf here too //this will fail if the device is already running if(VD->streamConf){ VD->streamConf->Release(); VD->streamConf = NULL; }else{ if(verbose)printf("ERROR: connecting device - prehaps it is already being used?\n"); stopDevice(deviceID); return S_FALSE; } //NULL RENDERER// //used to give the video stream somewhere to go to. hr = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)(&VD->pDestFilter)); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not create filter - NullRenderer\n"); stopDevice(deviceID); return hr; } hr = VD->pGraph->AddFilter(VD->pDestFilter, L"NullRenderer"); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not add filter - NullRenderer\n"); stopDevice(deviceID); return hr; } //RENDER STREAM// //This is where the stream gets put together. hr = VD->pCaptureGraph->RenderStream(&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video, VD->pVideoInputFilter, VD->pGrabberF, VD->pDestFilter); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not connect pins - RenderStream()\n"); stopDevice(deviceID); return hr; } //EXP - lets try setting the sync source to null - and make it run as fast as possible { IMediaFilter *pMediaFilter = 0; hr = VD->pGraph->QueryInterface(IID_IMediaFilter, (void**)&pMediaFilter); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not get IID_IMediaFilter interface\n"); }else{ pMediaFilter->SetSyncSource(NULL); pMediaFilter->Release(); } } //LETS RUN THE STREAM! hr = VD->pControl->Run(); if (FAILED(hr)){ if(verbose)printf("ERROR: Could not start graph\n"); stopDevice(deviceID); return hr; } //MAKE SURE THE DEVICE IS SENDING VIDEO BEFORE WE FINISH if(!bCallback){ long bufferSize = VD->videoSize; while( hr != S_OK){ hr = VD->pGrabber->GetCurrentBuffer(&bufferSize, (long *)VD->pBuffer); Sleep(10); } } if(verbose)printf("SETUP: Device is setup and ready to capture.\n\n"); VD->readyToCapture = true; //Release filters - seen someone else do this //looks like it solved the freezes //if we release this then we don't have access to the settings //we release our video input filter but then reconnect with it //each time we need to use it VD->pVideoInputFilter->Release(); VD->pVideoInputFilter = NULL; VD->pGrabberF->Release(); VD->pGrabberF = NULL; VD->pDestFilter->Release(); VD->pDestFilter = NULL; return S_OK; } // ---------------------------------------------------------------------- // Returns number of good devices // // ---------------------------------------------------------------------- int videoInput::getDeviceCount(){ ICreateDevEnum *pDevEnum = NULL; IEnumMoniker *pEnum = NULL; int deviceCounter = 0; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>(&pDevEnum)); if (SUCCEEDED(hr)) { // Create an enumerator for the video capture category. hr = pDevEnum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory, &pEnum, 0); if(hr == S_OK){ IMoniker *pMoniker = NULL; while (pEnum->Next(1, &pMoniker, NULL) == S_OK){ IPropertyBag *pPropBag; hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)(&pPropBag)); if (FAILED(hr)){ pMoniker->Release(); continue; // Skip this one, maybe the next one will work. } pPropBag->Release(); pPropBag = NULL; pMoniker->Release(); pMoniker = NULL; deviceCounter++; } pEnum->Release(); pEnum = NULL; } pDevEnum->Release(); pDevEnum = NULL; } return deviceCounter; } // ---------------------------------------------------------------------- // Do we need this? // // Enumerate all of the video input devices // Return the filter with a matching friendly name // ---------------------------------------------------------------------- HRESULT videoInput::getDevice(IBaseFilter** gottaFilter, int deviceId, WCHAR * wDeviceName, char * nDeviceName){ BOOL done = false; int deviceCounter = 0; // Create the System Device Enumerator. ICreateDevEnum *pSysDevEnum = NULL; HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void **)&pSysDevEnum); if (FAILED(hr)) { return hr; } // Obtain a class enumerator for the video input category. IEnumMoniker *pEnumCat = NULL; hr = pSysDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnumCat, 0); if (hr == S_OK) { // Enumerate the monikers. IMoniker *pMoniker = NULL; ULONG cFetched; while ((pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK) && (!done)) { if(deviceCounter == deviceId) { // Bind the first moniker to an object IPropertyBag *pPropBag; hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag); if (SUCCEEDED(hr)) { // To retrieve the filter's friendly name, do the following: VARIANT varName; VariantInit(&varName); hr = pPropBag->Read(L"FriendlyName", &varName, 0); if (SUCCEEDED(hr)) { //copy the name to nDeviceName & wDeviceName int count = 0; while( varName.bstrVal[count] != 0x00 ) { wDeviceName[count] = varName.bstrVal[count]; nDeviceName[count] = (char)varName.bstrVal[count]; count++; } // We found it, so send it back to the caller hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)gottaFilter); done = true; } VariantClear(&varName); pPropBag->Release(); pPropBag = NULL; pMoniker->Release(); pMoniker = NULL; } } deviceCounter++; } pEnumCat->Release(); pEnumCat = NULL; } pSysDevEnum->Release(); pSysDevEnum = NULL; if (done) { return hr; // found it, return native error } else { return VFW_E_NOT_FOUND; // didn't find it error } } // ---------------------------------------------------------------------- // Show the property pages for a filter // This is stolen from the DX9 SDK // ---------------------------------------------------------------------- HRESULT videoInput::ShowFilterPropertyPages(IBaseFilter *pFilter){ ISpecifyPropertyPages *pProp; HRESULT hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pProp); if (SUCCEEDED(hr)) { // Get the filter's name and IUnknown pointer. FILTER_INFO FilterInfo; hr = pFilter->QueryFilterInfo(&FilterInfo); IUnknown *pFilterUnk; pFilter->QueryInterface(IID_IUnknown, (void **)&pFilterUnk); // Show the page. CAUUID caGUID; pProp->GetPages(&caGUID); pProp->Release(); OleCreatePropertyFrame( NULL, // Parent window 0, 0, // Reserved FilterInfo.achName, // Caption for the dialog box 1, // Number of objects (just the filter) &pFilterUnk, // Array of object pointers. caGUID.cElems, // Number of property pages caGUID.pElems, // Array of property page CLSIDs 0, // Locale identifier 0, NULL // Reserved ); // Clean up. if(pFilterUnk)pFilterUnk->Release(); if(FilterInfo.pGraph)FilterInfo.pGraph->Release(); CoTaskMemFree(caGUID.pElems); } return hr; } // ---------------------------------------------------------------------- // This code was also brazenly stolen from the DX9 SDK // Pass it a file name in wszPath, and it will save the filter graph to that file. // ---------------------------------------------------------------------- HRESULT videoInput::SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath) { const WCHAR wszStreamName[] = L"ActiveMovieGraph"; HRESULT hr; IStorage *pStorage = NULL; // First, create a document file which will hold the GRF file hr = StgCreateDocfile( wszPath, STGM_CREATE | STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pStorage); if(FAILED(hr)) { return hr; } // Next, create a stream to store. IStream *pStream; hr = pStorage->CreateStream( wszStreamName, STGM_WRITE | STGM_CREATE | STGM_SHARE_EXCLUSIVE, 0, 0, &pStream); if (FAILED(hr)) { pStorage->Release(); return hr; } // The IPersistStream converts a stream into a persistent object. IPersistStream *pPersist = NULL; pGraph->QueryInterface(IID_IPersistStream, reinterpret_cast<void**>(&pPersist)); hr = pPersist->Save(pStream, TRUE); pStream->Release(); pPersist->Release(); if (SUCCEEDED(hr)) { hr = pStorage->Commit(STGC_DEFAULT); } pStorage->Release(); return hr; } // ---------------------------------------------------------------------- // For changing the input types // // ---------------------------------------------------------------------- HRESULT videoInput::routeCrossbar(ICaptureGraphBuilder2 **ppBuild, IBaseFilter **pVidInFilter, int conType, GUID captureMode){ //create local ICaptureGraphBuilder2 ICaptureGraphBuilder2 *pBuild = NULL; pBuild = *ppBuild; //create local IBaseFilter IBaseFilter *pVidFilter = NULL; pVidFilter = * pVidInFilter; // Search upstream for a crossbar. IAMCrossbar *pXBar1 = NULL; HRESULT hr = pBuild->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pVidFilter, IID_IAMCrossbar, (void**)&pXBar1); if (SUCCEEDED(hr)) { bool foundDevice = false; if(verbose)printf("SETUP: You are not a webcam! Setting Crossbar\n"); pXBar1->Release(); IAMCrossbar *Crossbar; hr = pBuild->FindInterface(&captureMode, &MEDIATYPE_Interleaved, pVidFilter, IID_IAMCrossbar, (void **)&Crossbar); if(hr != NOERROR){ hr = pBuild->FindInterface(&captureMode, &MEDIATYPE_Video, pVidFilter, IID_IAMCrossbar, (void **)&Crossbar); } LONG lInpin, lOutpin; hr = Crossbar->get_PinCounts(&lOutpin , &lInpin); BOOL IPin=TRUE; LONG pIndex=0 , pRIndex=0 , pType=0; while( pIndex < lInpin) { hr = Crossbar->get_CrossbarPinInfo( IPin , pIndex , &pRIndex , &pType); if( pType == conType){ if(verbose)printf("SETUP: Found Physical Interface"); switch(conType){ case PhysConn_Video_Composite: if(verbose)printf(" - Composite\n"); break; case PhysConn_Video_SVideo: if(verbose)printf(" - S-Video\n"); break; case PhysConn_Video_Tuner: if(verbose)printf(" - Tuner\n"); break; case PhysConn_Video_USB: if(verbose)printf(" - USB\n"); break; case PhysConn_Video_1394: if(verbose)printf(" - Firewire\n"); break; } foundDevice = true; break; } pIndex++; } if(foundDevice){ BOOL OPin=FALSE; LONG pOIndex=0 , pORIndex=0 , pOType=0; while( pOIndex < lOutpin) { hr = Crossbar->get_CrossbarPinInfo( OPin , pOIndex , &pORIndex , &pOType); if( pOType == PhysConn_Video_VideoDecoder) break; } Crossbar->Route(pOIndex,pIndex); }else{ if(verbose)printf("SETUP: Didn't find specified Physical Connection type. Using Defualt. \n"); } //we only free the crossbar when we close or restart the device //we were getting a crash otherwise //if(Crossbar)Crossbar->Release(); //if(Crossbar)Crossbar = NULL; if(pXBar1)pXBar1->Release(); if(pXBar1)pXBar1 = NULL; }else{ if(verbose)printf("SETUP: You are a webcam or snazzy firewire cam! No Crossbar needed\n"); return hr; } return hr; }
[ [ [ 1, 277 ], [ 281, 295 ], [ 297, 344 ], [ 346, 1030 ], [ 1032, 1094 ], [ 1096, 1106 ], [ 1108, 1181 ], [ 1183, 1229 ], [ 1231, 1301 ], [ 1303, 1344 ], [ 1346, 1473 ], [ 1476, 1659 ], [ 1662, 1703 ], [ 1705, 2335 ] ], [ [ 278, 280 ], [ 296, 296 ], [ 345, 345 ], [ 1031, 1031 ], [ 1095, 1095 ], [ 1107, 1107 ], [ 1182, 1182 ], [ 1230, 1230 ], [ 1302, 1302 ], [ 1345, 1345 ], [ 1474, 1475 ], [ 1660, 1661 ], [ 1704, 1704 ] ] ]
20aa778f66c1790be0f6d03ae9254afd57543dfb
15aa527215bba5ceee2211f0a4ad24b56b08f7e0
/onshoku/src/Sequencer.cpp
cb6eb562bd808d06d6633c04586b76ff5d2f26fd
[]
no_license
jmoraguiard/onshoku
5a7a4b5ec10136e9d00563ed3ed8dc998d876771
31d74b2ec5b95082db8760da627ab3584dbdafb4
refs/heads/master
2016-09-06T15:17:54.133475
2010-03-07T00:58:06
2010-03-07T00:58:06
32,319,393
0
0
null
null
null
null
UTF-8
C++
false
false
216
cpp
#include "Sequencer.h" Sequencer::Sequencer() { oldEllapsedTime = ofGetElapsedTimeMillis(); tempoDuration = 1000; tempoCounter = 0; } void Sequencer::update() { } void Sequencer::draw() { }
[ "jmoraguiard@37640e06-2978-11df-b3a4-f9036a7335b3" ]
[ [ [ 1, 18 ] ] ]
17715090612159393788de35d0fd93ed4e8c113b
d2996420f8c3a6bbeef63a311dd6adc4acc40436
/src/client/hud/OgreConsoleForGorilla.cpp
ea916f9dc51a8c5fd6dd3f50d9d1badd16695d09
[]
no_license
aruwen/graviator
4d2e06e475492102fbf5d65754be33af641c0d6c
9a881db9bb0f0de2e38591478429626ab8030e1d
refs/heads/master
2021-01-19T00:13:10.843905
2011-03-13T13:15:25
2011-03-13T13:15:25
32,136,578
0
0
null
null
null
null
UTF-8
C++
false
false
5,944
cpp
/* Description: This is a port of the OgreConsole code presented by PixL in the Ogre Forums then later added to the Ogre Wiki. This is a straight port replacing all the Overlay code with Gorilla code, some changes have been added but they are minor and do not add to the actual functionality of the class. */ #include "OgreConsoleForGorilla.h" template<> OgreConsole* Ogre::Singleton<OgreConsole>::ms_Singleton=0; #define CONSOLE_FONT_INDEX 14 #define CONSOLE_LINE_LENGTH 85 #define CONSOLE_LINE_COUNT 15 static const char legalchars[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890+!\"'#%&/()=?[]\\*-_.:,; "; OgreConsole::OgreConsole() : mScreen(0), mStartline(0), mUpdateConsole(false), mUpdatePrompt(false), mIsInitialised(false), mIsVisible(true) { } OgreConsole::~OgreConsole() { if (mIsInitialised) shutdown(); } void OgreConsole::init(Gorilla::Screen* screen) { if(mIsInitialised) shutdown(); Ogre::Root::getSingletonPtr()->addFrameListener(this); Ogre::LogManager::getSingleton().getDefaultLog()->addListener(this); // Create gorilla things here. mScreen = screen; mLayer = mScreen->createLayer(15); mGlyphData = mLayer->_getGlyphData(CONSOLE_FONT_INDEX); // Font.CONSOLE_FONT_INDEX mConsoleText = mLayer->createMarkupText(CONSOLE_FONT_INDEX, 10,10, Ogre::StringUtil::BLANK); mConsoleText->width(mScreen->getWidth() - 10); mPromptText = mLayer->createCaption(CONSOLE_FONT_INDEX, 10,10, "> _"); mDecoration = mLayer->createRectangle(8,8, mScreen->getWidth() - 16, mGlyphData->mLineHeight ); mDecoration->background_gradient(Gorilla::Gradient_NorthSouth, Gorilla::rgb(128,128,128,128), Gorilla::rgb(64,64,64,128)); mDecoration->border(2, Gorilla::rgb(128,128,128,128)); mIsInitialised = true; print("%5GraviatorConsole%0 Activated. Press F1 to show/hide.%R"); } void OgreConsole::shutdown() { if(!mIsInitialised) return; mIsInitialised = false; Ogre::Root::getSingletonPtr()->removeFrameListener(this); Ogre::LogManager::getSingleton().getDefaultLog()->removeListener(this); mScreen->destroy(mLayer); } void OgreConsole::onKeyPressed(const OIS::KeyEvent &arg) { if(!mIsVisible) return; if (arg.key == OIS::KC_RETURN || arg.key == OIS::KC_NUMPADENTER) { print("%3> " + prompt + "%R"); //split the parameter list Ogre::StringVector params = Ogre::StringUtil::split(prompt, " "); if (params.size()) { std::map<Ogre::String, OgreConsoleFunctionPtr>::iterator i; for(i=commands.begin();i!=commands.end();i++){ if((*i).first==params[0]){ if((*i).second) (*i).second(params); break; } } prompt.clear(); mUpdateConsole = true; mUpdatePrompt = true; } } else if (arg.key == OIS::KC_BACK) { if (prompt.size()) { prompt.erase(prompt.end() - 1); //=prompt.substr(0,prompt.length()-1); mUpdatePrompt = true; } } else if (arg.key == OIS::KC_PGUP) { if(mStartline>0) mStartline--; mUpdateConsole = true; } else if (arg.key == OIS::KC_PGDOWN) { if(mStartline<lines.size()) mStartline++; mUpdateConsole = true; } else { for(int c=0;c<sizeof(legalchars);c++){ if(legalchars[c]==arg.text){ prompt+=arg.text; break; } } mUpdatePrompt = true; } } bool OgreConsole::frameStarted(const Ogre::FrameEvent &evt) { if(mUpdateConsole) updateConsole(); if (mUpdatePrompt) updatePrompt(); return true; } void OgreConsole::updateConsole() { mUpdateConsole = false; std::stringstream text; std::list<Ogre::String>::iterator i,start,end; //make sure is in range if(mStartline>lines.size()) mStartline=lines.size(); int lcount=0; start=lines.begin(); for(int c=0;c<mStartline;c++) start++; end=start; for(int c=0;c<CONSOLE_LINE_COUNT;c++){ if(end==lines.end()) break; end++; } for(i=start;i!=end;i++) { lcount++; text << (*i) << "\n"; } mConsoleText->text(text.str()); // Move prompt downwards. mPromptText->top(10 + (lcount * mGlyphData->mLineHeight)); // Change background height so it covers the text and prompt mDecoration->height(((lcount+1) * mGlyphData->mLineHeight) + 4); mConsoleText->width(mScreen->getWidth() - 20); mDecoration->width(mScreen->getWidth() - 16); mPromptText->width(mScreen->getWidth() - 20); } void OgreConsole::updatePrompt() { mUpdatePrompt = false; std::stringstream text; text << "> " << prompt << "_"; mPromptText->text(text.str()); } void OgreConsole::print(const Ogre::String &text) { //subdivide it into lines const char *str=text.c_str(); int start=0,count=0; int len=text.length(); Ogre::String line; for(int c=0;c<len;c++){ if(str[c]=='\n'||line.length()>=CONSOLE_LINE_LENGTH){ lines.push_back(line); line=""; } if(str[c]!='\n') line+=str[c]; } if(line.length()) lines.push_back(line); if(lines.size()>CONSOLE_LINE_COUNT) mStartline=lines.size()-CONSOLE_LINE_COUNT; else mStartline=0; mUpdateConsole=true; } bool OgreConsole::frameEnded(const Ogre::FrameEvent &evt) { return true; } void OgreConsole::setVisible(bool isVisible) { mIsVisible = isVisible; mLayer->setVisible(mIsVisible); } void OgreConsole::addCommand(const Ogre::String &command, OgreConsoleFunctionPtr func) { commands[command]=func; } void OgreConsole::removeCommand(const Ogre::String &command) { commands.erase(commands.find(command)); } void OgreConsole::messageLogged( const Ogre::String& message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String &logName ) { print(message); }
[ "[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867" ]
[ [ [ 1, 249 ] ] ]
32492e0441468484729dbce84e380bda0de6a0af
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/Limn/LimnDW/LimnDW/TrompCurve.h
21cb97b2731c7c0bc5a542ba63a00ffdedd45013
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __TROMPCURVE_H #define __TROMPCURVE_H //--------------------------------------------------------------------------- class CTrompCurve : public MBaseMethod { public: CTrompCurve(MUnitDefBase * pUnitDef, TaggedObject * pNd); virtual void Init(); virtual void BuildDataFields(); virtual bool ExchangeDataFields(); virtual void EvalProducts(); virtual bool GetModelAction(CMdlActionArray & Acts); virtual bool SetModelAction(CMdlAction & Act); virtual bool GetModelGraphic(CMdlGraphicArray & Grfs); virtual bool OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf); protected: C_ModelParameters_DiamondWizard_TrompCurve m_DWParms; bool m_LBtnDn; bool m_RBtnDn; CPoint m_MousePt; }; #endif
[ [ [ 1, 34 ] ] ]
a69bae28cf8297bd9bcd81bbcd0b7b75e7ddff39
3c4f5bd6d7ac3878c181fb05ab41c1d755ddf343
/XRTFFormat.cpp
c0e57f151f9df813d5960e80aca64e4a779972e3
[]
no_license
imcooder/public
1078df18c1459e67afd1200346dd971ea3b71933
be947923c6e2fbd9c993a41115ace3e32dad74bf
refs/heads/master
2021-05-28T08:43:00.027020
2010-07-24T07:39:51
2010-07-24T07:39:51
32,301,120
2
1
null
null
null
null
GB18030
C++
false
false
7,792
cpp
/******************************************************************** Copyright (c) 2002-2003 汉王科技有限公司. 版权所有. 文件名称: XRTFFormat.cpp 文件内容: 制作简单RTF格式 版本历史: 1.0 作者: xuejuntao [email protected] 2008/06/31 *********************************************************************/ #include "StdAfx.h" #include "XRtfFormat.h" #include <HWXString.h> #include <XStrHelper.h> #include <GlobalEx.h> // // GLOBAL STREAM MANIPULATORS CRTFBuilder& Write(CRTFBuilder& r, CRichEditCtrl& c) throw () { r.Write(c); return r ; } CRTFBuilder& Size(CRTFBuilder&r, const LONG& n) throw () { r.Size(n); return r ; } CRTFBuilder& doBold(CRTFBuilder& r, const BOOL& b) { r.Bold(b); return r ; } CRTFBuilder& Strike(CRTFBuilder& r, const bool& b) { r.Strike(b); return r ; } CRTFBuilder& Italic(CRTFBuilder& r, const bool& b) { r.Italic(b); return r ; } CRTFBuilder& Underline(CRTFBuilder& r, const bool& b) { r.Underline(b); return r ; } CRTFBuilder& Font(CRTFBuilder& r, const LONG& n) { CString strFont; strFont.Format(TEXT("%d"), n); r.Font(strFont); return r ; } CRTFBuilder& Color( CRTFBuilder&r,const LONG& n) { r.Color((COLORREF)n); return r ; } CRTFBuilder& BackColor(CRTFBuilder&r,const LONG& n) { r.BackColor((COLORREF)n); return r ; } CRTFBuilder& AddColor(CRTFBuilder& r,const LONG& n) { r.AddColor((COLORREF)n); return r ; } CRTFBuilder& Font(CRTFBuilder& r, const CString& s) { r.Font(s); return r ; } CRTFBuilder& AddFont( CRTFBuilder& r, const CString& s) { r.AddFont(s); return r ; } CControlManip Write(CRichEditCtrl& c) throw () { return CControlManip(&Write, c); } CLONGManip Size(const LONG& n) throw() { return CLONGManip(&Size, n); } CLONGManip Font(const LONG& n) throw() { return CLONGManip(&Font, n); } CLONGManip Color(const LONG& n) throw() { return CLONGManip(&Color, n); } CLONGManip BackColor(const LONG& n) throw() { return CLONGManip(&BackColor, n); } CLONGManip AddColor(const LONG &n) throw() { return CLONGManip(&AddColor, n); } CStringManip Font(LPCTSTR s) throw() { return CStringManip(&Font, s); } CStringManip AddFont(LPCTSTR s) throw() { return CStringManip(&AddFont, s); } CBOOLManip Bold(const bool& b) throw() { return CBOOLManip((RTFSM_BOOLPFUNC)&doBold, b); } CBOOLManip Strike(const bool& b) throw() { return CBOOLManip( &Strike, b); } CBOOLManip Italic(const bool& b) throw() { return CBOOLManip(&Italic, b); } CBOOLManip Underline(const bool& b) throw() { return CBOOLManip(&Underline, b); } CRTFBuilder& operator << ( CRTFBuilder& b, RTFSM_PFUNC f) { return f(b); } CRTFBuilder& operator << ( CRTFBuilder& b, CManip& f) { return f.Run(b); } //CRTFBuilder& //operator << ( CRTFBuilder& b, // CControlManip& f) //{ // return f.Run(b); //} CRTFBuilder& Normal(CRTFBuilder& b) { b.Normal(); return b ; } CRTFBuilder& Black(CRTFBuilder& b) { b.Black(); return b ; } CRTFBuilder& Push(CRTFBuilder& b) { b.Push(); return b ; } CRTFBuilder& Pull(CRTFBuilder& b) { b.Pull(); return b ; } CRTFBuilder& Red(CRTFBuilder& b) { b.Red(); return b ; } CRTFBuilder& Green(CRTFBuilder& b) { b.Green(); return b ; } CRTFBuilder& Blue(CRTFBuilder& b) { b.Blue(); return b ; } CRTFBuilder& Bold(CRTFBuilder& b) { b.Bold(); return b ; } CRTFBuilder& Strike(CRTFBuilder& b) { b.Strike(); return b ; } CRTFBuilder& Italic(CRTFBuilder& b) { b.Italic(); return b ; } CRTFBuilder& Underline(CRTFBuilder& b) { b.Underline(); return b ; } CRTFBuilder::CRTFBuilder() { m_fontList.Add("Arial"); m_colorList.Add(RGB(0,0,0) ); m_colorList.Add(RGB(255,0,0) ); m_colorList.Add(RGB(0,255,0) ); m_colorList.Add(RGB(0,0,255) ); Size(35); } CRTFBuilder::~CRTFBuilder() { } void CRTFBuilder::Push() { m_attrStack.push(m_attr); } void CRTFBuilder::Pull() { m_attr = m_attrStack.top(); m_attrStack.pop(); } void CRTFBuilder::Color(const COLORREF& c) { LONG n (m_colorList.Find(c)); m_attr.m_nColorFground= n < 0 ? m_colorList.Add(c) : n ; } void CRTFBuilder::BackColor(const COLORREF& c) { LONG n (m_colorList.Find(c)); m_attr.m_nColorBground= n < 0 ? m_colorList.Add(c) : n ; } void CRTFBuilder::Black() { m_attr.m_nColorFground = 0 ; } void CRTFBuilder::Red() { m_attr.m_nColorFground = 1 ; } void CRTFBuilder::Green() { m_attr.m_nColorFground = 2 ; } void CRTFBuilder::Blue() { m_attr.m_nColorFground = 3 ; } void CRTFBuilder::Size(const LONG& n) { m_attr.m_nFontSize = n ; } void CRTFBuilder::Font(const CString& strFont) { int nCount = 0 ; for (list<CString>::iterator i = m_fontList.begin(); i != m_fontList.end(); i++, nCount++) { if ((*i) == strFont) { m_attr.m_nFontNumber = nCount ; return ; } } //not there, lets Add it m_fontList.Add(strFont); m_attr.m_nFontNumber = nCount ; } void CRTFBuilder::Bold(const BOOL& b) { m_attr.m_bsBold = b ; } void CRTFBuilder::Strike(const BOOL& b) { m_attr.m_bsStrike = b ; } void CRTFBuilder::Italic(const BOOL& b) { m_attr.m_bsItalic = b ; } void CRTFBuilder::Underline(const BOOL& b) { m_attr.m_bsUnderline = b ; } void CRTFBuilder::Normal() { Bold(false); Italic(false); Underline(false); Strike(false); } /* static DWORD CALLBACK EditStreamCallBack( DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb) { CString *pstr = (CString *)dwCookie; if(LONG(pstr->GetLength() * sizeof(TCHAR)) < cb) { TRACE(TEXT("Len = %d\n"), pstr->GetLength()); *pcb = pstr->GetLength() * sizeof(TCHAR); memcpy(pbBuff, (LPCTSTR)*pstr, *pcb); pstr->Empty(); } else { *pcb = cb; memcpy( pbBuff, (LPCTSTR)*pstr, *pcb); *pstr = pstr->Right(pstr->GetLength() - (cb / sizeof(TCHAR))); } return 0; }*/ static DWORD CALLBACK EditStreamCallBack( DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb) { CXStringA *pstr = (CXStringA*)dwCookie; if(pstr->StrLen() < cb) { *pcb = pstr->StrLen(); memcpy(pbBuff, (LPCSTR)*pstr, *pcb); pstr->Clear(); } else { *pcb = cb; memcpy( pbBuff, (LPCSTR)*pstr, *pcb); *pstr = pstr->Right(pstr->StrLen() - cb); } return 0; } void CRTFBuilder::Write(CRichEditCtrl& c) { m_string += TEXT('}'); LPCSTR strBuffer = TCharToChar(m_string); CXStringA strMbcs = strBuffer; if (strBuffer) { Mem_FreeMemory((void **)&strBuffer); } EDITSTREAM es = {(DWORD)&strMbcs, 0, EditStreamCallBack }; c.StreamIn(SF_RTF | SFF_SELECTION, es); m_string.Empty(); } CRTFBuilder& CRTFBuilder::operator+=(LPCTSTR p) { CString s(p) , s2 ; for (int i = 0 ; i < s.GetLength(); i ++) { if (s[i]==TEXT('\n')) { s2 += (CString)TEXT("\r\n") += TEXT("\\par ");//\\par " ; } else { s2 += s[i]; } } m_string += (CString) TEXT("{\\rtf1\\ansi\\ansicpg936\\uc2\\deff0\\deftab720") += (CString)m_fontList += (CString)m_colorList += (CString)m_attr += s2; return *this ; } CRTFBuilder&CRTFBuilder::operator << (LPCTSTR p) { *this+=p ; return *this ; } CRTFBuilder&CRTFBuilder::operator << (int n) { CString s ; s.Format(TEXT("%d"), n); *this += (LPCTSTR)s ; return *this ; } CRTFBuilder&CRTFBuilder::operator >> (CRichEditCtrl& e) { Write(e); return *this ; }
[ "jtxuee@716a2f10-c84c-11dd-bf7c-81814f527a11" ]
[ [ [ 1, 442 ] ] ]
f83bae79b3e0a303992baf7c0e27669a440e9bfd
741b36f4ddf392c4459d777930bc55b966c2111a
/incubator/happylib/HappyLib/HLMatrix4x4.h
ac9a956bf57f1c15b349b93fc41c4f18b319c440
[]
no_license
BackupTheBerlios/lwpp-svn
d2e905641f60a7c9ca296d29169c70762f5a9281
fd6f80cbba14209d4ca639f291b1a28a0ed5404d
refs/heads/master
2021-01-17T17:01:31.802187
2005-10-16T22:12:52
2005-10-16T22:12:52
40,805,554
0
0
null
null
null
null
UTF-8
C++
false
false
19,223
h
#ifndef _HLMATRIX4X4_H #define _HLMATRIX4X4_H // // This file contains the Matrix4X4T class, which is a 4x4 matrix type. // // MATRIX CONVENTIONS: // VectorT and PointT are conidered column vectors, i.e. a 1x4 Matrix (1x3 + implicit w). // The w component of PointT is implicitly 1. // The w component of VectorT is implicitly 0. // Matrix4X4T is row-major, i.e. [[xx xy xz xw] [yx yy yz yw] [zx zy zz zw] [wx wy wz ww]]. // Note that a 3x3 Matrix is implicitly [[xx xy xz 0] [yx yy yz 0] [zx zy zz 0] [0 0 0 1]]. // Thus to transform a point by a matrix we use newPoint = Mat * oldPoint. #ifndef _HLPOINT_H #include "HLPoint.h" #endif #ifndef _HLCOLOR_H #include "HLColor.h" #endif #include <float.h> // [FIXME] for _finite enum MatCell4{X4X,X4Y,X4Z,X4W, Y4X,Y4Y,Y4Z,Y4W, Z4X,Z4Y,Z4Z,Z4W, W4X,W4Y,W4Z,W4W}; template <class Obj> class Matrix4X4T { public: union { Obj _mat[16]; Obj _mtx[4][4]; }; enum Axis{X,Y,Z,W}; Matrix4X4T() {} Matrix4X4T(Obj const * m) { for (int i = 0; i < 16; i ++) _mat[i] = m[i]; } Matrix4X4T(double, double, double, double, double, double, double, double, double, double, double, double, double, double, double, double); Matrix4X4T(VectorT<Obj> const & vx, VectorT<Obj> const & vy, VectorT<Obj> const & vz) { // create a transformation matrix from Right, Up, Forward _mat[X4X] = vx[X]; _mat[Y4X] = vx[Y]; _mat[Z4X] = vx[Z]; _mat[W4X] = 0.0; _mat[X4Y] = vy[X]; _mat[Y4Y] = vy[Y]; _mat[Z4Y] = vy[Z]; _mat[W4Y] = 0.0; _mat[X4Z] = vz[X]; _mat[Y4Z] = vz[Y]; _mat[Z4Z] = vz[Z]; _mat[W4Z] = 0.0; _mat[X4W] = 0.0; _mat[Y4W] = 0.0; _mat[Z4W] = 0.0; _mat[W4W] = 1.0; } Matrix4X4T(VectorT<Obj> const & vx, VectorT<Obj> const & vy, VectorT<Obj> const & vz, PointT<Obj> const & pos) { // create a transformation matrix from Right, Up, Forward, Position _mat[X4X] = vx[X]; _mat[Y4X] = vx[Y]; _mat[Z4X] = vx[Z]; _mat[W4X] = 0.0; _mat[X4Y] = vy[X]; _mat[Y4Y] = vy[Y]; _mat[Z4Y] = vy[Z]; _mat[W4Y] = 0.0; _mat[X4Z] = vz[X]; _mat[Y4Z] = vz[Y]; _mat[Z4Z] = vz[Z]; _mat[W4Z] = 0.0; _mat[X4W] = pos[X]; _mat[Y4W] = pos[Y]; _mat[Z4W] = pos[Z]; _mat[W4W] = 1.0; } template<class Obj2> Matrix4X4T(Matrix4X4T<Obj2> const & m) { for (int i = 0; i < 16; i ++) _mat[i] = (Obj)m._mat[i]; } template<class Obj2> Matrix4X4T & operator = (Matrix4X4T<Obj2> const & m) { for (int i = 0; i < 16; i ++) _mat[i] = (Obj)m._mat[i]; return *this; } void set(Obj const * m) { for (int i = 0; i < 16; i ++) _mat[i] = m[i]; } void get(Obj * m) const { for (int i = 0; i < 16; i ++) m[i] = _mat[i]; } template <class Obj2> Obj2 wTrans(PointT<Obj2> const & src, PointT<Obj2> & dest) const { // wTrans performs Point = Mat * Point, but returns w instead of dividing through by w. dest[X] = Obj2(src[X]*_mat[X4X] + src[Y]*_mat[X4Y] + src[Z]*_mat[X4Z] + _mat[X4W]); dest[Y] = Obj2(src[X]*_mat[Y4X] + src[Y]*_mat[Y4Y] + src[Z]*_mat[Y4Z] + _mat[Y4W]); dest[Z] = Obj2(src[X]*_mat[Z4X] + src[Y]*_mat[Z4Y] + src[Z]*_mat[Z4Z] + _mat[Z4W]); return Obj2(src[X]*_mat[W4X] + src[Y]*_mat[W4Y] + src[Z]*_mat[W4Z] + _mat[W4W]); // [NOTE] src[W] is implicitly 1 } template <class Obj2> VectorT<Obj2> transposeTrans(VectorT<Obj2> const & v) const { // transforms v by the transpose // [NOTE] for surface normals use ~inverseMat.transposeTrans(norm) return VectorT<Obj2>( Obj2(v[X]*_mat[X4X] + v[Y]*_mat[Y4X] + v[Z]*_mat[Z4X]), Obj2(v[X]*_mat[X4Y] + v[Y]*_mat[Y4Y] + v[Z]*_mat[Z4Y]), Obj2(v[X]*_mat[X4Z] + v[Y]*_mat[Y4Z] + v[Z]*_mat[Z4Z])); } PointT<Obj> origin() const { return PointT<Obj>(_mat[X4W], _mat[Y4W], _mat[Z4W]) / _mat[W4W]; } VectorT<Obj> xHat() const { return VectorT<Obj>(_mat[X4X], _mat[Y4X], _mat[Z4X]); } VectorT<Obj> yHat() const { return VectorT<Obj>(_mat[X4Y], _mat[Y4Y], _mat[Z4Y]); } VectorT<Obj> zHat() const { return VectorT<Obj>(_mat[X4Z], _mat[Y4Z], _mat[Z4Z]); } void setXHat(VectorT<Obj> const & v) { _mat[X4X] = v[0]; _mat[Y4X] = v[1], _mat[Z4X] = v[2]; } void setYHat(VectorT<Obj> const & v) { _mat[X4Y] = v[0]; _mat[Y4Y] = v[1], _mat[Z4Y] = v[2]; } void setZHat(VectorT<Obj> const & v) { _mat[X4Z] = v[0]; _mat[Y4Z] = v[1], _mat[Z4Z] = v[2]; } double determinant() const; // determinant of the matrix Matrix4X4T transposed() const; // transposed matrix Matrix4X4T adjoint() const; // upper-left part of the adjoint matrix (use determinant to get the rest) Matrix4X4T inverse() const; // inverse of the matrix (adjoint() / determinant()) Matrix4X4T safeInverse() const; // inverse of the matrix (adjoint() / determinant()) void transpose() { *this = transposed(); } // transpose the matrix void invert() { *this = inverse(); } // invert the matrix Matrix4X4T & operator += (Matrix4X4T const &); Matrix4X4T & operator -= (Matrix4X4T const &); Matrix4X4T & operator *= (double); Matrix4X4T & operator *= (Matrix4X4T const &); Matrix4X4T & operator &= (Matrix4X4T const &); Matrix4X4T & operator /= (Matrix4X4T const &); int operator == (Matrix4X4T const &) const; int operator != (Matrix4X4T const & m) const { return !operator==(m); } operator Obj*() { return _mat; } operator const Obj*() const { return _mat; } Obj & operator () (int r, int c) { return _mat[r * 4 + c]; } const Obj & operator () (int r, int c) const { return _mat[r * 4 + c]; } void display(HLSTD::ostream &) const; // statics static Matrix4X4T Identity() { return Matrix4X4T(VectorT<Obj>::XHat(), VectorT<Obj>::YHat(), VectorT<Obj>::ZHat(), PointT<Obj>::Origin()); } static Matrix4X4T HPB(VectorT<Obj> const & hpb); static Matrix4X4T Scale(VectorT<Obj> const & scale); static Matrix4X4T AlignTo(VectorT<Obj> const & from, VectorT<Obj> const & to); static Matrix4X4T PointAt(VectorT<Obj> const & to); static Matrix4X4T Translate(VectorT<Obj> const & offset); }; typedef Matrix4X4T<double> Matrix4X4; typedef Matrix4X4T<float> Matrix4X4f; typedef Matrix4X4T<WeeFloat> Matrix4X4i; //// non-member functions //// template <class Obj, class Obj2> VectorT<Obj> operator * (Matrix4X4T<Obj2> const &, VectorT<Obj> const &); // transform vector template <class Obj, class Obj2> PointT<Obj> operator * (Matrix4X4T<Obj2> const &, PointT<Obj> const &); // transform point template <class Obj, class Obj2> ColorT<Obj> operator * (Matrix4X4T<Obj2> const & m, ColorT<Obj> const & a) { return ColorT<Obj>(m * VectorT<Obj>(a)); } template <class Obj> HLSTD::ostream & operator << (HLSTD::ostream & out, Matrix4X4T<Obj> const & m) { m.display(out); return out; } template <class Obj, class Obj2> VectorT<Obj> operator * (Matrix4X4T<Obj2> const & m, VectorT<Obj> const & v) { // [NOTE] This is NOT the function you want for surface normals, which are not really directions! enum Axis{X,Y,Z,W}; return VectorT<Obj>(Obj(v[X]*m[X4X] + v[Y]*m[X4Y] + v[Z]*m[X4Z]), Obj(v[X]*m[Y4X] + v[Y]*m[Y4Y] + v[Z]*m[Y4Z]), Obj(v[X]*m[Z4X] + v[Y]*m[Z4Y] + v[Z]*m[Z4Z])); // [NOTE] if m is such that w != 0, the result would no longer be a legal vector! // so be careful that the w column of your matrix looks liks [0 0 0 ?] } template <class Obj, class Obj2> PointT<Obj> operator * (Matrix4X4T<Obj2> const & m, PointT<Obj> const & pt) { PointT<Obj> tpt; Obj w = m.wTrans(pt, tpt); if (w != 0.0) return tpt / w; else HLASSERT(0, "Matrix4X4T * PointT: Degenerate matrix:\n" << m); return tpt; } template <class Obj> Matrix4X4T<Obj> operator + (Matrix4X4T<Obj> a, Matrix4X4T<Obj> const & b) { return a += b; } template <class Obj> Matrix4X4T<Obj> operator - (Matrix4X4T<Obj> a, Matrix4X4T<Obj> const & b) { return a -= b; } template <class Obj> Matrix4X4T<Obj> operator * (Matrix4X4T<Obj> a, Matrix4X4T<Obj> const & b) { return a *= b; } template <class Obj> Matrix4X4T<Obj> operator & (Matrix4X4T<Obj> a, Matrix4X4T<Obj> const & b) { return a &= b; } template <class Obj> Matrix4X4T<Obj> operator / (Matrix4X4T<Obj> a, Matrix4X4T<Obj> const & b) { return a /= b; } template <class Obj> Matrix4X4T<Obj> operator * (Matrix4X4T<Obj> a, double b) { return a *= b; } template <class Obj> Matrix4X4T<Obj> operator / (Matrix4X4T<Obj> a, double b) { return a *= 1.0 / b; } //// Matrix4X4T implementation //// template <class Obj> Matrix4X4T<Obj>::Matrix4X4T(double m0, double m1, double m2, double m3, double m4, double m5, double m6, double m7, double m8, double m9, double m10, double m11, double m12, double m13, double m14, double m15) { _mat[X4X] = (Obj)m0; _mat[X4Y] = (Obj)m1; _mat[X4Z] = (Obj)m2; _mat[X4W] = (Obj)m3; _mat[Y4X] = (Obj)m4; _mat[Y4Y] = (Obj)m5; _mat[Y4Z] = (Obj)m6; _mat[Y4W] = (Obj)m7; _mat[Z4X] = (Obj)m8; _mat[Z4Y] = (Obj)m9; _mat[Z4Z] = (Obj)m10; _mat[Z4W] = (Obj)m11; _mat[W4X] = (Obj)m12; _mat[W4Y] = (Obj)m13; _mat[W4Z] = (Obj)m14; _mat[W4W] = (Obj)m15; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator += (Matrix4X4T const & m) { for (int i = 0; i < 16; i ++) _mat[i] += m[i]; return *this; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator -= (Matrix4X4T const & m) { for (int i = 0; i < 16; i ++) _mat[i] -= m[i]; return *this; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator &= (Matrix4X4T const & m) { for (int i = 0; i < 16; i ++) _mat[i] *= m[i]; return *this; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator /= (Matrix4X4T const & m) { for (int i = 0; i < 16; i ++) _mat[i] /= m[i]; return *this; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator *= (double d) { for (int i = 0; i < 16; i ++) _mat[i] *= d; return *this; } template <class Obj> Matrix4X4T<Obj> & Matrix4X4T<Obj>::operator *= (Matrix4X4T const & b) { Matrix4X4T c; int ci = 0; for (int i = 0; i < 4; i ++) for (int j = 0; j < 4; j ++) { c[ci] = 0.0; int ai = i * 4; int bi = j; for (int k = 0; k < 4; k ++) { c[ci] += _mat[ai ++] * b[bi]; bi += 4; } ci ++; } return *this = c; } template <class Obj> int Matrix4X4T<Obj>::operator == (Matrix4X4T<Obj> const & m) const { for (int i = 0; i < 16; i ++) if (_mat[i] != m._mat[i]) return 0; return 1; } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::transposed() const { // [OPTIMIZEME] unroll and return-value-optimize Matrix4X4T b; for (int i = 0; i < 4; i ++) for (int j = 0; j < 4; j ++) b(j, i) = (*this)(i, j); return b; } template <class Obj> double Matrix4X4T<Obj>::determinant() const { // [OPTIMIZEME] A really good compiler should optimize this stuff pretty well, // but last I checked I'm not using a really good compiler ;) return _mat[X4X]*_mat[Y4Y]*_mat[Z4Z]*_mat[W4W]-_mat[X4X]*_mat[Y4Y]*_mat[Z4W]*_mat[W4Z] -_mat[X4X]*_mat[Z4Y]*_mat[Y4Z]*_mat[W4W]+_mat[X4X]*_mat[Z4Y]*_mat[Y4W]*_mat[W4Z] +_mat[X4X]*_mat[W4Y]*_mat[Y4Z]*_mat[Z4W]-_mat[X4X]*_mat[W4Y]*_mat[Y4W]*_mat[Z4Z] -_mat[Y4X]*_mat[X4Y]*_mat[Z4Z]*_mat[W4W]+_mat[Y4X]*_mat[X4Y]*_mat[Z4W]*_mat[W4Z] +_mat[Y4X]*_mat[Z4Y]*_mat[X4Z]*_mat[W4W]-_mat[Y4X]*_mat[Z4Y]*_mat[X4W]*_mat[W4Z] -_mat[Y4X]*_mat[W4Y]*_mat[X4Z]*_mat[Z4W]+_mat[Y4X]*_mat[W4Y]*_mat[X4W]*_mat[Z4Z] +_mat[Z4X]*_mat[X4Y]*_mat[Y4Z]*_mat[W4W]-_mat[Z4X]*_mat[X4Y]*_mat[Y4W]*_mat[W4Z] -_mat[Z4X]*_mat[Y4Y]*_mat[X4Z]*_mat[W4W]+_mat[Z4X]*_mat[Y4Y]*_mat[X4W]*_mat[W4Z] +_mat[Z4X]*_mat[W4Y]*_mat[X4Z]*_mat[Y4W]-_mat[Z4X]*_mat[W4Y]*_mat[X4W]*_mat[Y4Z] -_mat[W4X]*_mat[X4Y]*_mat[Y4Z]*_mat[Z4W]+_mat[W4X]*_mat[X4Y]*_mat[Y4W]*_mat[Z4Z] +_mat[W4X]*_mat[Y4Y]*_mat[X4Z]*_mat[Z4W]-_mat[W4X]*_mat[Y4Y]*_mat[X4W]*_mat[Z4Z] -_mat[W4X]*_mat[Z4Y]*_mat[X4Z]*_mat[Y4W]+_mat[W4X]*_mat[Z4Y]*_mat[X4W]*_mat[Y4Z]; } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::adjoint() const { // [OPTIMIZEME] A really good compiler should optimize this stuff pretty well, // but last I checked I'm not using a really good compiler ;) return Matrix4X4T( _mat[Y4Y]*_mat[Z4Z]*_mat[W4W]-_mat[Y4Y]*_mat[Z4W]*_mat[W4Z]-_mat[Z4Y]*_mat[Y4Z]*_mat[W4W] +_mat[Z4Y]*_mat[Y4W]*_mat[W4Z]+_mat[W4Y]*_mat[Y4Z]*_mat[Z4W]-_mat[W4Y]*_mat[Y4W]*_mat[Z4Z], -_mat[X4Y]*_mat[Z4Z]*_mat[W4W]+_mat[X4Y]*_mat[Z4W]*_mat[W4Z]+_mat[Z4Y]*_mat[X4Z]*_mat[W4W] -_mat[Z4Y]*_mat[X4W]*_mat[W4Z]-_mat[W4Y]*_mat[X4Z]*_mat[Z4W]+_mat[W4Y]*_mat[X4W]*_mat[Z4Z], _mat[X4Y]*_mat[Y4Z]*_mat[W4W]-_mat[X4Y]*_mat[Y4W]*_mat[W4Z]-_mat[Y4Y]*_mat[X4Z]*_mat[W4W] +_mat[Y4Y]*_mat[X4W]*_mat[W4Z]+_mat[W4Y]*_mat[X4Z]*_mat[Y4W]-_mat[W4Y]*_mat[X4W]*_mat[Y4Z], -_mat[X4Y]*_mat[Y4Z]*_mat[Z4W]+_mat[X4Y]*_mat[Y4W]*_mat[Z4Z]+_mat[Y4Y]*_mat[X4Z]*_mat[Z4W] -_mat[Y4Y]*_mat[X4W]*_mat[Z4Z]-_mat[Z4Y]*_mat[X4Z]*_mat[Y4W]+_mat[Z4Y]*_mat[X4W]*_mat[Y4Z], -_mat[Z4X]*_mat[Y4W]*_mat[W4Z]-_mat[W4X]*_mat[Y4Z]*_mat[Z4W]-_mat[Y4X]*_mat[Z4Z]*_mat[W4W] +_mat[Y4X]*_mat[Z4W]*_mat[W4Z]+_mat[Z4X]*_mat[Y4Z]*_mat[W4W]+_mat[W4X]*_mat[Y4W]*_mat[Z4Z], _mat[X4X]*_mat[Z4Z]*_mat[W4W]-_mat[X4X]*_mat[Z4W]*_mat[W4Z]-_mat[Z4X]*_mat[X4Z]*_mat[W4W] +_mat[Z4X]*_mat[X4W]*_mat[W4Z]+_mat[W4X]*_mat[X4Z]*_mat[Z4W]-_mat[W4X]*_mat[X4W]*_mat[Z4Z], -_mat[X4X]*_mat[Y4Z]*_mat[W4W]+_mat[X4X]*_mat[Y4W]*_mat[W4Z]+_mat[Y4X]*_mat[X4Z]*_mat[W4W] -_mat[Y4X]*_mat[X4W]*_mat[W4Z]-_mat[W4X]*_mat[X4Z]*_mat[Y4W]+_mat[W4X]*_mat[X4W]*_mat[Y4Z], _mat[X4X]*_mat[Y4Z]*_mat[Z4W]-_mat[X4X]*_mat[Y4W]*_mat[Z4Z]-_mat[Y4X]*_mat[X4Z]*_mat[Z4W] +_mat[Y4X]*_mat[X4W]*_mat[Z4Z]+_mat[Z4X]*_mat[X4Z]*_mat[Y4W]-_mat[Z4X]*_mat[X4W]*_mat[Y4Z], _mat[Y4X]*_mat[Z4Y]*_mat[W4W]-_mat[Y4X]*_mat[Z4W]*_mat[W4Y]-_mat[Z4X]*_mat[Y4Y]*_mat[W4W] +_mat[Z4X]*_mat[Y4W]*_mat[W4Y]+_mat[W4X]*_mat[Y4Y]*_mat[Z4W]-_mat[W4X]*_mat[Y4W]*_mat[Z4Y], -_mat[X4X]*_mat[Z4Y]*_mat[W4W]+_mat[X4X]*_mat[Z4W]*_mat[W4Y]+_mat[Z4X]*_mat[X4Y]*_mat[W4W] -_mat[Z4X]*_mat[X4W]*_mat[W4Y]-_mat[W4X]*_mat[X4Y]*_mat[Z4W]+_mat[W4X]*_mat[X4W]*_mat[Z4Y], _mat[X4X]*_mat[Y4Y]*_mat[W4W]-_mat[X4X]*_mat[Y4W]*_mat[W4Y]-_mat[Y4X]*_mat[X4Y]*_mat[W4W] +_mat[Y4X]*_mat[X4W]*_mat[W4Y]+_mat[W4X]*_mat[X4Y]*_mat[Y4W]-_mat[W4X]*_mat[X4W]*_mat[Y4Y], -_mat[X4X]*_mat[Y4Y]*_mat[Z4W]+_mat[X4X]*_mat[Y4W]*_mat[Z4Y]+_mat[Y4X]*_mat[X4Y]*_mat[Z4W] -_mat[Y4X]*_mat[X4W]*_mat[Z4Y]-_mat[Z4X]*_mat[X4Y]*_mat[Y4W]+_mat[Z4X]*_mat[X4W]*_mat[Y4Y], -_mat[Y4X]*_mat[Z4Y]*_mat[W4Z]+_mat[Y4X]*_mat[Z4Z]*_mat[W4Y]+_mat[Z4X]*_mat[Y4Y]*_mat[W4Z] -_mat[Z4X]*_mat[Y4Z]*_mat[W4Y]-_mat[W4X]*_mat[Y4Y]*_mat[Z4Z]+_mat[W4X]*_mat[Y4Z]*_mat[Z4Y], _mat[X4X]*_mat[Z4Y]*_mat[W4Z]-_mat[X4X]*_mat[Z4Z]*_mat[W4Y]-_mat[Z4X]*_mat[X4Y]*_mat[W4Z] +_mat[Z4X]*_mat[X4Z]*_mat[W4Y]+_mat[W4X]*_mat[X4Y]*_mat[Z4Z]-_mat[W4X]*_mat[X4Z]*_mat[Z4Y], -_mat[X4X]*_mat[Y4Y]*_mat[W4Z]+_mat[X4X]*_mat[Y4Z]*_mat[W4Y]+_mat[Y4X]*_mat[X4Y]*_mat[W4Z] -_mat[Y4X]*_mat[X4Z]*_mat[W4Y]-_mat[W4X]*_mat[X4Y]*_mat[Y4Z]+_mat[W4X]*_mat[X4Z]*_mat[Y4Y], _mat[X4X]*_mat[Y4Y]*_mat[Z4Z]-_mat[X4X]*_mat[Y4Z]*_mat[Z4Y]-_mat[Y4X]*_mat[X4Y]*_mat[Z4Z] +_mat[Y4X]*_mat[X4Z]*_mat[Z4Y]+_mat[Z4X]*_mat[X4Y]*_mat[Y4Z]-_mat[Z4X]*_mat[X4Z]*_mat[Y4Y]); } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::inverse() const { double det = determinant(); HLASSERT(det != 0.0, "Matrix4X4T::inverse(): Singular matrix:\n" << *this); return adjoint() / det; } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::safeInverse() const { double det = determinant(); if (!det) return adjoint() * 1e14; return adjoint() / det; } template <class Obj> void Matrix4X4T<Obj>::display(HLSTD::ostream & out) const { out << endl; for (int i = 0; i < 4; i ++) { out << "[ "; for (int j = 0; j < 4; j ++) { out << (*this)(i,j) << " "; } out << "]" << endl; } } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::HPB(VectorT<Obj> const & hpb) { // [OPTIMIZEME] just return the whole kitten kaboodle Matrix4X4T<Obj> m(VectorT<Obj>(cos(hpb[2]), -sin(hpb[2]), 0), VectorT<Obj>(sin(hpb[2]), cos(hpb[2]), 0), VectorT<Obj>(0, 0, 1)); m *= Matrix4X4T<Obj>(VectorT<Obj>(1, 0, 0), VectorT<Obj>(0, cos(hpb[1]), -sin(hpb[1])), VectorT<Obj>(0, sin(hpb[1]), cos(hpb[1]))); m *= Matrix4X4T<Obj>(VectorT<Obj>(cos(hpb[0]), 0, -sin(hpb[0])), VectorT<Obj>(0, 1, 0), VectorT<Obj>(sin(hpb[0]), 0, cos(hpb[0]))); return m; } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::Scale(VectorT<Obj> const & scale) { return Matrix4X4T<Obj>(VectorT<Obj>(scale[0], 0, 0), VectorT<Obj>(0, scale[1], 0), VectorT<Obj>(0, 0, scale[2])); } /* // [FIXME] incorporate this yummy "rotate around an axis" code into its own function: rcos = cos(phi); rsin = sin(phi); matrix[0][0] = rcos + u*u*(1-rcos); matrix[1][0] = w * rsin + v*u*(1-rcos); matrix[2][0] = -v * rsin + w*u*(1-rcos); matrix[0][1] = -w * rsin + u*v*(1-rcos); matrix[1][1] = rcos + v*v*(1-rcos); matrix[2][1] = u * rsin + w*v*(1-rcos); matrix[0][2] = v * rsin + u*w*(1-rcos); matrix[1][2] = -u * rsin + v*w*(1-rcos); matrix[2][2] = rcos + w*w*(1-rcos); */ template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::AlignTo(VectorT<Obj> const & from, VectorT<Obj> const & to) { // [FIXME] reference // rotates 'from' to 'to', the short way around // [NOTE] assumes 'from' and 'to' are normal vectors Obj e = from * to; if (e == (Obj)1.0) return Matrix4X4T<Obj>::Identity(); Obj denom = ((Obj)1.0 + e); if (!denom) // exactly opposite, so "short way" is undefined; { // choose a vector for the rotation axis VectorT<Obj> v = from % VectorT<Obj>::YHat(); // if we chose a bad one, choose another one if (!!v) v = from % VectorT<Obj>::ZHat(); v = ~v; // rotate 180 degrees around v Matrix4X4T<Obj> m; m._mtx[0][0] = v[0]*v[0]*2 - 1.0; m._mtx[1][0] = v[1]*v[0]*2; m._mtx[2][0] = v[2]*v[0]*2; m._mtx[0][1] = v[0]*v[1]*2; m._mtx[1][1] = v[1]*v[1]*2 - 1.0; m._mtx[2][1] = v[2]*v[1]*2; m._mtx[0][2] = v[0]*v[2]*2; m._mtx[1][2] = v[1]*v[2]*2; m._mtx[2][2] = v[2]*v[2]*2 - 1.0; m._mat[W4X] = (Obj)0.0; m._mat[W4Y] = (Obj)0.0; m._mat[W4Z] = (Obj)0.0; m._mat[X4W] = (Obj)0.0; m._mat[Y4W] = (Obj)0.0; m._mat[Z4W] = (Obj)0.0; m._mat[W4W] = (Obj)1.0; return m; } VectorT<Obj> v = from % to; VectorT<Obj> hv = v / denom; Obj hvxy = hv[0] * v[1]; Obj hvxz = hv[0] * v[2]; Obj hvyz = hv[2] * v[1]; Matrix4X4T<Obj> m; m._mtx[0][0] = e + hv[0] * v[0]; m._mtx[1][0] = hvxy + v[2]; m._mtx[2][0] = hvxz - v[1]; m._mtx[0][1] = hvxy - v[2]; m._mtx[1][1] = e + hv[1] * v[1]; m._mtx[2][1] = hvyz + v[0]; m._mtx[0][2] = hvxz + v[1]; m._mtx[1][2] = hvyz - v[0]; m._mtx[2][2] = e + hv[2] * v[2]; m._mat[W4X] = (Obj)0.0; m._mat[W4Y] = (Obj)0.0; m._mat[W4Z] = (Obj)0.0; m._mat[X4W] = (Obj)0.0; m._mat[Y4W] = (Obj)0.0; m._mat[Z4W] = (Obj)0.0; m._mat[W4W] = (Obj)1.0; return m; // [OPTIMIZEME] just return the whole kitten kaboodle } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::PointAt(VectorT<Obj> const & to) { VectorT<Obj> z = ~to; VectorT<Obj> x = ~(Vector::YHat() % z); VectorT<Obj> y = ~(z % x); return Matrix4X4T<Obj>(x, y, z); } template <class Obj> Matrix4X4T<Obj> Matrix4X4T<Obj>::Translate(VectorT<Obj> const & offset) { return Matrix4X4T<Obj>(1,0,0,offset[0], 0,1,0,offset[1], 0,0,1,offset[2], 0,0,0,1); } #endif
[ "lightwolf@dac1304f-7ce9-0310-a59f-f2d444f72a61" ]
[ [ [ 1, 432 ] ] ]
3169c2317a7a99db85abb3b6da9fb971330e80f7
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/numeric/ublas/matrix_sparse.hpp
9ca83735dff9d125822ed241a0d69d7a910ebde9
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
217,000
hpp
// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. The authors make no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #ifndef _BOOST_UBLAS_MATRIX_SPARSE_ #define _BOOST_UBLAS_MATRIX_SPARSE_ #include <boost/numeric/ublas/vector_sparse.hpp> #include <boost/numeric/ublas/matrix_expression.hpp> #include <boost/numeric/ublas/detail/matrix_assign.hpp> #if BOOST_UBLAS_TYPE_CHECK #include <boost/numeric/ublas/matrix.hpp> #endif // Iterators based on ideas of Jeremy Siek namespace boost { namespace numeric { namespace ublas { #ifdef BOOST_UBLAS_STRICT_MATRIX_SPARSE template<class M> class sparse_matrix_element: public container_reference<M> { public: typedef M matrix_type; typedef typename M::size_type size_type; typedef typename M::value_type value_type; typedef const value_type &const_reference; typedef value_type *pointer; typedef const value_type *const_pointer; private: // Proxied element operations void get_d () const { const_pointer p = (*this) ().find_element (i_, j_); if (p) d_ = *p; else d_ = value_type/*zero*/(); } void set (const value_type &s) const { pointer p = (*this) ().find_element (i_, j_); if (!p) (*this) ().insert_element (i_, j_, s); else *p = s; } public: // Construction and destruction BOOST_UBLAS_INLINE sparse_matrix_element (matrix_type &m, size_type i, size_type j): container_reference<matrix_type> (m), i_ (i), j_ (j) { } BOOST_UBLAS_INLINE sparse_matrix_element (const sparse_matrix_element &p): container_reference<matrix_type> (p), i_ (p.i_), j_ (p.j_) {} BOOST_UBLAS_INLINE ~sparse_matrix_element () { } // Assignment BOOST_UBLAS_INLINE sparse_matrix_element &operator = (const sparse_matrix_element &p) { // Overide the implict copy assignment p.get_d (); set (p.d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_matrix_element &operator = (const D &d) { set (d); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_matrix_element &operator += (const D &d) { get_d (); d_ += d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_matrix_element &operator -= (const D &d) { get_d (); d_ -= d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_matrix_element &operator *= (const D &d) { get_d (); d_ *= d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_matrix_element &operator /= (const D &d) { get_d (); d_ /= d; set (d_); return *this; } // Comparison template<class D> BOOST_UBLAS_INLINE bool operator == (const D &d) const { get_d (); return d_ == d; } template<class D> BOOST_UBLAS_INLINE bool operator != (const D &d) const { get_d (); return d_ != d; } // Conversion - weak link in proxy as d_ is not a perfect alias for the element BOOST_UBLAS_INLINE operator const_reference () const { get_d (); return d_; } // Conversion to reference - may be invalidated BOOST_UBLAS_INLINE value_type& ref () const { const pointer p = (*this) ().find_element (i_, j_); if (!p) return (*this) ().insert_element (i_, j_, value_type/*zero*/()); else return *p; } private: size_type i_; size_type j_; mutable value_type d_; }; /* * Generalise explicit reference access */ namespace detail { template <class V> struct element_reference<sparse_matrix_element<V> > { typedef typename V::value_type& reference; static reference get_reference (const sparse_matrix_element<V>& sve) { return sve.ref (); } }; } template<class M> struct type_traits<sparse_matrix_element<M> > { typedef typename M::value_type element_type; typedef type_traits<sparse_matrix_element<M> > self_type; typedef typename type_traits<element_type>::value_type value_type; typedef typename type_traits<element_type>::const_reference const_reference; typedef sparse_matrix_element<M> reference; typedef typename type_traits<element_type>::real_type real_type; typedef typename type_traits<element_type>::precision_type precision_type; static const unsigned plus_complexity = type_traits<element_type>::plus_complexity; static const unsigned multiplies_complexity = type_traits<element_type>::multiplies_complexity; static BOOST_UBLAS_INLINE real_type real (const_reference t) { return type_traits<element_type>::real (t); } static BOOST_UBLAS_INLINE real_type imag (const_reference t) { return type_traits<element_type>::imag (t); } static BOOST_UBLAS_INLINE value_type conj (const_reference t) { return type_traits<element_type>::conj (t); } static BOOST_UBLAS_INLINE real_type type_abs (const_reference t) { return type_traits<element_type>::type_abs (t); } static BOOST_UBLAS_INLINE value_type type_sqrt (const_reference t) { return type_traits<element_type>::type_sqrt (t); } static BOOST_UBLAS_INLINE real_type norm_1 (const_reference t) { return type_traits<element_type>::norm_1 (t); } static BOOST_UBLAS_INLINE real_type norm_2 (const_reference t) { return type_traits<element_type>::norm_2 (t); } static BOOST_UBLAS_INLINE real_type norm_inf (const_reference t) { return type_traits<element_type>::norm_inf (t); } static BOOST_UBLAS_INLINE bool equals (const_reference t1, const_reference t2) { return type_traits<element_type>::equals (t1, t2); } }; template<class M1, class T2> struct promote_traits<sparse_matrix_element<M1>, T2> { typedef typename promote_traits<typename sparse_matrix_element<M1>::value_type, T2>::promote_type promote_type; }; template<class T1, class M2> struct promote_traits<T1, sparse_matrix_element<M2> > { typedef typename promote_traits<T1, typename sparse_matrix_element<M2>::value_type>::promote_type promote_type; }; template<class M1, class M2> struct promote_traits<sparse_matrix_element<M1>, sparse_matrix_element<M2> > { typedef typename promote_traits<typename sparse_matrix_element<M1>::value_type, typename sparse_matrix_element<M2>::value_type>::promote_type promote_type; }; #endif // Index map based sparse matrix class template<class T, class L, class A> class mapped_matrix: public matrix_container<mapped_matrix<T, L, A> > { typedef T &true_reference; typedef T *pointer; typedef const T * const_pointer; typedef L layout_type; typedef mapped_matrix<T, L, A> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using matrix_container<self_type>::operator (); #endif typedef typename A::size_type size_type; typedef typename A::difference_type difference_type; typedef T value_type; typedef A array_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE typedef typename detail::map_traits<A, T>::reference reference; #else typedef sparse_matrix_element<self_type> reference; #endif typedef const matrix_reference<const self_type> const_closure_type; typedef matrix_reference<self_type> closure_type; typedef mapped_vector<T, A> vector_temporary_type; typedef self_type matrix_temporary_type; typedef sparse_tag storage_category; typedef typename L::orientation_category orientation_category; // Construction and destruction BOOST_UBLAS_INLINE mapped_matrix (): matrix_container<self_type> (), size1_ (0), size2_ (0), data_ () {} BOOST_UBLAS_INLINE mapped_matrix (size_type size1, size_type size2, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (size1), size2_ (size2), data_ () { detail::map_reserve (data (), restrict_capacity (non_zeros)); } BOOST_UBLAS_INLINE mapped_matrix (const mapped_matrix &m): matrix_container<self_type> (), size1_ (m.size1_), size2_ (m.size2_), data_ (m.data_) {} template<class AE> BOOST_UBLAS_INLINE mapped_matrix (const matrix_expression<AE> &ae, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (ae ().size1 ()), size2_ (ae ().size2 ()), data_ () { detail::map_reserve (data (), restrict_capacity (non_zeros)); matrix_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size1 () const { return size1_; } BOOST_UBLAS_INLINE size_type size2 () const { return size2_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return detail::map_capacity (data ()); } BOOST_UBLAS_INLINE size_type nnz () const { return data (). size (); } // Storage accessors BOOST_UBLAS_INLINE const array_type &data () const { return data_; } BOOST_UBLAS_INLINE array_type &data () { return data_; } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { // Guarding against overflow - thanks to Alexei Novakov for the hint. // non_zeros = (std::min) (non_zeros, size1_ * size2_); if (size1_ > 0 && non_zeros / size1_ >= size2_) non_zeros = size1_ * size2_; return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size1, size_type size2, bool preserve = true) { // FIXME preserve unimplemented BOOST_UBLAS_CHECK (!preserve, internal_logic ()); size1_ = size1; size2_ = size2; data ().clear (); } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool preserve = true) { detail::map_reserve (data (), restrict_capacity (non_zeros)); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i, size_type j) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i, j)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i, size_type j) const { const size_type element = layout_type::element (i, size1_, j, size2_); const_subiterator_type it (data ().find (element)); if (it == data ().end ()) return 0; BOOST_UBLAS_CHECK ((*it).first == element, internal_logic ()); // broken map return &(*it).second; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i, size_type j) const { const size_type element = layout_type::element (i, size1_, j, size2_); const_subiterator_type it (data ().find (element)); if (it == data ().end ()) return zero_; BOOST_UBLAS_CHECK ((*it).first == element, internal_logic ()); // broken map return (*it).second; } BOOST_UBLAS_INLINE reference operator () (size_type i, size_type j) { #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE const size_type element = layout_type::element (i, size1_, j, size2_); std::pair<subiterator_type, bool> ii (data ().insert (typename array_type::value_type (element, value_type/*zero*/()))); BOOST_UBLAS_CHECK ((ii.first)->first == element, internal_logic ()); // broken map return (ii.first)->second; #else return reference (*this, i, j); #endif } // Element assingment BOOST_UBLAS_INLINE true_reference insert_element (size_type i, size_type j, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i, j), bad_index ()); // duplicate element const size_type element = layout_type::element (i, size1_, j, size2_); std::pair<subiterator_type, bool> ii (data ().insert (typename array_type::value_type (element, t))); BOOST_UBLAS_CHECK ((ii.first)->first == element, internal_logic ()); // broken map if (!ii.second) // existing element (ii.first)->second = t; return (ii.first)->second; } BOOST_UBLAS_INLINE void erase_element (size_type i, size_type j) { subiterator_type it = data ().find (layout_type::element (i, size1_, j, size2_)); if (it == data ().end ()) return; data ().erase (it); } // Zeroing BOOST_UBLAS_INLINE void clear () { data ().clear (); } // Assignment BOOST_UBLAS_INLINE mapped_matrix &operator = (const mapped_matrix &m) { if (this != &m) { size1_ = m.size1_; size2_ = m.size2_; data () = m.data (); } return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_matrix &operator = (const matrix_container<C> &m) { resize (m ().size1 (), m ().size2 (), false); assign (m); return *this; } BOOST_UBLAS_INLINE mapped_matrix &assign_temporary (mapped_matrix &m) { swap (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_matrix &operator = (const matrix_expression<AE> &ae) { self_type temporary (ae, detail::map_capacity (data ())); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE mapped_matrix &assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_matrix& operator += (const matrix_expression<AE> &ae) { self_type temporary (*this + ae, detail::map_capacity (data ())); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_matrix &operator += (const matrix_container<C> &m) { plus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_matrix &plus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_matrix& operator -= (const matrix_expression<AE> &ae) { self_type temporary (*this - ae, detail::map_capacity (data ())); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_matrix &operator -= (const matrix_container<C> &m) { minus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_matrix &minus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_matrix& operator *= (const AT &at) { matrix_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_matrix& operator /= (const AT &at) { matrix_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (mapped_matrix &m) { if (this != &m) { std::swap (size1_, m.size1_); std::swap (size2_, m.size2_); data ().swap (m.data ()); } } BOOST_UBLAS_INLINE friend void swap (mapped_matrix &m1, mapped_matrix &m2) { m1.swap (m2); } // Iterator types private: // Use storage iterator typedef typename A::const_iterator const_subiterator_type; typedef typename A::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i, size_type j) { const size_type element = layout_type::element (i, size1_, j, size2_); subiterator_type it (data ().find (element)); BOOST_UBLAS_CHECK (it != data ().end(), bad_index ()); BOOST_UBLAS_CHECK ((*it).first == element, internal_logic ()); // broken map return it->second; } public: class const_iterator1; class iterator1; class const_iterator2; class iterator2; typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1; typedef reverse_iterator_base1<iterator1> reverse_iterator1; typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2; typedef reverse_iterator_base2<iterator2> reverse_iterator2; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) const { const_subiterator_type it (data ().lower_bound (layout_type::address (i, size1_, j, size2_))); const_subiterator_type it_end (data ().end ()); size_type index1 = size_type (-1); size_type index2 = size_type (-1); while (rank == 1 && it != it_end) { index1 = layout_type::index1 ((*it).first, size1_, size2_); index2 = layout_type::index2 ((*it).first, size1_, size2_); if (direction > 0) { if ((index1 >= i && index2 == j) || (i >= size1_)) break; ++ i; } else /* if (direction < 0) */ { if ((index1 <= i && index2 == j) || (i == 0)) break; -- i; } it = data ().lower_bound (layout_type::address (i, size1_, j, size2_)); } if (rank == 1 && index2 != j) { if (direction > 0) i = size1_; else /* if (direction < 0) */ i = 0; rank = 0; } return const_iterator1 (*this, rank, i, j, it); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) { subiterator_type it (data ().lower_bound (layout_type::address (i, size1_, j, size2_))); subiterator_type it_end (data ().end ()); size_type index1 = size_type (-1); size_type index2 = size_type (-1); while (rank == 1 && it != it_end) { index1 = layout_type::index1 ((*it).first, size1_, size2_); index2 = layout_type::index2 ((*it).first, size1_, size2_); if (direction > 0) { if ((index1 >= i && index2 == j) || (i >= size1_)) break; ++ i; } else /* if (direction < 0) */ { if ((index1 <= i && index2 == j) || (i == 0)) break; -- i; } it = data ().lower_bound (layout_type::address (i, size1_, j, size2_)); } if (rank == 1 && index2 != j) { if (direction > 0) i = size1_; else /* if (direction < 0) */ i = 0; rank = 0; } return iterator1 (*this, rank, i, j, it); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) const { const_subiterator_type it (data ().lower_bound (layout_type::address (i, size1_, j, size2_))); const_subiterator_type it_end (data ().end ()); size_type index1 = size_type (-1); size_type index2 = size_type (-1); while (rank == 1 && it != it_end) { index1 = layout_type::index1 ((*it).first, size1_, size2_); index2 = layout_type::index2 ((*it).first, size1_, size2_); if (direction > 0) { if ((index2 >= j && index1 == i) || (j >= size2_)) break; ++ j; } else /* if (direction < 0) */ { if ((index2 <= j && index1 == i) || (j == 0)) break; -- j; } it = data ().lower_bound (layout_type::address (i, size1_, j, size2_)); } if (rank == 1 && index1 != i) { if (direction > 0) j = size2_; else /* if (direction < 0) */ j = 0; rank = 0; } return const_iterator2 (*this, rank, i, j, it); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) { subiterator_type it (data ().lower_bound (layout_type::address (i, size1_, j, size2_))); subiterator_type it_end (data ().end ()); size_type index1 = size_type (-1); size_type index2 = size_type (-1); while (rank == 1 && it != it_end) { index1 = layout_type::index1 ((*it).first, size1_, size2_); index2 = layout_type::index2 ((*it).first, size1_, size2_); if (direction > 0) { if ((index2 >= j && index1 == i) || (j >= size2_)) break; ++ j; } else /* if (direction < 0) */ { if ((index2 <= j && index1 == i) || (j == 0)) break; -- j; } it = data ().lower_bound (layout_type::address (i, size1_, j, size2_)); } if (rank == 1 && index1 != i) { if (direction > 0) j = size2_; else /* if (direction < 0) */ j = 0; rank = 0; } return iterator2 (*this, rank, i, j, it); } class const_iterator1: public container_const_reference<mapped_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator1, value_type> { public: typedef typename mapped_matrix::value_type value_type; typedef typename mapped_matrix::difference_type difference_type; typedef typename mapped_matrix::const_reference reference; typedef const typename mapped_matrix::pointer pointer; typedef const_iterator2 dual_iterator_type; typedef const_reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator1 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator1 (const self_type &m, int rank, size_type i, size_type j, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), it_ (it) {} BOOST_UBLAS_INLINE const_iterator1 (const iterator1 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else *this = (*this) ().find1 (rank_, index1 () + 1, j_, 1); return *this; } BOOST_UBLAS_INLINE const_iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else *this = (*this) ().find1 (rank_, index1 () - 1, j_, -1); return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 begin () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 end () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rbegin () const { return const_reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rend () const { return const_reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator1 &operator = (const const_iterator1 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator1 begin1 () const { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator1 end1 () const { return find1 (0, size1_, 0); } class iterator1: public container_reference<mapped_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator1, value_type> { public: typedef typename mapped_matrix::value_type value_type; typedef typename mapped_matrix::difference_type difference_type; typedef typename mapped_matrix::true_reference reference; typedef typename mapped_matrix::pointer pointer; typedef iterator2 dual_iterator_type; typedef reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator1 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), it_ () {} BOOST_UBLAS_INLINE iterator1 (self_type &m, int rank, size_type i, size_type j, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else *this = (*this) ().find1 (rank_, index1 () + 1, j_, 1); return *this; } BOOST_UBLAS_INLINE iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else *this = (*this) ().find1 (rank_, index1 () - 1, j_, -1); return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 begin () const { self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 end () const { self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rbegin () const { return reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rend () const { return reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator1 &operator = (const iterator1 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; subiterator_type it_; friend class const_iterator1; }; BOOST_UBLAS_INLINE iterator1 begin1 () { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE iterator1 end1 () { return find1 (0, size1_, 0); } class const_iterator2: public container_const_reference<mapped_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator2, value_type> { public: typedef typename mapped_matrix::value_type value_type; typedef typename mapped_matrix::difference_type difference_type; typedef typename mapped_matrix::const_reference reference; typedef const typename mapped_matrix::pointer pointer; typedef const_iterator1 dual_iterator_type; typedef const_reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator2 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator2 (const self_type &m, int rank, size_type i, size_type j, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), it_ (it) {} BOOST_UBLAS_INLINE const_iterator2 (const iterator2 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else *this = (*this) ().find2 (rank_, i_, index2 () + 1, 1); return *this; } BOOST_UBLAS_INLINE const_iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else *this = (*this) ().find2 (rank_, i_, index2 () - 1, -1); return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 begin () const { const self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 end () const { const self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rbegin () const { return const_reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rend () const { return const_reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator2 &operator = (const const_iterator2 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator2 begin2 () const { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator2 end2 () const { return find2 (0, 0, size2_); } class iterator2: public container_reference<mapped_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator2, value_type> { public: typedef typename mapped_matrix::value_type value_type; typedef typename mapped_matrix::difference_type difference_type; typedef typename mapped_matrix::true_reference reference; typedef typename mapped_matrix::pointer pointer; typedef iterator1 dual_iterator_type; typedef reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator2 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), it_ () {} BOOST_UBLAS_INLINE iterator2 (self_type &m, int rank, size_type i, size_type j, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else *this = (*this) ().find2 (rank_, i_, index2 () + 1, 1); return *this; } BOOST_UBLAS_INLINE iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else *this = (*this) ().find2 (rank_, i_, index2 () - 1, -1); return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 begin () const { self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 end () const { self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rbegin () const { return reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rend () const { return reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*it_).first, m.size1 (), m.size2 ()); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { const self_type &m = (*this) (); BOOST_UBLAS_CHECK (layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*it_).first, m.size1 (), m.size2 ()); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator2 &operator = (const iterator2 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; subiterator_type it_; friend class const_iterator2; }; BOOST_UBLAS_INLINE iterator2 begin2 () { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE iterator2 end2 () { return find2 (0, 0, size2_); } // Reverse iterators BOOST_UBLAS_INLINE const_reverse_iterator1 rbegin1 () const { return const_reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator1 rend1 () const { return const_reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rbegin1 () { return reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rend1 () { return reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rbegin2 () const { return const_reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rend2 () const { return const_reverse_iterator2 (begin2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rbegin2 () { return reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rend2 () { return reverse_iterator2 (begin2 ()); } private: size_type size1_; size_type size2_; array_type data_; static const value_type zero_; }; template<class T, class L, class A> const typename mapped_matrix<T, L, A>::value_type mapped_matrix<T, L, A>::zero_ = value_type/*zero*/(); // Vector index map based sparse matrix class template<class T, class L, class A> class mapped_vector_of_mapped_vector: public matrix_container<mapped_vector_of_mapped_vector<T, L, A> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef A array_type; typedef const A const_array_type; typedef L layout_type; typedef mapped_vector_of_mapped_vector<T, L, A> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using matrix_container<self_type>::operator (); #endif typedef typename A::size_type size_type; typedef typename A::difference_type difference_type; typedef T value_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE typedef typename detail::map_traits<typename A::data_value_type, T>::reference reference; #else typedef sparse_matrix_element<self_type> reference; #endif typedef const matrix_reference<const self_type> const_closure_type; typedef matrix_reference<self_type> closure_type; typedef mapped_vector<T, typename A::value_type> vector_temporary_type; typedef self_type matrix_temporary_type; typedef typename A::value_type::second_type vector_data_value_type; typedef sparse_tag storage_category; typedef typename L::orientation_category orientation_category; // Construction and destruction BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector (): matrix_container<self_type> (), size1_ (0), size2_ (0), data_ () { data_ [layout_type::size1 (size1_, size2_)] = vector_data_value_type (); } BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector (size_type size1, size_type size2, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (size1), size2_ (size2), data_ () { data_ [layout_type::size1 (size1_, size2_)] = vector_data_value_type (); } BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector (const mapped_vector_of_mapped_vector &m): matrix_container<self_type> (), size1_ (m.size1_), size2_ (m.size2_), data_ (m.data_) {} template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector (const matrix_expression<AE> &ae, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (ae ().size1 ()), size2_ (ae ().size2 ()), data_ () { data_ [layout_type::size1 (size1_, size2_)] = vector_data_value_type (); matrix_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size1 () const { return size1_; } BOOST_UBLAS_INLINE size_type size2 () const { return size2_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { size_type non_zeros = 0; for (vector_const_subiterator_type itv = data_ ().begin (); itv != data_ ().end (); ++ itv) non_zeros += detail::map_capacity (*itv); return non_zeros; } BOOST_UBLAS_INLINE size_type nnz () const { size_type filled = 0; for (vector_const_subiterator_type itv = data_ ().begin (); itv != data_ ().end (); ++ itv) filled += (*itv).size (); return filled; } // Storage accessors BOOST_UBLAS_INLINE const_array_type &data () const { return data_; } BOOST_UBLAS_INLINE array_type &data () { return data_; } // Resizing BOOST_UBLAS_INLINE void resize (size_type size1, size_type size2, bool preserve = true) { // FIXME preserve unimplemented BOOST_UBLAS_CHECK (!preserve, internal_logic ()); size1_ = size1; size2_ = size2; data ().clear (); data () [layout_type::size1 (size1_, size2_)] = vector_data_value_type (); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i, size_type j) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i, j)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i, size_type j) const { const size_type element1 = layout_type::element1 (i, size1_, j, size2_); const size_type element2 = layout_type::element2 (i, size1_, j, size2_); vector_const_subiterator_type itv (data ().find (element1)); if (itv == data ().end ()) return 0; BOOST_UBLAS_CHECK ((*itv).first == element1, internal_logic ()); // broken map const_subiterator_type it ((*itv).second.find (element2)); if (it == (*itv).second.end ()) return 0; BOOST_UBLAS_CHECK ((*it).first == element2, internal_logic ()); // broken map return &(*it).second; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i, size_type j) const { const size_type element1 = layout_type::element1 (i, size1_, j, size2_); const size_type element2 = layout_type::element2 (i, size1_, j, size2_); vector_const_subiterator_type itv (data ().find (element1)); if (itv == data ().end ()) return zero_; BOOST_UBLAS_CHECK ((*itv).first == element1, internal_logic ()); // broken map const_subiterator_type it ((*itv).second.find (element2)); if (it == (*itv).second.end ()) return zero_; BOOST_UBLAS_CHECK ((*itv).first == element1, internal_logic ()); // broken map return (*it).second; } BOOST_UBLAS_INLINE reference operator () (size_type i, size_type j) { #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE const size_type element1 = layout_type::element1 (i, size1_, j, size2_); const size_type element2 = layout_type::element2 (i, size1_, j, size2_); vector_data_value_type& vd (data () [element1]); std::pair<subiterator_type, bool> ii (vd.insert (typename array_type::value_type::second_type::value_type (element2, value_type/*zero*/()))); BOOST_UBLAS_CHECK ((ii.first)->first == element2, internal_logic ()); // broken map return (ii.first)->second; #else return reference (*this, i, j); #endif } // Element assignment BOOST_UBLAS_INLINE true_reference insert_element (size_type i, size_type j, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i, j), bad_index ()); // duplicate element const size_type element1 = layout_type::element1 (i, size1_, j, size2_); const size_type element2 = layout_type::element2 (i, size1_, j, size2_); vector_data_value_type& vd (data () [element1]); std::pair<subiterator_type, bool> ii (vd.insert (typename vector_data_value_type::value_type (element2, t))); BOOST_UBLAS_CHECK ((ii.first)->first == element2, internal_logic ()); // broken map if (!ii.second) // existing element (ii.first)->second = t; return (ii.first)->second; } BOOST_UBLAS_INLINE void erase_element (size_type i, size_type j) { vector_subiterator_type itv (data ().find (layout_type::element1 (i, size1_, j, size2_))); if (itv == data ().end ()) return; subiterator_type it ((*itv).second.find (layout_type::element2 (i, size1_, j, size2_))); if (it == (*itv).second.end ()) return; (*itv).second.erase (it); } // Zeroing BOOST_UBLAS_INLINE void clear () { data ().clear (); data_ [layout_type::size1 (size1_, size2_)] = vector_data_value_type (); } // Assignment BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &operator = (const mapped_vector_of_mapped_vector &m) { if (this != &m) { size1_ = m.size1_; size2_ = m.size2_; data () = m.data (); } return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &operator = (const matrix_container<C> &m) { resize (m ().size1 (), m ().size2 ()); assign (m); return *this; } BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &assign_temporary (mapped_vector_of_mapped_vector &m) { swap (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &operator = (const matrix_expression<AE> &ae) { self_type temporary (ae); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector& operator += (const matrix_expression<AE> &ae) { self_type temporary (*this + ae); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &operator += (const matrix_container<C> &m) { plus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &plus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector& operator -= (const matrix_expression<AE> &ae) { self_type temporary (*this - ae); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &operator -= (const matrix_container<C> &m) { minus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector &minus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector& operator *= (const AT &at) { matrix_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_vector_of_mapped_vector& operator /= (const AT &at) { matrix_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (mapped_vector_of_mapped_vector &m) { if (this != &m) { std::swap (size1_, m.size1_); std::swap (size2_, m.size2_); data ().swap (m.data ()); } } BOOST_UBLAS_INLINE friend void swap (mapped_vector_of_mapped_vector &m1, mapped_vector_of_mapped_vector &m2) { m1.swap (m2); } // Iterator types private: // Use storage iterators typedef typename A::const_iterator vector_const_subiterator_type; typedef typename A::iterator vector_subiterator_type; typedef typename A::value_type::second_type::const_iterator const_subiterator_type; typedef typename A::value_type::second_type::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i, size_type j) { const size_type element1 = layout_type::element1 (i, size1_, j, size2_); const size_type element2 = layout_type::element2 (i, size1_, j, size2_); vector_subiterator_type itv (data ().find (element1)); BOOST_UBLAS_CHECK (itv != data ().end(), bad_index ()); BOOST_UBLAS_CHECK ((*itv).first == element1, internal_logic ()); // broken map subiterator_type it ((*itv).second.find (element2)); BOOST_UBLAS_CHECK (it != (*itv).second.end (), bad_index ()); BOOST_UBLAS_CHECK ((*it).first == element2, internal_logic ()); // broken map return it->second; } public: class const_iterator1; class iterator1; class const_iterator2; class iterator2; typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1; typedef reverse_iterator_base1<iterator1> reverse_iterator1; typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2; typedef reverse_iterator_base2<iterator2> reverse_iterator2; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) const { BOOST_UBLAS_CHECK (data ().begin () != data ().end (), internal_logic ()); for (;;) { vector_const_subiterator_type itv (data ().lower_bound (layout_type::address1 (i, size1_, j, size2_))); vector_const_subiterator_type itv_end (data ().end ()); if (itv == itv_end) return const_iterator1 (*this, rank, i, j, itv_end, (*(-- itv)).second.end ()); const_subiterator_type it ((*itv).second.lower_bound (layout_type::address2 (i, size1_, j, size2_))); const_subiterator_type it_end ((*itv).second.end ()); if (rank == 0) return const_iterator1 (*this, rank, i, j, itv, it); if (it != it_end && (*it).first == layout_type::address2 (i, size1_, j, size2_)) return const_iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return const_iterator1 (*this, rank, i, j, itv, it); i = (*it).first; } else { if (i >= size1_) return const_iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == (*itv).second.begin ()) return const_iterator1 (*this, rank, i, j, itv, it); -- it; i = (*it).first; } else { if (i == 0) return const_iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) { BOOST_UBLAS_CHECK (data ().begin () != data ().end (), internal_logic ()); for (;;) { vector_subiterator_type itv (data ().lower_bound (layout_type::address1 (i, size1_, j, size2_))); vector_subiterator_type itv_end (data ().end ()); if (itv == itv_end) return iterator1 (*this, rank, i, j, itv_end, (*(-- itv)).second.end ()); subiterator_type it ((*itv).second.lower_bound (layout_type::address2 (i, size1_, j, size2_))); subiterator_type it_end ((*itv).second.end ()); if (rank == 0) return iterator1 (*this, rank, i, j, itv, it); if (it != it_end && (*it).first == layout_type::address2 (i, size1_, j, size2_)) return iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return iterator1 (*this, rank, i, j, itv, it); i = (*it).first; } else { if (i >= size1_) return iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == (*itv).second.begin ()) return iterator1 (*this, rank, i, j, itv, it); -- it; i = (*it).first; } else { if (i == 0) return iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) const { BOOST_UBLAS_CHECK (data ().begin () != data ().end (), internal_logic ()); for (;;) { vector_const_subiterator_type itv (data ().lower_bound (layout_type::address1 (i, size1_, j, size2_))); vector_const_subiterator_type itv_end (data ().end ()); if (itv == itv_end) return const_iterator2 (*this, rank, i, j, itv_end, (*(-- itv)).second.end ()); const_subiterator_type it ((*itv).second.lower_bound (layout_type::address2 (i, size1_, j, size2_))); const_subiterator_type it_end ((*itv).second.end ()); if (rank == 0) return const_iterator2 (*this, rank, i, j, itv, it); if (it != it_end && (*it).first == layout_type::address2 (i, size1_, j, size2_)) return const_iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return const_iterator2 (*this, rank, i, j, itv, it); j = (*it).first; } else { if (j >= size2_) return const_iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == (*itv).second.begin ()) return const_iterator2 (*this, rank, i, j, itv, it); -- it; j = (*it).first; } else { if (j == 0) return const_iterator2 (*this, rank, i, j, itv, it); -- j; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) { BOOST_UBLAS_CHECK (data ().begin () != data ().end (), internal_logic ()); for (;;) { vector_subiterator_type itv (data ().lower_bound (layout_type::address1 (i, size1_, j, size2_))); vector_subiterator_type itv_end (data ().end ()); if (itv == itv_end) return iterator2 (*this, rank, i, j, itv_end, (*(-- itv)).second.end ()); subiterator_type it ((*itv).second.lower_bound (layout_type::address2 (i, size1_, j, size2_))); subiterator_type it_end ((*itv).second.end ()); if (rank == 0) return iterator2 (*this, rank, i, j, itv, it); if (it != it_end && (*it).first == layout_type::address2 (i, size1_, j, size2_)) return iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return iterator2 (*this, rank, i, j, itv, it); j = (*it).first; } else { if (j >= size2_) return iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == (*itv).second.begin ()) return iterator2 (*this, rank, i, j, itv, it); -- it; j = (*it).first; } else { if (j == 0) return iterator2 (*this, rank, i, j, itv, it); -- j; } } } } class const_iterator1: public container_const_reference<mapped_vector_of_mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator1, value_type> { public: typedef typename mapped_vector_of_mapped_vector::value_type value_type; typedef typename mapped_vector_of_mapped_vector::difference_type difference_type; typedef typename mapped_vector_of_mapped_vector::const_reference reference; typedef const typename mapped_vector_of_mapped_vector::pointer pointer; typedef const_iterator2 dual_iterator_type; typedef const_reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator1 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator1 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type &itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator1 (const iterator1 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { const self_type &m = (*this) (); i_ = index1 () + 1; if (rank_ == 1 && ++ itv_ == m.end1 ().itv_) *this = m.find1 (rank_, i_, j_, 1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index2 () != j_) *this = m.find1 (rank_, i_, j_, 1); } } return *this; } BOOST_UBLAS_INLINE const_iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { const self_type &m = (*this) (); i_ = index1 () - 1; if (rank_ == 1 && -- itv_ == m.end1 ().itv_) *this = m.find1 (rank_, i_, j_, -1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index2 () != j_) *this = m.find1 (rank_, i_, j_, -1); } } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 begin () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 end () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rbegin () const { return const_reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rend () const { return const_reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*itv_).first, (*it_).first) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*itv_).first, (*it_).first); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*itv_).first, (*it_).first) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*itv_).first, (*it_).first); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator1 &operator = (const const_iterator1 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator1 begin1 () const { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator1 end1 () const { return find1 (0, size1_, 0); } class iterator1: public container_reference<mapped_vector_of_mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator1, value_type> { public: typedef typename mapped_vector_of_mapped_vector::value_type value_type; typedef typename mapped_vector_of_mapped_vector::difference_type difference_type; typedef typename mapped_vector_of_mapped_vector::true_reference reference; typedef typename mapped_vector_of_mapped_vector::pointer pointer; typedef iterator2 dual_iterator_type; typedef reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator1 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator1 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { self_type &m = (*this) (); i_ = index1 () + 1; if (rank_ == 1 && ++ itv_ == m.end1 ().itv_) *this = m.find1 (rank_, i_, j_, 1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index2 () != j_) *this = m.find1 (rank_, i_, j_, 1); } } return *this; } BOOST_UBLAS_INLINE iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { self_type &m = (*this) (); i_ = index1 () - 1; if (rank_ == 1 && -- itv_ == m.end1 ().itv_) *this = m.find1 (rank_, i_, j_, -1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index2 () != j_) *this = m.find1 (rank_, i_, j_, -1); } } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 begin () const { self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 end () const { self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rbegin () const { return reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rend () const { return reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*itv_).first, (*it_).first) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*itv_).first, (*it_).first); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*itv_).first, (*it_).first) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*itv_).first, (*it_).first); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator1 &operator = (const iterator1 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator1; }; BOOST_UBLAS_INLINE iterator1 begin1 () { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE iterator1 end1 () { return find1 (0, size1_, 0); } class const_iterator2: public container_const_reference<mapped_vector_of_mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator2, value_type> { public: typedef typename mapped_vector_of_mapped_vector::value_type value_type; typedef typename mapped_vector_of_mapped_vector::difference_type difference_type; typedef typename mapped_vector_of_mapped_vector::const_reference reference; typedef const typename mapped_vector_of_mapped_vector::pointer pointer; typedef const_iterator1 dual_iterator_type; typedef const_reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator2 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator2 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type &itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator2 (const iterator2 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { const self_type &m = (*this) (); j_ = index2 () + 1; if (rank_ == 1 && ++ itv_ == m.end2 ().itv_) *this = m.find2 (rank_, i_, j_, 1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index1 () != i_) *this = m.find2 (rank_, i_, j_, 1); } } return *this; } BOOST_UBLAS_INLINE const_iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { const self_type &m = (*this) (); j_ = index2 () - 1; if (rank_ == 1 && -- itv_ == m.end2 ().itv_) *this = m.find2 (rank_, i_, j_, -1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index1 () != i_) *this = m.find2 (rank_, i_, j_, -1); } } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 begin () const { const self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 end () const { const self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rbegin () const { return const_reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rend () const { return const_reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*itv_).first, (*it_).first) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*itv_).first, (*it_).first); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*itv_).first, (*it_).first) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*itv_).first, (*it_).first); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator2 &operator = (const const_iterator2 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator2 begin2 () const { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator2 end2 () const { return find2 (0, 0, size2_); } class iterator2: public container_reference<mapped_vector_of_mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator2, value_type> { public: typedef typename mapped_vector_of_mapped_vector::value_type value_type; typedef typename mapped_vector_of_mapped_vector::difference_type difference_type; typedef typename mapped_vector_of_mapped_vector::true_reference reference; typedef typename mapped_vector_of_mapped_vector::pointer pointer; typedef iterator1 dual_iterator_type; typedef reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator2 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator2 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { self_type &m = (*this) (); j_ = index2 () + 1; if (rank_ == 1 && ++ itv_ == m.end2 ().itv_) *this = m.find2 (rank_, i_, j_, 1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index1 () != i_) *this = m.find2 (rank_, i_, j_, 1); } } return *this; } BOOST_UBLAS_INLINE iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { self_type &m = (*this) (); j_ = index2 () - 1; if (rank_ == 1 && -- itv_ == m.end2 ().itv_) *this = m.find2 (rank_, i_, j_, -1); else if (rank_ == 1) { it_ = (*itv_).second.begin (); if (it_ == (*itv_).second.end () || index1 () != i_) *this = m.find2 (rank_, i_, j_, -1); } } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*it_).second; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 begin () const { self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 end () const { self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rbegin () const { return reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rend () const { return reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*itv_).first, (*it_).first) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*itv_).first, (*it_).first); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*itv_).first, (*it_).first) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*itv_).first, (*it_).first); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator2 &operator = (const iterator2 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator2; }; BOOST_UBLAS_INLINE iterator2 begin2 () { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE iterator2 end2 () { return find2 (0, 0, size2_); } // Reverse iterators BOOST_UBLAS_INLINE const_reverse_iterator1 rbegin1 () const { return const_reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator1 rend1 () const { return const_reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rbegin1 () { return reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rend1 () { return reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rbegin2 () const { return const_reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rend2 () const { return const_reverse_iterator2 (begin2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rbegin2 () { return reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rend2 () { return reverse_iterator2 (begin2 ()); } private: size_type size1_; size_type size2_; array_type data_; static const value_type zero_; }; template<class T, class L, class A> const typename mapped_vector_of_mapped_vector<T, L, A>::value_type mapped_vector_of_mapped_vector<T, L, A>::zero_ = value_type/*zero*/(); // Comperssed array based sparse matrix class // Thanks to Kresimir Fresl for extending this to cover different index bases. template<class T, class L, std::size_t IB, class IA, class TA> class compressed_matrix: public matrix_container<compressed_matrix<T, L, IB, IA, TA> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef L layout_type; typedef compressed_matrix<T, L, IB, IA, TA> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using matrix_container<self_type>::operator (); #endif // ISSUE require type consistency check // is_convertable (IA::size_type, TA::size_type) typedef typename IA::value_type size_type; // size_type for the data arrays. typedef typename IA::size_type array_size_type; // FIXME difference type for sparse storage iterators should it be in the container? typedef typename IA::difference_type difference_type; typedef T value_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE typedef T &reference; #else typedef sparse_matrix_element<self_type> reference; #endif typedef IA index_array_type; typedef TA value_array_type; typedef const matrix_reference<const self_type> const_closure_type; typedef matrix_reference<self_type> closure_type; typedef compressed_vector<T, IB, IA, TA> vector_temporary_type; typedef self_type matrix_temporary_type; typedef sparse_tag storage_category; typedef typename L::orientation_category orientation_category; // Construction and destruction BOOST_UBLAS_INLINE compressed_matrix (): matrix_container<self_type> (), size1_ (0), size2_ (0), capacity_ (restrict_capacity (0)), filled1_ (1), filled2_ (0), index1_data_ (layout_type::size1 (size1_, size2_) + 1), index2_data_ (capacity_), value_data_ (capacity_) { index1_data_ [filled1_ - 1] = k_based (filled2_); storage_invariants (); } BOOST_UBLAS_INLINE compressed_matrix (size_type size1, size_type size2, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (size1), size2_ (size2), capacity_ (restrict_capacity (non_zeros)), filled1_ (1), filled2_ (0), index1_data_ (layout_type::size1 (size1_, size2_) + 1), index2_data_ (capacity_), value_data_ (capacity_) { index1_data_ [filled1_ - 1] = k_based (filled2_); storage_invariants (); } BOOST_UBLAS_INLINE compressed_matrix (const compressed_matrix &m): matrix_container<self_type> (), size1_ (m.size1_), size2_ (m.size2_), capacity_ (m.capacity_), filled1_ (m.filled1_), filled2_ (m.filled2_), index1_data_ (m.index1_data_), index2_data_ (m.index2_data_), value_data_ (m.value_data_) { storage_invariants (); } BOOST_UBLAS_INLINE compressed_matrix (const coordinate_matrix<T, L, IB, IA, TA> &m): matrix_container<self_type> (), size1_ (m.size1()), size2_ (m.size2()), index1_data_ (layout_type::size1 (size1_, size2_) + 1) { m.sort(); reserve(m.nnz(), false); filled2_ = m.nnz(); const_subiterator_type i_start = m.index1_data().begin(); const_subiterator_type i_end = (i_start + filled2_); const_subiterator_type i = i_start; size_type r = 1; for (; (r < layout_type::size1 (size1_, size2_)) && (i != i_end); ++r) { i = std::lower_bound(i, i_end, r); index1_data_[r] = k_based( i - i_start ); } filled1_ = r + 1; std::copy( m.index2_data().begin(), m.index2_data().begin() + filled2_, index2_data_.begin()); std::copy( m.value_data().begin(), m.value_data().begin() + filled2_, value_data_.begin()); index1_data_ [filled1_ - 1] = k_based(filled2_); storage_invariants (); } template<class AE> BOOST_UBLAS_INLINE compressed_matrix (const matrix_expression<AE> &ae, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (ae ().size1 ()), size2_ (ae ().size2 ()), capacity_ (restrict_capacity (non_zeros)), filled1_ (1), filled2_ (0), index1_data_ (layout_type::size1 (ae ().size1 (), ae ().size2 ()) + 1), index2_data_ (capacity_), value_data_ (capacity_) { index1_data_ [filled1_ - 1] = k_based (filled2_); storage_invariants (); matrix_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size1 () const { return size1_; } BOOST_UBLAS_INLINE size_type size2 () const { return size2_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return capacity_; } BOOST_UBLAS_INLINE size_type nnz () const { return filled2_; } // Storage accessors BOOST_UBLAS_INLINE static size_type index_base () { return IB; } BOOST_UBLAS_INLINE array_size_type filled1 () const { return filled1_; } BOOST_UBLAS_INLINE array_size_type filled2 () const { return filled2_; } BOOST_UBLAS_INLINE const index_array_type &index1_data () const { return index1_data_; } BOOST_UBLAS_INLINE const index_array_type &index2_data () const { return index2_data_; } BOOST_UBLAS_INLINE const value_array_type &value_data () const { return value_data_; } BOOST_UBLAS_INLINE void set_filled (const array_size_type& filled1, const array_size_type& filled2) { filled1_ = filled1; filled2_ = filled2; storage_invariants (); } BOOST_UBLAS_INLINE index_array_type &index1_data () { return index1_data_; } BOOST_UBLAS_INLINE index_array_type &index2_data () { return index2_data_; } BOOST_UBLAS_INLINE value_array_type &value_data () { return value_data_; } BOOST_UBLAS_INLINE void complete_index1_data () { while (filled1_ <= layout_type::size1 (size1_, size2_)) { this->index1_data_ [filled1_] = k_based (filled2_); ++ this->filled1_; } } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { non_zeros = (std::max) (non_zeros, (std::min) (size1_, size2_)); // Guarding against overflow - Thanks to Alexei Novakov for the hint. // non_zeros = (std::min) (non_zeros, size1_ * size2_); if (size1_ > 0 && non_zeros / size1_ >= size2_) non_zeros = size1_ * size2_; return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size1, size_type size2, bool preserve = true) { // FIXME preserve unimplemented BOOST_UBLAS_CHECK (!preserve, internal_logic ()); size1_ = size1; size2_ = size2; capacity_ = restrict_capacity (capacity_); filled1_ = 1; filled2_ = 0; index1_data_.resize (layout_type::size1 (size1_, size2_) + 1); index2_data_.resize (capacity_); value_data_.resize (capacity_); index1_data_ [filled1_ - 1] = k_based (filled2_); storage_invariants (); } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool preserve = true) { capacity_ = restrict_capacity (non_zeros); if (preserve) { index2_data_.resize (capacity_, size_type ()); value_data_.resize (capacity_, value_type ()); filled2_ = (std::min) (capacity_, filled2_); } else { index2_data_.resize (capacity_); value_data_.resize (capacity_); filled1_ = 1; filled2_ = 0; index1_data_ [filled1_ - 1] = k_based (filled2_); } storage_invariants (); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i, size_type j) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i, j)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i, size_type j) const { size_type element1 (layout_type::element1 (i, size1_, j, size2_)); size_type element2 (layout_type::element2 (i, size1_, j, size2_)); if (filled1_ <= element1 + 1) return 0; vector_const_subiterator_type itv (index1_data_.begin () + element1); const_subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); const_subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (element2), std::less<size_type> ())); if (it == it_end || *it != k_based (element2)) return 0; return &value_data_ [it - index2_data_.begin ()]; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i, size_type j) const { const_pointer p = find_element (i, j); if (p) return *p; else return zero_; } BOOST_UBLAS_INLINE reference operator () (size_type i, size_type j) { #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE size_type element1 (layout_type::element1 (i, size1_, j, size2_)); size_type element2 (layout_type::element2 (i, size1_, j, size2_)); if (filled1_ <= element1 + 1) return insert_element (i, j, value_type/*zero*/()); pointer p = find_element (i, j); if (p) return *p; else return insert_element (i, j, value_type/*zero*/()); #else return reference (*this, i, j); #endif } // Element assignment BOOST_UBLAS_INLINE true_reference insert_element (size_type i, size_type j, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i, j), bad_index ()); // duplicate element if (filled2_ >= capacity_) reserve (2 * filled2_, true); BOOST_UBLAS_CHECK (filled2_ < capacity_, internal_logic ()); size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); while (filled1_ <= element1 + 1) { index1_data_ [filled1_] = k_based (filled2_); ++ filled1_; } vector_subiterator_type itv (index1_data_.begin () + element1); subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (element2), std::less<size_type> ())); typename std::iterator_traits<subiterator_type>::difference_type n = it - index2_data_.begin (); BOOST_UBLAS_CHECK (it == it_end || *it != k_based (element2), internal_logic ()); // duplicate bound by lower_bound ++ filled2_; it = index2_data_.begin () + n; std::copy_backward (it, index2_data_.begin () + filled2_ - 1, index2_data_.begin () + filled2_); *it = k_based (element2); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy_backward (itt, value_data_.begin () + filled2_ - 1, value_data_.begin () + filled2_); *itt = t; while (element1 + 1 < filled1_) { ++ index1_data_ [element1 + 1]; ++ element1; } storage_invariants (); return *itt; } BOOST_UBLAS_INLINE void erase_element (size_type i, size_type j) { size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); if (element1 + 1 > filled1_) return; vector_subiterator_type itv (index1_data_.begin () + element1); subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (element2), std::less<size_type> ())); if (it != it_end && *it == k_based (element2)) { typename std::iterator_traits<subiterator_type>::difference_type n = it - index2_data_.begin (); std::copy (it + 1, index2_data_.begin () + filled2_, it); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy (itt + 1, value_data_.begin () + filled2_, itt); -- filled2_; while (index1_data_ [filled1_ - 2] > k_based (filled2_)) { index1_data_ [filled1_ - 1] = 0; -- filled1_; } while (element1 + 1 < filled1_) { -- index1_data_ [element1 + 1]; ++ element1; } } storage_invariants (); } // Zeroing BOOST_UBLAS_INLINE void clear () { filled1_ = 1; filled2_ = 0; index1_data_ [filled1_ - 1] = k_based (filled2_); storage_invariants (); } // Assignment BOOST_UBLAS_INLINE compressed_matrix &operator = (const compressed_matrix &m) { if (this != &m) { size1_ = m.size1_; size2_ = m.size2_; capacity_ = m.capacity_; filled1_ = m.filled1_; filled2_ = m.filled2_; index1_data_ = m.index1_data_; index2_data_ = m.index2_data_; value_data_ = m.value_data_; } storage_invariants (); return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_matrix &operator = (const matrix_container<C> &m) { resize (m ().size1 (), m ().size2 (), false); assign (m); return *this; } BOOST_UBLAS_INLINE compressed_matrix &assign_temporary (compressed_matrix &m) { swap (m); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_matrix &operator = (const matrix_expression<AE> &ae) { self_type temporary (ae, capacity_); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE compressed_matrix &assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_matrix& operator += (const matrix_expression<AE> &ae) { self_type temporary (*this + ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_matrix &operator += (const matrix_container<C> &m) { plus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_matrix &plus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_matrix& operator -= (const matrix_expression<AE> &ae) { self_type temporary (*this - ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_matrix &operator -= (const matrix_container<C> &m) { minus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_matrix &minus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE compressed_matrix& operator *= (const AT &at) { matrix_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE compressed_matrix& operator /= (const AT &at) { matrix_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (compressed_matrix &m) { if (this != &m) { std::swap (size1_, m.size1_); std::swap (size2_, m.size2_); std::swap (capacity_, m.capacity_); std::swap (filled1_, m.filled1_); std::swap (filled2_, m.filled2_); index1_data_.swap (m.index1_data_); index2_data_.swap (m.index2_data_); value_data_.swap (m.value_data_); } storage_invariants (); } BOOST_UBLAS_INLINE friend void swap (compressed_matrix &m1, compressed_matrix &m2) { m1.swap (m2); } // Back element insertion and erasure BOOST_UBLAS_INLINE void push_back (size_type i, size_type j, const_reference t) { if (filled2_ >= capacity_) reserve (2 * filled2_, true); BOOST_UBLAS_CHECK (filled2_ < capacity_, internal_logic ()); size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); while (filled1_ < element1 + 2) { index1_data_ [filled1_] = k_based (filled2_); ++ filled1_; } // must maintain sort order BOOST_UBLAS_CHECK ((filled1_ == element1 + 2 && (filled2_ == zero_based (index1_data_ [filled1_ - 2]) || index2_data_ [filled2_ - 1] < k_based (element2))), external_logic ()); ++ filled2_; index1_data_ [filled1_ - 1] = k_based (filled2_); index2_data_ [filled2_ - 1] = k_based (element2); value_data_ [filled2_ - 1] = t; storage_invariants (); } BOOST_UBLAS_INLINE void pop_back () { BOOST_UBLAS_CHECK (filled1_ > 0 && filled2_ > 0, external_logic ()); -- filled2_; while (index1_data_ [filled1_ - 2] > k_based (filled2_)) { index1_data_ [filled1_ - 1] = 0; -- filled1_; } -- index1_data_ [filled1_ - 1]; storage_invariants (); } // Iterator types private: // Use index array iterator typedef typename IA::const_iterator vector_const_subiterator_type; typedef typename IA::iterator vector_subiterator_type; typedef typename IA::const_iterator const_subiterator_type; typedef typename IA::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i, size_type j) { pointer p = find_element (i, j); BOOST_UBLAS_CHECK (p, bad_index ()); return *p; } public: class const_iterator1; class iterator1; class const_iterator2; class iterator2; typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1; typedef reverse_iterator_base1<iterator1> reverse_iterator1; typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2; typedef reverse_iterator_base2<iterator2> reverse_iterator2; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) const { for (;;) { array_size_type address1 (layout_type::address1 (i, size1_, j, size2_)); array_size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_const_subiterator_type itv (index1_data_.begin () + (std::min) (filled1_ - 1, address1)); if (filled1_ <= address1 + 1) return const_iterator1 (*this, rank, i, j, itv, index2_data_.begin () + filled2_); const_subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); const_subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); if (rank == 0) return const_iterator1 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return const_iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return const_iterator1 (*this, rank, i, j, itv, it); i = zero_based (*it); } else { if (i >= size1_) return const_iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return const_iterator1 (*this, rank, i, j, itv, it); i = zero_based (*(it - 1)); } else { if (i == 0) return const_iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) { for (;;) { array_size_type address1 (layout_type::address1 (i, size1_, j, size2_)); array_size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_subiterator_type itv (index1_data_.begin () + (std::min) (filled1_ - 1, address1)); if (filled1_ <= address1 + 1) return iterator1 (*this, rank, i, j, itv, index2_data_.begin () + filled2_); subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); if (rank == 0) return iterator1 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return iterator1 (*this, rank, i, j, itv, it); i = zero_based (*it); } else { if (i >= size1_) return iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return iterator1 (*this, rank, i, j, itv, it); i = zero_based (*(it - 1)); } else { if (i == 0) return iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) const { for (;;) { array_size_type address1 (layout_type::address1 (i, size1_, j, size2_)); array_size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_const_subiterator_type itv (index1_data_.begin () + (std::min) (filled1_ - 1, address1)); if (filled1_ <= address1 + 1) return const_iterator2 (*this, rank, i, j, itv, index2_data_.begin () + filled2_); const_subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); const_subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); if (rank == 0) return const_iterator2 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return const_iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return const_iterator2 (*this, rank, i, j, itv, it); j = zero_based (*it); } else { if (j >= size2_) return const_iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return const_iterator2 (*this, rank, i, j, itv, it); j = zero_based (*(it - 1)); } else { if (j == 0) return const_iterator2 (*this, rank, i, j, itv, it); -- j; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) { for (;;) { array_size_type address1 (layout_type::address1 (i, size1_, j, size2_)); array_size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_subiterator_type itv (index1_data_.begin () + (std::min) (filled1_ - 1, address1)); if (filled1_ <= address1 + 1) return iterator2 (*this, rank, i, j, itv, index2_data_.begin () + filled2_); subiterator_type it_begin (index2_data_.begin () + zero_based (*itv)); subiterator_type it_end (index2_data_.begin () + zero_based (*(itv + 1))); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); if (rank == 0) return iterator2 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return iterator2 (*this, rank, i, j, itv, it); j = zero_based (*it); } else { if (j >= size2_) return iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return iterator2 (*this, rank, i, j, itv, it); j = zero_based (*(it - 1)); } else { if (j == 0) return iterator2 (*this, rank, i, j, itv, it); -- j; } } } } class const_iterator1: public container_const_reference<compressed_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator1, value_type> { public: typedef typename compressed_matrix::value_type value_type; typedef typename compressed_matrix::difference_type difference_type; typedef typename compressed_matrix::const_reference reference; typedef const typename compressed_matrix::pointer pointer; typedef const_iterator2 dual_iterator_type; typedef const_reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator1 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator1 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type &itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator1 (const iterator1 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { i_ = index1 () + 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE const_iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { i_ = index1 () - 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 begin () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 end () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rbegin () const { return const_reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rend () const { return const_reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator1 &operator = (const const_iterator1 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator1 begin1 () const { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator1 end1 () const { return find1 (0, size1_, 0); } class iterator1: public container_reference<compressed_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator1, value_type> { public: typedef typename compressed_matrix::value_type value_type; typedef typename compressed_matrix::difference_type difference_type; typedef typename compressed_matrix::true_reference reference; typedef typename compressed_matrix::pointer pointer; typedef iterator2 dual_iterator_type; typedef reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator1 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator1 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { i_ = index1 () + 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { i_ = index1 () - 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 begin () const { self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 end () const { self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rbegin () const { return reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rend () const { return reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator1 &operator = (const iterator1 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator1; }; BOOST_UBLAS_INLINE iterator1 begin1 () { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE iterator1 end1 () { return find1 (0, size1_, 0); } class const_iterator2: public container_const_reference<compressed_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator2, value_type> { public: typedef typename compressed_matrix::value_type value_type; typedef typename compressed_matrix::difference_type difference_type; typedef typename compressed_matrix::const_reference reference; typedef const typename compressed_matrix::pointer pointer; typedef const_iterator1 dual_iterator_type; typedef const_reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator2 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator2 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator2 (const iterator2 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { j_ = index2 () + 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE const_iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { j_ = index2 () - 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 begin () const { const self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 end () const { const self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rbegin () const { return const_reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rend () const { return const_reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator2 &operator = (const const_iterator2 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator2 begin2 () const { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator2 end2 () const { return find2 (0, 0, size2_); } class iterator2: public container_reference<compressed_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator2, value_type> { public: typedef typename compressed_matrix::value_type value_type; typedef typename compressed_matrix::difference_type difference_type; typedef typename compressed_matrix::true_reference reference; typedef typename compressed_matrix::pointer pointer; typedef iterator1 dual_iterator_type; typedef reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator2 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator2 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { j_ = index2 () + 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { j_ = index2 (); if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 begin () const { self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 end () const { self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rbegin () const { return reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rend () const { return reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 (itv_ - (*this) ().index1_data_.begin (), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator2 &operator = (const iterator2 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator2; }; BOOST_UBLAS_INLINE iterator2 begin2 () { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE iterator2 end2 () { return find2 (0, 0, size2_); } // Reverse iterators BOOST_UBLAS_INLINE const_reverse_iterator1 rbegin1 () const { return const_reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator1 rend1 () const { return const_reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rbegin1 () { return reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rend1 () { return reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rbegin2 () const { return const_reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rend2 () const { return const_reverse_iterator2 (begin2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rbegin2 () { return reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rend2 () { return reverse_iterator2 (begin2 ()); } private: void storage_invariants () const { BOOST_UBLAS_CHECK (layout_type::size1 (size1_, size2_) + 1 == index1_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == index2_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == value_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (filled1_ > 0 && filled1_ <= layout_type::size1 (size1_, size2_) + 1, internal_logic ()); BOOST_UBLAS_CHECK (filled2_ <= capacity_, internal_logic ()); BOOST_UBLAS_CHECK (index1_data_ [filled1_ - 1] == k_based (filled2_), internal_logic ()); } size_type size1_; size_type size2_; array_size_type capacity_; array_size_type filled1_; array_size_type filled2_; index_array_type index1_data_; index_array_type index2_data_; value_array_type value_data_; static const value_type zero_; BOOST_UBLAS_INLINE static size_type zero_based (size_type k_based_index) { return k_based_index - IB; } BOOST_UBLAS_INLINE static size_type k_based (size_type zero_based_index) { return zero_based_index + IB; } friend class iterator1; friend class iterator2; friend class const_iterator1; friend class const_iterator2; }; template<class T, class L, std::size_t IB, class IA, class TA> const typename compressed_matrix<T, L, IB, IA, TA>::value_type compressed_matrix<T, L, IB, IA, TA>::zero_ = value_type/*zero*/(); // Coordinate array based sparse matrix class // Thanks to Kresimir Fresl for extending this to cover different index bases. template<class T, class L, std::size_t IB, class IA, class TA> class coordinate_matrix: public matrix_container<coordinate_matrix<T, L, IB, IA, TA> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef L layout_type; typedef coordinate_matrix<T, L, IB, IA, TA> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using matrix_container<self_type>::operator (); #endif // ISSUE require type consistency check // is_convertable (IA::size_type, TA::size_type) typedef typename IA::value_type size_type; // size_type for the data arrays. typedef typename IA::size_type array_size_type; // FIXME difference type for sprase storage iterators should it be in the container? typedef typename IA::difference_type difference_type; typedef T value_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE typedef T &reference; #else typedef sparse_matrix_element<self_type> reference; #endif typedef IA index_array_type; typedef TA value_array_type; typedef const matrix_reference<const self_type> const_closure_type; typedef matrix_reference<self_type> closure_type; typedef coordinate_vector<T, IB, IA, TA> vector_temporary_type; typedef self_type matrix_temporary_type; typedef sparse_tag storage_category; typedef typename L::orientation_category orientation_category; // Construction and destruction BOOST_UBLAS_INLINE coordinate_matrix (): matrix_container<self_type> (), size1_ (0), size2_ (0), capacity_ (restrict_capacity (0)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index1_data_ (capacity_), index2_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } BOOST_UBLAS_INLINE coordinate_matrix (size_type size1, size_type size2, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (size1), size2_ (size2), capacity_ (restrict_capacity (non_zeros)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index1_data_ (capacity_), index2_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } BOOST_UBLAS_INLINE coordinate_matrix (const coordinate_matrix &m): matrix_container<self_type> (), size1_ (m.size1_), size2_ (m.size2_), capacity_ (m.capacity_), filled_ (m.filled_), sorted_filled_ (m.sorted_filled_), sorted_ (m.sorted_), index1_data_ (m.index1_data_), index2_data_ (m.index2_data_), value_data_ (m.value_data_) { storage_invariants (); } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix (const matrix_expression<AE> &ae, size_type non_zeros = 0): matrix_container<self_type> (), size1_ (ae ().size1 ()), size2_ (ae ().size2 ()), capacity_ (restrict_capacity (non_zeros)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index1_data_ (capacity_), index2_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); matrix_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size1 () const { return size1_; } BOOST_UBLAS_INLINE size_type size2 () const { return size2_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return capacity_; } BOOST_UBLAS_INLINE size_type nnz () const { return filled_; } // Storage accessors BOOST_UBLAS_INLINE static size_type index_base () { return IB; } BOOST_UBLAS_INLINE array_size_type filled () const { return filled_; } BOOST_UBLAS_INLINE const index_array_type &index1_data () const { return index1_data_; } BOOST_UBLAS_INLINE const index_array_type &index2_data () const { return index2_data_; } BOOST_UBLAS_INLINE const value_array_type &value_data () const { return value_data_; } BOOST_UBLAS_INLINE void set_filled (const array_size_type &filled) { // Make sure that storage_invariants() succeeds if (sorted_ && filled < filled_) sorted_filled_ = filled; else sorted_ = (sorted_filled_ == filled); filled_ = filled; storage_invariants (); } BOOST_UBLAS_INLINE index_array_type &index1_data () { return index1_data_; } BOOST_UBLAS_INLINE index_array_type &index2_data () { return index2_data_; } BOOST_UBLAS_INLINE value_array_type &value_data () { return value_data_; } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { // minimum non_zeros non_zeros = (std::max) (non_zeros, (std::min) (size1_, size2_)); // ISSUE no maximum as coordinate may contain inserted duplicates return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size1, size_type size2, bool preserve = true) { // FIXME preserve unimplemented BOOST_UBLAS_CHECK (!preserve, internal_logic ()); size1_ = size1; size2_ = size2; capacity_ = restrict_capacity (capacity_); index1_data_.resize (capacity_); index2_data_.resize (capacity_); value_data_.resize (capacity_); filled_ = 0; sorted_filled_ = filled_; sorted_ = true; storage_invariants (); } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool preserve = true) { sort (); // remove duplicate elements capacity_ = restrict_capacity (non_zeros); if (preserve) { index1_data_.resize (capacity_, size_type ()); index2_data_.resize (capacity_, size_type ()); value_data_.resize (capacity_, value_type ()); filled_ = (std::min) (capacity_, filled_); } else { index1_data_.resize (capacity_); index2_data_.resize (capacity_); value_data_.resize (capacity_); filled_ = 0; } sorted_filled_ = filled_; storage_invariants (); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i, size_type j) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i, j)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i, size_type j) const { sort (); size_type element1 (layout_type::element1 (i, size1_, j, size2_)); size_type element2 (layout_type::element2 (i, size1_, j, size2_)); vector_const_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (element1), std::less<size_type> ())); vector_const_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (element1), std::less<size_type> ())); if (itv_begin == itv_end) return 0; const_subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); const_subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (element2), std::less<size_type> ())); if (it == it_end || *it != k_based (element2)) return 0; return &value_data_ [it - index2_data_.begin ()]; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i, size_type j) const { const_pointer p = find_element (i, j); if (p) return *p; else return zero_; } BOOST_UBLAS_INLINE reference operator () (size_type i, size_type j) { #ifndef BOOST_UBLAS_STRICT_MATRIX_SPARSE pointer p = find_element (i, j); if (p) return *p; else return insert_element (i, j, value_type/*zero*/()); #else return reference (*this, i, j); #endif } // Element assignment BOOST_UBLAS_INLINE void append_element (size_type i, size_type j, const_reference t) { if (filled_ >= capacity_) reserve (2 * filled_, true); BOOST_UBLAS_CHECK (filled_ < capacity_, internal_logic ()); size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); index1_data_ [filled_] = k_based (element1); index2_data_ [filled_] = k_based (element2); value_data_ [filled_] = t; ++ filled_; sorted_ = false; storage_invariants (); } BOOST_UBLAS_INLINE true_reference insert_element (size_type i, size_type j, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i, j), bad_index ()); // duplicate element append_element (i, j, t); return value_data_ [filled_ - 1]; } BOOST_UBLAS_INLINE void erase_element (size_type i, size_type j) { size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); sort (); vector_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (element1), std::less<size_type> ())); vector_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (element1), std::less<size_type> ())); subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (element2), std::less<size_type> ())); if (it != it_end && *it == k_based (element2)) { typename std::iterator_traits<subiterator_type>::difference_type n = it - index2_data_.begin (); vector_subiterator_type itv (index1_data_.begin () + n); std::copy (itv + 1, index1_data_.begin () + filled_, itv); std::copy (it + 1, index2_data_.begin () + filled_, it); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy (itt + 1, value_data_.begin () + filled_, itt); -- filled_; sorted_filled_ = filled_; } storage_invariants (); } // Zeroing BOOST_UBLAS_INLINE void clear () { filled_ = 0; sorted_filled_ = filled_; sorted_ = true; storage_invariants (); } // Assignment BOOST_UBLAS_INLINE coordinate_matrix &operator = (const coordinate_matrix &m) { if (this != &m) { size1_ = m.size1_; size2_ = m.size2_; capacity_ = m.capacity_; filled_ = m.filled_; sorted_filled_ = m.sorted_filled_; sorted_ = m.sorted_; index1_data_ = m.index1_data_; index2_data_ = m.index2_data_; value_data_ = m.value_data_; BOOST_UBLAS_CHECK (capacity_ == index1_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == index2_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == value_data_.size (), internal_logic ()); } storage_invariants (); return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_matrix &operator = (const matrix_container<C> &m) { resize (m ().size1 (), m ().size2 (), false); assign (m); return *this; } BOOST_UBLAS_INLINE coordinate_matrix &assign_temporary (coordinate_matrix &m) { swap (m); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix &operator = (const matrix_expression<AE> &ae) { self_type temporary (ae, capacity_); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix &assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix& operator += (const matrix_expression<AE> &ae) { self_type temporary (*this + ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_matrix &operator += (const matrix_container<C> &m) { plus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix &plus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix& operator -= (const matrix_expression<AE> &ae) { self_type temporary (*this - ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_matrix &operator -= (const matrix_container<C> &m) { minus_assign (m); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_matrix &minus_assign (const matrix_expression<AE> &ae) { matrix_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE coordinate_matrix& operator *= (const AT &at) { matrix_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE coordinate_matrix& operator /= (const AT &at) { matrix_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (coordinate_matrix &m) { if (this != &m) { std::swap (size1_, m.size1_); std::swap (size2_, m.size2_); std::swap (capacity_, m.capacity_); std::swap (filled_, m.filled_); std::swap (sorted_filled_, m.sorted_filled_); std::swap (sorted_, m.sorted_); index1_data_.swap (m.index1_data_); index2_data_.swap (m.index2_data_); value_data_.swap (m.value_data_); } storage_invariants (); } BOOST_UBLAS_INLINE friend void swap (coordinate_matrix &m1, coordinate_matrix &m2) { m1.swap (m2); } // Sorting and summation of duplicates BOOST_UBLAS_INLINE void sort () const { if (! sorted_ && filled_ > 0) { typedef index_triple_array<index_array_type, index_array_type, value_array_type> array_triple; array_triple ita (filled_, index1_data_, index2_data_, value_data_); const typename array_triple::iterator iunsorted = ita.begin () + sorted_filled_; // sort new elements and merge std::sort (iunsorted, ita.end ()); std::inplace_merge (ita.begin (), iunsorted, ita.end ()); // sum duplicates with += and remove array_size_type filled = 0; for (array_size_type i = 1; i < filled_; ++ i) { if (index1_data_ [filled] != index1_data_ [i] || index2_data_ [filled] != index2_data_ [i]) { ++ filled; if (filled != i) { index1_data_ [filled] = index1_data_ [i]; index2_data_ [filled] = index2_data_ [i]; value_data_ [filled] = value_data_ [i]; } } else { value_data_ [filled] += value_data_ [i]; } } filled_ = filled + 1; sorted_filled_ = filled_; sorted_ = true; storage_invariants (); } } // Back element insertion and erasure BOOST_UBLAS_INLINE void push_back (size_type i, size_type j, const_reference t) { size_type element1 = layout_type::element1 (i, size1_, j, size2_); size_type element2 = layout_type::element2 (i, size1_, j, size2_); // must maintain sort order BOOST_UBLAS_CHECK (sorted_ && (filled_ == 0 || index1_data_ [filled_ - 1] < k_based (element1) || (index1_data_ [filled_ - 1] == k_based (element1) && index2_data_ [filled_ - 1] < k_based (element2))) , external_logic ()); if (filled_ >= capacity_) reserve (2 * filled_, true); BOOST_UBLAS_CHECK (filled_ < capacity_, internal_logic ()); index1_data_ [filled_] = k_based (element1); index2_data_ [filled_] = k_based (element2); value_data_ [filled_] = t; ++ filled_; sorted_filled_ = filled_; storage_invariants (); } BOOST_UBLAS_INLINE void pop_back () { // ISSUE invariants could be simpilfied if sorted required as precondition BOOST_UBLAS_CHECK (filled_ > 0, external_logic ()); -- filled_; sorted_filled_ = (std::min) (sorted_filled_, filled_); sorted_ = sorted_filled_ = filled_; storage_invariants (); } // Iterator types private: // Use index array iterator typedef typename IA::const_iterator vector_const_subiterator_type; typedef typename IA::iterator vector_subiterator_type; typedef typename IA::const_iterator const_subiterator_type; typedef typename IA::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i, size_type j) { pointer p = find_element (i, j); BOOST_UBLAS_CHECK (p, bad_index ()); return *p; } public: class const_iterator1; class iterator1; class const_iterator2; class iterator2; typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1; typedef reverse_iterator_base1<iterator1> reverse_iterator1; typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2; typedef reverse_iterator_base2<iterator2> reverse_iterator2; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) const { sort (); for (;;) { size_type address1 (layout_type::address1 (i, size1_, j, size2_)); size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_const_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); vector_const_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); const_subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); const_subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); vector_const_subiterator_type itv (index1_data_.begin () + (it - index2_data_.begin ())); if (rank == 0) return const_iterator1 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return const_iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return const_iterator1 (*this, rank, i, j, itv, it); i = zero_based (*it); } else { if (i >= size1_) return const_iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return const_iterator1 (*this, rank, i, j, itv, it); i = zero_based (*(it - 1)); } else { if (i == 0) return const_iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator1 find1 (int rank, size_type i, size_type j, int direction = 1) { sort (); for (;;) { size_type address1 (layout_type::address1 (i, size1_, j, size2_)); size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); vector_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); vector_subiterator_type itv (index1_data_.begin () + (it - index2_data_.begin ())); if (rank == 0) return iterator1 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return iterator1 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast1 ()) { if (it == it_end) return iterator1 (*this, rank, i, j, itv, it); i = zero_based (*it); } else { if (i >= size1_) return iterator1 (*this, rank, i, j, itv, it); ++ i; } } else /* if (direction < 0) */ { if (layout_type::fast1 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return iterator1 (*this, rank, i, j, itv, it); i = zero_based (*(it - 1)); } else { if (i == 0) return iterator1 (*this, rank, i, j, itv, it); -- i; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) const { sort (); for (;;) { size_type address1 (layout_type::address1 (i, size1_, j, size2_)); size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_const_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); vector_const_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); const_subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); const_subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); const_subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); vector_const_subiterator_type itv (index1_data_.begin () + (it - index2_data_.begin ())); if (rank == 0) return const_iterator2 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return const_iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return const_iterator2 (*this, rank, i, j, itv, it); j = zero_based (*it); } else { if (j >= size2_) return const_iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return const_iterator2 (*this, rank, i, j, itv, it); j = zero_based (*(it - 1)); } else { if (j == 0) return const_iterator2 (*this, rank, i, j, itv, it); -- j; } } } } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator2 find2 (int rank, size_type i, size_type j, int direction = 1) { sort (); for (;;) { size_type address1 (layout_type::address1 (i, size1_, j, size2_)); size_type address2 (layout_type::address2 (i, size1_, j, size2_)); vector_subiterator_type itv_begin (detail::lower_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); vector_subiterator_type itv_end (detail::upper_bound (index1_data_.begin (), index1_data_.begin () + filled_, k_based (address1), std::less<size_type> ())); subiterator_type it_begin (index2_data_.begin () + (itv_begin - index1_data_.begin ())); subiterator_type it_end (index2_data_.begin () + (itv_end - index1_data_.begin ())); subiterator_type it (detail::lower_bound (it_begin, it_end, k_based (address2), std::less<size_type> ())); vector_subiterator_type itv (index1_data_.begin () + (it - index2_data_.begin ())); if (rank == 0) return iterator2 (*this, rank, i, j, itv, it); if (it != it_end && zero_based (*it) == address2) return iterator2 (*this, rank, i, j, itv, it); if (direction > 0) { if (layout_type::fast2 ()) { if (it == it_end) return iterator2 (*this, rank, i, j, itv, it); j = zero_based (*it); } else { if (j >= size2_) return iterator2 (*this, rank, i, j, itv, it); ++ j; } } else /* if (direction < 0) */ { if (layout_type::fast2 ()) { if (it == index2_data_.begin () + zero_based (*itv)) return iterator2 (*this, rank, i, j, itv, it); j = zero_based (*(it - 1)); } else { if (j == 0) return iterator2 (*this, rank, i, j, itv, it); -- j; } } } } class const_iterator1: public container_const_reference<coordinate_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator1, value_type> { public: typedef typename coordinate_matrix::value_type value_type; typedef typename coordinate_matrix::difference_type difference_type; typedef typename coordinate_matrix::const_reference reference; typedef const typename coordinate_matrix::pointer pointer; typedef const_iterator2 dual_iterator_type; typedef const_reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator1 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator1 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type &itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator1 (const iterator1 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { i_ = index1 () + 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE const_iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { i_ = index1 () - 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 begin () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator2 end () const { const self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rbegin () const { return const_reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator2 rend () const { return const_reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator1 &operator = (const const_iterator1 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator1 begin1 () const { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator1 end1 () const { return find1 (0, size1_, 0); } class iterator1: public container_reference<coordinate_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator1, value_type> { public: typedef typename coordinate_matrix::value_type value_type; typedef typename coordinate_matrix::difference_type difference_type; typedef typename coordinate_matrix::true_reference reference; typedef typename coordinate_matrix::pointer pointer; typedef iterator2 dual_iterator_type; typedef reverse_iterator2 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator1 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator1 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator1 &operator ++ () { if (rank_ == 1 && layout_type::fast1 ()) ++ it_; else { i_ = index1 () + 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE iterator1 &operator -- () { if (rank_ == 1 && layout_type::fast1 ()) -- it_; else { i_ = index1 () - 1; if (rank_ == 1) *this = (*this) ().find1 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 begin () const { self_type &m = (*this) (); return m.find2 (1, index1 (), 0); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator2 end () const { self_type &m = (*this) (); return m.find2 (1, index1 (), m.size2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rbegin () const { return reverse_iterator2 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator2 rend () const { return reverse_iterator2 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find1 (0, (*this) ().size1 (), j_), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator1 &operator = (const iterator1 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator1 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator1; }; BOOST_UBLAS_INLINE iterator1 begin1 () { return find1 (0, 0, 0); } BOOST_UBLAS_INLINE iterator1 end1 () { return find1 (0, size1_, 0); } class const_iterator2: public container_const_reference<coordinate_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator2, value_type> { public: typedef typename coordinate_matrix::value_type value_type; typedef typename coordinate_matrix::difference_type difference_type; typedef typename coordinate_matrix::const_reference reference; typedef const typename coordinate_matrix::pointer pointer; typedef const_iterator1 dual_iterator_type; typedef const_reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE const_iterator2 (): container_const_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE const_iterator2 (const self_type &m, int rank, size_type i, size_type j, const vector_const_subiterator_type itv, const const_subiterator_type &it): container_const_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} BOOST_UBLAS_INLINE const_iterator2 (const iterator2 &it): container_const_reference<self_type> (it ()), rank_ (it.rank_), i_ (it.i_), j_ (it.j_), itv_ (it.itv_), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { j_ = index2 () + 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE const_iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { j_ = index2 () - 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) () (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 begin () const { const self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_iterator1 end () const { const self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rbegin () const { return const_reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif const_reverse_iterator1 rend () const { return const_reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE const_iterator2 &operator = (const const_iterator2 &it) { container_const_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_const_subiterator_type itv_; const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator2 begin2 () const { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE const_iterator2 end2 () const { return find2 (0, 0, size2_); } class iterator2: public container_reference<coordinate_matrix>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator2, value_type> { public: typedef typename coordinate_matrix::value_type value_type; typedef typename coordinate_matrix::difference_type difference_type; typedef typename coordinate_matrix::true_reference reference; typedef typename coordinate_matrix::pointer pointer; typedef iterator1 dual_iterator_type; typedef reverse_iterator1 dual_reverse_iterator_type; // Construction and destruction BOOST_UBLAS_INLINE iterator2 (): container_reference<self_type> (), rank_ (), i_ (), j_ (), itv_ (), it_ () {} BOOST_UBLAS_INLINE iterator2 (self_type &m, int rank, size_type i, size_type j, const vector_subiterator_type &itv, const subiterator_type &it): container_reference<self_type> (m), rank_ (rank), i_ (i), j_ (j), itv_ (itv), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator2 &operator ++ () { if (rank_ == 1 && layout_type::fast2 ()) ++ it_; else { j_ = index2 () + 1; if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, 1); } return *this; } BOOST_UBLAS_INLINE iterator2 &operator -- () { if (rank_ == 1 && layout_type::fast2 ()) -- it_; else { j_ = index2 (); if (rank_ == 1) *this = (*this) ().find2 (rank_, i_, j_, -1); } return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index1 () < (*this) ().size1 (), bad_index ()); BOOST_UBLAS_CHECK (index2 () < (*this) ().size2 (), bad_index ()); if (rank_ == 1) { return (*this) ().value_data_ [it_ - (*this) ().index2_data_.begin ()]; } else { return (*this) ().at_element (i_, j_); } } #ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 begin () const { self_type &m = (*this) (); return m.find1 (1, 0, index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif iterator1 end () const { self_type &m = (*this) (); return m.find1 (1, m.size1 (), index2 ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rbegin () const { return reverse_iterator1 (end ()); } BOOST_UBLAS_INLINE #ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION typename self_type:: #endif reverse_iterator1 rend () const { return reverse_iterator1 (begin ()); } #endif // Indices BOOST_UBLAS_INLINE size_type index1 () const { if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size1 (), bad_index ()); return layout_type::index1 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return i_; } } BOOST_UBLAS_INLINE size_type index2 () const { BOOST_UBLAS_CHECK (*this != (*this) ().find2 (0, i_, (*this) ().size2 ()), bad_index ()); if (rank_ == 1) { BOOST_UBLAS_CHECK (layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)) < (*this) ().size2 (), bad_index ()); return layout_type::index2 ((*this) ().zero_based (*itv_), (*this) ().zero_based (*it_)); } else { return j_; } } // Assignment BOOST_UBLAS_INLINE iterator2 &operator = (const iterator2 &it) { container_reference<self_type>::assign (&it ()); rank_ = it.rank_; i_ = it.i_; j_ = it.j_; itv_ = it.itv_; it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator2 &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); // BOOST_UBLAS_CHECK (rank_ == it.rank_, internal_logic ()); if (rank_ == 1 || it.rank_ == 1) { return it_ == it.it_; } else { return i_ == it.i_ && j_ == it.j_; } } private: int rank_; size_type i_; size_type j_; vector_subiterator_type itv_; subiterator_type it_; friend class const_iterator2; }; BOOST_UBLAS_INLINE iterator2 begin2 () { return find2 (0, 0, 0); } BOOST_UBLAS_INLINE iterator2 end2 () { return find2 (0, 0, size2_); } // Reverse iterators BOOST_UBLAS_INLINE const_reverse_iterator1 rbegin1 () const { return const_reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator1 rend1 () const { return const_reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rbegin1 () { return reverse_iterator1 (end1 ()); } BOOST_UBLAS_INLINE reverse_iterator1 rend1 () { return reverse_iterator1 (begin1 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rbegin2 () const { return const_reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE const_reverse_iterator2 rend2 () const { return const_reverse_iterator2 (begin2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rbegin2 () { return reverse_iterator2 (end2 ()); } BOOST_UBLAS_INLINE reverse_iterator2 rend2 () { return reverse_iterator2 (begin2 ()); } private: void storage_invariants () const { BOOST_UBLAS_CHECK (capacity_ == index1_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == index2_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == value_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (filled_ <= capacity_, internal_logic ()); BOOST_UBLAS_CHECK (sorted_filled_ <= filled_, internal_logic ()); BOOST_UBLAS_CHECK (sorted_ == (sorted_filled_ == filled_), internal_logic ()); } size_type size1_; size_type size2_; array_size_type capacity_; mutable array_size_type filled_; mutable array_size_type sorted_filled_; mutable bool sorted_; mutable index_array_type index1_data_; mutable index_array_type index2_data_; mutable value_array_type value_data_; static const value_type zero_; BOOST_UBLAS_INLINE static size_type zero_based (size_type k_based_index) { return k_based_index - IB; } BOOST_UBLAS_INLINE static size_type k_based (size_type zero_based_index) { return zero_based_index + IB; } friend class iterator1; friend class iterator2; friend class const_iterator1; friend class const_iterator2; }; template<class T, class L, std::size_t IB, class IA, class TA> const typename coordinate_matrix<T, L, IB, IA, TA>::value_type coordinate_matrix<T, L, IB, IA, TA>::zero_ = value_type/*zero*/(); }}} #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 5205 ] ] ]
018baa35275e62f0afde5411f5f7b021fb83e417
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/src/algorithms/features/fast/SimpleFAST.cpp
7da5f3b53f9871df3868aad692a0c5c6ac202140
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
#include "SimpleFAST.hpp" #include "FASTFeature.hpp" #include "fast.hpp" namespace uniclop { // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // class SimpleFAST methods implementation args::options_description SimpleFAST::get_options_description() { args::options_description desc("SimpleFAST options"); desc.add_options() ( "fast.barrier", args::value<int>()->default_value(20), "threshold used to detect FAST features") ; return desc; } SimpleFAST::SimpleFAST(args::variables_map &options) { barrier = 20; // default value if ( options.count("fast.barrier") ) barrier = options["fast.barrier"].as<int>(); return; } SimpleFAST::~SimpleFAST() { return; } const vector<FASTFeature> & SimpleFAST::detect_features(const gray8c_view_t& view) { // no need to clear the vectors features it is done inside the functions // find corners fast::corner_detect(view, barrier, detected_features); // keep the best ones fast::nonmax(view, barrier, detected_features, best_features); return best_features; } }
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 60 ] ] ]
dcd1d7aaca05740cfaacbd86469eaef8f78f6133
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlPolynomialCurve3.h
2ac8b0aee69a9b428968291d8439ec145e02944b
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,917
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLPOLYNOMIALCURVE3_H #define WMLPOLYNOMIALCURVE3_H #include "WmlPolynomial1.h" #include "WmlSingleCurve3.h" namespace Wml { template <class Real> class WML_ITEM PolynomialCurve3 : public SingleCurve3<Real> { public: // Construction and destruction. PolynomialCurve3 accepts responsibility // for deleting the input polynomials. PolynomialCurve3 (Polynomial1<Real>* pkXPoly, Polynomial1<Real>* pkYPoly, Polynomial1<Real>* pkZPoly); virtual ~PolynomialCurve3 (); int GetDegree () const; const Polynomial1<Real>* GetXPolynomial () const; const Polynomial1<Real>* GetYPolynomial () const; const Polynomial1<Real>* GetZPolynomial () const; virtual Vector3<Real> GetPosition (Real fTime) const; virtual Vector3<Real> GetFirstDerivative (Real fTime) const; virtual Vector3<Real> GetSecondDerivative (Real fTime) const; virtual Vector3<Real> GetThirdDerivative (Real fTime) const; virtual Real GetVariation (Real fT0, Real fT1, const Vector3<Real>* pkP0 = NULL, const Vector3<Real>* pkP1 = NULL) const; protected: Polynomial1<Real>* m_pkXPoly; Polynomial1<Real>* m_pkYPoly; Polynomial1<Real>* m_pkZPoly; Polynomial1<Real> m_kXDer1, m_kYDer1, m_kZDer1; Polynomial1<Real> m_kXDer2, m_kYDer2, m_kZDer2; Polynomial1<Real> m_kXDer3, m_kYDer3, m_kZDer3; }; typedef PolynomialCurve3<float> PolynomialCurve3f; typedef PolynomialCurve3<double> PolynomialCurve3d; } #endif
[ [ [ 1, 59 ] ] ]
d0b54bf5d4d32998fb7ad2cb0a493d003db0ce18
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Utility/DialogBoxes.cpp
5be6aa1f6b364b207b845f6acaf0311209ff9c55
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
cpp
/* ColorGenerator.cpp Written by Matthew Fisher */ #include "..\\..\\Main.h" #include "DialogBoxes.h" bool DialogBoxes::Load(String &Result, const String &FileTypeDescription, const String &FileTypeExtension) { String Filter = FileTypeDescription; Filter.PushEnd('\0'); Filter += "*."; Filter += FileTypeExtension; Filter.PushEnd('\0'); return Load(Result, Filter); } bool DialogBoxes::Load(String &Result, const String &Filter) { OPENFILENAME ofn; char Filename[512]; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = Filename; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(Filename); ofn.lpstrFilter = Filter.CString(); ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(GetOpenFileName(&ofn) == TRUE) { Result = Filename; return true; } else { return false; } }
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 43 ] ] ]
3b14c5b5705fda6e0d92e5f140bb4a59612a0a32
71d018f8dbcf49cfb07511de5d58d6ad7df816f7
/scistudio/trunk/resrebuild.h
2e11ce1c93d402677159e3738448a415dd2e2b42
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
qq431169079/SciStudio
48225261386402530156fc2fc14ff0cad62174e8
a1fccbdcb423c045078b927e7c275b9d1bcae6b3
refs/heads/master
2020-05-29T13:01:50.800903
2010-09-14T07:10:07
2010-09-14T07:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,329
h
//--------------------------------------------------------------------------- #ifndef DlgResRebuildH #define DlgResRebuildH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "CGAUGES.h" #include "piereg.h" #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TDlgResRebuild : public TForm { __published: // IDE-managed Components TLabel *Status; TPanel *Panel1; TCGauge *ProgressGauge; TButton *OKButton; TPanel *pnlClient; TShape *Shape1; TLabel *Label1; TLabel *Label2; TLabel *Label3; TLabel *Label4; TLabel *Label5; TLabel *Label6; TShape *Shape2; TPie *Pie4; TPie *Pie3; TPie *Pie2; TPie *Pie1; void __fastcall FormClose(TObject *Sender, TCloseAction &Action); void __fastcall FormActivate(TObject *Sender); void __fastcall OKButtonClick(TObject *Sender); private: // User declarations public: // User declarations __fastcall TDlgResRebuild(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TDlgResRebuild *DlgResRebuild; //--------------------------------------------------------------------------- #endif
[ "mageofmarr@d0e240c1-a1d3-4535-ae25-191325aad40e" ]
[ [ [ 1, 44 ] ] ]
6aecf4a845577aef193fbb13db808d4173a77823
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D11/D3D11DomainShaderPipelineStage.h
eab669631b2c3dadc7ecfb7bf4c2642ae39f6cc2
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
7,012
h
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "D3D11PipelineStage.h" namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D11 { /// <summary> /// Domain Shader pipeline stage. /// </summary> public ref class DomainShaderPipelineStage : PipelineStage { public: /// <summary> /// Get the constant buffers used by the domain-shader stage. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSGetConstantBuffers)</para> /// </summary> /// <param name="startSlot">Index into the device's zero-based array to begin retrieving constant buffers from (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1).</param> /// <param name="numBuffers">Number of buffers to retrieve (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - startSlot).</param> /// <returns>Collection of constant buffer objects (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/> to be returned by the method.</returns> ReadOnlyCollection<D3DBuffer^>^ GetConstantBuffers(UInt32 startSlot, UInt32 numBuffers); /// <summary> /// Get an array of sampler state objects from the domain-shader stage. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSGetSamplers)</para> /// </summary> /// <param name="startSlot">Index into a zero-based array to begin getting samplers from (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1).</param> /// <param name="numSamplers">Number of samplers to get from a device context. Each pipeline stage has a total of 16 sampler slots available (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - startSlot).</param> /// <returns>A collection of sampler-state objects (see <see cref="SamplerState"/>)<seealso cref="SamplerState"/>.</returns> ReadOnlyCollection<SamplerState^>^ GetSamplers(UInt32 startSlot, UInt32 numSamplers); /// <summary> /// Get the domain shader currently set on the device. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSGetShader)</para> /// </summary> /// <param name="outClassInstances">A collection of class instance objects (see <see cref="ClassInstance"/>)<seealso cref="ClassInstance"/>.</param> /// <param name="numClassInstances">The number of class-instance elements requested.</param> /// <returns>A domain shader (see <see cref="DomainShader"/>)<seealso cref="DomainShader"/> to be returned by the method.</returns> DomainShader^ GetShader(UInt32 numClassInstances, [System::Runtime::InteropServices::Out] ReadOnlyCollection<ClassInstance^>^ %outClassInstances); /// <summary> /// Get the domain shader currently set on the device. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSGetShader)</para> /// </summary> /// <returns>A domain shader (see <see cref="DomainShader"/>)<seealso cref="DomainShader"/> to be returned by the method.</returns> DomainShader^ GetShader(); /// <summary> /// Get the domain-shader resources. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSGetShaderResources)</para> /// </summary> /// <param name="startSlot">Index into the device's zero-based array to begin getting shader resources from (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1).</param> /// <param name="numViews">The number of resources to get from the device. Up to a maximum of 128 slots are available for shader resources (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - startSlot).</param> /// <returns>A collection of shader resource view objects to be returned by the device.</returns> ReadOnlyCollection<ShaderResourceView^>^ GetShaderResources(UInt32 startSlot, UInt32 numViews); /// <summary> /// Set the constant buffers used by the domain-shader stage. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSSetConstantBuffers)</para> /// </summary> /// <param name="startSlot">Index into the zero-based array to begin setting constant buffers to (ranges from 0 to D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT - 1).</param> /// <param name="constantBuffers">Collection of constant buffers (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/> being given to the device.</param> void SetConstantBuffers(UInt32 startSlot, IEnumerable<D3DBuffer^>^ constantBuffers); /// <summary> /// Set an array of sampler states to the domain-shader stage. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSSetSamplers)</para> /// </summary> /// <param name="startSlot">Index into the device's zero-based array to begin setting samplers to (ranges from 0 to D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT - 1).</param> /// <param name="samplers">A collection of sampler-state objects (see <see cref="SamplerState"/>)<seealso cref="SamplerState"/>. See Remarks.</param> void SetSamplers(UInt32 startSlot, IEnumerable<SamplerState^>^ samplers); /// <summary> /// Set a domain shader to the device. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSSetShader)</para> /// </summary> /// <param name="domainShader">A domain shader (see <see cref="DomainShader"/>)<seealso cref="DomainShader"/>. /// Passing in null disables the shader for this pipeline stage.</param> /// <param name="classInstances">A collection of class-instance objects (see <see cref="ClassInstance"/>)<seealso cref="ClassInstance"/>. /// Each interface used by a shader must have a corresponding class instance or the shader will get disabled. /// Set to null if the shader does not use any interfaces.</param> void SetShader(DomainShader^ domainShader, IEnumerable<ClassInstance^>^ classInstances); /// <summary> /// Set a domain shader to the device. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSSetShader)</para> /// </summary> /// <param name="domainShader">A domain shader (see <see cref="DomainShader"/>)<seealso cref="DomainShader"/>. /// Passing in null disables the shader for this pipeline stage.</param> void SetShader(DomainShader^ domainShader); /// <summary> /// Bind an array of shader resources to the domain-shader stage. /// <para>(Also see DirectX SDK: ID3D11DeviceContext::DSSetShaderResources)</para> /// </summary> /// <param name="startSlot">Index into the device's zero-based array to begin setting shader resources to (ranges from 0 to D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT - 1).</param> /// <param name="shaderResourceViews">Collection of shader resource view objects to set to the device.</param> void SetShaderResources(UInt32 startSlot, IEnumerable<ShaderResourceView^>^ shaderResourceViews); protected: DomainShaderPipelineStage() {} internal: DomainShaderPipelineStage(DeviceContext^ parent) : PipelineStage(parent) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 107 ] ] ]
3f2499f73f9aabf1b8e0c4f4c2462d8ea7600cc3
08c7de4d101008cb44841fa781c94f5bc17d8e20
/src/piece_widget.cpp
c3055985aa3945eebaa6bf84ae0195aa1619a3b8
[]
no_license
CowboyCoders/cow_player
1a661067b070b18b377db136e35aefa3bc035149
ac0f5ba408459fb509105ddac99424e5afeefd22
refs/heads/master
2020-05-20T05:30:34.968270
2010-08-28T12:49:10
2010-08-28T12:49:10
868,351
1
0
null
null
null
null
UTF-8
C++
false
false
5,942
cpp
#include "piece_widget.h" #include "ui_piece_widget.h" #include <QPainter> #include <QToolTip> #include <QMouseEvent> #include <sstream> #include <algorithm> #include <cassert> #include <iostream> // Block size in pixels const int block_size = 5; // Spacing between and before blocks const int margin = 2; piece_widget::piece_widget(QWidget *parent) : QAbstractScrollArea(parent), ui(new Ui::piece_widget), repaint_needed_(false) { ui->setupUi(this); paint_timer_ = new QTimer(this); paint_timer_->setInterval(250); connect(paint_timer_, SIGNAL(timeout()), this, SLOT(timed_repaint())); setMouseTracking(true); // Receive mouse move events even without buttons pressed setBackgroundRole(QPalette::Dark); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); refresh_scrollbar(); } piece_widget::~piece_widget() { delete ui; } void piece_widget::timed_repaint() { repaint_needed_ = false; paint_timer_->stop(); viewport()->update(); // Redraw. TODO: Dont redraw if not neccessary } void piece_widget::set_piece_states(const std::vector<int>& piece_states) { piece_states_ = piece_states; refresh_scrollbar(); request_repaint(); } void piece_widget::set_device_map(const std::map<int,std::string>& map) { device_map_ = map; } void piece_widget::set_colors(const std::vector<QColor>& colors) { colors_ = colors; request_repaint(); } void piece_widget::piece_downloaded(int piece_index, int device) { piece_states_[piece_index] = device; if (!repaint_needed_) { // Check if this piece is being displayed const int item_size = block_size + margin; // Number of columns int ncols = (viewport()->width() - margin) / item_size; // Number of rows int nrows = viewport()->height() / item_size + 2; int npieces = ncols * nrows; // Index of the piece in the upper left corner size_t piece_index = ((verticalScrollBar()->value() - margin) / item_size) * ncols; // Check if inside visible piece range if (piece_index >= piece_index && piece_index <= piece_index + npieces) { request_repaint(); } } } void piece_widget::refresh_scrollbar() { const int item_size = block_size + margin; // Number of columns int ncols = (viewport()->width() - margin) / item_size; // Number of rows int nrows = piece_states_.size() / ncols + 1; // Number of rows in the windows int nrowsvisible = viewport()->height() / item_size; verticalScrollBar()->setRange(0, (nrows - nrowsvisible) * item_size + margin); verticalScrollBar()->setPageStep(nrowsvisible * item_size); verticalScrollBar()->setSingleStep(item_size); // Force a repaint viewport()->repaint(); } int piece_widget::piece_at(const QPoint& pos) const { const int item_size = block_size + margin; // The amout of pixels to offset the pieces with to get smooth scrolling int offset = ((this->verticalScrollBar()->value() - margin) % item_size + margin); // Number of columns int ncols = (this->viewport()->width() - margin) / item_size; // Index of the piece in the upper left corner size_t piece_index = ((this->verticalScrollBar()->value() - margin) / item_size) * ncols; // Number of rows int nrows = std::min<int>((piece_states_.size() - piece_index) / ncols + 2, viewport()->height() / item_size + 2); int corrected_x = (std::max)(pos.x() - 1, 0); int corrected_y = (std::max)(pos.y() + offset - 1, 0); int piece = piece_index + (corrected_y / item_size) * ncols + corrected_x / item_size; return piece < piece_states_.size() ? piece : -1; } void piece_widget::changeEvent(QEvent *e) { QAbstractScrollArea::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void piece_widget::resizeEvent(QResizeEvent* e) { refresh_scrollbar(); } void piece_widget::paintEvent(QPaintEvent* e) { QAbstractScrollArea::paintEvent(e); if(colors_.empty() || piece_states_.empty()) { return; } // Unset repaint flags and timer repaint_needed_ = false; paint_timer_->stop(); QPainter painter(this->viewport()); painter.setPen(Qt::NoPen); const int item_size = block_size + margin; // The amout of pixels to offset the pieces with to get smooth scrolling int offset = -((this->verticalScrollBar()->value() - margin) % item_size + margin); // Number of columns int ncols = (this->viewport()->width() - margin) / item_size; // Index of the piece in the upper left corner size_t piece_index = ((this->verticalScrollBar()->value() - margin) / item_size) * ncols; // Number of rows int nrows = std::min<int>((piece_states_.size() - piece_index) / ncols + 2, viewport()->height() / item_size + 2); for (int r = 0; r < nrows; r++) { for (int c = 0; c < ncols && piece_index < piece_states_.size(); c++) { painter.setBrush(colors_[piece_states_[piece_index++] % colors_.size()]); painter.drawRect(QRect(c*(block_size+margin) + margin, offset + r*(block_size+margin)+margin, block_size, block_size)); } } } void piece_widget::mouseMoveEvent(QMouseEvent* e) { int piece = piece_at(e->pos()); if (piece != -1) { std::stringstream ss; ss << piece << " : " << device_map_[piece_states_[piece]]; QToolTip::showText(e->globalPos(), QString(ss.str().c_str()), this); } else { QToolTip::hideText(); } }
[ "[email protected]", "devnull@localhost" ]
[ [ [ 1, 6 ], [ 8, 54 ], [ 56, 65 ], [ 67, 132 ], [ 134, 187 ], [ 189, 206 ], [ 208, 212 ] ], [ [ 7, 7 ], [ 55, 55 ], [ 66, 66 ], [ 133, 133 ], [ 188, 188 ], [ 207, 207 ] ] ]
326c0f8acdccd46ef99a111404392353166d317b
3cfa229d1d57ce69e0e83bc99c3ca1d005ae38ad
/glome/common/LogWindow.cpp
1c5a8ced2efe01b21977821b52f1d5858cfd7cc8
[]
no_license
chadaustin/sphere
33fc2fe65acf2eb56e35ade3619643faaced7021
0d74cfb268c16d07ebb7cb2540b7b0697c2a127a
refs/heads/master
2021-01-10T13:28:33.766988
2009-11-08T00:38:57
2009-11-08T00:38:57
36,419,098
2
1
null
null
null
null
UTF-8
C++
false
false
8,251
cpp
#include <string.h> #include "LogWindow.hpp" #define STRING_HEIGHT 16 //////////////////////////////////////////////////////////////////////////////// CLogWindow::CLogWindow(HINSTANCE instance, const char* caption) { // zero out the strings m_TopString = 0; m_NumStrings = 0; memset(m_CurrentString, 0, sizeof(m_CurrentString)); memset(m_Strings, 0, sizeof(m_Strings)); InitializeCriticalSection(&StringManagement); // thread routine needs access to parameters m_Instance = instance; m_Caption = new char[strlen(caption) + 1]; strcpy(m_Caption, caption); // create thread DWORD thread_id; CreateThread( NULL, 0, ThreadRoutine, this, 0, &thread_id); } //////////////////////////////////////////////////////////////////////////////// CLogWindow::~CLogWindow() { // tell thread to shut down delete[] m_Caption; } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::WriteString(const char* string) { // combine the two strings char* concatenated = new char[strlen(m_CurrentString) + strlen(string) + 1]; char* delete_me = concatenated; strcpy(concatenated, m_CurrentString); strcat(concatenated, string); // remove sections that end with \n and send them to the window while (strchr(concatenated, '\n')) { *strchr(concatenated, '\n') = 0; AddString(concatenated); concatenated += strlen(concatenated) + 1; } // cut out chunks that are bigger than the max string width while (strlen(concatenated) > MAX_STRING_LENGTH) { // grab the part we're going to send to the window char deleted = concatenated[MAX_STRING_LENGTH]; concatenated[MAX_STRING_LENGTH] = 0; AddString(concatenated); // advance the string pointer to the next chunk concatenated += MAX_STRING_LENGTH; concatenated[0] = deleted; } // put the rest of the string into the current string strcpy(m_CurrentString, concatenated); delete[] delete_me; } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::AddString(const char* string) { EnterCriticalSection(&StringManagement); // if we have reached the end, scroll all other strings back if (m_NumStrings == MAX_STRINGS) { for (int i = 0; i < MAX_STRINGS - 1; i++) strcpy(m_Strings[i], m_Strings[i + 1]); strcpy(m_Strings[MAX_STRINGS - 1], string); } // otherwise, stick the string on the end else { strcpy(m_Strings[m_NumStrings], string); m_NumStrings++; } LeaveCriticalSection(&StringManagement); InvalidateRect(m_Window, NULL, TRUE); RECT ClientRect; GetClientRect(m_Window, &ClientRect); int page_size = ClientRect.bottom / STRING_HEIGHT; UpdateScrollBar(page_size); } //////////////////////////////////////////////////////////////////////////////// DWORD WINAPI CLogWindow::ThreadRoutine(LPVOID parameter) { CLogWindow* This = (CLogWindow*)parameter; // register window class WNDCLASS wc; memset(&wc, 0, sizeof(wc)); wc.lpfnWndProc = WindowProc; wc.hInstance = This->m_Instance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; wc.lpszClassName = "LogWindowClass"; RegisterClass(&wc); // get the font so the window can use it This->m_Font = (HFONT)GetStockObject(DEFAULT_GUI_FONT); // create window This->m_Window = CreateWindowEx( WS_EX_CLIENTEDGE, "LogWindowClass", This->m_Caption, WS_OVERLAPPEDWINDOW | WS_VSCROLL, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, This->m_Instance, NULL); // attach this object to the window SetWindowLong(This->m_Window, GWL_USERDATA, (LONG)This); if (This->m_Window == NULL) return 0; // display window ShowWindow(This->m_Window, SW_SHOW); UpdateWindow(This->m_Window); // message loop MSG msg; while (GetMessage(&msg, This->m_Window, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } //////////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK CLogWindow::WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { // get log window object associated with window CLogWindow* This = (CLogWindow*)GetWindowLong(window, GWL_USERDATA); switch (message) { case WM_VSCROLL: This->OnVScroll(LOWORD(wparam), HIWORD(wparam)); return 0; //////////////////////////////////////////////////////////////////////////// case WM_SIZE: This->OnSize(LOWORD(lparam), HIWORD(lparam)); return 0; //////////////////////////////////////////////////////////////////////////// case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(window, &ps); This->OnPaint(ps.hdc); EndPaint(window, &ps); return 0; } //////////////////////////////////////////////////////////////////////////// default: return DefWindowProc(window, message, wparam, lparam); } } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::OnVScroll(int code, int pos) { RECT ClientRect; GetClientRect(m_Window, &ClientRect); int PageSize = ClientRect.bottom / STRING_HEIGHT; switch (code) { case SB_LINEDOWN: m_TopString++; break; case SB_LINEUP: m_TopString--; break; case SB_PAGEDOWN: m_TopString += PageSize; break; case SB_PAGEUP: m_TopString -= PageSize; break; case SB_TOP: m_TopString = 0; break; case SB_BOTTOM: m_TopString = m_NumStrings - PageSize; break; case SB_THUMBPOSITION: m_TopString = pos; break; case SB_THUMBTRACK: m_TopString = pos; break; } BracketTopString(0, m_NumStrings - PageSize); UpdateScrollBar(PageSize); InvalidateRect(m_Window, NULL, TRUE); } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::OnSize(int cx, int cy) { int page_size = cy / STRING_HEIGHT; BracketTopString(0, m_NumStrings - page_size); UpdateScrollBar(page_size); InvalidateRect(m_Window, NULL, TRUE); } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::OnPaint(HDC dc) { EnterCriticalSection(&StringManagement); RECT ClientRect; GetClientRect(m_Window, &ClientRect); // initialize the DC SaveDC(dc); SetTextColor(dc, RGB(0, 0, 0)); SetBkMode(dc, TRANSPARENT); SelectObject(dc, m_Font); int visible_strings = ClientRect.bottom / STRING_HEIGHT + 1; // draw the strings for (int i = m_TopString; i < m_TopString + visible_strings; i++) if (i < m_NumStrings) { RECT TextRect; TextRect.top = (i - m_TopString) * STRING_HEIGHT; TextRect.left = 0; TextRect.bottom = TextRect.top + STRING_HEIGHT; TextRect.right = ClientRect.right; DrawText(dc, m_Strings[i], -1, &TextRect, DT_LEFT | DT_TOP | DT_SINGLELINE | DT_VCENTER); } // restore the DC and end the painting operation RestoreDC(dc, -1); LeaveCriticalSection(&StringManagement); } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::BracketTopString(int min, int max) { if (m_TopString > max) m_TopString = max; if (m_TopString < min) m_TopString = min; } //////////////////////////////////////////////////////////////////////////////// void CLogWindow::UpdateScrollBar(int page_size) { SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; si.nMin = 0; si.nMax = m_NumStrings; si.nPage = page_size; si.nPos = m_TopString; SetScrollInfo(m_Window, SB_VERT, &si, TRUE); } ////////////////////////////////////////////////////////////////////////////////
[ "surreality@c0eb2ce6-7f40-480a-a1e0-6c4aea08c2c2" ]
[ [ [ 1, 308 ] ] ]
35f2a27b8ce591e9804b456729883ba321915f7f
9eb4d50f6f499d091c036b5745dd17173693b8bf
/src/wii/wii_vb_language.h
4b828d563a83abc970a2030af929a88311f7ac55
[]
no_license
MathewWi/wiirtual-boy
53efab60de238134c43e00502186c1cfe39245ec
4f4a2b75a721e42e036a91956ca32a549ec0a8ff
refs/heads/master
2021-01-01T17:00:37.708274
2011-06-27T15:22:53
2011-06-27T15:22:53
32,204,974
1
1
null
null
null
null
UTF-8
C++
false
false
2,025
h
/* WiirtualBoy : Wii port of the Mednafen Virtual Boy emulator Copyright (C) 2011 raz0red and Arikado 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. */ /* text definitions: control - "U/D = Scroll. A = Select. Home = Exit" menu0 - "Load Cartridge" load0 - "U/D = Scroll. L/R = Page. A = Select. B = Back. Home = Exit" load1 - " cartridges found. displaying " menu1 - "Save state management" save0 - "Auto load:" save1 - "Auto save:" save2 - "Load saved state" menu2 - "Display settings" display0 - "Screen size:" display1 - "Display mode:" menu3 - "Advanced" advanced0 - "Debug mode:" advanced1 - "Top menu exit:" advanced2 - "Wiimote [menu]:" */ #ifndef WII_VB_LANGUAGE_H #define WII_VB_LANGUAGE_H #include <string> using namespace std; class Language { public: Language(); ~Language(); bool languageLoad(char* filepath); string name;//Language name string control; string menu[4]; string load[2]; string save[3]; string display[2]; string advanced[3]; private: string parseTag(string tag, string filebuffer); }; bool generateEnglishLanguageFile(char *filepath); #endif
[ "[email protected]@00a74ce0-9458-8d50-ee98-3d1c5c732d48", "[email protected]@00a74ce0-9458-8d50-ee98-3d1c5c732d48" ]
[ [ [ 1, 30 ], [ 46, 66 ], [ 73, 82 ] ], [ [ 31, 45 ], [ 67, 72 ] ] ]
732dd4fb4e5967e89bfdcdf9f062d2f55138b04a
1960e1ee431d2cfd2f8ed5715a1112f665b258e3
/src/com/coenuminst.cpp
e90892d45663c6b78396e8b0795f630abf7bab2f
[]
no_license
BackupTheBerlios/bvr20983
c26a1379b0a62e1c09d1428525f3b4940d5bb1a7
b32e92c866c294637785862e0ff9c491705c62a5
refs/heads/master
2021-01-01T16:12:42.021350
2009-11-01T22:38:40
2009-11-01T22:38:40
39,518,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,455
cpp
/* * $Id$ * * Generic COM Enum class. * * Copyright (C) 2008 Dorothea Wachmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ #include "os.h" #include "com/coenum.tmpl" using namespace bvr20983::COM; template class COEnum<IEnumFORMATETC,FORMATETC>; template class COEnum<IEnumConnectionPoints,IConnectionPoint*, AddrefAllocFtr<IConnectionPoint*>, ReleaseFreeFtr<IConnectionPoint*>, AddrefFtr<IConnectionPoint*> >; template class COEnum<IEnumOLEVERB,OLEVERB>; template class COEnum<IEnumString,LPOLESTR,StringAllocFtr,StringFreeFtr>; template class COEnum<IEnumConnections,CONNECTDATA,AddrefCPAllocFtr,ReleaseCPFreeFtr,AddrefCPFtr>; /*==========================END-OF-FILE===================================*/
[ "dwachmann@01137330-e44e-0410-aa50-acf51430b3d2" ]
[ [ [ 1, 39 ] ] ]
bbf4b8a5170f9c3c4aced9da785f8004a120e7d6
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgParticle/SegmentPlacer
b16682f85721127e0c5b9c4f5dc7f206c07766c2
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
4,231
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ //osgParticle - Copyright (C) 2002 Marco Jez #ifndef OSGPARTICLE_SEGMENT_PLACER #define OSGPARTICLE_SEGMENT_PLACER 1 #include <osgParticle/Placer> #include <osgParticle/Particle> #include <osg/CopyOp> #include <osg/Object> #include <osg/Vec3> namespace osgParticle { /** A segment-shaped particle placer. To use this placer you have to define a segment, by setting its two vertices (<B>A</B> and <B>B</B>); when an emitter requests a <CODE>SegmentPlacer</CODE> to place a particle, the position is chosen randomly within that segment. */ class SegmentPlacer: public Placer { public: inline SegmentPlacer(); inline SegmentPlacer(const SegmentPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); META_Object(osgParticle, SegmentPlacer); /// get vertex <B>A</B>. inline const osg::Vec3& getVertexA() const; /// Set vertex <B>A</B> of the segment as a vector. inline void setVertexA(const osg::Vec3& v); /// Set vertex <B>A</B> of the segment as three floats. inline void setVertexA(float x, float y, float z); /// get vertex <B>B</B>. inline const osg::Vec3& getVertexB() const; /// Set vertex <B>B</B> of the segment as a vector. inline void setVertexB(const osg::Vec3& v); /// Set vertex <B>B</B> of the segment as three floats. inline void setVertexB(float x, float y, float z); /// Set both vertices. inline void setSegment(const osg::Vec3& A, const osg::Vec3& B); /// Place a particle. This method is called by <CODE>ModularEmitter</CODE>, do not call it manually. inline void place(Particle* P) const; /// return the control position inline osg::Vec3 getControlPosition() const; protected: virtual ~SegmentPlacer() {} SegmentPlacer& operator=(const SegmentPlacer&) { return *this; } private: osg::Vec3 _vertexA; osg::Vec3 _vertexB; }; // INLINE FUNCTIONS inline SegmentPlacer::SegmentPlacer() : Placer(), _vertexA(-1, 0, 0), _vertexB(1, 0, 0) { } inline SegmentPlacer::SegmentPlacer(const SegmentPlacer& copy, const osg::CopyOp& copyop) : Placer(copy, copyop), _vertexA(copy._vertexA), _vertexB(copy._vertexB) { } inline const osg::Vec3& SegmentPlacer::getVertexA() const { return _vertexA; } inline const osg::Vec3& SegmentPlacer::getVertexB() const { return _vertexB; } inline void SegmentPlacer::setSegment(const osg::Vec3& A, const osg::Vec3& B) { _vertexA = A; _vertexB = B; } inline void SegmentPlacer::place(Particle* P) const { P->setPosition(rangev3(_vertexA, _vertexB).get_random()); } inline void SegmentPlacer::setVertexA(const osg::Vec3& v) { _vertexA = v; } inline void SegmentPlacer::setVertexA(float x, float y, float z) { _vertexA.set(x, y, z); } inline void SegmentPlacer::setVertexB(const osg::Vec3& v) { _vertexB = v; } inline void SegmentPlacer::setVertexB(float x, float y, float z) { _vertexB.set(x, y, z); } inline osg::Vec3 SegmentPlacer::getControlPosition() const { return (_vertexA+_vertexB)*0.5f; } } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 136 ] ] ]
4865becf818fb7769511f1bdd179e725bf471dbd
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/hash_set/hash_set_kernel_abstract.h
320c53971af740aad9fdfcaf2562e378ab310c6a
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
6,827
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_HASH_SET_KERNEl_ABSTRACT_ #ifdef DLIB_HASH_SET_KERNEl_ABSTRACT_ #include "../general_hash/general_hash.h" #include "../interfaces/enumerable.h" #include "../interfaces/remover.h" #include "../serialize.h" #include "../memory_manager/memory_manager_kernel_abstract.h" #include <functional> namespace dlib { template < typename T, unsigned long expnum, typename mem_manager = memory_manager<char>::kernel_1a, typename compare = std::less<T> > class hash_set : public enumerable<const T>, public remover<T> { /*! REQUIREMENTS ON T domain must be comparable by compare where compare is a functor compatible with std::less and T must be hashable by general_hash (general_hash is defined in dlib/general_hash) and T must be swappable by a global swap() and T must have a default constructor REQUIREMENTS ON expnum expnum < 32 2^expnum is the number of buckets to hash items of type T into. Note that this is really just a suggestion to the hash table. Implementations are free to manage the table size however is most appropriate. REQUIREMENTS ON mem_manager must be an implementation of memory_manager/memory_manager_kernel_abstract.h or must be an implementation of memory_manager_global/memory_manager_global_kernel_abstract.h or must be an implementation of memory_manager_stateless/memory_manager_stateless_kernel_abstract.h mem_manager::type can be set to anything. POINTERS AND REFERENCES TO INTERNAL DATA swap() and is_member() functions do not invalidate pointers or references to internal data. All other functions have no such guarantee. INITIAL VALUE size() == 0 ENUMERATION ORDER No order is specified. Only that each element will be visited once and only once. WHAT THIS OBJECT REPRESENTS hash_set contains items of type T This object represents an unaddressed collection of items. Every element in a hash_set is unique. Also note that unless specified otherwise, no member functions of this object throw exceptions. definition of equivalent: a is equivalent to b if a < b == false and b < a == false !*/ public: typedef T type; typedef compare compare_type; typedef mem_manager mem_manager_type; hash_set( ); /*! ensures - #*this is properly initialized throws - std::bad_alloc or any exception thrown by T's constructor !*/ virtual ~hash_set( ); /*! ensures - all memory associated with *this has been released !*/ void clear( ); /*! ensures - #*this has its initial value throws - std::bad_alloc or any exception thrown by T's constructor if this exception is thrown then *this is unusable until clear() is called and succeeds !*/ void add ( T& item ); /*! requires - is_member(item) == false ensures - #is_member(item) == true - #item has an initial value for its type - #size() == size() + 1 - #at_start() == true throws - std::bad_alloc or any exception thrown by T's constructor if add() throws then it has no effect !*/ bool is_member ( const T& item ) const; /*! ensures - returns whether or not there is an element in *this equivalent to item !*/ void remove ( const T& item, T& item_copy ); /*! requires - is_member(item) == true - &item != &item_copy (i.e. item and item_copy cannot be the same variable) ensures - #is_member(item) == false - the element in *this equivalent to item has been removed and swapped into #item_copy - #size() == size() - 1 - #at_start() == true !*/ void destroy ( const T& item ); /*! requires - is_member(item) == true ensures - #is_member(item) == false - #size() == size() - 1 - #at_start() == true !*/ void swap ( hash_set& item ); /*! ensures - swaps *this and item !*/ private: // restricted functions hash_set(hash_set&); // copy constructor hash_set& operator=(hash_set&); // assignment operator }; template < typename T, unsigned long expnum, typename mem_manager, typename compare > inline void swap ( hash_set<T,expnum,mem_manager,compare>& a, hash_set<T,expnum,mem_manager,compare>& b ) { a.swap(b); } /*! provides a global swap function !*/ template < typename T, unsigned long expnum, typename mem_manager, typename compare > void deserialize ( hash_set<T,expnum,mem_manager,compare>& item, std::istream& in ); /*! provides deserialization support !*/ } #endif // DLIB_HASH_SET_KERNEl_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 207 ] ] ]
9a66986a0406449d21c9b2e8cf0225f87796315f
638c9b075ac3bfdf3b2d96f1dd786684d7989dcd
/spark/source/SpTurbulenceOp.h
0dcd1d56d5adfc6def2419d659c2055373362355
[]
no_license
cycle-zz/archives
4682d6143b9057b21af9845ecbd42d7131750b1b
f92b677342e75e5cb7743a0d1550105058aff8f5
refs/heads/master
2021-05-27T21:07:16.240438
2010-03-18T08:01:46
2010-03-18T08:01:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,836
h
// ############################################################################# //! SpTurbulenceOp.h : Turbulence stream operator to be used with a stream basis // // Created : Aug 2004 // Copyright : (C) 2004 by Derek Gerstmann // Email : [email protected] // // ############################################################################# // ============================================================================= // // 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. // // ============================================================================= #ifndef SP_GLSL_TURBULENCE_OP_H #define SP_GLSL_TURBULENCE_OP_H #include "SpGridSg.h" #include "SpStreamOperator.h" #include "SpStreamBuffer.h" #include "SpStreamBasis.h" #include "SpGpuProgram.h" #include "SpStreamFeedback.h" #include "SpGlslVertexProgram.h" #include "SpGlslFragmentProgram.h" //---------------------------------------------------------------------------- namespace Spark { //---------------------------------------------------------------------------- //! Turbulence stream operator to be used with a stream basis class //---------------------------------------------------------------------------- class SpTurbulenceOp : public SpStreamOperator { //! Construction: public: SpTurbulenceOp( float fX=1, float fY=1, float fZ=1, float fOctaves = 4, float fIncrement = 0.5f, float fLacunarity = 2.0345f); virtual ~SpTurbulenceOp(); //: Initializes internal data members void initialize( SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy, bool bCreateTextures); //! Access Methods: public: virtual void setInputStream(SpStreamBasis *pkInputStream); virtual void setInputStream(SpStreamInput* pkInputStream); void setOctaves(float fOctaves); float getOctaves() const; void setLacunarity(float fLacunarity); float getLacunarity() const; void setIncrement(float fIncrement); float getIncrement() const; virtual void setOffset(float fX, float fY, float fZ); virtual void getOffset(float& rfX, float& rfY, float& rfZ) const; //! Internal Methods: protected: //: Activates the output stream, if necessary virtual bool enableOutputStream(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //: Sets the necessary state for the stream operation virtual bool setupState(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //: Performs the stream operation virtual bool processStream(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //: Puts the results of the operation into the output stream. virtual bool updateOutputStream(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //: Resets the state virtual bool resetState(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //: Deactivates the output stream, if necessary virtual bool disableOutputStream(SpStreamBuffer* pkBuffer, SpStreamFeedback *pkCopy); //! Internal Data: protected: float m_fOffsetX; float m_fOffsetY; float m_fOffsetZ; float m_fX; float m_fY; float m_fZ; float m_fOctaves; float m_fIncrement; float m_fLacunarity; unsigned int m_uiCurrentPass; unsigned int m_uiMaxOctaves; double * m_adExponents; bool m_bInitialized; bool m_bCreateTextures; bool m_bInputIsBasis; SpGridSg m_kGrid; unsigned int* m_auiTextures; unsigned int m_uiTextureCount; SpGlslVertexProgram* m_pkIdentityVertexProgram; SpGlslFragmentProgram* m_pkAddMultiTextureProgram; }; //---------------------------------------------------------------------------- } // end namespace: Spark #endif
[ [ [ 1, 132 ] ] ]
8c6e399124df3998eda4429501c0ac97904c64c6
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/Engine/Engine/EngineDx.h
71036171e58eb1abd8bd645a604322f60468b1d9
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
h
#ifndef _ENGINE_DX_ #define _ENGINE_DX_ #ifndef _BLEND_OPERATION_NONE_ #include "WrapperDX/Device/State/BlendOperationNone.h" #endif #ifndef _MANAGER_ #include "Engine/Manager/Manager.h" #endif #ifndef _VIEW_PORT_ #include "WrapperDX/Device/ViewPort.h" #endif #ifndef _MATRIX4X4_ #include "Core/Math/Matrix4x4.h" #endif class Device3D; class RenderTarget; class DepthStencil; template< class T >class BlendState; class Manager; class TimeManager; class InputManager; class EngineCamera; class ScreenText; class Light; class RasterizerState; class Engine { protected: // Debug Display bool m_bDisplayText; // Fullscreen resolution, windowed resolution HWND m_hWnd; HINSTANCE m_hInstance; bool m_bFullscreen; unsigned int m_uFullscreenWidth; unsigned int m_uFullscreenHeight; unsigned int m_uWindowedWidth; unsigned int m_uWindowedHeight; // Render Device3D * m_pDevice; RenderTarget * m_pDefaultRenderTarget; DepthStencil * m_pDefaultDepthStencil; BlendState<BlendOperationNone> * m_pDefaultBlendState; ViewPort m_oDefaultViewPort; RasterizerState * m_pDefaultRasterizerState; RasterizerState * m_pRasterizerWireFrame; // Manager Manager * m_pManager[Manager::eManager_COUNT]; // Camera EngineCamera * m_pCamera; float m_fSpeedCam; // Screen Text ScreenText * m_pScreenText; // Light Light * m_pLight; public: Engine(); virtual ~Engine(); virtual HRESULT Create(HWND _hWnd, HINSTANCE _hInstance, unsigned int _uWidth, unsigned int _uHeight, bool _bFullscreen = false); virtual HRESULT Destroy(); virtual void Update() = 0; virtual HRESULT ToggleFullScreen(); virtual HRESULT Resize(unsigned int _uWidth, unsigned int _uHeight); unsigned int GetWidth(); unsigned int GetHeight(); // render virtual void RenderText(); virtual void BeginRender(); virtual void Render() = 0; virtual void EndRender(); // input void SetMousePosition(int _x, int _y); virtual void UpdateKeyboard(); virtual void UpdateMouse(); // Manager void UpdateManager(); TimeManager * GetTimeManager() const; InputManager * GetInputManager() const; }; #endif // _ENGINE_DX_
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
[ [ [ 1, 101 ] ] ]
203af3bf62e7a221c94729522de05a18dbdc8f9d
ed2a1c83681d8ed2d08f8a74707536791e5cd057
/d3d8.DLL/Built-in Extension Files/Screenshot Files/Screenshot.cpp
899cb45c5a1471f53ec7620c30c57af70e7a3d51
[ "Apache-2.0" ]
permissive
MartinMReed/XenDLL
e33d5c27187e58fd4401b2dbcaae3ebab8279bc2
51a05c3cec7b2142f704f2ea131202a72de843ec
refs/heads/master
2021-01-10T19:10:40.492482
2007-10-31T16:38:00
2007-10-31T16:38:00
12,150,175
13
2
null
null
null
null
UTF-8
C++
false
false
11,401
cpp
#include "../../CustomDevice Files/CustomDevice.h" #include "Capture Files\blit.h" #include "Capture Files\BMP Functions.h" //#include "Capture Files\DIB Functions.h" #include "Capture Files\JPG Functions.h" Screenshot* g_Screenshot = NULL; //------------------------------------------------------- // adapted from xenhook 5.0 by Achilles and v0id //------------------------------------------------------- bool Screenshot::Initialize(void) { initialized = false; // if the folder does not exist, create it if (GetFileAttributes("XenDLL Files/Extensions/Screenshot/") == 0xFFFFFFFF) CreateDirectory("XenDLL Files/Extensions/Screenshot/", NULL); const char* data = NULL; // read the config file if (data = _ReadConfigItem("filePath", "XenDLL Files/Extensions/Screenshot/Screenshot.xml")) { if (data[strlen(data)-1] == '\\' || data[strlen(data)-1] == '/') filePath = _restring(data, 0, strlen(data)-1); else filePath = _restring(data, 0, strlen(data)); } else { _WriteConfigItem("filePath", "screenshots", "XenDLL Files/Extensions/Screenshot/Screenshot.xml"); } // if the folder does not exist, create it if (GetFileAttributes(filePath) == 0xFFFFFFFF) CreateDirectory(filePath, NULL); // read the config file if (data = _ReadConfigItem("screenshotQuality", "XenDLL Files/Extensions/Screenshot/Screenshot.xml")) { screenshotQuality = atoi(data); } else { char buffer[256]; sprintf_s(buffer, sizeof(buffer), "%i",screenshotQuality ); _WriteConfigItem("screenshotQuality", buffer, "XenDLL Files/Extensions/Screenshot/Screenshot.xml"); } // read the config file data = _ReadConfigItem("includeGUI", "XenDLL Files/Extensions/Screenshot/Screenshot.xml"); if (data == NULL || _stricmp(data, "true") == 0) { includeGUI = true; } if (data == NULL) { _WriteConfigItem("includeGUI", "true", "XenDLL Files/Extensions/Screenshot/Screenshot.xml"); } /// initialized = true; SetupScreenshot(); return initialized; } //------------------------------------------------------- // adapted from xenhook 5.0 by Achilles and v0id //------------------------------------------------------- void Screenshot::SetupScreenshot(void) { if (initialized == false) return; // find the game window HWND hwnd = FindWindow(NULL, NULL); // get from HGooey IDirect3DDevice8* device = _D3DDevice(); // unscale the screen size screenshotWidth = (UINT)floor(_W2X((float)_ScreenWidth())); screenshotHeight = (UINT)floor(_H2Y((float)_ScreenHeight())); // make sure height and width are even for texture copying if (screenshotWidth % 2 == 1) screenshotWidth++; if (screenshotHeight % 2 == 1) screenshotHeight++; IDirect3DSurface8* pBB = NULL; device->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBB); D3DSURFACE_DESC desc; pBB->GetDesc(&desc); pBB->Release(); HRESULT hr = device->CreateTexture(screenshotWidth, screenshotHeight, 1, D3DUSAGE_RENDERTARGET, desc.Format, D3DPOOL_DEFAULT,&screenshotCopyTexture); if (FAILED(hr)) { hr = D3DXCreateTexture(device, screenshotWidth, screenshotHeight, 1, D3DUSAGE_RENDERTARGET, desc.Format, D3DPOOL_DEFAULT,&screenshotCopyTexture); if (FAILED(hr)) hr = device->CreateTexture(screenshotWidth, screenshotHeight, 1, D3DUSAGE_RENDERTARGET | D3DUSAGE_SOFTWAREPROCESSING, desc.Format, D3DPOOL_DEFAULT,&screenshotCopyTexture); } screenshotCopyTexture->GetLevelDesc(0, &desc); if (FAILED(device->CreateRenderTarget(screenshotWidth, screenshotHeight, desc.Format, D3DMULTISAMPLE_NONE, false, &screenshotRenderSurface))) device->CreateRenderTarget(screenshotWidth, screenshotHeight, desc.Format, D3DMULTISAMPLE_NONE, false, &screenshotRenderSurface); screenshotRenderSurface->GetDesc(&desc); device->CreateImageSurface(screenshotWidth, screenshotHeight, desc.Format, &screenshotFinalSurface); SetRect(&image, 0, 0, screenshotWidth, screenshotHeight); } //------------------------------------------------------- // adapted from xenhook 5.0 by Achilles and v0id //------------------------------------------------------- void Screenshot::CaptureScreen(void) { if (initialized == false) return; // find the game window HWND hwnd = FindWindow(NULL, NULL); // get from HGooey IDirect3DDevice8* device = _D3DDevice(); D3DSURFACE_DESC desc; IDirect3DSurface8* srcSurf = NULL; device->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &srcSurf); srcSurf->GetDesc(&desc); IDirect3DSurface8* pCopySurface = NULL; screenshotCopyTexture->GetSurfaceLevel(0, &pCopySurface); RECT rWindow; SetRect(&rWindow, image.left, image.top, screenshotWidth, screenshotHeight); POINT points[] = {{0, 0}}; HRESULT hr = device->CopyRects(srcSurf, &rWindow, 1, pCopySurface, points); srcSurf->Release(); // get copy surface info - needed for scaling on cards with limited texture support // to calc text coordinates pCopySurface->GetDesc(&desc); //save the current render target IDirect3DSurface8* pSavedRenderTarget = NULL; device->GetRenderTarget(&pSavedRenderTarget); // save the current stencil buffer IDirect3DSurface8* pSavedStencilBuffer = NULL; device->GetDepthStencilSurface(&pSavedStencilBuffer); // set new render target for shrinkage device->SetRenderTarget(screenshotRenderSurface, NULL); // blit to our new render target RECT rect = {0, 0, screenshotWidth, screenshotHeight}; D3DXVECTOR4 srcTextureCoodRect; srcTextureCoodRect.x = 0; srcTextureCoodRect.y = 0; srcTextureCoodRect.z = (float)rWindow.right/screenshotWidth; //copy surface to backbuffer ratio srcTextureCoodRect.w = (float)rWindow.bottom/screenshotHeight; BlitRect(device, screenshotCopyTexture, &rect, &srcTextureCoodRect); hr = device->SetRenderTarget(pSavedRenderTarget, pSavedStencilBuffer); pSavedStencilBuffer->Release(); pSavedRenderTarget->Release(); SetRect(&rWindow, 0, 0, screenshotWidth, screenshotHeight); device->CopyRects(screenshotRenderSurface, &rWindow, 1, screenshotFinalSurface, points); // lock the surface for reading D3DLOCKED_RECT lockedRect; screenshotFinalSurface->LockRect(&lockedRect, NULL, D3DLOCK_READONLY); screenshotFinalSurface->GetDesc(&desc); UINT iBpp; if (desc.Format == D3DFMT_A8R8G8B8 || desc.Format == D3DFMT_X8R8G8B8) iBpp = 4; else iBpp = 2; int iBufsize = iBpp * (image.right - image.left) * (image.bottom - image.top); int iRowWidth = iBpp * (image.right - image.left); char* pBitData = new char[iBufsize]; for (int y = 0; y < (int)(image.bottom - image.top); y++) memcpy(pBitData + y*iRowWidth, (char*)lockedRect.pBits + y*lockedRect.Pitch, iRowWidth); // unlock the surface screenshotFinalSurface->UnlockRect(); HBITMAP hBitmap = CreateBitmap((image.right - image.left), (image.bottom - image.top), 1, iBpp*8, pBitData); delete[] pBitData; if (hBitmap) { HANDLE hDib = (HANDLE)ConvertDDBtoDIB(hwnd, hBitmap, NULL); DeleteObject(hBitmap); if (hDib) { char buffer[MAX_PATH]; time_t rawTime; tm timeInfo; time(&rawTime); localtime_s(&timeInfo, &rawTime); sprintf_s(buffer, 256, "%s/screen_%i-%i-%i_%i.%i.%i.jpg", filePath, timeInfo.tm_year + 1900, timeInfo.tm_mon, timeInfo.tm_mday, timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec); JpegFromDib(hDib, screenshotQuality, buffer); DeleteObject(hDib); } } pCopySurface->Release(); } //------------------------------------------------------- // the device was lost (ie ALT+TAB to minimize the game) //------------------------------------------------------- void Screenshot::LostDevice(void) { if (initialized == false) return; ClearScreenshot(); } //------------------------------------------------------- // //------------------------------------------------------- void Screenshot::ResetDevice(void) { if (initialized == false) return; SetupScreenshot(); } //------------------------------------------------------- // called before any extensions draw on the screen //------------------------------------------------------- void Screenshot::PreRender(void) { if (initialized == false) return; // DO NOT DRAW IN HERE, ALL DRAWING IS DISABLED. // ONLY DRAW IN Render() if (captureScreen) { CaptureScreen(); captureScreen = false; capTakenAt = timeGetTime(); } } //------------------------------------------------------- // do your drawing / call your main code in here //------------------------------------------------------- void Screenshot::Render(void) { if (initialized == false) return; // draw text or execute/call main code if (capTakenAt + 3000 > timeGetTime()) { _DrawText("Screen Shot Saved", 0.0f, 0.0f, 1, COLOR_PURPLE, false, NULL); } else { capTakenAt = 0; } } //------------------------------------------------------- // handle keyboard input // // cKey = DIK_[Key] // bDown = pressed down if true, released if false // // return true = send command to game // return false = do not send the command to the game // // DirectInput Key-Identifier Table: // http://calc.xentales.com/HGooey/DIK.html or // http://www.xentales.com/calc/HGooey/DIK.html //------------------------------------------------------- bool Screenshot::HandleKeyboard(void) { if (initialized == false) return true; KeyInfo xKey = _Key(); if (xKey.bDown) // key is pressed down { if (xKey.cKey == DIK_SYSRQ) { return false; } } else if (xKey.bRepeat == false) // key has been released { if (xKey.cKey == DIK_SYSRQ) { captureScreen = true; return false; } } return true; } //------------------------------------------------------- // //------------------------------------------------------- Screenshot::Screenshot(void) { initialized = false; includeGUI = false; captureScreen = false; capTakenAt = 0; SetRect(&image, 0, 0, 0, 0); filePath = "screenshots"; screenshotQuality = 100; screenshotWidth = 0; screenshotHeight = 0; screenshotCopyTexture = NULL; screenshotRenderSurface = NULL; screenshotFinalSurface = NULL; } //------------------------------------------------------- // adapted from xenhook 5.0 by Achilles and v0id //------------------------------------------------------- void Screenshot::ClearScreenshot(void) { if (screenshotCopyTexture) { screenshotCopyTexture->Release(); screenshotCopyTexture = NULL; } if (screenshotRenderSurface) { screenshotRenderSurface->Release(); screenshotRenderSurface = NULL; } if (screenshotFinalSurface) { screenshotFinalSurface->Release(); screenshotFinalSurface = NULL; } } //------------------------------------------------------- // //------------------------------------------------------- bool Screenshot::Uninitialize(void) { initialized = false; if (filePath) { delete[] filePath; filePath = NULL; } ClearScreenshot(); return initialized; } //------------------------------------------------------- // //------------------------------------------------------- Screenshot::~Screenshot(void) { Uninitialize(); }
[ [ [ 1, 437 ] ] ]
629d62826b0f87f3a6770890d9dd211682599a67
df96cbce59e3597f2aecc99ae123311abe7fce94
/watools/common/v8_wrapper.h
67b43193d47b618db758d96f7881801fba10ff70
[]
no_license
abhishekbhalani/webapptools
f08b9f62437c81e0682497923d444020d7b319a2
93b6034e0a9e314716e072eb6d3379d92014f25a
refs/heads/master
2021-01-22T17:58:00.860044
2011-12-14T10:54:11
2011-12-14T10:54:11
40,562,019
2
0
null
null
null
null
UTF-8
C++
false
false
14,225
h
#ifndef __V8_WRAPPER__H__ #define __V8_WRAPPER__H__ #include <string> #include <sstream> #include <boost/static_assert.hpp> #include <v8.h> #include <jsWrappers/jsGlobal.h> #include <weLogger.h> class js_dom_Node; class js_dom_NodeList; class js_html2_HTMLCollection; class js_html2_HTMLDocument; class js_html2_HTMLElement; namespace v8_wrapper { class iterator_dfs; class tree_node; typedef js_html2_HTMLDocument jsDocument; typedef boost::shared_ptr<tree_node> tree_node_ptr; typedef std::vector<tree_node_ptr> tree_node_list; /** * This template class is data structure for javascript wrapped DOM. */ template <class T> class dom_data { public: }; template <> class dom_data <js_html2_HTMLDocument> { public: dom_data():m_opened(false) {} std::ostringstream m_strbuf; bool m_opened; v8_wrapper::tree_node_ptr m_execution_point; }; /** * Tree structure and iteration for DOM */ class tree_node : public boost::enable_shared_from_this<tree_node> { public: tree_node():m_tag(HTML_TAG___UNKNOWN_TAG__) {} tree_node(const tree_node& copy):m_child_list(copy.m_child_list),m_tag(copy.m_tag),m_this(copy.m_this) {} virtual ~tree_node() {} /** * Creates DFS iterator for DOM node children * @return v8_wrapper::iterator_dfs */ virtual iterator_dfs begin_dfs(); /** * Creates end() of iterator element for compatibility with STL methods * @return v8_wrapper::iterator_dfs */ virtual iterator_dfs end_dfs(); /** * Prints list of attributes * @return const std::string */ virtual const std::string get_fields() { return std::string(); }; /** * Prints tag from current node. Ex. <input disabled="0" name="lr" readOnly="0" type="hidden" value="213" > * @return const std::string */ const std::string get_dump() { std::ostringstream _out; _out << "<" << get_tag_name(m_tag) << " " << get_fields() << ">"; return _out.str(); }; /** * Removes all children recursively and clear these parent pointers */ void clear_children(); tree_node_ptr m_parent; tree_node_list m_child_list; tree_node_list m_fields; HTML_TAG m_tag; v8::Persistent<v8::Object> m_this; webEngine::html_entity_ptr m_entity; }; /** * Depth-first search iterator for node */ class iterator_dfs: public boost::iterator_facade <iterator_dfs, tree_node_ptr, boost::forward_traversal_tag> { public: /** * Create iterator from a tree_node. This is equivalent for STL begin() * @param tree_node & */ explicit iterator_dfs(tree_node&); /** * Create end() iterator. */ iterator_dfs(); /** * Returns curren deep level * @return size_t */ size_t current_level() const { return m_stack.size(); } protected: friend class boost::iterator_core_access; virtual void increment(); virtual tree_node_ptr & dereference() const; virtual bool equal(iterator_dfs const& other) const; private: tree_node_ptr m_node; tree_node_list::iterator m_it; vector< tree_node_list::iterator > m_stack; bool m_end; }; /** * Create JavaScript object for class T and put objToWrap into InternalField * @param tree_node * objToWrap * @return */ template<class T> v8::Handle<v8::Object> wrap_object(v8_wrapper::tree_node *objToWrap); /** * Creates tree_node from entity * @param webEngine::html_entity_ptr objToWrap * @return v8_wrapper::tree_node_ptr */ v8_wrapper::tree_node_ptr wrap_entity(webEngine::html_entity_ptr objToWrap); /** * Convert html_entity_ptr DOM to JS DOM. If parent not pecofied, will be created jsDocument. Returns parent node. * @param const webEngine::html_entity_ptr & dom * @param tree_node_ptr parent * @return v8_wrapper::tree_node_ptr */ v8_wrapper::tree_node_ptr wrap_dom(const webEngine::html_entity_ptr& dom, v8_wrapper::tree_node_ptr parent = v8_wrapper::tree_node_ptr() ); /** * Register all wrapped JS classes. This function automatically generated. * @param v8::Persistent<v8::ObjectTemplate> global */ void RegisterAll(v8::Persistent<v8::ObjectTemplate> global); /** * Updates standard document lists: images, applets, forms, links, anchors * @param jsDocument & doc */ void update_document(jsDocument& doc); /** * Check tree_node for attribute "name". Returns object or Undefined * @param tree_node * treenode * @param const std::string & name * @return v8::Handle<v8::Value> */ v8::Handle<v8::Value> check_object_name(v8_wrapper::tree_node* treenode, const std::string &name); /** * Main wrapper class. This class implements JavaScript constraction and destruction of the wrapped objects. */ template <class T> class Registrator : public virtual tree_node { public: Registrator() { LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8_wrapper::Registrator<> 0x") << std::hex << (size_t)this << _T(" construct ") << std::string(typeid(T).name()) ); } virtual ~Registrator() { if( !this->m_this.IsEmpty() ) { #if 0// _DEBUG if( !this->m_this.IsWeak() ) { LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8_wrapper::Registrator<> 0x") << std::hex << (size_t)this << _T(" handle is not weak ") << std::string(typeid(T).name()) ); } else if( !this->m_this.IsNearDeath()) { LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8_wrapper::Registrator<> 0x") << std::hex << (size_t)this << _T(" handle is not near death ") << std::string(typeid(T).name()) ); } #endif if( this->m_this->InternalFieldCount() > 0 ) { this->m_this->SetInternalField(0, v8::External::New(NULL)); } } LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8_wrapper::Registrator<> 0x") << std::hex << (size_t)this << _T(" ~destruct ") << std::string(typeid(T).name()) ); } /** * Returns JavaScript object template for creating new JavaScript objects */ static v8::Persistent<v8::FunctionTemplate> GetTemplate(); /** * This method allows to add custom handlers into python-generated GetTemplate() */ inline static void AdditionalHandlersGetTemplate(v8::Local<v8::ObjectTemplate> instance, v8::Local<v8::ObjectTemplate> prototype) {} /** * This Constructor() must be calling from JavaScript to create new ojects. */ static v8::Handle<v8::Value> Constructor(const v8::Arguments& args) { if (!args.IsConstructCall()) return v8::ThrowException(v8::String::New("DOM object constructor cannot be called as a function.")); T* obj = new T(); LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8 JavaScript binded call 0x") << std::hex << (size_t)obj << _T(" constructor ") << std::string(typeid(T).name()) ); obj->m_this = v8::Persistent<v8::Object>::New(wrap_object< T >(obj)); //obj->m_this.MakeWeak( obj , Registrator< T >::Destructor); return obj->m_this; } /** * Destructor() for calling from V8 garbage collector */ static void Destructor(v8::Persistent<v8::Value> object, void* ) { void* ptr = v8::Local<v8::External>::Cast(object->ToObject()->GetInternalField(0))->Value(); LOG4CXX_TRACE(webEngine::iLogger::GetLogger(), _T("v8 JavaScript binded call 0x") << std::hex << (size_t)ptr << _T(" destructor ") << std::string(typeid(T).name())); object->ToObject()->SetInternalField(0, v8::External::New(NULL)); if(ptr) delete static_cast< T *>(ptr); } dom_data<T> m_data; }; template<class T> typename v8::Handle<v8::Value> IndexedPropertyGetter_handler(uint32_t index, const v8::AccessorInfo& info); template<class T> typename v8::Handle<v8::Value> NamedPropertyGetter_handler(v8::Local<v8::String> property, const v8::AccessorInfo& info); template<class T> typename v8::Handle<v8::Integer> NamedPropertyQuery_handler(v8::Local<v8::String> property, const v8::AccessorInfo& info); template<class T> typename v8::Handle<v8::Array> NamedPropertyEnumerator_handler(const v8::AccessorInfo& info); template<> void v8_wrapper::Registrator<js_dom_NodeList>::AdditionalHandlersGetTemplate(v8::Local<v8::ObjectTemplate> instance, v8::Local<v8::ObjectTemplate> prototype) { instance->SetIndexedPropertyHandler(IndexedPropertyGetter_handler<js_dom_NodeList>); } template<> void v8_wrapper::Registrator<jsDocument>::AdditionalHandlersGetTemplate(v8::Local<v8::ObjectTemplate> instance, v8::Local<v8::ObjectTemplate> prototype) { instance->SetNamedPropertyHandler(NamedPropertyGetter_handler<jsDocument>); } template<> void v8_wrapper::Registrator<js_html2_HTMLCollection>::AdditionalHandlersGetTemplate(v8::Local<v8::ObjectTemplate> instance, v8::Local<v8::ObjectTemplate> prototype) { instance->SetIndexedPropertyHandler(IndexedPropertyGetter_handler<js_html2_HTMLCollection>); instance->SetNamedPropertyHandler(NamedPropertyGetter_handler<js_html2_HTMLCollection>); } template<class T> v8::Handle<v8::Value> getElementsByTagName(v8_wrapper::tree_node* root, const std::string& tagname) { T* result = new T(); result->m_this = v8::Persistent<v8::Object>::New(wrap_object< T >(result)); HTML_TAG val_tag = find_tag_by_name(tagname); for(v8_wrapper::iterator_dfs it = root->begin_dfs(); it != root->end_dfs(); ++it) { if((*it) && (*it)->m_tag == val_tag) result->m_child_list.push_back(*it); } unsigned long *len = const_cast<unsigned long*>(&result->length); *len = result->m_child_list.size(); return result->m_this; } template<class T> v8::Handle<v8::Object> wrap_object(v8_wrapper::tree_node *objToWrap) { v8::HandleScope scope; v8::Local<v8::Object> _instance = v8_wrapper::Registrator<T>::GetTemplate()->GetFunction()->NewInstance(); // _instance->SetInternalField(0, v8::External::New(objToWrap)); return scope.Close(_instance); } // for custom attribute get/set template<class J, int N> class CustomAttribute { public: static v8::Handle<v8::Value> static_get(v8::Local<v8::String> property, const v8::AccessorInfo &info) { return v8::Handle<v8::Value>(); }; static void static_set(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info) {}; static const bool implemented = false; }; template<> class CustomAttribute<js_html2_HTMLElement, 7 /*innerHTML*/> { public: static v8::Handle<v8::Value> static_get(v8::Local<v8::String> property, const v8::AccessorInfo &info); static void static_set(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info); static const bool implemented = true; }; template<> class CustomAttribute<js_html2_HTMLDocument, 12 /*innerHTML*/> { public: static v8::Handle<v8::Value> static_get(v8::Local<v8::String> property, const v8::AccessorInfo &info); static void static_set(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info); static const bool implemented = true; }; template<> class CustomAttribute<js_dom_Node, 6 /*firstChild*/> { public: static v8::Handle<v8::Value> static_get(v8::Local<v8::String> property, const v8::AccessorInfo &info); static void static_set(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info); static const bool implemented = true; }; /////// casting c++ types from/to v8::Value //////////////// From v8::Value template <typename T> inline T Get(const v8::Local<v8::Value>& val); template <> inline std::string Get(const v8::Local<v8::Value>& val) { if(val->IsString()) { v8::String::Utf8Value utf8(val); return *utf8; } return std::string(); } template <> inline int Get(const v8::Local<v8::Value>& val) { return val->Int32Value(); } template <> inline long Get(const v8::Local<v8::Value>& val) { return val->Int32Value(); } template <> inline unsigned int Get(const v8::Local<v8::Value>& val) { return val->Uint32Value(); } template <> inline bool Get(const v8::Local<v8::Value>& val) { return val->BooleanValue(); } template <> inline unsigned long Get(const v8::Local<v8::Value>& val) { return val->Uint32Value(); } template <> inline unsigned short int Get(const v8::Local<v8::Value>& val) { return val->Uint32Value(); } template <> inline v8::Handle<v8::Value> Get(const v8::Local<v8::Value>& val) { return v8::Handle<v8::Value>(val); } template <> inline double Get(const v8::Local<v8::Value>& val) { return val->NumberValue(); } //////////////// to v8::Value template <typename T> inline v8::Handle<v8::Value> Set(const T& val); template <> inline v8::Handle<v8::Value> Set(const v8::Handle<v8::Value>& val) { return val; } template <> inline v8::Handle<v8::Value> Set(const bool& val) { return v8::Handle<v8::Value>(v8::Boolean::New(val)); } template <> inline v8::Handle<v8::Value> Set(const long int& val) { return v8::Handle<v8::Value>(v8::Int32::New(val)); } template <> inline v8::Handle<v8::Value> Set(const short int& val) { return v8::Handle<v8::Value>(v8::Int32::New(val)); } template <> inline v8::Handle<v8::Value> Set(const short unsigned int& val) { return v8::Handle<v8::Value>(v8::Uint32::New(val)); } template <> inline v8::Handle<v8::Value> Set(const long unsigned int& val) { return v8::Handle<v8::Value>(v8::Uint32::New(val)); } template <> inline v8::Handle<v8::Value> Set(const double& val) { return v8::Handle<v8::Value>(v8::Number::New(val)); } template <> inline v8::Handle<v8::Value> Set(const std::string& val) { return v8::Handle<v8::Value>(v8::String::New(val.c_str())); } } //namespace v8_wrapper #endif
[ "stinger911@79c36d58-6562-11de-a3c1-4985b5740c72" ]
[ [ [ 1, 464 ] ] ]
4c1be3e26a6a9cdb0a2d7c4aff0498ff4b343770
515e917815568d213e75bfcbd3fb9f0e08cf2677
/tengine/sound/sound.cpp
096338d4c8ebcdb5d82819b715c10a12b2cced13
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
7,136
cpp
#include "sound.h" #include <stdio.h> #include <SDL.h> #include <SDL_mixer.h> #include <strutils.h> CSoundLibrary* CSoundLibrary::s_pSoundLibrary = NULL; float CSoundLibrary::s_flMasterVolume = 1; static CSoundLibrary g_SoundLibrary = CSoundLibrary(); CSoundLibrary::CSoundLibrary() { s_pSoundLibrary = this; SDL_Init(SDL_INIT_AUDIO); if(Mix_OpenAudio(22050, AUDIO_S16, 2, 4096)) SDL_Quit(); Mix_ChannelFinished(&CSoundLibrary::ChannelFinished); } CSoundLibrary::~CSoundLibrary() { for (size_t i = 0; i < m_apSounds.size(); i++) { delete m_apSounds[i]; } Mix_CloseAudio(); s_pSoundLibrary = NULL; } size_t CSoundLibrary::AddSound(const tstring& pszFilename) { size_t iSound = FindSound(pszFilename); if (iSound != ~0) return iSound; m_apSounds.push_back(new CSound(pszFilename)); iSound = m_apSounds.size()-1; return iSound; } CSound* CSoundLibrary::GetSound(size_t i) { if (i >= m_apSounds.size()) return NULL; return m_apSounds[i]; } size_t CSoundLibrary::FindSound(const tstring& pszFilename) { for (size_t i = 0; i < m_apSounds.size(); i++) { if (m_apSounds[i]->m_sFilename == pszFilename) return i; } return ~0; } void CSoundLibrary::PlaySound(CBaseEntity* pEntity, const tstring& pszFilename, float flVolume, bool bLoop) { if (Get()->m_aiActiveSounds.find(pEntity) != Get()->m_aiActiveSounds.end()) { if (Get()->m_aiActiveSounds[pEntity].find(pszFilename) != Get()->m_aiActiveSounds[pEntity].end()) StopSound(pEntity, pszFilename); } size_t iSound = Get()->FindSound(pszFilename); if (iSound >= Get()->m_apSounds.size()) return; CSound* pSound = Get()->m_apSounds[iSound]; if( pSound->m_pSound == NULL ) return; int iChannel = Mix_PlayChannel(-1, pSound->m_pSound, bLoop?-1:0); if (iChannel < 0) return; Get()->m_aiActiveSounds[pEntity][pszFilename].iChannel = iChannel; Get()->m_aiActiveSounds[pEntity][pszFilename].flVolume = flVolume; Mix_Volume(Get()->m_aiActiveSounds[pEntity][pszFilename].iChannel, (int)(flVolume*s_flMasterVolume*MIX_MAX_VOLUME)); } void CSoundLibrary::StopSound(CBaseEntity* pEntity, const tstring& pszFilename) { if (!pEntity) { // Un-register the channel finish callback for the time being because we clear the active sound list by ourselves. Mix_ChannelFinished(NULL); eastl::map<CBaseEntity*, eastl::map<tstring, CSoundInstance> >::iterator it = Get()->m_aiActiveSounds.begin(); while (it != Get()->m_aiActiveSounds.end()) { eastl::map<tstring, CSoundInstance>::iterator it2 = Get()->m_aiActiveSounds[(*it).first].begin(); while (it2 != Get()->m_aiActiveSounds[(*it).first].end()) { Mix_HaltChannel(Get()->m_aiActiveSounds[(*it).first][(*it2).first].iChannel); it2++; } it++; } Get()->m_aiActiveSounds.clear(); Mix_ChannelFinished(&CSoundLibrary::ChannelFinished); return; } if (Get()->m_aiActiveSounds.find(pEntity) == Get()->m_aiActiveSounds.end()) return; if (pszFilename != _T("")) { // Un-register the channel finish callback for the time being because we clear the active sound list by ourselves. Mix_ChannelFinished(NULL); eastl::map<tstring, CSoundInstance>::iterator it2 = Get()->m_aiActiveSounds[pEntity].begin(); while (it2 != Get()->m_aiActiveSounds[pEntity].end()) { Mix_HaltChannel(Get()->m_aiActiveSounds[pEntity][(*it2).first].iChannel); it2++; } Get()->m_aiActiveSounds[pEntity].clear(); Mix_ChannelFinished(&CSoundLibrary::ChannelFinished); return; } if (Get()->m_aiActiveSounds[pEntity].find(pszFilename) == Get()->m_aiActiveSounds[pEntity].end()) return; Mix_HaltChannel(Get()->m_aiActiveSounds[pEntity][pszFilename].iChannel); } bool CSoundLibrary::IsSoundPlaying(CBaseEntity* pEntity, const tstring& pszFilename) { if (Get()->m_aiActiveSounds.find(pEntity) == Get()->m_aiActiveSounds.end()) return false; if (Get()->m_aiActiveSounds[pEntity].find(pszFilename) == Get()->m_aiActiveSounds[pEntity].end()) return false; return true; } Mix_Music *g_pMusic = NULL; void CSoundLibrary::PlayMusic(const tstring& pszFilename, bool bLoop) { if (g_pMusic) StopMusic(); g_pMusic = Mix_LoadMUS(convertstring<tchar, char>(pszFilename).c_str()); Mix_PlayMusic(g_pMusic, bLoop?-1:0); } void CSoundLibrary::StopMusic() { if (!g_pMusic) return; Mix_HaltMusic(); Mix_FreeMusic(g_pMusic); // Because music wants to be free! g_pMusic = NULL; } bool CSoundLibrary::IsMusicPlaying() { return !!Mix_PlayingMusic(); } void CSoundLibrary::SetSoundVolume(CBaseEntity* pEntity, const tstring& pszFilename, float flVolume) { if (Get()->m_aiActiveSounds.find(pEntity) == Get()->m_aiActiveSounds.end()) return; if (Get()->m_aiActiveSounds[pEntity].find(pszFilename) == Get()->m_aiActiveSounds[pEntity].end()) return; Get()->m_aiActiveSounds[pEntity][pszFilename].flVolume = flVolume; Mix_Volume(Get()->m_aiActiveSounds[pEntity][pszFilename].iChannel, (int)(flVolume*s_flMasterVolume*MIX_MAX_VOLUME)); } void CSoundLibrary::SetSoundVolume(float flVolume) { s_flMasterVolume = flVolume; for (eastl::map<CBaseEntity*, eastl::map<tstring, CSoundInstance> >::iterator it = Get()->m_aiActiveSounds.begin(); it != Get()->m_aiActiveSounds.end(); it++) { for (eastl::map<tstring, CSoundInstance>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++) Mix_Volume(it2->second.iChannel, (int)(it2->second.flVolume*s_flMasterVolume*MIX_MAX_VOLUME)); } } void CSoundLibrary::SetMusicVolume(float flVolume) { Mix_VolumeMusic((int)(flVolume*128)); } void CSoundLibrary::ChannelFinished(int iChannel) { eastl::map<CBaseEntity*, eastl::map<tstring, CSoundInstance> >::iterator it = Get()->m_aiActiveSounds.begin(); while (it != Get()->m_aiActiveSounds.end()) { CBaseEntity* pEntity = (*it).first; eastl::map<tstring, CSoundInstance>::iterator it2 = Get()->m_aiActiveSounds[pEntity].begin(); while (it2 != Get()->m_aiActiveSounds[pEntity].end()) { tstring pszFilename = (*it2).first; if (iChannel == Get()->m_aiActiveSounds[pEntity][(*it2).first].iChannel) { Get()->m_aiActiveSounds[pEntity].erase(Get()->m_aiActiveSounds[pEntity].find(pszFilename)); if (Get()->m_aiActiveSounds[pEntity].size() == 0) Get()->m_aiActiveSounds.erase(Get()->m_aiActiveSounds.find(pEntity)); return; } it2++; } it++; } } void CSoundLibrary::EntityDeleted(CBaseEntity* pEntity) { // Remove from the active sound list. Let the sounds finish what they're playing. if (Get()->m_aiActiveSounds.find(pEntity) != Get()->m_aiActiveSounds.end()) Get()->m_aiActiveSounds.erase(Get()->m_aiActiveSounds.find(pEntity)); } CSound::CSound(const tstring& pszFilename) { SDL_RWops* pRW = SDL_RWFromFile(convertstring<tchar, char>(pszFilename).c_str(), "rb"); m_pSound = Mix_LoadWAV_RW(pRW, 1); m_sFilename = pszFilename; } CSound::~CSound() { if( m_pSound != NULL ) { Mix_FreeChunk( m_pSound ); } }
[ [ [ 1, 9 ], [ 11, 36 ], [ 38, 56 ], [ 58, 67 ], [ 69, 89 ], [ 93, 94 ], [ 96, 101 ], [ 103, 105 ], [ 107, 108 ], [ 110, 124 ], [ 126, 129 ], [ 131, 132 ], [ 134, 145 ], [ 147, 148 ], [ 150, 160 ], [ 162, 165 ], [ 167, 186 ], [ 188, 194 ], [ 197, 200 ], [ 207, 215 ], [ 217, 220 ], [ 222, 223 ], [ 226, 246 ], [ 248, 248 ], [ 250, 262 ] ], [ [ 10, 10 ], [ 37, 37 ], [ 57, 57 ], [ 68, 68 ], [ 90, 92 ], [ 95, 95 ], [ 102, 102 ], [ 106, 106 ], [ 109, 109 ], [ 125, 125 ], [ 130, 130 ], [ 133, 133 ], [ 146, 146 ], [ 149, 149 ], [ 161, 161 ], [ 166, 166 ], [ 187, 187 ], [ 195, 196 ], [ 201, 206 ], [ 216, 216 ], [ 221, 221 ], [ 224, 225 ], [ 247, 247 ], [ 249, 249 ] ] ]
4dbe0eab2d849f1ad16fef926780a002c4d261aa
216398e30aca5f7874edfb8b72a13f95c22fbb5a
/AITerm/src/AITerm/SemanticTemplateProcessor.h
225458e3a07708b8f21269468132e14b4f1445b9
[]
no_license
markisme/healthcare
791813ac6ac811870f3f28d1d31c3d5a07fb2fa2
7ab5a959deba02e7637da02a3f3c681548871520
refs/heads/master
2021-01-10T07:18:42.195610
2009-09-09T13:00:10
2009-09-09T13:00:10
35,987,767
0
0
null
null
null
null
UHC
C++
false
false
1,518
h
#pragma once #include "NamedEntityRecognition.h" struct TemplateSlot { std::vector<std::string> _tagNameList; std::string _type; bool _need; }; typedef std::vector<TemplateSlot> Template; typedef std::vector<Template> TemplateList; // 매칭 결과 컨테이너 struct MatchedSlot { std::string _slotType; std::string _word; std::string _tagName; bool _need; int _wordPos; }; struct MatchedTemplate { std::vector<MatchedSlot> _slotList; int _tempNo; int _questionNo; }; typedef std::vector<MatchedTemplate> ResultMatchedTemplate; class SemanticTemplateProcessor { public: SemanticTemplateProcessor(); ~SemanticTemplateProcessor(); void Start( ResultNamedEntityRecognition * resultNamedEntityRecognition ); void LoadTemplateList( TemplateList & tempList ); void SaveResultSemanticTemplateProcess( ResultMatchedTemplate & inResultMatchedTemplate ); ResultMatchedTemplate & GetResultMatchedTemplate() { return _resultMatchedTemplate; } private: bool IsMatchWord( NamedEntityList & namedEntityList, std::string & tagName, MatchedTemplate & matchedTemplate, MatchedSlot & outMatchedSlot ); bool IsWordInSlot( MatchedTemplate & matchedTemplate, int n ); void CompareTagname( TemplateList & tempList, NamedEntityList & namedEntityList, MatchedTemplate & outMatchedTemplate ); void SelectTemplate( ResultMatchedTemplate & resultMatchedTemplate, MatchedTemplate & outMatchedTemplate ); private: ResultMatchedTemplate _resultMatchedTemplate; };
[ "naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9" ]
[ [ [ 1, 53 ] ] ]
42006c8efa57356e743878371b316442dde44f1f
6baa03d2d25d4685cd94265bd0b5033ef185c2c9
/TGL/src/objects/TGLobject_ship_xterminator.cpp
fbc56f035d2cff5c6af2a33d8cd9fdbdcc88c661
[]
no_license
neiderm/transball
6ac83b8dd230569d45a40f1bd0085bebdc4a5b94
458dd1a903ea4fad582fb494c6fd773e3ab8dfd2
refs/heads/master
2021-01-10T07:01:43.565438
2011-12-12T23:53:54
2011-12-12T23:53:54
55,928,360
0
0
null
null
null
null
UTF-8
C++
false
false
7,064
cpp
#ifdef KITSCHY_DEBUG_MEMORY #include "debug_memorymanager.h" #endif #ifdef _WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "math.h" #include "string.h" #include "gl.h" #include "glu.h" #include "SDL.h" #include "SDL_mixer.h" #include "SDL_ttf.h" #include "List.h" #include "Symbol.h" #include "2DCMC.h" #include "auxiliar.h" #include "GLTile.h" #include "2DCMC.h" #include "sound.h" #include "keyboardstate.h" #include "randomc.h" #include "VirtualController.h" #include "GLTManager.h" #include "SFXManager.h" #include "TGLobject.h" #include "TGLobject_ship.h" #include "TGLobject_ship_xterminator.h" #include "TGLobject_bullet.h" #include "TGLobject_bullet_missile.h" #include "TGLobject_ball.h" #include "TGLobject_FX_particle.h" #include "TGLobject_FX_explosion2.h" #include "TGLmap.h" #include "debug.h" TGLobject_ship_xterminator::TGLobject_ship_xterminator(float x,float y,int initial_fuel) : TGLobject_ship(x,y,initial_fuel) { m_scale=0.45f; m_thrusting=false; m_ball=0; m_max_fuel=50*96; m_fuel=(initial_fuel/2)*96; } /* TGLobject_ship_xterminator::TGLobject_ship */ TGLobject_ship_xterminator::~TGLobject_ship_xterminator() { if (m_thrust_channel!=-1) { Mix_HaltChannel(m_thrust_channel); m_thrust_channel=-1; } // if } /* TGLobject_ship_xterminator::~TGLobject_ship */ bool TGLobject_ship_xterminator::cycle(VirtualController *k,TGLmap *map,GLTManager *GLTM,SFXManager *SFXM,int sfx_volume) { m_cycle++; // Check for collision: if (map->collision(this,0,0,0)) { if (!map->collision_with_foreground(this,0,0,0)) { TGLobject *obj = map->collision_with_object(this); if (obj->is_a("TGLobject_soft_bullet")) { int a=obj->get_angle()-90; while(a<0) a+=360; while(a>=360) a-=360; m_speed_x+=float(cos_degree(a)*48.0)/256.0f; m_speed_y+=float(sin_degree(a)*48.0)/256.0f; } else { Sound_play(SFXM->get("sfx/explosion"),sfx_volume); map->add_auxiliary_front_object(new TGLobject_FX_explosion2(get_x(),get_y(),256,200)); return false; } } else { Sound_play(SFXM->get("sfx/explosion"),sfx_volume); map->add_auxiliary_front_object(new TGLobject_FX_explosion2(get_x(),get_y(),256,200)); return false; } } // if m_thrusting=false; if (m_fuel_recharging_timmer>0) { m_fuel_recharging_timmer--; if (m_fuel_recharging_timmer==0) { if (m_fuel_channel!=-1) { Mix_HaltChannel(m_fuel_channel); m_fuel_channel=-1; } // if } // if } // if if (k->m_button[1] && (fabs(m_speed_x)+fabs(m_speed_y))<1) { TGLobject_ball *ball; ball=(TGLobject_ball *)map->object_exists("TGLobject_ball",get_x()-16,get_y(),get_x()+16,get_y()+64); if (ball!=0 && m_ball==0) { if (ball->attractor()) { if (ball->get_state()==0) map->action(0); ball->capture(2); m_ball=ball; Sound_play(SFXM->get("sfx/takeball"),sfx_volume); } // if } // if // Attractor effect: { if ((m_cycle%6)==0) { map->add_auxiliary_back_object(new TGLobject_FX_particle(get_x(),get_y()+48,0,0,-1,0,false, 0.5f,0.5f, 0.5f,0.5f, 1,1, 1,0,0.75,0.5f,50,GLTM->get("objects/ripple-back"))); map->add_auxiliary_front_object(new TGLobject_FX_particle(get_x(),get_y()+48,0,0,-1,0,false, 0.5f,0.5f, 0.5f,0.5f, 1,1, 1,0,0.75,0.5f,50,GLTM->get("objects/ripple-front"))); } // if }; } // if if (k->m_button[0] && !k->m_old_button[0] && m_fuel>96) { TGLobject *bullet; int a=m_angle-90; while(a<0) a+=360; while(a>=360) a-=360; bullet=new TGLobject_bullet_missile(float(get_x()+(cos_degree(a)*8)),float(get_y()+(sin_degree(a)*8)),0,m_angle,4,4,GLTM->get("objects/bullet-grey-missile1"),GLTM->get("objects/bullet-grey-missile2"),this); if (m_ball!=0) bullet->exclude_for_collision(m_ball); map->add_object_back(bullet); m_fuel-=96; Sound_play(SFXM->get("sfx/shipshot2"),sfx_volume); } // if if (k->m_joystick[VC_LEFT]) { m_angle-=4; if (m_angle<0) m_angle+=360; } // if if (k->m_joystick[VC_RIGHT]) { m_angle+=4; if (m_angle>=360) m_angle-=360; } // if if (k->m_joystick[VC_UP] && m_fuel>0) { int a=m_angle-90; while(a<0) a+=360; while(a>=360) a-=360; m_speed_x+=float(cos_degree(a)*11.0)/256.0f; m_speed_y+=float(sin_degree(a)*11.0)/256.0f; m_thrusting=true; m_fuel--; } // if if (m_speed_x>0) m_speed_x-=1.0f/256.0f; if (m_speed_x<0) m_speed_x+=1.0f/256.0f; m_speed_y+=2.0f/256.0f; if (m_speed_x>8) m_speed_x=8; if (m_speed_x<-8) m_speed_x=-8; if (m_speed_y>8) m_speed_y=8; if (m_speed_y<-8) m_speed_y=-8; m_x+=m_speed_x; m_y+=m_speed_y; if ((m_x)<0) { m_x=0; m_speed_x=0; } /* if */ if ((m_y)<0) { m_y=0; m_speed_y=0; } /* if */ if ((m_x)>(map->get_dx())) { m_x=float(map->get_dx()); m_speed_x=0; } /* if */ if ((m_y)>(map->get_dy())) { m_y=float(map->get_dy()); m_speed_y=0; } /* if */ // Ball attraction: if (m_ball!=0) { float dx=m_ball->get_x()-get_x(); float dy=m_ball->get_y()-get_y(); float d=float(sqrt(dx*dx+dy*dy)); if (d<2) d=2; { float inc=float(28/sqrt(d)); float inc_x=((dx/d)*inc)/256.0f; float inc_y=((dy/d)*inc)/256.0f; m_ball->set_speed_x(m_ball->get_speed_x()-inc_x); m_ball->set_speed_y(m_ball->get_speed_y()-inc_y); } } // if if (m_thrusting) { if ((m_cycle%4)==0) map->add_auxiliary_back_object(new TGLobject_FX_particle(get_x(),get_y(),rand()%60,0,0,1,false,0.125f,0,0.5f,1.5f,50,GLTM->get("objects/smoke"))); if (m_thrust_channel==-1) { m_thrust_channel=Sound_play_continuous(SFXM->get("sfx/thrust"),sfx_volume); } // if } else { if (m_thrust_channel!=-1) { Mix_HaltChannel(m_thrust_channel); m_thrust_channel=-1; } // if } // if return true; } /* TGLobject::cycle */ void TGLobject_ship_xterminator::draw(GLTManager *GLTM) { if (m_last_mask==0) m_last_mask=GLTM->get("objects/ship-xterminator-1"); if (m_thrusting) { if (((m_cycle/4)%2)==0) m_last_tile=GLTM->get("objects/ship-xterminator-2"); else m_last_tile=GLTM->get("objects/ship-xterminator-3"); } else { m_last_tile=GLTM->get("objects/ship-xterminator-1"); } // if if (m_last_tile!=0) m_last_tile->draw(m_x,m_y,0,float(m_angle),m_scale); } /* TGLobject_ship_xterminator::draw */ bool TGLobject_ship_xterminator::is_a(Symbol *c) { if (c->cmp("TGLobject_ship_xterminator")) return true; return TGLobject_ship::is_a(c); } /* TGLobject_ship_xterminator::is_a */ bool TGLobject_ship_xterminator::is_a(char *c) { bool retval; Symbol *s=new Symbol(c); retval=is_a(s); delete s; return retval; } /* TGLobject_ship_xterminator::is_a */ const char *TGLobject_ship_xterminator::get_class(void) { return "TGLobject_ship_xterminator"; } /* TGLobject_ship_xterminator:get_class */
[ "santi.ontanon@535450eb-5f2b-0410-a0e9-a13dc2d1f197" ]
[ [ [ 1, 271 ] ] ]
179417c3712dc7894585c660c3eb3e73664e35d3
8bb0a1d6c74f3a17d90c64d9ee40ae5153d15acb
/ cs191-nds-project/splash_screen/CS191_Project/include/CCollisionManager.h
84fb7b2993ebdb0315f7a6052622bf97e6045791
[]
no_license
btuduri/cs191-nds-project
9b12382316c0a59d4e48acd7f40ed55c5c4cde41
146b2218cc53f960a034d053238a4cf111726279
refs/heads/master
2020-03-30T19:13:10.122474
2008-05-19T02:26:19
2008-05-19T02:26:19
32,271,764
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
h
#ifndef CCOLLISIONMANAGER_H_ #define CCOLLISIONMANAGER_H_ #include "ProjectLib.h" #include "CMovableSprite.h" #include "CBasicObject.h" #include "CSprite.h" class CCollisionManager { public: CCollisionManager(){numSprites=0; numObjects=0;} ~CCollisionManager(){} void registerSprite(CMovableSprite *sprite); bool removeSprite(CMovableSprite *sprite); void registerObject(CBasicObject *obj); bool removeObject(CBasicObject *obj); void moveAllSpritesAlongX( float units ); void moveAllSpritesAlongY( float units ); void moveAllObjectsAlongX( float units ); void moveAllObjectsAlongY( float units ); bool checkObjectCollisions(CBasicObject *cbo, float toX, float toY); bool checkSpriteCollisions(CMovableSprite *sprite, float toX, float toY); CBasicObject *getLastObjectTouched(){return lastObjectTouched;} private: CBasicObject *lastObjectTouched; vector<CMovableSprite*> sprites; vector<CBasicObject*> objects; u32 numSprites; u32 numObjects; }; #endif /*CCOLLISIONMANAGER_H_*/
[ "kingofcode@67d8362a-e844-0410-8493-f333cf7aaa27" ]
[ [ [ 1, 45 ] ] ]
a27bff05fa41e76278eac20b4f98311b7e35d50c
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/zzogl-pg/opengl/ZZoglFlush.cpp
4b11439f5a0741061f538578ac0df1d688ce438a
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
79,938
cpp
/* ZZ Open GL graphics plugin * Copyright (c)2009-2010 [email protected], [email protected] * Based on Zerofrog's ZeroGS KOSMOS (c)2005-2008 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ // Realization of Flush -- drawing function of GS #include <stdlib.h> #include "GS.h" #include "Mem.h" #include "zerogs.h" #include "targets.h" #include "ZZoglFlushHack.h" #include "ZZoglShaders.h" using namespace ZeroGS; //------------------ Defines #ifndef ZEROGS_DEVBUILD #define INC_GENVARS() #define INC_TEXVARS() #define INC_ALPHAVARS() #define INC_RESOLVE() #define g_bUpdateEffect 0 #define g_bSaveTex 0 bool g_bSaveTrans = 0; #define g_bSaveResolved 0 #else // defined(ZEROGS_DEVBUILD) #define INC_GENVARS() ++g_nGenVars #define INC_TEXVARS() ++g_nTexVars #define INC_ALPHAVARS() ++g_nAlphaVars #define INC_RESOLVE() ++g_nResolve bool g_bSaveTrans = 0; bool g_bUpdateEffect = 0; bool g_bSaveTex = 0; // saves the curent texture bool g_bSaveResolved = 0; #endif // !defined(ZEROGS_DEVBUILD) #define STENCIL_ALPHABIT 1 // if set, dest alpha >= 0x80 #define STENCIL_PIXELWRITE 2 // if set, pixel just written (reset after every Flush) #define STENCIL_FBA 4 // if set, just written pixel's alpha >= 0 (reset after every Flush) #define STENCIL_SPECIAL 8 // if set, indicates that pixel passed its alpha test (reset after every Flush) //#define STENCIL_PBE 16 #define STENCIL_CLEAR (2|4|8|16) void Draw(const VB& curvb) { glDrawArrays(primtype[curvb.curprim.prim], 0, curvb.nCount); } #define GL_BLEND_RGB(src, dst) { \ s_srcrgb = src; \ s_dstrgb = dst; \ zgsBlendFuncSeparateEXT(s_srcrgb, s_dstrgb, s_srcalpha, s_dstalpha); \ } #define GL_BLEND_ALPHA(src, dst) { \ s_srcalpha = src; \ s_dstalpha = dst; \ zgsBlendFuncSeparateEXT(s_srcrgb, s_dstrgb, s_srcalpha, s_dstalpha); \ } #define GL_BLEND_ALL(srcrgb, dstrgb, srcalpha, dstalpha) { \ s_srcrgb = srcrgb; \ s_dstrgb = dstrgb; \ s_srcalpha = srcalpha; \ s_dstalpha = dstalpha; \ zgsBlendFuncSeparateEXT(s_srcrgb, s_dstrgb, s_srcalpha, s_dstalpha); \ } #define GL_ZTEST(enable) { \ if (enable) glEnable(GL_DEPTH_TEST); \ else glDisable(GL_DEPTH_TEST); \ } #define GL_ALPHATEST(enable) { \ if( enable ) glEnable(GL_ALPHA_TEST); \ else glDisable(GL_ALPHA_TEST); \ } #define GL_BLENDEQ_RGB(eq) { \ s_rgbeq = eq; \ zgsBlendEquationSeparateEXT(s_rgbeq, s_alphaeq); \ } #define GL_BLENDEQ_ALPHA(eq) { \ s_alphaeq = eq; \ zgsBlendEquationSeparateEXT(s_rgbeq, s_alphaeq); \ } #define COLORMASK_RED 1 #define COLORMASK_GREEN 2 #define COLORMASK_BLUE 4 #define COLORMASK_ALPHA 8 #define GL_COLORMASK(mask) glColorMask(!!((mask)&COLORMASK_RED), !!((mask)&COLORMASK_GREEN), !!((mask)&COLORMASK_BLUE), !!((mask)&COLORMASK_ALPHA)) // ----------------- Types //------------------ Dummies //------------------ variables extern int g_nDepthBias; extern float g_fBlockMult; // used for old cards, that do not support Alpha-32float textures. We store block data in u16 and use it. bool g_bUpdateStencil = 1; //u32 g_SaveFrameNum = 0; // ZZ extern ZZshProgram g_psprog; // 2 -- ZZ // local alpha blending settings static GLenum s_rgbeq, s_alphaeq; // set by zgsBlendEquationSeparateEXT // ZZ static const u32 blendalpha[3] = { GL_SRC_ALPHA, GL_DST_ALPHA, GL_CONSTANT_COLOR_EXT }; // ZZ static const u32 blendinvalpha[3] = { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_CONSTANT_COLOR_EXT }; //ZZ static const u32 g_dwAlphaCmp[] = { GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL }; // ZZ // used for afail case static const u32 g_dwReverseAlphaCmp[] = { GL_ALWAYS, GL_NEVER, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL, GL_LESS, GL_LEQUAL, GL_EQUAL }; static const u32 g_dwZCmp[] = { GL_NEVER, GL_ALWAYS, GL_GEQUAL, GL_GREATER }; ///////////////////// // graphics resources #define s_bForceTexFlush 1 // ZZ static u32 s_ptexCurSet[2] = {0}; static u32 s_ptexNextSet[2] = {0}; // ZZ extern vector<u32> s_vecTempTextures; // temporary textures, released at the end of every frame extern bool s_bTexFlush; bool s_bWriteDepth = false; bool s_bDestAlphaTest = false; int s_ClutResolve = 0; // ZZ int g_nDepthUsed = 0; // ffx2 pal movies int s_nWriteDepthCount = 0; // ZZ int s_nWriteDestAlphaTest = 0; // ZZ //////////////////// // State parameters static Vector vAlphaBlendColor; // used for GPU_COLOR static bool bNeedBlendFactorInAlpha; // set if the output source alpha is different from the real source alpha (only when blend factor > 0x80) static u32 s_dwColorWrite = 0xf; // the color write mask of the current target typedef union { struct { u8 _bNeedAlphaColor; // set if vAlphaBlendColor needs to be set u8 _b2XAlphaTest; // Only valid when bNeedAlphaColor is set. if 1st bit set set, double all alpha testing values // otherwise alpha testing needs to be done separately. u8 _bDestAlphaColor; // set to 1 if blending with dest color (process only one tri at a time). If 2, dest alpha is always 1. u8 _bAlphaClamping; // if first bit is set, do min; if second bit, do max }; u32 _bAlphaState; } g_flag_vars; g_flag_vars g_vars; //#define bNeedAlphaColor g_vars._bNeedAlphaColor #define b2XAlphaTest g_vars._b2XAlphaTest #define bDestAlphaColor g_vars._bDestAlphaColor #define bAlphaClamping g_vars._bAlphaClamping int g_PrevBitwiseTexX = -1, g_PrevBitwiseTexY = -1; // textures stored in SAMP_BITWISEANDX and SAMP_BITWISEANDY // ZZ //static alphaInfo s_alphaInfo; // ZZ extern u8* g_pbyGSClut; extern int ppf; int s_nWireframeCount = 0; //------------------ Namespace namespace ZeroGS { VB vb[2]; float fiTexWidth[2], fiTexHeight[2]; // current tex width and height //u8 s_AAx = 0, s_AAy = 0; // if AAy is set, then AAx has to be set Point AA = {0,0}; int icurctx = -1; extern CRangeManager s_RangeMngr; // manages overwritten memory // zz void FlushTransferRanges(const tex0Info* ptex); //zz RenderFormatType GetRenderFormat() { return g_RenderFormatType; } //zz // use to update the state void SetTexVariables(int context, FRAGMENTSHADER* pfragment); // zz void SetTexInt(int context, FRAGMENTSHADER* pfragment, int settexint); // zz void SetAlphaVariables(const alphaInfo& ainfo); // zzz void ResetAlphaVariables(); inline void SetAlphaTestInt(pixTest curtest); inline void RenderAlphaTest(const VB& curvb, ZZshParameter sOneColor); inline void RenderStencil(const VB& curvb, u32 dwUsingSpecialTesting); inline void ProcessStencil(const VB& curvb); inline void RenderFBA(const VB& curvb, ZZshParameter sOneColor); inline void ProcessFBA(const VB& curvb, ZZshParameter sOneColor); // zz } //------------------ Code inline float AlphaReferedValue(int aref) { return b2XAlphaTest ? min(1.0f, (float)aref / 127.5f) : (float)aref / 255.0f ; } inline void SetAlphaTest(const pixTest& curtest) { // if s_dwColorWrite is nontrivial, than we should not off alphatest. // This fix GOW and Okami. if (!curtest.ate && USEALPHATESTING && (s_dwColorWrite != 2 && s_dwColorWrite != 14)) { glDisable(GL_ALPHA_TEST); } else { glEnable(GL_ALPHA_TEST); glAlphaFunc(g_dwAlphaCmp[curtest.atst], AlphaReferedValue(curtest.aref)); } } // Return, if tcc, aem or psm mode told us, than Alpha test should be used // if tcc == 0 than no alpha used, aem used for alpha expanding and I am not sure // that it's correct, psm -- color mode, inline bool IsAlphaTestExpansion(tex0Info tex0) { return (tex0.tcc && gs.texa.aem && PSMT_ALPHAEXP(PIXEL_STORAGE_FORMAT(tex0))); } // Switch wireframe rendering off for first flush, so it's draw few solid primitives inline void SwitchWireframeOff() { if (conf.wireframe()) { if (s_nWireframeCount > 0) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } } // Switch wireframe rendering on, look at previous function inline void SwitchWireframeOn() { if (conf.wireframe()) { if (s_nWireframeCount > 0) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); --s_nWireframeCount; } } } int GetTexFilter(const tex1Info& tex1) { // always force if (conf.bilinear == 2) return 1; int texfilter = 0; if (conf.bilinear && ptexBilinearBlocks != 0) { if (tex1.mmin <= 1) texfilter = tex1.mmin | tex1.mmag; else texfilter = tex1.mmag ? ((tex1.mmin + 2) & 5) : tex1.mmin; texfilter = texfilter == 1 || texfilter == 4 || texfilter == 5; } return texfilter; } void ZeroGS::ReloadEffects() { #ifdef ZEROGS_DEVBUILD for (int i = 0; i < ARRAY_SIZE(ppsTexture); ++i) { SAFE_RELEASE_PROG(ppsTexture[i].prog); } memset(ppsTexture, 0, sizeof(ppsTexture)); LoadExtraEffects(); #endif } long BufferNumber = 0; // This is a debug function. It prints all buffer info and save current texture into the file, then prints the file name. inline void VisualBufferMessage(int context) { #if defined(WRITE_PRIM_LOGS) && defined(_DEBUG) BufferNumber++; ZeroGS::VB& curvb = vb[context]; static const char* patst[8] = { "NEVER", "ALWAYS", "LESS", "LEQUAL", "EQUAL", "GEQUAL", "GREATER", "NOTEQUAL"}; static const char* pztst[4] = { "NEVER", "ALWAYS", "GEQUAL", "GREATER" }; static const char* pafail[4] = { "KEEP", "FB_ONLY", "ZB_ONLY", "RGB_ONLY" }; ZZLog::Debug_Log("**Drawing ctx %d, num %d, fbp: 0x%x, zbp: 0x%x, fpsm: %d, zpsm: %d, fbw: %d", context, vb[context].nCount, curvb.prndr->fbp, curvb.zbuf.zbp, curvb.prndr->psm, curvb.zbuf.psm, curvb.prndr->fbw); ZZLog::Debug_Log("prim: prim=%x iip=%x tme=%x fge=%x abe=%x aa1=%x fst=%x ctxt=%x fix=%x", curvb.curprim.prim, curvb.curprim.iip, curvb.curprim.tme, curvb.curprim.fge, curvb.curprim.abe, curvb.curprim.aa1, curvb.curprim.fst, curvb.curprim.ctxt, curvb.curprim.fix); ZZLog::Debug_Log("test: ate:%d, atst: %s, aref: %d, afail: %s, date: %d, datm: %d, zte: %d, ztst: %s, fba: %d", curvb.test.ate, patst[curvb.test.atst], curvb.test.aref, pafail[curvb.test.afail], curvb.test.date, curvb.test.datm, curvb.test.zte, pztst[curvb.test.ztst], curvb.fba.fba); ZZLog::Debug_Log("alpha: A%d B%d C%d D%d FIX:%d pabe: %d; aem: %d, ta0: %d, ta1: %d\n", curvb.alpha.a, curvb.alpha.b, curvb.alpha.c, curvb.alpha.d, curvb.alpha.fix, gs.pabe, gs.texa.aem, gs.texa.ta[0], gs.texa.ta[1]); ZZLog::Debug_Log("tex0: tbp0=0x%x, tbw=%d, psm=0x%x, tw=%d, th=%d, tcc=%d, tfx=%d, cbp=0x%x, cpsm=0x%x, csm=%d, csa=%d, cld=%d", curvb.tex0.tbp0, curvb.tex0.tbw, curvb.tex0.psm, curvb.tex0.tw, curvb.tex0.th, curvb.tex0.tcc, curvb.tex0.tfx, curvb.tex0.cbp, curvb.tex0.cpsm, curvb.tex0.csm, curvb.tex0.csa, curvb.tex0.cld); char* Name; // if (g_bSaveTex) { // if (g_bSaveTex == 1) Name = NamedSaveTex(&curvb.tex0, 1); // else // Name = NamedSaveTex(&curvb.tex0, 0); ZZLog::Error_Log("TGA name '%s'.", Name); free(Name); // } // ZZLog::Debug_Log("frame: %d, buffer %ld.\n", g_SaveFrameNum, BufferNumber); ZZLog::Debug_Log("buffer %ld.\n", BufferNumber); #endif } inline void SaveRendererTarget(VB& curvb) { #ifdef _DEBUG // if (g_bSaveFlushedFrame & 0x80000000) // { // char str[255]; // sprintf(str, "rndr%d.tga", g_SaveFrameNum); // SaveRenderTarget(str, curvb.prndr->fbw, curvb.prndr->fbh, 0); // } #endif } // Stop effects in Developers mode inline void FlushUpdateEffect() { #if defined(DEVBUILD) if (g_bUpdateEffect) { ReloadEffects(); g_bUpdateEffect = 0; } #endif } // Check, maybe we cold skip flush inline bool IsFlushNoNeed(VB& curvb, const pixTest& curtest) { if (curvb.nCount == 0 || (curtest.zte && curtest.ztst == 0) || IsBadFrame(curvb)) { curvb.nCount = 0; return true; } return false; } // Transfer targets, that are located in current texture. inline void FlushTransferRangesHelper(VB& curvb) { if (s_RangeMngr.ranges.size() > 0) { // don't want infinite loop, so set nCount to 0. u32 prevcount = curvb.nCount; curvb.nCount = 0; FlushTransferRanges(curvb.curprim.tme ? &curvb.tex0 : NULL); curvb.nCount += prevcount; } } // If set bit for texture checking, do it. Maybe it's all. inline bool FushTexDataHelper(VB& curvb) { if (curvb.bNeedFrameCheck || curvb.bNeedZCheck) { curvb.CheckFrame(curvb.curprim.tme ? curvb.tex0.tbp0 : 0); } if (curvb.bNeedTexCheck) // Zeydlitz want to try this { curvb.FlushTexData(); if (curvb.nCount == 0) return true; } return false; } // Null target mean that we do something really bad. inline bool FlushCheckForNULLTarget(VB& curvb, int context) { if ((curvb.prndr == NULL) || (curvb.pdepth == NULL)) { ERROR_LOG_SPAMA("Current render target NULL (ctx: %d)", context); curvb.nCount = 0; return true; } return false; } // O.k. A set of resolutions, we do before real flush. We do RangeManager, FrameCheck and // ZCheck before this. inline bool FlushInitialTest(VB& curvb, const pixTest& curtest, int context) { GL_REPORT_ERRORD(); assert(context >= 0 && context <= 1); FlushUpdateEffect(); if (IsFlushNoNeed(curvb, curtest)) return true; FlushTransferRangesHelper(curvb); if (FushTexDataHelper(curvb)) return true; GL_REPORT_ERRORD(); if (FlushCheckForNULLTarget(curvb, context)) return true; return false; } // Try to different approach if texture target was not found inline CRenderTarget* FlushReGetTarget(int& tbw, int& tbp0, int& tpsm, VB& curvb) { // This was incorrect code CRenderTarget* ptextarg = NULL; if ((ptextarg == NULL) && (tpsm == PSMT8) && (conf.settings().reget)) { // check for targets with half the width. Break Valkyrie Chronicles ptextarg = s_RTs.GetTarg(tbp0, tbw / 2, curvb); if (ptextarg == NULL) { tbp0 &= ~0x7ff; ptextarg = s_RTs.GetTarg(tbp0, tbw / 2, curvb); // mgs3 hack if (ptextarg == NULL) { // check the next level (mgs3) tbp0 &= ~0xfff; ptextarg = s_RTs.GetTarg(tbp0, tbw / 2, curvb); // mgs3 hack } if (ptextarg != NULL && ptextarg->start > tbp0*256) { // target beyond range, so ignore ptextarg = NULL; } } } if (PSMT_ISZTEX(tpsm) && (ptextarg == NULL)) { // try depth ptextarg = s_DepthRTs.GetTarg(tbp0, tbw, curvb); } if ((ptextarg == NULL) && (conf.settings().texture_targs)) { // check if any part of the texture intersects the current target if (!PSMT_ISCLUT(tpsm) && (curvb.tex0.tbp0 >= curvb.frame.fbp) && ((curvb.tex0.tbp0) < curvb.prndr->end)) { ptextarg = curvb.prndr; } } #ifdef _DEBUG if (tbp0 == 0x3600 && tbw == 0x100) { if (ptextarg == NULL) { printf("Miss %x 0x%x %d\n", tbw, tbp0, tpsm); typedef map<u32, CRenderTarget*> MAPTARGETS; for (MAPTARGETS::iterator itnew = s_RTs.mapTargets.begin(); itnew != s_RTs.mapTargets.end(); ++itnew) { printf("\tRender %x 0x%x %x\n", itnew->second->fbw, itnew->second->fbp, itnew->second->psm); } for (MAPTARGETS::iterator itnew = s_DepthRTs.mapTargets.begin(); itnew != s_DepthRTs.mapTargets.end(); ++itnew) { printf("\tDepth %x 0x%x %x\n", itnew->second->fbw, itnew->second->fbp, itnew->second->psm); } printf("\tCurvb 0x%x 0x%x 0x%x %x\n", curvb.frame.fbp, curvb.prndr->end, curvb.prndr->fbp, curvb.prndr->fbw); } else printf("Hit %x 0x%x %x\n", tbw, tbp0, tpsm); } #endif return ptextarg; } // Find target to draw a texture, it's highly p inline CRenderTarget* FlushGetTarget(VB& curvb) { int tbw, tbp0, tpsm; CRenderTarget* ptextarg = NULL; if (!curvb.curprim.tme) return ptextarg; if (curvb.bNeedTexCheck) { printf("How it is possible?\n"); // not yet initied, but still need to get correct target! (xeno3 ingame) tbp0 = ZZOglGet_tbp0_TexBits(curvb.uNextTex0Data[0]); tbw = ZZOglGet_tbw_TexBitsMult(curvb.uNextTex0Data[0]); tpsm = ZZOglGet_psm_TexBitsFix(curvb.uNextTex0Data[0]); } else { tbw = curvb.tex0.tbw; tbp0 = curvb.tex0.tbp0; tpsm = curvb.tex0.psm; } ptextarg = s_RTs.GetTarg(tbp0, tbw, curvb); if (ptextarg == NULL) ptextarg = FlushReGetTarget(tbw, tbp0, tpsm, curvb); if ((ptextarg != NULL) && !(ptextarg->status & CRenderTarget::TS_NeedUpdate)) { if (PSMT_BITMODE(tpsm) == 4) // handle 8h cluts { // don't support clut targets, read from mem // 4hl - kh2 check - from dx version -- arcum42 if (tpsm == PSMT4 && s_ClutResolve <= 1) { // xenosaga requires 2 resolves u32 prevcount = curvb.nCount; curvb.nCount = 0; ptextarg->Resolve(); s_ClutResolve++; curvb.nCount += prevcount; } ptextarg = NULL; } else { if (ptextarg == curvb.prndr) { // need feedback curvb.prndr->CreateFeedback(); if (s_bWriteDepth && (curvb.pdepth != NULL)) curvb.pdepth->SetRenderTarget(1); else ResetRenderTarget(1); } } } else { ptextarg = NULL; } return ptextarg; } // Set target for current context inline void FlushSetContextTarget(VB& curvb, int context) { if (!curvb.bVarsSetTarg) { SetContextTarget(context); } else { assert(curvb.pdepth != NULL); if (curvb.pdepth->status & CRenderTarget::TS_Virtual) { if (!curvb.zbuf.zmsk) { CRenderTarget* ptemp = s_DepthRTs.Promote(GetFrameKey(curvb.pdepth)); assert(ptemp == curvb.pdepth); } else { curvb.pdepth->status &= ~CRenderTarget::TS_NeedUpdate; } } if ((curvb.pdepth->status & CRenderTarget::TS_NeedUpdate) || (curvb.prndr->status & CRenderTarget::TS_NeedUpdate)) SetContextTarget(context); } assert(!(curvb.prndr->status&CRenderTarget::TS_NeedUpdate)); curvb.prndr->status = 0; if (curvb.pdepth != NULL) { #ifdef _DEBUG // Reduce an assert to a warning. if (curvb.pdepth->status & CRenderTarget::TS_NeedUpdate) { ZZLog::Debug_Log("In FlushSetContextTarget, pdepth has TS_NeedUpdate set."); } #endif if (!curvb.zbuf.zmsk) { assert(!(curvb.pdepth->status & CRenderTarget::TS_Virtual)); curvb.pdepth->status = 0; } } } inline void FlushSetStream(VB& curvb) { glBindBuffer(GL_ARRAY_BUFFER, g_vboBuffers[g_nCurVBOIndex]); g_nCurVBOIndex = (g_nCurVBOIndex + 1) % g_vboBuffers.size(); glBufferData(GL_ARRAY_BUFFER, curvb.nCount * sizeof(VertexGPU), curvb.pBufferData, GL_STREAM_DRAW); // void* pdata = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); // memcpy_amd(pdata, curvb.pBufferData, curvb.nCount * sizeof(VertexGPU)); // glUnmapBuffer(GL_ARRAY_BUFFER); SET_STREAM(); GL_REPORT_ERRORD(); } int SetMaskR = 0x0; int SetMaskG = 0x0; int SetMaskB = 0x0; // Set color mask. Really, it's not as good as PS2 one. inline void FlushSetColorMask(VB& curvb) { s_dwColorWrite = (PSMT_BITMODE(curvb.prndr->psm) == 1) ? (COLORMASK_BLUE | COLORMASK_GREEN | COLORMASK_RED) : 0xf; int maskR = ZZOglGet_fbmRed_FrameBits(curvb.frame.fbm); int maskG = ZZOglGet_fbmGreen_FrameBits(curvb.frame.fbm); int maskB = ZZOglGet_fbmBlue_FrameBits(curvb.frame.fbm); int maskA = ZZOglGet_fbmAlpha_FrameBits(curvb.frame.fbm); if (maskR == 0xff) s_dwColorWrite &= ~COLORMASK_RED; if (maskG == 0xff) s_dwColorWrite &= ~COLORMASK_GREEN; if (maskB == 0xff) s_dwColorWrite &= ~COLORMASK_BLUE; if ((maskA == 0xff) || (curvb.curprim.abe && (curvb.test.atst == 2 && curvb.test.aref == 128))) s_dwColorWrite &= ~COLORMASK_ALPHA; GL_COLORMASK(s_dwColorWrite); } // Set Scissors for scissor test. inline void FlushSetScissorRect(VB& curvb) { Rect& scissor = curvb.prndr->scissorrect; glScissor(scissor.x, scissor.y, scissor.w, scissor.h); } // Prior really doing something check context inline void FlushDoContextJob(VB& curvb, int context) { SaveRendererTarget(curvb); FlushSetContextTarget(curvb, context); icurctx = context; FlushSetStream(curvb); FlushSetColorMask(curvb); FlushSetScissorRect(curvb); } // Set 1 is Alpha test is EQUAL and alpha should be proceed with care. inline int FlushGetExactcolor(const pixTest curtest) { if (!(g_nPixelShaderVer&SHADER_REDUCED)) // ffx2 breaks when ==7 return ((curtest.ate && curtest.aref <= 128) && (curtest.atst == 4));//||curtest.atst==7); return 0; } // fill the buffer by decoding the clut inline void FlushDecodeClut(VB& curvb, GLuint& ptexclut) { glGenTextures(1, &ptexclut); glBindTexture(GL_TEXTURE_2D, ptexclut); vector<char> data(PSMT_ISHALF_STORAGE(curvb.tex0) ? 512 : 1024); if (ptexclut != 0) { int nClutOffset = 0, clutsize; int entries = PSMT_IS8CLUT(curvb.tex0.psm) ? 256 : 16; if (curvb.tex0.csm && curvb.tex0.csa) printf("ERROR, csm1\n"); if (PSMT_IS32BIT(curvb.tex0.cpsm)) // 32 bit { nClutOffset = 64 * curvb.tex0.csa; clutsize = min(entries, 256 - curvb.tex0.csa * 16) * 4; } else { nClutOffset = 64 * (curvb.tex0.csa & 15) + (curvb.tex0.csa >= 16 ? 2 : 0); clutsize = min(entries, 512 - curvb.tex0.csa * 16) * 2; } if (PSMT_IS32BIT(curvb.tex0.cpsm)) // 32 bit { memcpy_amd(&data[0], g_pbyGSClut + nClutOffset, clutsize); } else { u16* pClutBuffer = (u16*)(g_pbyGSClut + nClutOffset); u16* pclut = (u16*) & data[0]; int left = ((u32)nClutOffset & 2) ? 0 : ((nClutOffset & 0x3ff) / 2) + clutsize - 512; if (left > 0) clutsize -= left; while (clutsize > 0) { pclut[0] = pClutBuffer[0]; pclut++; pClutBuffer += 2; clutsize -= 2; } if (left > 0) { pClutBuffer = (u16*)(g_pbyGSClut + 2); while (left > 0) { pclut[0] = pClutBuffer[0]; left -= 2; pClutBuffer += 2; pclut++; } } } GLenum tempType = PSMT_ISHALF_STORAGE(curvb.tex0) ? GL_UNSIGNED_SHORT_5_5_5_1 : GL_UNSIGNED_BYTE; Texture2D(4, 256, 1, GL_RGBA, tempType, &data[0]); s_vecTempTextures.push_back(ptexclut); if (g_bSaveTex) SaveTexture("clut.tga", GL_TEXTURE_2D, ptexclut, 256, 1); setTex2DWrap(GL_REPEAT); setTex2DFilters(GL_LINEAR); } } inline int FlushGetShaderType(VB& curvb, CRenderTarget* ptextarg, GLuint& ptexclut) { if (PSMT_ISCLUT(curvb.tex0.psm) && !(conf.settings().no_target_clut)) { FlushDecodeClut(curvb, ptexclut); if (!(g_nPixelShaderVer&SHADER_REDUCED) && PSMT_ISHALF(ptextarg->psm)) { return 4; } else { // Valkyrie return 2; } } if (PSMT_ISHALF_STORAGE(curvb.tex0) != PSMT_ISHALF(ptextarg->psm) && (!(g_nPixelShaderVer&SHADER_REDUCED) || !curvb.curprim.fge)) { if (PSMT_ISHALF_STORAGE(curvb.tex0)) { // converting from 32->16 // Radiata Chronicles return 3; } else { // converting from 16->32 // Star Ward: Force return 0; } } return 1; } //Set page offsets depends on shader type. inline Vector FlushSetPageOffset(FRAGMENTSHADER* pfragment, int shadertype, CRenderTarget* ptextarg) { SetShaderCaller("FlushSetPageOffset"); Vector vpageoffset; vpageoffset.w = 0; switch (shadertype) { case 3: vpageoffset.x = -0.1f / 256.0f; vpageoffset.y = -0.001f / 256.0f; vpageoffset.z = -0.1f / (ptextarg->fbh); vpageoffset.w = 0.0f; break; case 4: vpageoffset.x = 2; vpageoffset.y = 1; vpageoffset.z = 0; vpageoffset.w = 0.0001f; break; } // zoe2 if (PSMT_ISZTEX(ptextarg->psm)) vpageoffset.w = -1.0f; ZZshSetParameter4fv(pfragment->fPageOffset, vpageoffset, "g_fPageOffset"); return vpageoffset; } //Set texture offsets depends omn shader type. inline Vector FlushSetTexOffset(FRAGMENTSHADER* pfragment, int shadertype, VB& curvb, CRenderTarget* ptextarg) { SetShaderCaller("FlushSetTexOffset"); Vector v; if (shadertype == 3) { Vector v; v.x = 16.0f / (float)curvb.tex0.tw; v.y = 16.0f / (float)curvb.tex0.th; v.z = 0.5f * v.x; v.w = 0.5f * v.y; ZZshSetParameter4fv(pfragment->fTexOffset, v, "g_fTexOffset"); } else if (shadertype == 4) { Vector v; v.x = 16.0f / (float)ptextarg->fbw; v.y = 16.0f / (float)ptextarg->fbh; v.z = -1; v.w = 8.0f / (float)ptextarg->fbh; ZZshSetParameter4fv(pfragment->fTexOffset, v, "g_fTexOffset"); } return v; } // Set dimension (Real!) of texture. z and w inline Vector FlushTextureDims(FRAGMENTSHADER* pfragment, int shadertype, VB& curvb, CRenderTarget* ptextarg) { SetShaderCaller("FlushTextureDims"); Vector vTexDims; vTexDims.x = (float)RW(curvb.tex0.tw) ; vTexDims.y = (float)RH(curvb.tex0.th) ; // look at the offset of tbp0 from fbp if (curvb.tex0.tbp0 <= ptextarg->fbp) { vTexDims.z = 0;//-0.5f/(float)ptextarg->fbw; vTexDims.w = 0;//0.2f/(float)ptextarg->fbh; } else { //u32 tbp0 = curvb.tex0.tbp0 >> 5; // align to a page int blockheight = PSMT_ISHALF(ptextarg->psm) ? 64 : 32; int ycoord = ((curvb.tex0.tbp0 - ptextarg->fbp) / (32 * (ptextarg->fbw >> 6))) * blockheight; int xcoord = (((curvb.tex0.tbp0 - ptextarg->fbp) % (32 * (ptextarg -> fbw >> 6)))) * 2; vTexDims.z = (float)xcoord; vTexDims.w = (float)ycoord; } if (shadertype == 4) vTexDims.z += 8.0f; ZZshSetParameter4fv(pfragment->fTexDims, vTexDims, "g_fTexDims"); return vTexDims; } // Apply TEX1 mmag and mmin -- filter for expanding/reducing texture // We ignore all settings, only NEAREST (0) is used inline void FlushApplyResizeFilter(VB& curvb, u32& dwFilterOpts, CRenderTarget* ptextarg, int context) { u32 ptexset = (ptextarg == curvb.prndr) ? ptextarg->ptexFeedback : ptextarg->ptex; s_ptexCurSet[context] = ptexset; if ((!curvb.tex1.mmag) || (!curvb.tex1.mmin)) glBindTexture(GL_TEXTURE_RECTANGLE_NV, ptexset); if (!curvb.tex1.mmag) { glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MAG_FILTER, GL_NEAREST); dwFilterOpts |= 1; } if (!curvb.tex1.mmin) { glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MIN_FILTER, GL_NEAREST); dwFilterOpts |= 2; } } // Usage existing targets depends on several tricks, 32-16 conversion and CLUTing, so we need to handle it. inline FRAGMENTSHADER* FlushUseExistRenderTarget(VB& curvb, CRenderTarget* ptextarg, u32& dwFilterOpts, int exactcolor, int context) { if (ptextarg->IsDepth()) SetWriteDepth(); GLuint ptexclut = 0; //int psm = PIXEL_STORAGE_FORMAT(curvb.tex0); int shadertype = FlushGetShaderType(curvb, ptextarg, ptexclut); FRAGMENTSHADER* pfragment = LoadShadeEffect(shadertype, 0, curvb.curprim.fge, IsAlphaTestExpansion(curvb.tex0), exactcolor, curvb.clamp, context, NULL); Vector vpageoffset = FlushSetPageOffset(pfragment, shadertype, ptextarg); Vector v = FlushSetTexOffset(pfragment, shadertype, curvb, ptextarg); Vector vTexDims = FlushTextureDims(pfragment, shadertype, curvb, ptextarg); if (pfragment->sCLUT != NULL && ptexclut != 0) ZZshGLSetTextureParameter(pfragment->sCLUT, ptexclut, "CLUT"); FlushApplyResizeFilter(curvb, dwFilterOpts, ptextarg, context); if (g_bSaveTex) SaveTexture("tex.tga", GL_TEXTURE_RECTANGLE_NV, ptextarg == curvb.prndr ? ptextarg->ptexFeedback : ptextarg->ptex, RW(ptextarg->fbw), RH(ptextarg->fbh)); return pfragment; } // Usage most major shader. inline FRAGMENTSHADER* FlushMadeNewTarget(VB& curvb, int exactcolor, int context) { // save the texture if (g_bSaveTex) { if (g_bSaveTex == 1) { SaveTex(&curvb.tex0, 1); /*CMemoryTarget* pmemtarg = */ g_MemTargs.GetMemoryTarget(curvb.tex0, 0); } else { SaveTex(&curvb.tex0, 0); } } FRAGMENTSHADER* pfragment = LoadShadeEffect(0, GetTexFilter(curvb.tex1), curvb.curprim.fge, IsAlphaTestExpansion(curvb.tex0), exactcolor, curvb.clamp, context, NULL); if (pfragment == NULL) ZZLog::Error_Log("Could not find memory target shader."); return pfragment; } // We made an shader, so now need to put all common variables. inline void FlushSetTexture(VB& curvb, FRAGMENTSHADER* pfragment, CRenderTarget* ptextarg, int context) { SetTexVariables(context, pfragment); SetTexInt(context, pfragment, ptextarg == NULL); // have to enable the texture parameters(curtest.atst) if( curvb.ptexClamp[0] != 0 ) ZZshGLSetTextureParameter(pfragment->sBitwiseANDX, curvb.ptexClamp[0], "Clamp 0"); if( curvb.ptexClamp[1] != 0 ) ZZshGLSetTextureParameter(pfragment->sBitwiseANDY, curvb.ptexClamp[1], "Clamp 1"); if( pfragment->sMemory != NULL && s_ptexCurSet[context] != 0) ZZshGLSetTextureParameter(pfragment->sMemory, s_ptexCurSet[context], "Clamp memory"); } // Reset program and texture variables; inline void FlushBindProgramm(FRAGMENTSHADER* pfragment, int context) { vb[context].bTexConstsSync = 0; vb[context].bVarsTexSync = 0; ZZshSetPixelShader(pfragment->prog); } inline FRAGMENTSHADER* FlushRendererStage(VB& curvb, u32& dwFilterOpts, CRenderTarget* ptextarg, int exactcolor, int context) { FRAGMENTSHADER* pfragment = NULL; // set the correct pixel shaders if (curvb.curprim.tme) { if (ptextarg != NULL) pfragment = FlushUseExistRenderTarget(curvb, ptextarg, dwFilterOpts, exactcolor, context); else pfragment = FlushMadeNewTarget(curvb, exactcolor, context); if (pfragment == NULL) { ZZLog::Error_Log("Shader is not found."); // return NULL; } FlushSetTexture(curvb, pfragment, ptextarg, context); } else { pfragment = &ppsRegular[curvb.curprim.fge + 2 * s_bWriteDepth]; } GL_REPORT_ERRORD(); // set the shaders SetShaderCaller("FlushRendererStage"); ZZshSetVertexShader(pvs[2 * ((curvb.curprim._val >> 1) & 3) + 8 * s_bWriteDepth + context]); FlushBindProgramm(pfragment, context); GL_REPORT_ERRORD(); return pfragment; } inline bool AlphaCanRenderStencil(VB& curvb) { return g_bUpdateStencil && (PSMT_BITMODE(curvb.prndr->psm) != 1) && !ZZOglGet_fbmHighByte(curvb.frame.fbm) && !(conf.settings().no_stencil); } inline void AlphaSetStencil(bool DoIt) { if (DoIt) { glEnable(GL_STENCIL_TEST); GL_STENCILFUNC(GL_ALWAYS, 0, 0); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); } else glDisable(GL_STENCIL_TEST); } inline void AlphaSetDepthTest(VB& curvb, const pixTest curtest, FRAGMENTSHADER* pfragment) { glDepthMask(!curvb.zbuf.zmsk && curtest.zte); // && curtest.zte && (curtest.ztst > 1) ); if (curtest.zte) { if (curtest.ztst > 1) g_nDepthUsed = 2; if ((curtest.ztst == 2) ^(g_nDepthBias != 0)) { g_nDepthBias = (curtest.ztst == 2); //SETRS(D3DRS_DEPTHBIAS, g_nDepthBias?FtoDW(0.0003f):FtoDW(0.000015f)); } glDepthFunc(g_dwZCmp[curtest.ztst]); } GL_ZTEST(curtest.zte); if (s_bWriteDepth) { if (!curvb.zbuf.zmsk) curvb.pdepth->SetRenderTarget(1); else ResetRenderTarget(1); } } inline u32 AlphaSetupBlendTest(VB& curvb) { if (curvb.curprim.abe) SetAlphaVariables(curvb.alpha); else glDisable(GL_BLEND); u32 oldabe = curvb.curprim.abe; if (gs.pabe) { //ZZLog::Error_Log("PABE!"); curvb.curprim.abe = 1; glEnable(GL_BLEND); } return oldabe; } inline void AlphaRenderFBA(VB& curvb, FRAGMENTSHADER* pfragment, bool s_bDestAlphaTest, bool bCanRenderStencil) { // needs to be before RenderAlphaTest if ((gs.pabe) || (curvb.fba.fba && !ZZOglGet_fbmHighByte(curvb.frame.fbm)) || (s_bDestAlphaTest && bCanRenderStencil)) { RenderFBA(curvb, pfragment->sOneColor); } } inline u32 AlphaRenderAlpha(VB& curvb, const pixTest curtest, FRAGMENTSHADER* pfragment, int exactcolor) { SetShaderCaller("AlphaRenderAlpha"); u32 dwUsingSpecialTesting = 0; if (curvb.curprim.abe) { if ((bNeedBlendFactorInAlpha || ((curtest.ate && curtest.atst > 1) && (curtest.aref > 0x80)))) { // need special stencil processing for the alpha RenderAlphaTest(curvb, pfragment->sOneColor); dwUsingSpecialTesting = 1; } // harvest fishing Vector v = vAlphaBlendColor; if (exactcolor) { v.y *= 255; v.w *= 255; } ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); } else { // not using blending so set to defaults Vector v = exactcolor ? Vector(1, 510 * 255.0f / 256.0f, 0, 0) : Vector(1, 2 * 255.0f / 256.0f, 0, 0); ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); } return dwUsingSpecialTesting; } inline void AlphaRenderStencil(VB& curvb, bool s_bDestAlphaTest, bool bCanRenderStencil, u32 dwUsingSpecialTesting) { if (s_bDestAlphaTest && bCanRenderStencil) { // if not 24bit and can write to high alpha bit RenderStencil(curvb, dwUsingSpecialTesting); } else { s_stencilref = STENCIL_SPECIAL; s_stencilmask = STENCIL_SPECIAL; // setup the stencil to only accept the test pixels if (dwUsingSpecialTesting) { glEnable(GL_STENCIL_TEST); glStencilMask(STENCIL_PIXELWRITE); GL_STENCILFUNC(GL_EQUAL, STENCIL_SPECIAL | STENCIL_PIXELWRITE, STENCIL_SPECIAL); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); } } #ifdef _DEBUG if (bDestAlphaColor == 1) { ZZLog::Debug_Log("Dest alpha blending! Manipulate alpha here."); } #endif if (bCanRenderStencil && gs.pabe) { // only render the pixels with alpha values >= 0x80 GL_STENCILFUNC(GL_EQUAL, s_stencilref | STENCIL_FBA, s_stencilmask | STENCIL_FBA); } GL_REPORT_ERRORD(); } inline void AlphaTest(VB& curvb) { // printf ("%d %d %d %d %d\n", curvb.test.date, curvb.test.datm, gs.texa.aem, curvb.test.ate, curvb.test.atst ); // return; // Zeydlitz changed this with a reason! It's an "Alpha more than 1 hack." if (curvb.test.ate == 1 && curvb.test.atst == 1 && curvb.test.date == 1) { if (curvb.test.datm == 1) { glAlphaFunc(GL_GREATER, 1.0f); } else { glAlphaFunc(GL_LESS, 1.0f); printf("%d %d %d\n", curvb.test.date, curvb.test.datm, gs.texa.aem); } } if (!curvb.test.ate || curvb.test.atst > 0) { Draw(curvb); } GL_REPORT_ERRORD(); } inline void AlphaPabe(VB& curvb, FRAGMENTSHADER* pfragment, int exactcolor) { if (gs.pabe) { SetShaderCaller("AlphaPabe"); // only render the pixels with alpha values < 0x80 glDisable(GL_BLEND); GL_STENCILFUNC_SET(); Vector v; v.x = 1; v.y = 2; v.z = 0; v.w = 0; if (exactcolor) v.y *= 255; ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); Draw(curvb); // reset if (!s_stencilmask) s_stencilfunc = GL_ALWAYS; GL_STENCILFUNC_SET(); } GL_REPORT_ERRORD(); } // Alpha Failure does not work properly on this cases. True means that no failure job should be done. // First three cases are trivial manual. inline bool AlphaFailureIgnore(const pixTest curtest) { if ((!curtest.ate) || (curtest.atst == 1) || (curtest.afail == 0)) return true; if (conf.settings().no_alpha_fail && ((s_dwColorWrite < 8) || (s_dwColorWrite == 15 && curtest.atst == 5 && (curtest.aref == 64)))) return true; // old and seemingly incorrect code. // if ((s_dwColorWrite < 8 && s_dwColorWrite !=8) && curtest.afail == 1) // return true; // if ((s_dwColorWrite == 0xf) && curtest.atst == 5 && curtest.afail == 1 && !(conf.settings() & GAME_REGETHACK)) // return true; return false; } // more work on alpha failure case inline void AlphaFailureTestJob(VB& curvb, const pixTest curtest, FRAGMENTSHADER* pfragment, int exactcolor, bool bCanRenderStencil, int oldabe) { // Note, case when ate == 1, atst == 0 and afail > 0 in documentation wrote as failure case. But it seems that // either doc's are incorrect or this case has some issues. if (AlphaFailureIgnore(curtest)) return; #ifdef NOALFAFAIL ZZLog::Error_Log("Alpha job here %d %d %d %d %d %d", s_dwColorWrite, curtest.atst, curtest.afail, curtest.aref, gs.pabe, s_bWriteDepth); // return; #endif SetShaderCaller("AlphaFailureTestJob"); // need to reverse the test and disable some targets glAlphaFunc(g_dwReverseAlphaCmp[curtest.atst], AlphaReferedValue(curtest.aref)); if (curtest.afail & 1) // front buffer update only { if (curtest.afail == 3) glColorMask(1, 1, 1, 0);// disable alpha glDepthMask(0); if (s_bWriteDepth) ResetRenderTarget(1); } else { // zbuffer update only glColorMask(0, 0, 0, 0); } if (gs.pabe && bCanRenderStencil) { // only render the pixels with alpha values >= 0x80 Vector v = vAlphaBlendColor; if (exactcolor) { v.y *= 255; v.w *= 255; } ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); glEnable(GL_BLEND); GL_STENCILFUNC(GL_EQUAL, s_stencilref | STENCIL_FBA, s_stencilmask | STENCIL_FBA); } Draw(curvb); GL_REPORT_ERRORD(); if (gs.pabe) { // only render the pixels with alpha values < 0x80 glDisable(GL_BLEND); GL_STENCILFUNC_SET(); Vector v; v.x = 1; v.y = 2; v.z = 0; v.w = 0; if (exactcolor) v.y *= 255; ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); Draw(curvb); // reset if (oldabe) glEnable(GL_BLEND); if (!s_stencilmask) s_stencilfunc = GL_ALWAYS; GL_STENCILFUNC_SET(); } // restore if ((curtest.afail & 1) && !curvb.zbuf.zmsk) { glDepthMask(1); if (s_bWriteDepth) { assert(curvb.pdepth != NULL); curvb.pdepth->SetRenderTarget(1); } } GL_COLORMASK(s_dwColorWrite); // not needed anymore since rest of ops concentrate on image processing GL_REPORT_ERRORD(); } inline void AlphaSpecialTesting(VB& curvb, FRAGMENTSHADER* pfragment, u32 dwUsingSpecialTesting, int exactcolor) { if (dwUsingSpecialTesting) { SetShaderCaller("AlphaSpecialTesting"); // render the real alpha glDisable(GL_ALPHA_TEST); glColorMask(0, 0, 0, 1); if (s_bWriteDepth) { ResetRenderTarget(1); } glDepthMask(0); glStencilFunc(GL_EQUAL, STENCIL_SPECIAL | STENCIL_PIXELWRITE, STENCIL_SPECIAL | STENCIL_PIXELWRITE); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); Vector v = Vector(0, exactcolor ? 510.0f : 2.0f, 0, 0); ZZshSetParameter4fv(pfragment->sOneColor, v, "g_fOneColor"); Draw(curvb); // don't need to restore } GL_REPORT_ERRORD(); } inline void AlphaDestinationTest(VB& curvb, FRAGMENTSHADER* pfragment, bool s_bDestAlphaTest, bool bCanRenderStencil) { if (s_bDestAlphaTest) { if ((s_dwColorWrite & COLORMASK_ALPHA)) { if (curvb.fba.fba) ProcessFBA(curvb, pfragment->sOneColor); else if (bCanRenderStencil) // finally make sure all entries are 1 when the dest alpha >= 0x80 (if fba is 1, this is already the case) ProcessStencil(curvb); } } else if ((s_dwColorWrite & COLORMASK_ALPHA) && curvb.fba.fba) ProcessFBA(curvb, pfragment->sOneColor); if (bDestAlphaColor == 1) { // need to reset the dest colors to their original counter parts //WARN_LOG("Need to reset dest alpha color\n"); } } inline void AlphaSaveTarget(VB& curvb) { #ifdef _DEBUG return; // Do nothing // if( g_bSaveFlushedFrame & 0xf ) { //#ifdef _WIN32 // CreateDirectory("frames", NULL); //#else // char* strdir=""; // sprintf(strdir, "mkdir %s", "frames"); // system(strdir); //#endif // char str[255]; // sprintf(str, "frames/frame%.4d.tga", g_SaveFrameNum++); // //glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); // switch to the backbuffer // //glFlush(); // //SaveTexture("tex.jpg", GL_TEXTURE_RECTANGLE_NV, curvb.prndr->ptex, RW(curvb.prndr->fbw), RH(curvb.prndr->fbh)); // SaveRenderTarget(str, RW(curvb.prndr->fbw), RH(curvb.prndr->fbh), 0); // } #endif } inline void AlphaColorClamping(VB& curvb, const pixTest curtest) { // clamp the final colors, when enabled ffx2 credits mess up //if (gs.colclamp) ZZLog::Error_Log("ColClamp!"); if ((curvb.curprim.abe && bAlphaClamping) && (GetRenderFormat() != RFT_byte8) && !(conf.settings().no_color_clamp)) // if !colclamp, skip { //ZZLog::Error_Log("Clamped."); ResetAlphaVariables(); // if processing the clamping case, make sure can write to the front buffer glDisable(GL_STENCIL_TEST); glEnable(GL_BLEND); glDisable(GL_ALPHA_TEST); glDisable(GL_DEPTH_TEST); glDepthMask(0); glColorMask(1, 1, 1, 0); if (s_bWriteDepth) ResetRenderTarget(1); SetShaderCaller("AlphaColorClamping"); ZZshSetPixelShader(ppsOne.prog); GL_BLEND_RGB(GL_ONE, GL_ONE); float f; if (bAlphaClamping & 1) // min { f = 0; ZZshSetParameter4fv(ppsOne.sOneColor, &f, "g_fOneColor"); GL_BLENDEQ_RGB(GL_MAX_EXT); Draw(curvb); } // bios shows white screen if (bAlphaClamping & 2) // max { f = 1; ZZshSetParameter4fv(ppsOne.sOneColor, &f, "g_fOneColor"); GL_BLENDEQ_RGB(GL_MIN_EXT); Draw(curvb); } if (!curvb.zbuf.zmsk) { glDepthMask(1); if (s_bWriteDepth) { assert(curvb.pdepth != NULL); curvb.pdepth->SetRenderTarget(1); } } if (curvb.test.ate && USEALPHATESTING) glEnable(GL_ALPHA_TEST); GL_ZTEST(curtest.zte); } } inline void FlushUndoFiter(u32 dwFilterOpts) { if (dwFilterOpts) { // undo filter changes (binding didn't change) if (dwFilterOpts & 1) glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (dwFilterOpts & 2) glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } // This is the most important function! It draws all collected info onscreen. void ZeroGS::Flush(int context) { FUNCLOG VB& curvb = vb[context]; const pixTest curtest = curvb.test; if (FlushInitialTest(curvb, curtest, context)) return; VisualBufferMessage(context); GL_REPORT_ERRORD(); CRenderTarget* ptextarg = FlushGetTarget(curvb); SwitchWireframeOff(); FlushDoContextJob(curvb, context); u32 dwUsingSpecialTesting = 0, dwFilterOpts = 0; int exactcolor = FlushGetExactcolor(curtest); FRAGMENTSHADER* pfragment = FlushRendererStage(curvb, dwFilterOpts, ptextarg, exactcolor, context); bool bCanRenderStencil = AlphaCanRenderStencil(curvb); if (curtest.date || gs.pabe) SetDestAlphaTest(); AlphaSetStencil(s_bDestAlphaTest && bCanRenderStencil); AlphaSetDepthTest(curvb, curtest, pfragment); // Error! SetAlphaTest(curtest); u32 oldabe = AlphaSetupBlendTest(curvb); // Unavoidable // needs to be before RenderAlphaTest AlphaRenderFBA(curvb, pfragment, s_bDestAlphaTest, bCanRenderStencil); dwUsingSpecialTesting = AlphaRenderAlpha(curvb, curtest, pfragment, exactcolor); // Unavoidable AlphaRenderStencil(curvb, s_bDestAlphaTest, bCanRenderStencil, dwUsingSpecialTesting); AlphaTest(curvb); // Unavoidable AlphaPabe(curvb, pfragment, exactcolor); AlphaFailureTestJob(curvb, curtest, pfragment, exactcolor, bCanRenderStencil, oldabe); AlphaSpecialTesting(curvb, pfragment, dwUsingSpecialTesting, exactcolor); AlphaDestinationTest(curvb, pfragment, s_bDestAlphaTest, bCanRenderStencil); AlphaSaveTarget(curvb); GL_REPORT_ERRORD(); AlphaColorClamping(curvb, curtest); FlushUndoFiter(dwFilterOpts); ppf += curvb.nCount + 0x100000; curvb.nCount = 0; curvb.curprim.abe = oldabe; SwitchWireframeOn(); GL_REPORT_ERRORD(); } void ZeroGS::FlushBoth() { Flush(0); Flush(1); } inline void ZeroGS::RenderFBA(const VB& curvb, ZZshParameter sOneColor) { // add fba to all pixels GL_STENCILFUNC(GL_ALWAYS, STENCIL_FBA, 0xff); glStencilMask(STENCIL_CLEAR); glStencilOp(GL_ZERO, GL_KEEP, GL_REPLACE); glDisable(GL_DEPTH_TEST); glDepthMask(0); glColorMask(0, 0, 0, 0); if (s_bWriteDepth) ResetRenderTarget(1); SetShaderCaller("RenderFBA"); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 1); Vector v(1,2,0,0); ZZshSetParameter4fv(sOneColor, v, "g_fOneColor"); Draw(curvb); SetAlphaTest(curvb.test); // reset (not necessary) GL_COLORMASK(s_dwColorWrite); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); if (!curvb.zbuf.zmsk) { glDepthMask(1); assert(curvb.pdepth != NULL); if (s_bWriteDepth) curvb.pdepth->SetRenderTarget(1); } GL_ZTEST(curvb.test.zte); } __forceinline void ZeroGS::RenderAlphaTest(const VB& curvb, ZZshParameter sOneColor) { if (!g_bUpdateStencil) return; if ((curvb.test.ate) && (curvb.test.afail == 1)) glDisable(GL_ALPHA_TEST); glDepthMask(0); glColorMask(0, 0, 0, 0); if (s_bWriteDepth) ResetRenderTarget(1); SetShaderCaller("RenderAlphaTest"); Vector v(1,2,0,0); ZZshSetParameter4fv(sOneColor, v, "g_fOneColor"); // or a 1 to the stencil buffer wherever alpha passes glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); s_stencilfunc = GL_ALWAYS; glEnable(GL_STENCIL_TEST); if (!s_bDestAlphaTest) { // clear everything s_stencilref = 0; glStencilMask(STENCIL_CLEAR); glDisable(GL_ALPHA_TEST); GL_STENCILFUNC_SET(); Draw(curvb); if (curvb.test.ate && curvb.test.afail != 1 && USEALPHATESTING) glEnable(GL_ALPHA_TEST); } if (curvb.test.ate && curvb.test.atst > 1 && curvb.test.aref > 0x80) { v = Vector(1,1,0,0); ZZshSetParameter4fv(sOneColor, v, "g_fOneColor"); glAlphaFunc(g_dwAlphaCmp[curvb.test.atst], AlphaReferedValue(curvb.test.aref)); } s_stencilref = STENCIL_SPECIAL; glStencilMask(STENCIL_SPECIAL); GL_STENCILFUNC_SET(); glDisable(GL_DEPTH_TEST); Draw(curvb); if (curvb.test.zte) glEnable(GL_DEPTH_TEST); GL_ALPHATEST(0); GL_COLORMASK(s_dwColorWrite); if (!curvb.zbuf.zmsk) { glDepthMask(1); // set rt next level if (s_bWriteDepth) curvb.pdepth->SetRenderTarget(1); } } inline void ZeroGS::RenderStencil(const VB& curvb, u32 dwUsingSpecialTesting) { //NOTE: This stencil hack for dest alpha testing ONLY works when // the geometry in one DrawPrimitive call does not overlap // mark the stencil buffer for the new data's bits (mark 4 if alpha is >= 0xff) // mark 4 if a pixel was written (so that the stencil buf can be changed with new values) glStencilMask(STENCIL_PIXELWRITE); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); s_stencilmask = (curvb.test.date ? STENCIL_ALPHABIT : 0) | (dwUsingSpecialTesting ? STENCIL_SPECIAL : 0); s_stencilfunc = s_stencilmask ? GL_EQUAL : GL_ALWAYS; s_stencilref = curvb.test.date * curvb.test.datm | STENCIL_PIXELWRITE | (dwUsingSpecialTesting ? STENCIL_SPECIAL : 0); GL_STENCILFUNC_SET(); } inline void ZeroGS::ProcessStencil(const VB& curvb) { assert(!curvb.fba.fba); // set new alpha bit glStencilMask(STENCIL_ALPHABIT); GL_STENCILFUNC(GL_EQUAL, STENCIL_PIXELWRITE, STENCIL_PIXELWRITE | STENCIL_FBA); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glDisable(GL_DEPTH_TEST); glDepthMask(0); glColorMask(0, 0, 0, 0); if (s_bWriteDepth) ResetRenderTarget(1); GL_ALPHATEST(0); SetShaderCaller("ProcessStencil"); ZZshSetPixelShader(ppsOne.prog); Draw(curvb); // process when alpha >= 0xff GL_STENCILFUNC(GL_EQUAL, STENCIL_PIXELWRITE | STENCIL_FBA | STENCIL_ALPHABIT, STENCIL_PIXELWRITE | STENCIL_FBA); Draw(curvb); // clear STENCIL_PIXELWRITE bit glStencilMask(STENCIL_CLEAR); GL_STENCILFUNC(GL_ALWAYS, 0, STENCIL_PIXELWRITE | STENCIL_FBA); Draw(curvb); // restore state GL_COLORMASK(s_dwColorWrite); if (curvb.test.ate && USEALPHATESTING) glEnable(GL_ALPHA_TEST); if (!curvb.zbuf.zmsk) { glDepthMask(1); if (s_bWriteDepth) { assert(curvb.pdepth != NULL); curvb.pdepth->SetRenderTarget(1); } } GL_ZTEST(curvb.test.zte); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); } __forceinline void ZeroGS::ProcessFBA(const VB& curvb, ZZshParameter sOneColor) { if ((curvb.frame.fbm&0x80000000)) return; // add fba to all pixels that were written and alpha was less than 0xff glStencilMask(STENCIL_ALPHABIT); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); GL_STENCILFUNC(GL_EQUAL, STENCIL_FBA | STENCIL_PIXELWRITE | STENCIL_ALPHABIT, STENCIL_PIXELWRITE | STENCIL_FBA); glDisable(GL_DEPTH_TEST); glDepthMask(0); glColorMask(0, 0, 0, 1); if (s_bWriteDepth) ResetRenderTarget(1); SetShaderCaller("ProcessFBA"); // processes the pixels with ALPHA < 0x80*2 glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_LEQUAL, 1); // add 1 to dest GL_BLEND_ALPHA(GL_ONE, GL_ONE); GL_BLENDEQ_ALPHA(GL_FUNC_ADD); float f = 1; ZZshSetParameter4fv(sOneColor, &f, "g_fOneColor"); ZZshSetPixelShader(ppsOne.prog); Draw(curvb); glDisable(GL_ALPHA_TEST); // reset bits glStencilMask(STENCIL_CLEAR); GL_STENCILFUNC(GL_GREATER, 0, STENCIL_PIXELWRITE | STENCIL_FBA); glStencilOp(GL_KEEP, GL_KEEP, GL_ZERO); Draw(curvb); if (curvb.test.atst && USEALPHATESTING) { glEnable(GL_ALPHA_TEST); glAlphaFunc(g_dwAlphaCmp[curvb.test.atst], AlphaReferedValue(curvb.test.aref)); } // restore (SetAlphaVariables) GL_BLEND_ALPHA(GL_ONE, GL_ZERO); if (vAlphaBlendColor.y < 0) GL_BLENDEQ_ALPHA(GL_FUNC_REVERSE_SUBTRACT); // reset (not necessary) GL_COLORMASK(s_dwColorWrite); if (!curvb.zbuf.zmsk) { glDepthMask(1); if (s_bWriteDepth) curvb.pdepth->SetRenderTarget(1); } GL_ZTEST(curvb.test.zte); } void ZeroGS::SetContextTarget(int context) { FUNCLOG VB& curvb = vb[context]; GL_REPORT_ERRORD(); if (curvb.prndr == NULL) curvb.prndr = s_RTs.GetTarg(curvb.frame, 0, get_maxheight(curvb.gsfb.fbp, curvb.gsfb.fbw, curvb.gsfb.psm)); // make sure targets are valid if (curvb.pdepth == NULL) { frameInfo f; f.fbp = curvb.zbuf.zbp; f.fbw = curvb.frame.fbw; f.fbh = curvb.prndr->fbh; f.psm = curvb.zbuf.psm; f.fbm = 0; curvb.pdepth = (CDepthTarget*)s_DepthRTs.GetTarg(f, CRenderTargetMngr::TO_DepthBuffer | CRenderTargetMngr::TO_StrictHeight | (curvb.zbuf.zmsk ? CRenderTargetMngr::TO_Virtual : 0), get_maxheight(curvb.zbuf.zbp, curvb.gsfb.fbw, 0)); } assert(curvb.prndr != NULL && curvb.pdepth != NULL); if (curvb.pdepth->fbh != curvb.prndr->fbh) ZZLog::Debug_Log("(curvb.pdepth->fbh(0x%x) != curvb.prndr->fbh(0x%x))", curvb.pdepth->fbh, curvb.prndr->fbh); //assert(curvb.pdepth->fbh == curvb.prndr->fbh); if (curvb.pdepth->status & CRenderTarget::TS_Virtual) { if (!curvb.zbuf.zmsk) { CRenderTarget* ptemp = s_DepthRTs.Promote(curvb.pdepth->fbp | (curvb.pdepth->fbw << 16)); assert(ptemp == curvb.pdepth); } else { curvb.pdepth->status &= ~CRenderTarget::TS_NeedUpdate; } } bool bSetTarg = 1; if (curvb.pdepth->status & CRenderTarget::TS_NeedUpdate) { assert(!(curvb.pdepth->status & CRenderTarget::TS_Virtual)); // don't update if virtual curvb.pdepth->Update(context, curvb.prndr); bSetTarg = 0; } GL_REPORT_ERRORD(); if (curvb.prndr->status & CRenderTarget::TS_NeedUpdate) { /* if(bSetTarg) { * printf ( " Here\n "); * if(s_bWriteDepth) { * curvb.pdepth->SetRenderTarget(1); * curvb.pdepth->SetDepthStencilSurface(); * } * else * curvb.pdepth->SetDepthStencilSurface(); * }*/ curvb.prndr->Update(context, curvb.pdepth); } else { //if( (vb[0].prndr != vb[1].prndr && vb[!context].bVarsSetTarg) || !vb[context].bVarsSetTarg ) curvb.prndr->SetRenderTarget(0); //if( bSetTarg && ((vb[0].pdepth != vb[1].pdepth && vb[!context].bVarsSetTarg) || !vb[context].bVarsSetTarg) ) curvb.pdepth->SetDepthStencilSurface(); if (conf.mrtdepth && ZeroGS::IsWriteDepth()) curvb.pdepth->SetRenderTarget(1); if (s_ptexCurSet[0] == curvb.prndr->ptex) s_ptexCurSet[0] = 0; if (s_ptexCurSet[1] == curvb.prndr->ptex) s_ptexCurSet[1] = 0; curvb.prndr->SetViewport(); } curvb.prndr->SetTarget(curvb.frame.fbp, curvb.scissor, context); if ((curvb.zbuf.zbp - curvb.pdepth->fbp) != (curvb.frame.fbp - curvb.prndr->fbp) && curvb.test.zte) ZZLog::Warn_Log("Frame and zbuf not aligned."); curvb.bVarsSetTarg = true; if (vb[!context].prndr != curvb.prndr) vb[!context].bVarsSetTarg = false; #ifdef _DEBUG // These conditions happen often enough that we'll just warn about it rather then abort in Debug mode. if (curvb.prndr->status & CRenderTarget::TS_NeedUpdate) { ZZLog::Debug_Log("In SetContextTarget, prndr is ending with TS_NeedUpdate set."); } if (curvb.pdepth != NULL && (curvb.pdepth->status & CRenderTarget::TS_NeedUpdate)) { ZZLog::Debug_Log("In SetContextTarget, pdepth is ending with TS_NeedUpdate set."); } #endif GL_REPORT_ERRORD(); } void ZeroGS::SetTexInt(int context, FRAGMENTSHADER* pfragment, int settexint) { FUNCLOG if (settexint) { tex0Info& tex0 = vb[context].tex0; CMemoryTarget* pmemtarg = g_MemTargs.GetMemoryTarget(tex0, 1); if (vb[context].bVarsTexSync) { if (vb[context].pmemtarg != pmemtarg) { SetTexVariablesInt(context, GetTexFilter(vb[context].tex1), tex0, true, pfragment, s_bForceTexFlush); vb[context].bVarsTexSync = true; } } else { SetTexVariablesInt(context, GetTexFilter(vb[context].tex1), tex0, false, pfragment, s_bForceTexFlush); vb[context].bVarsTexSync = true; INC_TEXVARS(); } } else { vb[context].bVarsTexSync = false; } } // clamp relies on texture width void ZeroGS::SetTexClamping(int context, FRAGMENTSHADER* pfragment) { FUNCLOG SetShaderCaller("SetTexClamping"); clampInfo* pclamp = &ZeroGS::vb[context].clamp; Vector v, v2; v.x = v.y = 0; u32* ptex = ZeroGS::vb[context].ptexClamp; ptex[0] = ptex[1] = 0; float fw = ZeroGS::vb[context].tex0.tw ; float fh = ZeroGS::vb[context].tex0.th ; switch (pclamp->wms) { case 0: v2.x = -1e10; v2.z = 1e10; break; case 1: // pclamp // suikoden5 movie text v2.x = 0; v2.z = 1 - 0.5f / fw; break; case 2: // reg pclamp v2.x = (pclamp->minu + 0.5f) / fw; v2.z = (pclamp->maxu - 0.5f) / fw; break; case 3: // region rep x v.x = 0.9999f; v.z = (float)fw; v2.x = (float)GPU_TEXMASKWIDTH / fw; v2.z = pclamp->maxu / fw; int correctMinu = pclamp->minu & (~pclamp->maxu); // (A && B) || C == (A && (B && !C)) + C if (correctMinu != g_PrevBitwiseTexX) { g_PrevBitwiseTexX = correctMinu; ptex[0] = ZeroGS::s_BitwiseTextures.GetTex(correctMinu, 0); } break; } switch (pclamp->wmt) { case 0: v2.y = -1e10; v2.w = 1e10; break; case 1: // pclamp // suikoden5 movie text v2.y = 0; v2.w = 1 - 0.5f / fh; break; case 2: // reg pclamp v2.y = (pclamp->minv + 0.5f) / fh; v2.w = (pclamp->maxv - 0.5f) / fh; break; case 3: // region rep y v.y = 0.9999f; v.w = (float)fh; v2.y = (float)GPU_TEXMASKWIDTH / fh; v2.w = pclamp->maxv / fh; int correctMinv = pclamp->minv & (~pclamp->maxv); // (A && B) || C == (A && (B && !C)) + C if (correctMinv != g_PrevBitwiseTexY) { g_PrevBitwiseTexY = correctMinv; ptex[1] = ZeroGS::s_BitwiseTextures.GetTex(correctMinv, ptex[0]); } break; } if (pfragment->fTexWrapMode != 0) ZZshSetParameter4fv(pfragment->fTexWrapMode, v, "g_fTexWrapMode"); if (pfragment->fClampExts != 0) ZZshSetParameter4fv(pfragment->fClampExts, v2, "g_fClampExts"); } // Fixme should be in Vector lib inline bool equal_vectors(Vector a, Vector b) { if (abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z) + abs(a.w - b.w) < 0.01) return true; else return false; } int CheckTexArray[4][2][2][2] = {{{{0, }}}}; void ZeroGS::SetTexVariables(int context, FRAGMENTSHADER* pfragment) { FUNCLOG if (!vb[context].curprim.tme) return; assert(!vb[context].bNeedTexCheck); Vector v, v2; tex0Info& tex0 = vb[context].tex0; //float fw = (float)tex0.tw; //float fh = (float)tex0.th; if (!vb[context].bTexConstsSync) { SetShaderCaller("SetTexVariables"); // alpha and texture highlighting Vector valpha, valpha2 ; // if clut, use the frame format int psm = PIXEL_STORAGE_FORMAT(tex0); // ZZLog::Error_Log( "A %d psm, is-clut %d. cpsm %d | %d %d", psm, PSMT_ISCLUT(psm), tex0.cpsm, tex0.tfx, tex0.tcc ); Vector vblack; vblack.x = vblack.y = vblack.z = vblack.w = 10; /* tcc -- Tecture Color Component 0=RGB, 1=RGBA + use Alpha from TEXA reg when not in PSM * tfx -- Texture Function (0=modulate, 1=decal, 2=hilight, 3=hilight2) * * valpha2 = 0 0 2 1 0 0 2 1 * 1 0 0 0 1 1 0 0 * 0 0 2 0 0 1 2 0 * 0 0 2 0 0 1 2 0 * * 0 1,!nNeed 1, psm=2, 10 1, psm=1 * valpha = 0 0 0 1 0 2 0 0 2ta0 2ta1-2ta0 0 0 2ta0 0 0 0 * 0 0 0 1 0 1 0 0 ta0 ta1-ta0 0 0 ta0 0 0 0 * 0 0 1 1 0 1 1 1 1 1 ta0 0 1 1 * 0 0 1 1 0 1 1 0 1 0 ta0 0 1 0 */ valpha2.x = (tex0.tfx == 1) ; valpha2.y = (tex0.tcc == 1) && (tex0.tfx != 0) ; valpha2.z = (tex0.tfx != 1) * 2 ; valpha2.w = (tex0.tfx == 0) ; if (tex0.tcc == 0 || !PSMT_ALPHAEXP(psm)) { valpha.x = 0 ; valpha.y = (!!tex0.tcc) * (1 + (tex0.tfx == 0)) ; } else { valpha.x = (gs.texa.fta[0]) * (1 + (tex0.tfx == 0)) ; valpha.y = (gs.texa.fta[psm != PSMCT24] - gs.texa.fta[0]) * (1 + (tex0.tfx == 0)) ; } valpha.z = (tex0.tfx >= 3) ; valpha.w = (tex0.tcc == 0) || (tex0.tcc == 1 && tex0.tfx == 2) ; if (tex0.tcc && gs.texa.aem && psm == PSMCT24) vblack.w = 0; /* // Test, old code. Vector valpha3, valpha4; switch(tex0.tfx) { case 0: valpha3.z = 0; valpha3.w = 0; valpha4.x = 0; valpha4.y = 0; valpha4.z = 2; valpha4.w = 1; break; case 1: valpha3.z = 0; valpha3.w = 1; valpha4.x = 1; valpha4.y = 0; valpha4.z = 0; valpha4.w = 0; break; case 2: valpha3.z = 1; valpha3.w = 1.0f; valpha4.x = 0; valpha4.y = tex0.tcc ? 1.0f : 0.0f; valpha4.z = 2; valpha4.w = 0; break; case 3: valpha3.z = 1; valpha3.w = tex0.tcc ? 0.0f : 1.0f; valpha4.x = 0; valpha4.y = tex0.tcc ? 1.0f : 0.0f; valpha4.z = 2; valpha4.w = 0; break; } if( tex0.tcc ) { if( tex0.tfx == 1 ) { //mode.x = 10; valpha3.z = 0; valpha3.w = 0; valpha4.x = 1; valpha4.y = 1; valpha4.z = 0; valpha4.w = 0; } if( PSMT_ALPHAEXP(psm) ) { if( tex0.tfx == 0 ) { // make sure alpha is mult by two when the output is Cv = Ct*Cf valpha3.x = 2*gs.texa.fta[0]; // if 24bit, always choose ta[0] valpha3.y = 2*gs.texa.fta[psm != 1]; valpha3.y -= valpha.x; } else { valpha3.x = gs.texa.fta[0]; // if 24bit, always choose ta[0] valpha3.y = gs.texa.fta[psm != 1]; valpha3.y -= valpha.x; } } else { if( tex0.tfx == 0 ) { valpha3.x = 0; valpha3.y = 2; } else { valpha3.x = 0; valpha3.y = 1; } } } else { // reset alpha to color valpha3.x = valpha3.y = 0; valpha3.w = 1; } if ( equal_vectors(valpha, valpha3) && equal_vectors(valpha2, valpha4) ) { if (CheckTexArray[tex0.tfx][tex0.tcc][psm!=1][PSMT_ALPHAEXP(psm)] == 0) { printf ( "Good issue %d %d %d %d\n", tex0.tfx, tex0.tcc, psm, PSMT_ALPHAEXP(psm) ); CheckTexArray[tex0.tfx][tex0.tcc][psm!=1][PSMT_ALPHAEXP(psm) ] = 1; } } else if (CheckTexArray[tex0.tfx][tex0.tcc][psm!=1][PSMT_ALPHAEXP(psm)] == -1) { printf ("Bad array, %d %d %d %d\n\tolf valpha %f, %f, %f, %f : valpha2 %f %f %f %f\n\tnew valpha %f, %f, %f, %f : valpha2 %f %f %f %f\n", tex0.tfx, tex0.tcc, psm, PSMT_ALPHAEXP(psm), valpha3.x, valpha3.y, valpha3.z, valpha3.w, valpha4.x, valpha4.y, valpha4.z, valpha4.w, valpha.x, valpha.y, valpha.z, valpha.w, valpha2.x, valpha2.y, valpha2.z, valpha2.w); CheckTexArray[tex0.tfx][tex0.tcc][psm!=1][PSMT_ALPHAEXP(psm)] = -1 ; } // Test;*/ ZZshSetParameter4fv(pfragment->fTexAlpha, valpha, "g_fTexAlpha"); ZZshSetParameter4fv(pfragment->fTexAlpha2, valpha2, "g_fTexAlpha2"); if (IsAlphaTestExpansion(tex0)) ZZshSetParameter4fv(pfragment->fTestBlack, vblack, "g_fTestBlack"); SetTexClamping(context, pfragment); vb[context].bTexConstsSync = true; } if (s_bTexFlush) { if (PSMT_ISCLUT(tex0.psm)) texClutWrite(context); else s_bTexFlush = false; } } void ZeroGS::SetTexVariablesInt(int context, int bilinear, const tex0Info& tex0, bool CheckVB, FRAGMENTSHADER* pfragment, int force) { FUNCLOG Vector v; CMemoryTarget* pmemtarg = g_MemTargs.GetMemoryTarget(tex0, 1); assert( pmemtarg != NULL && pfragment != NULL && pmemtarg->ptex != NULL); if (pmemtarg == NULL || pfragment == NULL || pmemtarg->ptex == NULL) { ZZLog::Error_Log("SetTexVariablesInt error."); return; } if (CheckVB && vb[context].pmemtarg == pmemtarg) return; SetShaderCaller("SetTexVariablesInt"); float fw = (float)tex0.tw; float fh = (float)tex0.th; bool bUseBilinear = bilinear > 1 || (bilinear && conf.bilinear); if (bUseBilinear) { v.x = (float)fw; v.y = (float)fh; v.z = 1.0f / (float)fw; v.w = 1.0f / (float)fh; if (pfragment->fRealTexDims) ZZshSetParameter4fv(pfragment->fRealTexDims, v, "g_fRealTexDims"); else ZZshSetParameter4fv(cgGetNamedParameter(pfragment->prog,"g_fRealTexDims"),v, "g_fRealTexDims"); } if (m_Blocks[tex0.psm].bpp == 0) { ZZLog::Error_Log("Undefined tex psm 0x%x!", tex0.psm); return; } const BLOCK& b = m_Blocks[tex0.psm]; float fbw = (float)tex0.tbw; Vector vTexDims; vTexDims.x = b.vTexDims.x * (fw); vTexDims.y = b.vTexDims.y * (fh); vTexDims.z = (float)BLOCK_TEXWIDTH * (0.002f / 64.0f + 0.01f / 128.0f); vTexDims.w = (float)BLOCK_TEXHEIGHT * 0.1f / 512.0f; if (bUseBilinear) { vTexDims.x *= 1 / 128.0f; vTexDims.y *= 1 / 512.0f; vTexDims.z *= 1 / 128.0f; vTexDims.w *= 1 / 512.0f; } float g_fitexwidth = g_fiGPU_TEXWIDTH / (float)pmemtarg->widthmult; //float g_texwidth = GPU_TEXWIDTH*(float)pmemtarg->widthmult; float fpage = tex0.tbp0 * (64.0f * g_fitexwidth);// + 0.05f * g_fitexwidth; float fpageint = floorf(fpage); //int starttbp = (int)fpage; // 2048 is number of words to span one page //float fblockstride = (2048.0f /(float)(g_texwidth*BLOCK_TEXWIDTH)) * b.vTexDims.x * fbw; float fblockstride = (2048.0f / (float)(GPU_TEXWIDTH * (float)pmemtarg->widthmult * BLOCK_TEXWIDTH)) * b.vTexDims.x * fbw; assert(fblockstride >= 1.0f); v.x = (float)(2048 * g_fitexwidth); v.y = fblockstride; v.z = g_fBlockMult / (float)pmemtarg->widthmult; v.w = fpage - fpageint ; if (g_fBlockMult > 1) { // make sure to divide by mult (since the G16R16 texture loses info) v.z *= b.bpp * (1 / 32.0f); } ZZshSetParameter4fv(pfragment->fTexDims, vTexDims, "g_fTexDims"); // ZZshSetParameter4fv(pfragment->fTexBlock, b.vTexBlock, "g_fTexBlock"); // I change it, and it's working. Seems casting from Vector to float[4] is ok. ZZshSetParameter4fv(pfragment->fTexBlock, &b.vTexBlock.x, "g_fTexBlock"); ZZshSetParameter4fv(pfragment->fTexOffset, v, "g_fTexOffset"); // get hardware texture dims //int texheight = (pmemtarg->realheight+pmemtarg->widthmult-1)/pmemtarg->widthmult; int texwidth = GPU_TEXWIDTH * pmemtarg->widthmult * pmemtarg->channels; v.y = 1.0f; v.x = (fpageint - (float)pmemtarg->realy / (float)pmemtarg->widthmult + 0.5f);//*v.y; v.z = (float)texwidth; /* if( !(g_nPixelShaderVer & SHADER_ACCURATE) || bUseBilinear ) { if (tex0.psm == PSMT4 ) v.w = 0.0f; else v.w = 0.25f; } else v.w = 0.5f;*/ v.w = 0.5f; ZZshSetParameter4fv(pfragment->fPageOffset, v, "g_fPageOffset"); if (force) s_ptexCurSet[context] = pmemtarg->ptex->tex; else s_ptexNextSet[context] = pmemtarg->ptex->tex; vb[context].pmemtarg = pmemtarg; vb[context].bVarsTexSync = false; } #define SET_ALPHA_COLOR_FACTOR(sign) \ { \ switch(a.c) \ { \ case 0: \ vAlphaBlendColor.y = (sign) ? 2.0f*255.0f/256.0f : -2.0f*255.0f/256.0f; \ s_srcalpha = GL_ONE; \ s_alphaeq = (sign) ? GL_FUNC_ADD : GL_FUNC_REVERSE_SUBTRACT; \ break; \ \ case 1: \ /* if in 24 bit mode, dest alpha should be one */ \ switch(PSMT_BITMODE(vb[icurctx].prndr->psm)) \ { \ case 0: \ bDestAlphaColor = (a.d!=2)&&((a.a==a.d)||(a.b==a.d)); \ break; \ \ case 1: \ /* dest alpha should be one */ \ bDestAlphaColor = 2; \ break; \ /* default: 16bit surface, so returned alpha is ok */ \ } \ break; \ \ case 2: \ bNeedBlendFactorInAlpha = true; /* should disable alpha channel writing */ \ vAlphaBlendColor.y = 0; \ vAlphaBlendColor.w = (sign) ? (float)a.fix * (2.0f/255.0f) : (float)a.fix * (-2.0f/255.0f); \ usec = 0; /* change so that alpha comes from source*/ \ break; \ } \ } \ //if( a.fix <= 0x80 ) { \ // dwTemp = (a.fix*2)>255?255:(a.fix*2); \ // dwTemp = dwTemp|(dwTemp<<8)|(dwTemp<<16)|0x80000000; \ // printf("bfactor: %8.8x\n", dwTemp); \ // glBlendColorEXT(dwTemp); \ // } \ // else { \ void ZeroGS::ResetAlphaVariables() { FUNCLOG } inline void ZeroGS::NeedFactor(int w) { if (bDestAlphaColor == 2) { bNeedBlendFactorInAlpha = (w + 1) ? true : false; vAlphaBlendColor.y = 0; vAlphaBlendColor.w = (float)w; } } //static int CheckArray[48][2] = {{0,}}; void ZeroGS::SetAlphaVariables(const alphaInfo& a) { FUNCLOG bool alphaenable = true; // TODO: negative color when not clamping turns to positive??? g_vars._bAlphaState = 0; // set all to zero bNeedBlendFactorInAlpha = false; b2XAlphaTest = 1; //u32 dwTemp = 0xffffffff; bDestAlphaColor = 0; // default s_srcalpha = GL_ONE; s_dstalpha = GL_ZERO; s_alphaeq = GL_FUNC_ADD; s_rgbeq = 1; // s_alphaInfo = a; vAlphaBlendColor = Vector(1, 2 * 255.0f / 256.0f, 0, 0); u32 usec = a.c; /* * Alpha table * a + b + d * S D * 0 a -a 1 | 0 0 0 * 1 0 0 0 | a -a 1 * 2 0 0 0 | 0 0 0 * * d = 0 Cs * a b 0 Cs 1 Cd 2 0 * | | * 0 000: a+-a+ 1 | 0+ 0+ 0 = 1 | 010: a+ 0+ 1 | 0+-a+ 0 = 1-(-a)(+)(-a) | 020: a+ 0+ 1 | 0+ 0+ 0 = 1-(-a) (+) 0 * 1 100: 0+-a+ 1 | a+ 0+ 0 = 1-a (+) a | 110: 0+ 0+ 1 | a+-a+ 0 = 1 | 120: 0+ 0+ 1 | a+ 0+ 0 = 1 (+) a * 2 200: 0+-a+ 1 | 0+ 0+ 0 = 1-a (+) 0 | 210: 0+ 0+ 1 | 0+-a+ 0 = 1 (-) a | 220: 0+ 0+ 1 | 0+ 0+ 0 = 1 * * d = 1 Cd * 0 | 1 | 2 * 0 001: a+-a+ 0 | 0+ 0+ 1 = 0 (+) 1 | 011: a+ 0+ 0 | 0+-a+ 1 = a (+) 1-a | 021: a+ 0+ 0 | 0+ 0+ 1 = a (+) 1 * 1 101: 0+-a+ 0 | a+ 0+ 1 = (-a)(+) 1-(-a) | 111: 0+ 0+ 0 | a+-a+ 1 = 0 (+) 1 | 121: 0+ 0+ 0 | a+ 0+ 1 = 0 (+) 1-(-a) * 2 201: 0+-a+ 0 | 0+ 0+ 1 = a (R-)1 | 211: 0+ 0+ 0 | 0+-a+ 1 = 0 (+) 1-a | 221: 0+ 0+ 0 | 0+ 0+ 1 = 0 (+) 1 * * d = 2 0 * 0 | 1 | 2 * 0 002: a+-a+ 0 | 0+ 0+ 0 = 0 | 012: a+ 0+ 0 | 0+-a+ 0 = a (-) a | 022: a+ 0+ 0 | 0+ 0+ 0 = a (+) 0 * 1 102: 0+-a+ 0 | a+ 0+ 0 = a (R-) a | 112: 0+ 0+ 0 | a+-a+ 0 = 0 | 122: 0+ 0+ 0 | a+ 0+ 0 = 0 (+) a * 2 202: 0+-a+ 0 | 0+ 0+ 0 = a (R-) 0 | 212: 0+ 0+ 0 | 0+-a+ 0 = 0 (-) a | 222: 0+ 0+ 0 | 0+ 0+ 0 = 0 * * Formulae is: (a-b) * (c /32) + d * 0 1 2 * a Cs Cd 0 * b Cs Cd 0 * c As Ad ALPHA.FIX * d Cs Cd 0 * * We want to emulate Cs * F1(alpha) + Cd * F2(alpha) by OpenGl blending: (Cs * Ss (+,-,R-) Cd * Sd) * SET_ALPHA_COLOR_FACTOR(sign) set Set A (as As>>7, Ad>>7 or FIX>>7) with sign. * So we could use 1+a as one_minus_alpha and -a as alpha. * */ int code = (a.a * 16) + (a.b * 4) + a.d ; #define one_minus_alpha (bDestAlphaColor == 2) ? GL_ONE_MINUS_SRC_ALPHA : blendinvalpha[usec] #define alpha (bDestAlphaColor == 2) ? GL_SRC_ALPHA : blendalpha[usec] #define one (bDestAlphaColor == 2) ? GL_ONE : blendalpha[usec] #define zero (bDestAlphaColor == 2) ? GL_ZERO : blendinvalpha[usec] switch (code) { case 0: // 000 // Cs -- nothing changed case 20: // 110 = 16+4=20 // Cs case 40: // 220 = 32+8=40 // Cs { alphaenable = false; break; } case 2: //002 // 0 -- should be zero case 22: //112 // 0 case 42: //222 = 32+8+2 =42 // 0 { s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = GL_ZERO; break; } case 1: //001 // Cd -- Should be destination alpha case 21: //111, // Cd -- 0*Source + 1*Desrinarion case 41: //221 = 32+8+1=41 // Cd -- { s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = GL_ONE; break; } case 4: // 010 // (Cs-Cd)*A+Cs = Cs * (A + 1) - Cd * A { bAlphaClamping = 3; SET_ALPHA_COLOR_FACTOR(0); // a = -A s_rgbeq = GL_FUNC_ADD; // Cs*(1-a)+Cd*a s_srcrgb = one_minus_alpha ; s_dstrgb = alpha; NeedFactor(-1); break; } case 5: // 011 // (Cs-Cd)*A+Cs = Cs * A + Cd * (1-A) { bAlphaClamping = 3; // all testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = alpha; s_dstrgb = one_minus_alpha; NeedFactor(1); break; } case 6: //012 // (Cs-Cd)*FIX { bAlphaClamping = 3; SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_SUBTRACT; s_srcrgb = alpha; s_dstrgb = alpha; break; } case 8: //020 // Cs*A+Cs = Cs * (1+A) { bAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(0); // Zeyflitz change this! a = -A s_rgbeq = GL_FUNC_ADD; s_srcrgb = one_minus_alpha; // Cs*(1-a). s_dstrgb = GL_ZERO; // NeedFactor(1); break; } case 9: //021 // Cs*A+Cd { bAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = alpha; // ZZ change it to. s_dstrgb = GL_ONE; break; } case 10: //022 // Cs*A { bAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = alpha; s_dstrgb = GL_ZERO; break; } case 16: //100 { bAlphaClamping = 3; SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = one_minus_alpha; s_dstrgb = alpha; NeedFactor(1); break; } case 17: //101 { bAlphaClamping = 3; // all testing SET_ALPHA_COLOR_FACTOR(0); s_rgbeq = GL_FUNC_ADD; s_srcrgb = alpha; s_dstrgb = one_minus_alpha; NeedFactor(-1); break; } case 18: //102 { bAlphaClamping = 3; SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_REVERSE_SUBTRACT; s_srcrgb = alpha; s_dstrgb = alpha; break; } case 24: //120 = 16+8 { bAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ONE; s_dstrgb = alpha; break; } case 25: //121 // Cd*(1+A) { bAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(0); s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = one_minus_alpha; // NeedFactor(-1); break; } case 26: //122 { bAlphaClamping = 2; SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = alpha; break; } case 32: // 200 = 32 { bAlphaClamping = 1; // min testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = one_minus_alpha; s_dstrgb = GL_ZERO; break; } case 33: //201 // -Cs*A + Cd { bAlphaClamping = 1; // min testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_REVERSE_SUBTRACT; s_srcrgb = alpha; s_dstrgb = GL_ONE; break; } case 34: //202 case 38: //212 { bAlphaClamping = 1; // min testing -- negative values s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = GL_ZERO; break; } case 36: //210 { bAlphaClamping = 1; // min testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_SUBTRACT; s_srcrgb = GL_ONE; s_dstrgb = alpha; break; } case 37: //211 { bAlphaClamping = 1; // min testing SET_ALPHA_COLOR_FACTOR(1); s_rgbeq = GL_FUNC_ADD; s_srcrgb = GL_ZERO; s_dstrgb = one_minus_alpha; break; } default: { ZZLog::Error_Log("Bad alpha code %d | %d %d %d", code, a.a, a.b, a.d); } } /* int t_rgbeq = GL_FUNC_ADD; int t_srcrgb = GL_ONE; int t_dstrgb = GL_ZERO; int tAlphaClamping = 0; if( a.a == a.b ) { // just d remains if( a.d == 0 ) {} else { t_dstrgb = a.d == 1 ? GL_ONE : GL_ZERO; t_srcrgb = GL_ZERO; t_rgbeq = GL_FUNC_ADD; //a) (001) (111) (221) b) (002) (112) (222) } goto EndSetAlpha; } else if( a.d == 2 ) { // zero if( a.a == 2 ) { // zero all color t_srcrgb = GL_ZERO; t_dstrgb = GL_ZERO; goto EndSetAlpha; // (202) (212) } else if( a.b == 2 ) { //b2XAlphaTest = 1; // a) (022) // b) (122) SET_ALPHA_COLOR_FACTOR(1); if( bDestAlphaColor == 2 ) { t_rgbeq = GL_FUNC_ADD; t_srcrgb = a.a == 0 ? GL_ONE : GL_ZERO; t_dstrgb = a.a == 0 ? GL_ZERO : GL_ONE; } else { tAlphaClamping = 2; t_rgbeq = GL_FUNC_ADD; t_srcrgb = a.a == 0 ? blendalpha[usec] : GL_ZERO; t_dstrgb = a.a == 0 ? GL_ZERO : blendalpha[usec]; } goto EndSetAlpha; } // nothing is zero, so must do some real blending //b2XAlphaTest = 1; //a) (012) //b) (102) tAlphaClamping = 3; SET_ALPHA_COLOR_FACTOR(1); t_rgbeq = a.a == 0 ? GL_FUNC_SUBTRACT : GL_FUNC_REVERSE_SUBTRACT; t_srcrgb = bDestAlphaColor == 2 ? GL_ONE : blendalpha[usec]; t_dstrgb = bDestAlphaColor == 2 ? GL_ONE : blendalpha[usec]; } else if( a.a == 2 ) { // zero //b2XAlphaTest = 1; tAlphaClamping = 1; // min testing SET_ALPHA_COLOR_FACTOR(1); if( a.b == a.d ) { // can get away with 1-A // a.a == a.d == 2!! (200) (211) t_rgbeq = GL_FUNC_ADD; t_srcrgb = (a.b == 0 && bDestAlphaColor != 2) ? blendinvalpha[usec] : GL_ZERO; t_dstrgb = (a.b == 0 || bDestAlphaColor == 2) ? GL_ZERO : blendinvalpha[usec]; } else { // a) (201) b)(210) t_rgbeq = a.b==0 ? GL_FUNC_REVERSE_SUBTRACT : GL_FUNC_SUBTRACT; t_srcrgb = (a.b == 0 && bDestAlphaColor != 2) ? blendalpha[usec] : GL_ONE; t_dstrgb = (a.b == 0 || bDestAlphaColor == 2 ) ? GL_ONE : blendalpha[usec]; } } else if( a.b == 2 ) { tAlphaClamping = 2; // max testing SET_ALPHA_COLOR_FACTOR(a.a!=a.d); if( a.a == a.d ) { // can get away with 1+A, but need to set alpha to negative // a)(020) // b)(121) t_rgbeq = GL_FUNC_ADD; if( bDestAlphaColor == 2 ) { t_srcrgb = (a.a == 0) ? GL_ONE_MINUS_SRC_ALPHA : GL_ZERO; t_dstrgb = (a.a == 0) ? GL_ZERO : GL_ONE_MINUS_SRC_ALPHA; } else { t_srcrgb = a.a == 0 ? blendinvalpha[usec] : GL_ZERO; t_dstrgb = a.a == 0 ? GL_ZERO : blendinvalpha[usec]; } } else { //a)(021) //b)(120) //b2XAlphaTest = 1; t_rgbeq = GL_FUNC_ADD; t_srcrgb = (a.a == 0 && bDestAlphaColor != 2) ? blendalpha[usec] : GL_ONE; t_dstrgb = (a.a == 0 || bDestAlphaColor == 2) ? GL_ONE : blendalpha[usec]; } } else { // all 3 components are valid! tAlphaClamping = 3; // all testing SET_ALPHA_COLOR_FACTOR(a.a!=a.d); if( a.a == a.d ) { // can get away with 1+A, but need to set alpha to negative // a) 010, // b) 101 t_rgbeq = GL_FUNC_ADD; if( bDestAlphaColor == 2 ) { // all ones t_srcrgb = a.a == 0 ? GL_ONE_MINUS_SRC_ALPHA : GL_SRC_ALPHA; t_dstrgb = a.a == 0 ? GL_SRC_ALPHA : GL_ONE_MINUS_SRC_ALPHA; } else { t_srcrgb = a.a == 0 ? blendinvalpha[usec] : blendalpha[usec]; t_dstrgb = a.a == 0 ? blendalpha[usec] : blendinvalpha[usec]; } } else { t_rgbeq = GL_FUNC_ADD; // a) 011 // b) 100 // if( bDestAlphaColor == 2 ) { // all ones t_srcrgb = a.a != 0 ? GL_ONE_MINUS_SRC_ALPHA : GL_SRC_ALPHA; t_dstrgb = a.a != 0 ? GL_SRC_ALPHA : GL_ONE_MINUS_SRC_ALPHA; } else { //b2XAlphaTest = 1; t_srcrgb = a.a != 0 ? blendinvalpha[usec] : blendalpha[usec]; t_dstrgb = a.a != 0 ? blendalpha[usec] : blendinvalpha[usec]; } } } EndSetAlpha: if ( alphaenable && (t_rgbeq != s_rgbeq || s_srcrgb != t_srcrgb || t_dstrgb != s_dstrgb || tAlphaClamping != bAlphaClamping)) { if (CheckArray[code][(bDestAlphaColor==2)] != -1) { printf ( "A code %d, 0x%x, 0x%x, 0x%x, 0x%x %d\n", code, alpha, one_minus_alpha, one, zero, bDestAlphaColor ); printf ( " Difference %d %d %d %d | 0x%x 0x%x | 0x%x 0x%x | 0x%x 0x%x | %d %d\n", code, a.a, a.b, a.d, t_rgbeq, s_rgbeq, t_srcrgb, s_srcrgb, t_dstrgb, s_dstrgb, tAlphaClamping, bAlphaClamping); CheckArray[code][(bDestAlphaColor==2)] = -1; } } else if (CheckArray[code][(bDestAlphaColor==2)] == 0){ printf ( "Add good code %d %d, psm %d destA %d\n", code, a.c, vb[icurctx].prndr->psm, bDestAlphaColor); CheckArray[code][(bDestAlphaColor==2)] = 1; }*/ if (alphaenable) { zgsBlendFuncSeparateEXT(s_srcrgb, s_dstrgb, s_srcalpha, s_dstalpha); zgsBlendEquationSeparateEXT(s_rgbeq, s_alphaeq); glEnable(GL_BLEND); // always set } else { glDisable(GL_BLEND); } INC_ALPHAVARS(); } void ZeroGS::SetWriteDepth() { FUNCLOG if (conf.mrtdepth) { s_bWriteDepth = true; s_nWriteDepthCount = 4; } } bool ZeroGS::IsWriteDepth() { FUNCLOG return s_bWriteDepth; } bool ZeroGS::IsWriteDestAlphaTest() { FUNCLOG return s_bDestAlphaTest; } void ZeroGS::SetDestAlphaTest() { FUNCLOG s_bDestAlphaTest = true; s_nWriteDestAlphaTest = 4; } void ZeroGS::SetTexFlush() { FUNCLOG s_bTexFlush = true; // if( PSMT_ISCLUT(vb[0].tex0.psm) ) // texClutWrite(0); // if( PSMT_ISCLUT(vb[1].tex0.psm) ) // texClutWrite(1); if (!s_bForceTexFlush) { if (s_ptexCurSet[0] != s_ptexNextSet[0]) s_ptexCurSet[0] = s_ptexNextSet[0]; if (s_ptexCurSet[1] != s_ptexNextSet[1]) s_ptexCurSet[1] = s_ptexNextSet[1]; } }
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 2989 ] ] ]
ddd61f01630dda1ee1402de476e6416b6c718358
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/CoreEngine/EntityPropertySystem.h
2edd8f0c3f93012241b150479473e3bed9f8e48c
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
8,470
h
#ifndef ENTITYPROPERTYSYSTEM_H_ #define ENTITYPROPERTYSYSTEM_H_ #include <zoidcom/zoidcom.h> #include <boost/thread/mutex.hpp> #include <map> namespace HovUni { class Entity; class EntityProperty; class EntityPropertyMapReplicator; typedef std::pair<int,EntityProperty*> Property; typedef std::map<int,EntityProperty*> PropertyMap; /** * The container for properties, it is a wrapper arround a map. * This class is thread safe. * @author Pieter-Jan Pintens */ class EntityPropertyMap { private: boost::mutex mMutex; /** * The replicator is our friend */ friend class EntityPropertyMapReplicator; /** * The entity the map belongs to */ Entity * mEntity; /** * The actual map */ std::map<int,EntityProperty*> mMap; /** * The current version */ signed char mUpdate; /** * Call this method when there is an update that needs to be propagated over network */ void update(); public: /** * Constructor */ EntityPropertyMap( Entity * entity ); /** * Destructor */ ~EntityPropertyMap(); /** * Add a property to the map if no property with same key exists in the map * * @param property * @return true if added, false if property with same key already exists */ bool addProperty( EntityProperty * property ); /** * Check if the property with given key exists in the map * * @return true if the property with given key exists in the map, false otherwise */ bool hasProperty( int key ) const; /** * Get the property with given key * * @return the property with given key, null if not found */ EntityProperty * getProperty( int key ); /** * Remove propery with given key from the map * * @param key, the key of the property * @param del, if true the property will be deleted aswell * @return true if property removed, false if no such property found */ bool removeProperty ( int key, bool del = true ); /** * Remove propery from the map * * @param property, the property * @param del, if true the property will be deleted aswell * @return true if property removed, false if no such property found */ bool removeProperty ( EntityProperty * property, bool del = true ); /** * Remove propery with given key from the map * * @param key, the key of the property * @return the property removed from the map, null if no such property found */ EntityProperty * removeProperty ( int key ); /** * Remove propery from the map * * @param property, the property * @return the property removed from the map, null if no such property found */ EntityProperty * removeProperty ( EntityProperty * property ); }; /** * Factory for all properties. This class is thread safe. * @author Pieter-Jan Pintens */ class EntityPropertyFactory { private: /** * Mutex */ static boost::mutex mMutex; /** * The factory map used for creation of new Properties */ static std::map<int,EntityProperty*(*)()> * mFactory; public: /** * Add a property to the factory, if the factory map is not created it will be created here * * @param id * @param creation function */ static void add(int id,EntityProperty*(*r)()); /** * Remove a property to the factory, if the factory map is emtpy after this remove it will be destroyed * * @param id */ static void remove(int id); /** * Create a EntityPropery with given id * * @param id */ static EntityProperty* create(int id); }; /** * A tagging interface, user properties should add this as a static member! * This interface will register the property under given ID which should be unique. * @author Pieter-Jan Pintens */ template<typename T, int ID> class EntityPropertyTag{ public: EntityPropertyTag(){ EntityPropertyFactory::add(ID,&EntityPropertyTag::create); } ~EntityPropertyTag(){ EntityPropertyFactory::remove(ID); } static EntityProperty * create(){ return new T(ID); } operator int (){ return ID; } int operator() (){ return ID; } }; /** * The base class for properties that can be attached to an entity * @author Pieter-Jan Pintens */ class EntityProperty { protected: /** * The map is our friend so it can set entity */ friend class EntityPropertyMap; //friend class EntityPropertyMapReplicator; /** * The entity the property belongs to */ Entity * mEntity; /** * The version of the property */ signed char mVersion; /** * The key for the property, this should be unique */ const int mKey; public: /** * Constructor * * @param id */ EntityProperty( int id ); /** * Destructor */ virtual ~EntityProperty(void); /** * Get the entity this property belongs to * @return the entity this property belongs to */ Entity * getEntity(); /** * Get the property type * @return the property type */ int getKey() const; /** * Write this property to bitstream * * @param bitstream */ virtual void write(ZCom_BitStream& bitstream) const = 0; /** * Read this property to bitstream * * @param bitstream */ virtual void read(ZCom_BitStream& bitstream) = 0; /** * Call this method when there is an update that needs to be propagated over network */ void update(); /** * Get the current version of the property * * @return the current version */ signed char getVersion() const; }; /** * Replicator for the property map */ class EntityPropertyMapReplicator : public ZCom_ReplicatorAdvanced { private: /** * Every 3 seconds a forced update is send */ static const unsigned int DEFAULT_TIMEOUT = 200L; enum TYPE { ADD = 0x0, UPDATE = 0x1, REMOVE = 0x2, RESET = 0x3 }; /** * Data */ EntityPropertyMap& mData; /** * The version of the map */ unsigned char mUpdate; /** * Copy of the Map to find changes */ std::map<int,int> mCopy; /** * Connection id of the server */ ZCom_ConnID mAuthority; /** * Timeout before some forced update is send */ unsigned int mTimeout; private: //Update the map with info on the stream void updateMap(ZCom_BitStream &_stream); //check for and send updates of the map void storeAdd(EntityProperty * property, ZCom_BitStream &_stream); void storeRemove(int propertykey, ZCom_BitStream &_stream); void storeUpdate(EntityProperty * property, ZCom_BitStream &_stream); void storeReset(ZCom_BitStream &_stream); public: EntityPropertyMapReplicator (EntityPropertyMap& data, ZCom_ReplicatorSetup * setup); EntityPropertyMapReplicator(EntityPropertyMap& data, zU8 _flags, zU8 _rules, zU8 _intercept_id = 0, zS16 _mindelay = -1, zS16 _maxdelay = -1); virtual void onConnectionAdded (ZCom_ConnID _cid, eZCom_NodeRole _remoterole); //A node has become relevant on the specified connection and thus to this replicator, too. virtual void onConnectionRemoved (ZCom_ConnID _cid, eZCom_NodeRole _remoterole){ } //The node on this connection is no longer relevant. virtual void onDataReceived (ZCom_ConnID _cid, eZCom_NodeRole _remoterole, ZCom_BitStream &_stream, bool _store, zU32 _estimated_time_sent); //Data has been received from the replicator of a remote node. virtual void onLocalRoleChanged (eZCom_NodeRole _oldrole, eZCom_NodeRole _newrole){ } //The role of the local node which owns this replicator has changed. virtual void onPacketReceived (ZCom_ConnID _cid){ } //The given connection has received a packet. virtual void onPreSendData (ZCom_ConnID _cid, eZCom_NodeRole _remoterole, zU32 *_lastupdate){ } //Zoidcom is about to transmit data to the given client. virtual void onRemoteRoleChanged (ZCom_ConnID _cid, eZCom_NodeRole _oldrole, eZCom_NodeRole _newrole){ } //The role of a node on a remote connection has changed it's role. virtual void Process (eZCom_NodeRole _localrole, zU32 _simulation_time_passed); //Do any kind of processing. virtual void* peekData(){ return 0; } virtual void clearPeekData(){} virtual void onDataAcked(ZCom_ConnID _cid, zU32 _reference_id, ZCom_BitStream *_data){} virtual void onDataLost(ZCom_ConnID _cid, zU32 _reference_id, ZCom_BitStream *_data) {} }; } #endif
[ "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "[email protected]" ]
[ [ [ 1, 11 ], [ 13, 27 ], [ 33, 40 ], [ 42, 45 ], [ 47, 77 ], [ 79, 84 ], [ 86, 93 ], [ 95, 110 ], [ 112, 216 ], [ 218, 279 ], [ 281, 288 ], [ 292, 293 ], [ 296, 301 ], [ 303, 303 ], [ 305, 334 ], [ 336, 336 ], [ 338, 338 ], [ 340, 340 ], [ 369, 381 ] ], [ [ 12, 12 ], [ 28, 32 ], [ 41, 41 ], [ 46, 46 ], [ 78, 78 ], [ 85, 85 ], [ 94, 94 ], [ 111, 111 ], [ 217, 217 ], [ 280, 280 ], [ 289, 291 ], [ 294, 295 ], [ 302, 302 ], [ 304, 304 ], [ 335, 335 ], [ 337, 337 ], [ 339, 339 ], [ 341, 368 ] ] ]
62563bfaa7d97cf3b8fc81e5b3ec8fd149f3126d
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/LuaPlus/Src/Modules/windows/windows.cpp
5561289f01039d8a77f6695ec3ada0536b3d7f86
[ "MIT" ]
permissive
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,333
cpp
#include <windows.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "LuaPlus/LuaPlus.h" #include "KeystrokeEngine.h" using namespace LuaPlus; static int LS_GetForegroundWindow( LuaState* state ) { HWND hwnd = ::GetForegroundWindow(); state->PushInteger((UINT)hwnd); return 1; } static int LS_GetActiveWindow( LuaState* state ) { HWND hwnd = ::GetActiveWindow(); state->PushInteger((UINT)hwnd); return 1; } static int LS_GetFocus( LuaState* state ) { HWND hwnd = ::GetFocus(); state->PushInteger((UINT)hwnd); return 1; } static int LS_GetWindowText( LuaState* state ) { LuaStack args(state); if (!args[1].IsNumber()) { state->PushString(""); return 1; } HWND hwnd = (HWND)(UINT)args[1].GetNumber(); // ::GetWindowText does not always seem to work CString sText; char buffer[257]; buffer[0] = 0; if (hwnd != 0) { ::SendMessage(hwnd, WM_GETTEXT, 256, (LPARAM)(LPCTSTR)buffer); } state->PushString(buffer); return 1; } static int LS_FindWindowEx( LuaState* state ) { LuaStack args(state); if (!args[1].IsNumber()) { state->PushNumber(0); return 1; } HWND hwnd = (HWND)(UINT)args[1].GetNumber(); HWND hwndChildAfter = (HWND)(args[2].IsNumber() ? (UINT)args[2].GetNumber() : 0); LPCSTR className = args[3].IsString() ? args[3].GetString() : NULL; LPCSTR windowName = args[4].IsString() ? args[4].GetString() : NULL; HWND foundHwnd = FindWindowEx(hwnd, hwndChildAfter, className, windowName); state->PushInteger((UINT)foundHwnd); return 1; } #if 0 #include "PushKeys.h" #pragma package(smart_init) //common to pushkeys & TPushKeys void DoPushKeys(class TPushKeys* TPK,CString k); void DoDelay(int mS); void ActivateTarget(); HWND GTargetWindow; bool GTrackTarget; //--------------------------------------------------------------------------- //constructor __fastcall TPushKeys::TPushKeys(TComponent* Owner) : TComponent(Owner) { //initial values fKeys=""; fWindowTitle=""; fWinMatch=wmExactMatch; fDelay=0; fIsPushing=false; fUseANSI=false; fReturnFocus=false; fTrackTarget=true; TargetWindow=NULL; } //--------------------------------------------------------------------------- // activate target window void ActivateTarget() { if (GTargetWindow!=GetForegroundWindow() && GTrackTarget) { if (IsWindow(GTargetWindow) && GTargetWindow!=NULL) { SetForegroundWindow(GTargetWindow); } } } //--------------------------------------------------------------------------- //process individual OnKey events passed from pushkeys //and default key delay void TPushKeys::HandleOnKeyEvent(CString &Key,TShiftState &ShiftState) { //pass keys to users OnKey event handler if (OnKey) { OnKey(this,Key,ShiftState); } } //--------------------------------------------------------------------------- //do inter-key delay void TPushKeys::DoKeyDelay() { if (Process==NULL) { //timed delay DoDelay(KeyDelayValue); } else //wait for input buffer to empty from process passed to onpus event { WaitForInputIdle(Process,ProcessWait); } } //--------------------------------------------------------------------------- void __fastcall TPushKeys::SetKeys(CString keys) { fKeys=keys; } //--------------------------------------------------------------------------- //pass string in function call HWND __fastcall TPushKeys::Push(CString k) { return PushMethod(k); } //--------------------------------------------------------------------------- //normal call using Keys property HWND __fastcall TPushKeys::Push() { return PushMethod(fKeys); } //--------------------------------------------------------------------------- //method to simulate key presses //returns false if window title contained a value but window could not be found HWND __fastcall TPushKeys::PushMethod(CString k) { //active flag fIsPushing=true; //calculate default key delay value KeyDelayValue=0; if (fDelay!=0) { //value specified if (fDelay>0) { KeyDelayValue=fDelay; } else //negative==use keyboard delay value { //get value DWORD kbs; SystemParametersInfo(SPI_GETKEYBOARDSPEED,0,&kbs,0); //i think this is how it works kbs+=2; KeyDelayValue=1000/kbs; } } //no title specified? if (fWindowTitle=="") { TargetWindow=GetForegroundWindow(); } else { //enum windows & match window title FindWindowTitle(); } //pass window handle, activation flag, Process handle & wait time to OnPush event handler bool Activate=true; //default process handle & wait time Process=NULL; ProcessWait=0; if (OnPush) { OnPush(this,TargetWindow,Activate,Process,ProcessWait); } //ok to push flag bool DoPushing=true; //set target window as active? if (Activate) { //activate window if valid if (TargetWindow!=NULL && IsWindow(TargetWindow)) { SetForegroundWindow(TargetWindow); } else //no pushing to be done { TargetWindow=NULL; DoPushing=false; } } //global target GTargetWindow=TargetWindow; GTrackTarget=Activate ? fTrackTarget : false; //ok to push? if (DoPushing) { //push the keys DoPushKeys(this,k); } //return focus? if (fReturnFocus) { //give time for key presses to complete DoDelay(100); HWND ThisWindow=((TForm*)(this->Owner))->Handle; if (IsWindow(ThisWindow) && ThisWindow!=NULL) { SetForegroundWindow(ThisWindow); } } //all done fIsPushing=false; return TargetWindow; } //--------------------------------------------------------------------------- //find match for window title void TPushKeys::FindWindowTitle() { TargetWindow=NULL; EnumWindows((WNDENUMPROC)TPKListWindows,(long)this); } //--------------------------------------------------------------------------- //enum windows proc used to step through window titles BOOL __stdcall TPKListWindows(HWND hWnd, LPARAM lparam) { TPushKeys* caller=(TPushKeys*)lparam; //get window title char buf[255]; GetWindowText(hWnd,buf,255); CString srch(buf); if (lstrlen(buf)==0) { return true; } //do match switch(caller->fWinMatch) { //exact match required (case sensitive) case wmExactMatch: if (srch==caller->fWindowTitle) { caller->TargetWindow=hWnd; return false; } break; //only starting characters need to match (case insensitive) case wmStartMatch: if (srch.UpperCase().Pos(caller->fWindowTitle.UpperCase())==1) { caller->TargetWindow=hWnd; return false; } break; //any sub string ok (case insensitive) case wmPartialMatch: if (srch.UpperCase().Pos(caller->fWindowTitle.UpperCase())!=0) { caller->TargetWindow=hWnd; return false; } break; } //continue looking return true; } #endif 0 #if 0 //--------------------------------------------------------------------------- //*************************************************************************** // PushKeys Code * //*************************************************************************** //--------------------------------------------------------------------------- // the following functions are used internally only void PushAKey(CHAR ch); void PushFnKey(CString KeyCode); void PushShiftKey(CHAR ch,bool Off=true); void PushCTRLKey(char key,bool Off=true); void PushALTKey(char key,bool Off=true); void PushRALTKey(char key,bool Off=true); void PressKey(BYTE Vk, UINT Scan); void __PushKeys(CString src); void CTRLOn(); void CTRLOff(); void ALTOn(); void ALTOff(); void RALTOn(); void RALTOff(); void SHIFTOn(); void SHIFTOff(); void AllOff(); bool IsAFunctionKey(CString fk); byte GetFunctionKey(CString fk); byte GetControlKey(CString fk); int GetFunctionKeyCount(CString &fk); bool ProcessFuncKey(CString k); void SetKeyStates(TShiftState ss); void PushKeys(CString src); void PushDOSKeys(CString src); void OnKeyHandler(bool IsFnKey,CString Key); void InitialKeyState(); void PushAString(CString s); //--------------------------------------------------------------------------- //PUSHKEYS for C++ Builder (component) //original version 1.0 for Visual Basic //Copyright by Data Solutions Pty Ltd (ACN 010 951 498) //All rights reserved. //Email for info: [email protected] //This is the C++Builder component implementation //C++ component modifications and additions by Alan Warriner //[email protected] #define VK_BREAK VK_CANCEL #define VK_BELL 0x07 #define VK_LINEFEED 0x0A // These variables indicate whether these keys are pressed bool AltOn,RAltOn, ShiftOn, ControlOn; //ANSI key equivalents flag bool DOSKey; //instance calling these routines TPushKeys* GTPK; //----------------------------------------------------------- //entry point for component void DoPushKeys(TPushKeys* TPK,CString keys) { //set DOS flag DOSKey=TPK->UseANSI; //set global access GTPK=TPK; //extract {}} }}} {{{ {} 4} type thing bool lb=false, rb=false; CString tv=""; int lastbrace=-1; int cnt=0; for (int i=1;i<=keys.GetLength();i++) { char sc=keys[i]; if (sc=='{') { //if processed left brace last then delete if (!lb) { lb=true; rb=false; tv+=sc; cnt++; lastbrace=cnt; } } else if (sc=='}') { //ditto for right brace (or left brace not previous) if (!rb && lb && cnt-lastbrace>1) { rb=true; lb=false; tv+=sc; cnt++; } } else { tv+=sc; cnt++; } } //orphan { if (lb) { tv.Delete(lastbrace,1); } //delete trailing int tvl=tv.GetLength(); if (tv>0) { if (tv[tvl]=='{') { tv.Delete(tvl,1); } } keys=tv; //call appropriate routine if (DOSKey) { PushDOSKeys(keys); } else { PushKeys(keys); } } //----------------------------------------------------------- //friend of TPK on key handler //extract key string and pass to handler //process keypushes etc on return void OnKeyHandler(bool IsFnKey,CString Key) { CString k=Key; CString uk=k.UpperCase(); int count; bool CallKeyHandler=false; //delay bool IsSleep=uk.Pos("SLEEP")==1; //********************* //clear clipboard bool IsClearClip=uk.Pos("EMPTYCLIP")==1; //run bool IsRun=uk.Pos("RUN ")==1; //{\0xxx} bool IsDirect=k.Pos("\\")==1 && k.GetLength()>1; if (k=="\\") { IsDirect=false; IsFnKey=false; } //function key? or clear clipboard or run if(IsFnKey || IsSleep || IsDirect || IsClearClip || IsRun) { //get count value & strip out count characters if (!IsRun) { count=GetFunctionKeyCount(k); } if(IsAFunctionKey(uk) || IsDirect) { //not a control key? if (GetControlKey(uk)==(byte)-1) k="{"+uk+"}"; CallKeyHandler=true; } //sleep or clear clipboard or run if (IsSleep || IsClearClip || IsRun) { k="{"+Key.UpperCase()+"}"; CallKeyHandler=true; } } else { if (k.GetLength()==1) { CallKeyHandler=true; } } if (!CallKeyHandler) return; //set up shiftstate to pass here //************************** TShiftState KeyState,CopyOfKeyState; if (ShiftOn) KeyState<<ssShift; if (ControlOn) KeyState<<ssCtrl; if (AltOn) KeyState<<ssAlt; //keep a copy CopyOfKeyState=KeyState; //pass to onkey & delay handler //************************ GTPK->HandleOnKeyEvent(k,KeyState); //returned keys //************************ CString returned=k; int rl=returned.GetLength(); uk=returned.UpperCase(); if (rl==0) return; //process returned shiftstate //************** //changed? if (KeyState!=CopyOfKeyState) { //set key states SetKeyStates(KeyState); } //process keys returned //*************************** IsSleep=uk.Pos("{SLEEP")==1; //clear clipboard IsClearClip=uk.Pos("{EMPTYCLIP")==1; //run IsRun=uk.Pos("{RUN ")==1; //single key(s)? if (rl<3) { PushAString(returned); } else { if (returned[1]=='{' && returned[rl]=='}') { //strip out braces CString fk=returned.SubString(2,rl-2).UpperCase(); bool IsNL=k=="{NEWLINE}" || uk=="{NL}"; //is it a function key? if(IsAFunctionKey(fk) && !IsNL) { PushFnKey(fk); } //CRLF else if (IsNL) { // New line = Carriage return & Line Feed = ^M^J for (int i=0;i<count;i++) { if (DOSKey)//ANSI equivalent { PushCTRLKey('M'); PushCTRLKey('J'); } else { UINT ScanKey = MapVirtualKey(VK_RETURN, 0); PressKey(VK_RETURN,ScanKey); ScanKey = MapVirtualKey(VK_LINEFEED, 0); PressKey(VK_LINEFEED,ScanKey); } } } //direct {\xxxx} else if(fk.Pos("\\")==1 && fk.GetLength()>1) { if (fk.GetLength()>1) { //start key presses ALTOn(); //step along numbers for (int numpointer=2;numpointer<=fk.GetLength();numpointer++) { char number=fk[numpointer]; if (number>='0' && number<='9') { //get numpad key byte npk[]={VK_NUMPAD0,VK_NUMPAD1,VK_NUMPAD2,VK_NUMPAD3,VK_NUMPAD4 ,VK_NUMPAD5,VK_NUMPAD6,VK_NUMPAD7,VK_NUMPAD8,VK_NUMPAD9}; byte numpadkey=npk[number-'0']; //press key PressKey(numpadkey,MapVirtualKey(numpadkey,0)); } } //all done ALTOff(); } } //delay else if(IsSleep)//sleep { int count=GetFunctionKeyCount(fk); DoDelay(count); } //clear clipboard else if (IsClearClip) { int count=GetFunctionKeyCount(fk); for (int c=0;c<count;c++) { if (OpenClipboard(NULL)) { EmptyClipboard(); CloseClipboard(); } } } else if (IsRun)//run { CString runcmd=Key.SubString(4,fk.GetLength()); WinExec(runcmd.c_str(),SW_SHOWNORMAL); } else //do single keys { PushAString(returned); } } else { PushAString(returned); } } //reset changed shiftstate //************** //changed? if (KeyState!=CopyOfKeyState) { //reset key states SetKeyStates(CopyOfKeyState); } //do inter-key delay if not a sleep command if(!IsSleep) { GTPK->DoKeyDelay(); } } //----------------------------------------------------------- //push each key in a string void PushAString(CString s) { for(int i=0;i<s.GetLength();i++) { PushAKey(s[i+1]); } } //----------------------------------------------------------- //set control key states void SetKeyStates(TShiftState ss) { if (ss.Contains(ssShift)) { SHIFTOn(); } else { SHIFTOff(); } if (ss.Contains(ssCtrl)) { CTRLOn(); } else { CTRLOff(); } if (ss.Contains(ssAlt)) { ALTOn(); } else { ALTOff(); } } //----------------------------------------------------------- //return no of times function key {xx y} will be pressed //strip out count charcters int GetFunctionKeyCount(CString &fk) { int rv=1; int numstart=fk.LastDelimiter(" "); if (numstart!=0 && numstart<fk.GetLength()) { //extract count rv=StrToIntDef(fk.SubString(numstart,999),-1); //valid numeric characters? if (rv>=0) { //strip out count characters fk=fk.SubString(1,numstart-1); } else { rv=1; } } return rv; } //----------------------------------------------------------- //return a control key character key code from a string //-1 if no match byte GetControlKey(CString fk) { CString ck="+^%!"; int idx=ck.Pos(fk[1]); if (idx==0) idx=-1; return (byte)idx; } //----------------------------------------------------------- //return a function key virtual key code from a string //-1 if no match byte GetFunctionKey(CString fk) { byte rv=-1; // Function Keys CString fkeys[]={ "BACKSPACE","BS","BKSP" ,"BELL" ,"RIGHTWIN" ,"LEFTWIN","START" ,"APPS","CONTEXT" ,"PAUSE" ,"BREAK" ,"CANCEL" ,"CAPSLOCK","CAPS" ,"DELETE","DEL" ,"DOWN" ,"END" ,"ENTER","RETURN" ,"ESCAPE","ESC" ,"FF" ,"HELP" ,"HOME" ,"INSERT","INS" ,"LEFT" ,"NEWLINE","NL" ,"NUMLOCK" ,"PGDN","PAGEDOWN","NEXT" ,"PGUP","PAGEUP","PRIOR" ,"PRINTSCREEN","PRTSC" ,"RIGHT" ,"SCROLLLOCK","SCRLK" ,"TAB" ,"UP" ,"F1","F2","F3","F4","F5","F6" ,"F7","F8","F9","F10","F11","F12" ,"F13","F14","F15","F16","F17","F18" ,"F19","F20","F21","F22","F23","F24" ,"NUMPAD0","NUMPAD1","NUMPAD2","NUMPAD3","NUMPAD4" ,"NUMPAD5","NUMPAD6","NUMPAD7","NUMPAD8","NUMPAD9" ,"NUMPADMUTIPLY","NUMPAD*" ,"NUMPADADD","NUMPAD+" ,"NUMPADSUBTRACT","NUMPAD-" ,"NUMPADDECIMAL","NUMPAD." ,"NUMPADDIVIDE","NUMPAD/" ,"LEFTBRACE","RIGHTBRACE" }; byte fvk[]={ VK_BACK,VK_BACK,VK_BACK ,VK_BELL ,VK_RWIN ,VK_LWIN,VK_LWIN ,VK_APPS, VK_APPS ,VK_PAUSE ,VK_BREAK ,VK_CANCEL ,VK_CAPITAL,VK_CAPITAL ,VK_DELETE,VK_DELETE ,VK_DOWN ,VK_END ,VK_RETURN,VK_RETURN ,VK_ESCAPE,VK_ESCAPE ,VK_CLEAR ,VK_HELP ,VK_HOME ,VK_INSERT,VK_INSERT ,VK_LEFT ,VK_LINEFEED,VK_LINEFEED ,VK_NUMLOCK ,VK_NEXT,VK_NEXT,VK_NEXT ,VK_PRIOR,VK_PRIOR,VK_PRIOR ,VK_SNAPSHOT,VK_SNAPSHOT ,VK_RIGHT ,VK_SCROLL,VK_SCROLL ,VK_TAB ,VK_UP ,VK_F1,VK_F2,VK_F3,VK_F4,VK_F5,VK_F6 ,VK_F7,VK_F8,VK_F9,VK_F10,VK_F11,VK_F12 ,VK_F13,VK_F14,VK_F15,VK_F16,VK_F17,VK_F18 ,VK_F19,VK_F20,VK_F21,VK_F22,VK_F23,VK_F24 ,VK_NUMPAD0,VK_NUMPAD1,VK_NUMPAD2,VK_NUMPAD3,VK_NUMPAD4 ,VK_NUMPAD5,VK_NUMPAD6,VK_NUMPAD7,VK_NUMPAD8,VK_NUMPAD9 ,VK_MULTIPLY,VK_MULTIPLY ,VK_ADD,VK_ADD ,VK_SUBTRACT,VK_SUBTRACT ,VK_DECIMAL,VK_DECIMAL ,VK_DIVIDE,VK_DIVIDE ,'{','}' }; int arraysize=sizeof(fvk)/sizeof(fvk[0]); fk=fk.UpperCase(); for (int i=0;i<arraysize;i++) { if (fk==fkeys[i]) { rv=fvk[i]; break; } } return rv; } //----------------------------------------------------------- //indicate if passed string represents a function key bool IsAFunctionKey(CString fk) { bool rv=false; if (GetFunctionKey(fk)!=(byte)-1 || GetControlKey(fk)!=(byte)-1) rv=true; return rv; } //----------------------------------------------------------- //delay loop void DoDelay(int mS) { if (mS==0) return; DWORD start=GetTickCount(); DWORD end=start+mS; //has time wrapped if (end<start) //wait for it to reach zero { while (GetTickCount()>start) { Application->ProcessMessages(); } } while(GetTickCount()<end) { Application->ProcessMessages(); } } //----------------------------------------------------------- //do CTRL keys void CTRLOn() { if (ControlOn) return; ActivateTarget(); keybd_event(VK_CONTROL, (BYTE)MapVirtualKey(VK_CONTROL,0), 0, 0); ControlOn=true; } //----------------------------------------------------------- void CTRLOff() { if(!ControlOn) return; ActivateTarget(); keybd_event(VK_CONTROL, (BYTE)MapVirtualKey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0); ControlOn=false; } //----------------------------------------------------------- //ctrl + void PushCTRLKey(char k,bool Off) { CTRLOn(); PushAKey(k); if (Off) CTRLOff(); } //----------------------------------------------------------- //do normal Alt keys void ALTOn() { if(AltOn) return; ActivateTarget(); keybd_event(VK_MENU, (BYTE)MapVirtualKey(VK_MENU,0), 0, 0); AltOn=true; } //----------------------------------------------------------- void ALTOff() { if(!AltOn) return; ActivateTarget(); keybd_event(VK_MENU, (BYTE)MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0); AltOn=false; } //----------------------------------------------------------- //do right Alt keys AltGr void RALTOn() { if(RAltOn) return; //simulate ALTOn(); CTRLOn(); RAltOn=true; } //----------------------------------------------------------- void RALTOff() { if(!RAltOn) return; //simulate ALTOff(); CTRLOff(); RAltOn=false; } //----------------------------------------------------------- //do shift keys void SHIFTOn() { if (ShiftOn) return; ActivateTarget(); keybd_event(VK_SHIFT, (BYTE)MapVirtualKey(VK_SHIFT,0), 0, 0); ShiftOn=true; } //----------------------------------------------------------- void SHIFTOff() { if(!ShiftOn) return; ActivateTarget(); keybd_event(VK_SHIFT, (BYTE)MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_KEYUP, 0); ShiftOn=false; } //----------------------------------------------------------- void PressKey(BYTE Vk, UINT Scan) { //Presses the appropriate key specified ActivateTarget(); keybd_event(Vk, (BYTE)Scan, 0, 0); keybd_event(Vk, (BYTE)Scan, KEYEVENTF_KEYUP, 0); } //----------------------------------------------------------- void PushAKey(CHAR k) { bool doshift=false; bool doalt=false; bool doctrl=false; DWORD vks=VkKeyScan(k); DWORD oeks=OemKeyScan(k); if(oeks!=(DWORD)-1) //standard key { if (oeks & 0x00020000) { doshift=true; } if (oeks & 0x00040000) { doctrl=true; } if (oeks & 0x00080000) { doalt=true; } } //not a standard key else { oeks=vks; if (oeks & 0x0100) { doshift=true; } if (oeks & 0x0200) { doctrl=true; } if (oeks & 0x0400) { doalt=true; } } //invalid key code if (oeks==(DWORD)-1 || vks==(DWORD)-1) return; //no need for shift if it's already on if (ShiftOn) { doshift=false; } //no need for ctrl if it's already on if (ControlOn) { doctrl=false; } //no need for alt if it's already on if (AltOn) { doalt=false; } //shift on if (doshift) { SHIFTOn(); } //ctrl on if (doctrl) { CTRLOn(); } //alt on if (doalt) { ALTOn(); } // Press the key PressKey((BYTE)vks, (BYTE)oeks); //shift off if (doshift) { SHIFTOff(); } //ctrl off if (doctrl) { CTRLOff(); } //alt off if (doalt) { ALTOff(); } } //----------------------------------------------------------- //function keys void PushFnKey(CString KeyCode) { // Outputs function key. KeyCode may have a number of times to be output LONG NumPushes; INT index; CString FnKey; CString OrigCode; bool isfnkey=false; // Work out which function key to push and how many times //get key press count & strip out count characters NumPushes=GetFunctionKeyCount(KeyCode); //keep a copy OrigCode=KeyCode; FnKey=KeyCode.UpperCase(); //direct code entry if (FnKey.Pos("\\")==1) { ProcessFuncKey(FnKey); return; } //braces if (FnKey=="LEFTBRACE" || FnKey=="RIGHTBRACE") { char pc=FnKey.Pos("LEFT")<1 ? '}' : '{'; for (index=1;index<=NumPushes;index++) { PushAKey(pc); } return; } //search for F key byte fnkey=GetFunctionKey(FnKey); if (fnkey==(byte)-1) fnkey=GetControlKey(FnKey); if (fnkey!=(byte)-1) { isfnkey=true; } //press f key if (isfnkey) { bool dodos=false; //do DOS conversion? if (DOSKey) { byte vk[]={VK_BELL,VK_BREAK,VK_RETURN,VK_ESCAPE,VK_CLEAR,VK_LINEFEED,VK_TAB}; char dk[]={'G','C','M','[','L','J','I'}; //search for key equivalent for (int i=0;i<sizeof(vk)/sizeof(vk[0]);i++) { if (fnkey==vk[i]) { //match found dodos=true; for (index=1;index<=NumPushes;index++) { //do key press PushCTRLKey(dk[i]); } break; } } } if (!dodos)//normal fkey { for (index=1;index<=NumPushes;index++) { //reserved characters if (GetControlKey(fnkey)!=(byte)-1) { PushAKey(fnkey); } else { //full printscreen if (fnkey==VK_SNAPSHOT && !AltOn) { PressKey(fnkey,1); } else { PressKey(fnkey,MapVirtualKey(fnkey,0)); } } } } } //sleeep or NL or clear clipboard or run else if(FnKey!="SLEEP" && FnKey!="NEWLINE" && FnKey!="NL" && FnKey !="EMPTYCLIP" && FnKey.Pos("RUN ")!=1) { // Ordinary keys for (index=1; index<=NumPushes; index++) { for (int i=0;i<OrigCode.GetLength();i++) { char ss=OrigCode[i+1]; //watch for {~ 2} if(ss!='~' || OrigCode=="~") { OnKeyHandler(false,ss); } else { //{hello world~ 3} OnKeyHandler(true,"ENTER"); } } } } } //----------------------------------------------------------- //set initial key state variables void InitialKeyState() { SHORT ks=GetAsyncKeyState(VK_SHIFT); ShiftOn=(ks & 0x8000)==0x8000; ks=GetAsyncKeyState(VK_CONTROL); ControlOn=(ks & 0x8000)==0x8000; ks=GetAsyncKeyState(VK_MENU); AltOn=(ks & 0x8000)==0x8000; RAltOn=AltOn & ControlOn; } //----------------------------------------------------------- //all control keys off void AllOff() { SHIFTOff(); ALTOff(); RALTOff(); CTRLOff(); } //normal pushkeys void PushKeys(CString src) { InitialKeyState(); AllOff(); DOSKey=false; __PushKeys(src); } //----------------------------------------------------------- //DOS pushkeys void PushDOSKeys(CString src) { InitialKeyState(); AllOff(); DOSKey=true; __PushKeys(src); } //----------------------------------------------------------- //send f keys to onkey handler bool ProcessFuncKey(CString k) { //talke a copy CString temp=k; //get count value & strip out count characters //from temporary value int count=GetFunctionKeyCount(k); //is it a function key? if (IsAFunctionKey(k) || k.Pos("\\")==1) { //pass it count times to handler for(int i=0;i<count;i++) { OnKeyHandler(true,k); } return true; } else { //restore original if not an F key k=temp; } return false; } //----------------------------------------------------------- void __PushKeys(const char* src) { //Copyright by Data Solutions Pty Ltd (ACN 010 951 498) //All rights reserved. //Email for info: [email protected] // This is the routine that does all the work int index; CString SubStr; INT BrCnt; CHAR BrOpen; CHAR BrClose; CHAR Ch; CHAR nextCh; int srcLen=strlen(src); if (srcLen == 0) return; char ck[]={'+','^','%','!'}; void (*ckonfuncs[])()={SHIFTOn,CTRLOn,ALTOn,RALTOn}; void (*ckofffuncs[])()={SHIFTOff,CTRLOff,ALTOff,RALTOff}; index = 0; while (index<srcLen) { char nextCh = src[index + 1]; // control keys & functions bool controlkey = false; int ckidx; //is it a control key next? for (int ckidx = 0; ckidx < sizeof(ck) / sizeof(*ck); ckidx++) { if (nextCh == ck[ckidx]) { //contol key alone? if (srcLen == 1) { //turn control key on (*ckonfuncs[ckidx])(); //control key off (*ckofffuncs[ckidx])(); //exit return; } controlkey=true; break; } } //shift,ctrl,alt,ralt found if (controlkey && srcLen>=index+2) { BrOpen=src[index+2]; if ((BrOpen=='(')||(BrOpen=='{')) { if (BrOpen=='(') { BrClose=')'; } else { BrClose='}'; } index++; SubStr=""; BrCnt=1; while ((index<srcLen-1)&&(BrCnt!=0)) { index++; Ch=src[index+1]; if (Ch!=BrClose) { SubStr+=Ch; } else { BrCnt--; } if (Ch==BrOpen) BrCnt++; } // Turn control key on (*ckonfuncs[ckidx])(); // Push the keys if (SubStr!="") { if (BrOpen=='(') { __PushKeys(SubStr); } else { CString t=SubStr; if(ProcessFuncKey(t)) { t=""; } if (t.GetLength()>0) PushFnKey(t); } } // Turn control key off (*ckofffuncs[ckidx])(); } else { // The next key uses control index++; (*ckonfuncs[ckidx])(); OnKeyHandler(false,src[index+1]); (*ckofffuncs[ckidx])(); } } else if (nextCh=='{' && src!="{}" && src!="}{") { // Function keys index++; SubStr=""; while ((index<(srcLen-1))&&(src[index+1]!='}')) { SubStr+=src[index+1]; index++; } if(srcLen>1) { if (src[srcLen]=='}' && src[srcLen-1]=='}') { // Right brace OnKeyHandler(false,'}'); PushAKey('}'); index++; } else { CString k=SubStr; if (ProcessFuncKey(k)) { k=""; } else if(k.UpperCase().Pos("SLEEP")==1) { //sleep OnKeyHandler(false,k); } //**************************************** //clear clipboard else if (k.UpperCase().Pos("EMPTYCLIP")==1) { OnKeyHandler(false,k); } //run else if (k.UpperCase().Pos("RUN ")==1) { OnKeyHandler(false,k); } //not a function key (a 3} type of thing if(k.GetLength()>0) { PushFnKey(k); } } } } else if (nextCh=='~') { // The enter key ProcessFuncKey("ENTER"); } else { OnKeyHandler(false,nextCh); } index++; } //turn all control keys off AllOff(); } #endif 0 /* static int LS_DoIt( LuaState* state ) { if (!args[1].IsNumber()) { return 0; } HWND hwnd = (HWND)(UINT)args[1].GetNumber(); UINT vk = '1'; UINT scan = MapVirtualKey(vk, 0); INPUT input; input.type = INPUT_KEYBOARD; input.ki.wVk = vk; input.ki.wScan = scan; input.ki.dwFlags = 0; input.ki.time = 0; input.ki.dwExtraInfo = GetMessageExtraInfo(); // ::SendMessage(hwnd, WM_KEYDOWN, VK_NUMPAD1, 1 | (scan << 16)); UINT numEvents = ::SendInput(1, &input, sizeof(INPUT)); printf("%d\n", numEvents); input.type = INPUT_KEYBOARD; input.ki.wVk = vk; input.ki.wScan = scan; input.ki.dwFlags = KEYEVENTF_KEYUP; input.ki.time = 0; input.ki.dwExtraInfo = GetMessageExtraInfo(); // ::SendMessage(hwnd, WM_KEYDOWN, VK_NUMPAD1, 1 | (scan << 16)); numEvents = ::SendInput(1, &input, sizeof(INPUT)); printf("%d\n", numEvents); return 0; } */ static int LS_SendKeys( LuaState* state ) { LuaStack args(state); LPCSTR keys = args[1].GetString(); CKeystrokeEngine keystrokeEngine(keys); keystrokeEngine.SendKeys(); return 0; } extern "C" LUAMODULE_API int luaopen_windows(lua_State* L) { LuaState* state = LuaState::CastState(L); LuaObject obj = state->GetGlobals().CreateTable( "windows" ); obj.Register( "GetForegroundWindow", LS_GetForegroundWindow ); obj.Register( "GetActiveWindow", LS_GetActiveWindow ); obj.Register( "GetFocus", LS_GetFocus ); obj.Register( "GetWindowText", LS_GetWindowText ); obj.Register( "FindWindowEx", LS_FindWindowEx ); obj.Register( "SendKeys", LS_SendKeys ); // obj.Register( "DoIt", LS_DoIt ); return 0; }
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 1635 ] ] ]
29198eb43915dbfbd6d29b9d9cf3ec18edd54f2d
fc7dbcb3bcdb16010e9b1aad4ecba41709089304
/EdkCompatibilityPkg/Sample/Tools/Source/UefiVfrCompile/VfrFormPkg.h
9091204f991a7565e09f339527c770a71d69e06c
[]
no_license
Itomyl/loongson-uefi
5eb0ece5875406b00dbd265d28245208d6bbc99a
70b7d5495e2b451899e2ba2ef677384de075d984
refs/heads/master
2021-05-28T04:38:29.989074
2010-05-31T02:47:26
2010-05-31T02:47:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
61,581
h
/*++ Copyright (c) 2004 - 2010, Intel Corporation All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: VfrFormPkg.h Abstract: --*/ #ifndef _EFIIFRCLASS_H_ #define _EFIIFRCLASS_H_ #include "string.h" #include "EfiVfr.h" #include "VfrError.h" #include "VfrUtilityLib.h" /* * The functions below are used for flags setting */ static inline BOOLEAN _FLAGS_ZERO ( IN UINT8 &Flags ) { return Flags == 0; } static inline VOID _FLAG_CLEAR ( IN UINT8 &Flags, IN UINT8 Mask ) { Flags &= (~Mask); } static inline UINT8 _FLAG_TEST_AND_CLEAR ( IN UINT8 &Flags, IN UINT8 Mask ) { UINT8 Ret = Flags & Mask; Flags &= (~Mask); return Ret; } static inline UINT8 _IS_EQUAL ( IN UINT8 &Flags, IN UINT8 Value ) { return Flags == Value; } /* * The definition of CIfrBin */ typedef enum { PENDING, ASSIGNED } ASSIGN_FLAG; struct SPendingAssign { INT8 *mKey; // key ! unique VOID *mAddr; UINT32 mLen; ASSIGN_FLAG mFlag; UINT32 mLineNo; struct SPendingAssign *mNext; SPendingAssign (IN INT8 *, IN VOID *, IN UINT32, IN UINT32); ~SPendingAssign (); VOID SetAddrAndLen (IN VOID *, IN UINT32); VOID AssignValue (IN VOID *, IN UINT32); INT8 * GetKey (VOID); }; struct SBufferNode { CHAR8 *mBufferStart; CHAR8 *mBufferEnd; CHAR8 *mBufferFree; struct SBufferNode *mNext; }; class CFormPkg { private: UINT32 mBufferSize; SBufferNode *mBufferNodeQueueHead; SBufferNode *mBufferNodeQueueTail; SBufferNode *mCurrBufferNode; SBufferNode *mReadBufferNode; UINT32 mReadBufferOffset; UINT32 mPkgLength; VOID _WRITE_PKG_LINE (IN FILE *, IN UINT32 , IN INT8 *, IN INT8 *, IN UINT32); VOID _WRITE_PKG_END (IN FILE *, IN UINT32 , IN INT8 *, IN INT8 *, IN UINT32); private: SPendingAssign *PendingAssignList; public: CFormPkg (IN UINT32 BufferSize); ~CFormPkg (); CHAR8 * IfrBinBufferGet (IN UINT32); inline UINT32 GetPkgLength (VOID); VOID Open (); UINT32 Read (IN CHAR8 *, IN UINT32); VOID Close (); EFI_VFR_RETURN_CODE BuildPkgHdr (OUT EFI_HII_PACKAGE_HEADER **); EFI_VFR_RETURN_CODE BuildPkg (IN FILE *); EFI_VFR_RETURN_CODE GenCFile (IN INT8 *, IN FILE *); public: EFI_VFR_RETURN_CODE AssignPending (IN INT8 *, IN VOID *, IN UINT32, IN UINT32); VOID DoPendingAssign (IN INT8 *, IN VOID *, IN UINT32); bool HavePendingUnassigned (VOID); VOID PendingAssignPrintAll (VOID); }; extern CFormPkg gCFormPkg; struct SIfrRecord { UINT32 mLineNo; CHAR8 *mIfrBinBuf; UINT8 mBinBufLen; UINT32 mOffset; SIfrRecord *mNext; SIfrRecord (VOID); ~SIfrRecord (VOID); }; #define EFI_IFR_RECORDINFO_IDX_INVALUD 0xFFFFFF #define EFI_IFR_RECORDINFO_IDX_START 0x0 class CIfrRecordInfoDB { private: bool mSwitch; UINT32 mRecordCount; SIfrRecord *mIfrRecordListHead; SIfrRecord *mIfrRecordListTail; SIfrRecord * GetRecordInfoFromIdx (IN UINT32); public: CIfrRecordInfoDB (VOID); ~CIfrRecordInfoDB (VOID); inline VOID TurnOn (VOID) { mSwitch = TRUE; } inline VOID TurnOff (VOID) { mSwitch = FALSE; } UINT32 IfrRecordRegister (IN UINT32, IN CHAR8 *, IN UINT8, IN UINT32); VOID IfrRecordInfoUpdate (IN UINT32, IN UINT32, IN CHAR8*, IN UINT8, IN UINT32); VOID IfrRecordOutput (IN FILE *, IN UINT32 LineNo); }; extern CIfrRecordInfoDB gCIfrRecordInfoDB; /* * The definition of CIfrObj */ extern bool gCreateOp; class CIfrObj { private: bool mDelayEmit; CHAR8 *mObjBinBuf; UINT8 mObjBinLen; UINT32 mLineNo; UINT32 mRecordIdx; UINT32 mPkgOffset; VOID _EMIT_PENDING_OBJ (VOID); public: CIfrObj (IN UINT8 OpCode, OUT CHAR8 **IfrObj = NULL, IN UINT8 ObjBinLen = 0, IN BOOLEAN DelayEmit = FALSE); virtual ~CIfrObj(VOID); inline VOID SetLineNo (IN UINT32 LineNo) { mLineNo = LineNo; } inline CHAR8 * GetObjBinAddr (VOID) { return mObjBinBuf; } inline UINT8 GetObjBinLen (VOID) { return mObjBinLen; } inline bool ExpendObjBin (IN UINT8 Size) { if ((mDelayEmit == TRUE) && ((mObjBinLen + Size) > mObjBinLen)) { mObjBinLen += Size; return TRUE; } else { return FALSE; } } }; /* * The definition of CIfrOpHeader */ class CIfrOpHeader { private: EFI_IFR_OP_HEADER *mHeader; public: CIfrOpHeader (IN UINT8 OpCode, IN VOID *StartAddr, IN UINT8 Length = 0); CIfrOpHeader (IN CIfrOpHeader &); VOID IncLength (UINT8 Size) { if ((mHeader->Length + Size) > mHeader->Length) { mHeader->Length += Size; } } VOID DecLength (UINT8 Size) { if (mHeader->Length >= Size) { mHeader -= Size; } } UINT8 GetLength () { return mHeader->Length; } UINT8 GetScope () { return mHeader->Scope; } VOID SetScope (IN UINT8 Scope) { mHeader->Scope = Scope; } }; extern UINT8 gScopeCount; /* * The definition of CIfrStatementHeader */ class CIfrStatementHeader { private: EFI_IFR_STATEMENT_HEADER *mHeader; public: CIfrStatementHeader ( IN EFI_IFR_STATEMENT_HEADER *StartAddr ) : mHeader ((EFI_IFR_STATEMENT_HEADER *)StartAddr) { mHeader = StartAddr; mHeader->Help = EFI_STRING_ID_INVALID; mHeader->Prompt = EFI_STRING_ID_INVALID; } EFI_IFR_STATEMENT_HEADER *GetStatementHeader () { return mHeader; } VOID SetPrompt (IN EFI_STRING_ID Prompt) { mHeader->Prompt = Prompt; } VOID SetHelp (IN EFI_STRING_ID Help) { mHeader->Help = Help; } }; /* * The definition of CIfrQuestionHeader */ #define EFI_IFR_QUESTION_FLAG_DEFAULT 0 class CIfrQuestionHeader : public CIfrStatementHeader { private: EFI_IFR_QUESTION_HEADER *mHeader; EFI_IFR_STATEMENT_HEADER * QH2SH (EFI_IFR_QUESTION_HEADER *Qheader) { return &(Qheader)->Header; } public: EFI_QUESTION_ID QUESTION_ID (VOID) { return mHeader->QuestionId; } EFI_VARSTORE_ID VARSTORE_ID (VOID) { return mHeader->VarStoreId; } VOID VARSTORE_INFO (OUT EFI_VARSTORE_INFO *Info) { if (Info != NULL) { Info->mVarStoreId = mHeader->VarStoreId; memcpy (&Info->mVarStoreId, &mHeader->VarStoreInfo, sizeof (Info->mVarStoreId)); } } UINT8 FLAGS (VOID) { return mHeader->Flags; } public: CIfrQuestionHeader ( IN EFI_IFR_QUESTION_HEADER *StartAddr, IN UINT8 Flags = EFI_IFR_QUESTION_FLAG_DEFAULT ) : CIfrStatementHeader (QH2SH(StartAddr)) { mHeader = StartAddr; mHeader->QuestionId = EFI_QUESTION_ID_INVALID; mHeader->VarStoreId = EFI_VARSTORE_ID_INVALID; mHeader->VarStoreInfo.VarName = EFI_STRING_ID_INVALID; mHeader->VarStoreInfo.VarOffset = EFI_VAROFFSET_INVALID; mHeader->Flags = Flags; } VOID SetQuestionId (IN EFI_QUESTION_ID QuestionId) { mHeader->QuestionId = QuestionId; } VOID SetVarStoreInfo (IN EFI_VARSTORE_INFO *Info) { mHeader->VarStoreId = Info->mVarStoreId; mHeader->VarStoreInfo.VarName = Info->mInfo.mVarName; mHeader->VarStoreInfo.VarOffset = Info->mInfo.mVarOffset; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 Flags) { if (_FLAG_TEST_AND_CLEAR (Flags, EFI_IFR_FLAG_READ_ONLY)) { mHeader->Flags |= EFI_IFR_FLAG_READ_ONLY; } _FLAG_CLEAR (Flags, 0x02); if (_FLAG_TEST_AND_CLEAR (Flags, EFI_IFR_FLAG_CALLBACK)) { mHeader->Flags |= EFI_IFR_FLAG_CALLBACK; } _FLAG_CLEAR (Flags, 0x08); if (_FLAG_TEST_AND_CLEAR (Flags, EFI_IFR_FLAG_RESET_REQUIRED)) { mHeader->Flags |= EFI_IFR_FLAG_RESET_REQUIRED; } _FLAG_CLEAR (Flags, 0x20); if (_FLAG_TEST_AND_CLEAR (Flags, EFI_IFR_FLAG_OPTIONS_ONLY)) { mHeader->Flags |= EFI_IFR_FLAG_OPTIONS_ONLY; } return _FLAGS_ZERO (Flags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; static CIfrQuestionHeader *gCurrentQuestion = NULL; /* * The definition of CIfrMinMaxStepData */ class CIfrMinMaxStepData { private: MINMAXSTEP_DATA *mMinMaxStepData; public: CIfrMinMaxStepData (MINMAXSTEP_DATA *DataAddr) : mMinMaxStepData (DataAddr) { mMinMaxStepData->u64.MinValue = 0; mMinMaxStepData->u64.MaxValue = 0; mMinMaxStepData->u64.Step = 0; } VOID SetMinMaxStepData (IN UINT64 MinValue, IN UINT64 MaxValue, IN UINT64 Step) { mMinMaxStepData->u64.MinValue = MinValue; mMinMaxStepData->u64.MaxValue = MaxValue; mMinMaxStepData->u64.Step = Step; } VOID SetMinMaxStepData (IN UINT32 MinValue, IN UINT32 MaxValue, IN UINT32 Step) { mMinMaxStepData->u32.MinValue = MinValue; mMinMaxStepData->u32.MaxValue = MaxValue; mMinMaxStepData->u32.Step = Step; } VOID SetMinMaxStepData (IN UINT16 MinValue, IN UINT16 MaxValue, IN UINT16 Step) { mMinMaxStepData->u16.MinValue = MinValue; mMinMaxStepData->u16.MaxValue = MaxValue; mMinMaxStepData->u16.Step = Step; } VOID SetMinMaxStepData (IN UINT8 MinValue, IN UINT8 MaxValue, IN UINT8 Step) { mMinMaxStepData->u8.MinValue = MinValue; mMinMaxStepData->u8.MaxValue = MaxValue; mMinMaxStepData->u8.Step = Step; } }; /* * The definition of all of the UEFI IFR Objects */ class CIfrFormSet : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_FORM_SET *mFormSet; public: CIfrFormSet () : CIfrObj (EFI_IFR_FORM_SET_OP, (CHAR8 **)&mFormSet), CIfrOpHeader (EFI_IFR_FORM_SET_OP, &mFormSet->Header) { mFormSet->Help = EFI_STRING_ID_INVALID; mFormSet->FormSetTitle = EFI_STRING_ID_INVALID; memset (&mFormSet->Guid, 0, sizeof (EFI_GUID)); } VOID SetGuid (IN EFI_GUID *Guid) { memcpy (&mFormSet->Guid, Guid, sizeof (EFI_GUID)); } VOID SetFormSetTitle (IN EFI_STRING_ID FormSetTitle) { mFormSet->FormSetTitle = FormSetTitle; } VOID SetHelp (IN EFI_STRING_ID Help) { mFormSet->Help = Help; } }; class CIfrEnd : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_END *mEnd; public: CIfrEnd () : CIfrObj (EFI_IFR_END_OP, (CHAR8 **)&mEnd), CIfrOpHeader (EFI_IFR_END_OP, &mEnd->Header) {} }; class CIfrDefaultStore : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_DEFAULTSTORE *mDefaultStore; public: CIfrDefaultStore () : CIfrObj (EFI_IFR_DEFAULTSTORE_OP, (CHAR8 **)&mDefaultStore), CIfrOpHeader (EFI_IFR_DEFAULTSTORE_OP, &mDefaultStore->Header) { mDefaultStore->DefaultId = EFI_VARSTORE_ID_INVALID; mDefaultStore->DefaultName = EFI_STRING_ID_INVALID; } VOID SetDefaultName (IN EFI_STRING_ID DefaultName) { mDefaultStore->DefaultName = DefaultName; } VOID SetDefaultId (IN UINT16 DefaultId) { mDefaultStore->DefaultId = DefaultId; } }; #define EFI_FORM_ID_MAX 0xFFFF #define EFI_FREE_FORM_ID_BITMAP_SIZE ((EFI_FORM_ID_MAX + 1) / EFI_BITS_PER_UINT32) class CIfrForm : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_FORM *mForm; STATIC UINT32 FormIdBitMap[EFI_FREE_FORM_ID_BITMAP_SIZE]; STATIC BOOLEAN ChekFormIdFree (IN EFI_FORM_ID FormId) { UINT32 Index = (FormId / EFI_BITS_PER_UINT32); UINT32 Offset = (FormId % EFI_BITS_PER_UINT32); return (FormIdBitMap[Index] & (0x80000000 >> Offset)) == 0; } STATIC VOID MarkFormIdUsed (IN EFI_FORM_ID FormId) { UINT32 Index = (FormId / EFI_BITS_PER_UINT32); UINT32 Offset = (FormId % EFI_BITS_PER_UINT32); FormIdBitMap[Index] |= (0x80000000 >> Offset); } public: CIfrForm () : CIfrObj (EFI_IFR_FORM_OP, (CHAR8 **)&mForm), CIfrOpHeader (EFI_IFR_FORM_OP, &mForm->Header) { mForm->FormId = 0; mForm->FormTitle = EFI_STRING_ID_INVALID; } EFI_VFR_RETURN_CODE SetFormId (IN EFI_FORM_ID FormId) { if (CIfrForm::ChekFormIdFree (FormId) == FALSE) { return VFR_RETURN_FORMID_REDEFINED; } mForm->FormId = FormId; CIfrForm::MarkFormIdUsed (FormId); return VFR_RETURN_SUCCESS; } VOID SetFormTitle (IN EFI_STRING_ID FormTitle) { mForm->FormTitle = FormTitle; } }; class CIfrVarStore : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_VARSTORE *mVarStore; public: CIfrVarStore () : CIfrObj (EFI_IFR_VARSTORE_OP, (CHAR8 **)&mVarStore, sizeof (EFI_IFR_VARSTORE), TRUE), CIfrOpHeader (EFI_IFR_VARSTORE_OP, &mVarStore->Header) { mVarStore->VarStoreId = EFI_VARSTORE_ID_INVALID; mVarStore->Size = 0; memset (&mVarStore->Guid, 0, sizeof (EFI_GUID)); mVarStore->Name[0] = '\0'; } VOID SetGuid (IN EFI_GUID *Guid) { memcpy (&mVarStore->Guid, Guid, sizeof (EFI_GUID)); } VOID SetVarStoreId (IN EFI_VARSTORE_ID VarStoreId) { mVarStore->VarStoreId = VarStoreId; } VOID SetSize (IN UINT16 Size) { mVarStore->Size = Size; } VOID SetName (IN INT8 *Name) { UINT8 Len; if (Name != NULL) { Len = strlen (Name); if (Len != 0) { if (ExpendObjBin (Len) == TRUE) { IncLength (Len); strcpy ((INT8 *)(mVarStore->Name), Name); } } } } }; class CIfrVarStoreEfi : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_VARSTORE_EFI *mVarStoreEfi; public: CIfrVarStoreEfi () : CIfrObj (EFI_IFR_VARSTORE_EFI_OP, (CHAR8 **)&mVarStoreEfi), CIfrOpHeader (EFI_IFR_VARSTORE_EFI_OP, &mVarStoreEfi->Header) { mVarStoreEfi->VarStoreId = EFI_VAROFFSET_INVALID; memset (&mVarStoreEfi->Guid, 0, sizeof (EFI_GUID)); } VOID SetGuid (IN EFI_GUID *Guid) { memcpy (&mVarStoreEfi->Guid, Guid, sizeof (EFI_GUID)); } VOID SetVarStoreId (IN UINT16 VarStoreId) { mVarStoreEfi->VarStoreId = VarStoreId; } VOID SetAttributes (IN UINT32 Attributes) { mVarStoreEfi->Attributes = Attributes; } }; class CIfrVarStoreNameValue : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_VARSTORE_NAME_VALUE *mVarStoreNameValue; public: CIfrVarStoreNameValue () : CIfrObj (EFI_IFR_VARSTORE_NAME_VALUE_OP, (CHAR8 **)&mVarStoreNameValue), CIfrOpHeader (EFI_IFR_VARSTORE_NAME_VALUE_OP, &mVarStoreNameValue->Header) { mVarStoreNameValue->VarStoreId = EFI_VAROFFSET_INVALID; memset (&mVarStoreNameValue->Guid, 0, sizeof (EFI_GUID)); } VOID SetGuid (IN EFI_GUID *Guid) { memcpy (&mVarStoreNameValue->Guid, Guid, sizeof (EFI_GUID)); } VOID SetVarStoreId (IN UINT16 VarStoreId) { mVarStoreNameValue->VarStoreId = VarStoreId; } }; class CIfrImage : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_IMAGE *mImage; public: CIfrImage () : CIfrObj (EFI_IFR_IMAGE_OP, (CHAR8 **)&mImage), CIfrOpHeader (EFI_IFR_FORM_OP, &mImage->Header) { mImage->Id = EFI_IMAGE_ID_INVALID; } VOID SetImageId (IN EFI_IMAGE_ID ImageId) { mImage->Id = ImageId; } }; class CIfrLocked : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_LOCKED *mLocked; public: CIfrLocked () : CIfrObj (EFI_IFR_LOCKED_OP, (CHAR8 **)&mLocked), CIfrOpHeader (EFI_IFR_LOCKED_OP, &mLocked->Header) {} }; class CIfrRule : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_RULE *mRule; public: CIfrRule () : CIfrObj (EFI_IFR_RULE_OP, (CHAR8 **)&mRule), mRule ((EFI_IFR_RULE *)GetObjBinAddr()), CIfrOpHeader (EFI_IFR_RULE_OP, &mRule->Header) { mRule->RuleId = EFI_RULE_ID_INVALID; } VOID SetRuleId (IN UINT8 RuleId) { mRule->RuleId = RuleId; } }; static EFI_IFR_TYPE_VALUE gZeroEfiIfrTypeValue = {0, }; class CIfrDefault : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_DEFAULT *mDefault; public: CIfrDefault ( IN UINT16 DefaultId = EFI_HII_DEFAULT_CLASS_STANDARD, IN UINT8 Type = EFI_IFR_TYPE_OTHER, IN EFI_IFR_TYPE_VALUE Value = gZeroEfiIfrTypeValue ) : CIfrObj (EFI_IFR_DEFAULT_OP, (CHAR8 **)&mDefault), CIfrOpHeader (EFI_IFR_DEFAULT_OP, &mDefault->Header) { mDefault->Type = Type; mDefault->Value = Value; mDefault->DefaultId = DefaultId; } VOID SetDefaultId (IN UINT16 DefaultId) { mDefault->DefaultId = DefaultId; } VOID SetType (IN UINT8 Type) { mDefault->Type = Type; } VOID SetValue (IN EFI_IFR_TYPE_VALUE Value) { mDefault->Value = Value; } }; class CIfrValue : public CIfrObj, public CIfrOpHeader{ private: EFI_IFR_VALUE *mValue; public: CIfrValue () : CIfrObj (EFI_IFR_VALUE_OP, (CHAR8 **)&mValue), CIfrOpHeader (EFI_IFR_VALUE_OP, &mValue->Header) {} }; class CIfrSubtitle : public CIfrObj, public CIfrOpHeader, public CIfrStatementHeader { private: EFI_IFR_SUBTITLE *mSubtitle; public: CIfrSubtitle () : CIfrObj (EFI_IFR_SUBTITLE_OP, (CHAR8 **)&mSubtitle), CIfrOpHeader (EFI_IFR_SUBTITLE_OP, &mSubtitle->Header), CIfrStatementHeader (&mSubtitle->Statement) { mSubtitle->Flags = 0; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 LFlags) { if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_FLAGS_HORIZONTAL)) { mSubtitle->Flags |= EFI_IFR_FLAGS_HORIZONTAL; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; class CIfrText : public CIfrObj, public CIfrOpHeader, public CIfrStatementHeader { private: EFI_IFR_TEXT *mText; public: CIfrText () : CIfrObj (EFI_IFR_TEXT_OP, (CHAR8 **)&mText), CIfrOpHeader (EFI_IFR_TEXT_OP, &mText->Header), CIfrStatementHeader (&mText->Statement) { mText->TextTwo = EFI_STRING_ID_INVALID; } VOID SetTextTwo (IN EFI_STRING_ID StringId) { mText->TextTwo = StringId; } }; class CIfrRef : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_REF *mRef; public: CIfrRef () : CIfrObj (EFI_IFR_REF_OP, (CHAR8 **)&mRef), CIfrOpHeader (EFI_IFR_REF_OP, &mRef->Header), CIfrQuestionHeader (&mRef->Question) { mRef->FormId = 0; } VOID SetFormId (IN EFI_FORM_ID FormId) { mRef->FormId = FormId; } }; class CIfrRef2 : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_REF2 *mRef2; public: CIfrRef2 () : CIfrObj (EFI_IFR_REF_OP, (CHAR8 **)&mRef2, sizeof (EFI_IFR_REF2)), CIfrOpHeader (EFI_IFR_REF_OP, &mRef2->Header, sizeof (EFI_IFR_REF2)), CIfrQuestionHeader (&mRef2->Question) { mRef2->FormId = 0; mRef2->QuestionId = EFI_QUESTION_ID_INVALID; } VOID SetFormId (IN EFI_FORM_ID FormId) { mRef2->FormId = FormId; } EFI_VFR_RETURN_CODE SetQuestionId (IN EFI_QUESTION_ID QuestionId) { if (QuestionId == EFI_QUESTION_ID_INVALID) { return VFR_RETURN_UNDEFINED; } mRef2->QuestionId = QuestionId; return VFR_RETURN_SUCCESS; } }; class CIfrRef3 : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_REF3 *mRef3; public: CIfrRef3 () : CIfrObj (EFI_IFR_REF_OP, (CHAR8 **)&mRef3, sizeof(EFI_IFR_REF3)), CIfrOpHeader (EFI_IFR_REF_OP, &mRef3->Header, sizeof (EFI_IFR_REF3)), CIfrQuestionHeader (&mRef3->Question) { mRef3->FormId = 0; mRef3->QuestionId = EFI_QUESTION_ID_INVALID; memset (&mRef3->FormSetId, 0, sizeof (EFI_GUID)); } VOID SetFormId (IN EFI_FORM_ID FormId) { mRef3->FormId = FormId; } VOID SetQuestionId (IN EFI_QUESTION_ID QuestionId) { mRef3->QuestionId = QuestionId; } VOID SetFormSetId (IN EFI_GUID FormSetId) { mRef3->FormSetId = FormSetId; } }; class CIfrRef4 : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_REF4 *mRef4; public: CIfrRef4 () : CIfrObj (EFI_IFR_REF_OP, (CHAR8 **)&mRef4, sizeof(EFI_IFR_REF3)), CIfrOpHeader (EFI_IFR_REF_OP, &mRef4->Header, sizeof (EFI_IFR_REF3)), CIfrQuestionHeader (&mRef4->Question) { mRef4->FormId = 0; mRef4->QuestionId = EFI_QUESTION_ID_INVALID; memset (&mRef4->FormSetId, 0, sizeof (EFI_GUID)); mRef4->DevicePath = EFI_STRING_ID_INVALID; } VOID SetFormId (IN EFI_FORM_ID FormId) { mRef4->FormId = FormId; } VOID SetQuestionId (IN EFI_QUESTION_ID QuestionId) { mRef4->QuestionId = QuestionId; } VOID SetFormSetId (IN EFI_GUID FormSetId) { mRef4->FormSetId = FormSetId; } VOID SetDevicePath (IN EFI_STRING_ID DevicePath) { mRef4->DevicePath = DevicePath; } }; class CIfrResetButton : public CIfrObj, public CIfrOpHeader, public CIfrStatementHeader { private: EFI_IFR_RESET_BUTTON *mResetButton; public: CIfrResetButton () : CIfrObj (EFI_IFR_RESET_BUTTON_OP, (CHAR8 **)&mResetButton), CIfrOpHeader (EFI_IFR_RESET_BUTTON_OP, &mResetButton->Header), CIfrStatementHeader (&mResetButton->Question.Header) { mResetButton->DefaultId = EFI_HII_DEFAULT_CLASS_STANDARD; } VOID SetDefaultId (IN UINT16 DefaultId) { mResetButton->DefaultId = DefaultId; } }; class CIfrCheckBox : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_CHECKBOX *mCheckBox; public: CIfrCheckBox () : CIfrObj (EFI_IFR_CHECKBOX_OP, (CHAR8 **)&mCheckBox), CIfrOpHeader (EFI_IFR_CHECKBOX_OP, &mCheckBox->Header), CIfrQuestionHeader (&mCheckBox->Question) { mCheckBox->Flags = EFI_IFR_CHECKBOX_DEFAULT; gCurrentQuestion = this; } ~CIfrCheckBox () { gCurrentQuestion = NULL; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_CHECKBOX_DEFAULT)) { mCheckBox->Flags |= EFI_IFR_CHECKBOX_DEFAULT; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_CHECKBOX_DEFAULT_MFG)) { mCheckBox->Flags |= EFI_IFR_CHECKBOX_DEFAULT_MFG; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; class CIfrAction : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_ACTION *mAction; public: CIfrAction () : CIfrObj (EFI_IFR_ACTION_OP, (CHAR8 **)&mAction), CIfrOpHeader (EFI_IFR_ACTION_OP, &mAction->Header), CIfrQuestionHeader (&mAction->Question) { mAction->QuestionConfig = EFI_STRING_ID_INVALID; } VOID SetQuestionConfig (IN EFI_STRING_ID QuestionConfig) { mAction->QuestionConfig = QuestionConfig; } }; class CIfrDate : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_DATE *mDate; public: CIfrDate () : CIfrObj (EFI_IFR_DATE_OP, (CHAR8 **)&mDate), CIfrOpHeader (EFI_IFR_DATE_OP, &mDate->Header), CIfrQuestionHeader (&mDate->Question) { mDate->Flags = 0; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_QF_DATE_YEAR_SUPPRESS)) { mDate->Flags |= EFI_QF_DATE_YEAR_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_QF_DATE_MONTH_SUPPRESS)) { mDate->Flags |= EFI_QF_DATE_MONTH_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_QF_DATE_DAY_SUPPRESS)) { mDate->Flags |= EFI_QF_DATE_DAY_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, QF_DATE_STORAGE_NORMAL)) { mDate->Flags |= QF_DATE_STORAGE_NORMAL; } else if (_FLAG_TEST_AND_CLEAR (LFlags, QF_DATE_STORAGE_TIME)) { mDate->Flags |= QF_DATE_STORAGE_TIME; } else if (_FLAG_TEST_AND_CLEAR (LFlags, QF_DATE_STORAGE_WAKEUP)) { mDate->Flags |= QF_DATE_STORAGE_WAKEUP; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; class CIfrNumeric : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader, public CIfrMinMaxStepData { private: EFI_IFR_NUMERIC *mNumeric; public: CIfrNumeric () : CIfrObj (EFI_IFR_NUMERIC_OP, (CHAR8 **)&mNumeric), CIfrOpHeader (EFI_IFR_NUMERIC_OP, &mNumeric->Header), CIfrQuestionHeader (&mNumeric->Question), CIfrMinMaxStepData (&mNumeric->data) { mNumeric->Flags = EFI_IFR_NUMERIC_SIZE_1 | EFI_IFR_DISPLAY_UINT_DEC; gCurrentQuestion = this; } ~CIfrNumeric () { gCurrentQuestion = NULL; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (LFlags & EFI_IFR_DISPLAY) { mNumeric->Flags = LFlags; } else { mNumeric->Flags = LFlags | EFI_IFR_DISPLAY_UINT_DEC; } return VFR_RETURN_SUCCESS; } }; class CIfrOneOf : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader, public CIfrMinMaxStepData { private: EFI_IFR_ONE_OF *mOneOf; public: CIfrOneOf () : CIfrObj (EFI_IFR_ONE_OF_OP, (CHAR8 **)&mOneOf), CIfrOpHeader (EFI_IFR_ONE_OF_OP, &mOneOf->Header), CIfrQuestionHeader (&mOneOf->Question), CIfrMinMaxStepData (&mOneOf->data) { mOneOf->Flags = 0; gCurrentQuestion = this; } ~CIfrOneOf () { gCurrentQuestion = NULL; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (LFlags & EFI_IFR_DISPLAY) { mOneOf->Flags = LFlags; } else { mOneOf->Flags = LFlags | EFI_IFR_DISPLAY_UINT_DEC; } return VFR_RETURN_SUCCESS; } }; class CIfrString : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_STRING *mString; public: CIfrString () : CIfrObj (EFI_IFR_STRING_OP, (CHAR8 **)&mString), CIfrOpHeader (EFI_IFR_STRING_OP, &mString->Header), CIfrQuestionHeader (&mString->Question) { mString->Flags = 0; mString->MinSize = 0; mString->MaxSize = 0; gCurrentQuestion = this; } ~CIfrString () { gCurrentQuestion = NULL; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_STRING_MULTI_LINE)) { mString->Flags |= EFI_IFR_STRING_MULTI_LINE; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } VOID SetMinSize (IN UINT8 Flags) { mString->MinSize = Flags; } VOID SetMaxSize (IN UINT8 MaxSize) { mString->MaxSize = MaxSize; } }; class CIfrPassword : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_PASSWORD *mPassword; public: CIfrPassword () : CIfrObj (EFI_IFR_PASSWORD_OP, (CHAR8 **)&mPassword), CIfrOpHeader (EFI_IFR_PASSWORD_OP, &mPassword->Header), CIfrQuestionHeader (&mPassword->Question) { mPassword->MinSize = 0; mPassword->MaxSize = 0; gCurrentQuestion = this; } ~CIfrPassword () { gCurrentQuestion = NULL; } VOID SetMinSize (IN UINT16 MinSize) { mPassword->MinSize = MinSize; } VOID SetMaxSize (IN UINT16 MaxSize) { mPassword->MaxSize = MaxSize; } }; class CIfrOrderedList : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_ORDERED_LIST *mOrderedList; public: CIfrOrderedList () : CIfrObj (EFI_IFR_ORDERED_LIST_OP, (CHAR8 **)&mOrderedList), CIfrOpHeader (EFI_IFR_ORDERED_LIST_OP, &mOrderedList->Header), CIfrQuestionHeader (&mOrderedList->Question) { mOrderedList->MaxContainers = 0; mOrderedList->Flags = 0; gCurrentQuestion = this; } ~CIfrOrderedList () { gCurrentQuestion = NULL; } VOID SetMaxContainers (IN UINT8 MaxContainers) { mOrderedList->MaxContainers = MaxContainers; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_UNIQUE_SET)) { mOrderedList->Flags |= EFI_IFR_UNIQUE_SET; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_NO_EMPTY_SET)) { mOrderedList->Flags |= EFI_IFR_NO_EMPTY_SET; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; class CIfrTime : public CIfrObj, public CIfrOpHeader, public CIfrQuestionHeader { private: EFI_IFR_TIME *mTime; public: CIfrTime () : CIfrObj (EFI_IFR_TIME_OP, (CHAR8 **)&mTime), CIfrOpHeader (EFI_IFR_TIME_OP, &mTime->Header), CIfrQuestionHeader (&mTime->Question) { mTime->Flags = 0; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 HFlags, IN UINT8 LFlags) { EFI_VFR_RETURN_CODE Ret; Ret = CIfrQuestionHeader::SetFlags (HFlags); if (Ret != VFR_RETURN_SUCCESS) { return Ret; } if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_HOUR_SUPPRESS)) { mTime->Flags |= QF_TIME_HOUR_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_MINUTE_SUPPRESS)) { mTime->Flags |= QF_TIME_MINUTE_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_SECOND_SUPPRESS)) { mTime->Flags |= QF_TIME_SECOND_SUPPRESS; } if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_STORAGE_NORMAL)) { mTime->Flags |= QF_TIME_STORAGE_NORMAL; } else if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_STORAGE_TIME)) { mTime->Flags |= QF_TIME_STORAGE_TIME; } else if (_FLAG_TEST_AND_CLEAR (LFlags, QF_TIME_STORAGE_WAKEUP)) { mTime->Flags |= QF_TIME_STORAGE_WAKEUP; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; class CIfrDisableIf : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_DISABLE_IF *mDisableIf; public: CIfrDisableIf () : CIfrObj (EFI_IFR_DISABLE_IF_OP, (CHAR8 **)&mDisableIf), mDisableIf ((EFI_IFR_DISABLE_IF *) GetObjBinAddr()), CIfrOpHeader (EFI_IFR_DISABLE_IF_OP, &mDisableIf->Header) {} }; class CIfrSuppressIf : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_SUPPRESS_IF *mSuppressIf; public: CIfrSuppressIf () : CIfrObj (EFI_IFR_SUPPRESS_IF_OP, (CHAR8 **)&mSuppressIf), CIfrOpHeader (EFI_IFR_SUPPRESS_IF_OP, &mSuppressIf->Header) {} }; class CIfrGrayOutIf : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GRAY_OUT_IF *mGrayOutIf; public: CIfrGrayOutIf () : CIfrObj (EFI_IFR_GRAY_OUT_IF_OP, (CHAR8 **)&mGrayOutIf), CIfrOpHeader (EFI_IFR_GRAY_OUT_IF_OP, &mGrayOutIf->Header) {} }; class CIfrInconsistentIf : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_INCONSISTENT_IF *mInconsistentIf; public: CIfrInconsistentIf () : CIfrObj (EFI_IFR_INCONSISTENT_IF_OP, (CHAR8 **)&mInconsistentIf), CIfrOpHeader (EFI_IFR_INCONSISTENT_IF_OP, &mInconsistentIf->Header) { mInconsistentIf->Error = EFI_STRING_ID_INVALID; } VOID SetError (IN EFI_STRING_ID Error) { mInconsistentIf->Error = Error; } }; class CIfrNoSubmitIf : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_NO_SUBMIT_IF *mNoSubmitIf; public: CIfrNoSubmitIf () : CIfrObj (EFI_IFR_NO_SUBMIT_IF_OP, (CHAR8 **)&mNoSubmitIf), CIfrOpHeader (EFI_IFR_NO_SUBMIT_IF_OP, &mNoSubmitIf->Header) { mNoSubmitIf->Error = EFI_STRING_ID_INVALID; } VOID SetError (IN EFI_STRING_ID Error) { mNoSubmitIf->Error = Error; } }; class CIfrRefresh : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_REFRESH *mRefresh; public: CIfrRefresh () : CIfrObj (EFI_IFR_REFRESH_OP, (CHAR8 **)&mRefresh), CIfrOpHeader (EFI_IFR_REFRESH_OP, &mRefresh->Header) { mRefresh->RefreshInterval = 0; } VOID SetRefreshInterval (IN UINT8 RefreshInterval) { mRefresh->RefreshInterval = RefreshInterval; } }; class CIfrVarStoreDevice : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_VARSTORE_DEVICE *mVarStoreDevice; public: CIfrVarStoreDevice () : CIfrObj (EFI_IFR_VARSTORE_DEVICE_OP, (CHAR8 **)&mVarStoreDevice), CIfrOpHeader (EFI_IFR_VARSTORE_DEVICE_OP, &mVarStoreDevice->Header) { mVarStoreDevice->DevicePath = EFI_STRING_ID_INVALID; } VOID SetDevicePath (IN EFI_STRING_ID DevicePath) { mVarStoreDevice->DevicePath = DevicePath; } }; class CIfrOneOfOption : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_ONE_OF_OPTION *mOneOfOption; public: CIfrOneOfOption () : CIfrObj (EFI_IFR_ONE_OF_OPTION_OP, (CHAR8 **)&mOneOfOption), CIfrOpHeader (EFI_IFR_ONE_OF_OPTION_OP, &mOneOfOption->Header) { mOneOfOption->Flags = 0; mOneOfOption->Option = EFI_STRING_ID_INVALID; mOneOfOption->Type = EFI_IFR_TYPE_OTHER; memset (&mOneOfOption->Value, 0, sizeof (mOneOfOption->Value)); } VOID SetOption (IN EFI_STRING_ID Option) { mOneOfOption->Option = Option; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 LFlags) { if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_OPTION_DEFAULT)) { mOneOfOption->Flags |= EFI_IFR_OPTION_DEFAULT; } if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_OPTION_DEFAULT_MFG)) { mOneOfOption->Flags |= EFI_IFR_OPTION_DEFAULT_MFG; } if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_NUM_SIZE_8)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_NUM_SIZE_8); mOneOfOption->Flags |= EFI_IFR_TYPE_NUM_SIZE_8; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_NUM_SIZE_16)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_NUM_SIZE_16); mOneOfOption->Flags |= EFI_IFR_TYPE_NUM_SIZE_16; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_NUM_SIZE_32)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_NUM_SIZE_32); mOneOfOption->Flags |= EFI_IFR_TYPE_NUM_SIZE_32; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_NUM_SIZE_64)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_NUM_SIZE_64); mOneOfOption->Flags |= EFI_IFR_TYPE_NUM_SIZE_64; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_BOOLEAN)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_BOOLEAN); mOneOfOption->Flags |= EFI_IFR_TYPE_BOOLEAN; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_TIME)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_TIME); mOneOfOption->Flags |= EFI_IFR_TYPE_TIME; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_DATE)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_DATE); mOneOfOption->Flags |= EFI_IFR_TYPE_DATE; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_STRING)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_STRING); mOneOfOption->Flags |= EFI_IFR_TYPE_STRING; } else if (_IS_EQUAL (LFlags, EFI_IFR_TYPE_OTHER)) { _FLAG_CLEAR (LFlags, EFI_IFR_TYPE_OTHER); mOneOfOption->Flags |= EFI_IFR_TYPE_OTHER; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } VOID SetType (IN UINT8 Type) { mOneOfOption->Type = Type; } VOID SetValue (IN EFI_IFR_TYPE_VALUE Value) { mOneOfOption->Value = Value; } UINT8 GetFlags (VOID) { return mOneOfOption->Flags; } }; static EFI_GUID IfrTianoGuid = EFI_IFR_TIANO_GUID; class CIfrClass : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GUID_CLASS *mClass; public: CIfrClass () : CIfrObj (EFI_IFR_GUID_OP, (CHAR8 **)&mClass, sizeof (EFI_IFR_GUID_CLASS)), CIfrOpHeader (EFI_IFR_GUID_OP, &mClass->Header, sizeof (EFI_IFR_GUID_CLASS)) { mClass->ExtendOpCode = EFI_IFR_EXTEND_OP_CLASS; mClass->Guid = IfrTianoGuid; mClass->Class = EFI_NON_DEVICE_CLASS; } VOID SetClass (IN UINT16 Class) { mClass->Class = Class; } }; class CIfrSubClass : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GUID_SUBCLASS *mSubClass; public: CIfrSubClass () : CIfrObj (EFI_IFR_GUID_OP, (CHAR8 **)&mSubClass, sizeof (EFI_IFR_GUID_SUBCLASS)), CIfrOpHeader (EFI_IFR_GUID_OP, &mSubClass->Header, sizeof (EFI_IFR_GUID_SUBCLASS)) { mSubClass->ExtendOpCode = EFI_IFR_EXTEND_OP_SUBCLASS; mSubClass->Guid = IfrTianoGuid; mSubClass->SubClass = EFI_SETUP_APPLICATION_SUBCLASS; } VOID SetSubClass (IN UINT16 SubClass) { mSubClass->SubClass = SubClass; } }; class CIfrLabel : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GUID_LABEL *mLabel; public: CIfrLabel () : CIfrObj (EFI_IFR_GUID_OP, (CHAR8 **)&mLabel, sizeof (EFI_IFR_GUID_LABEL)), CIfrOpHeader (EFI_IFR_GUID_OP, &mLabel->Header, sizeof (EFI_IFR_GUID_LABEL)) { mLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; mLabel->Guid = IfrTianoGuid; } VOID SetNumber (IN UINT16 Number) { mLabel->Number = Number; } }; class CIfrBanner : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GUID_BANNER *mBanner; public: CIfrBanner () : CIfrObj (EFI_IFR_GUID_OP, (CHAR8 **)&mBanner, sizeof (EFI_IFR_GUID_BANNER)), CIfrOpHeader (EFI_IFR_GUID_OP, &mBanner->Header, sizeof (EFI_IFR_GUID_BANNER)) { mBanner->ExtendOpCode = EFI_IFR_EXTEND_OP_BANNER; mBanner->Guid = IfrTianoGuid; } VOID SetTitle (IN EFI_STRING_ID StringId) { mBanner->Title = StringId; } VOID SetLine (IN UINT16 Line) { mBanner->LineNumber = Line; } VOID SetAlign (IN UINT8 Align) { mBanner->Alignment = Align; } }; class CIfrTimeout : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GUID_TIMEOUT *mTimeout; public: CIfrTimeout (IN UINT16 Timeout = 0) : CIfrObj (EFI_IFR_GUID_OP, (CHAR8 **)&mTimeout, sizeof (EFI_IFR_GUID_TIMEOUT)), CIfrOpHeader (EFI_IFR_GUID_OP, &mTimeout->Header, sizeof (EFI_IFR_GUID_TIMEOUT)) { mTimeout->ExtendOpCode = EFI_IFR_EXTEND_OP_TIMEOUT; mTimeout->Guid = IfrTianoGuid; mTimeout->TimeOut = Timeout; } VOID SetTimeout (IN UINT16 Timeout) { mTimeout->TimeOut = Timeout; } }; class CIfrDup : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_DUP *mDup; public: CIfrDup ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_DUP_OP, (CHAR8 **)&mDup), CIfrOpHeader (EFI_IFR_DUP_OP, &mDup->Header) { SetLineNo (LineNo); } }; class CIfrEqIdId : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_EQ_ID_ID *mEqIdId; public: CIfrEqIdId ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_EQ_ID_ID_OP, (CHAR8 **)&mEqIdId), CIfrOpHeader (EFI_IFR_EQ_ID_ID_OP, &mEqIdId->Header) { SetLineNo (LineNo); mEqIdId->QuestionId1 = EFI_QUESTION_ID_INVALID; mEqIdId->QuestionId2 = EFI_QUESTION_ID_INVALID; } VOID SetQuestionId1 ( IN EFI_QUESTION_ID QuestionId, IN INT8 *VarIdStr, IN UINT32 LineNo ) { if (QuestionId != EFI_QUESTION_ID_INVALID) { mEqIdId->QuestionId1 = QuestionId; } else { gCFormPkg.AssignPending (VarIdStr, (VOID *)(&mEqIdId->QuestionId1), sizeof (EFI_QUESTION_ID), LineNo); } } VOID SetQuestionId2 ( IN EFI_QUESTION_ID QuestionId, IN INT8 *VarIdStr, IN UINT32 LineNo ) { if (QuestionId != EFI_QUESTION_ID_INVALID) { mEqIdId->QuestionId2 = QuestionId; } else { gCFormPkg.AssignPending (VarIdStr, (VOID *)(&mEqIdId->QuestionId2), sizeof (EFI_QUESTION_ID), LineNo); } } }; class CIfrEqIdVal : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_EQ_ID_VAL *mEqIdVal; public: CIfrEqIdVal ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_EQ_ID_VAL_OP, (CHAR8 **)&mEqIdVal), CIfrOpHeader (EFI_IFR_EQ_ID_VAL_OP, &mEqIdVal->Header) { SetLineNo (LineNo); mEqIdVal->QuestionId = EFI_QUESTION_ID_INVALID; } VOID SetQuestionId ( IN EFI_QUESTION_ID QuestionId, IN INT8 *VarIdStr, IN UINT32 LineNo ) { if (QuestionId != EFI_QUESTION_ID_INVALID) { mEqIdVal->QuestionId = QuestionId; } else { gCFormPkg.AssignPending (VarIdStr, (VOID *)(&mEqIdVal->QuestionId), sizeof (EFI_QUESTION_ID), LineNo); } } VOID SetValue (IN UINT16 Value) { mEqIdVal->Value = Value; } }; class CIfrEqIdList : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_EQ_ID_LIST *mEqIdVList; public: CIfrEqIdList ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_EQ_ID_LIST_OP, (CHAR8 **)&mEqIdVList, sizeof (EFI_IFR_EQ_ID_LIST), TRUE), CIfrOpHeader (EFI_IFR_EQ_ID_LIST_OP, &mEqIdVList->Header) { SetLineNo (LineNo); mEqIdVList->QuestionId = EFI_QUESTION_ID_INVALID; mEqIdVList->ListLength = 0; mEqIdVList->ValueList[0] = 0; } VOID SetQuestionId ( IN EFI_QUESTION_ID QuestionId, IN INT8 *VarIdStr, IN UINT32 LineNo ) { if (QuestionId != EFI_QUESTION_ID_INVALID) { mEqIdVList->QuestionId = QuestionId; } else { gCFormPkg.AssignPending (VarIdStr, (VOID *)(&mEqIdVList->QuestionId), sizeof (EFI_QUESTION_ID), LineNo); } } VOID SetListLength (IN UINT16 ListLength) { mEqIdVList->ListLength = ListLength; } VOID SetValueList (IN UINT16 Index, IN UINT16 Value) { if (Index == 0) { mEqIdVList->ValueList[0] = Value; return; } if (ExpendObjBin (sizeof (UINT16)) ==TRUE) { IncLength (sizeof (UINT16)); mEqIdVList->ValueList[Index] = Value; } } }; class CIfrQuestionRef1 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_QUESTION_REF1 *mQuestionRef1; public: CIfrQuestionRef1 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_QUESTION_REF1_OP, (CHAR8 **)&mQuestionRef1), CIfrOpHeader (EFI_IFR_QUESTION_REF1_OP, &mQuestionRef1->Header) { SetLineNo (LineNo); mQuestionRef1->QuestionId = EFI_QUESTION_ID_INVALID; } VOID SetQuestionId ( IN EFI_QUESTION_ID QuestionId, IN INT8 *VarIdStr, IN UINT32 LineNo ) { if (QuestionId != EFI_QUESTION_ID_INVALID) { mQuestionRef1->QuestionId = QuestionId; } else { gCFormPkg.AssignPending (VarIdStr, (VOID *)(&mQuestionRef1->QuestionId), sizeof (EFI_QUESTION_ID), LineNo); } } }; class CIfrQuestionRef2 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_QUESTION_REF2 *mQuestionRef2; public: CIfrQuestionRef2 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_QUESTION_REF2_OP, (CHAR8 **)&mQuestionRef2), CIfrOpHeader (EFI_IFR_QUESTION_REF2_OP, &mQuestionRef2->Header) { SetLineNo (LineNo); } }; class CIfrQuestionRef3 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_QUESTION_REF3 *mQuestionRef3; public: CIfrQuestionRef3 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_QUESTION_REF3_OP, (CHAR8 **)&mQuestionRef3), CIfrOpHeader (EFI_IFR_QUESTION_REF3_OP, &mQuestionRef3->Header) { SetLineNo (LineNo); } }; class CIfrQuestionRef3_2 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_QUESTION_REF3_2 *mQuestionRef3_2; public: CIfrQuestionRef3_2 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_QUESTION_REF3_OP, (CHAR8 **)&mQuestionRef3_2, sizeof (EFI_IFR_QUESTION_REF3_2)), CIfrOpHeader (EFI_IFR_QUESTION_REF3_OP, &mQuestionRef3_2->Header, sizeof (EFI_IFR_QUESTION_REF3_2)) { SetLineNo (LineNo); mQuestionRef3_2->DevicePath = EFI_STRING_ID_INVALID; } VOID SetDevicePath (IN EFI_STRING_ID DevicePath) { mQuestionRef3_2->DevicePath = DevicePath; } }; class CIfrQuestionRef3_3 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_QUESTION_REF3_3 *mQuestionRef3_3; public: CIfrQuestionRef3_3 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_QUESTION_REF3_OP, (CHAR8 **)&mQuestionRef3_3, sizeof (EFI_IFR_QUESTION_REF3_3)), CIfrOpHeader (EFI_IFR_QUESTION_REF3_OP, &mQuestionRef3_3->Header, sizeof (EFI_IFR_QUESTION_REF3_3)) { SetLineNo (LineNo); mQuestionRef3_3->DevicePath = EFI_STRING_ID_INVALID; memset (&mQuestionRef3_3->Guid, 0, sizeof (EFI_GUID)); } VOID SetDevicePath (IN EFI_STRING_ID DevicePath) { mQuestionRef3_3->DevicePath = DevicePath; } VOID SetGuid (IN EFI_GUID *Guid) { mQuestionRef3_3->Guid = *Guid; } }; class CIfrRuleRef : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_RULE_REF *mRuleRef; public: CIfrRuleRef ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_RULE_REF_OP, (CHAR8 **)&mRuleRef), CIfrOpHeader (EFI_IFR_RULE_REF_OP, &mRuleRef->Header) { SetLineNo (LineNo); mRuleRef->RuleId = EFI_RULE_ID_INVALID; } VOID SetRuleId (IN UINT8 RuleId) { mRuleRef->RuleId = RuleId; } }; class CIfrStringRef1 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_STRING_REF1 *mStringRef1; public: CIfrStringRef1 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_STRING_REF1_OP, (CHAR8 **)&mStringRef1), CIfrOpHeader (EFI_IFR_STRING_REF1_OP, &mStringRef1->Header) { SetLineNo (LineNo); mStringRef1->StringId = EFI_STRING_ID_INVALID; } VOID SetStringId (IN EFI_STRING_ID StringId) { mStringRef1->StringId = StringId; } }; class CIfrStringRef2 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_STRING_REF2 *mStringRef2; public: CIfrStringRef2 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_STRING_REF2_OP, (CHAR8 **)&mStringRef2), CIfrOpHeader (EFI_IFR_STRING_REF2_OP, &mStringRef2->Header) { SetLineNo (LineNo); } }; class CIfrThis : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_THIS *mThis; public: CIfrThis ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_THIS_OP, (CHAR8 **)&mThis), CIfrOpHeader (EFI_IFR_THIS_OP, &mThis->Header) { SetLineNo (LineNo); } }; class CIfrUint8 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_UINT8 *mUint8; public: CIfrUint8 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_UINT8_OP, (CHAR8 **)&mUint8), CIfrOpHeader (EFI_IFR_UINT8_OP, &mUint8->Header) { SetLineNo (LineNo); } VOID SetValue (IN UINT8 Value) { mUint8->Value = Value; } }; class CIfrUint16 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_UINT16 *mUint16; public: CIfrUint16 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_UINT16_OP, (CHAR8 **)&mUint16), CIfrOpHeader (EFI_IFR_UINT16_OP, &mUint16->Header) { SetLineNo (LineNo); } VOID SetValue (IN UINT16 Value) { mUint16->Value = Value; } }; class CIfrUint32 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_UINT32 *mUint32; public: CIfrUint32 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_UINT32_OP, (CHAR8 **)&mUint32), CIfrOpHeader (EFI_IFR_UINT32_OP, &mUint32->Header) { SetLineNo (LineNo); } VOID SetValue (IN UINT32 Value) { mUint32->Value = Value; } }; class CIfrUint64 : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_UINT64 *mUint64; public: CIfrUint64 ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_UINT64_OP, (CHAR8 **)&mUint64), CIfrOpHeader (EFI_IFR_UINT64_OP, &mUint64->Header) { SetLineNo (LineNo); } VOID SetValue (IN UINT64 Value) { mUint64->Value = Value; } }; class CIfrTrue : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TRUE *mTrue; public: CIfrTrue ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TRUE_OP, (CHAR8 **)&mTrue), CIfrOpHeader (EFI_IFR_TRUE_OP, &mTrue->Header) { SetLineNo (LineNo); } }; class CIfrFalse : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_FALSE *mFalse; public: CIfrFalse ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_FALSE_OP, (CHAR8 **)&mFalse), CIfrOpHeader (EFI_IFR_FALSE_OP, &mFalse->Header) { SetLineNo (LineNo); } }; class CIfrOne : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_ONE *mOne; public: CIfrOne ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_ONE_OP, (CHAR8 **)&mOne), CIfrOpHeader (EFI_IFR_ONE_OP, &mOne->Header) { SetLineNo (LineNo); } }; class CIfrOnes : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_ONES *mOnes; public: CIfrOnes ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_ONES_OP, (CHAR8 **)&mOnes), CIfrOpHeader (EFI_IFR_ONES_OP, &mOnes->Header) { SetLineNo (LineNo); } }; class CIfrZero : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_ZERO *mZero; public: CIfrZero ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_ZERO_OP, (CHAR8 **)&mZero), CIfrOpHeader (EFI_IFR_ZERO_OP, &mZero->Header) { SetLineNo (LineNo); } }; class CIfrUndefined : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_UNDEFINED *mUndefined; public: CIfrUndefined ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_UNDEFINED_OP, (CHAR8 **)&mUndefined), CIfrOpHeader (EFI_IFR_UNDEFINED_OP, &mUndefined->Header) { SetLineNo (LineNo); } }; class CIfrVersion : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_VERSION *mVersion; public: CIfrVersion ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_VERSION_OP, (CHAR8 **)&mVersion), CIfrOpHeader (EFI_IFR_VERSION_OP, &mVersion->Header) { SetLineNo (LineNo); } }; class CIfrLength : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_LENGTH *mLength; public: CIfrLength ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_LENGTH_OP, (CHAR8 **)&mLength), CIfrOpHeader (EFI_IFR_LENGTH_OP, &mLength->Header) { SetLineNo (LineNo); } }; class CIfrNot : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_NOT *mNot; public: CIfrNot ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_NOT_OP, (CHAR8 **)&mNot), CIfrOpHeader (EFI_IFR_NOT_OP, &mNot->Header) { SetLineNo (LineNo); } }; class CIfrBitWiseNot : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_BITWISE_NOT *mBitWise; public: CIfrBitWiseNot ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_BITWISE_NOT_OP, (CHAR8 **)&mBitWise), CIfrOpHeader (EFI_IFR_BITWISE_NOT_OP, &mBitWise->Header) { SetLineNo (LineNo); } }; class CIfrToBoolean : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TO_BOOLEAN *mToBoolean; public: CIfrToBoolean ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TO_BOOLEAN_OP, (CHAR8 **)&mToBoolean), CIfrOpHeader (EFI_IFR_TO_BOOLEAN_OP, &mToBoolean->Header) { SetLineNo (LineNo); } }; class CIfrToString : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TO_STRING *mToString; public: CIfrToString ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TO_STRING_OP, (CHAR8 **)&mToString), CIfrOpHeader (EFI_IFR_TO_STRING_OP, &mToString->Header) { SetLineNo (LineNo); } VOID SetFormat (IN UINT8 Format) { mToString->Format = Format; } }; class CIfrToUint : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TO_UINT *mToUint; public: CIfrToUint ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TO_UINT_OP, (CHAR8 **)&mToUint), CIfrOpHeader (EFI_IFR_TO_UINT_OP, &mToUint->Header) { SetLineNo (LineNo); } }; class CIfrToUpper : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TO_UPPER *mToUpper; public: CIfrToUpper ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TO_UPPER_OP, (CHAR8 **)&mToUpper), CIfrOpHeader (EFI_IFR_TO_UPPER_OP, &mToUpper->Header) { SetLineNo (LineNo); } }; class CIfrToLower : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TO_LOWER *mToLower; public: CIfrToLower ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TO_LOWER_OP, (CHAR8 **)&mToLower), CIfrOpHeader (EFI_IFR_TO_LOWER_OP, &mToLower->Header) { SetLineNo (LineNo); } }; class CIfrAdd : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_ADD *mAdd; public: CIfrAdd ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_ADD_OP, (CHAR8 **)&mAdd), CIfrOpHeader (EFI_IFR_ADD_OP, &mAdd->Header) { SetLineNo (LineNo); } }; class CIfrBitWiseAnd : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_BITWISE_AND *mBitWiseAnd; public: CIfrBitWiseAnd ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_BITWISE_AND_OP, (CHAR8 **)&mBitWiseAnd), CIfrOpHeader (EFI_IFR_BITWISE_AND_OP, &mBitWiseAnd->Header) { SetLineNo(LineNo); } }; class CIfrBitWiseOr : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_BITWISE_OR *mBitWiseOr; public: CIfrBitWiseOr ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_BITWISE_OR_OP, (CHAR8 **)&mBitWiseOr), CIfrOpHeader (EFI_IFR_BITWISE_OR_OP, &mBitWiseOr->Header) { SetLineNo (LineNo); } }; class CIfrAnd : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_AND *mAnd; public: CIfrAnd ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_AND_OP, (CHAR8 **)&mAnd), CIfrOpHeader (EFI_IFR_AND_OP, &mAnd->Header) { SetLineNo (LineNo); } }; class CIfrCatenate : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_CATENATE *mCatenate; public: CIfrCatenate ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_CATENATE_OP, (CHAR8 **)&mCatenate), CIfrOpHeader (EFI_IFR_CATENATE_OP, &mCatenate->Header) { SetLineNo (LineNo); } }; class CIfrDivide : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_DIVIDE *mDivide; public: CIfrDivide ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_DIVIDE_OP, (CHAR8 **)&mDivide), CIfrOpHeader (EFI_IFR_DIVIDE_OP, &mDivide->Header) { SetLineNo (LineNo); } }; class CIfrEqual : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_EQUAL *mEqual; public: CIfrEqual ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_EQUAL_OP, (CHAR8 **)&mEqual), CIfrOpHeader (EFI_IFR_EQUAL_OP, &mEqual->Header) { SetLineNo (LineNo); } }; class CIfrGreaterEqual : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GREATER_EQUAL *mGreaterEqual; public: CIfrGreaterEqual ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_GREATER_EQUAL_OP, (CHAR8 **)&mGreaterEqual), CIfrOpHeader (EFI_IFR_GREATER_EQUAL_OP, &mGreaterEqual->Header) { SetLineNo (LineNo); } }; class CIfrGreaterThan : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_GREATER_THAN *mGreaterThan; public: CIfrGreaterThan ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_GREATER_THAN_OP, (CHAR8 **)&mGreaterThan), CIfrOpHeader (EFI_IFR_GREATER_THAN_OP, &mGreaterThan->Header) { SetLineNo (LineNo); } }; class CIfrLessEqual : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_LESS_EQUAL *mLessEqual; public: CIfrLessEqual ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_LESS_EQUAL_OP, (CHAR8 **)&mLessEqual), CIfrOpHeader (EFI_IFR_LESS_EQUAL_OP, &mLessEqual->Header) { SetLineNo (LineNo); } }; class CIfrLessThan : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_LESS_THAN *mLessThan; public: CIfrLessThan ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_LESS_THAN_OP, (CHAR8 **)&mLessThan), CIfrOpHeader (EFI_IFR_LESS_THAN_OP, &mLessThan->Header) { SetLineNo (LineNo); } }; class CIfrMatch : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_MATCH *mMatch; public: CIfrMatch ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_MATCH_OP, (CHAR8 **)&mMatch), CIfrOpHeader (EFI_IFR_MATCH_OP, &mMatch->Header) { SetLineNo (LineNo); } }; class CIfrMultiply : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_MULTIPLY *mMultiply; public: CIfrMultiply ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_MULTIPLY_OP, (CHAR8 **)&mMultiply), CIfrOpHeader (EFI_IFR_MULTIPLY_OP, &mMultiply->Header) { SetLineNo (LineNo); } }; class CIfrModulo : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_MODULO *mModulo; public: CIfrModulo ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_MODULO_OP, (CHAR8 **)&mModulo), CIfrOpHeader (EFI_IFR_MODULO_OP, &mModulo->Header) { SetLineNo (LineNo); } }; class CIfrNotEqual : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_NOT_EQUAL *mNotEqual; public: CIfrNotEqual ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_NOT_EQUAL_OP, (CHAR8 **)&mNotEqual), CIfrOpHeader (EFI_IFR_NOT_EQUAL_OP, &mNotEqual->Header) { SetLineNo (LineNo); } }; class CIfrOr : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_OR *mOr; public: CIfrOr ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_OR_OP, (CHAR8 **)&mOr), CIfrOpHeader (EFI_IFR_OR_OP, &mOr->Header) { SetLineNo (LineNo); } }; class CIfrShiftLeft : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_SHIFT_LEFT *mShiftLeft; public: CIfrShiftLeft ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_SHIFT_LEFT_OP, (CHAR8 **)&mShiftLeft), CIfrOpHeader (EFI_IFR_SHIFT_LEFT_OP, &mShiftLeft->Header) { SetLineNo (LineNo); } }; class CIfrShiftRight : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_SHIFT_RIGHT *mShiftRight; public: CIfrShiftRight ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_SHIFT_RIGHT_OP, (CHAR8 **)&mShiftRight), CIfrOpHeader (EFI_IFR_SHIFT_RIGHT_OP, &mShiftRight->Header) { SetLineNo (LineNo); } }; class CIfrSubtract : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_SUBTRACT *mSubtract; public: CIfrSubtract ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_SUBTRACT_OP, (CHAR8 **)&mSubtract), CIfrOpHeader (EFI_IFR_SUBTRACT_OP, &mSubtract->Header) { SetLineNo (LineNo); } }; class CIfrConditional : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_CONDITIONAL *mConditional; public: CIfrConditional ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_CONDITIONAL_OP, (CHAR8 **)&mConditional), CIfrOpHeader (EFI_IFR_CONDITIONAL_OP, &mConditional->Header) { SetLineNo (LineNo); } }; class CIfrFind : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_FIND *mFind; public: CIfrFind ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_FIND_OP, (CHAR8 **)&mFind), CIfrOpHeader (EFI_IFR_FIND_OP, &mFind->Header) { SetLineNo (LineNo); } VOID SetFormat (IN UINT8 Format) { mFind->Format = Format; } }; class CIfrMid : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_MID *mMid; public: CIfrMid ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_MID_OP, (CHAR8 **)&mMid), CIfrOpHeader (EFI_IFR_MID_OP, &mMid->Header) { SetLineNo (LineNo); } }; class CIfrToken : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_TOKEN *mToken; public: CIfrToken ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_TOKEN_OP, (CHAR8 **)&mToken), CIfrOpHeader (EFI_IFR_TOKEN_OP, &mToken->Header) { SetLineNo (LineNo); } }; class CIfrSpan : public CIfrObj, public CIfrOpHeader { private: EFI_IFR_SPAN *mSpan; public: CIfrSpan ( IN UINT32 LineNo ) : CIfrObj (EFI_IFR_SPAN_OP, (CHAR8 **)&mSpan), CIfrOpHeader (EFI_IFR_SPAN_OP, &mSpan->Header) { SetLineNo (LineNo); mSpan->Flags = EFI_IFR_FLAGS_FIRST_MATCHING; } EFI_VFR_RETURN_CODE SetFlags (IN UINT8 LFlags) { if (_IS_EQUAL (LFlags, EFI_IFR_FLAGS_FIRST_MATCHING)) { mSpan->Flags |= EFI_IFR_FLAGS_FIRST_MATCHING; } else if (_FLAG_TEST_AND_CLEAR (LFlags, EFI_IFR_FLAGS_FIRST_NON_MATCHING)) { mSpan->Flags |= EFI_IFR_FLAGS_FIRST_NON_MATCHING; } return _FLAGS_ZERO (LFlags) ? VFR_RETURN_SUCCESS : VFR_RETURN_FLAGS_UNSUPPORTED; } }; #endif
[ [ [ 1, 2271 ] ] ]
a14f71a4813d958d399d809b06e04ce8d2cb139e
fb7d4d40bf4c170328263629acbd0bbc765c34aa
/SpaceBattle/SpaceBattleLib/GeneratedCode/Modele/Implementation/Couleur.h
0cbd8110c00605ce5ee5fc01e5e09c73f13462ae
[]
no_license
bvannier/SpaceBattle
e146cda9bac1608141ad8377620623514174c0cb
6b3e1a8acc5d765223cc2b135d2b98c8400adf06
refs/heads/master
2020-05-18T03:40:16.782219
2011-11-28T22:49:36
2011-11-28T22:49:36
2,659,535
0
1
null
null
null
null
UTF-8
C++
false
false
387
h
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ModeleImplementation { enum Couleur { }; }
[ [ [ 1, 13 ] ] ]
084fb1ed17916160dfb3d2d8541df322e1f5f340
0c1f669f3dfdab47085bf537348b0354f836abea
/ qtremotedroid/QTNavigator_oldcode/QTNavigator/Server/src/start.h
79ecd977166a68493b3de00994d813dfea940d89
[]
no_license
harlentan/qtremotedroid
fc5fc96d4374c39561aea73470a88d1f0a68b637
d07dd045213711538b38c7ced2fd6d5a8edcf241
refs/heads/master
2021-01-10T11:37:59.331004
2010-12-12T09:55:39
2010-12-12T09:55:39
54,114,402
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#ifndef START_H #define START_H #include <QtGui/QWidget> #include "UDPClient.h" QT_BEGIN_NAMESPACE class QLabel; class QProgressBar; class QPixmap; class QSplashScreen; QT_END_NAMESPACE class start : public QWidget { Q_OBJECT public: start(QWidget *parent = 0); ~start(); private: void setupUI(); QLabel *imageLabel; UDPClient *udpClientObj; }; #endif // START_H
[ [ [ 1, 30 ] ] ]
2faedf25505284fb7190a9137dc01a95ec672100
bc0a05b60c7ef7180120c577e377a977abd4c725
/ColorConfiguration.cpp
98692fdfc68bf17a30a27a0bb428d935f9b9a182
[]
no_license
swak/stonesense
7f0b821d4dcd48ba02b4c0df2850cd7355b4f2fa
54b791c019d4874c0880fc44903b26af2925231f
refs/heads/master
2021-01-06T20:37:39.613771
2011-08-04T16:55:09
2011-08-04T16:55:09
42,753,526
0
0
null
null
null
null
UTF-8
C++
false
false
3,765
cpp
#include "ColorConfiguration.h" #include "ContentLoader.h" #include <set> ColorMaterialConfiguration::ColorMaterialConfiguration() { color = al_map_rgb(255,255,255); colorSet = 0; } ColorConfiguration::ColorConfiguration() { color = al_map_rgb(255,255,255); colorSet = 0; } ColorConfiguration::~ColorConfiguration() { colorMaterials.clear(); } void parseColorElement( TiXmlElement* elemColor, vector<ColorConfiguration> & configTable) { const char* colorRedStr = elemColor->Attribute("red"); if(colorRedStr == NULL || colorRedStr[0] == 0) { contentError("Invalid or missing color attribute",elemColor); return; //nothing to work with } const char* colorGreenStr = elemColor->Attribute("green"); if(colorGreenStr == NULL || colorGreenStr[0] == 0) { contentError("Invalid or missing color attribute",elemColor); return; //nothing to work with } const char* colorBlueStr = elemColor->Attribute("blue"); if(colorBlueStr == NULL || colorBlueStr[0] == 0) { contentError("Invalid or missing color attribute",elemColor); return; //nothing to work with } int red = atoi(colorRedStr); int green = atoi(colorGreenStr); int blue = atoi(colorBlueStr); ALLEGRO_COLOR color = al_map_rgb(red, green, blue); //parse material elements TiXmlElement* elemMaterial = elemColor->FirstChildElement("material"); if(elemMaterial == NULL) { //if none, there's nothing to be done with this color. contentError("Invalid or missing material attribute",elemColor); return; } for( ;elemMaterial;elemMaterial = elemMaterial->NextSiblingElement("material")) { // get material type int elemIndex = lookupMaterialType(elemMaterial->Attribute("value")); if (elemIndex == INVALID_INDEX) { contentError("Invalid or missing value attribute",elemMaterial); continue; } // parse subtype elements TiXmlElement* elemSubtype = elemMaterial->FirstChildElement("subtype"); if (elemSubtype == NULL) { // add the configurations if (configTable.size() <= (uint32_t)elemIndex) { //increase size if needed configTable.resize(elemIndex+1); } if(configTable.at(elemIndex).colorSet == false) { configTable.at(elemIndex).color = color; configTable.at(elemIndex).colorSet = true; } return; } for ( ;elemSubtype; elemSubtype = elemSubtype ->NextSiblingElement("subtype")) { // get subtype int subtypeId = lookupMaterialIndex(elemIndex,elemSubtype->Attribute("value")); if (subtypeId == INVALID_INDEX) { contentError("Invalid or missing value attribute",elemSubtype); continue; } // add the configurations if (configTable.size() <= (uint32_t)elemIndex) { //increase size if needed configTable.resize(elemIndex+1); } if (configTable.at(elemIndex).colorMaterials.size() <= (uint32_t)subtypeId) { //increase size if needed configTable.at(elemIndex).colorMaterials.resize(subtypeId+1); } if (configTable.at(elemIndex).colorMaterials.at(subtypeId).colorSet == false) { configTable.at(elemIndex).colorMaterials.at(subtypeId).color = color; configTable.at(elemIndex).colorMaterials.at(subtypeId).colorSet = true; } } } } void flushColorConfig(vector<ColorConfiguration>& config) { config.clear(); } bool addSingleColorConfig( TiXmlElement* elemRoot) { string elementType = elemRoot->Value(); if(elementType.compare( "colors" ) == 0){ //parse colors TiXmlElement* elemColor = elemRoot->FirstChildElement("color"); while( elemColor ){ parseColorElement( elemColor, contentLoader.colorConfigs); elemColor = elemColor->NextSiblingElement("color"); } } return true; }
[ "Japa.Mala.Illo@4d48de78-bd66-11de-9616-7b1d4728551e", "japa.mala.illo@4d48de78-bd66-11de-9616-7b1d4728551e" ]
[ [ [ 1, 119 ], [ 122, 132 ] ], [ [ 120, 121 ] ] ]
5338b01e798f0f16e8de30acb2546080ca10ee48
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/linkmonitor.h
284673bbe95b62f5402a81787ded16f0c4a0d784
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,680
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: /************************************************************************/ /* 2010.1.4 ¹ØâùƼ */ /***********************************************************************/ #include <iostream> #include <vector> #include "G_common_defs.h" class Packet; class LinkMonitor { public: LinkMonitor(); virtual ~LinkMonitor(); virtual LinkMonitor* Copy() const; void Transmit(Packet*); // Called on every packet transmit void Log(std::ostream&, Mult_t = 0.0, const char* = nil, char = ' '); public: std::vector<double> history; // Number bits currently tx'ed for each class };
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 65 ] ] ]
7768e1d945c7296957dc56d3488c5e28e4d920ba
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/CodeLite/language.cpp
8d1c4cbf01f228250e12449b462daae7842bc955
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
17,493
cpp
#include "precompiled_header.h" #include "language.h" #include "variable.h" #include "function.h" #include "ctags_manager.h" #include "y.tab.h" #include <wx/stopwatch.h> #include <wx/ffile.h> #ifdef __VISUALC__ #ifdef _DEBUG #define new DEBUG_NEW #endif #endif //=============================================================== //defined in generated files from the yacc grammar: //cpp_scope_garmmar.y //cpp_variables_grammar.y //expr_garmmar.y extern std::string get_scope_name(const std::string &in, std::string &lastFuncName, std::string &lastFuncSignature); extern ExpressionResult &parse_expression(const std::string &in); extern void get_variables(const std::string &in, VariableList &li); extern void get_functions(const std::string &in, FunctionList &li); //=============================================================== Language::Language() : m_expression(wxEmptyString) , m_scanner(new CppScanner()) , m_tokenScanner(new CppScanner()) { // Initialise the braces map m_braces['<'] = '>'; m_braces['('] = ')'; m_braces['['] = ']'; m_braces['{'] = '}'; // C++ / C auto complete delimiters for tokens std::vector<wxString> delimArr; delimArr.push_back(_T("::")); delimArr.push_back(_T("->")); delimArr.push_back(_T(".")); SetAutoCompDeliemters(delimArr); } /// Destructor Language::~Language() { } /// Return the visible scope until pchStopWord is encountered wxString Language::GetScope(const wxString& srcString) { std::vector<wxString> scope_stack; wxString currScope; int type; // Initialize the scanner with the string to search const wxCharBuffer scannerText = _C(srcString); m_scanner->SetText( scannerText.data()); bool changedLine = false; bool consumeLine = false; int curline = 0; while(true) { type = m_scanner->yylex(); // Eof ? if(type == 0) { if(!currScope.empty()) scope_stack.push_back(currScope); break; } // eat up all tokens until next line if( consumeLine && m_scanner->lineno() == curline) continue; consumeLine = false; // Get the current line number, it will help us detect preprocessor lines changedLine = (m_scanner->lineno() > curline); curline = m_scanner->lineno(); // For debug purposes wxString word = _U(m_scanner->YYText()); switch(type) { case (int)'{': currScope += _T("\n"); scope_stack.push_back(currScope); currScope = _T("{\n"); break; case (int)'}': // Discard the current scope since it is completed if( !scope_stack.empty() ) { currScope = scope_stack.back(); scope_stack.pop_back(); currScope += _T("\n{}\n"); } else currScope = wxEmptyString; break; case (int)'#': if(changedLine) { // We are at the start of a new line // consume everything until new line is found or end of text consumeLine = true; break; } default: currScope += _T(" "); currScope += _U(m_scanner->YYText()); break; } } m_scanner->Reset(); if(scope_stack.empty()) return srcString; currScope = wxEmptyString; size_t i = 0; for(; i < scope_stack.size(); i++) currScope += scope_stack[i]; // if the current scope is not empty, terminate it with ';' and return if( currScope.IsEmpty() == false ) { currScope += _T(";"); return currScope; } return srcString; } bool Language::NextToken(wxString &token, wxString &delim) { int type(0); int depth(0); while( (type = m_tokenScanner->yylex()) != 0 ) { switch(type) { case CLCL: case wxT('.'): case lexARROW: if(depth == 0){ delim = _U(m_tokenScanner->YYText()); return true; }else{ token << wxT(" ") << _U(m_tokenScanner->YYText()); } break; case wxT('<'): case wxT('['): case wxT('('): case wxT('{'): depth++; token << wxT(" ") << _U(m_tokenScanner->YYText()); break; case wxT('>'): case wxT(']'): case wxT(')'): case wxT('}'): depth--; token << wxT(" ") << _U(m_tokenScanner->YYText()); break; default: token << wxT(" ") << _U(m_tokenScanner->YYText()); break; } } return false; } void Language::SetAutoCompDeliemters(const std::vector<wxString> &delimArr) { m_delimArr = delimArr; } bool Language::ProcessExpression(const wxString& stmt, const wxString& text, wxString &typeName, //output wxString &typeScope)//output { ExpressionResult result; wxString statement( stmt ); bool evaluationSucceeded = true; // Trim whitespace from right and left static wxString trimString(_T("{};\r\n\t\v ")); statement.erase(0, statement.find_first_not_of(trimString)); statement.erase(statement.find_last_not_of(trimString)+1); wxString dbgStmnt = statement; // First token is handled sepratly wxString word; wxString oper; wxString lastFuncSig; wxString accumulatedScope; std::vector<TagEntry> tags; wxString visibleScope = GetScope(text); wxString scopeName = GetScopeName(visibleScope, NULL, &lastFuncSig); wxLogMessage(wxT("Current scope: [") + scopeName + wxT("]")); wxString parentTypeName, parentTypeScope; //get next token using the tokenscanner object m_tokenScanner->SetText(_C(statement)); while(NextToken(word, oper)) { result = ParseExpression(word); //parsing failed? if(result.m_name.empty()) { wxLogMessage(wxT("Failed to parse expression: ") + word); evaluationSucceeded = false; break; } //no tokens before this, what we need to do now, is find the TagEntry //that corrseponds to the result if(result.m_isaType) { //------------------------------------------- // Handle type (usually when casting is found //-------------------------------------------- typeScope = result.m_scope.empty() ? wxT("<global>") : _U(result.m_scope.c_str()); if(oper == wxT("->") || oper == wxT(".")) { wxLogMessage(wxT("Illegal usage of '->', '.' operator on a type :") + _U(result.m_name.c_str())); evaluationSucceeded = false; break; } typeName = _U(result.m_name.c_str()); } else if(result.m_isThis) { //----------------------------------------- // special handle for 'this' keyword //----------------------------------------- typeScope = result.m_scope.empty() ? wxT("<global>") : _U(result.m_scope.c_str()); if(scopeName == wxT("<global>")) { wxLogMessage(wxT("Illegal use of 'this' keyword outside of valid scope")); evaluationSucceeded = false; break; } if(oper == wxT("::")) { wxLogMessage(wxT("Illegal usage of '::' operator on 'this' keyword")); evaluationSucceeded = false; break; } // if(oper == wxT("::")) if(result.m_isPtr && oper == wxT(".")) { wxLogMessage(wxT("Did u mean to use '->' instead of '.'?")); evaluationSucceeded = false; break; } if(!result.m_isPtr && oper == wxT("->")) { wxLogMessage(wxT("Did u mean to use '.' instead of '->'?")); evaluationSucceeded = false; break; } typeName = scopeName; } else { //------------------------------------------- // found an identifier //-------------------------------------------- wxString scopeToSearch(scopeName); if(parentTypeScope.IsEmpty() == false && parentTypeScope != wxT("<global>")) { scopeToSearch = parentTypeScope + wxT("::") + parentTypeName; } else if((parentTypeScope.IsEmpty()|| parentTypeScope == wxT("<global>")) && !parentTypeName.IsEmpty()) { scopeToSearch = parentTypeName; } //-------------------------------------------------------------------------------------------- //keep the scope that we searched so far. The accumumlated scope //are used for types, for scenarios like: //void Box::GetWidth() //{ // Rectangle:: // //trying to process the above code, will yield searching Rectangle inside Box scope, since we are //inside Box's GetWidth() function. //the correct behavior shuold be searching for Rectangle in the global scope. //to correct this, we do special handling for Qualifier followed by coloon:colon operator (::) if(accumulatedScope.IsEmpty() == false) { if(accumulatedScope == wxT("<global>")) { accumulatedScope = scopeToSearch; } else { accumulatedScope << wxT("::"); accumulatedScope << scopeToSearch; } } else { accumulatedScope << wxT("<global>"); } if(oper == wxT("::")) { //if the operator was something like 'Qualifier::', it is safe to assume //that the secope to be searched is the full expression scopeToSearch = accumulatedScope; } //get the derivation list of the typename bool res(false); res = TypeFromName( _U(result.m_name.c_str()), visibleScope, lastFuncSig, scopeToSearch, parentTypeName.IsEmpty(), typeName, //output typeScope); //output if(!res){ evaluationSucceeded = false; break; } } parentTypeName = typeName; parentTypeScope = typeScope; } if(evaluationSucceeded) { wxLogMessage(wxT("The expression [") + dbgStmnt + wxT("], evaluated into [") + parentTypeScope + wxT("::") + parentTypeName + wxT("]")); } return evaluationSucceeded; } void Language::ParseComments(const wxFileName &fileName, std::vector<DbRecordPtr> *comments) { wxString content; try { wxFFile f(fileName.GetFullPath().GetData()); if( !f.IsOpened() ) return; // read the content of the file and parse it f.ReadAll( &content ); f.Close(); } catch( ... ) { return; } m_scanner->Reset(); m_scanner->SetText( _C(content) ); m_scanner->KeepComment( 1 ); int type( 0 ); wxString comment(_T("")); int line(-1); while( true ) { type = m_scanner->yylex(); if( type == 0 ) //eof break; // we keep only comments if( type == CPPComment ) { // incase the previous comment was one line above this one, // concatenate them to a single comment if( m_scanner->lineno() - 1 == line ) { comment << m_scanner->GetComment(); line = m_scanner->lineno(); m_scanner->ClearComment(); continue; } // first time or no comment is buffer if( comment.IsEmpty() ) { comment = m_scanner->GetComment(); line = m_scanner->lineno(); m_scanner->ClearComment(); continue; } if( comment.IsEmpty() == false ) { comments->push_back( static_cast<DbRecord*>( new Comment( comment, fileName.GetFullPath(), line - 1)) ); comment.Empty(); line = -1; } comments->push_back( static_cast<DbRecord*>( new Comment( m_scanner->GetComment(), fileName.GetFullPath(), m_scanner->lineno()-1)) ); m_scanner->ClearComment(); } else if( type == CComment ) { comments->push_back( static_cast<DbRecord*>( new Comment( m_scanner->GetComment(), fileName.GetFullPath(), m_scanner->lineno()) ) ); m_scanner->ClearComment(); } } if( comment.IsEmpty() == false ) { comments->push_back( static_cast<DbRecord*>( new Comment( comment, fileName.GetFullPath(), line - 1) ) ); } // reset the scanner m_scanner->KeepComment( 0 ); m_scanner->Reset(); } wxString Language::GetScopeName(const wxString &in, wxString *lastFuncName, wxString *lastFuncSignature) { std::string lastFunc, lastFuncSig; const wxCharBuffer buf = _C(in); std::string scope_name = get_scope_name(buf.data(), lastFunc, lastFuncSig); wxString scope = _U(scope_name.c_str()); if(lastFuncName){ *lastFuncName = _U(lastFunc.c_str()); } if(lastFuncSignature){ *lastFuncSignature = _U(lastFuncSig.c_str()); } if(scope.IsEmpty()){ scope = wxT("<global>"); } return scope; } ExpressionResult Language::ParseExpression(const wxString &in) { const wxCharBuffer buf = _C(in); ExpressionResult result = parse_expression(buf.data()); return result; } bool Language::TypeFromName(const wxString &name, const wxString &text, const wxString &extraScope, const wxString &scopeName, bool firstToken, wxString &type, wxString &typeScope) { //try local scope VariableList li; FunctionList fooList; //first we try to match the current scope std::vector<TagEntryPtr> tags; TagsManagerST::Get()->FindByNameAndScope(name, scopeName, tags); if(tags.size() == 1) { TagEntryPtr tag(tags.at(0)); //we have a single match! if(tag->GetKind() == wxT("function") || tag->GetKind() == wxT("prototype")) { Function foo; if(FunctionFromPattern(tag->GetPattern(), foo)) { type = _U(foo.m_returnValue.m_type.c_str()); typeScope = foo.m_returnValue.m_typeScope.empty() ? wxT("<global>") : _U(foo.m_returnValue.m_typeScope.c_str()); return true; } // if(FunctionFromPattern(tag->GetPattern(), foo)) return false; } // if(tag->GetKind() == wxT("function") || tag->GetKind() == wxT("prototype")) else if(tag->GetKind() == wxT("member") || tag->GetKind() == wxT("variable")) { Variable var; if(VariableFromPattern(tag->GetPattern(), var)) { type = _U(var.m_type.c_str()); typeScope = var.m_typeScope.empty() ? wxT("<global>") : _U(var.m_typeScope.c_str()); return true; } return false; } else { type = tag->GetName(); typeScope = tag->GetScopeName(); } return true; } // if(tags.size() == 1) else { //if list contains more than one entry, check if all entries are of type 'function' or 'prototype' //(they can be mixed). If all entries are of one of these types, test their return value, //if all have the same return value, then we are ok Function foo; wxString tmpType, tmpTypeScope; bool allthesame(true); for(size_t i=0; i<tags.size(); i++) { TagEntryPtr tag(tags.at(i)); if(!FunctionFromPattern(tag->GetPattern(), foo)) { allthesame = false; break; } // if(!FunctionFromPattern(tag.GetPattern(), foo)) tmpType = _U(foo.m_returnValue.m_type.c_str()); tmpTypeScope = foo.m_returnValue.m_typeScope.empty() ? wxT("<global>") : _U(foo.m_returnValue.m_typeScope.c_str()); if(i > 0 && (tmpType != type || tmpTypeScope != typeScope)) { allthesame = false; break; } // if(i > 0 && (tmpType != type || tmpTypeScope != typeScope)) type = tmpType; typeScope = tmpTypeScope; } if(allthesame && !tags.empty()) { return true; } //can we test visible scope? if(firstToken) { const wxCharBuffer buf = _C(text); const wxCharBuffer buf2 = _C(extraScope); get_variables(buf.data(), li); get_variables(buf2.data(), li); //search for a full match in the returned list for(VariableList::iterator iter = li.begin(); iter != li.end(); iter++) { Variable var = (*iter); wxString var_name = _U(var.m_name.c_str()); if(var_name == name) { type = _U(var.m_type.c_str()); typeScope = var.m_typeScope.empty() ? wxT("<global>") : _U(var.m_typeScope.c_str()); return true; } } // for(VariableList::iterator iter = li.begin(); iter != li.end(); iter++) //no match in local scope, try the database } // if(firstToken) //too many matches or none at all wxLogMessage(wxT("too many matches or none at all for name: ") + name + wxT(" at scope: ") + scopeName); return false; } } bool Language::VariableFromPattern(const wxString &in, Variable &var) { VariableList li; wxString pattern(in); //we need to extract the return value from the pattern pattern = pattern.BeforeLast(wxT('$')); pattern = pattern.AfterFirst(wxT('^')); const wxCharBuffer patbuf = _C(pattern); li.clear(); get_variables(patbuf.data(), li); if(li.size() == 1) { var = (*li.begin()); return true; } // if(li.size() == 1) return false; } bool Language::FunctionFromPattern(const wxString &in, Function &foo) { FunctionList fooList; wxString pattern(in); //we need to extract the return value from the pattern pattern = pattern.BeforeLast(wxT('$')); pattern = pattern.AfterFirst(wxT('^')); //a limitiation of the function parser... pattern += wxT(';'); const wxCharBuffer patbuf = _C(pattern); get_functions(patbuf.data(), fooList); if(fooList.size() == 1) { foo = (*fooList.begin()); return true; } return false; } void Language::GetLocalVariables(const wxString &in, std::vector<TagEntryPtr> &tags, const wxString &name, SearchFlags flags) { VariableList li; Variable var; wxString pattern(in); const wxCharBuffer patbuf = _C(pattern); li.clear(); get_variables(patbuf.data(), li); VariableList::iterator iter = li.begin(); for(; iter != li.end(); iter++) { var = (*iter); wxString tagName = _U(var.m_name.c_str()); //if we have name, collect only tags that matches name if(!name.IsEmpty()){ if(flags == PartialMatch && !tagName.StartsWith(name)) continue; if(flags == ExactMatch && tagName != name) continue; } TagEntryPtr tag(new TagEntry()); tag->SetName(tagName); tag->SetKind(wxT("variable")); tag->SetParent(wxT("<local>")); tag->SetAccess(wxT("public")); tag->SetPattern(_U(var.m_pattern.c_str())); tags.push_back(tag); } }
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 651 ] ] ]
2fd76f999651fec0a6205c26ed251bcfc6ae39bc
af2233c4d6a1f94106134a73408fb234b6ae8436
/RenderUtility/GL.h
5168befec45985f5b1d7d13b925d8bc9388913d3
[]
no_license
liwenqiang1990/gpu-streaming-benchmark
33b01cd5c4964466a4be2de5a3a2f67c2389eb77
4339b8cc6d00820e20669488a0406d186d2ffc15
refs/heads/master
2020-06-01T11:07:42.246460
2011-06-20T21:39:02
2011-06-20T21:39:02
34,671,006
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
h
#ifndef GL_H #define GL_H #define GLEW_STATIC #include <GL/glew.h> //a GL wrapper struct glInitStatus { glInitStatus() :pixelPackedAlignment(1),pixelUnpackedAlignment(1) {}; //PixelStorei unsigned int pixelPackedAlignment, pixelUnpackedAlignment; // }; /* * A collection of reusable function on top of OpenGL * */ class GL { public: GL(); ~GL(); //init GL static void InitGLContext(); //called when there is no GLUT static void InitGLStatus(glInitStatus &GLstatus); //drawing geometry commands static void DrawFullScreenQuad(); static void DrawFullScreenQuadNegativeOneToOne(); //view port and camera static void SetupPerspectView(int w, int h, float *rotMat4X4, float *transVec3, float *eye = 0 ); static void SetupOrthogonalView(int viewport_ox, int viewport_oy,int viewport_w, int viewport_h, int left=0, int right=1, int bottom=0, int top=1); //MRT static void DrawRenderTarget(int o_x, int o_y, int x, int y, GLuint tex); //Matrix static void BuildViewingMatrix(float* modelViewMatrix, float translate[], float invRotMat[]);//tran vec3 rot vec16 static void BuildViewingMatrixNoTranslation(GLfloat* modelViewMatrix, GLfloat invRotMat[]); //error checking static void CheckErrors(); private: }; #endif
[ "[email protected]@46a6917a-aa20-85b6-2959-6e77123ad00a" ]
[ [ [ 1, 59 ] ] ]
f76341bcf8195f9182e15f7e9ad99695e6dfdb12
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
/itl/src/itl/mapgentor.hpp
cabd4340df04a44a98f4646c9922174d59a3023b
[ "BSL-1.0" ]
permissive
WolfgangSt/itl
e43ed68933f554c952ddfadefef0e466612f542c
6609324171a96565cabcf755154ed81943f07d36
refs/heads/master
2016-09-05T20:35:36.628316
2008-11-04T11:44:44
2008-11-04T11:44:44
327,076
0
1
null
null
null
null
UTF-8
C++
false
false
5,136
hpp
/*----------------------------------------------------------------------------+ Copyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin +-----------------------------------------------------------------------------+ Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +----------------------------------------------------------------------------*/ /* ------------------------------------------------------------------ class MapGentorT A random generator for Maps. ContainerGentorT does not cover maps, because its value_type contains const parts so void some(value_type& x) can NOT be implemented --------------------------------------------------------------------*/ #ifndef __MAPGENTOR_H_JOFA_000724__ #define __MAPGENTOR_H_JOFA_000724__ #include <itl/itl_list.hpp> #include <itl/gentorit.hpp> namespace itl { template <class MapTV> class MapGentorT: public RandomGentorAT<MapTV> { public: typedef typename MapTV::value_type ValueTypeTD; typedef typename MapTV::key_type DomainTD; typedef typename MapTV::data_type CodomainTD; typedef list<ValueTypeTD> SampleTypeTD; MapGentorT(): p_domainGentor(NULL), p_codomainGentor(NULL) {} ~MapGentorT() { delete p_domainGentor; delete p_codomainGentor; } virtual void some(MapTV& x); void last(MapTV& x)const; void last_permuted(MapTV& x)const; void setDomainGentor(RandomGentorAT<DomainTD>* gentor) { if(p_domainGentor) delete p_domainGentor; p_domainGentor = gentor; } void setCodomainGentor(RandomGentorAT<CodomainTD>* gentor) { if(p_codomainGentor) delete p_codomainGentor; p_codomainGentor = gentor; } void setRangeOfSampleSize(int lwb, int upb) { m_sampleSizeRange = rightopen_interval(lwb,upb); } void setRangeOfSampleSize(const interval<int>& szRange) { J_ASSERT(szRange.is_rightopen()); m_sampleSizeRange = szRange; } private: RandomGentorAT<DomainTD>* p_domainGentor; RandomGentorAT<CodomainTD>* p_codomainGentor; interval<int> m_sampleSizeRange; SampleTypeTD m_sample; int m_sampleSize; }; template <class MapTV> void MapGentorT<MapTV>::some(MapTV& x) { NumberGentorT<int> intGentor; x.clear(); m_sample.clear(); m_sampleSize = intGentor(m_sampleSizeRange); for(int i=0; i<m_sampleSize; i++) { DomainTD key; p_domainGentor->some(key); CodomainTD val; p_codomainGentor->some(val); x += ValueTypeTD(key,val); m_sample.push_back(ValueTypeTD(key,val)); } } template <class MapTV> void MapGentorT<MapTV>::last(MapTV& x)const { x.clear(); const_FORALL(typename SampleTypeTD, it, m_sample) x += *it; } template <class MapTV> void MapGentorT<MapTV>::last_permuted(MapTV& x)const { x.clear(); SampleTypeTD perm; NumberGentorT<int> intGentor; const_FORALL(typename SampleTypeTD, it, m_sample) { if( 0==intGentor(2) ) perm.push_back(*it); else perm.push_front(*it); } const_FORALL(typename SampleTypeTD, pit, perm) x += *pit; } /* template <class MapTV> void MapGentorT<MapTV>::lastSample(SampleTypeTD& sam)const { sam = m_sample; } template <class MapTV> void MapGentorT<MapTV>::lastSample_permuted(SampleTypeTD& sam) { NumberGentorT<unsigned> intGentor; x.clear(); int coin = intGentor.some(2); // gives 0 or 1 const_FORALL(typename SampleTypeTD, it, m_sample) { if( 0==intGentor.some(2) ) sam.push_back(*it); else sam.push_front(*it); } } */ } // namespace itl #endif
[ "jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a" ]
[ [ [ 1, 160 ] ] ]
ed06bb503c0c6f906772787f53c7345af8646c65
cd07acbe92f87b59260478f62a6f8d7d1e218ba9
/src/SpermView.cpp
1a4392e3f6bf8f97bae062ffd6d5ba928331e59e
[]
no_license
niepp/sperm-x
3a071783e573d0c4bae67c2a7f0fe9959516060d
e8f578c640347ca186248527acf82262adb5d327
refs/heads/master
2021-01-10T06:27:15.004646
2011-09-24T03:33:21
2011-09-24T03:33:21
46,690,957
1
1
null
null
null
null
GB18030
C++
false
false
47,996
cpp
// SpermView.cpp : implementation of the CSpermView class // #include "stdafx.h" #include "dxtrans.h" #include "spermview.h" #include "MemDC.h" #include "wingdi.h" #include "math.h" #include "spermview.h" #include "ImageProcess.h" #include "Sperm.h" #include "DShowUtilities.h" #include "SpermDoc.h" #include "SpermView.h" #include "browerdlg.h" #include "mainfrm.h" #include "math.h" #include "View3.h" #include "patientInfo.h" #include "OptionDlg.h" #include "spermview.h" #include "MorphaDetectDLG.h" #include "SpermMorphaSet.h" #include "AllFunction.h" #include "ImageConvert.h" #include "resource.h" #include "LiveDetectDLG.h" #include "PrinteDlg.h" #include "dib.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSpermView extern _ConnectionPtr theConnection; extern CSpermView* theView1; extern CView3* theView3; extern CString theStrPathApp; IMPLEMENT_DYNCREATE(CSpermView, CScrollView) BEGIN_MESSAGE_MAP(CSpermView, CScrollView) ON_WM_CONTEXTMENU() //{{AFX_MSG_MAP(CSpermView) ON_WM_ERASEBKGND() ON_COMMAND(ID_IMAGE, OnImage) ON_COMMAND(ID_PRINT_TABLE, OnPrintTable) ON_COMMAND(ID_PRINT_PREVIEW, OnPrintPreview) ON_COMMAND(ID_PRINT_SETUP, OnPrintSetup) ON_COMMAND(ID_DATA_OPTION_S, OnDataOption) ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_LBUTTONDBLCLK() ON_COMMAND(ID_FILE_OPEN_S, OnFileOpen) ON_COMMAND(ID_BUTTON_LEFTARROW, OnButtonLeftarrow) ON_COMMAND(ID_BUTTON_RIGHTARROW, OnButtonRightarrow) ON_UPDATE_COMMAND_UI(ID_BUTTON_LEFTARROW, OnUpdateButtonLeftarrow) ON_UPDATE_COMMAND_UI(ID_BUTTON_RIGHTARROW, OnUpdateButtonRightarrow) ON_COMMAND(ID_DELETE_SPERM, OnDeleteSperm) ON_WM_MOUSEWHEEL() ON_WM_SIZE() ON_COMMAND(ID_SPERM_MORSET, OnSpermMorset) ON_COMMAND(ID_NORMAL_SPERM, OnSpermNormal) ON_UPDATE_COMMAND_UI(ID_FILE_OPEN_S, OnUpdateFileOpenS) ON_COMMAND(ID_SPERM_DEL, OnSpermDel) ON_COMMAND(ID_MENU_A, OnSpermAddA) ON_COMMAND(ID_MENU_B, OnSpermAddB) ON_COMMAND(ID_MENU_C, OnSpermAddC) ON_COMMAND(ID_MENU_D, OnSpermAddD) ON_WM_TIMER() ON_COMMAND(ID_MENU_ADD_NORMAL2DB, OnMenuAddNormal2DB) ON_COMMAND(ID_MENU_ADD_ABNORMAL2DB, OnMenuAddAbnormal2DB) // ON_COMMAND(ID_MENU_DB_VERDICT, OnMenuDbVerdict) //}}AFX_MSG_MAP // Standard printing commands ON_MESSAGE(USER_MM_CAP_FRM_HAS_BEEN_FINISHED, OnCapFrmFinished) ON_COMMAND(ID_FILE_PRINT, CScrollView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CScrollView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CScrollView::OnFilePrintPreview) END_MESSAGE_MAP() CSpermView::CSpermView() { // TODO: add construction code here m_bAnalyseFinished=false; m_nOpenOpt = 0; m_nPos = -1; CBitmap bmp; bmp.LoadBitmap(IDB_BITMAP1); ///加载位图 m_brushBackground.CreatePatternBrush(&bmp); ///创建位图画刷 // { 3.29 m_eViewShowMode = INITIAL; // 处理中的序列图 memset(m_lpImage, NULL, sizeof(m_lpImage)); // 序列帧数据区指针 memset(m_lpBMIH, NULL, sizeof(m_lpBMIH)); // 序列帧信息头的指针 // 轨迹跟踪分析结果图 m_lpTrackResultBmData = NULL; // 轨迹跟踪结果图数据区指针 m_lpTrackResultBmInfo = NULL; // 轨迹跟踪结果图信息头的指针 // 轨迹跟踪手工调整图 m_lpAdjustBmData = NULL; m_lpAdjustBmInfo = NULL; m_nDeviceID = 0; m_bMenuItemFileOpen = true; // } 3.29 // { 2009_3_31 mMoveShowTimer = 0; mFrm = 0; // } 2009_3_31 } CSpermView::~CSpermView() { int i = 0; for(i=0; i<FRAME_NUM; i++) { delete []m_lpImage[i]; m_lpImage[i] = NULL; } for(i=0; i<FRAME_NUM; i++) { delete []m_lpBMIH[i]; m_lpBMIH[i] = NULL; } } BOOL CSpermView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CScrollView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CSpermView drawing void CSpermView::OnDraw(CDC* pDC) { theView1 = this; CSpermDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here CRect rect; GetClientRect(rect); CPoint sp= GetScrollPosition(); rect.right += sp.x; rect.bottom += sp.y; long wd = rect.Width(); long ht = rect.Height(); CDC memDC; memDC.CreateCompatibleDC(pDC); CBitmap bitmap; bitmap.CreateCompatibleBitmap(pDC,m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); memDC.SelectObject(&bitmap); memDC.FillSolidRect(rect, RGB(255,255,255)); switch(m_eViewShowMode) { case VIDEO_PLAY: // 视频播放状态 break; case FRAME_ADJUST_RESULT: // 显示实时调整结果状态 if( m_lpAdjustBmInfo != NULL) { ::StretchDIBits(pDC->m_hDC, 0, 0, wd, ht, 0, 0, m_lpAdjustBmInfo->biWidth, m_lpAdjustBmInfo->biHeight, m_lpAdjustBmData, (LPBITMAPINFO)(m_lpAdjustBmInfo), DIB_RGB_COLORS, SRCCOPY); } return; break; case VIDEO_RESULT: // 视频分析结果显示状态 if( m_lpTrackResultBmInfo != NULL) { ::StretchDIBits(pDC->m_hDC, 0, 0, wd, ht, 0, 0, m_lpTrackResultBmInfo->biWidth, m_lpTrackResultBmInfo->biHeight, m_lpTrackResultBmData, (LPBITMAPINFO)(m_lpTrackResultBmInfo), DIB_RGB_COLORS, SRCCOPY); } return; break; case MORPHA_IMAGE: // 形态学图像打开显示状态 if(m_imgMorphaImg.GetImage()) { CSize sz(m_imgMorphaImg.Width(), m_imgMorphaImg.Height()); SetScrollSizes(MM_TEXT,sz); m_imgMorphaImg.Show(memDC.m_hDC, 0, 0, m_imgMorphaImg.Width(), m_imgMorphaImg.Height() ); } break; case MORPHA_RESULT: // 形态学图像结果显示状态 if(m_bAnalyseFinished) { // 形态学分析图 DrawImage(&memDC); CSize sz(m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); SetScrollSizes(MM_TEXT,sz); } break; case INITIAL: // 初始态 default: pDC->FillRect(rect,&m_brushBackground); //用背景画刷填充区域 break; } pDC->SetViewportOrg(-GetScrollPosition()); pDC->BitBlt(0,0,rect.Width(),rect.Height(),&memDC,0,0,SRCCOPY); } ///////////////////////////////////////////////////////////////////////////// // CSpermView printing BOOL CSpermView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation pInfo->SetMaxPage(4); pInfo->m_nNumPreviewPages = 9; return DoPreparePrinting(pInfo); } void CSpermView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { // TODO: add extra initialization before printing pInfo->m_nNumPreviewPages = 9; } void CSpermView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CSpermView diagnostics #ifdef _DEBUG void CSpermView::AssertValid() const { CScrollView::AssertValid(); } void CSpermView::Dump(CDumpContext& dc) const { CScrollView::Dump(dc); } CSpermDoc* CSpermView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSpermDoc))); return (CSpermDoc*)m_pDocument; } #endif //_DEBUG BOOL CSpermView::OnEraseBkgnd(CDC* pDC) { // TODO: Add your message handler code here and/or call default CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView=(CView3*)pMainFrm->GetView3(); if (pView->m_pwndLiveDetectDlg->m_pVideoPlay && pView->m_pwndLiveDetectDlg->m_bIsVideoPlay == TRUE) return true; return CScrollView::OnEraseBkgnd(pDC); } // void CSpermView::InverseImage(LPBITMAPINFOHEADER lpSrcInfo, LPBYTE lpSrcData) // { // int i, j; // int nh = lpSrcInfo->biHeight, nw = lpSrcInfo->biWidth; // long lw = WIDTHBYTES((m_lpBMIH[0]->biWidth)*32);//每行的字节数 // for (i=0; i<nh; i++){ // for (j=0; j<nw; j++){ // if( lpSrcData[ i*lw + nw*4 + 0 ] >= 220 ){ // lpSrcData[ i*lw + nw*4 + 0 ] = 255 - lpSrcData[ i*lw + nw*4 + 0 ]; // lpSrcData[ i*lw + nw*4 + 1 ] = lpSrcData[ i*lw + nw*4 + 0 ]; // lpSrcData[ i*lw + nw*4 + 1 ] = lpSrcData[ i*lw + nw*4 + 0 ]; // } // } // } // } void CSpermView::OnImage() { // TODO: Add your command handler code here switch(theView3->m_eDetectMode) { case CView3::CAMERAAVI: // 关闭摄像头 theView3->m_pwndLiveDetectDlg->m_cap.Stop(); break; case CView3::VIDEOAVI: // 暂停视频文件 theView3->m_pwndLiveDetectDlg->OnBtnPause(); { theView3->m_pwndLiveDetectDlg->GetDlgItem(IDC_BTN_PLAY)->EnableWindow(false); theView3->m_pwndLiveDetectDlg->GetDlgItem(IDC_BTN_STOP)->EnableWindow(false); theView3->m_pwndLiveDetectDlg->GetDlgItem(IDC_BTN_PAUSE)->EnableWindow(false); theView3->m_pwndLiveDetectDlg->GetDlgItem(IDC_BTN_RESUME)->EnableWindow(false); } break; } m_eViewShowMode = FRAME_ADJUST_RESULT; Invalidate(); #ifdef _SAVE_IMAGE_FRAME //取得运行程序的绝对路径 CString sPath(theStrPathApp); sPath += "\\Sperm_Images\\"; if(CreateDirectory((LPCTSTR)sPath,NULL)) AfxMessageBox("CreateDirectory suceed...\n"); CFile file; CFileException e; CDib *pdib = new CDib; #endif // _SAVE_IMAGE_FRAME int m; long lw = WIDTHBYTES((m_lpBMIH[0]->biWidth)*32);//每行的字节数 for(m=0; m<FRAME_NUM; m++) { #ifdef _SAVE_IMAGE_FRAME pdib->m_pInfoHeader = m_lpBMIH[m]; pdib->m_pData = m_lpImage[m]; CString str; str.Format("%d.bmp", m+1); CString SaveBmpPath = sPath + str; // 文件绝对路径 file.Open( SaveBmpPath, CFile::modeCreate | CFile::modeWrite); pdib->SaveDibFile(&file); file.Close(); #endif // _SAVE_IMAGE_FRAME ::Rgb2Gray(m_lpBMIH[m], m_lpImage[m]); //灰度化 //InverseImage(m_lpBMIH[m], m_lpImage[m]); //::MediaFilter(m_lpBMIH[m], m_lpImage[m]); //中值滤波 //::MeanFilter(m_lpBMIH[m], m_lpImage[m]); //高斯平滑 } // 运动回放用的图像序列 int nh = m_lpBMIH[0]->biHeight; int nw = m_lpBMIH[0]->biWidth; LPBITMAPINFOHEADER (&pMoveImgSeqInfo)[FRAME_NUM] = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqInfo; LPBYTE (&pMoveImgSeqData)[FRAME_NUM] = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqData; for(m=0; m<FRAME_NUM; m++) { DeleteDIBImage(pMoveImgSeqInfo[m], pMoveImgSeqData[m]); } int i, j; for(m=0; m<FRAME_NUM; m++) { NewDIBImage(pMoveImgSeqInfo[m], pMoveImgSeqData[m], nw, nh, 4); for(i=0; i<nh; ++i) for(j=0; j<nw; ++j) memcpy(pMoveImgSeqData[m] + i*lw + j*4, m_lpImage[m] + i*lw + j*4, 3); } } LRESULT CSpermView::OnCapFrmFinished(WPARAM wParam,LPARAM lParam) { switch(theView3->m_eDetectMode) { case CView3::CAMERAAVI: GuoPing(); break; case CView3::VIDEOAVI: GuoPing(); break; } return S_OK; } CString GetConnectIP() { CString bstr = (char*)theConnection->GetConnectionString(); int nl = bstr.Find("Data Source=") + strlen("Data Source="); int nr = bstr.Find(";", nl); return bstr.Mid(nl, nr-nl); } void CSpermView::OnPrintTable() { /* crxparm parm; parm.ipadd = TEXT( GetConnectIP() ); parm.database = TEXT("sperm"); parm.username = TEXT("sa"); parm.passwd = TEXT("sa"); ReportPrinter cpr; cpr.PrintReport(reportype,parm,pDectectNo);*/ } void CSpermView::OnPrintPreview() { PreviewResult(2,"asgdhdfhgj"); /* int reportype = 2; CString strdetect("asgdhdfhgj"); crxparm parm; parm.ipadd = TEXT( GetConnectIP() ); parm.database = TEXT("sperm"); parm.username = TEXT("sa"); parm.passwd = TEXT("sa"); CPrinteDlg cpld(reportype,parm,strdetect); cpld.DoModal(); */ } void CSpermView::OnPrintSetup() { // TODO: Add your command handler code here // SendMessage(WM_COMMAND,ID_FILE_PRINT_SETUP); // OnFilePrintSetup(); } void CSpermView::OnDataOption() { COptionDlg dlg; dlg.DoModal(); } void CSpermView::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView=(CView3*)pMainFrm->GetView3(); CMorphaDetectDLG* pWnd=(CMorphaDetectDLG*)pView->m_pwndMorphaDetDlg; if(pWnd==NULL || pWnd->m_hWnd == NULL) return; vector<SpermImage>& m_vRSpermImage = pWnd->m_vRSpermImage; vector<SpermImage>& m_vOSpermImage = pWnd->m_vOSpermImage; vector<SperMopyParameter>&m_vSperMopyParameter = pWnd->m_vSperMopyParameter; vector<SpermRegion>&m_vSpermRegion = pWnd->m_vSpermRegion ; vector<IsSperNormal>&m_vbIsNormal = pWnd->m_vbIsNormal; int i, iPos = -1, n; n = m_vRSpermImage.size(); CPoint sp = GetScrollPosition(); // 得到视图滚动了多少(以象素为单位) point += sp; double d, min = 1<<20; CPoint p; for(i=0; i<n; i++) { if( m_vSpermRegion[i].isDeleted == TRUE ) continue; p = CPoint(m_vSpermRegion[i].SpermCenterPos.y, m_vSpermRegion[i].SpermCenterPos.x); if( IsInRect(point, pWnd->m_nR, p) ) { d = dist(point, p); if(d<min) { min = d; iPos = i; } } } pWnd->m_nSelNO = iPos; m_nPos = iPos; if(m_nPos == -1 ) return; CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); pWnd->UpdateData(FALSE); pWnd->Invalidate(); CScrollView::OnLButtonDown(nFlags, point); } void CSpermView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CScrollView::OnLButtonUp(nFlags, point); } void CSpermView::OnLButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CPoint sPoint=point+GetScrollPosition(); ClientToScreen(&sPoint); int iPos=GetSpermIndex(sPoint); if(iPos != -1) { CSpermMorphaSet dlg(iPos); dlg.DoModal(); CPoint sp=GetScrollPosition(); CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); } CScrollView::OnLButtonDblClk(nFlags, point); } void CSpermView::OnFileOpen() { switch(m_nOpenOpt) { case LIVE_VIDEO_CAMERA : // 摄像头视频流采集 default break; case LIVE_VIEDO_FILE: // 硬盘视频文件采集 FileOpenDiskVideoFile(); break; case MORPHA: // 形态学分析图像 FileOpenMorphaImage(); break; } } void CSpermView::FileOpenDiskVideoFile() { CMainFrame* pFrame=(CMainFrame*)AfxGetApp()->m_pMainWnd; CFileDialog dlg(TRUE,NULL,NULL,NULL,"AVI文件(*.avi)|*.avi|Mpeg文件(*.mpg)|*.mpg|Mp3文件(*.mp3)|*.mp3|Wave文件(*.wav)|*.wav|All Files (*.*)|*.*||"); dlg.m_ofn.lpstrTitle="打开多媒体文件"; if(dlg.DoModal()==IDOK) { theView3->GetDlgItem(IDC_BUTTON_MORPHADETECT)->EnableWindow(FALSE); theView3->GetDlgItem(IDC_BTN_LIVEDETECTED)->EnableWindow(TRUE); if(theView3->m_pwndLiveDetectDlg->m_pVideoPlay) { theView3->m_pwndLiveDetectDlg->m_pVideoPlay->OnVideoStop(); delete theView3->m_pwndLiveDetectDlg->m_pVideoPlay; theView3->m_pwndLiveDetectDlg->m_pVideoPlay = NULL; } theView3->m_pwndLiveDetectDlg->m_pVideoPlay = new CMyVideoPlay; theView3->m_pwndLiveDetectDlg->m_pVideoPlay->Init(this->GetSafeHwnd(), this->GetSafeHwnd(), dlg.GetPathName() ); theView3->m_pwndLiveDetectDlg->m_pVideoPlay->OnVideoPlay(); theView3->m_pwndLiveDetectDlg->m_dFrequency = theView3->m_pwndLiveDetectDlg->m_pVideoPlay->GetVideoInfo().mFramePerSecond; m_eViewShowMode = VIDEO_PLAY; SetScrollSizes(MM_TEXT, CSize(100,100)); } } void CSpermView::FileOpenMorphaImage() { CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView=(CView3*)pMainFrm->GetView3(); CString strOpenFileType = "位图文件(*.bmp)|*.bmp|jpg文件(*.jpg;*.jpeg)|*.jpg;jpeg|All Files (*.*)|*.*||"; CFileDialog OpenDlg(TRUE, "打开图片", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strOpenFileType,NULL); if(OpenDlg.DoModal() == IDOK) { m_bAnalyseFinished = false; // 0314 AfxGetMainWnd()->SetWindowText(CString("精子检测系统_")+OpenDlg.GetFileName()); // 0314 bool bLoad = m_imgMorphaImg.Load(OpenDlg.GetPathName()); if(bLoad == false) { CString strMsg; strMsg.Format("Load Morpah Image %s Error",OpenDlg.GetPathName()); MessageBox(strMsg,"ERROR",MB_ICONERROR); return ; } CDC *pDC = GetDC(); m_imgMorphaImg.Show(pDC->m_hDC,0,0,m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); ReleaseDC(pDC); if(pView->m_pwndMorphaDetDlg->GetSafeHwnd()) { pView->m_pwndMorphaDetDlg->InitStr(); pView->m_pwndMorphaDetDlg->UpdateData(FALSE); pView->m_pwndMorphaDetDlg->clearworkspace(); pView->m_pwndMorphaDetDlg->Invalidate(); pView->m_pwndMorphaDetDlg->GetDlgItem(IDC_BUTTON_MORPHADETECT_FINISH)->EnableWindow(FALSE); } pView->m_pwndMorphaDetDlg->m_lsOperateIndex.clear(); pView->GetDlgItem(IDC_BUTTON_MORPHADETECT)->EnableWindow(TRUE); pView->GetDlgItem(IDC_BTN_LIVEDETECTED)->EnableWindow(FALSE); ++pView->m_pwndMorphaDetDlg->m_nVideoFiled; m_eViewShowMode = MORPHA_IMAGE; CSize sz(m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); SetScrollSizes(MM_TEXT,sz); Invalidate(); } } BOOL CSpermView::IsInRect(CPoint cen,int r,CPoint p) { if(p.x < cen.x+r && p.x >cen.x-r && p.y < cen.y+r && p.y >cen.y-r ) return TRUE; else return FALSE; } double CSpermView::dist(CPoint p, CPoint q) { float d = (p.x-q.x)*(p.x-q.x) + (p.y-q.y)*(p.y-q.y); return sqrt(d); } void CSpermView::DrawImage(CDC *pDC) { int i,n; CMainFrame* pMainfrm=(CMainFrame*)AfxGetMainWnd(); CMorphaDetectDLG* pWnd=(CMorphaDetectDLG*)((CView3*)pMainfrm->GetView3())->m_pwndMorphaDetDlg; if(pWnd==NULL || pWnd->m_hWnd == NULL) return; vector<SpermRegion>& m_vSpermRegion = pWnd->m_vSpermRegion; int& m_r=pWnd->m_nR; vector<IsSperNormal>& m_vbIsNormal=pWnd->m_vbIsNormal; vector<SperMopyParameter>& m_vSperMopyParameter=pWnd->m_vSperMopyParameter; LPBYTE& m_lpResBmDataSrc=pWnd->m_lpResBmDataSrc; LPBITMAPINFOHEADER& m_lpResBmInfoSrc= pWnd->m_lpResBmInfoSrc; LPBYTE& m_lpResEdgeBmDataSrc=pWnd->m_lpResEdgeBmDataSrc; LPBITMAPINFOHEADER& m_lpResEdgeBmInfoSrc= pWnd->m_lpResEdgeBmInfoSrc; switch(pWnd->m_wndCbxShowOpt.GetCurSel()) { case 2: // 画原图 m_imgMorphaImg.Show(pDC->m_hDC,0,0,m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); break; case 1: // 画填充图 if(m_lpResBmInfoSrc && m_lpResBmDataSrc) { ::StretchDIBits(pDC->GetSafeHdc(), 0,0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, m_lpResBmDataSrc, (LPBITMAPINFO)m_lpResBmInfoSrc, DIB_RGB_COLORS, SRCCOPY); } break; case 0: // 画边缘图 if(m_lpResEdgeBmDataSrc && m_lpResBmInfoSrc) { ::StretchDIBits(pDC->GetSafeHdc(), 0,0,m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, m_lpResEdgeBmDataSrc, (LPBITMAPINFO)m_lpResBmInfoSrc, DIB_RGB_COLORS, SRCCOPY); } break; } if(pWnd->m_wndChkRectangle.GetCheck()) { // 画边框 CPen myRedPen(PS_SOLID, 1, RGB(255,0,0)); CPen myBluePen(PS_SOLID, 1, RGB(0,0,255)); CPen *myPen, *pOldPen; n = m_vSpermRegion.size(); list<int>& m_lsOperateIndex = pWnd->m_lsOperateIndex; for(i=0; i<n; i++) { if(m_vbIsNormal[i].IsNormalVector[0] == TRUE) myPen = &myBluePen; else myPen = &myRedPen; pOldPen = pDC->SelectObject(myPen); // 选用红画笔 pDC->SelectObject(GetStockObject(NULL_BRUSH)); // 空白画刷 if( find(m_lsOperateIndex.begin(),pWnd->m_itListIndex,i ) != pWnd->m_itListIndex ) continue; CPoint lt = CPoint(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x - m_r); CPoint rt = CPoint(m_vSpermRegion[i].SpermCenterPos.y + m_r, m_vSpermRegion[i].SpermCenterPos.x - m_r); CPoint lb = CPoint(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r); CPoint rb = CPoint(m_vSpermRegion[i].SpermCenterPos.y + m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r); CRect rect = CRect(lt, rb); if( m_nPos == i) { pDC->SelectObject(pOldPen); COLORREF color; if(m_vbIsNormal[i].IsNormalVector[0] == TRUE) color = RGB(0,0,255); // 选用蓝画笔 else color = RGB(255,0,0); // 选用红画笔 CPen dotpen(PS_DASHDOT,1,color); pDC->SelectObject(&dotpen); pDC->Rectangle(rect); pDC->SelectObject(myPen); } else { pDC->Rectangle(rect); } } if(n>0) pDC->SelectObject(pOldPen); // 编号 { CPen myPen(PS_SOLID, 2, RGB(255,0,0)); CPen *pOldPen = pDC->SelectObject(&myPen); //选用新画笔 pDC->SetBkMode(TRANSPARENT); CString strNo, cs; n = m_vbIsNormal.size(); for(i=0; i<n; i++) { if( find(m_lsOperateIndex.begin(),pWnd->m_itListIndex,i) != pWnd->m_itListIndex ) continue; pDC->SetTextColor(RGB(0,0,255)); strNo.Format("%d", i+1); pDC->TextOut(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r - 15, strNo); if( m_vbIsNormal[i].IsNormalVector[0] == TRUE ) { pDC->SetTextColor(RGB(0,0,255)); cs = "正常"; } else { pDC->SetTextColor(RGB(255,0,0)); cs = "异常"; } pDC->TextOut(m_vSpermRegion[i].SpermCenterPos.y - m_r + 20, m_vSpermRegion[i].SpermCenterPos.x + m_r - 17, cs); } pDC->SelectObject(pOldPen); } } if(m_nPos != -1) { CString cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_length); pWnd->m_strLength = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_width); pWnd->m_strWidth = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_area); pWnd->m_strArea = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_perimeter); pWnd->m_strPerimeter = cs; cs.Format("%3.2lf", m_vSperMopyParameter[m_nPos].m_ellipticity); pWnd->m_strEllipticity = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_perfor_area); pWnd->m_strPerforArea = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_head_area); pWnd->m_strHeadArea = cs; cs.Format("%.1f", m_vSperMopyParameter[m_nPos].m_head_perfor_area*100); pWnd->m_strHeadPerforArea = cs + "%"; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_length); pWnd->m_strMitsomaLength = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_width); pWnd->m_strMitosomaWidth = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_angle); pWnd->m_strMitosmaDevangle = cs + "度"; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_ruga); pWnd->m_strRuga = cs; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_extension); pWnd->m_strExtension = cs; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_symmetry); pWnd->m_strSymmetry = cs; // 精子编号 cs.Format("第%d号精子 -->> ", m_nPos+1); pWnd->m_strInfo = cs; cs = ( (m_vbIsNormal[m_nPos].IsNormalVector[0] == TRUE ) ? "正常" : "异常"); pWnd->m_strIsNormal = cs; pWnd->UpdateData(FALSE); pWnd->Invalidate(); } } void CSpermView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); CSize sizeTotal; // TODO: calculate the total size of this view sizeTotal.cx = sizeTotal.cy = 100; SetScrollSizes(MM_TEXT, sizeTotal); } void CSpermView::OnButtonLeftarrow() { // TODO: Add your command handler code here CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView3= (CView3*)pMainFrm->GetView3(); CMorphaDetectDLG*& pMorphaDlg=pView3->m_pwndMorphaDetDlg; list<int>& m_lsOperateIndex=pView3->m_pwndMorphaDetDlg->m_lsOperateIndex; list<int>::iterator& m_itListIndex=pView3->m_pwndMorphaDetDlg->m_itListIndex; --m_itListIndex; pMorphaDlg->AddSperm(*m_itListIndex); pMorphaDlg->FormResultImage(); CString str; str.Format("目前一共检测了%d个视野,%d个精子,其中%d个正常,%d个异常.", pMorphaDlg->m_nVideoFiled,pMorphaDlg->m_MhNum.AbnormalSpermNum+pMorphaDlg->m_MhNum.NormalSpermNum, pMorphaDlg->m_MhNum.NormalSpermNum,pMorphaDlg->m_MhNum.AbnormalSpermNum); pMorphaDlg->GetDlgItem(IDC_DETECT_INFO)->SetWindowText(str); CPoint sp=GetScrollPosition(); CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); } void CSpermView::OnButtonRightarrow() { CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView3= (CView3*)pMainFrm->GetView3(); CMorphaDetectDLG*& pMorphaDlg=pView3->m_pwndMorphaDetDlg; list<int>& m_lsOperateIndex=pView3->m_pwndMorphaDetDlg->m_lsOperateIndex; list<int>::iterator& m_itListIndex=pView3->m_pwndMorphaDetDlg->m_itListIndex; pMorphaDlg->DeleteSperm(*m_itListIndex); ++m_itListIndex; pMorphaDlg->FormResultImage(); CString str; str.Format("目前一共检测了%d个视野,%d个精子,其中%d个正常,%d个异常.", pMorphaDlg->m_nVideoFiled,pMorphaDlg->m_MhNum.AbnormalSpermNum+pMorphaDlg->m_MhNum.NormalSpermNum, pMorphaDlg->m_MhNum.NormalSpermNum,pMorphaDlg->m_MhNum.AbnormalSpermNum); pMorphaDlg->GetDlgItem(IDC_DETECT_INFO)->SetWindowText(str); CPoint sp=GetScrollPosition(); CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); } void CSpermView::OnUpdateButtonLeftarrow(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here CMainFrame* pMainFrm = (CMainFrame*)AfxGetMainWnd(); CView3* pView3=(CView3*)pMainFrm->GetView3(); list<int>& m_lsOperateIndex=pView3->m_pwndMorphaDetDlg->m_lsOperateIndex; list<int>::iterator& m_itListIndex=pView3->m_pwndMorphaDetDlg->m_itListIndex; pCmdUI->Enable(m_itListIndex != m_lsOperateIndex.begin()); } void CSpermView::OnUpdateButtonRightarrow(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here CMainFrame* pMainFrm = (CMainFrame*)AfxGetMainWnd(); CView3* pView3=(CView3*)pMainFrm->GetView3(); list<int>& m_lsOperateIndex=pView3->m_pwndMorphaDetDlg->m_lsOperateIndex; list<int>::iterator& m_itListIndex=pView3->m_pwndMorphaDetDlg->m_itListIndex; pCmdUI->Enable(m_itListIndex != m_lsOperateIndex.end()); } void CSpermView::OnContextMenu(CWnd*, CPoint point) { // CG: This block was added by the Pop-up Menu component if(m_imgMorphaImg.GetImage() != NULL) { if (point.x == -1 && point.y == -1){ //keystroke invocation CRect rect; GetClientRect(rect); ClientToScreen(rect); point = rect.TopLeft(); point.Offset(5, 5); } int index=GetSpermIndex(point+GetScrollPosition()); if( index == -1 ) return; CPoint lpoint=point; ScreenToClient(&lpoint); DWORD dw=0; dw |= lpoint.x; dw |= (lpoint.y<<16); SendMessage(WM_LBUTTONDOWN,0,(LPARAM)dw); CMenu menu; menu.LoadMenu(CG_IDR_POPUP_SPERM_VIEW); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); CWnd* pWndPopupOwner = this; while (pWndPopupOwner->GetStyle() & WS_CHILD) pWndPopupOwner = pWndPopupOwner->GetParent(); pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner); } // // 活力的 if(theView3->m_pwndLiveDetectDlg->m_bIsUserState) { // 停止运动视频回放 CDC *pDC = GetDC(); CRect rc; GetClientRect(&rc); long cW = rc.Width(); long cH = rc.Height(); KillTimer(mMoveShowTimer); mFrm = 0; long nw = m_lpTrackResultBmInfo->biWidth; long nh = m_lpTrackResultBmInfo->biHeight; ::StretchDIBits(pDC->m_hDC, 0, 0, cW, cH, 0, 0, nw, nh, m_lpTrackResultBmData, (LPBITMAPINFO)(m_lpTrackResultBmInfo), DIB_RGB_COLORS, SRCCOPY); ReleaseDC(pDC); LPBYTE lpSrc = theView3->m_pwndLiveDetectDlg->m_lpBmData; LPBITMAPINFOHEADER lpInfo = theView3->m_pwndLiveDetectDlg->m_lpBmInfo; int width = lpInfo->biWidth; int height = lpInfo->biHeight; CPoint pt = point; ScreenToClient(&pt); mClick_pt = pt; pt.x *= width/double(cW); pt.y *= height/double(cH); pt.y = height - 1 - pt.y; m_pt = pt; CMenu menu; menu.LoadMenu(CG_IDR_POPUP_USERCHANGE); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); CWnd* pWndPopupOwner = this; while (pWndPopupOwner->GetStyle() & WS_CHILD) pWndPopupOwner = pWndPopupOwner->GetParent(); pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner); } // } void CSpermView::DrawMemDCImage(CDC *pDC1,const CRect rect) { CMemDC dc(pDC1,rect); CMemDC pDC=&dc; theView1 = this; CSpermDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here if(m_imgMorphaImg.GetImage()) { m_imgMorphaImg.Show(pDC->m_hDC,0,0,m_imgMorphaImg.Width(),m_imgMorphaImg.Height(),rect.left,rect.top); } if(m_bAnalyseFinished) // 形态学分析图 DrawMemResImg(pDC); } void CSpermView::DrawMemResImg(CDC *pDC) { int i,n; CMainFrame* pMainfrm=(CMainFrame*)AfxGetMainWnd(); CMorphaDetectDLG* pWnd=(CMorphaDetectDLG*)((CView3*)pMainfrm->GetView3())->m_pwndMorphaDetDlg; if(pWnd==NULL || pWnd->m_hWnd == NULL) return; vector<SpermRegion>& m_vSpermRegion = pWnd->m_vSpermRegion; vector<SperMopyParameter>&m_vSperMopyParameter=pWnd->m_vSperMopyParameter ; int& m_r=pWnd->m_nR; vector<IsSperNormal>& m_vbIsNormal=pWnd->m_vbIsNormal; LPBYTE& m_lpResBmDataSrc=pWnd->m_lpResBmDataSrc; LPBITMAPINFOHEADER& m_lpResBmInfoSrc= pWnd->m_lpResBmInfoSrc; LPBYTE& m_lpResEdgeBmDataSrc=pWnd->m_lpResEdgeBmDataSrc; LPBITMAPINFOHEADER& m_lpResEdgeBmInfoSrc= pWnd->m_lpResEdgeBmInfoSrc; switch(pWnd->m_wndCbxShowOpt.GetCurSel()) { case 2: // 画原图 m_imgMorphaImg.Show(pDC->m_hDC,0,0,m_imgMorphaImg.Width(),m_imgMorphaImg.Height()); break; case 1: // 画填充图 if(m_lpResBmInfoSrc && m_lpResBmDataSrc) { ::StretchDIBits(pDC->GetSafeHdc(), 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, m_lpResBmDataSrc, (LPBITMAPINFO)m_lpResBmInfoSrc, DIB_RGB_COLORS, SRCCOPY); } break; case 0: // 画边缘图 if(m_lpResEdgeBmDataSrc && m_lpResBmInfoSrc) { ::StretchDIBits(pDC->GetSafeHdc(), 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, 0, 0, m_lpResBmInfoSrc->biWidth, m_lpResBmInfoSrc->biHeight, m_lpResEdgeBmDataSrc, (LPBITMAPINFO)m_lpResBmInfoSrc, DIB_RGB_COLORS, SRCCOPY); } break; } n = m_vSpermRegion.size(); list<int>& m_lsOperateIndex = pWnd->m_lsOperateIndex; if(pWnd->m_wndChkRectangle.GetCheck()) { // 画边框 CPen myRedPen(PS_SOLID, 1, RGB(255,0,0)); CPen myBluePen(PS_SOLID, 1, RGB(0,0,255)); CPen *myPen, *pOldPen; for(i=0; i<n; i++) { if(m_vbIsNormal[i].IsNormalVector[0] == TRUE) myPen = &myBluePen; else myPen = &myRedPen; pOldPen = pDC->SelectObject(myPen); // 选用红画笔 pDC->SelectObject(GetStockObject(NULL_BRUSH)); // 空白画刷 if( find(m_lsOperateIndex.begin(),pWnd->m_itListIndex,i ) != pWnd->m_itListIndex ) continue; CPoint lt = CPoint(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x - m_r); CPoint rt = CPoint(m_vSpermRegion[i].SpermCenterPos.y + m_r, m_vSpermRegion[i].SpermCenterPos.x - m_r); CPoint lb = CPoint(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r); CPoint rb = CPoint(m_vSpermRegion[i].SpermCenterPos.y + m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r); CRect rect = CRect(lt, rb); if( m_nPos == i) { pDC->SelectObject(pOldPen); COLORREF color; if(m_vbIsNormal[i].IsNormalVector[0] == TRUE) color = RGB(0,0,255); // 选用蓝画笔 else color = RGB(255,0,0); // 选用红画笔 CPen dotpen(PS_DASHDOT,1,color); pDC->SelectObject(&dotpen); pDC->Rectangle(rect); pDC->SelectObject(myPen); } else { pDC->Rectangle(rect); } } pDC->SelectObject(pOldPen); // 编号 { CPen myPen(PS_SOLID, 2, RGB(255,0,0)); CPen *pOldPen = pDC->SelectObject(&myPen); //选用新画笔 pDC->SetBkMode(TRANSPARENT); CString strNo, cs; n = m_vbIsNormal.size(); for(i=0; i<n; i++) { if( find(m_lsOperateIndex.begin(),pWnd->m_itListIndex,i) != pWnd->m_itListIndex ) continue; pDC->SetTextColor(RGB(0,0,255)); strNo.Format("%d", i+1); pDC->TextOut(m_vSpermRegion[i].SpermCenterPos.y - m_r, m_vSpermRegion[i].SpermCenterPos.x + m_r - 15, strNo); if( m_vbIsNormal[i].IsNormalVector[0] == TRUE ) { pDC->SetTextColor(RGB(0,0,255)); cs = "正常"; } else { pDC->SetTextColor(RGB(255,0,0)); cs = "异常"; } pDC->TextOut(m_vSpermRegion[i].SpermCenterPos.y - m_r + 20, m_vSpermRegion[i].SpermCenterPos.x + m_r - 17, cs); } pDC->SelectObject(pOldPen); } } { CPen myPen(PS_SOLID, 2, RGB(255,0,0)); CPen *pOldPen = pDC->SelectObject(&myPen); //选用新画笔 pDC->SetBkMode(TRANSPARENT); CString strNo, cs; n = m_vbIsNormal.size(); for(i=0; i<n; i++) { if( find(m_lsOperateIndex.begin(),pWnd->m_itListIndex,i) != pWnd->m_itListIndex ) continue; if(m_nPos != -1) { CString cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_length); pWnd->m_strLength = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_width); pWnd->m_strWidth = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_area); pWnd->m_strArea = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_perimeter); pWnd->m_strPerimeter = cs; cs.Format("%3.2lf", m_vSperMopyParameter[m_nPos].m_ellipticity); pWnd->m_strEllipticity = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_perfor_area); pWnd->m_strPerforArea = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_head_area); pWnd->m_strHeadArea = cs; cs.Format("%.1lf", m_vSperMopyParameter[m_nPos].m_head_perfor_area*100); pWnd->m_strHeadPerforArea = cs + "%"; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_length); pWnd->m_strMitsomaLength = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_width); pWnd->m_strMitosomaWidth = cs; cs.Format("%.2lf", m_vSperMopyParameter[m_nPos].m_tail_angle); pWnd->m_strMitosmaDevangle = cs + "度"; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_ruga); pWnd->m_strRuga = cs; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_extension); pWnd->m_strExtension = cs; cs.Format("%.2f", m_vSperMopyParameter[m_nPos].m_symmetry); pWnd->m_strSymmetry = cs; // 精子编号 cs.Format("第%d号精子 -->> ", m_nPos+1); pWnd->m_strInfo = cs; cs = ( (m_vbIsNormal[m_nPos].IsNormalVector[0] == TRUE ) ? "正常" : "异常"); pWnd->m_strIsNormal = cs; pWnd->UpdateData(FALSE); pWnd->Invalidate(); } } pDC->SelectObject(pOldPen); } } void CSpermView::OnDeleteSperm() { CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView=(CView3*)pMainFrm->GetView3(); CMorphaDetectDLG* pWnd=(CMorphaDetectDLG*)pView->m_pwndMorphaDetDlg; pWnd->OnButtonDeletesperm(); } void CSpermView::OnMenuAddNormal2DB() { // TODO: Add your command handler code here theView3->m_pwndMorphaDetDlg->WriteMorphaSpermData( theView3->m_pwndMorphaDetDlg->m_nSelNO, true); } void CSpermView::OnMenuAddAbnormal2DB() { // TODO: Add your command handler code here theView3->m_pwndMorphaDetDlg->WriteMorphaSpermData( theView3->m_pwndMorphaDetDlg->m_nSelNO, false); } int CSpermView::GetSpermIndex(CPoint pt) { ScreenToClient(&pt); CMainFrame* pMainFrm=(CMainFrame*)AfxGetMainWnd(); CView3* pView=(CView3*)pMainFrm->GetView3(); CMorphaDetectDLG* pWnd=(CMorphaDetectDLG*)pView->m_pwndMorphaDetDlg; vector<SpermRegion>& m_vSpermRegion=pWnd->m_vSpermRegion; int i,iPos=-1; double d, min = 1<<20; CPoint p; for(i=0; i<m_vSpermRegion.size(); i++) { if( m_vSpermRegion[i].isDeleted == TRUE ) continue; p = CPoint(m_vSpermRegion[i].SpermCenterPos.y, m_vSpermRegion[i].SpermCenterPos.x); if( IsInRect(p, pWnd->m_nR, pt) ) { d = dist(p, pt); if(d < min ) { min = d; iPos = i; } } } pWnd->m_nSelNO = iPos; return iPos; } BOOL CSpermView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { // TODO: Add your message handler code here and/or call default CSize sz1=GetTotalSize(); CRect rect; GetClientRect(rect); CSize sz2(rect.Width(),rect.Height()); if(sz1.cy<sz2.cy) return CScrollView::OnMouseWheel(nFlags, zDelta, pt);; SCROLLINFO si; zDelta = -zDelta; GetScrollInfo(SB_VERT,&si); si.nPos += zDelta/12; SetScrollInfo(SB_VERT,&si); CPoint sp=GetScrollPosition(); CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); return CScrollView::OnMouseWheel(nFlags, zDelta, pt); } void CSpermView::UserShowSperm() { CPoint sp=GetScrollPosition(); CRect rc; GetClientRect(rc); CDC* pDC=GetDC(); rc.bottom+=sp.y; rc.right+=sp.x; pDC->SetViewportOrg(-sp); DrawMemDCImage(pDC,rc); ReleaseDC(pDC); } void CSpermView::OnSize(UINT nType, int cx, int cy) { CSize sz(100,100); SetScrollSizes(MM_TEXT,sz); CScrollView::OnSize(nType, cx, cy); } void CSpermView::GuoPing() { OnImage(); const int nChooseToAdjust = 0; // 选取第1帧做为调整图,和结果图 // ReadImageFromDisk(nChooseToAdjust, m_pFile); int nW = m_lpBMIH[nChooseToAdjust]->biWidth; int nH = m_lpBMIH[nChooseToAdjust]->biHeight; int nC = m_lpBMIH[nChooseToAdjust]->biBitCount/8; if( theView3->m_pwndLiveDetectDlg->m_lpBmInfo && theView3->m_pwndLiveDetectDlg->m_lpBmData ) { DeleteDIBImage(theView3->m_pwndLiveDetectDlg->m_lpBmInfo, theView3->m_pwndLiveDetectDlg->m_lpBmData); } NewDIBImage(theView3->m_pwndLiveDetectDlg->m_lpBmInfo, theView3->m_pwndLiveDetectDlg->m_lpBmData, nW, nH, nC); memcpy(theView3->m_pwndLiveDetectDlg->m_lpBmInfo, m_lpBMIH[nChooseToAdjust], sizeof(BITMAPINFOHEADER)); memcpy(theView3->m_pwndLiveDetectDlg->m_lpBmData, m_lpImage[nChooseToAdjust], theView3->m_pwndLiveDetectDlg->m_lpBmInfo->biSizeImage); if( theView3->m_pwndLiveDetectDlg->m_lpOringinImgHead && theView3->m_pwndLiveDetectDlg->m_lpOringinImgData ) { DeleteDIBImage(theView3->m_pwndLiveDetectDlg->m_lpOringinImgHead, theView3->m_pwndLiveDetectDlg->m_lpOringinImgData); } NewDIBImage(theView3->m_pwndLiveDetectDlg->m_lpOringinImgHead, theView3->m_pwndLiveDetectDlg->m_lpOringinImgData, nW, nH, nC); memcpy(theView3->m_pwndLiveDetectDlg->m_lpOringinImgHead, m_lpBMIH[nChooseToAdjust], sizeof(BITMAPINFOHEADER)); memcpy(theView3->m_pwndLiveDetectDlg->m_lpOringinImgData, m_lpImage[nChooseToAdjust], theView3->m_pwndLiveDetectDlg->m_lpBmInfo->biSizeImage); ::Rgb2Gray(theView3->m_pwndLiveDetectDlg->m_lpOringinImgHead, theView3->m_pwndLiveDetectDlg->m_lpOringinImgData); if( m_lpAdjustBmInfo && m_lpAdjustBmData ) DeleteDIBImage(m_lpAdjustBmInfo, m_lpAdjustBmData); NewDIBImage(m_lpAdjustBmInfo, m_lpAdjustBmData, nW, nH, nC); memcpy(m_lpAdjustBmInfo, m_lpBMIH[nChooseToAdjust], sizeof(BITMAPINFOHEADER)); memcpy(m_lpAdjustBmData, m_lpImage[nChooseToAdjust], m_lpBMIH[nChooseToAdjust]->biSizeImage); if( m_lpTrackResultBmInfo && m_lpTrackResultBmData ) DeleteDIBImage(m_lpTrackResultBmInfo, m_lpTrackResultBmData); NewDIBImage(m_lpTrackResultBmInfo, m_lpTrackResultBmData, nW, nH, nC); memcpy(m_lpTrackResultBmInfo, m_lpBMIH[nChooseToAdjust], sizeof(BITMAPINFOHEADER)); memcpy(m_lpTrackResultBmData, m_lpImage[nChooseToAdjust], m_lpBMIH[nChooseToAdjust]->biSizeImage); //{ 314 if(theView3->m_pwndLiveDetectDlg->m_iplBinaryImage != NULL) cvReleaseImage(&theView3->m_pwndLiveDetectDlg->m_iplBinaryImage); theView3->m_pwndLiveDetectDlg->m_iplBinaryImage = cvCreateImage(cvSize(m_lpBMIH[nChooseToAdjust]->biWidth,m_lpBMIH[nChooseToAdjust]->biHeight), 8,m_lpBMIH[nChooseToAdjust]->biBitCount/8); //} 314 theView3->m_pwndLiveDetectDlg->m_bIsVideoPlay = false; theView3->m_pwndLiveDetectDlg->m_bControlState = true; theView3->m_pwndLiveDetectDlg->m_bModeChange = false; theView3->m_pwndLiveDetectDlg->m_bAutoAnalyse = true; theView3->m_pwndLiveDetectDlg->m_bMoveShow = true; theView3->m_pwndLiveDetectDlg->OnUpdateButtonState(); if( theView3->m_pwndLiveDetectDlg->m_nHeight > 0 && theView3->m_pwndLiveDetectDlg->m_nWidth > 0 && theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry ) { for(int i=0; i<theView3->m_pwndLiveDetectDlg->m_nHeight; i++) { delete [](theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry[i]); theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry[i] = NULL; } delete [](theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry); theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry = NULL; } theView3->m_pwndLiveDetectDlg->m_nHeight = m_lpBMIH[nChooseToAdjust]->biHeight; theView3->m_pwndLiveDetectDlg->m_nWidth = m_lpBMIH[nChooseToAdjust]->biWidth; if(!theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry) { theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry = new bool*[theView3->m_pwndLiveDetectDlg->m_nHeight]; for(int i=0; i<theView3->m_pwndLiveDetectDlg->m_nHeight; i++) { theView3->m_pwndLiveDetectDlg->m_ppIVisitMarkAry[i] = new bool[theView3->m_pwndLiveDetectDlg->m_nWidth]; } } ::SendMessage(theView3->m_pwndLiveDetectDlg->GetSafeHwnd(), WM_HSCROLL, 0, (LPARAM)( theView3->m_pwndLiveDetectDlg->m_wndSliderGrayValue.GetSafeHwnd() ) ); } void CSpermView::OnSpermMorset() { // TODO: Add your command handler code here if(m_nPos == -1) return; CSpermMorphaSet dlg(m_nPos); dlg.DoModal(); Invalidate(); } void CSpermView::OnSpermNormal() { // TODO: Add your command handler code here if(m_nPos == -1) return; theView3->m_pwndMorphaDetDlg->m_vbIsNormal[m_nPos].IsNormalVector[0] = TRUE; Invalidate(); } void CSpermView::PreviewResult(int reprottype, CString detectno) { crxparm parm; parm.ipadd = TEXT( GetConnectIP() ); parm.database = TEXT("sperm"); parm.username = TEXT("sa"); parm.passwd = TEXT("sa"); CPrinteDlg cpld(reprottype,parm,detectno); cpld.DoModal(); } void CSpermView::OnUpdateFileOpenS(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here pCmdUI->Enable(m_bMenuItemFileOpen); } BOOL CSpermView::ReadImageFromDisk(int i, CFile *pFile) { CDib *pDib = new CDib(); BOOL ret = pDib->ReadDibFile(pFile); ::NewDIBImage(m_lpBMIH[i], m_lpImage[i], pDib->m_pInfoHeader->biWidth, pDib->m_pInfoHeader->biHeight, 4); memcpy(m_lpBMIH[i], pDib->m_pInfoHeader, sizeof(BITMAPINFOHEADER)); delete pDib, pDib = NULL; return ret; } BOOL CSpermView::WriteImageToDisk(int i, CFile *pFile) { CDib *pDib = new CDib(m_lpBMIH[i], m_lpImage[i]); BOOL ret = pDib->SaveDibFile(pFile); delete pDib, pDib = NULL; return ret; } void CSpermView::markTheNewSperm(const POINT& pt, COLORTYPE ct) { long h = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqInfo[0]->biHeight; long w = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqInfo[0]->biWidth; int parr[][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,-1}, {0,0}, {0,1}, {1,-1}, {1,0}, {1,1}, {-1,-2}, {0,-2}, {1,-2}, {-1,2}, {0,2}, {1,2}, {2,-1}, {2,0}, {2,1}, {-2,-1}, {-2,0}, {-2,1} }; vector<ColorPoint>vp; ColorPoint cp; int t=0; for (t=0; t<sizeof(parr)/sizeof(parr[0]); t++) { int x = pt.x + parr[t][0]; int y = pt.y + parr[t][1]; if( x>=0 && x<w && y>=0 && y<h ) { cp.pt.x = y; cp.pt.y = x; cp.ct = ct; vp.push_back(cp); } } theView3->m_pwndLiveDetectDlg->m_vp.push_back(vp); theView3->m_pwndLiveDetectDlg->FormTrackMap(); } void CSpermView::OnSpermAddA() { CLiveDetectDLG * pdlg = theView3->m_pwndLiveDetectDlg; pdlg->m_nAclass++; pdlg->GetSpermMoveParameter(); pdlg->ShowSpermLiveDetectedResult(); theView3->UpdateData(FALSE); markTheNewSperm(m_pt, REDT); CRect rc(mClick_pt.x-5, mClick_pt.y-5, mClick_pt.x+5, mClick_pt.y+5); InvalidateRect(&rc); } void CSpermView::OnSpermAddB() { CLiveDetectDLG * pdlg = theView3->m_pwndLiveDetectDlg; pdlg->m_nBclass++; pdlg->GetSpermMoveParameter(); pdlg->ShowSpermLiveDetectedResult(); theView3->UpdateData(FALSE); markTheNewSperm(m_pt, GREENT); CRect rc(mClick_pt.x-5, mClick_pt.y-5, mClick_pt.x+5, mClick_pt.y+5); InvalidateRect(&rc); } void CSpermView::OnSpermAddC() { CLiveDetectDLG * pdlg = theView3->m_pwndLiveDetectDlg; pdlg->m_nCclass++; pdlg->GetSpermMoveParameter(); pdlg->ShowSpermLiveDetectedResult(); theView3->UpdateData(FALSE); markTheNewSperm(m_pt, BLUET); CRect rc(mClick_pt.x-5, mClick_pt.y-5, mClick_pt.x+5, mClick_pt.y+5); InvalidateRect(&rc); } void CSpermView::OnSpermAddD() { CLiveDetectDLG * pdlg = theView3->m_pwndLiveDetectDlg; pdlg->m_nDclass++; pdlg->GetSpermMoveParameter(); pdlg->ShowSpermLiveDetectedResult(); theView3->UpdateData(FALSE); markTheNewSperm(m_pt, YELLOWT); CRect rc(mClick_pt.x-5, mClick_pt.y-5, mClick_pt.x+5, mClick_pt.y+5); InvalidateRect(&rc); } void CSpermView::OnSpermDel() { CLiveDetectDLG * pdlg = theView3->m_pwndLiveDetectDlg; int nDelNO = -1; int r, max_r = 3; int i=0, j=0; for(i=0; i<pdlg->m_vp.size(); i++) { for(j=0; j<pdlg->m_vp[i].size(); j++) { CPoint p(pdlg->m_vp[i][j].pt); swap(p.x, p.y); r = dist(p, m_pt) + 0.5; if( r < max_r ) { nDelNO = i; max_r = r; } } } if( nDelNO > 0 ) { switch(pdlg->m_vp[nDelNO][0].ct) { case REDT: pdlg->m_nAclass--; break; case GREENT: pdlg->m_nBclass--; break; case BLUET: pdlg->m_nCclass--; break; case YELLOWT: pdlg->m_nDclass--; break; default: break; } pdlg->GetSpermMoveParameter(); pdlg->ShowSpermLiveDetectedResult(); pdlg->m_vp[nDelNO].clear(); pdlg->FormTrackMap(); CRect rc(mClick_pt.x-50, mClick_pt.y-50, mClick_pt.x+50, mClick_pt.y+50); InvalidateRect(&rc); } } void CSpermView::OnTimer(UINT nIDEvent) { // TODO: Add your message handler code here and/or call default if( nIDEvent == mMoveShowTimer ) { CDC *pDC = GetDC(); CRect rc; GetClientRect(&rc); long cW = rc.Width(); long cH = rc.Height(); if( mFrm < FRAME_NUM-1 ) { mFrm++; } else { mFrm = 0; } LPBITMAPINFOHEADER lpInfo = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqInfo[mFrm]; LPBYTE lpData = theView3->m_pwndLiveDetectDlg->m_pMoveImgSeqData[mFrm]; long nw = lpInfo->biWidth; long nh = lpInfo->biHeight; ::StretchDIBits(pDC->m_hDC, 0, 0, cW, cH, 0, 0, nw, nh, lpData, (LPBITMAPINFO)(lpInfo), DIB_RGB_COLORS, SRCCOPY); ReleaseDC(pDC); } CScrollView::OnTimer(nIDEvent); }
[ "harithchen@e030fd90-5f31-5877-223c-63bd88aa7192" ]
[ [ [ 1, 1636 ] ] ]
2f5f333da1b527212826ce46a66b956565488539
95d583eacc45df62b6b6459e2ec79404686cb2b1
/source/lib/string_extended.cpp
d4e12769b82e3e3e9e54cdaa9826766f1842a5e5
[]
no_license
sebasrodriguez/teoconj
81a917c57724a718e6288798f7c58863a1dad523
aee99839a8ddb293b0ed1402dfe72b80dbfe0af0
refs/heads/master
2021-01-01T15:36:42.773692
2010-03-13T01:04:12
2010-03-13T01:04:12
32,334,661
0
0
null
null
null
null
UTF-8
C++
false
false
627
cpp
#include "string_extended.h" void strsplit(string str, char c, ListaString &l){ bool scanning = false; string buffer; int i = 0; while(str[i] != EOS){ if(str[i] == c){ if(scanning){ ListaStringInsBack(l, buffer); scanning = false; strdestruir(buffer); } }else{ if(!scanning){ strcrear(buffer); scanning = true; } straddchar(buffer, str[i]); } i ++; } if(scanning) ListaStringInsBack(l, buffer); }
[ "srpabliyo@861ad466-0edf-11df-a223-d798cd56f61e" ]
[ [ [ 1, 25 ] ] ]
1abd76c560e2ee2091b4c9fec1b59f82bbb1c424
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/tempomarker.h
01c70a40d9e50bd1958bd0aabc8c1e3562c3781c
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
9,422
h
///////////////////////////////////////////////////////////////////////////// // Name: tempomarker.h // Purpose: Stores and renders tempo markers // Author: Brad Larsen // Modified by: // Created: Jan 13, 2005 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifndef __TEMPOMARKER_H__ #define __TEMPOMARKER_H__ #include "systemsymbol.h" /// Stores and renders tempo markers class TempoMarker : public SystemSymbol { friend class TempoMarkerTestSuite; // Constants public: // Default constants static const wxChar* DEFAULT_DESCRIPTION; ///< Default value for the description member variable static const wxByte DEFAULT_BEAT_TYPE; ///< Default value for the beat type value static const wxUint32 DEFAULT_BEATS_PER_MINUTE; ///< Default value for the beats per minute value // Beats Per Minute Constants static const wxUint32 MIN_BEATS_PER_MINUTE; ///< Minimum allowed value for the beats per minute static const wxUint32 MAX_BEATS_PER_MINUTE; ///< Maximum allowed value for the beats per minute enum types { notShown = (wxByte)0x00, ///< Metronome marker is not shown standardMarker = (wxByte)0x01, ///< Standard beats per minute marker (i.e. quarter note = 120) listesso = (wxByte)0x02, ///< Listesso marker (i.e. quarter note = half note) alterationOfPace = (wxByte)0x03 ///< Alteration of pace (accel. or rit.) }; enum beatTypes { half = (wxByte)0x00, halfDotted = (wxByte)0x01, quarter = (wxByte)0x02, quarterDotted = (wxByte)0x03, eighth = (wxByte)0x04, eighthDotted = (wxByte)0x05, sixteenth = (wxByte)0x06, sixteenDotted = (wxByte)0x07, thirtySecond = (wxByte)0x08, thirtySecondDotted = (wxByte)0x09 }; enum tripletFeelTypes { noTripletFeel = (wxByte)0x00, tripletFeelEighth = (wxByte)0x01, tripletFeelSixteenth = (wxByte)0x02, tripletFeelEighthOff = (wxByte)0x03, tripletFeelSixteenthOff = (wxByte)0x04 }; enum flags { beatsPerMinuteMask = (wxUint32)0xffff, ///< Mask used to retrieve the beats per minute value tripletFeelTypeMask = (wxUint32)0x70000, ///< Mask used to retrieve the triplet feel type listessoBeatTypeMask = (wxUint32)0x780000, ///< Mask used to retrieve the listesso beat type beatTypeMask = (wxUint32)0x7800000, ///< Mask used to retrieve the beat type typeMask = (wxUint32)0x18000000 ///< Mask used to retrieve the tempo marker type }; // Member variables protected: wxString m_description; public: // Constructor/Destructor TempoMarker(); TempoMarker(wxUint32 system, wxUint32 position, wxByte beatType, wxUint32 beatsPerMinute, const wxChar* description, wxByte tripletFeelType); TempoMarker(wxUint32 system, wxUint32 position, wxByte beatType, wxByte listessoBeatType, const wxChar* description); TempoMarker(wxUint32 system, wxUint32 position, bool accelerando); TempoMarker(const TempoMarker& tempoMarker); ~TempoMarker(); // Creation Functions /// Creates an exact duplicate of the object /// @return The duplicate object PowerTabObject* CloneObject() const {return (new TempoMarker(*this));} // Operators const TempoMarker& operator=(const TempoMarker& tempoMarker); bool operator==(const TempoMarker& tempoMarker) const; bool operator!=(const TempoMarker& tempoMarker) const; // Serialize Functions protected: bool DoSerialize(PowerTabOutputStream& stream); bool DoDeserialize(PowerTabInputStream& stream, wxWord version); public: // MFC Class Functions /// Gets the MFC Class Name for the object /// @return The MFC Class Name wxString GetMFCClassName() const {return (wxT("CTempoMarker"));} /// Gets the MFC Class Schema for the object /// @return The MFC Class Schema wxWord GetMFCClassSchema() const {return ((wxWord)1);} // Type Functions /// Determines if a type is valid /// @param type Type to validate /// @return True if the type is valid, false if not static bool IsValidType(wxByte type) {return (type <= alterationOfPace);} bool SetType(wxByte type); wxByte GetType() const; /// Determines if the metronome marker is shown /// @return True if the metronome marker is shown, false if not bool IsMetronomeMarkerShown() const {return (GetType() != notShown);} // Standard Marker Functions bool SetStandardMarker(wxByte beatType, wxUint32 beatsPerMinute, const wxChar* description, wxByte tripletFeelType = noTripletFeel); /// Determines if the tempo marker is a standard marker /// @return True if the tempo marker is a standard marker, false if not bool IsStandardMarker() const {return (GetType() == standardMarker);} // Listesso Functions bool SetListesso(wxByte beatType, wxByte listessoBeatType, const wxChar* description = wxT("")); /// Determines if the tempo marker is a listesso /// @return True if the tempo marker is a listesso, false if not bool IsListesso() const {return (GetType() == listesso);} // Alteration Of Pace Functions /// Determines if the tempo marker is an alteration of pace /// @return True if the tempo marker is an alteration of pace, false if not bool IsAlterationOfPace() const {return (GetType() == alterationOfPace);} bool SetAlterationOfPace(bool accelerando); /// Determines if the tempo marker is an accelerando marker /// @return True if the tempo marker is an accelerando marker, false if not bool IsAccelerando() const {return ((IsAlterationOfPace()) && (GetBeatType() == 0));} /// Determines if the tempo marker is a ritardando marker /// @return True if the tempo marker is a ritardando marker, false if not bool IsRitardando() const {return ((IsAlterationOfPace()) && (GetBeatType() == 1));} // Beat Type Functions /// Determines if a beat type is valid /// @param beatType Beat type to validate /// @return True if the beat type is valid, false if not static bool IsValidBeatType(wxByte beatType) {return (beatType <= thirtySecondDotted);} bool SetBeatType(wxByte beatType); wxByte GetBeatType() const; // Listesso Beat Type Functions bool SetListessoBeatType(wxByte beatType); wxByte GetListessoBeatType() const; // Triplet Feel Functions /// Determines if a triplet feel type is valid /// @param tripletFeelType Triplet feel type to validate /// @return True if the triplet feel type is valid, false if not static bool IsValidTripletFeelType(wxByte tripletFeelType) {return (tripletFeelType <= tripletFeelSixteenthOff);} bool SetTripletFeelType(wxByte tripletFeelType); wxByte GetTripletFeelType() const; /// Determines if the tempo marker has a triplet feel effect /// @return True if the tempo marker has a triplet feel effect, false if not bool HasTripletFeel() const {return (GetTripletFeelType() != noTripletFeel);} // Beats Per Minute Functions /// Determines if a beats per minute value is valid /// @param beatsPerMinute Beats per minute value to validate /// @return True if the beats per minute value is valid, false if not static bool IsValidBeatsPerMinute(wxUint32 beatsPerMinute) {return ((beatsPerMinute >= MIN_BEATS_PER_MINUTE) && ((beatsPerMinute <= MAX_BEATS_PER_MINUTE)));} /// Sets the beats per minute /// @param beatsPerMinute Beats per minute value to set /// @return True if the beats per minute value was set, false if not bool SetBeatsPerMinute(wxUint32 beatsPerMinute); /// Gets the beats per minute /// @return The beats per minute wxUint32 GetBeatsPerMinute() const {return ((wxUint32)(m_data & beatsPerMinuteMask));} // Description Functions /// Sets the description /// @param description Description to set /// @return True if the description was set, false if not bool SetDescription(const wxChar* description) {wxCHECK(description != NULL, false); m_description = description; return (true);} /// Gets the description /// @return The description wxString GetDescription() const {return (m_description);} }; WX_DEFINE_POWERTABARRAY(TempoMarker*, TempoMarkerArray); #endif
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 211 ] ] ]
8c62f628f2f389148f2e5e6aa3c36f009a3fda44
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/QuestMgr.h
86582a9fca32a5c9254910936bb5184c634c2826
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
5,704
h
// Copyright (C) 2004 WoW Daemon // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef __QUESTMGR_H #define __QUESTMGR_H struct QuestRelation { Quest *qst; uint8 type; }; class Item; typedef std::list<QuestRelation *> QuestRelationList; class WOWD_SERVER_DECL QuestMgr : public Singleton < QuestMgr > { public: ~QuestMgr(); void AddQuest(Quest* quest) { m_quests[quest->id] = quest; } Quest* FindQuest(uint32 questid) { HM_NAMESPACE::hash_map<uint32, Quest*>::iterator itr = m_quests.find(questid); if(itr == m_quests.end()) return NULL; else return itr->second; } // Quest Loading bool LoadSQLQuests(); uint32 PlayerMeetsReqs(Player* plr, Quest* qst); uint32 CalcStatus(Object* quest_giver, Player* plr); uint32 CalcQuestStatus(Object* quest_giver, Player* plr, QuestRelation* qst); uint32 CalcQuestStatus(Object* quest_giver, Player* plr, Quest* qst, uint8 type); uint32 ActiveQuestsCount(Object* quest_giver, Player* plr); //Packet Forging... void BuildOfferReward(WorldPacket* data,Quest* qst, Object* qst_giver, uint32 menutype); void BuildQuestDetails(WorldPacket* data, Quest* qst, Object* qst_giver, uint32 menutype); void BuildRequestItems(WorldPacket* data, Quest* qst, Object* qst_giver, uint32 menutype); void BuildQuestComplete(WorldPacket* data, Quest* qst); void BuildQuestList(WorldPacket* data, Object* qst_giver, Player* plr); bool OnActivateQuestGiver(Object *qst_giver, Player *plr); void SendQuestUpdateAddKill(Player* plr, uint32 questid, uint32 entry, uint32 count, uint32 tcount, uint64 guid); void BuildQuestUpdateAddItem(WorldPacket* data, uint32 itemid, uint32 count); void BuildQuestUpdateComplete(WorldPacket* data, Quest* qst); void BuildQuestFailed(WorldPacket* data, uint32 questid); bool OnGameObjectActivate(Player *plr, GameObject *go); void OnPlayerKill(Player* plr, Creature* victim); void OnPlayerItemPickup(Player* plr, Item* item); void OnPlayerExploreArea(Player* plr, uint32 AreaID); void OnQuestFinished(Player* plr, Quest* qst, Object *qst_giver, uint32 reward_slot); uint32 GenerateQuestXP(Player *pl, Quest *qst); void SendQuestInvalid( INVALID_REASON reason, Player *plyr); void SendQuestFailed(FAILED_REASON failed, Player *plyr); void SendQuestUpdateFailed(Quest *pQuest, Player *plyr); void SendQuestUpdateFailedTimer(Quest *pQuest, Player *plyr); void SendQuestLogFull(Player *plyr); void LoadNPCQuests(Creature *qst_giver); void LoadGOQuests(GameObject *go); QuestRelationList* GetCreatureQuestList(uint32 entryid); QuestRelationList* GetGOQuestList(uint32 entryid); uint32 GetGameObjectLootQuest(uint32 GO_Entry); void SetGameObjectLootQuest(uint32 GO_Entry, uint32 Item_Entry); inline bool IsQuestRepeatable(Quest *qst) { return qst->is_repeatable; } inline int32 QuestHasMob(Quest* qst, uint32 mob) { for(uint32 i = 0; i < 4; ++i) if(qst->required_mob[i] == mob) return qst->required_mobcount[i]; return -1; } inline int32 GetOffsetForMob(Quest *qst, uint32 mob) { for(uint32 i = 0; i < 4; ++i) if(qst->required_mob[i] == mob) return i; return -1; } inline int32 GetOffsetForItem(Quest *qst, uint32 itm) { for(uint32 i = 0; i < 4; ++i) if(qst->required_item[i] == itm) return i; return -1; } inline HM_NAMESPACE::hash_map<uint32, Quest*>::iterator Begin() { return m_quests.begin(); } inline HM_NAMESPACE::hash_map<uint32, Quest*>::iterator End() { return m_quests.end(); } private: HM_NAMESPACE::hash_map<uint32, Quest*> m_quests; HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_npc_quests; HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_obj_quests; HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_itm_quests; HM_NAMESPACE::hash_map<uint32, uint32> m_ObjectLootQuestList; template <class T> void _AddQuest(uint32 entryid, Quest *qst, uint8 type); template <class T> HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& _GetList(); // Quest Loading void _RemoveChar(char* c, std::string *str); void _CleanLine(std::string *str); }; template<> inline HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<Creature>() {return m_npc_quests;} template<> inline HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<GameObject>() {return m_obj_quests;} template<> inline HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<Item>() {return m_itm_quests;} #define sQuestMgr QuestMgr::getSingleton() #endif
[ [ [ 1, 155 ] ] ]
8e4deb1555339b73d062dac6f162dd46069b3a5b
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/databaseserver/dpaccountclient.h
e50970f1d37551fc2eaadbfdbb4583627442f5b1
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,908
h
#ifndef __DPACCOUNTCLIENT_H__ #define __DPACCOUNTCLIENT_H__ #include "dpmng.h" #include "msghdr.h" #undef theClass #define theClass CDPAccountClient #undef theParameters #define theParameters CAr & ar, LPBYTE lpBuf, u_long uBufSize class CDPAccountClient : public CDPMng { public: /* #ifdef __S0114_RELOADPRO SET_STRING m_OutAccount_List; CTime m_tMemDelete; BOOL m_bMemDelete; #endif // __S0114_RELOADPRO */ // Constructions CDPAccountClient(); virtual ~CDPAccountClient(); // Overrides virtual void SysMessageHandler( LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID idFrom ); virtual void UserMessageHandler( LPDPMSG_GENERIC lpMsg, DWORD dwMsgSize, DPID idFrom ); // Operations void SendAddIdofServer( DWORD dwIdofServer ); void SendRemoveAccount( char* lpString ); void SendRemoveAllAccounts( void ); void SendBuyingInfo( PBUYING_INFO2 pbi2, SERIALNUMBER iSerialNumber ); #ifdef __SERVERLIST0911 void SendServerEnable( int nMulti, long lEnable ); #endif // __SERVERLIST0911 /* #ifdef __S0114_RELOADPRO void SendCompleteReloadProject(); void ReloadProject(); #endif // __S0114_RELOADPRO */ // Handlers USES_PFNENTRIES; void OnGetPlayerList( CAr & ar, LPBYTE, u_long ); #ifdef __REMOVE_PLAYER_0221 void OnRemovePlayer( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); #endif // __REMOVE_PLAYER_0221 void OnJoin( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); void OnPlayerCount( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); void OnCloseExistingConnection( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); void OnOneHourNotify( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); void OnFail( CAr & ar, LPBYTE, u_long ); void OnBuyingInfo( CAr & ar, LPBYTE lpBuf, u_long uBufSize ); // 2 /* #ifdef __S0114_RELOADPRO void OnReloadProject( CAr& ar, LPBYTE lpBuf, u_long uBufSize ); #endif // __S0114_RELOADPRO */ }; #endif // __DPACCOUNTCLIENT_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 61 ] ] ]
0ccc23db96e21c31be4b687d582f3a50c47ebd24
14f73382b96f592b53bf77ee8adc4948508a3edf
/src/re330/Node.h
aa621fd3a26fd67a71b83fcb7a7a91684c4c101d
[]
no_license
alawrenc/graphics-projects
2fb86312b13db1fb1d17f6e0c987fcc1af1568bb
d0e4fa974cb49c60ab2e6c11e1185adbea1a32cd
refs/heads/master
2021-01-18T07:58:40.639644
2010-05-12T00:37:19
2010-05-12T00:37:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
h
#ifndef __Node_h__ #define __Node_h__ #include "Matrix4.h" #include "Camera.h" #include "RenderContext.h" namespace RE330 { class Node { public: // initializes to identity matrix Node(): parent(NULL), localToWorldTransform(Matrix4::IDENTITY) {} ~Node(){ } Node * getParent() { return parent; } void setParent( Node * node) { parent = node; } virtual void draw(Matrix4 m, RenderContext& rc, Camera c) = 0; Matrix4 getLocalToWorldTransform() { return Matrix4(localToWorldTransform); } protected: Node * parent; Matrix4 localToWorldTransform; }; } #endif
[ [ [ 1, 3 ], [ 9, 9 ], [ 39, 41 ] ], [ [ 4, 8 ], [ 10, 38 ] ] ]
94ee805e32345d5f93fcaf5d2ca9bc4937398d2f
9f00cc73bdc643215425e6bc43ea9c6ef3094d39
/OOP/ex1/EmptyRectangle.cpp
08f79a4c574c53dd6164c11875b5d29c71d89226
[]
no_license
AndreyShamis/oopos
c0700e1d9d889655a52ad2bc58731934e968b1dd
0114233944c4724f242fd38ac443a925faf81762
refs/heads/master
2021-01-25T04:01:48.005423
2011-07-16T14:23:12
2011-07-16T14:23:12
32,789,875
0
0
null
null
null
null
UTF-8
C++
false
false
1,241
cpp
// // @ Project : Paint // @ File Name : Empty Rectanle.cpp // @ Date : 3/3/2011 // @ Author : Andrey Shamis Ilia Gaysinski // @ Description : A class that reprisen "EmptyRectangle" shape at glut window // #include "EmptyRectangle.h" //============================================================================= // Constractor of class EmptyRectangle, get color and coordinat of start // point to creat the shape. EmptyRectangle::EmptyRectangle(float x, float y,const RgbColor &color) { // set coordinats of shape _x = x; _y = y; _size = DEFAULT_SIZE_SH; // set default side size of shape _color = color; // set color of shape } //============================================================================= // implementation of virtual function that drow the shape at glut window // get nothing // return nothing void EmptyRectangle::Draw() { glBegin(GL_LINE_LOOP); // Start drawing a Empty Rectanglle glColor3f(_color.r, _color.g, _color.b);// Set color of shape // set points of shape glVertex2f (_x, _y); glVertex2f (_x, _y - _size); glVertex2f (_x + (_size * 2), _y - _size); glVertex2f (_x + (_size * 2), _y); glEnd(); // End of drawing a vertical }
[ "[email protected]@c8aee422-7d7c-7b79-c2f1-0e09d0793d10" ]
[ [ [ 1, 38 ] ] ]
d14948fc5d77c4e94b37ab7cb5bd6ace383746c1
7a6f06d37d3a1cf37532fb12935031e558b8a6ce
/patch/source/Irrlicht/PhXSceneGlobalNode.h
250155d0973b227d689c87d4444d2edfbb7c2908
[]
no_license
pecc0/phx-irrlicht
8ab7192e2604f3d1f7f4dc45a86118d162574a69
d1009e6e46e2056fb1e046855c95ab39b2bb3fba
refs/heads/master
2016-09-05T19:00:20.648062
2011-01-19T22:02:51
2011-01-19T22:02:51
32,383,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
h
/* AUTORIGHTS Copyright (C) 2010,2011 Petko Petkov ([email protected]) This file is part of JWorld. JWorld 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #pragma once #include "ISceneNode.h" namespace irr { namespace scene { class CPhXSceneGlobalNode : public ISceneNode { public: CPhXSceneGlobalNode(ISceneNode* parent, ISceneManager* mgr, core::aabbox3d<f32> bounds = core::aabbox3d<f32>( core::vector3d<f32>(-1000,-1000,-1000), core::vector3d<f32>(1000,1000,1000))); virtual ~CPhXSceneGlobalNode(void); virtual void render(){}; virtual const core::aabbox3d<f32>& getBoundingBox() const; virtual void OnAnimate(u32 timeMs); protected: core::aabbox3d<f32> boundings; }; } }
[ "petkodp@8db76cfa-2e72-11de-afe2-b5feb05456f9", "[email protected]@8db76cfa-2e72-11de-afe2-b5feb05456f9" ]
[ [ [ 1, 19 ] ], [ [ 20, 46 ] ] ]
a61ae4827a740ee726dc58b5b8b586942a8bf3d7
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
/Exercises/OpenGL6/DDEngine/linearAlgebra.cpp
ff9143234e8d3123c1841ed65a4bf6d18a2aa0df
[]
no_license
giacomof/gameengines2010itu
8407be66d1aff07866d3574a03804f2f5bcdfab1
bc664529a429394fe5743d5a76a3d3bf5395546b
refs/heads/master
2016-09-06T05:02:13.209432
2010-12-12T22:18:19
2010-12-12T22:18:19
35,165,366
0
0
null
null
null
null
UTF-8
C++
false
false
27,270
cpp
#define _USE_MATH_DEFINES #include "linearAlgebra.h" using namespace std; static const float PI = 3.14159f; static const int parallelThreads = 2; // Constructor for vectors without parameter Vector::Vector(void) { // Resize the variable to the right size and set the fourth coordinate to 0 since it is a vector. for(unsigned short i = 0; i < 3; i++) { data[i] = 0; } data[3] = 0; } // Constructor for vectors with parameters Vector::Vector(float x, float y, float z) { // Fill in the parameters data[0] = x; data[1] = y; data[2] = z; data[3] = 0; } // Function to calculate the magnitude of a vector float Vector::getMagnitude(void) { float magnitude = (*this) * (*this); magnitude = sqrt(magnitude); // Return the result return magnitude; } // Returns the quadratic magnitude float Vector::getQuadraticMagnitude(void) { return (*this) * (*this); } // Function to normalize the vector Vector Vector::normalize(void) { // Create a new vector to store the results Vector result = Vector(); // Calculate the magnitude of the vector float magnitude = this->getMagnitude(); // If the vector has magnitude = 0, then return an empty vector if (magnitude == 0) { result.set(0, 0); result.set(1, 0); result.set(2, 0); // If the vector magnitude is 1, then it is already normalized } else if (magnitude == 1) { result.set(0, this->get(0)); result.set(1, this->get(1)); result.set(2, this->get(2)); // else, normalize the vector } else { result.set(0, this->get(0) / magnitude); result.set(1, this->get(1) / magnitude); result.set(2, this->get(2) / magnitude); } // Return the result return result; } // Operator overload for the + sign Vector Vector::operator+(Vector &other) { // Create a new vector to store the results Vector result = Vector(); // Calculate the result result.set(0, this->get(0) + other.get(0) ); result.set(1, this->get(1) + other.get(1) ); result.set(2, this->get(2) + other.get(2) ); // If was a sum between a point and a vector // the result will be a point if ((data[3] == 1) || (other.get(3) == 1)) { result.set(3, 1); } return result; } // Operator overload for the - sign between two vectors Vector Vector::operator-(Vector &other) { // Create a new vector to store the results Vector result = Vector(); // Calculate the result result.set(0, this->get(0) - other.get(0) ); result.set(1, this->get(1) - other.get(1) ); result.set(2, this->get(2) - other.get(2) ); // Return it return result; } // Operator overload for the * sign between two vectors float Vector::operator*(Vector &other) { // Create a new float to store the result float result; // Calculate the result result = (data[0] * other.data[0] + data[1] * other.data[1] + data[2] * other.data[2]); // Return the Dot product return result; } // Operator overload for the * sign between a vector and a float Vector Vector::operator*(float s) { Vector result = Vector(); // Scale the the vector result.set(0, data[0] * s); result.set(1, data[1] * s); result.set(2, data[2] * s); return result; } // Vector cross product Vector Vector::operator%(Vector &other) { Vector result = Vector(); // Scale the the vector result.set(0, data[1] * other.data[2] - data[2] * other.data[1]); result.set(1, -data[0] * other.data[2] - data[2] * other.data[0]); result.set(2, data[0] * other.data[1] - data[1] * other.data[0]); return result; } // Operator Overload for vector comparison bool Vector::operator==(Vector &other) { bool equal = true; for (unsigned short i = 0; i < 4; i++) { if (data[i] != other.data[i]) { equal = false; } } return equal; } // Operator overload for the [] symbols (Vector[0] returns the content of data[0]) float Vector::operator[](unsigned short i) { // Access the internal stl vector in the same place as the class vector was accessed and return the content return data[i]; } // Operator overload for << for sending a vector to the output stream std::ostream & operator<< (std::ostream &os, const Vector &v) { // Add to the output stream in the following format: "{x,y,z}" os << "{" << v.get(0) << "," << v.get(1) << "," << v.get(2)<< "," << v.get(3) << "}"; // Return the stream return os; } // Constructor for points without parameters Point::Point(void) { // This constructor is called identically to the vector constructor. The fourth coordinate is 1 because we're dealing with a point for(unsigned short i = 0; i < 3; i++) { data[i] = 0; } data[3] = 1; } // Constructor for points with parameters Point::Point(float x, float y, float z) { // Fill in the parameters data[0] = x; data[1] = y; data[2] = z; data[3] = 1; } // Operator overload for the * sign between a point and a float Point Point::operator*(float s) { Point result = Point(); // Scale the the vector result.set(0, data[0] * s); result.set(1, data[1] * s); result.set(2, data[2] * s); return result; } // Operator overload for the + sign Point Point::operator+(Point &other) { // Create a new vector to store the results Point result = Point(); // Calculate the result result.set(0, this->get(0) + other.get(0) ); result.set(1, this->get(1) + other.get(1) ); result.set(2, this->get(2) + other.get(2) ); result.set(3, 1); return result; } // Constructor for quaternions without parameter Quaternion::Quaternion(void) { vector = Vector(); w = 0; } // Constructor for quaternions from a vector and an angle in rad Quaternion::Quaternion(Vector axis, float degree) { float sinAngle; degree *= 0.5f; Vector vn = axis.normalize(); sinAngle = sin(degree*PI/180); vn = vn * sinAngle; for (unsigned short i = 0; i < 3; i++) { vector.set(i, vn.get(i)); } w = cos(degree*PI/180); } Quaternion::Quaternion(float p_x, float p_y, float p_z, float p_w) { vector.setX(p_x); vector.setY(p_y); vector.setZ(p_z); w = p_w; } // Operator overload for sum between quaternions Quaternion Quaternion::operator+(Quaternion &other) { Vector resultVector = Vector(this->getVector() + other.getVector()); float resultDegree = this->getW() + other.getW(); Quaternion resultQuaternion = Quaternion(); resultQuaternion.vector = resultVector; resultQuaternion.w = resultDegree; return resultQuaternion; } // Operator overload for multiplication between quaternions Quaternion Quaternion::operator*(Quaternion &other) { Vector resultVector = Vector(); resultVector.setX(w * other.vector.getX() + vector.getX() * other.w + vector.getY() * other.vector.getZ() - vector.getZ() * other.vector.getY()); resultVector.setY(w * other.vector.getY() + vector.getY() * other.w + vector.getZ() * other.vector.getX() - vector.getX() * other.vector.getZ()); resultVector.setZ(w * other.vector.getZ() + vector.getZ() * other.w + vector.getX() * other.vector.getY() - vector.getY() * other.vector.getX()); float resultW = w * other.w - vector.getX() * other.vector.getX() - vector.getY() * other.vector.getY() - vector.getZ() * other.vector.getZ(); Quaternion resultQuaternion = Quaternion(); resultQuaternion.vector = resultVector; resultQuaternion.w = resultW; return resultQuaternion; } // Operator overload for multiplication between quaternions and vectors Vector Quaternion::operator*(Vector &other) { Vector temp = other.normalize(); Quaternion vectorQuaternion = Quaternion(); Quaternion multiplicationQuaternion = Quaternion(); Vector result = Vector(); vectorQuaternion.setX(this->getX()); vectorQuaternion.setY(this->getY()); vectorQuaternion.setZ(this->getZ()); multiplicationQuaternion = vectorQuaternion * this->getConjugate(); multiplicationQuaternion = *this * multiplicationQuaternion; result.setX(multiplicationQuaternion.getX()); result.setY(multiplicationQuaternion.getY()); result.setZ(multiplicationQuaternion.getZ()); return result; } // Quaternion comparison bool Quaternion::operator==(Quaternion &other) { bool equal; if ((vector == other.getVector()) && (w == other.getW())) { equal = true; } else { equal = false; } return equal; } // Quaternion magnitude calculation float Quaternion::getMagnitude(void) { float magnitude = vector.getQuadraticMagnitude() + w*w; magnitude = sqrt(magnitude); return magnitude; } // Quaternion normalization Quaternion Quaternion::normalize(void) { Quaternion result = Quaternion(); float magnitude = this->getMagnitude(); result.setX(vector.getX() / magnitude); result.setY(vector.getY() / magnitude); result.setZ(vector.getZ() / magnitude); result.setW(w / magnitude); return result; } // Quaternion conjugate calculation Quaternion Quaternion::getConjugate(void) { Quaternion result = Quaternion(); result.setX(-this->getVector().getX()); result.setY(-this->getVector().getY()); result.setZ(-this->getVector().getZ()); result.setW(this->getW()); return result; } //Function for getting members of quaternion Vector Quaternion::getVector(void) { return vector; } float Quaternion::getW(void) { return w; } // Function for getting axis and angle from quaternion void Quaternion::getAxisAngle(Vector *axis, float *angle) { float magnitude = vector.getMagnitude(); axis->set(0, vector.get(0) / magnitude); axis->set(1, vector.get(1) / magnitude); axis->set(2, vector.get(2) / magnitude); *angle = (acos(w) * 2.0f)*180/PI; } void Quaternion::setX(float value) { vector.setX(value); } void Quaternion::setY(float value) { vector.setY(value); } void Quaternion::setZ(float value) { vector.setZ(value); } void Quaternion::setW(float value) { w = value; } // Function to output quaternions std::ostream & operator<< (std::ostream &os, const Quaternion &q) { // I add to the output stream in the following format: "{x,y,z}" os << "{(" << q.vector.get(0) << "," << q.vector.get(1) << "," << q.vector.get(2)<< ")," << q.w << "}"; // I return the stream return os; } // Constructor for matrices without parameters Matrix::Matrix(void) { } // Constructor for matrices with parameters Matrix::Matrix(float a00, float a01, float a02, float a03, float a10, float a11, float a12, float a13, float a20, float a21, float a22, float a23, float a30, float a31, float a32, float a33) { data[0] = a00; data[1] = a01; data[2] = a02; data[3] = a03; data[4] = a10; data[5] = a11; data[6] = a12; data[7] = a13; data[8] = a20; data[9] = a21; data[10] = a22; data[11] = a23; data[12] = a30; data[13] = a31; data[14] = a32; data[15] = a33; } // Constructor for matrices from an array of float Matrix::Matrix(float * values) { for(unsigned short i=0; i<16; i++) { data[i]=values[i]; } } // Generate the identity matrix Matrix Matrix::generateIdentityMatrix(void) { Matrix result; result.set(0,0,1); result.set(0,1,0); result.set(0,2,0); result.set(0,3,0); result.set(1,0,0); result.set(1,1,1); result.set(1,2,0); result.set(1,3,0); result.set(2,0,0); result.set(2,1,0); result.set(2,2,1); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a translation matrix from three float values Matrix Matrix::generateTranslationMatrix(float tX, float tY, float tZ) { Matrix result = Matrix(); result.set(0,0,1); result.set(0,1,0); result.set(0,2,0); result.set(0,3,tX); result.set(1,0,0); result.set(1,1,1); result.set(1,2,0); result.set(1,3,tY); result.set(2,0,0); result.set(2,1,0); result.set(2,2,1); result.set(2,3,tZ); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a scaling matrix from three float values Matrix Matrix::generateScalingMatrix(float sX, float sY, float sZ) { Matrix result = Matrix(); result.set(0,0,sX); result.set(0,1,0); result.set(0,2,0); result.set(0,3,0); result.set(1,0,0); result.set(1,1,sY); result.set(1,2,0); result.set(1,3,0); result.set(2,0,0); result.set(2,1,0); result.set(2,2,sZ); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a uniform scaling matrix from a float value Matrix Matrix::generateUniformScalingMatrix(float s) { Matrix result = Matrix(); result.set(0,0,s); result.set(0,1,0); result.set(0,2,0); result.set(0,3,0); result.set(1,0,0); result.set(1,1,s); result.set(1,2,0); result.set(1,3,0); result.set(2,0,0); result.set(2,1,0); result.set(2,2,s); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a rotation matrix about x-axes, from a float value Matrix Matrix::generateXRotationMatrix(float degree) { Matrix result = Matrix(); float sincos[2]; sincos[0] = sin(degree*PI/180); sincos[1] = cos(degree*PI/180); result.set(0,0,1); result.set(0,1,0); result.set(0,2,0); result.set(0,3,0); result.set(1,0,0); result.set(1,1,sincos[1]); result.set(1,2,-sincos[0]); result.set(1,3,0); result.set(2,0,0); result.set(2,1,sincos[0]); result.set(2,2,sincos[1]); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a rotation matrix about y-axes, from a float value Matrix Matrix::generateYRotationMatrix(float degree) { Matrix result = Matrix(); float sincos[2]; sincos[0] = sin(degree*PI/180); sincos[1] = cos(degree*PI/180); result.set(0,0,sincos[1]); result.set(0,1,0); result.set(0,2,sincos[0]); result.set(0,3,0); result.set(1,0,0); result.set(1,1,1); result.set(1,2,0); result.set(1,3,0); result.set(2,0,-sincos[0]); result.set(2,1,0); result.set(2,2,sincos[1]); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a rotation matrix about z-axes, from a float value Matrix Matrix::generateZRotationMatrix(float degree) { Matrix result = Matrix(); float sincos[2]; sincos[0] = sin(degree*PI/180); sincos[1] = cos(degree*PI/180); result.set(0,0,sincos[1]); result.set(0,1,-sincos[0]); result.set(0,2,0); result.set(0,3,0); result.set(1,0,sincos[0]); result.set(1,1,sincos[1]); result.set(1,2,0); result.set(1,3,0); result.set(2,0,0); result.set(2,1,0); result.set(2,2,1); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a rotation matrix about an arbitrary axes, from a Vector and a float Matrix Matrix::generateAxisRotationMatrix(Vector axis, float degree) { Matrix result = Matrix(); float sincos[2]; float k; sincos[0] = sin(degree*PI/180); sincos[1] = cos(degree*PI/180); k = 1-sincos[1]; result.set(0,0,(axis.get(0)*axis.get(0)*k)+sincos[1]); result.set(0,1,(axis.get(0)*axis.get(1)*k)-(axis.get(2)*sincos[0])); result.set(0,2,(axis.get(0)*axis.get(2)*k)+(axis.get(1)*sincos[0])); result.set(0,3,0); result.set(1,0,(axis.get(0)*axis.get(1)*k)+(axis.get(2)*sincos[0])); result.set(1,1,(axis.get(1)*axis.get(1)*k)+sincos[1]); result.set(1,2,(axis.get(1)*axis.get(2)*k)-(axis.get(0)*sincos[0])); result.set(1,3,0); result.set(2,0,(axis.get(0)*axis.get(1)*k)-(axis.get(1)*sincos[0])); result.set(2,1,(axis.get(1)*axis.get(2)*k)+(axis.get(0)*sincos[0])); result.set(2,2,(axis.get(2)*axis.get(2)*k)+sincos[1]); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a rotation matrix from a quaternion Matrix Matrix::generateQuaternionRotationMatrix(Quaternion q) { float x2 = q.getVector().getX() * q.getVector().getX(); float y2 = q.getVector().getY() * q.getVector().getY(); float z2 = q.getVector().getZ() * q.getVector().getZ(); float xy = q.getVector().getX() * q.getVector().getY(); float xz = q.getVector().getX() * q.getVector().getZ(); float yz = q.getVector().getY() * q.getVector().getZ(); float dx = q.getW() * q.getVector().getX(); float dy = q.getW() * q.getVector().getY(); float dz = q.getW() * q.getVector().getZ(); Matrix result = Matrix(); result.set(0,0,(1.0f - 2.0f * (y2 + z2))); result.set(0,1,(2.0f * (xy - dz))); result.set(0,2,(2.0f * (xz + dy))); result.set(0,3,0); result.set(1,0,(2.0f * (xy + dz))); result.set(1,1,(1.0f - 2.0f * (x2 + z2))); result.set(1,2,(2.0f * (yz - dx))); result.set(1,3,0); result.set(2,0,(2.0f * (xz - dy))); result.set(2,1,(2.0f * (yz + dx))); result.set(2,2,(1.0f - 2.0f * (x2 + y2))); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Generate a shearing matrix from six float values Matrix Matrix::generateShearingMatrix(float sXY,float sXZ,float sYX,float sYZ,float sZX,float sZY) { Matrix result = Matrix(); result.set(0,0,1); result.set(0,1,sXY); result.set(0,2,sXZ); result.set(0,3,0); result.set(1,0,sYX); result.set(1,1,1); result.set(1,2,sYZ); result.set(1,3,0); result.set(2,0,sZX); result.set(2,1,sZY); result.set(2,2,1); result.set(2,3,0); result.set(3,0,0); result.set(3,1,0); result.set(3,2,0); result.set(3,3,1); return result; } // Function for returning the quaternion from a matrix Quaternion Matrix::getQuaternion(Matrix &mat) { Quaternion result = Quaternion(); float s; float t = 1 + mat.get(0) + mat.get(5) + mat.get(10); if (t > 0) { s = sqrt(t) * 2; result.setX((mat.get(9) - mat.get(6)) / s); result.setY((mat.get(2) - mat.get(8)) / s); result.setZ((mat.get(4) - mat.get(1)) / s); result.setW(0.25 * s); return result; } if ( mat.get(0) > mat.get(5) && mat.get(0) > mat.get(10)) { s = sqrt( 1.0 + mat.get(0) - mat.get(5) - mat.get(10)) * 2; result.setX(0.25 * s); result.setY((mat.get(4) + mat.get(1)) / s); result.setZ((mat.get(2) + mat.get(8)) / s); result.setW((mat.get(9) - mat.get(6)) / s); return result; } else if ( mat.get(5) > mat.get(10)) { s = sqrt( 1.0 + mat.get(5) - mat.get(0) - mat.get(10) ) * 2; result.setX((mat.get(4) + mat.get(1)) / s); result.setY(0.25 * s); result.setZ((mat.get(9) + mat.get(6)) / s); result.setW((mat.get(2) - mat.get(8)) / s); return result; } else { s = sqrt( 1.0 + mat.get(10) - mat.get(0) - mat.get(5)) * 2; result.setX((mat.get(2) + mat.get(8)) / s); result.setY((mat.get(9) + mat.get(6)) / s); result.setZ(0.25 * s); result.setW((mat.get(4) - mat.get(1)) / s); return result; } } // Operator overload for the * sign between two matrices Matrix Matrix::operator*(Matrix &other) { Matrix result = Matrix(); // This set of loops will go though each field in the result matrix, // then calculate using another loop to resuse code for each multiplication // between elements r is row, c is column, i is row for one element // of a multiplication and column for the other element of the same multiplication omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int c = 0; c < 4; c++) for (unsigned short r = 0; r < 4; r++) { float temp = 0; for (unsigned short i = 0; i < 4; i++) { temp = temp + this->get(r,i) * other.get(i,c); } result.set(r,c, temp); } return result; } // Operator overload for the * sign between a matrix and a scalar Matrix Matrix::operator*(float other) { Matrix result = Matrix(); omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int r = 0; r < 4; r++) for (unsigned short c = 0; c < 4; c++) { result.set(r,c, data[4*r + c]*other); } return result; } // Operator overload for the * sign between a matrix and a vector Vector Matrix::operator*(Vector &other) { Vector result = Vector(); // This reuses the code from the matrix * matrix overload. Here I have removed the column loop since a vector only has one omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int r = 0; r < 3; r++) { float temp = 0; for (unsigned short i = 0; i < 4; i++) { temp = temp + this->get(r,i) * other.get(i); } result.set(r, temp); } result.set(3, other.get(3)); return result; } // Operator overload for the * sign between a matrix and a vector Point Matrix::operator*(Point &other) { Point result = Point(); // This reuses the code from the matrix * matrix overload. Here I have removed the column loop since a vector only has one omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int r = 0; r < 3; r++) { float temp = 0; for (unsigned short i = 0; i < 4; i++) { temp = temp + this->get(r,i) * other.get(i); } result.set(r, temp); } result.set(3, other.get(3)); return result; } // Operator overload for matrix comparison bool Matrix::operator==(Matrix &other) { bool equal = true; omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int r = 0; r < 4; r++) { for (unsigned short c = 0; c < 4; c++) { if(data[r*4 + c] != other.get(r, c)) { equal = false; } } } return equal; } // Function for the transpose matrix Matrix Matrix::getTranspose() { // Result matrix Matrix result = Matrix(); // Inversion of row and columns omp_set_num_threads(parallelThreads); #pragma omp parallel for for (int r = 0; r < 4; r++) { for (unsigned int c = 0; c < 4; c++) { result.set(c,r,this->get(r,c)); } } return result; } // Calculate the inverse of a 4x4 matrix with Laplace expansion algorithm // if the determinant is != 0, otherwise return the identity matrix Matrix Matrix::getInverse() { Matrix result = Matrix(); float temp0 = data[0]*data[5] - data[1]*data[4]; float temp1 = data[0]*data[6] - data[2]*data[4]; float temp2 = data[0]*data[7] - data[3]*data[4]; float temp3 = data[1]*data[6] - data[2]*data[5]; float temp4 = data[1]*data[7] - data[3]*data[5]; float temp5 = data[2]*data[7] - data[3]*data[6]; float temp6 = data[8]*data[13] - data[9]*data[12]; float temp7 = data[8]*data[14] - data[10]*data[12]; float temp8 = data[8]*data[15] - data[11]*data[12]; float temp9 = data[9]*data[14] - data[10]*data[13]; float temp10 = data[9]*data[15] - data[11]*data[13]; float temp11 = data[10]*data[15] - data[11]*data[14]; float determinant = temp0*temp11 - temp1*temp10 + temp2*temp9 + temp3*temp8 - temp4*temp7 + temp5*temp6; if (determinant != 0) { result.set(0,0,data[5]*temp11-data[6]*temp10+data[7]*temp9); result.set(0,1,-data[1]*temp11+data[2]*temp10-data[3]*temp9); result.set(0,2,data[13]*temp5-data[14]*temp4+data[15]*temp3); result.set(0,3,-data[9]*temp5+data[10]*temp4-data[11]*temp3); result.set(1,0,-data[4]*temp11+data[6]*temp8-data[7]*temp7); result.set(1,1,data[0]*temp11-data[2]*temp8+data[3]*temp7); result.set(1,2,-data[12]*temp5+data[14]*temp2-data[15]*temp1); result.set(1,3,data[8]*temp5-data[10]*temp2+data[11]*temp1); result.set(2,0,data[4]*temp10-data[5]*temp8+data[7]*temp6); result.set(2,1,-data[0]*temp10+data[1]*temp8-data[3]*temp6); result.set(2,2,data[12]*temp4-data[13]*temp2+data[15]*temp0); result.set(2,3,-data[8]*temp4+data[9]*temp2-data[11]*temp0); result.set(3,0,-data[4]*temp9+data[5]*temp7-data[6]*temp6); result.set(3,1,data[0]*temp9-data[1]*temp7+data[2]*temp6); result.set(3,2,-data[12]*temp3+data[13]*temp1-data[14]*temp0); result.set(3,3,data[8]*temp3-data[9]*temp1+data[10]*temp0); } else { result = Matrix::generateIdentityMatrix(); return result; } return result*(1/determinant); } // Calculate the determinant of a 4x4 matrix with Laplace expansion algorithm float Matrix::getDeterminant() { float temp0 = data[0]*data[5] - data[1]*data[4]; float temp1 = data[0]*data[6] - data[2]*data[4]; float temp2 = data[0]*data[7] - data[3]*data[4]; float temp3 = data[1]*data[6] - data[2]*data[5]; float temp4 = data[1]*data[7] - data[3]*data[5]; float temp5 = data[2]*data[7] - data[3]*data[6]; float temp6 = data[8]*data[13] - data[9]*data[12]; float temp7 = data[8]*data[14] - data[10]*data[12]; float temp8 = data[8]*data[15] - data[11]*data[12]; float temp9 = data[9]*data[14] - data[10]*data[13]; float temp10 = data[9]*data[15] - data[11]*data[13]; float temp11 = data[10]*data[15] - data[11]*data[14]; return temp0*temp11 - temp1*temp10 + temp2*temp9 + temp3*temp8 - temp4*temp7 + temp5*temp6; } // Return the matrix inside the float vector received as argument void Matrix::getMatrix(float * matrix) { for(int i=0; i<16; i++) { matrix[i]=data[i]; } } // Return the specified row as vector Vector Matrix::getRowAsVector(unsigned short row) { Vector result = Vector(); for (unsigned int i = 0; i < 4; i++){ result.set(i,this->get(row,i)); } return result; } // Return the specified column as vector Vector Matrix::getColumnAsVector(unsigned short column) { Vector result = Vector(); for (unsigned int i = 0; i < 4; i++){ result.set(i,this->get(i,column)); } return result; } // Operator overload for << for sending a matrix to the output stream std::ostream & operator<< (std::ostream &os, const Matrix &m) { // I add to the output stream in the following format: "{a00,a01,a02,a03 // a10,a11,a12,a13 // a20,a21,a22,a23 // a30,a31,a32,a33}". os << endl; os << "{" << m.get(0,0) << "," << m.get(0,1) << "," << m.get(0,2) << "," << m.get(0,3) << endl; os << " " << m.get(1,0) << "," << m.get(1,1) << "," << m.get(1,2) << "," << m.get(1,3) << endl; os << " " << m.get(2,0) << "," << m.get(2,1) << "," << m.get(2,2) << "," << m.get(2,3) << endl; os << " " << m.get(3,0) << "," << m.get(3,1) << "," << m.get(3,2) << "," << m.get(3,3) << "}"; // I return the stream return os; }
[ "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d" ]
[ [ [ 1, 1019 ] ] ]
4ee9be4f8bb57f24a08adbb48b09b1d10735627f
a8e78ee1cae74946b8b68aaaf0447d745d6fbaf3
/CPPUnitBCB6/borland/AppEjemplo/AppEjemplo.cpp
a6c674709615f83f7facb1be511551e548862bf2
[]
no_license
jmnavarro/BCB_CPPUnit
66c155026bd8445ca016e1327b0d222e3f4a10ad
7de1560d537db56d265fde482420bc6f66f01c32
refs/heads/master
2021-01-23T13:58:57.815624
2011-07-01T08:47:23
2011-07-01T08:47:23
1,982,570
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "ITestRunner.h" #include "MulticasterTest.h" #include "ExampleTestCase.h" //--------------------------------------------------------------------------- WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { ITestRunner runner; runner.addTest( MulticasterTest::suite() ); runner.addTest( ExampleTestCase::suite() ); runner.run (); } catch (Exception &exception) { Application->ShowException(&exception); } return 0; } //---------------------------------------------------------------------------
[ [ [ 1, 28 ] ] ]
68a66463397b08d3fdefcd9c5c1d10b551d9cf25
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Comun/Error.cpp
716409144a180a722f4354244033b42ca71e7d86
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
220
cpp
#include "Error.h" Error::Error(void){ } Error::Error(string id, string valor, string idOperacion) : Respuesta(id, valor, idOperacion){ } Error::~Error(void) { } bool Error::isError(){ return true; }
[ "natlehmann@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 15 ] ] ]
5bfb2549f525388519b5bef0f6ec854d07d2aa44
4797c7058b7157e3d942e82cf8ad94b58be488ae
/PlayerShip.h
90893b4762ea047ffa8964db542c1d5a10aea28d
[]
no_license
koguz/DirectX-Space-Game
2d1d8179439870fd1427beb9624f1c5452546c39
be672051fd0009cbd5851c92bd344d3b23645474
refs/heads/master
2020-05-18T02:11:47.963185
2011-05-25T14:35:26
2011-05-25T14:35:26
1,799,267
0
0
null
null
null
null
UTF-8
C++
false
false
788
h
#ifndef PLAYERSHIP__H__ #define PLAYERSHIP__H__ #include <dsound.h> #include <vector> #include "MySound.h" #include "BaseObject.h" #include "Laser.h" class PlayerShip:public BaseObject { public: PlayerShip(); bool Init(IDirect3DDevice9* d, IDirectSound8 *s); void Update(float dtime); void SetSpeed(float p); void FireLaser(); void Scratched(); void Hit(int d); int getHealth() { return health; } void SpeedUp(); void SpeedDown(); void SpeedNormal(); std::vector<Laser> lasers; MySound Engine; //, Mission1; private: IDirectSound8* Sound; MySound Fire, Scratch, HitSound;// , Mission1; unsigned int lastShot; float maxSpeed; float minSpeed; float casSpeed; unsigned int laserInterval; int health; int lastGen; }; #endif
[ [ [ 1, 40 ] ] ]
24978989d5d3224ee0c66b91a4bfbabf6e3dc8ae
2112057af069a78e75adfd244a3f5b224fbab321
/branches/ref1/src-root/include/ireon_client/interface/client_interface.h
a7166ea382ea667aac1d46c3c59adf42e06ee4ba
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,137
h
/** * @file client_interface.h * Client interface class */ /* Copyright (C) 2005 ireon.org developers council * $Id$ * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef _CLIENT_I_INTERFACE_H #define _CLIENT_I_INTERFACE_H #include "interface/interface.h" class CClientInterface : public CInterface { private: CClientInterface(); public: ~CClientInterface(); static CClientInterface* instance() {{if( !m_singleton ) m_singleton = new CClientInterface; return m_singleton;}} bool init(RenderWindow* win); void pulseUpdate(Real time); bool frameStarted(const FrameEvent &evt); bool isFirstPerson() {return m_firstPerson;} void setFirstPerson(bool value) {m_firstPerson = value;} CharacterPtr getTarget(); void setTarget(CharacterPtr target) {m_target = target;} void nextTarget(); CharacterPtr getHighlight() {return m_highlight;} void setCamR(Real radius) {m_camR = radius;} void mouseMoved(MouseEvent *e); protected: void mousePressedNoGUI(MouseEvent *e); private: /** Difference between needed and real y rotation (if needed position is under ground */ Radian m_diffY; ///Distance from camera to character Real m_camR; ///Camera position in previous frame Vector3 m_prevCamPos; ///First person camera on bool m_firstPerson; CharacterPtr m_target; CharacterPtr m_highlight; static CClientInterface* m_singleton; }; #endif
[ [ [ 1, 82 ] ] ]
906a42d5e975cb98e7230cf3ff46e219f3813ed0
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/ModelsC/MG/MG_TWOPH.CPP
09e25be50ff796510656cee848fa90fe20669e4c
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
132,787
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #include "stdafx.h" #include <string.h> #include <math.h> #include <stdlib.h> #include <float.h> #include "sc_defs.h" #include "datacnvs.h" #include "ndtree.h" #include "flwnode.h" #define __MG_TWOPH_CPP #include "mg_twoph.h" #include "net_err.h" #include "mathlib.h" #include "dbgmngr.h" //#include "optoff.h" #define dbgPipeline 01 #if dbgPipeline static CDbgMngr dbgAddSegs ("MG", "AddSegs"); static CDbgMngr dbgVelocities ("MG", "Velocities"); static CDbgMngr dbgCalcPress ("MG", "CalcPress"); static CDbgMngr dbgEstDP ("MG", "EstDP"); static CDbgMngr dbgTempDerivs ("MG", "TempDerivs"); static CDbgMngr dbgPosition ("MG", "Position"); static CDbgMngr dbgTPPDump ("MG", "TPPDump"); #endif #define PressCalc1 01 const int IgnoreStepStart=1; //#pragma message("NB NB NB optimise off -------------------------------------------------------") //#pragma optimize("", off) //========================================================================== // // // //========================================================================== TPPGasProps::TPPGasProps() { dGasDens=DefGasDens; dNormGasDens=DefNormGasDens; dGasCp=2.0; dGasSum=0.0; } //-------------------------------------------------------------------------- void TPPGasProps::InitSum(double Gas) { dGasSum=Gas; if (dGasSum<=1.0e-6) { dGasDens=DefGasDens; dNormGasDens=DefNormGasDens; dGasCp=2.0; } } //-------------------------------------------------------------------------- void TPPGasProps::Sum(TPPGasProps & Other, double OtherGMass) { double TotGMass=dGasSum+OtherGMass; if (TotGMass>1.0e-6) { dGasCp=(dGasSum*dGasCp+OtherGMass*Other.dGasCp)/TotGMass; dNormGasDens=(dGasSum*dNormGasDens+OtherGMass*Other.dNormGasDens)/TotGMass; dGasDens=(dGasSum*dGasDens+OtherGMass*Other.dGasDens)/TotGMass; } dGasSum=TotGMass; } //-------------------------------------------------------------------------- TPPLiqProps::TPPLiqProps() { dLiqDens=DefLiqDens; dLiqCp=3.0; dLiqSum=0.0; } //-------------------------------------------------------------------------- void TPPLiqProps::InitSum(double Liq) { dLiqSum=Liq; if (dLiqSum<=1.0e-6) { dLiqDens=DefLiqDens; dLiqCp=3.0; } } //-------------------------------------------------------------------------- void TPPLiqProps::Sum(TPPLiqProps & Other, double OtherLMass) { double TotLMass=dLiqSum+OtherLMass; if (TotLMass>1.0e-6) { dLiqCp=(dLiqSum*dLiqCp+OtherLMass*Other.dLiqCp)/TotLMass; dLiqDens=(dLiqSum*dLiqDens+OtherLMass*Other.dLiqDens)/TotLMass; } dLiqSum=TotLMass; } //-------------------------------------------------------------------------- TPPProps::TPPProps() { } //-------------------------------------------------------------------------- void TPPProps::InitSum(double Gas, double Liq) { TPPGasProps::InitSum(Gas); TPPLiqProps::InitSum(Liq); } //-------------------------------------------------------------------------- void TPPProps::Sum(TPPProps & Other, double OtherGMass, double OtherLMass) { TPPGasProps::Sum(Other, OtherGMass); TPPLiqProps::Sum(Other, OtherLMass); } //-------------------------------------------------------------------------- TPPProps & TPPProps::operator=(TPPGasProps & Other) { dGasDens=Other.dGasDens; dNormGasDens=Other.dNormGasDens; dGasCp=Other.dGasCp; dGasSum=Other.dGasSum; return *this; }; //-------------------------------------------------------------------------- TPPProps & TPPProps::operator=(TPPLiqProps & Other) { dLiqDens=Other.dLiqDens; dLiqCp=Other.dLiqCp; dLiqSum=Other.dLiqSum; return *this; }; //========================================================================== // // // //========================================================================== TPPSection::TPPSection() { iMyIndex=0; dRelDatum=0.0; nSlugs=0; dTotLiqHoldup=0; dStart=0.0; dEnd=0.0; dAngle=0.0; } TPPSection::~TPPSection() { } //========================================================================== // // // //========================================================================== TPPJoin::TPPJoin() { dMeasP=Std_P; dMeasT=Std_T; dMeasGasVel=0.0; dMeasLiqVel=0.0; bMeasHorFlowRegime=0; bMeasFlowRegime=0; } //-------------------------------------------------------------------------- TPPJoin::TPPJoin(TPPJoin & Other) { dMeasP = Other.dMeasP; dMeasT = Other.dMeasT; dMeasGasVel=Other.dMeasGasVel; dMeasLiqVel=Other.dMeasLiqVel; bMeasHorFlowRegime=Other.bMeasHorFlowRegime; bMeasFlowRegime =Other.bMeasFlowRegime; }; //-------------------------------------------------------------------------- TPPJoin & TPPJoin::operator=(TPPJoin & Other) { dMeasP = Other.dMeasP; dMeasT = Other.dMeasT; dMeasGasVel=Other.dMeasGasVel; dMeasLiqVel=Other.dMeasLiqVel; bMeasHorFlowRegime=Other.bMeasHorFlowRegime; bMeasFlowRegime =Other.bMeasFlowRegime; return *this; }; //-------------------------------------------------------------------------- TPPJoin::~TPPJoin() { }; //========================================================================== // // // //========================================================================== TPPFlowStuff::TPPFlowStuff() { bHorFlowRegime=0; // DP Calc FLow regime bFlowRegime=0; // Flow Regime // dQmRng=0; // Ranged Flow due to DP dQmEst=0; // Calc Flow due to DP dQmG=0; // Calc Flow due to DP dQmL=0; // Calc Flow due to DP //dQv=0; // Volume flow dQvG=0; // Gas Vol Flow due to DP dQvL=0; // Liq Vol FLow due to DP dVapFrac=1; // Mean vapour fraction sLiqVolFrac=0; // Slip Liq Volume Fraction dDarcyCorrection=0; dSupGasVel=0; // Superficial Gas Velocity dSupLiqVel=0; // Superficial Liquid Velocity dTotalVel=0; // Total Velocity dDPq=0; dDPqDq=0; dDPmB=0; dDPmQ=0; dDPmDq=0; dDPApplied=0; dDPz=0; dVelStart=0; dGasVelo=0; dLiqVelo=0; } //-------------------------------------------------------------------------- TPPFlowStuff::TPPFlowStuff(double Position, double Velocity, double Mass, double Temperature, TPPProps & Properties) { bHorFlowRegime=0; // DP Calc FLow regime bFlowRegime=0; // Flow Regime // dQmRng=0; // Ranged Flow due to DP dQmEst=0; // Calc Flow due to DP dQmG=0; // Calc Flow due to DP dQmL=0; // Calc Flow due to DP //dQv=0; // Volume flow dQvG=0; // Gas Vol Flow due to DP dQvL=0; // Liq Vol FLow due to DP dVapFrac=1; // Mean vapour fraction sLiqVolFrac=0; // Slip Liq Volume Fraction dDarcyCorrection=0; dSupGasVel=0; // Superficial Gas Velocity dSupLiqVel=0; // Superficial Liquid Velocity dTotalVel=0; // Total Velocity dDPq=0; dDPqDq=0; dDPmB=0; dDPmQ=0; dDPmDq=0; dDPApplied=0; dDPz=0; dVelStart=0; dGasVelo=0; dLiqVelo=0; } //-------------------------------------------------------------------------- TPPFlowStuff::TPPFlowStuff(TPPFlowStuff & Other) { bHorFlowRegime = Other.bHorFlowRegime; bFlowRegime = Other.bFlowRegime; // dQmRng = Other.dQmRng; dQmEst = Other.dQmEst; dQmG = Other.dQmG; dQmL = Other.dQmL; dQvG = Other.dQvG; dQvL = Other.dQvL; dVapFrac = Other.dVapFrac; sLiqVolFrac = Other.sLiqVolFrac; dDarcyCorrection = Other.dDarcyCorrection; dSupGasVel = Other.dSupGasVel; dSupLiqVel = Other.dSupLiqVel; dTotalVel = Other.dTotalVel; dDPq = Other.dDPq; dDPqDq = Other.dDPqDq; dDPmB = Other.dDPmB; dDPmQ = Other.dDPmQ; dDPmDq = Other.dDPmDq; dDPApplied = Other.dDPApplied; dDPz = Other.dDPz; dVelStart = Other.dVelStart; dGasVelo = Other.dGasVelo; dLiqVelo = Other.dLiqVelo; } //-------------------------------------------------------------------------- TPPFlowStuff & TPPFlowStuff::operator=(TPPFlowStuff & Other) { bHorFlowRegime = Other.bHorFlowRegime; bFlowRegime = Other.bFlowRegime; // dQmRng = Other.dQmRng; dQmEst = Other.dQmEst; dQmG = Other.dQmG; dQmL = Other.dQmL; dQvG = Other.dQvG; dQvL = Other.dQvL; dVapFrac = Other.dVapFrac; sLiqVolFrac = Other.sLiqVolFrac; dDarcyCorrection = Other.dDarcyCorrection; dSupGasVel = Other.dSupGasVel; dSupLiqVel = Other.dSupLiqVel; dTotalVel = Other.dTotalVel; dDPq = Other.dDPq; dDPqDq = Other.dDPqDq; dDPmB = Other.dDPmB; dDPmQ = Other.dDPmQ; dDPmDq = Other.dDPmDq; dDPApplied = Other.dDPApplied; dDPz = Other.dDPz; dVelStart = Other.dVelStart; dGasVelo = Other.dGasVelo; dLiqVelo = Other.dLiqVelo; return *this; } //-------------------------------------------------------------------------- TPPFlowStuff::~TPPFlowStuff() { } double TPPFlowStuff::sHorLiqFlowFrac(double a, double b, double c, double nVolFrac, double Nfr) // returns the liquid holdup in a horizontal pipe assuming slip between the liquid and gas. Used in the Beggs and Brill Correlation { if (Nfr == 0) return 0; else return a*pow(nVolFrac, b)/pow(Nfr, c); } //-------------------------------------------------------------------------- double TPPFlowStuff::sElevFactor(double e, double f, double g, double h, double nVolFrac, double Nlv, double Nfr, double angle) // returns the factor to correct the liquid holdup in an elevated pipe, -90 < angle < 90 degrees { if ((angle == 0) || (nVolFrac == 0)) return 1; else { double ElevFact = 1+(1-nVolFrac)*log(h*pow(nVolFrac, e)*pow(Nlv, f)*pow(Nfr, g))*(sin(1.8*angle)-0.333*pow(sin(1.8*angle), 3)); if (ElevFact >= 1) return ElevFact; else return 1; } } //-------------------------------------------------------------------------- double TPPFlowStuff::DarcyDP(double Vel, double Rho, double Length, double Diam, double Rough, double Viscosity) { if ((Vel == 0) || (Rho == 0 ) || (Diam == 0) || (Viscosity == 0)) return 0; else { double Re, SG, pwrFac; Re = (Diam*Vel*Rho)/Viscosity; //Reynold's number SG = Rho / 1000.0; pwrFac = 2.0; // Churchill equation Ref: Churchill, S.W., Friction factor equation spans all flow regimes, // Chem. Eng., Nov. 7, 1977. double A, B, F_Fac, const_num; A = Pow((-2.457 * log(Pow(7.0/Re,0.9) + 0.27 * Rough/Diam)), 16); B = Pow((37530.0/Re), 16); F_Fac = 8 * Pow((Pow((8/Re), 12) + 1.0/Pow((A + B), 1.5)),0.0833); const_num = 2.0 * F_Fac * SG * Length * Pow(Vel,pwrFac) / Diam; return const_num; } } //-------------------------------------------------------------------------- void TPPFlowStuff::BeggsAndBrill(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Q, double &DPq, double &DPz, flag StartOfStep) { // Beggs and Brill correlation double Viscosity, LSurfTension; //Physical values need to be calculated (short term fix here) - AKS double nDensity, sDensity; //double dP_friction, dP_elevation; double Nfr, Nlv; double Vm, nLiqVolFrac, sLiqVolFrac_0, ElevAngle, L1, L2, L3, L4; //bHorFlowRegime; LSurfTension = 15e-3; // Hardwired for now, from example, Gas Processors Association if (0 && (fabs(dQvL) < 1e-5) && (fabs(dQvG) < 1e-4)) { DPq=0; DPz=0; } else { Vm = fabs(dQvL + dQvG) / Pipe.Area(); ElevAngle = Angle; // Calculate the Froude Number Nfr = Sqr(Vm) / gd if (Pipe.dDiam == 0) Nfr = 0; // Error message ??? AKS else Nfr = Sqr(Vm)/(9.81 * Pipe.dDiam); if (LSurfTension == 0) Nlv = 0; else Nlv = dSupLiqVel * pow((Props.dLiqDens/(9.81*LSurfTension)),0.25); nLiqVolFrac = dQvL / GTZ(dQvL + dQvG); // no slip density nDensity = Props.dLiqDens*nLiqVolFrac+(1-nLiqVolFrac)*Props.dGasDens; Viscosity = nLiqVolFrac*20e-3+(1-nLiqVolFrac)*0.015e-3; // Hardwired, Pa.s for now // From example, Gas processors association double y_L; if (nLiqVolFrac <= 1e-6) { sDensity=nDensity; y_L = 1.0; // gives modifying factor of 1 for dP_friction bHorFlowRegime = HFR_Segregated; bFlowRegime = TPR_Stratified; } else { L1 = 316.0 * pow(nLiqVolFrac, 0.302); L2 = 0.0009252 * pow(nLiqVolFrac, -2.4684); L3 = 0.10 * pow(nLiqVolFrac, -1.4516); L4 = 0.5 * pow(nLiqVolFrac, -6.738); // Find flow regime in horizontal pipe if (((nLiqVolFrac <= 0.01) && (Nfr <= L1)) || ((nLiqVolFrac > 0.01) && (Nfr <= L2))) { bHorFlowRegime = HFR_Segregated; // Sectregated flow bFlowRegime = TPR_Stratified; } else if ((nLiqVolFrac > 0.01) && (Nfr > L2) && (Nfr <= L3)) { bHorFlowRegime = HFR_Transition; // Transition flow bFlowRegime = TPR_Transition; } else if (((nLiqVolFrac > 0.01) && (nLiqVolFrac <= 0.4) && (Nfr > L3) && (Nfr <= L1)) || ((nLiqVolFrac > 0.4) && ((Nfr > L3) && (Nfr <= L4)))) { bHorFlowRegime = HFR_Intermittent; // Intermittent flow - slug or plug flow bFlowRegime = TPR_Slug; } else if (((nLiqVolFrac <= 0.4) && (Nfr > L1)) || ((nLiqVolFrac > 0.4) && (Nfr > L4))) { bHorFlowRegime = HFR_Distributed; // Distributed flow bFlowRegime = TPR_Bubble; } else { bHorFlowRegime = HFR_Segregated; // Catch All - Sectregated flow bFlowRegime = TPR_Stratified; } //calculate liquid holdup switch (bHorFlowRegime) { case HFR_Segregated: { sLiqVolFrac_0 = sHorLiqFlowFrac(0.98, 0.4846, 0.0868, nLiqVolFrac, Nfr); if (ElevAngle >= 0) sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-3.768,3.539,-1.614,0.011,nLiqVolFrac, Nlv, Nfr, ElevAngle); else sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); break; } case HFR_Transition: { double sLiqVolFrac_1; double AFactor = (L3-Nfr)/(L3-L2); sLiqVolFrac_0 = sHorLiqFlowFrac(0.98, 0.4846, 0.0868, nLiqVolFrac, Nfr); //Sectregated flow if (ElevAngle >= 0 ) sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-3.768,3.539,-1.614,0.011,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Sectregated flow else sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); sLiqVolFrac = AFactor*sLiqVolFrac_1; sLiqVolFrac_0 = sHorLiqFlowFrac(0.845, 0.5351, 0.0173, nLiqVolFrac, Nfr); // Intermittent flow if (ElevAngle >= 0) sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(0.305,-0.4473,0.0978,2.96,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Intermittent flow else sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); sLiqVolFrac = sLiqVolFrac + (1-AFactor)*sLiqVolFrac_1; break; } case HFR_Intermittent: { sLiqVolFrac_0 = sHorLiqFlowFrac(0.845, 0.5351, 0.0173, nLiqVolFrac, Nfr); // Intermittent flow if (ElevAngle >= 0) sLiqVolFrac = sLiqVolFrac_0*sElevFactor(0.305,-0.4473,0.0978,2.96,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Intermittent flow else sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); break; } case HFR_Distributed: { sLiqVolFrac_0 = sHorLiqFlowFrac(1.065,0.6824,0.0609, nLiqVolFrac, Nfr); if (ElevAngle >= 0) sLiqVolFrac = sLiqVolFrac_0; else sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); break; } } if (ElevAngle > 0) sLiqVolFrac = sLiqVolFrac*0.924; else if (ElevAngle < 0) sLiqVolFrac = sLiqVolFrac*0.685; //Payne et al correction factor // need to create a FE_Darcy object - do not know how to do?? Instead hav coppied code sDensity = Props.dLiqDens*sLiqVolFrac+(1-sLiqVolFrac)*Props.dGasDens; //Slip density (gasses slipping past liquid) y_L = nLiqVolFrac/Sqr(sLiqVolFrac); } //Calculate the pressure drop due to friction in the pipe DPq = DarcyDP(dTotalVel, nDensity, Len, Pipe.dDiam, Pipe.dRough, Viscosity);//Darcy // TOGO BACK maybe ! //modify darcy for 2 phase flow //double S; //if ((y_L > 1.0) && (y_L <= 1.200517)) // { // double S2=log(1.200517)/(-0.0523+3.182*log(1.200517)-0.8725*Sqr(log(1.200517))+0.01853*pow(log(1.200517), 4)); // double S1=0.0; // S=(S2-S1)/(1.200517-1.0)*(y_L-1.0)+S1;//Fitted straight line for discontinuity area // //given function very close to a straight line! // } //else // S=log(y_L)/(-0.0523+3.182*log(y_L)-0.8725*Sqr(log(y_L))+0.01853*pow(log(y_L), 4)); //dDarcyCorrection=exp(S); dDarcyCorrection = 0.5; //fudge to make system stable. DPq = -Sign(Q)*dDarcyCorrection*DPq; // Slug Noise; //DPq *= 1.0+Pipe.dSlugResInc*dTotLiqHoldup/Pipe.SectionVolume(); //Calculate change in pressure due to change in height DPz = 9.81*sDensity*Len*sin(ElevAngle)/1000; //modified for 2 phase flow by using slip density } } //-------------------------------------------------------------------------- /* void TPPFlowStuff::BeggsAndBrillInv(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Q, double &DPq, double &DPz, flag StartOfStep) { // Beggs and Brill correlation double Viscosity, LSurfTension; //Physical values need to be calculated (short term fix here) - AKS double nDensity, sDensity; //double dP_friction, dP_elevation; double Nfr, Nlv; double Vm, nLiqVolFrac, sLiqVolFrac_0, ElevAngle, L1, L2, L3, L4; //bHorFlowRegime; LSurfTension = 15e-3; // Hardwired for now, from example, Gas Processors Association if (0 && (fabs(dQvL) < 1e-5) && (fabs(dQvG) < 1e-4)) { DPq=0; DPz=0; } else { // Calc Atual // dQmL=Q*(1.0-dVapFrac); // dQmG=Q-dQmL; // dQvL=dQmL/Props.dLiqDens; // dQvG=dQmG/Props.dGasDens; // dSupLiqVel=dQvL/Pipe.Area(); // dSupGasVel=dQvG/Pipe.Area(); // dTotalVel=dSupLiqVel+dSupGasVel; sLiqVolFrac=(dQvL)/GTZ(dQvG+dQvL); // Vm = fabs(dQvL + dQvG) / Pipe.Area(); // // ElevAngle = Angle; // // // Calculate the Froude Number Nfr = Sqr(Vm) / gd // // if (Pipe.dDiam == 0) // Nfr = 0; // Error message ??? AKS // else // Nfr = Sqr(Vm)/(9.81 * Pipe.dDiam); // if (LSurfTension == 0) // Nlv = 0; // else // Nlv = dSupLiqVel * pow((Props.dLiqDens/(9.81*LSurfTension)),0.25); / nLiqVolFrac = dQvL / GTZ(dQvL + dQvG); // no slip density nDensity = Props.dLiqDens*nLiqVolFrac+(1-nLiqVolFrac)*Props.dGasDens; // Viscosity = nLiqVolFrac*20e-3+(1-nLiqVolFrac)*0.015e-3; // Hardwired, Pa.s for now // // From example, Gas processors association // // double y_L; // if (nLiqVolFrac <= 1e-6) // { // sDensity=nDensity; // y_L = 1.0; // gives modifying factor of 1 for dP_friction // bHorFlowRegime = HFR_Segregated; // bFlowRegime = TPR_Stratified; // } // else // { // L1 = 316.0 * pow(nLiqVolFrac, 0.302); // L2 = 0.0009252 * pow(nLiqVolFrac, -2.4684); // L3 = 0.10 * pow(nLiqVolFrac, -1.4516); // L4 = 0.5 * pow(nLiqVolFrac, -6.738); // // // Find flow regime in horizontal pipe // if (((nLiqVolFrac <= 0.01) && (Nfr <= L1)) || ((nLiqVolFrac > 0.01) && (Nfr <= L2))) // { // bHorFlowRegime = HFR_Segregated; // Sectregated flow // bFlowRegime = TPR_Stratified; // } // else if ((nLiqVolFrac > 0.01) && (Nfr > L2) && (Nfr <= L3)) // { // bHorFlowRegime = HFR_Transition; // Transition flow // bFlowRegime = TPR_Transition; // } // else if (((nLiqVolFrac > 0.01) && (nLiqVolFrac <= 0.4) && (Nfr > L3) && (Nfr <= L1)) || // ((nLiqVolFrac > 0.4) && ((Nfr > L3) && (Nfr <= L4)))) // { // bHorFlowRegime = HFR_Intermittent; // Intermittent flow - slug or plug flow // bFlowRegime = TPR_Slug; // } // else if (((nLiqVolFrac <= 0.4) && (Nfr > L1)) || ((nLiqVolFrac > 0.4) && (Nfr > L4))) // { // bHorFlowRegime = HFR_Distributed; // Distributed flow // bFlowRegime = TPR_Bubble; // } // else // { // bHorFlowRegime = HFR_Segregated; // Catch All - Sectregated flow // bFlowRegime = TPR_Stratified; // } // //calculate liquid holdup // switch (bHorFlowRegime) // { // case HFR_Segregated: // { // sLiqVolFrac_0 = sHorLiqFlowFrac(0.98, 0.4846, 0.0868, nLiqVolFrac, Nfr); // if (ElevAngle >= 0) // sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-3.768,3.539,-1.614,0.011,nLiqVolFrac, Nlv, Nfr, ElevAngle); // else // sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); // break; // } // case HFR_Transition: // { // double sLiqVolFrac_1; // double AFactor = (L3-Nfr)/(L3-L2); // sLiqVolFrac_0 = sHorLiqFlowFrac(0.98, 0.4846, 0.0868, nLiqVolFrac, Nfr); //Sectregated flow // if (ElevAngle >= 0 ) // sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-3.768,3.539,-1.614,0.011,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Sectregated flow // else // sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); // sLiqVolFrac = AFactor*sLiqVolFrac_1; // sLiqVolFrac_0 = sHorLiqFlowFrac(0.845, 0.5351, 0.0173, nLiqVolFrac, Nfr); // Intermittent flow // if (ElevAngle >= 0) // sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(0.305,-0.4473,0.0978,2.96,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Intermittent flow // else // sLiqVolFrac_1 = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); // sLiqVolFrac = sLiqVolFrac + (1-AFactor)*sLiqVolFrac_1; // break; // } // case HFR_Intermittent: // { // sLiqVolFrac_0 = sHorLiqFlowFrac(0.845, 0.5351, 0.0173, nLiqVolFrac, Nfr); // Intermittent flow // if (ElevAngle >= 0) // sLiqVolFrac = sLiqVolFrac_0*sElevFactor(0.305,-0.4473,0.0978,2.96,nLiqVolFrac, Nlv, Nfr, ElevAngle); // Intermittent flow // else // sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); // break; // } // case HFR_Distributed: // { // sLiqVolFrac_0 = sHorLiqFlowFrac(1.065,0.6824,0.0609, nLiqVolFrac, Nfr); // if (ElevAngle >= 0) // sLiqVolFrac = sLiqVolFrac_0; // else // sLiqVolFrac = sLiqVolFrac_0*sElevFactor(-0.3692,0.1244,-0.5056,4.7,nLiqVolFrac, Nlv, Nfr, ElevAngle); // break; // } // } // if (ElevAngle > 0) // sLiqVolFrac = sLiqVolFrac*0.924; // else if (ElevAngle < 0) // sLiqVolFrac = sLiqVolFrac*0.685; //Payne et al correction factor // // // need to create a FE_Darcy object - do not know how to do?? Instead hav coppied code // // sDensity = Props.dLiqDens*sLiqVolFrac+(1-sLiqVolFrac)*Props.dGasDens; //Slip density (gasses slipping past liquid) // y_L = nLiqVolFrac/Sqr(sLiqVolFrac); // } // // //Calculate the pressure drop due to friction in the pipe // DPq = DarcyDP(dTotalVel, nDensity, Len, Pipe.dDiam, Pipe.dRough, Viscosity);//Darcy // // // TOGO BACK maybe ! // //modify darcy for 2 phase flow // //double S; // //if ((y_L > 1.0) && (y_L <= 1.200517)) // // { // // double S2=log(1.200517)/(-0.0523+3.182*log(1.200517)-0.8725*Sqr(log(1.200517))+0.01853*pow(log(1.200517), 4)); // // double S1=0.0; // // S=(S2-S1)/(1.200517-1.0)*(y_L-1.0)+S1;//Fitted straight line for discontinuity area // // //given function very close to a straight line! // // } // //else // // S=log(y_L)/(-0.0523+3.182*log(y_L)-0.8725*Sqr(log(y_L))+0.01853*pow(log(y_L), 4)); // //dDarcyCorrection=exp(S); // dDarcyCorrection = 0.5; //fudge to make system stable. // DPq = -Sign(Q)*dDarcyCorrection*DPq; // // Slug Noise; // //DPq *= 1.0+Pipe.dSlugResInc*dTotLiqHoldup/Pipe.SectionVolume(); // // //Calculate change in pressure due to change in height // DPz = 9.81*sDensity*Len*sin(ElevAngle)/1000; //modified for 2 phase flow by using slip density // } } */ //-------------------------------------------------------------------------- void TPPFlowStuff::Coker(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Q, double &DPq, double &DPz, flag StartOfStep) { // Not checked yet - flow eregimes look incorrect - AKS //Coker, A. K. "Understanding Two-Phasse Flow in Process Piping" //Establish flow regimes by Baker Parameters. double LSurfTension = 15.0; // dynes/cm, Hardwired for now, from example, Gas Processors Association double LViscosity = 20.0; //cP, Hardwired, for now, From example, Gas processors association double GViscosity = 0.015; //cP, Hardwired, for now, From example, Gas processors association sLiqVolFrac= dQvL/GTZ(dQvG+dQvL); if ((fabs(dQmL) < 1e-5) && (fabs(dQmG) < 1e-5)) { DPq=0; DPz=0; } else if (fabs(dQmG) < 1e-5) { DPq= DarcyDP(dSupLiqVel, Props.dLiqDens, Len, Pipe.dDiam, Pipe.dRough, LViscosity*1e-3);//Darcy DPz = 9.81*Props.dLiqDens*1.0*sin(Angle)/1000; } else if (fabs(dQmL) < 1e-5) { DPq= DarcyDP(dSupGasVel, Props.dGasDens, Len, Pipe.dDiam, Pipe.dRough, GViscosity*1e-3);//Darcy DPz = 9.81*Props.dGasDens*1.0*sin(Angle)/1000; } else { // Calc Pressure Drop for liquid and the for gas alone double DPL, DPG, LMmod, YG; DPL= DarcyDP(dSupLiqVel, Props.dLiqDens, Len, Pipe.dDiam, Pipe.dRough, LViscosity*1e-3);//Darcy DPG= DarcyDP(dSupGasVel, Props.dGasDens, Len, Pipe.dDiam, Pipe.dRough, GViscosity*1e-3);//Darcy LMmod= sqrt(DPL/DPG); // Lockhart-Martinelli two-phase flow modulus //Establish flow regimes by Baker Parameters. double Bx, By; Bx= fabs(531*dQmL/dQmG*(sqrt(Props.dLiqDens*Props.dGasDens)/(Props.dLiqDens*2/3))*(pow(LViscosity,1/3)/LSurfTension)); By= fabs(2.16*dQmG/Pipe.Area()/(sqrt(Props.dLiqDens*Props.dGasDens)));//in m/s By= By*3600/0.3048; //converted to ft/h //Calc Constants for flow regime range double By1=exp(9.774459-0.6548*log(Bx)); double By2=exp(8.67694-0.1901*log(Bx)); double By3=exp(11.3976-0.6084*log(Bx)+0.0779*log(Bx)*log(Bx)); double By4=exp(10.7448-1.6265*log(Bx)+0.2839*log(Bx)*log(Bx)); double By5=exp(14.569802-1.0173*log(Bx)); double By6=exp(7.8206-0.2189*log(Bx)); if ((By < By1) && (By < By2)) { bFlowRegime = TPR_Stratified; } else if (By < By1) { bFlowRegime = TPR_Wave; } else if ((By < By6) && (By < By5)) { bFlowRegime = TPR_Plug; } else if ((Bx < 7.418) && (By < By3)) { bFlowRegime = TPR_Annular; } else if ((Bx > 7.418) && (By < By4) && (By < By5)) { bFlowRegime = TPR_Slug; } else if ((Bx > 7.418) && (By < By3) && (By > By4)) { bFlowRegime = TPR_Annular; } else if ((Bx > 7.418) && (By < By4)) { bFlowRegime = TPR_Bubble; } else { bFlowRegime = TPR_Dispersed; } switch (bFlowRegime) { case TPR_Bubble: { YG= Sqr(14.2*pow(LMmod,0.75)/(pow((dQmL/Pipe.Area()*0.453592/0.3048/0.3048/3600),0.1))); break; } case TPR_Plug: { YG= Sqr(27.315*pow(LMmod,0.855)/(pow((dQmL/Pipe.Area()*0.453592/0.3048/0.3048/3600),0.17))); break; } case TPR_Stratified: { YG= Sqr(15.4*LMmod/(pow((dQmL/Pipe.Area()*0.453592/0.3048/0.3048/3600),0.8))); break; } case TPR_Slug: { YG= 1.19*pow(LMmod,0.815)/(pow((dQmL/Pipe.Area()*0.453592/0.3048/0.3048/3600),0.5)); break; } case TPR_Annular: { double dInch; if (Pipe.dDiam > 10*0.0254) dInch= 10; else dInch= Pipe.dDiam/0.0254; YG= Sqr((4.8-0.3125*dInch)*pow(LMmod,(0.343-0.021*dInch))); break; } case TPR_Dispersed: { YG= Sqr(exp(1.4659+0.49138*log(LMmod)+0.04887*Sqr(log(LMmod))-0.000349*(log(LMmod)*log(LMmod)*log(LMmod)))); break; } case TPR_Wave: { // the Huntington friction factor is used double Hx= dQmL/dQmG*LViscosity/GViscosity; double HF= exp(0.211*log(Hx)-3.993); DPq= 0.0336*HF*Sqr(dQmG*3600/0.453592)/(pow((Pipe.dDiam/0.0254),5)*Props.dGasDens*pow(0.3048,3)/0.453592);// in psig/ft DPq= DPq*Len*0.3048/6.894757; // in kPa break; } } if (bFlowRegime != TPR_Wave) { DPq= -Sign(Q)*DPG*YG; } double tDensity = (Props.dGasDens*dQvG+Props.dLiqDens*dQvL)/GTZ(dQvL+dQvG); DPz = 9.81*tDensity*Len*sin(Angle)/1000; } } //-------------------------------------------------------------------------- void TPPFlowStuff::SetFlwInfo(TwoPhasePipe & Pipe, TPPProps &Props, double Q) { //dVapFrac=1.0; // Kludge dQmL=Q*(1.0-dVapFrac); dQmG=Q-dQmL; dQvL=dQmL/Props.dLiqDens; dQvG=dQmG/Props.dGasDens; dSupLiqVel=dQvL/Pipe.Area(); dSupGasVel=dQvG/Pipe.Area(); dTotalVel=dSupLiqVel+dSupGasVel; } //-------------------------------------------------------------------------- void TPPFlowStuff::StartStep() { dVelStart=dTotalVel; } //-------------------------------------------------------------------------- void TPPFlowStuff::EstimateDP1(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Mass, double Q, double &DPq, double &DPz, double &DPmB, double &DPmQ, flag StartOfStep) { double dQmRng=FlwEqn::RangeFlow(Q, 0.001); //dQmRng=GTZ(fabs(Q)); SetFlwInfo(Pipe, Props, dQmRng); DPq=0.0; DPmB=0.0; DPmQ=0.0; switch (1) { case 1: // Beggs & Brill BeggsAndBrill(Pipe, Props, Len, Angle, dQmRng, DPq, DPz, StartOfStep); // Coker(Pipe, Q, DPq, DPz, StartOfStep); //DPq=-Sign(Q)*fabs(DPq); break; default: { double R=Pipe.dLineRes*1.0; DPq=-Sign(Q)*(dQvL+dQvG)*R; break; } } // Reconstruct DPq double R=fabs(DPq)/dQmRng; DPq = -Q*R; // Reset Vel's etc to actual flows. SetFlwInfo(Pipe, Props, Q); double Denom; if (StartOfStep) { DPmB=0.0; DPmQ=0.0; Denom=-1; } else { Denom=(Max(ICGetTimeInc()*0.01, ICGetTimeIncFromStartOfStep())*Pipe.Area()); DPmB=Mass*(dVelStart)*0.001/Denom; DPmQ=-Mass*(dTotalVel)*0.001/Denom; } #if dbgPipeline if (dbgEstDP() && Pipe.fDoDbgBrk) dbgpln("%10.10s Vs:%14.6g Vt:%14.6g Dn:%14.6g dT:%14.6g dTs:%14.6g Pa:%14.6g", Pipe.Tag(),dVelStart,dTotalVel,Denom, ICGetTimeInc(), ICGetTimeIncFromStartOfStep(), Pipe.Area()); #endif //DPm=0.0; } //-------------------------------------------------------------------------- void TPPFlowStuff::EstimateDP(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Mass, double Q) { flag StartOfStep= !IgnoreStepStart && ICStepStart(); //double dQmRng=Sign(Q)*FlwEqn::RangeFlow(Max(0.01, Q), 10.0); //double dQmRng1=Sign(Q)*FlwEqn::RangeFlow(Max(0.01, Q)*1.01, 10.0); double dQ=Sign(Q)*Max(0.01, fabs(Q)*1.01); double dQ0=Q; double dQ1=Q+dQ; //double dQ=Sign(Q)*Max(1e-8, fabs(Q)*0.1); //double dQ=fabs(dQmRng)*0.1; //double dQ=dQ1-dQ0; double dPq1,dPz1,dPmB1,dPmQ1,dPq0,dPz0,dPmB0,dPmQ0, dPm1, dPm0; EstimateDP1(Pipe, Props, Len, Angle, Mass, dQ1, dPq1, dPz1, dPmB1, dPmQ1, StartOfStep); EstimateDP1(Pipe, Props, Len, Angle, Mass, dQ0, dPq0, dPz0, dPmB0, dPmQ0, StartOfStep); dDPz=dPz0; dDPq=dPq0; dDPqDq=(dPq1-dPq0)/(dQ); dPm0=dPmB0+dPmQ0; dPm1=dPmB1+dPmQ1; dDPmB=dPmB0; dDPmQ=dPmQ0; dDPmDq=(dPm1-dPm0)/(dQ); // Reconstruct DPq //double R=fabs(dDPq/dQmRng); //dDPq=-Sign(Q)*R*fabs(Q); SetFlwInfo(Pipe, Props, Q); if (StartOfStep) dVelStart=dTotalVel; if (sLiqVolFrac < 0.99999999) dGasVelo=Sign(Q)*fabs(dQvG)/((1-sLiqVolFrac)*Pipe.Area()); else dGasVelo=0; if (sLiqVolFrac > 0.00000001) { dLiqVelo=Sign(Q)*fabs(dQvL)/(sLiqVolFrac*Pipe.Area()); if (sLiqVolFrac >= 0.99999999) dGasVelo=dLiqVelo; } else dLiqVelo=dGasVelo; // dGasVelo=Sign(Q)*fabs(dTotalVel);///((1-sLiqVolFrac)*Pipe.Area()); // dLiqVelo=0.35*dGasVelo; // if (sLiqVolFrac > 0.00000001) // { // dLiqVelo=Sign(Q)*fabs(dQvL)/(sLiqVolFrac*Pipe.Area()); // if (sLiqVolFrac >= 0.99999999) // dGasVelo=dLiqVelo; // } // else // dLiqVelo=dGasVelo; if (fabs(dGasVelo)>100 || fabs(dLiqVelo)>100) { int xxx=0; } #if dbgPipeline if (dbgEstDP() && Pipe.fDoDbgBrk) dbgpln("%10.10s %2i %2i Q:%14.6g DPq:%14.6g DPm:%14.6g LVF:%14.6g TotVel:%14.6g", Pipe.Tag(),bHorFlowRegime,bFlowRegime,Q,dDPq,dDPmB+dDPmQ,sLiqVolFrac,dTotalVel); #endif } //-------------------------------------------------------------------------- void TPPFlowStuff::EstimateFlows(TwoPhasePipe & Pipe, TPPProps &Props, double Len, double Angle, double Mass, double DP) { #if dbgPipeline if (dbgEstDP() && Pipe.fDoDbgBrk) dbgpln("EstFlows DP:%14.6g", DP); #endif dDPApplied=DP; for (int Loop=100; ;Loop--) { EstimateDP(Pipe, Props, Len, Angle, Mass, dQmEst); // Reconstruct DP through R; // double R=fabs(dDPq/dQmRng); // dDPq=Sign(dDPq)*R*fabs(dQmEst); //@ Start of Step dont change estimates - if Momentum Calcs Used if (!IgnoreStepStart && ICStepStart()) break; double Sigma_dP=-(dDPq+dDPmB+dDPmQ); double P_Applied=DP; double Sigma_dPdQ = fabs(dDPqDq) + fabs(dDPmDq); double dQUnLim=(fabs(Sigma_dPdQ) > 1.0e-8 ? - (Sigma_dP - P_Applied) / Sigma_dPdQ : 0.0); #if dbgPipeline if (dbgEstDP() && Pipe.fDoDbgBrk) dbgpln("%sDP:%14.6g dDPq:%14.6g dDPm:%14.6g dDPqDq:%14.6g dDPmDq:%14.6g Sigma_dPdQ:%14.6g dQUnLim:%14.6g", " ", DP,dDPq,dDPmB+dDPmQ,dDPqDq,dDPmDq,Sigma_dPdQ,dQUnLim); #endif if (fabs(dQUnLim)<(1.0e-6+1.0e-6*fabs(dQmEst))) break; if (Loop==0) { LogError(Pipe.FullObjTag(), 0, "Segment Flows not converged"); break; } dQmEst+=dQUnLim; #if dbgPipeline if (fabs(dQmEst)>1.0e10) { int xxx=0; } #endif } } //========================================================================== // // // //========================================================================== static long dbgSegBaseCnt=0; TPPSegBase::TPPSegBase() { iPos = new Integrator ("SegPos", dPosition, dVelocity, dPosition, ValidFlags); iTemp = new Integrator ("SegTemp", dTemp, dTempDeriv, dTemp, ValidFlags); iMass = new Integrator ("SegMass", dMass, dMassDeriv, dMassTest, ValidFlags); dPosition = 0.0; dVelocity = 0.0; dMass = 0.0; dMassDeriv = 0.0; dMassTest = 0.0; dTemp = Std_T; dTempDeriv = 0.0; iAge = 0; //dbgpln("------------------ CTOR SegBase A %i", ++dbgSegBaseCnt); pImg = new SpConduit;//(&SM_OilClass, "Tmp", NULL, TOA_Free); } //-------------------------------------------------------------------------- TPPSegBase::TPPSegBase(double Position, double Velocity, double Mass, double Temperature, SpConduit * Img) { iPos = new Integrator("SegPos", dPosition, dVelocity, dPosition, ValidFlags); iTemp = new Integrator ("SegTemp", dTemp, dTempDeriv, dTemp, ValidFlags); iMass = new Integrator ("SegMass", dMass, dMassDeriv, dMassTest, ValidFlags); dPosition = Position; dVelocity = Velocity; dMass = Mass; dMassDeriv = 0.0; dMassTest = 0.0; dTemp = Temperature; dTempDeriv = 0.0; iAge = 0; //dbgpln("------------------ CTOR SegBase B %i", ++dbgSegBaseCnt); pImg = new SpConduit;//M_Oil(&SM_OilClass, "Tmp", NULL, TOA_Free); pImg->QCopy(*Img); } //-------------------------------------------------------------------------- TPPSegBase::~TPPSegBase() { delete iPos; delete iTemp; delete iMass; delete pImg; //dbgpln("------------------ DTOR SegBase %i", dbgSegBaseCnt--); } //-------------------------------------------------------------------------- TPPGSegment::TPPGSegment() { dPress = Std_P; dPressGrad = 0.0; dLiqMass = 0.0; } //-------------------------------------------------------------------------- TPPGSegment::TPPGSegment(double Position, double Velocity, double Mass, double Temperature, TPPGasProps & Properties, SpConduit * Img) : TPPSegBase(Position, Velocity, Mass, Temperature, Img) { GProps = Properties; dPress = Std_P; dPressGrad = 0.0; dLiqMass = 0.0; } //-------------------------------------------------------------------------- TPPLSegment::TPPLSegment() { } //-------------------------------------------------------------------------- TPPLSegment::TPPLSegment(double Position, double Velocity, double Mass, double Temperature, TPPLiqProps & Properties, SpConduit * Img) : TPPSegBase(Position, Velocity, Mass, Temperature, Img) { LProps = Properties; } ////-------------------------------------------------------------------------- // //double TPPSection::EiCoeff(int CoeffNo, double Omega, double mu_r, double k) //// AKS ///* Chung et al. Coefficients to Calculate Ei, Table 9-5, // Reid R C, Prausnitz J M, Polling B E,1987,'The Properties of Gases & Liquids', // 4th Ed, McGraw-Hill, NewYork, pp 427 */ // { // switch (CoeffNo) // { // case 1: // return 6.324+50.412*Omega-51.680*pow(mu_r,4)+1189.0*k; // case 2: // return 1.21e-3-1.154e-3*Omega-6.257e-3*pow(mu_r,4)+0.03728*k; // case 3: // return 5.283+254.209*Omega-168.48*pow(mu_r,4)+3898.0*k; // case 4: // return 6.623+38.096*Omega-8.464*pow(mu_r,4)+31.42*k; // case 5: // return 19.745+7.630*Omega-14.354*pow(mu_r,4)+31.53*k; // case 6: // return -1.9-12.537*Omega+4.985*pow(mu_r,4)-18.15*k; // case 7: // return 24.275+3.450*Omega-11.291*pow(mu_r,4)+69.35*k; // case 8: // return 0.7972+1.117*Omega+0.01235*pow(mu_r,4)-4.117*k; // case 9: // return -0.2382+0.06770*Omega-0.8163*pow(mu_r,4)+4.025*k; // case 10: // return 0.06863+0.3479*Omega+0.5926*pow(mu_r,4)-0.727*k; // default: // return 1; // } // } ////-------------------------------------------------------------------------- //double kFac(double NoOHgroups, double MolWeight) //// for general viscosity calcs, should calc and enter in database //// AKS ///* Chung et al. // Reid R C, Prausnitz J M, Polling B E,1987,'The Properties of Gases & Liquids', // 4th Ed, McGraw-Hill, NewYork, pp 396*/ // { // if (NoOHgroups == 0) // return 0.0; // else // return 0.0682+0.2767*(17*NoOHgroups/MolWeight); // } // ////-------------------------------------------------------------------------- // //double TPPSection::CalcGasViscosity(TwoPhasePipe & Pipe) //// AKS // ///* Chung et al. // Reid R C, Prausnitz J M, Polling B E,1987,'The Properties of Gases & Liquids', // 4th Ed, McGraw-Hill, NewYork, pp 413,414 // Mixing rules*/ // ////AKS - Assume have a matrix of acentric factors, dipole moments, and association values (k) // { ///* double Sum_e_k, Sum_sigma3, Sum_omega, Sum_k, Sum_M, Sum_dipole4; // double ij_e_k, ij_sigma, ij_omega, ij_k, ij_M; // double i_e_k, j_e_k, i_sigma, j_sigma, i_omega, j_omega, i_k, j_k, i_M, j_M; // double i_y, j_y; // // Sum_e_k = 0; // Sum_sigma = 0; // Sum_omega = 0; // Sum_k = 0; // Sum_M = 0; // // for (int j = 0; SDB.No(); j++) // { // if SDB[j].IsVap() // { // j_sigma = 0.809*pow((SDB[j].VCrit()*1e3), (1/3)); // j_e_k = SBD[j].TCrit()/1.2593; // j_omega = SBD[j].AcentricFac(); // AKS - assume that we have, currently do not!! // j_k = SBD[j].kFac(); // AKS - assume that we have, currently do not!! // j_dipole = SBD[j].DipoleMom(); // AKS - assume that we have, currently do not!! // j_M = SBD[j].MolWt(); // // j_y = SBD[j].MolFrac(); // // for (int i = 0; SDB.No();i++) // { // if SDB[i].IsVap() // { // i_sigma = 0.809*pow((SDB[i].VCrit()*1e3), (1/3)); // ij_sigma = sqrt(i_sigma*j_sigma); // i_e_k = SBD[i].TCrit()/1.2593; // ij_e_k = sqrt(i_e_k*j_e_k); // i_omega = SBD[i].AcentricFac(); // AKS - assume that we have, currently do not!! // ij_omega = (i_omega+j_omega)/2; // i_k = SBD[i].kFac(); // AKS - assume that we have, currently do not!! // ij_k = sqrt(i_k*j_k); // i_dipole = SBD[i].DipoleMom(); // AKS - assume that we have, currently do not!! // i_M = SBD[i].MolWt(); // if (i_M + j_M) == 0 // ij_M = 0; // else // ij_M = 2*i_M*j_M/(i_M+j_M); // i_y = SBD[i].MolFrac(); // // Sum_sigma3 = Sum_sigma3 + i_y*j_y*pow(ij_sigma, 3); // Sum_e_k = Sum_e_k + i_y*j_y*ij_e_k*pow(ij_sigma, 3); // Sum_M = Sum_M + i_y*j_y*ij_e_k*Sqr(ij_sigma)*sqrt(ij_M); // Sum_omega = Sum_omega + i_y*j_y*ij_omega*pow(ij_sigma, 3); // if !(ij_sigma == 0) // Sum_dipole4= Sum_dipole4 + i_y*j_y*Sqr(i_dipole*j_dipole)/pow(ij_sigma, 3); // Sum_k = Sum_k + i_y*j_y*ij_k; // } // } // } // } // if (Sum_sigma == 0) // Error, or bad data - AKS // { // Sum_e_k = 0; // Sum_M = 0; // Sum_omega = 0; // Sum_dipole4 = 0; // } // else // { // Sum_e_k = Sum_e_k/Sum_sigma; // Sum_omega = Sum_omega/Sum_sigma; // Sum_dipole4 = Sum_dipole4*Sum_sigma; // Sum_sigma = pow(Sum_sigma, (1/3)); // if (Sum_e_k == 0) // Sum_M = 0; // Error, or bad data - AKS // else // Sum_M = Sqr(Sum_M/(Sum_e_k*Sqr(Sum_sigma)); // // } // // // double T1, Tc, Vc, MolWeight, Acentric, dipoleMom4, k; // // double T = Pipe.dTemp; // Temperature of the pipe, check var name - AKS // // if (Sum_e_k == 0)/ / Error, or bad data - AKS // T1 = 0; // else // T1 = T/Sum_e_k; // // MolWeight = Sum_M; // Acentric = Sum_omega; // k = Sum_k; // Tc = 1.2593*Sum_e_k; // Vc = pow((Sum_sigma/0.809), 3); // if ((Vc == 0) || (Tc == 0)) // Error, or bad data - AKS // dipoleMom4 = 0; // else // dipoleMom4 = Sum_dipole4*pow(131.3, 4)/Sqr(Vc*Tc); // //*/ // ///* Chung et al. // Reid R C, Prausnitz J M, Polling B E,1987,'The Properties of Gases & Liquids', // 4th Ed, McGraw-Hill, NewYork, pp 396,397,426,427 // // Viscosity [Pa.s] // MolWeight [g/mol] // Tc [K] // Vc [cm^3/mol] // Rho [kg/m^3] // dipoleMom [debyes] // // An accurate estimate of the density at the T and P is required */ // // // /* double y, G1, G2, Visc1, Visc2, Fc, OmegaV; // double E1, E2, E3, E4, E5, E6, E7, E8, E9, E10; // // y = dGasDens*Vc/6; // E1 = EiCoeff(1, Acentric, dipoleMom4, k); // E2 = EiCoeff(2,Acentric, dipoleMom4, k); // E3 = EiCoeff(3 Acentric, dipoleMom4, k); // E4= EiCoeff(4, Acentric, dipoleMom4, k); // E5= EiCoeff(5,Aentric, dipoleMom4, k); // E6= EiCoeff(6,Aentric, dipoleMom4, k); // E7= EiCoeff(7, Acentric, dipoleMom4, k); // E8= EiCoeff(8, Acentric, dipoleMom4, k); // E9= EiCoeff(9, Acentric, dipoleMom4, k); // E10= EiCoeff(10, Acentric, dipoleMom4, k); // // // G1 = (1-0.5*y)/pow((1-y),3); // G2 = E1((1-exp(-E4*y))/y)+E2*G1*exp(E5*y)+E3*G1; // G2 = G2/(E1*E4+E2+E3); // // Fc = 1-0.2756*Acentric+0.059035*dipoleMom4+k; // // OmegaV = 1.16145*pow(T1,-0.14874)+0.52487*exp(-0.77320*T1)+2.16178*exp(-2.43787*T1); // // Visc1 = E7*Sqr(y)*G2*exp(E8+E9/T1+E10/Sqr(T1)); // Visc2 = sqrt(T1)/OmegaV*Fc*(1/G2+E6*y)+Visc1; // // return = Visc2*36.344*sqrt(MolWeight*Tc)/pow(Vc, 2/3)*1e-7; //*/ //return 0; // } //========================================================================== // // // //========================================================================== //ACCESS_SPECIE(H2o, "H2o"); //========================================================================== // // Two Phase Pipeline // //========================================================================== /*#D:#T:TwoPhasePipe #X:#n#u<#l<#b<General Description>>>#N#NThis model is used to calculate the flow conditons in a pipeline carrying gases and liquids. The model calculates the flow regime, pressure drop due to friction for each regime and the heat loss from the pipeline. #n#n#h<Variables to be supplied by the user> #n#i<Z_Rqd :>The required datum of the pipe. #n#i<Rs :>The resistance of the TwoPhasePipe (to do). #n#i<Tau :>The damping constant of the TwoPhasePipe. #n#i<Flash :>This determines whether flashing will occur in the pipe , 1 indicates that it occurs, 0 indicates that it does not occur. The default is 1 #n#i<FlashIn :>This determines whether the material is able to flash as it enters the TwoPhasePipe (to do) , 1 indicates that it occurs, 0 indicates that it does not occur. The default is 0 #n#i<T_Rqd :>The required temperature of the material within the TwoPhasePipe. #n#i<P_Rqd :>The required pressure of the material within the TwoPhasePipe. #n#i<Model :>This allows the selection of the model that is be used to calculate how the species are combined, there are two options : 'Mass Wt Mean' : A mass weighted mean is used. 'Light/Heavy Oil' : This uses relative density. #n#i<T :>The temperature of the material within the TwoPhasePipe. The default is 20dC #n#i<Species List :>This is a list of all the species, used in the particular flow engine, with their current mass in kilograms. This is where the specie composition of the TwoPhasePipe is determined. The default, for each species, is 0 kg #n#n#h<Variables calculated by the model> #n#i<Z :>The height of the TwoPhasePipe, in relation to the common datum. #n#i<P :>The pressure of the material within the TwoPhasePipe. #n#i<Rho :>The density of the material within the TwoPhasePipe. #n#i<NdP :>The normalised pressure drop across the TwoPhasePipe. #n#i<Mt :>The total mass of all the species within the TwoPhasePipe. #n#i<Rho :>The density of the material within the TwoPhasePipe. #n#i<Sf :>The percentage of solids within the TwoPhasePipe. #n#i<Lf :>The percentage of liquids within the TwoPhasePipe. #n#i<Vf :>The percentage of vapours within the TwoPhasePipe. #n#h<Other>#n Default model prefix:TPP#n Short name:TwoPhPip#n Model type:Link #G:Links */ // To Improve long Drw_TwoPhasePipe[] = { DD_Poly, -10,1, -10,-1, 10,-1, 10,1, -10,1, DD_End }; IMPLEMENT_MODELUNIT(TwoPhasePipe, "TwoPhPip", "", Drw_TwoPhasePipe, "TPP", TOC_ALL|TOC_GRP_ENERGY|TOC_USER, "TwoPhasePipe", "TwoPhasePipe") const int MinNSects=5; const int MinNSegs=4; //-------------------------------------------------------------------------- TwoPhasePipe::TwoPhasePipe(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) : // MdlNode(pClass_, TagIn, pAttach, eAttach), Pipe(pClass_, TagIn, pAttach, eAttach), FlowImg("FlowImg", this, TOA_Embedded)//, { AttachIOAreas(TwoIOAreaList); bSimple=false; fFlash = 0; dLength = 2000.0; dDiam = 12.0*0.0254; dRough = 0.0003; //AKS dAngleS = 0.0; dAngle = 0; //AKS dAngleE = 0.0; dLengthS = dNAN(); dLengthE = dNAN(); dMaxSlugVolume = 2.86; dSlugResInc = 0.1; dSlugAppears = 0.05; dSlugMinLen = 0.5; dSlugReduction = 0.4; SetNSections(2); SetNGSegments(5); SetNLSegments(5); InitSlug.SetSize(3); InitSlug[0].dPosition = -1.0; InitSlug[0].dVolume = 0.0; InitSlug[1].dPosition = -1.0; InitSlug[1].dVolume = 0.0; InitSlug[2].dPosition = -2.0; InitSlug[2].dVolume = 0.0; dSeaTemp = C_2_K(8.0); dHTC = 0.005; dODiam = dDiam + 2.0 * 0.0254; dLineRes = 1.0; dRqdLinePress = 5000.0; dRqdLineTemp = Std_T; dRqdVapFrac = 0.94; dTotLiqHoldup = 0.0; nSlugs = 0; nMaxSlugs = 5; dQmGEntry = 0.0; dQmLEntry = 0.0; dQmGExit = 0.0; dQmLExit = 0.0; dCpGEntry = 0.0; dCpLEntry = 0.0; dCpGExit = 0.0; dCpLExit = 0.0; fDoSetLinePress=false; fDoSetLineSlugs=false; }; //-------------------------------------------------------------------------- TwoPhasePipe::~TwoPhasePipe() { GasSeg.SetSize(0); LiqSeg.SetSize(0); //SetNGSegments(0); //SetNLSegments(0); }; //-------------------------------------------------------------------------- void TwoPhasePipe::BuildDataDefn(DataDefnBlk &DDB) { DDB.CheckBoxBtn("Simple", "", DC_, "", &bSimple, this, isParm);//|SetOnChange); if (bSimple) { Pipe::BuildDataDefn(DDB); return; } DDB.BeginStruct(this); DDB.Text (""); DDB.Double ("GasDens", "", DC_Rho, "kg/m^3", &FdProps.dGasDens, this, 0); DDB.Double ("LiqDens", "", DC_Rho, "kg/m^3", &FdProps.dLiqDens, this, 0); DDB.Double ("GasCp", "", DC_CpMs, "kJ/kg.C", &FdProps.dGasCp, this, 0); DDB.Double ("LiqCp", "", DC_CpMs, "kJ/kg.C", &FdProps.dLiqCp, this, 0); DDB.Text (""); DDB.Double ("QmGEntry", "", DC_Qm, "kg/s", &dQmGEntry, this, 0); DDB.Double ("QmLEntry", "", DC_Qm, "kg/s", &dQmLEntry, this, 0); DDB.Double ("QmGExit", "", DC_Qm, "kg/s", &dQmGExit, this, 0); DDB.Double ("QmLExit", "", DC_Qm, "kg/s", &dQmLExit, this, 0); DDB.Double ("CpGEntry", "", DC_CpMs, "kJ/kg.C", &dCpGEntry, this, noView); DDB.Double ("CpLEntry", "", DC_CpMs, "kJ/kg.C", &dCpLEntry, this, noView); DDB.Double ("CpGExit", "", DC_CpMs, "kJ/kg.C", &dCpGExit, this, noView); DDB.Double ("CpLExit", "", DC_CpMs, "kJ/kg.C", &dCpLExit, this, noView); DDB.Double ("TempEntry", "", DC_T, "C", &dTempEntry, this, 0); DDB.Double ("TempExit", "", DC_T, "C", &dTempExit, this, 0); if (LastFullGSeg()>0) { DDB.Double ("PSeg0", "", DC_P, "kPa", &GasSeg[0]->dPress, this, 0|InitHidden); DDB.Double ("PSegN", "", DC_P, "kPa", &GasSeg[LastFullGSeg()]->dPress, this, 0|InitHidden); } BuildDataDefnShowIOs(DDB); DDB.Page("Parms", DDB_OptPage); DDB.Double ("Datum", "Z", DC_L, "m", &dDatum, this, 0); DDB.Long ("NSections", "", DC_, "", xidNSections, this, isParm); DDB.Long ("NGSegments", "", DC_, "", xidNGSegments, this, 0); DDB.Long ("NLSegments", "", DC_, "", xidNLSegments, this, 0); DDB.Double ("LengthS", "", DC_L, "m", &dLengthS, this, isParm|NAN_OK); DDB.Double ("Length", "", DC_L, "m", &dLength, this, isParm); DDB.Double ("LengthE", "", DC_L, "m", &dLengthE, this, isParm|NAN_OK); DDB.Double ("Diameter", "", DC_L, "m", &dDiam, this, isParm); DDB.Double ("PipeRoughness","Rough", DC_L, "mm", &dRough, this, isParm); DDB.Double ("", "AngleS", DC_Ang , "deg", &dAngleS, this, isParm); DDB.Double ("", "Angle", DC_Ang , "deg", &dAngle, this, isParm); DDB.Double ("", "AngleE", DC_Ang , "deg", &dAngleE, this, isParm); DDB.Double ("MaxSlugVolume", "", DC_Vol, "m^3", &dMaxSlugVolume, this, isParm); DDB.Double ("TotLiqHoldup", "", DC_Vol, "m^3", &dTotLiqHoldup, this, 0); DDB.Long ("MaxNSlugs", "", DC_, "", &nMaxSlugs, this, isParm); DDB.Long ("NSlugs", "", DC_, "", &nSlugs, this, 0); DDB.Text ("Slug Growth"); DDB.Double ("dSlugAppears", "", DC_Frac, "%", &dSlugAppears, this, isParm); DDB.Double ("dSlugResInc", "", DC_Frac, "%", &dSlugResInc, this, isParm); DDB.Double ("SlugMinLen", "", DC_L, "m", &dSlugMinLen, this, isParm); DDB.Double ("SlugReduction", "", DC_Frac, "%", &dSlugReduction, this, isParm); DDB.Text ("Thermal Loss"); DDB.Double ("SeaTemp", "", DC_T, "C", &dSeaTemp, this, isParm); DDB.Double ("ODiameter", "", DC_L, "m", &dODiam, this, isParm); DDB.Double ("HTC", "", DC_HTC, "W/m^2K", &dHTC, this, isParm); DDB.Text ("Initial Conditions"); DDB.Double ("Press_Rqd", "P_Rqd", DC_P, "kPag", &dRqdLinePress, this, isParm); DDB.Double ("Temp_Rqd", "T_Rqd", DC_T, "C", &dRqdLineTemp, this, isParm); DDB.Double ("VapFrac_Rqd", "", DC_Frac, "%", &dRqdVapFrac, this, isParm); DDB.Text ("Initial Slugs"); DDB.Double ("SlugPos0", "", DC_L, "m", &InitSlug[0].dPosition, this, isParm); DDB.Double ("SlugVol0", "", DC_Vol, "m^3", &InitSlug[0].dVolume, this, isParm); DDB.Double ("SlugPos1", "", DC_L, "m", &InitSlug[1].dPosition, this, isParm); DDB.Double ("SlugVol1", "", DC_Vol, "m^3", &InitSlug[1].dVolume, this, isParm); DDB.Double ("SlugPos2", "", DC_L, "m", &InitSlug[2].dPosition, this, isParm); DDB.Double ("SlugVol2", "", DC_Vol, "m^3", &InitSlug[2].dVolume, this, isParm); DDB.Button ("Set Line Press", "", DC_, "", xidTPPSetLineP, this, isParm); DDB.Button ("Set Line Slugs", "", DC_, "", xidTPPSetLineSegs, this, isParm); DDB.Text (""); static DDBValueLst DDBRegimes[]={ {TPR_Stratified, "Stratified"}, {TPR_Transition, "Transition"}, {TPR_Slug, "Slug"}, {TPR_Bubble, "Bubble"}, {TPR_Spray, "Spray"}, {TPR_Annular, "Annular"}, {TPR_Wave, "Wave"}, {0}}; static DDBValueLst DDBFlwRegimes[]={ {HFR_Segregated, "Segregated"}, {HFR_Transition, "Transition"}, {HFR_Intermittent, "Intermittent"}, {HFR_Distributed, "Distributed"}, {0}}; DDBPages PgTyp=DDB_RqdPage; Strng Tg; DDB.BeginArray(this, "Sect", "TPPSects", NSections(), 0); for (int i = 0; i<NSections(); i++) { Tg.Set("%i",i); DDB.Visibility(ALLMODES, True, True); DDB.BeginElement(this, Tg(), NULL); if ((i%10)==0 && i<NSections()-1) { Tg.Set("Sect%i",i); DDB.Page(Tg(), PgTyp); //PgTyp=DDB_OptPage; } DDB.Long ("NSlugs", "", DC_, "", &Sect[i].nSlugs, this, 0); DDB.Double ("LiquidHoldup", "", DC_Vol, "m^3", &Sect[i].dTotLiqHoldup, this, 0); // DDB.Text(""); DDB.Double ("Start", "", DC_L, "m", &Sect[i].dStart, this, 0); DDB.Double ("End", "", DC_L, "m", &Sect[i].dEnd, this, 0); } DDB.EndArray(); PgTyp=DDB_RqdPage; DDB.BeginArray(this, "TPJoin", "TPPJoin", NJoins(), 0); for (i = 0; i<NJoins(); i++) { Tg.Set("%i",i); DDB.Visibility(ALLMODES, True, True); DDB.BeginElement(this, Tg(), NULL); if ((i%10)==0 && i<NJoins()-1) { Tg.Set("Join%i",i); DDB.Page(Tg(), PgTyp); //PgTyp=DDB_OptPage; } DDB.Double ("T", "", DC_T, "C", &Join[i]->dMeasT, this, 0); DDB.Double ("P", "", DC_P, "kPa", &Join[i]->dMeasP, this, 0); DDB.Double ("GasVelocity", "", DC_Ldt, "m/s", &Join[i]->dMeasGasVel, this, 0); DDB.Double ("LiqVelocity", "", DC_Ldt, "m/s", &Join[i]->dMeasLiqVel, this, 0); DDB.Byte ("HorFlowRegime", "", DC_, "", &Join[i]->bMeasHorFlowRegime, this, 0, DDBFlwRegimes); DDB.Byte ("FlowRegime", "", DC_, "", &Join[i]->bMeasFlowRegime, this, 0, DDBRegimes); DDB.Double ("Pos", "", DC_L, "m", xidJoinPos+i, this, 0); } DDB.EndArray(); PgTyp=DDB_RqdPage; DDB.BeginArray(this, "GSeg", "TPPSegs", NSections(), 0); for (int sg=0; sg<NGSegments(); sg++) { TPPGSegment &Sg=GSeg(sg); Tg.Set("%i", sg); DDB.BeginElement(this, Tg(), NULL); if ((sg%5)==0 && sg<NGSegments()-1) { Tg.Set("GSeg%i",sg); DDB.Page(Tg(), PgTyp); //PgTyp=DDB_OptPage; } DDB.Double ("Position", "", DC_L, "m", &Sg.dPosition, this, 0); if (sg<NFullGSegs()) { //double dLength=GSegLength(sg); DDB.Double ("Velocity", "", DC_Ldt, "m/s", &Sg.dVelocity, this, 0); DDB.Double ("Length", "", DC_L, "m", xidGSegLen+sg, this, 0); DDB.Double ("Mass", "", DC_M, "kg", &Sg.dMass, this, 0); DDB.Double ("Temperature", "", DC_T, "C", &Sg.dTemp, this, 0); DDB.Double ("VapFrac", "", DC_Frac,"%", &Sg.dVapFrac, this, 0); //DDB.Byte ("HorFlowRegime", "", DC_, "", &Sg.bHorFlowRegime, this, 0, DDBFlwRegimes); DDB.Byte ("FlowRegime", "", DC_, "", &Sg.bFlowRegime, this, 0, DDBRegimes); DDB.Double ("Press", "", DC_P, "kPa", &Sg.dPress, this, 0); DDB.Double ("PressGrad", "", DC_P, "kPa", &Sg.dPressGrad, this, 0); DDB.Double ("GasVelo", "", DC_Ldt, "m/s", &Sg.dGasVelo, this, 0); DDB.Double ("LiqVelo", "", DC_Ldt, "m/s", &Sg.dLiqVelo, this, 0); DDB.Double ("GasDens", "", DC_Rho, "kg/m^3", &Sg.GProps.dGasDens, this, 0|InitHidden/*noView*/); DDB.Double ("NGasDens", "", DC_Rho, "kg/m^3", &Sg.GProps.dNormGasDens, this, 0|InitHidden/*noView*/); DDB.Double ("GasCp", "", DC_CpMs, "kJ/kg.C", &Sg.GProps.dGasCp, this, 0|InitHidden/*noView*/); DDB.Double ("QmEst", "", DC_Qm, "kg/s", &Sg.dQmEst, this, 0|InitHidden/*noView*/); DDB.Double ("TotVel", "", DC_Ldt, "m/s", &Sg.dTotalVel, this, 0|InitHidden/*noView*/); } } DDB.EndArray(); PgTyp=DDB_RqdPage; DDB.BeginArray(this, "LSeg", "TPPSegs", NSections(), 0); for (sg=0; sg<NLSegments(); sg++) { TPPLSegment &Sg=LSeg(sg); Tg.Set("%i", sg); DDB.BeginElement(this, Tg(), NULL); if ((sg%5)==0 && sg<NLSegments()-1) { Tg.Set("LSeg%i",sg); DDB.Page(Tg(), PgTyp); //PgTyp=DDB_OptPage; } DDB.Double ("Position", "", DC_L, "m", &Sg.dPosition, this, 0); if (sg<NFullLSegs()) { //uble dLength=LSegLength(sg); DDB.Double ("Velocity", "", DC_Ldt, "m/s", &Sg.dVelocity, this, 0); DDB.Double ("Length", "", DC_L, "m", xidLSegLen+sg, this, 0); DDB.Double ("Mass", "", DC_M, "kg", &Sg.dMass, this, 0); DDB.Double ("Temperature", "", DC_T, "C", &Sg.dTemp, this, 0); DDB.Double ("FillFrac", "", DC_Frac,"%", xidLSegFillFrac+sg, this, 0); //DDB.Byte ("HorFlowRegime", "", DC_, "", &Sg.bHorFlowRegime, this, 0, DDBFlwRegimes); DDB.Byte ("FlowRegime", "", DC_, "", &Sg.bFlowRegime, this, 0, DDBRegimes); //DDB.Double ("Press", "", DC_P, "kPa", &Sg.dPress, this, 0); //DDB.Double ("PressGrad", "", DC_P, "kPa", &Sg.dPressGrad, this, 0); DDB.Double ("GasVelo", "", DC_Ldt, "m/s", &Sg.dGasVelo, this, 0); DDB.Double ("LiqVelo", "", DC_Ldt, "m/s", &Sg.dLiqVelo, this, 0); DDB.Double ("LiqDens", "", DC_Rho, "kg/m^3", &Sg.LProps.dLiqDens, this, noView); DDB.Double ("LiqCp", "", DC_CpMs, "kJ/kg.C", &Sg.LProps.dLiqCp, this, noView); } } DDB.EndArray(); DDB.Object(&FlowImg, this, NULL, NULL, DDB_RqdPage); DDB.EndStruct(); }; // -------------------------------------------------------------------------- static byte TPP_Cnt=0x38; static byte TPP_End=0x39; flag TwoPhasePipe::GetOtherData(FilingControlBlock &FCB) { // DWORD nBytes; // for (int s=0; s<Join.GetSize(); s++) // { // FCB.WriteFile(&TPP_Cnt, sizeof(TPP_Cnt), &nBytes); // Join[s]->GetOtherData(FCB); // } // // FCB.WriteFile(&TPP_End, sizeof(TPP_End), &nBytes); return True; }; // -------------------------------------------------------------------------- flag TwoPhasePipe::PutOtherData(FilingControlBlock &FCB) { // int RqdSects=2; // // byte What; // DWORD nRead; // FCB.ReadFile(&What, sizeof(What), &nRead); // while (What==TPP_Cnt && nRead==sizeof(What)) // { // SetNSections(Max(NSections(), RqdSects)); // Join[RqdSects-2]->PutOtherData(FCB); // FCB.ReadFile(&What, sizeof(What), &nRead); // RqdSects++; // } // ASSERT(What==TPP_End); return True; }; // ------------------------------------------------------------------------- void TwoPhasePipe::SetNSections(int NSects) { NSects=Range(MinNSects,NSects,MaxTPPSections); Join.SetSize(NSects-1); Sect.SetSize(NSects); double SLen=Valid(dLengthS) ? dLengthS : 0.5 * dLength /(NSects-1); double ELen=Valid(dLengthE) ? dLengthE : 0.5 * dLength /(NSects-1); double MLen=(dLength-(SLen+ELen))/(NSects-2); double Pos=0.0; for (int s=0; s<Sect.GetSize(); s++) { Sect[s].iMyIndex=s; Sect[s].dStart=Pos; Pos+=(s==0 ? SLen : (s<UBSect() ? MLen : ELen)); Sect[s].dEnd=Pos; Sect[s].dAngle= (s==0 ? dAngleS : (s<UBSect() ? dAngle : dAngleE)); } } // ------------------------------------------------------------------------- void TwoPhasePipe::SetNGSegments(int NSegs) { GasSeg.SetSize(Max(MinNSegs,NSegs), 32); SegsChanged(); }; // ------------------------------------------------------------------------- void TwoPhasePipe::SetNLSegments(int NSegs) { LiqSeg.SetSize(Max(MinNSegs,NSegs), 32); SegsChanged(); }; // -------------------------------------------------------------------------- flag TwoPhasePipe::DataXchg(DataChangeBlk & DCB) { if (bSimple) return Pipe::DataXchg(DCB); if (MdlNode::DataXchg(DCB)) return 1; switch (DCB.lHandle) { case xidNSections: { if (DCB.rL) { SetNSections(*DCB.rL); SetLinePress(); } DCB.L=NSections(); return 1; } case xidNGSegments: { if (DCB.rL) SetNGSegments(*DCB.rL); DCB.L=NGSegments(); return 1; } case xidNLSegments: { if (DCB.rL) SetNLSegments(*DCB.rL); DCB.L=NLSegments(); return 1; } case xidTPPSetLineP: { if (DCB.rB && (*DCB.rB!=0) && (DCB.dwOpts &(TABOpt_ForFile|TABOpt_ForSnapShot|TABOpt_ForScenario))==0) { SetLinePress(); // SetLineSegs(False); } DCB.B=0; return 1; } case xidTPPSetLineSegs: { if (DCB.rB && (*DCB.rB!=0) && (DCB.dwOpts &(TABOpt_ForFile|TABOpt_ForSnapShot|TABOpt_ForScenario))==0) SetLineSegs(True); DCB.B=0; return 1; } default : { if (DCB.lHandle>=xidJoinStart && DCB.lHandle<xidJoinStart+Join.GetSize()) DCB.D=JoinStart(DCB.lHandle-xidJoinStart); else if (DCB.lHandle>=xidJoinEnd && DCB.lHandle<xidJoinEnd+Join.GetSize()) DCB.D=JoinEnd(DCB.lHandle-xidJoinEnd); else if (DCB.lHandle>=xidJoinPos && DCB.lHandle<xidJoinPos+Join.GetSize()) DCB.D=JoinPos(DCB.lHandle-xidJoinPos); else if (DCB.lHandle>=xidLSegFillFrac && DCB.lHandle<xidLSegFillFrac+LiqSeg.GetSize()) DCB.D=FillFraction(DCB.lHandle-xidLSegFillFrac); else if (DCB.lHandle>=xidLSegLen && DCB.lHandle<xidLSegLen+LiqSeg.GetSize()) DCB.D=LSegLength(DCB.lHandle-xidLSegLen); else if (DCB.lHandle>=xidGSegLen && DCB.lHandle<xidGSegLen+GasSeg.GetSize()) DCB.D=GSegLength(DCB.lHandle-xidGSegLen); return 1; } } return 0; } // ------------------------------------------------------------------------- flag TwoPhasePipe::ValidateData(ValidateDataBlk & VDB) { if (bSimple) { return MN_Lnk::ValidateData(VDB); } flag OK=1; if (Valid(dLengthS)) dLengthS = Range(10.0, dLengthS,10000.0); dLength = Range(100.0, dLength, 10000.0); if (Valid(dLengthE)) dLengthE = Range(10.0, dLengthE,10000.0); dDiam = Range(0.001, dDiam ,10.0); dRough = Range(0.0, dRough , 10.0); dAngleS = Range(-90.0, dAngleS ,90.0); dAngle = Range(-90.0, dAngle ,90.0); dAngleE = Range(-90.0, dAngleE ,90.0); dArea=PI*Sqr(dDiam)/4.0; dVolume=dLength*dArea; dODiam=Max(dODiam, dDiam+0.001); Sect[0].dAngle=dAngleS; for (int SectNo=1; SectNo<UBSect(); SectNo++); { Sect[SectNo].dAngle = dAngle; } Sect[UBSect()].dAngle=dAngleE; SetNGSegments(Max(2, NGSegments())); double Pos2Date=-dLength; for (int sg=0; sg<NGSegments(); sg++) { TPPGSegment & GSg=*GasSeg[sg]; GSg.dPosition=Max(Pos2Date+0.01, GSg.dPosition); Pos2Date=GSg.dPosition; if (GSg.pImg->QMass(som_Vap)<1.0e-3 && GSg.dMass>1.0e-3) GSg.pImg->QCopy(FlowImg);//.Model()); } SetNLSegments(Max(2, NLSegments())); Pos2Date=-dLength; for (sg=0; sg<NLSegments(); sg++) { TPPLSegment & LSg=*LiqSeg[sg]; LSg.dPosition=Max(Pos2Date+0.01, LSg.dPosition); Pos2Date=LSg.dPosition; if (LSg.pImg->QMass(som_Liq)<1.0e-3 && LSg.dMass>1.0e-3) LSg.pImg->QCopy(FlowImg);//.Model()); } //EvaluateSegment(0.0); CalcPressures(0.0); DbgDump(0.0); return MdlNode::ValidateData(VDB) && OK; } //-------------------------------------------------------------------------- flag TwoPhasePipe::GetModelAction(Strng & Tag, MdlActionArray & Acts) { //MdlAction {MAT_NULL, MAT_State, MAT_Value}; MdlAction M0(0, MAT_State, !fDoSetLinePress, "Set Line Press", 1); MdlAction M1(1, MAT_State, !fDoSetLineSlugs, "Set Line Slugs", 1); // MdlAction M1 = {1, MAT_State, VPB.On(), "Close", 0}; // MdlAction M2 = {2, MAT_Value, VPB.On(), "Manual Posn (%)", true, VPB.ManualPosition(this)*100, 0.0, 100.0}; Acts.SetSize(0); Acts.SetAtGrow(0, M0); Acts.SetAtGrow(1, M1); // Acts.SetAtGrow(2, M2); return True; }; //-------------------------------------------------------------------------- flag TwoPhasePipe::SetModelAction(Strng & Tag, MdlAction & Act) { switch (Act.iIndex) { case 0: fDoSetLinePress=true; break; case 1: fDoSetLineSlugs=true; break; } return true; }; // ------------------------------------------------------------------------- void TwoPhasePipe::PostConnect(int IONo) { MN_Lnk::PostConnect(IONo); FlwBlk &FB = *IOFB(IONo,0); pFlwEqn pEqn=FB.AssignFlwEqnGroup(PipeGroup, "FE_Line", this); if (typeid(*pEqn)!=typeid(FE_Linear)) { DoBreak(); } if (pEqn==NULL) { pFlwEqn pEqn=FB.AssignFlwEqnGroup(PipeGroup, PipeGroup.Default(), this); DoBreak(); } } //--------------------------------------------------------------------------- void TwoPhasePipe::ConfigureJoins() { if (bSimple) { MN_Lnk::ConfigureJoins(); return; } SetIO_Open(0, 0, false, ESS_Denied); SetIO_Open(1, 0, false, ESS_Denied); }; //-------------------------------------------------------------------------- void TwoPhasePipe::AddStdSegment(double Pos, double Len, double Press, double Temp, double VapFrac, TPPProps &Properties, SpConduit * Img) { double TotVolume=Len*dArea; double LiqMass=0.0; double GasMass=Properties.dNormGasDens*TotVolume*Press/Std_P*Std_T/Temp; for (int loop=0;loop<200;loop++) { double LiqVol=LiqMass/Properties.dLiqDens; if (LiqVol>0.9*TotVolume) { LiqVol=0.9*TotVolume; LiqMass=LiqVol*Properties.dLiqDens; } #if PressCalc1 GasMass=Properties.dNormGasDens*(TotVolume)*Press/Std_P*Std_T/Temp; #else GasMass=Properties.dNormGasDens*(TotVolume-LiqVol)*Press/Std_P*Std_T/Temp; #endif double Vf=GasMass/GTZ(GasMass+LiqMass); if (fabs(Vf-VapFrac)<0.00001) break; LiqMass=0.9*LiqMass+0.1*(1.0-VapFrac)*(GasMass+LiqMass); } // TPPGSegment *pG=new TPPGSegment(Pos, 0.0, GasMass, Temp, Properties, Img); // pG->iPos->SetTestValue(dLength); // GasSeg.Add(pG); int iG=GasSeg.GetSize(); GasSeg.SetSize(iG+1); TPPGSegment *pG=GasSeg[iG]; pG->dPosition=Pos; pG->dVelocity=0.0; pG->dMass=GasMass; pG->dTemp=Temp; pG->GProps=Properties; pG->dPress = Std_P; pG->dPressGrad = 0.0; pG->dLiqMass = 0.0; pG->pImg->QCopy(*Img); pG->iPos->SetTestValue(dLength); // TPPLSegment *pL=new TPPLSegment(Pos, 0.0, LiqMass, Temp, Properties, Img); // pL->iPos->SetTestValue(dLength); // LiqSeg.Add(pL); int iL=LiqSeg.GetSize(); LiqSeg.SetSize(iL+1); TPPLSegment *pL=LiqSeg[iL]; pL->dPosition=Pos; pL->dVelocity=0.0; pL->dMass=GasMass; pL->dTemp=Temp; pL->LProps=Properties; //pL->dPress = Std_P; //pL->dPressGrad = 0.0; //pL->dLiqMass = 0.0; pL->pImg->QCopy(*Img); pL->iPos->SetTestValue(dLength); SegsChanged(); } //-------------------------------------------------------------------------- void TwoPhasePipe::SetLinePress() { SetNSections(NSections()); // To Get Positions Correct dRqdLinePress=Range(Std_P, dRqdLinePress, 25000.0); dRqdVapFrac=Range(0.5, dRqdVapFrac, 1.0); GasSeg.SetSize(0); LiqSeg.SetSize(0); SegsChanged(); // Must Straddle the Whole Pipeline double Pos2Date=0.0; int iSect=0; int Done=0; while (!Done)//Pos2Date<=dLength-0.5*MeanSegLength()) { double SegEnd=Min(dLength, Pos2Date+MeanSegLength()); double SegLen=SegEnd-Pos2Date; if (dLength-SegEnd<0.1*SegLen) { Done=True; SegLen=dLength-Pos2Date; } AddStdSegment(Pos2Date, SegLen, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); Pos2Date+=SegLen; iSect=SectIndex(Pos2Date); } double SegEnd=dLength; double SegLen=SegEnd-Pos2Date; //AddStdSegment(Pos2Date, Len, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps); // The Dummy one AddStdSegment(dLength, SegLen, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); EvaluateSegment(0.0); CalcPressures(0.0); } //-------------------------------------------------------------------------- void TwoPhasePipe::SetLineSegs(flag DoSlugs) { dRqdVapFrac=Range(0.5, dRqdVapFrac, 1.0); // GasSeg.SetSize(0); LiqSeg.SetSize(0); int iNxtSlug=0; // Must Straddle the Whole Pipeline double Pos2Date=0.0; int iSect=0; int Done=0; double SpareLen=10.0; while (!Done && (Pos2Date < dLength-0.1)) { double NxtSlugPos=iNxtSlug<InitSlug.GetSize() ? InitSlug[iNxtSlug].dPosition: dLength*2.0; if (NxtSlugPos<0.0 || InitSlug[iNxtSlug].dVolume<=0.001) NxtSlugPos=dLength*2.0; double SegEnd=Min(dLength, Pos2Date+MeanSegLength()); flag DoSlug=DoSlugs && (NxtSlugPos<=SegEnd); if (DoSlug) SegEnd=NxtSlugPos; double SegLen=SegEnd-Pos2Date; if (dLength-SegEnd<0.1*Max(0.01*MeanSegLength(), SegLen)) { Done=True; SegLen=dLength-Pos2Date; DoSlug=False; } if (SegLen<=SpareLen) break; int s=SectIndex(Pos2Date); TPPJoin &Jn0=*Join[Max(0,s-1)]; TPPJoin &Jn1=*Join[Min(s,UBJoin())]; double Press=0.5*(Jn0.dMeasP+Jn1.dMeasP); double Temp=0.5*(Jn0.dMeasT+Jn1.dMeasT); // AddStdSegment(Pos2Date, SegLen, Press, Temp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); double TotVolume=SegLen*dArea; double LiqMass=(1.0-dRqdVapFrac)*TotVolume*FdProps.dLiqDens; TPPLSegment *pL=new TPPLSegment(Pos2Date, 0.0, LiqMass, dRqdLineTemp, FdProps, &FlowImg); pL->iPos->SetTestValue(dLength); LiqSeg.Add(pL); Pos2Date+=SegLen; if (DoSlug) { double SlugS=InitSlug[iNxtSlug].dPosition; double LiqVolume=InitSlug[iNxtSlug].dVolume; double LiqMass=FdProps.dLiqDens*LiqVolume; double LLen=LiqVolume/dArea/0.95; double MaxLiqLen=dLength-Pos2Date;//-SpareLen; if (LLen>MaxLiqLen) { LiqMass*=MaxLiqLen/LLen; LLen=MaxLiqLen; } // Add Line 5 % of length //AddStdSegment(Pos2Date, 1.05*LLen, Press, Temp, 0.01, FdProps, &FlowImg);//.Model()); TPPLSegment *pL=new TPPLSegment(Pos2Date, 0.0, LiqMass, dRqdLineTemp, FdProps, &FlowImg); pL->iPos->SetTestValue(dLength); LiqSeg.Add(pL); // Stretch them and add extra liquid Pos2Date+=LLen; //LiqSeg[UBLSeg()]->dMass+=LiqMass; iNxtSlug++; } iSect=SectIndex(Pos2Date); } double SegEnd=dLength; double SegLen=SegEnd-Pos2Date; //AddStdSegment(Pos2Date, Len, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps); // The Dummy one // AddStdSegment(dLength, SegLen, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); TPPLSegment *pL=new TPPLSegment(dLength, SegLen, 0.0, dRqdLineTemp, FdProps, &FlowImg); pL->iPos->SetTestValue(dLength); LiqSeg.Add(pL); EvaluateSegment(0.0); CalcPressures(0.0); SegsChanged(); } //-------------------------------------------------------------------------- //void TwoPhasePipe::SetLineSegs(flag DoSlugs) // { // dRqdVapFrac=Range(0.5, dRqdVapFrac, 1.0); // // GasSeg.SetSize(0); // LiqSeg.SetSize(0); // SegsChanged(); // int iNxtSlug=0; // // Must Straddle the Whole Pipeline // double Pos2Date=0.0; // int iSect=0; // int Done=0; // while (!Done)//Pos2Date<=dLength-0.5*MeanSegLength()) // { // double NxtSlugPos=iNxtSlug<InitSlug.GetSize() ? InitSlug[iNxtSlug].dPosition: dLength*2.0; // if (NxtSlugPos<0.0 || InitSlug[iNxtSlug].dVolume<=0.001) // NxtSlugPos=dLength*2.0; // double SegEnd=Min(dLength, Pos2Date+MeanSegLength()); // flag DoSlug=DoSlugs && (NxtSlugPos<=SegEnd); // if (DoSlug) // SegEnd=NxtSlugPos; // double SegLen=SegEnd-Pos2Date; // if (dLength-SegEnd<0.1*SegLen) // { // Done=True; // SegLen=dLength-Pos2Date; // DoSlug=False; // } // // int s=SectIndex(Pos2Date); // TPPJoin &Jn0=*Join[Max(0,s-1)]; // TPPJoin &Jn1=*Join[Min(s,UBJoin())]; // double Press=0.5*(Jn0.dMeasP+Jn1.dMeasP); // double Temp=0.5*(Jn0.dMeasT+Jn1.dMeasT); // // AddStdSegment(Pos2Date, SegLen, Press, Temp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); // Pos2Date+=SegLen; // if (DoSlug) // { // double SlugS=InitSlug[iNxtSlug].dPosition; // double LiqVolume=InitSlug[iNxtSlug].dVolume; // double LiqMass=FdProps.dLiqDens*LiqVolume; // double LLen=LiqVolume/dArea; // // Add Line 5 % of length // AddStdSegment(Pos2Date, 1.05*LLen, Press, Temp, 0.01, FdProps, &FlowImg);//.Model()); // // Stretch them and add extra liquid // Pos2Date+=1.05*LLen; // //LiqSeg[UBLSeg()]->dMass+=LiqMass; // // iNxtSlug++; // } // iSect=SectIndex(Pos2Date); // } // double SegEnd=dLength; // double SegLen=SegEnd-Pos2Date; // //AddStdSegment(Pos2Date, Len, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps); // // The Dummy one // AddStdSegment(dLength, SegLen, dRqdLinePress, dRqdLineTemp, dRqdVapFrac, FdProps, &FlowImg);//.Model()); // // EvaluateSegment(0.0); // CalcPressures(0.0); // } // //-------------------------------------------------------------------------- int TwoPhasePipe::GSegIndex(double Pos) { if (Pos>0.5*dLength) { int Index=NFullGSegs()-1; while ((Index>0) && (GasSeg[Index]->dPosition >= Pos)) Index--; return Index; } else { int Index=0; while ((Index<NFullGSegs()-1) && (GasSeg[Index+1]->dPosition < Pos)) Index++; return Index; } } //-------------------------------------------------------------------------- int TwoPhasePipe::LSegIndex(double Pos) { if (Pos>0.5*dLength) { int Index=NFullLSegs()-1; while ((Index>0) && (LiqSeg[Index]->dPosition >= Pos)) Index--; return Index; } else { int Index=0; while ((Index<NFullLSegs()-1) && (LiqSeg[Index+1]->dPosition < Pos)) Index++; return Index; } } //-------------------------------------------------------------------------- int TwoPhasePipe::SectIndex(double Pos) { if (Pos<=SectionEnd(0)) return 0; double L=SectionLength(1); return Range(1, (int)(1.0+GEZ(Pos-SectionStart(1))/L), UBSect()); } //-------------------------------------------------------------------------- int TwoPhasePipe::JoinIndex(double Pos) { if (Pos<=JoinEnd(0)) return 0; double L=JoinLength(1); return Range(1, (int)(1.0+GEZ(Pos-JoinStart(1))/L), UBJoin()); } //-------------------------------------------------------------------------- double TwoPhasePipe::GVelocity(double Pos) { int Index=Range(0, GSegIndex(Pos), NFullGSegs()-2); double Vel0=GSeg(Index).dGasVelo; double Vel1=GSeg(Index+1).dGasVelo; double L0=GSegStart(Index); double L1=GSegStart(Index+1); return (Vel0+(Vel1-Vel0)*(Pos-L0)/(L1-L0)); } //-------------------------------------------------------------------------- double TwoPhasePipe::LVelocity(double Pos) { int Index=Range(0, LSegIndex(Pos), NFullLSegs()-2); double Vel0=LSeg(Index).dLiqVelo; double Vel1=LSeg(Index+1).dLiqVelo; double L0=LSegStart(Index); double L1=LSegStart(Index+1); return (Vel0+(Vel1-Vel0)*(Pos-L0)/(L1-L0)); } //-------------------------------------------------------------------------- double TwoPhasePipe::Pressure(double Pos) { for (int Index=0; Index<NFullGSegs()-2; Index++) if (GSegMid(Index+1)>Pos) break; double Prs0=GasSeg[Index]->dPress; double Prs1=GasSeg[Index+1]->dPress; double L0=GSegMid(Index); double L1=GSegMid(Index+1); return Prs0+(Prs1-Prs0)*(Pos-L0)/(L1-L0); } //-------------------------------------------------------------------------- double TwoPhasePipe::Temperature(double Pos) { for (int Index=0; Index<NFullGSegs()-2; Index++) if (GSegMid(Index+1)>Pos) break; double Tmp0=GasSeg[Index]->dTemp; double Tmp1=GasSeg[Index+1]->dTemp; double L0=GSegMid(Index); double L1=GSegMid(Index+1); return Tmp0+(Tmp1-Tmp0)*(Pos-L0)/(L1-L0); } //-------------------------------------------------------------------------- void TwoPhasePipe::AddMass(double &GMass0, double &Temp0, TPPGasProps &Props0, double GMass1, double Temp1, TPPGasProps & Props1) { double Cp0=GMass0*Props0.dGasCp; // kJ/C double Cp1=GMass1*Props1.dGasCp; // kJ/C Props0.Sum(Props1, GMass1); Temp0=(Temp0*Cp0+Temp1*Cp1)/GTZ(Cp0+Cp1); GMass0+=GEZ(GMass1); } //-------------------------------------------------------------------------- void TwoPhasePipe::AddMass(double &LMass0, double &Temp0, TPPLiqProps & Props0, double LMass1, double Temp1, TPPLiqProps & Props1) { double Cp0=LMass0*Props0.dLiqCp; // kJ/C double Cp1=LMass1*Props1.dLiqCp; // kJ/C Props0.Sum(Props1, LMass1); Temp0=(Temp0*Cp0+Temp1*Cp1)/GTZ(Cp0+Cp1); LMass0+=GEZ(LMass1); } //-------------------------------------------------------------------------- void TwoPhasePipe::AddMass(double &GMass0, double &LMass0, double &Temp0, TPPProps & Props0, double GMass1, double LMass1, double Temp1, TPPProps & Props1) { double Cp0=GMass0*Props0.dGasCp+LMass0*Props0.dLiqCp; // kJ/C double Cp1=GMass1*Props1.dGasCp+LMass1*Props1.dLiqCp; // kJ/C Props0.Sum(Props1, GMass1, LMass1); Temp0=(Temp0*Cp0+Temp1*Cp1)/GTZ(Cp0+Cp1); LMass0+=GEZ(LMass1); GMass0+=GEZ(GMass1); } //-------------------------------------------------------------------------- void TwoPhasePipe::AddSweptMass(flag AtStart, double dTime, double &GasMass, double &LiqMass, double &MixTemp) { double TotalCp=0.0; double SweepS, SweepE; if (AtStart) { // Flow is (+) into pipe double Vel=IOFlw[0].dQvG/GTZ((1-IOFlw[0].sLiqVolFrac)*Area()); SweepS=0.0; SweepE=GEZ(-Vel*dTime); } else { // Flow is (+) into pipe double Vel=IOFlw[1].dQvG/GTZ((1-IOFlw[1].sLiqVolFrac)*Area()); double SweepL=GEZ(Vel*dTime); SweepS=dLength-SweepL; SweepE=dLength; } for (int sg=0; sg<NFullGSegs(); sg++) { TPPGSegment &Sg=*GasSeg[sg]; double SegS=GSegStart(sg); double SegE=GSegEnd(sg); double SegL=SegE-SegS; if (SegE<SweepS) continue; if (SegS>SweepE) break; double Portion=CalcPortion(SegS, SegE, SweepS, SweepE); double Gm=Portion*Sg.dMass; double GasCp=Gm*FdProps.dGasCp; double FdTemp=Sg.Temp(); MixTemp=(MixTemp*TotalCp+FdTemp*GasCp)/GTZ(TotalCp+GasCp); GasMass+=Gm; TotalCp+=GasCp; } if (AtStart) { double Vel=IOFlw[0].dQvL/GTZ((IOFlw[0].sLiqVolFrac)*Area()); SweepS=0.0; SweepE=GEZ(-Vel*dTime); } else { double Vel=IOFlw[1].dQvL/GTZ((IOFlw[1].sLiqVolFrac)*Area()); double SweepL=GEZ(Vel*dTime); SweepS=dLength-SweepL; SweepE=dLength; } for (sg=0; sg<NFullLSegs(); sg++) { TPPLSegment &Sg=*LiqSeg[sg]; double SegS=LSegStart(sg); double SegE=LSegEnd(sg); double SegL=SegE-SegS; if (SegE<SweepS) continue; if (SegS>SweepE) break; double Portion=CalcPortion(SegS, SegE, SweepS, SweepE); double Lm=Portion*Sg.dMass; double LiqCp=Lm*FdProps.dLiqCp; // kJ/C double FdTemp=Sg.Temp(); MixTemp=(MixTemp*TotalCp+FdTemp*LiqCp)/GTZ(TotalCp+LiqCp); LiqMass+=Lm; TotalCp+=LiqCp; } } //-------------------------------------------------------------------------- void TwoPhasePipe::LiqMassInSegs(double SegS, double SegE, double &LiqMass, double &LiqTemp, TPPLiqProps & LProps) { //double MxTemp=Std_T; //double GasMass=0.0; //LiqMass=0.0; //LProps.InitSum(); //LProps).Sum(Sg.GProps, GasMass); int lsg=0; for (;;) { TPPLSegment & LSg=*LiqSeg[lsg]; double LSegS=LSegStart(lsg); double LSegE=LSegEnd(lsg); double Portion=CalcPortion(LSegS, LSegE, SegS, SegE); double Lm=Portion*LSg.dMass; // TPPProps LProps; // LProps=LSg.LProps; AddMass(LiqMass, LiqTemp, LProps, Lm, LSg.dTemp, LSg.LProps); if (LSegE>=SegE || lsg>=LastFullLSeg()) break; lsg++; } // double LVol=GEZ(LiqMass)/Sg.MxProps.dLiqDens; // double GVol=Max(1.0e-6, GSegLength(sg)*dArea-LVol); // // Sg.dVapFrac=GEZ(GasMass)/GTZ(LiqMass+GasMass); // Sg.dLiqMass=LiqMass; // Sg.GProps.dGasDens=GEZ(GasMass)/GTZ(GVol); // // Not Good // Sg.MxProps.dGasDens=Sg.GProps.dGasDens; // Sg.dPress=Sg.GProps.dGasDens/GTZ(Sg.GProps.dNormGasDens)*Std_P*MxTemp /*Sg.dTemp*/ /Std_T; } //-------------------------------------------------------------------------- void TwoPhasePipe::CalcPressures(double dTime) { #if dbgPipeline if (dbgCalcPress() && fDoDbgBrk) dbgpln("CalcPress %s", FullObjTag()); #endif if (NoFlwIOs()==0) return; #if dbgPipeline if (dbgPosition() && fDoDbgBrk) { for (int sg=0; sg<NFullGSegs(); sg++) dbgpln("GSeg %3i P:%14.6g M:%14.6g T:%14.6g L:%14.6g", sg, GasSeg[sg]->dPosition, GasSeg[sg]->dMass, GasSeg[sg]->dTemp, GSegLength(sg)); for (sg=0; sg<NFullLSegs(); sg++) dbgpln("LSeg %3i P:%14.6g M:%14.6g T:%14.6g L:%14.6g", sg, LiqSeg[sg]->dPosition, LiqSeg[sg]->dMass, LiqSeg[sg]->dTemp, LSegLength(sg)); } #endif // Init Section & Joins int lsg=0; for (int sg=0; sg<NFullGSegs(); sg++) { TPPGSegment &Sg=*GasSeg[sg]; double GasMass=Sg.dMass; double MxTemp=Sg.dTemp; double LiqMass=0.0; //double LiqTemp=Std_T; Sg.MxProps.InitSum(); Sg.MxProps.GP().Sum(Sg.GProps, GasMass); double GSegS=GSegStart(sg); double GSegE=GSegEnd(sg); for (;;) { TPPLSegment & LSg=*LiqSeg[lsg]; double LSegS=LSegStart(lsg); double LSegE=LSegEnd(lsg); double Portion=CalcPortion(LSegS, LSegE, GSegS, GSegE); double Lm=Portion*LSg.dMass; TPPProps LProps; LProps=LSg.LProps; AddMass(GasMass, LiqMass, MxTemp, Sg.MxProps, 0.0, Lm, LSg.dTemp, LProps); if (LSegE>=GSegE || lsg>=LastFullLSeg()) break; lsg++; } double LVol=GEZ(LiqMass)/Sg.MxProps.dLiqDens; #if PressCalc1 double GVol=Max(1.0e-6, GSegLength(sg)*dArea); #else double GVol=Max(1.0e-6, GSegLength(sg)*dArea-LVol); #endif Sg.dVapFrac=GEZ(GasMass)/GTZ(LiqMass+GasMass); Sg.dLiqMass=LiqMass; Sg.GProps.dGasDens=Max(1.0e-3, GEZ(GasMass)/GTZ(GVol)); // Not Good Sg.MxProps.dGasDens=Sg.GProps.dGasDens; Sg.dPress=Sg.GProps.dGasDens/GTZ(Sg.GProps.dNormGasDens)*Std_P*MxTemp /*Sg.dTemp*/ /Std_T; if (sg==0) IOFlw[0].dVapFrac=Sg.dVapFrac; else if (sg==LastFullGSeg()) IOFlw[1].dVapFrac=Sg.dVapFrac; if (sg==0) Sg.dPressGrad=0.0; else { TPPGSegment &Sg0=*GasSeg[sg-1]; double Len=GSegMid(sg)-GSegMid(sg-1); Sg.dPressGrad=(Sg0.dPress-Sg.dPress)/GTZ(Len); if (fabs(Sg.dPressGrad)>1.0e6) { int xxx=0; } } #if dbgPipeline if (dbgCalcPress() && fDoDbgBrk) dbgpln("Sg %3i %3i : T:%12.3f Gm:%14.6f Lm:%14.6f Gv:%14.6f Lv:%14.6f Vf:%14.6f Gd:%14.6f P:%14.6f Pgr:%14.6f", sg,lsg, Sg.dTemp, GasMass, LiqMass, GVol, LVol, Sg.dVapFrac, Sg.GProps.dGasDens, Sg.dPress, Sg.dPressGrad); #endif } // Init Section & Joins int gsg=0; for (sg=0; sg<NFullLSegs(); sg++) { TPPLSegment &Sg=*LiqSeg[sg]; double LiqMass=Sg.dMass; double MxTemp=Sg.dTemp; double GasMass=0.0; //double LiqTemp=Std_T; Sg.MxProps.InitSum(); Sg.MxProps.LP().Sum(Sg.LProps, LiqMass); double LSegS=LSegStart(sg); double LSegE=LSegEnd(sg); for (;;) { TPPGSegment & GSg=*GasSeg[gsg]; double GSegS=GSegStart(gsg); double GSegE=GSegEnd(gsg); double Portion=CalcPortion(GSegS, GSegE, LSegS, LSegE); double Gm=Portion*GSg.dMass; TPPProps GProps; GProps=GSg.GProps; AddMass(GasMass, LiqMass, MxTemp, Sg.MxProps, Gm, 0.0, GSg.dTemp, GProps); if (GSegE>=LSegE || gsg>=LastFullGSeg()) break; gsg++; } double LVol=GEZ(LiqMass)/Sg.MxProps.dLiqDens; #if PressCalc1 double GVol=Max(1.0e-6, LSegLength(sg)*dArea); #else double GVol=Max(1.0e-6, LSegLength(sg)*dArea-LVol); #endif Sg.dVapFrac=GEZ(GasMass)/GTZ(LiqMass+GasMass); Sg.dGasMass=GasMass; //Sg.GProps.dGasDens=GEZ(GasMass)/GTZ(GVol); // Not Good Sg.MxProps.dGasDens=Max(1.0e-3, GEZ(GasMass)/GTZ(GVol));//GProps.dGasDens; //Sg.dPress=Sg.GProps.dGasDens/GTZ(Sg.GProps.dNormGasDens)*Std_P*MxTemp /*Sg.dTemp*/ /Std_T; // if (sg==0) // IOFlw[0].dVapFrac=Sg.dVapFrac; // else if (sg==LastFullGSeg()) // IOFlw[1].dVapFrac=Sg.dVapFrac; // if (sg==0) // Sg.dPressGrad=0.0; // else // { // TPPGSegment &Sg0=*GasSeg[sg-1]; // double Len=GSegMid(sg)-GSegMid(sg-1); // Sg.dPressGrad=(Sg0.dPress-Sg.dPress)/GTZ(Len); // if (fabs(Sg.dPressGrad)>1.0e6) // { // int xxx=0; // } // } #if dbgPipeline if (dbgCalcPress() && fDoDbgBrk) dbgpln("Sg %3i %3i : T:%12.3f Gm:%14.6f Lm:%14.6f Gv:%14.6f Lv:%14.6f Vf:%14.6f", sg,gsg, Sg.dTemp, GasMass, LiqMass, GVol, LVol, Sg.dVapFrac);//, Sg.GProps.dGasDens); #endif } int GIndex=1; int LIndex=1; for (int j=0; j<NJoins(); j++) { double Pos=JoinPos(j); while (GIndex<LastFullGSeg() && GSegMid(GIndex)<Pos) GIndex++; while (LIndex<LastFullLSeg() && LSegMid(LIndex)<Pos) LIndex++; double L0=GSegMid(GIndex-1); double L1=GSegMid(GIndex); double Prs0=GasSeg[GIndex-1]->dPress; double Prs1=GasSeg[GIndex]->dPress; Join[j]->dMeasP=Prs0+(Prs1-Prs0)*(Pos-L0)/(L1-L0); double Tmp0=GasSeg[GIndex-1]->dTemp; double Tmp1=GasSeg[GIndex]->dTemp; Join[j]->dMeasT=Tmp0+(Tmp1-Tmp0)*(Pos-L0)/(L1-L0); double GVel0=(GIndex>1) ? GasSeg[GIndex-1]->dGasVelo : IOFlw[0].dGasVelo; double GVel1=GasSeg[GIndex]->dGasVelo; Join[j]->dMeasGasVel=GVel0+(GVel1-GVel0)*(Pos-L0)/(L1-L0); double LVel0=(LIndex>1) ? LiqSeg[LIndex-1]->dLiqVelo : IOFlw[0].dLiqVelo; double LVel1=LiqSeg[LIndex]->dLiqVelo; Join[j]->dMeasLiqVel=LVel0+(LVel1-LVel0)*(Pos-L0)/(L1-L0); Join[j]->bMeasHorFlowRegime=GasSeg[GIndex]->bHorFlowRegime; Join[j]->bMeasFlowRegime=GasSeg[GIndex]->bFlowRegime; } }; //-------------------------------------------------------------------------- void TwoPhasePipe::CreateSlug(double SlugPos, double SlugVol) { // Find Segment // NB Two slugs cannot adjoin each other for (int sg=1; sg<NFullLSegs()-1; sg++) { TPPLSegment &Sg=*LiqSeg[sg]; if (LSegEnd(sg)>SlugPos) { if (!IsSlug(sg)) { double SegS=LSegStart(sg); double SegE=LSegEnd(sg); double SegL=SegE-SegS; if (SegL>0.5*MeanSegLength()) { double SegLMass=Sg.dMass; double SlugMass=SlugVol*Sg.LProps.dLiqDens; SlugMass=Min(0.5*SegLMass, Min(SlugVol, SegL*dArea)*Sg.LProps.dLiqDens); SlugVol=1.05*SlugMass/Sg.LProps.dLiqDens; double SlugLen=SlugVol/dArea; //if (SegL>3.0*SlugLen) { // Must keep Gas between Slugs if (!IsSlug(sg-1) && SlugPos<SegS+0.33*SegL) { SlugPos=SegS; TPPLSegment *pL=new TPPLSegment(SlugPos, Sg.dVelocity, SlugMass, Sg.dTemp, Sg.LProps, Sg.pImg); pL->iPos->SetTestValue(dLength); LiqSeg.InsertAt(sg, pL); SegsChanged(); Sg.dPosition+=SlugLen; Sg.dMass-=SlugMass; } else if (IsSlug(sg+1) && SlugPos>SegS+0.67*SegL) { if ((sg+1)<NFullLSegs() && !IsSlug(sg+1)) { SlugPos=SegE-SlugLen; TPPLSegment *pL=new TPPLSegment(SlugPos, Sg.dVelocity, SlugMass, Sg.dTemp, Sg.LProps, Sg.pImg); pL->iPos->SetTestValue(dLength); LiqSeg.InsertAt(sg+1, pL); SegsChanged(); Sg.dMass-=SlugMass; } } else { // Split This Segment double HalfSegLMass=0.5*(SegLMass-SlugMass); double HalfSegLen=0.5*(SegL-SlugLen); double Seg0Pos=Sg.dPosition+HalfSegLen; double Seg1Pos=Seg0Pos+SlugLen; TPPLSegment *pL0=new TPPLSegment(Seg0Pos, Sg.dVelocity, SlugMass, Sg.dTemp, Sg.LProps, Sg.pImg); TPPLSegment *pL1=new TPPLSegment(Seg1Pos, Sg.dVelocity, HalfSegLMass, Sg.dTemp, Sg.LProps, Sg.pImg); pL0->iPos->SetTestValue(dLength); pL1->iPos->SetTestValue(dLength); LiqSeg.InsertAt(sg+1, pL0); LiqSeg.InsertAt(sg+2, pL1); SegsChanged(); Sg.dMass=HalfSegLMass; } } } } break; } } } //-------------------------------------------------------------------------- int TwoPhasePipe::RemoveSlug(int iSlug) { TPPLSegment &Sg=*LiqSeg[iSlug]; double SlugLen = LSegLength(iSlug); double LostMass = dSlugReduction*Sg.dMass; double LostLen = dSlugReduction*SlugLen; if (iSlug>0 && (SlugLen-LostLen<dSlugMinLen)) { // kill this slug TPPLSegment &Prv=*LiqSeg[iSlug-1]; Prv.dMass+=Sg.dMass; Prv.LProps.InitSum(Prv.dMass); Prv.LProps.Sum(Sg.LProps, Sg.dMass); // Assume Props OK && TempOK delete LiqSeg[iSlug]; LiqSeg.RemoveAt(iSlug); SegsChanged(); return True; } else { // reduce slug len TPPLSegment &Prv=*LiqSeg[iSlug-1]; Prv.dMass+=LostMass; Sg.dMass-=LostMass; Sg.dPosition+=LostLen; } return False; } //-------------------------------------------------------------------------- int TwoPhasePipe::CombineLSegs(int iSeg0, int iSeg1) { TPPLSegment &Sg0=*LiqSeg[iSeg0]; TPPLSegment &Sg1=*LiqSeg[iSeg1]; // kill this slug //Sg0.dMass+=Sg1.dMass; AddMass(Sg0.dMass, Sg0.dTemp, Sg0.LProps, Sg1.dMass, Sg1.dTemp, Sg1.LProps); Sg0.LProps.InitSum(Sg0.dMass); Sg0.LProps.Sum(Sg1.LProps, Sg1.dMass); delete LiqSeg[iSeg1]; LiqSeg.RemoveAt(iSeg1); SegsChanged(); return True; } //-------------------------------------------------------------------------- void TwoPhasePipe::EvaluateSegment(double dTime) { //Add New Existing slugs around if (NGSegments()<2) return; #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("EvaluateSegment : ========%14.2g %s", dTime, FullObjTag()); #endif for (int sg=0; sg<NGSegments(); sg++) GasSeg[sg]->iAge++; for (sg=0; sg<NLSegments(); sg++) LiqSeg[sg]->iAge++; if (1) { for (int iG=0; iG<NGSegments()-1; iG++) { if (GSegLength(iG)<SegMergeFactor*MeanSegLength()) { int xxx=0; } } for (int iL=0; iL<NLSegments()-1; iL++) { if (LSegLength(iL)<0.1*SegMergeFactor*MeanSegLength()) { double lll=LSegLength(iL); TPPLSegment &L=LSeg(iL); int xxx=0; } } } // Remove short segments at ends / merge at Start SetGSegStart(0, 0.0); while (NGSegments()>MinNSegs && GSegLength(0)<SegMergeFactor*MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Gas Seg %i", 1); #endif TPPGSegment &SgRemove =*GasSeg[0]; TPPGSegment &SgKeep =*GasSeg[1]; AddMass(SgKeep.dMass, SgKeep.dTemp, SgKeep.GProps, SgRemove.dMass, SgRemove.dTemp, SgRemove.GProps); delete GasSeg[0]; GasSeg.RemoveAt(0); SegsChanged(); } while (LSegEnd(0)<0.0) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Liq Seg %i", 1); #endif delete LiqSeg[0]; LiqSeg.RemoveAt(0); SegsChanged(); } while (LSegStart(NLSegments()-1)>Length()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Liq Seg %i", 1); #endif delete LiqSeg[NLSegments()-1]; LiqSeg.RemoveAt(NLSegments()-1); SegsChanged(); } SetLSegStart(0, 0.0); SetLSegStart(NLSegments()-1, Length()); while (NLSegments()>MinNSegs && LSegLength(0)<0.1*SegMergeFactor*MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Liq Seg %i", 1); #endif TPPLSegment &SgRemove =*LiqSeg[0]; TPPLSegment &SgKeep =*LiqSeg[1]; AddMass(SgKeep.dMass, SgKeep.dTemp, SgKeep.LProps, SgKeep.dMass*Range(0., LSegLength(0)/LSegLength(1), 1.0), SgRemove.dTemp, SgRemove.LProps); delete LiqSeg[0]; LiqSeg.RemoveAt(0); SegsChanged(); } // Remove short segments at ends / merge at Exit while (NGSegments()>MinNSegs && GSegLength(LastFullGSeg())<SegMergeFactor*MeanSegLength()) { int iLFGSg = LastFullGSeg(); #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Gas Seg %i L:%8.2f Msl:%8.2f", iLFGSg, GSegLength(LastFullGSeg()), MeanSegLength()); #endif TPPGSegment &SgKeep =*GasSeg[iLFGSg-1]; TPPGSegment &SgRemove =*GasSeg[iLFGSg]; AddMass(SgKeep.dMass, SgKeep.dTemp, SgKeep.GProps, SgRemove.dMass, SgRemove.dTemp, SgRemove.GProps); delete GasSeg[iLFGSg]; GasSeg.RemoveAt(iLFGSg); SegsChanged(); } while (NLSegments()>MinNSegs && LSegLength(LastFullLSeg())<0.1*SegMergeFactor*MeanSegLength()) { int iLFLSg=LastFullLSeg(); #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Remove Liq Seg %i L:%8.2f Msl:%8.2f", iLFLSg, LSegLength(iLFLSg), MeanSegLength()); #endif TPPLSegment &SgKeep=*LiqSeg[iLFLSg-1]; TPPLSegment &SgRemove=*LiqSeg[iLFLSg]; AddMass(SgKeep.dMass, SgKeep.dTemp, SgKeep.LProps, SgKeep.dMass*Range(0., LSegLength(iLFLSg)/LSegLength(iLFLSg-1), 1.0), SgRemove.dTemp, SgRemove.LProps); delete LiqSeg[iLFLSg]; LiqSeg.RemoveAt(iLFLSg); SegsChanged(); } if (GSegLength(0) > SegSplitFactor * MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Add GasSeg Start L:%8.2f Msl:%8.2f", GSegLength(0), MeanSegLength()); #endif TPPLiqProps LProps0; TPPLiqProps LProps1; double LiqMass0=0.0; double LiqTemp0=0.0; double LiqMass1=0.0; double LiqTemp1=0.0; LiqMassInSegs(GSegStart(0), GSegMid(0), LiqMass0, LiqTemp0, LProps0); LiqMassInSegs(GSegMid(0), GSegEnd(0), LiqMass1, LiqTemp1, LProps1); double LiqVol0=LiqMass0/GTZ(LProps0.dLiqDens); double LiqVol1=LiqMass1/GTZ(LProps1.dLiqDens); #if PressCalc1 double GasVol0=0.5*GSegLength(0)*dArea; double GasVol1=0.5*GSegLength(0)*dArea; #else double GasVol0=0.5*GSegLength(0)*dArea-LiqVol0; double GasVol1=0.5*GSegLength(0)*dArea-LiqVol1; #endif double GasVolM=0.5*(GasVol0+GasVol1); TPPGSegment &Sg0 =*GasSeg[0]; TPPGSegment &Sg1 =*GasSeg[1]; // Add new segment double Scl0, Scl1; double TM0 = Temperature(0.25 * GSegEnd(0)); double TMM = Temperature(0.50 * GSegEnd(0)); double TM1 = Temperature(0.75 * GSegEnd(0)); double PM0 = Pressure(0.25 * GSegEnd(0)); double PMM = Pressure(0.50 * GSegEnd(0)); double PM1 = Pressure(0.75 * GSegEnd(0)); double X0 = PM0/GTZ(TM0); double X1 = PM1/GTZ(TM1); Scl0=X0/GTZ(X0+X1)*GasVol0/GTZ(GasVolM); //Scl0 = 0.5 * PM0/GTZ(PMM)*TMM/GTZ(TM0)*GasVol0/GTZ(GasVolM); Scl1 = 1.0 - Scl0; TPPGSegment *pG = new TPPGSegment(0.0, 0.0/*Sg0.Velocity()*/, Scl0*Sg0.dMass, TM0, Sg0.GProps, Sg0.pImg); TPPGSegment &SgN=*pG; SgN.iPos->SetTestValue(dLength); Sg0.dMass*=Scl1; Sg0.dTemp=TM1; Sg0.SetPosition(0.5*GSegLength(0)); // should be Assignment operator Sg0.bHorFlowRegime = Sg1.bHorFlowRegime; Sg0.bFlowRegime = Sg1.bFlowRegime; // Sg0.dQmRng = Sg1.dQmRng; Sg0.dQmEst = Sg1.dQmEst; Sg0.dQmG = Sg1.dQmG; Sg0.dQmL = Sg1.dQmL; Sg0.dQvG = Sg1.dQvG; Sg0.dQvL = Sg1.dQvL; Sg0.dVapFrac = Sg1.dVapFrac; Sg0.sLiqVolFrac = Sg1.sLiqVolFrac; Sg0.dDarcyCorrection = Sg1.dDarcyCorrection; Sg0.dSupGasVel = Sg1.dSupGasVel; Sg0.dSupLiqVel = Sg1.dSupLiqVel; Sg0.dTotalVel = Sg1.dTotalVel; Sg0.dDPq = Sg1.dDPq; Sg0.dDPqDq = Sg1.dDPqDq; Sg0.dDPmB = Sg1.dDPmB; Sg0.dDPmQ = Sg1.dDPmQ; Sg0.dDPmDq = Sg1.dDPmDq; Sg0.dDPApplied = Sg1.dDPApplied; Sg0.dDPz = Sg1.dDPz; Sg0.dVelStart = Sg1.dVelStart; Sg0.dGasVelo = Sg1.dGasVelo; Sg0.dLiqVelo = Sg1.dLiqVelo; Sg0.dVelocity = Sg1.dVelocity; GasSeg.InsertAt(0, pG); SegsChanged(); } if (LSegLength(0) > SegSplitFactor * MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Add LiqSeg Start L:%8.2f Msl:%8.2f", LSegLength(0), MeanSegLength()); #endif TPPLSegment &Sg0 =*LiqSeg[0]; TPPLSegment &Sg1 =*LiqSeg[1]; // Add new segment double TM0 = Temperature(0.25 * LSegEnd(0)); double TMM = Temperature(0.50 * LSegEnd(0)); double TM1 = Temperature(0.75 * LSegEnd(0)); double Scl0, Scl1; Scl0 = 0.5; Scl1 = 1.0 - Scl0; TPPLSegment *pL = new TPPLSegment(0.0, 0.0, Scl0*Sg0.dMass, TM0, Sg0.LProps, Sg0.pImg); TPPLSegment &SgN=*pL; SgN.iPos->SetTestValue(dLength); Sg0.dMass*=Scl1; Sg0.dTemp*=TM1; Sg0.SetPosition(0.5*LSegLength(0)); Sg0.bHorFlowRegime = Sg1.bHorFlowRegime; Sg0.bFlowRegime = Sg1.bFlowRegime; // Sg0.dQmRng = Sg1.dQmRng; Sg0.dQmEst = Sg1.dQmEst; Sg0.dQmG = Sg1.dQmG; Sg0.dQmL = Sg1.dQmL; Sg0.dQvG = Sg1.dQvG; Sg0.dQvL = Sg1.dQvL; Sg0.dVapFrac = Sg1.dVapFrac; Sg0.sLiqVolFrac = Sg1.sLiqVolFrac; Sg0.dDarcyCorrection = Sg1.dDarcyCorrection; Sg0.dSupGasVel = Sg1.dSupGasVel; Sg0.dSupLiqVel = Sg1.dSupLiqVel; Sg0.dTotalVel = Sg1.dTotalVel; Sg0.dDPq = Sg1.dDPq; Sg0.dDPqDq = Sg1.dDPqDq; Sg0.dDPmB = Sg1.dDPmB; Sg0.dDPmQ = Sg1.dDPmQ; Sg0.dDPmDq = Sg1.dDPmDq; Sg0.dDPApplied = Sg1.dDPApplied; Sg0.dDPz = Sg1.dDPz; Sg0.dVelStart = Sg1.dVelStart; Sg0.dGasVelo = Sg1.dGasVelo; Sg0.dLiqVelo = Sg1.dLiqVelo; Sg0.dVelocity = Sg1.dVelocity; LiqSeg.InsertAt(0, pL); SegsChanged(); } if (GSegLength(LastFullGSeg()) > SegSplitFactor * MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Add GasSeg End L:%8.2f Msl:%8.2f", GSegLength(LastFullGSeg()), MeanSegLength()); #endif TPPLiqProps LProps0; TPPLiqProps LProps1; double LiqMass0=0.0; double LiqTemp0=0.0; double LiqMass1=0.0; double LiqTemp1=0.0; LiqMassInSegs(GSegStart(LastFullGSeg()), GSegMid(LastFullGSeg()), LiqMass0, LiqTemp0, LProps0); LiqMassInSegs(GSegMid(LastFullGSeg()), GSegEnd(LastFullGSeg()), LiqMass1, LiqTemp1, LProps1); double LiqVol0=LiqMass0/GTZ(LProps0.dLiqDens); double LiqVol1=LiqMass1/GTZ(LProps1.dLiqDens); #if PressCalc1 double GasVol0=0.5*GSegLength(LastFullGSeg())*dArea; double GasVol1=0.5*GSegLength(LastFullGSeg())*dArea; #else double GasVol0=0.5*GSegLength(LastFullGSeg())*dArea-LiqVol0; double GasVol1=0.5*GSegLength(LastFullGSeg())*dArea-LiqVol1; #endif double GasVolM=0.5*(GasVol0+GasVol1); // TPPGSegment &Sg0 =*GasSeg[LastFullGSeg()-1]; TPPGSegment &Sg0 =*GasSeg[LastFullGSeg()]; double PosS=GSegStart(LastFullGSeg()); double Pos0=PosS + 0.25 * GSegLength(LastFullGSeg()); double PosM=PosS + 0.50 * GSegLength(LastFullGSeg()); double Pos1=PosS + 0.75 * GSegLength(LastFullGSeg()); // Add new segment double Scl0, Scl1; double TM0 = Temperature(Pos0); double TMM = Temperature(PosM); double TM1 = Temperature(Pos1); double PM0 = Pressure(Pos0); double PMM = Pressure(PosM); double PM1 = Pressure(Pos1); double X0 = PM0/GTZ(TM0); double X1 = PM1/GTZ(TM1); Scl0=X0/GTZ(X0+X1)*GasVol0/GTZ(GasVolM); //Scl0 = 0.5 * PM0/GTZ(PMM)*TMM/GTZ(TM0)*GasVol0/GTZ(GasVolM); Scl1 = 1.0 - Scl0; TPPGSegment *pG = new TPPGSegment(PosM, Sg0.Velocity(), Scl1*Sg0.dMass, TM1, Sg0.GProps, Sg0.pImg); TPPGSegment &SgN=*pG; SgN.iPos->SetTestValue(dLength); Sg0.dMass*=Scl0; Sg0.dTemp=TM0; //0.SetPosition(0.5*GSegEnd(0)); // should be Assignment operator SgN.bHorFlowRegime = Sg0.bHorFlowRegime; SgN.bFlowRegime = Sg0.bFlowRegime; // Sg0.dQmRng = Sg1.dQmRng; SgN.dQmEst = Sg0.dQmEst; SgN.dQmG = Sg0.dQmG; SgN.dQmL = Sg0.dQmL; SgN.dQvG = Sg0.dQvG; SgN.dQvL = Sg0.dQvL; SgN.dVapFrac = Sg0.dVapFrac; SgN.sLiqVolFrac = Sg0.sLiqVolFrac; SgN.dDarcyCorrection = Sg0.dDarcyCorrection; SgN.dSupGasVel = Sg0.dSupGasVel; SgN.dSupLiqVel = Sg0.dSupLiqVel; SgN.dTotalVel = Sg0.dTotalVel; SgN.dDPq = Sg0.dDPq; SgN.dDPqDq = Sg0.dDPqDq; SgN.dDPmB = Sg0.dDPmB; SgN.dDPmQ = Sg0.dDPmQ; SgN.dDPmDq = Sg0.dDPmDq; SgN.dDPApplied = Sg0.dDPApplied; SgN.dDPz = Sg0.dDPz; SgN.dVelStart = Sg0.dVelStart; SgN.dGasVelo = Sg0.dGasVelo; SgN.dLiqVelo = Sg0.dLiqVelo; SgN.dVelocity = Sg0.dVelocity; GasSeg.InsertAt(LastFullGSeg()+1, pG); SegsChanged(); } if (LSegLength(LastFullLSeg()) > SegSplitFactor * MeanSegLength()) { #if dbgPipeline if (dbgAddSegs() && fDoDbgBrk) dbgpln("Add LiqSeg End L:%8.2f Msl:%8.2f", LSegLength(LastFullLSeg()), MeanSegLength()); #endif TPPLSegment &Sg0 =*LiqSeg[LastFullLSeg()]; //TPPLSegment &Sg1 =*LiqSeg[1]; // Add new segment double PosS=LSegStart(LastFullLSeg()); double Pos0=PosS + 0.25 * LSegLength(LastFullLSeg()); double PosM=PosS + 0.50 * LSegLength(LastFullLSeg()); double Pos1=PosS + 0.75 * LSegLength(LastFullLSeg()); double TM0 = Temperature(Pos0); double TMM = Temperature(PosM); double TM1 = Temperature(Pos1); double Scl0, Scl1; Scl0 = 0.5; Scl1 = 1.0 - Scl0; TPPLSegment *pL = new TPPLSegment(PosM, Sg0.Velocity(), Scl1*Sg0.dMass, TM1, Sg0.LProps, Sg0.pImg); TPPLSegment &SgN=*pL; SgN.iPos->SetTestValue(dLength); Sg0.dMass*=Scl0; Sg0.dTemp*=TM0; //Sg0.SetPosition(0.5*LSegEnd(0)); SgN.dVelocity = Sg0.dVelocity; LiqSeg.InsertAt(LastFullLSeg()+1, pL); SegsChanged(); } if (dTime>0.0 && nSlugs<nMaxSlugs) { for (int s=0; s<NFullGSegs(); s++) { TPPGSegment &Sg=*GasSeg[s]; // Add to number of slugs slugs if neccessary if ((dTime>0.0) && (Sg.bFlowRegime==TPR_Slug)) { if (((float)rand())/RAND_MAX<dSlugAppears) { double SlugPos=GSegStart(s)+((double)rand())/RAND_MAX*GSegLength(s); double SlugVol=((float)rand())/RAND_MAX*dMaxSlugVolume; CreateSlug(SlugPos, SlugVol); } } } for (int sg=1; sg<NFullLSegs()-1; ) { TPPLSegment &Sg=*LiqSeg[sg]; if (IsSlug(sg) && LSegEnd(sg)<dLength) if (GasSeg[GSegIndex(Sg.Position())]->bFlowRegime!=TPR_Slug) if (RemoveSlug(sg)) continue; sg++; } // double SegCombineLen=MeanSegLength(); // for (sg=1; sg<NFullLSegs()-1; ) // { // TPPLSegment &Sg=*LiqSeg[sg]; // if ((LSegLength(sg)+LSegLength(sg+1))<SegCombineLen && !IsSlug(sg) && !IsSlug(sg+1)) // if (CombineLSegs(sg, sg+1)) // continue; // sg++; // } } nSlugs=0; dTotLiqHoldup=0.0; for (int s=0; s<Sect.GetSize(); s++) { TPPSection &Sct=Sect[s]; Sct.nSlugs=0; Sct.dTotLiqHoldup=0.0; } for (sg=0; sg<NFullLSegs(); sg++) { TPPLSegment &Sg=*LiqSeg[sg]; double SegS=LSegStart(sg); double SegE=LSegEnd(sg); double SegL=GTZ(SegE-SegS); int Sct0=SectIndex(SegS); int Sct1=SectIndex(SegE); // Buildup Mass in sections; for (int s=Sct0; s<=Sct1; s++) { double Portion=GEZ(Min(SectionEnd(s), SegE)-Max(SectionStart(s), SegS))/GTZ(SegE-SegS); TPPSection & Sct=Sect[s]; double LiqVolume=Portion*Sg.dMass/Sg.LProps.dLiqDens; Sect[s].dTotLiqHoldup+=LiqVolume; dTotLiqHoldup+=LiqVolume; } if (IsSlug(sg)) { Sect[Sct0].nSlugs++; nSlugs++; } } Strng Tg; for (sg=0; sg<NGSegments(); sg++) { GSeg(sg).iPos->Tag().Set("%s.GSPos_%i",sTag(),sg); //GSeg(sg).iPos->TagIs(Tg()); GSeg(sg).iTemp->Tag().Set("%s.GSTmp_%i",sTag(),sg); //GSeg(sg).iTemp->TagIs(Tg()); GSeg(sg).iMass->Tag().Set("%s.GSMas_%i",sTag(),sg); //GSeg(sg).iMass->TagIs(Tg()); } for (sg=0; sg<NLSegments(); sg++) { LSeg(sg).iPos->Tag().Set("%s.LSPos_%i",sTag(),sg); //LSeg(sg).iPos->TagIs(Tg()); LSeg(sg).iTemp->Tag().Set("%s.LSTmp_%i",sTag(),sg); //LSeg(sg).iTemp->TagIs(Tg()); LSeg(sg).iMass->Tag().Set("%s.LSMas_%i",sTag(),sg); //LSeg(sg).iMass->TagIs(Tg()); } } //-------------------------------------------------------------------------- void TwoPhasePipe::StartSolution() { if (bSimple) { MN_Lnk::StartSolution(); return; } MdlNode::StartSolution(); EvaluateSegment(0.0); } //-------------------------------------------------------------------------- void TwoPhasePipe::StartStep() { if (bSimple) { MN_Lnk::StartStep(); return; } MdlNode::StartStep(); if (fDoSetLinePress) { SetLinePress(); fDoSetLinePress=false; } if (fDoSetLineSlugs) { SetLinePress(); SetLineSegs(True); fDoSetLineSlugs=false; } // if (IOConduit(0)->QMass()>1.0e-10) // FlowImg.QSetM(*IOConduit(0), som_ALL, IOConduit(0)->QMass(), IOP_Self(0)); if (IOQmEst_In(0)>0 && IOConduit(0)->QMass()>1.0e-10) { FlowImg.QSetM(*IOConduit(0), som_ALL, IOConduit(0)->QMass(), IOP_Self(0)); GasSeg[0]->pImg->QCopy(*IOConduit(0));//->Model()); LiqSeg[0]->pImg->QCopy(*IOConduit(0));//->Model()); } if (IOQmEst_In(1)>0 && IOConduit(1)->QMass()>1.0e-10) { FlowImg.QSetM(*IOConduit(1), som_ALL, IOConduit(1)->QMass(), IOP_Self(1)); GasSeg[LastFullGSeg()]->pImg->QCopy(*IOConduit(1));//->Model()); LiqSeg[LastFullLSeg()]->pImg->QCopy(*IOConduit(1));//->Model()); } if (FlowImg.QMass()>1.0e-10) { double T=FlowImg.Temp(); double P=FlowImg.Press(); if (FlowImg.QMass(som_Liq)>1.0e-3) { FdProps.dNormGasDens=FlowImg.NRho(som_Vap); FdProps.dGasDens=FlowImg.Rho(som_Vap); SpMArray Vap(FlowImg.MArray(), som_Vap); FdProps.dGasCp=FlowImg.msCp(som_ALL,T,P,&Vap); } if (FlowImg.QMass(som_Liq)>1.0e-3) { FdProps.dLiqDens=FlowImg.Rho(som_Liq); SpMArray Liq(FlowImg.MArray(), som_Liq); FdProps.dLiqCp=FlowImg.msCp(som_ALL,T,P,&Liq); } } for (int sg=0; sg<NFullGSegs(); sg++) GasSeg[sg]->StartStep(); for (sg=0; sg<NFullLSegs(); sg++) LiqSeg[sg]->StartStep(); } // ------------------------------------------------------------------------- void TwoPhasePipe::EvalJoinPressures() { if (bSimple) { MN_Lnk::EvalJoinPressures(); return; } CalcPressures(ICGetTimeIncFromStartOfStep()); Set_IOP_Self(0, GasSeg[0]->dPress); Set_IOP_Self(1, GasSeg[LastFullGSeg()]->dPress); }; // ------------------------------------------------------------------------- flag TwoPhasePipe::EvalFlowEquations(CSpPropInfo *pProps, int IONo, int FE) { if (bSimple) { return MN_Lnk::EvalFlowEquations(IONo, FE); } #if dbgPipeline if (dbgEstDP() && fDoDbgBrk) dbgpln("EvalFlws"); #endif FlwBlk &FB = *IOFB(IONo,0); double QIn = FB.QmSign()*FB.QmMeas(); // pFlwBlk pC = IOFB(IONo); FE_Linear* pEqn=(FE_Linear*)FB.ChangeFlwEqn(&FE_LinearClass); if (typeid(*pEqn)!=typeid(FE_Linear)) { DoBreak(); } int iSg=IONo==0 ? 0 : LastFullGSeg(); TPPFlowStuff &Flw=IOFlw[IONo]; int Sgn=(IONo==0) ? 1 : -1; if (IONo==1) { int xxx=0; } double Len=0.5*GSegLength(iSg); double Angle=IONo==0 ? dAngleS : dAngleE; double Mass=0.5*GasSeg[iSg]->dMass; TPPProps &Props=GasSeg[iSg]->MxProps; Flw.EstimateDP(*this, Props, Len, Angle, Mass, QIn); FB.SetActLength(Len); FB.SetDPq(Flw.dDPq, Flw.dDPqDq); FB.SetDPz(Flw.dDPz, 0.0); // FB.SetDPm(-Sgn*Flw.dDPmB, -Sgn*Flw.dDPmQ, -Sgn*Flw.dDPmDq); FB.SetArea(dArea); FB.SetMomentum(/*IC,*/ Max(10.0, FlowImg.Rho()*4.0)); // *4 is a kludge FB.SetQmFree(); // if (IONo==1) // { //dbgpln("-- L:%11.4g M:%11.4g P:%11.4g Q:%11.4g dPq:%11.4g dPmB:%11.4g DPApp:%11.4g Rho:%11.4g", // Len, Mass, GasSeg[LastFullGSeg()]->dPress, QIn, Flw.dDPq, FB.DPmB(), Flw.dDPApplied, Props.dGasDens); // } Flw.dDPApplied=Sgn*(IOP_Flng(IONo)-IOP_Self(IONo)); Flw.dQmEst=QIn*Sgn; Flw.SetFlwInfo(*this, Props, QIn*Sgn); return True; }; //-------------------------------------------------------------------------- void TwoPhasePipe::EvalProducts() { if (bSimple) { MN_Lnk::EvalProducts(); return; } int LastFlw=UBSect(); for (int sg=1; sg<NFullGSegs(); sg++) { TPPGSegment &Sg0=*GasSeg[sg-1]; TPPGSegment &Sg1=*GasSeg[sg]; double Len=GSegMid(sg)-GSegMid(sg-1); double Angle=Sect[SectIndex(GSegStart(sg))].dAngle; double Mass=0.5*(Sg0.dMass+Sg1.dMass); TPPProps Mx; Mx.InitSum(); Mx.Sum(Sg0.MxProps, Sg0.dMass, Sg0.dLiqMass); Mx.Sum(Sg1.MxProps, Sg1.dMass, Sg1.dLiqMass); Sg1.EstimateFlows(*this, Mx, Len, Angle, Mass, Sg1.dPressGrad*Len); } for (sg=1; sg<NFullLSegs(); sg++) { TPPLSegment &Sg0=*LiqSeg[sg-1]; TPPLSegment &Sg1=*LiqSeg[sg]; double Pos0=LSegMid(sg-1); double Pos1=LSegMid(sg); double Len=Pos1-Pos0; double Angle=Sect[SectIndex(LSegStart(sg))].dAngle; double Mass=0.5*(Sg0.dMass+Sg1.dMass); double DPress=Pressure(Pos0)-Pressure(Pos1); //if (DPress) TPPProps Mx; Mx.InitSum(); Mx.Sum(Sg0.MxProps, Sg0.dGasMass, Sg0.dMass); Mx.Sum(Sg1.MxProps, Sg1.dGasMass, Sg1.dMass); Sg1.EstimateFlows(*this, Mx, Len, Angle, Mass, DPress); } if (IOQmEst_Out(0)>=0.0) { double GasMass=0.0; double LiqMass=0.0; double MixTemp=Std_T; AddSweptMass(True, ICGetTimeInc(), GasMass, LiqMass, MixTemp); IOConduit(0)->QSetM(*(GasSeg[0]->pImg), som_Vap, GasMass/GTZ(ICGetTimeInc()), IOP_Self(0)); IOConduit(0)->QAddM(*(LiqSeg[0]->pImg), som_Liq, LiqMass/GTZ(ICGetTimeInc())); //IOConduit(0)->QSetM(*(GasSeg[0]->pImg), som_Vap, fabs(IOFlw[0].dQmG), IOP_Self(0)); //IOConduit(0)->QAddM(*(LiqSeg[0]->pImg), som_Liq, fabs(IOFlw[0].dQmL)); //Conduit(0)->SetTemp(MixTemp); IOConduit(0)->SetTemp(GasSeg[0]->dTemp); } dQmGEntry=Sign(IOQmEst_In(0))*IOConduit(0)->QMass(som_Vap); dQmLEntry=Sign(IOQmEst_In(0))*IOConduit(0)->QMass(som_SL); double T0=IOConduit(0)->Temp(); double P0=IOP_Self(0); SpMArray G0(IOConduit(0)->MArray(), som_Vap); SpMArray L0(IOConduit(0)->MArray(), som_Liq); dCpGEntry=IOConduit(0)->msCp(som_ALL,T0, P0, &G0); dCpLEntry=IOConduit(0)->msCp(som_ALL,T0, P0, &L0); dTempEntry=IOConduit(0)->Temp(); if (IOQmEst_Out(1)>=0.0) { double GasMass=0.0; double LiqMass=0.0; double MixTemp=Std_T; AddSweptMass(False, ICGetTimeInc(), GasMass, LiqMass, MixTemp); IOConduit(1)->QSetM(*(GasSeg[LastFullGSeg()]->pImg), som_Vap, GasMass/GTZ(ICGetTimeInc()), IOP_Self(1)); IOConduit(1)->QAddM(*(LiqSeg[LastFullLSeg()]->pImg), som_Liq, LiqMass/GTZ(ICGetTimeInc())); // IOConduit(1)->QSetM(FlowImg, som_Vap, GasMass/GTZ(ICGetTimeInc()), IOP_Self(1)); // IOConduit(1)->QAddM(FlowImg, som_Liq, LiqMass/GTZ(ICGetTimeInc())); // IOConduit(1)->QSetM(*(GasSeg[LastFullGSeg()]->pImg), som_Vap, fabs(IOFlw[1].dQmG), IOP_Self(1)); // IOConduit(1)->QAddM(*(LiqSeg[LastFullLSeg()]->pImg), som_Liq, fabs(IOFlw[1].dQmL)); IOConduit(1)->SetTemp(GasSeg[LastFullGSeg()]->dTemp); } dQmGExit=Sign(IOQmEst_Out(1))*IOConduit(1)->QMass(som_Vap); dQmLExit=Sign(IOQmEst_Out(1))*IOConduit(1)->QMass(som_SL); double T1=IOConduit(1)->Temp(); double P1=IOP_Self(1); SpMArray G1(IOConduit(1)->MArray(), som_Vap); SpMArray L1(IOConduit(1)->MArray(), som_Liq); dCpGExit=IOConduit(1)->msCp(som_ALL,T1, P1, &G1); dCpLExit=IOConduit(1)->msCp(som_ALL,T1, P1, &L1); // dCpGExit=IOConduit(1)->msCp(som_Vap); // dCpLExit=IOConduit(1)->msCp(som_SL); dTempExit=IOConduit(1)->Temp(); }; //-------------------------------------------------------------------------- const int SmoothVelocities = 1; void TwoPhasePipe::EvalDerivs() { if (bSimple) { MN_Lnk::EvalDerivs(); return; } Strng Tg; double SteelMassPerLen=7800.0*PI*(Sqr(dODiam)-Sqr(dDiam))/4.0; for (int sg=0; sg<NGSegments(); sg++) { GSeg(sg).dMassDeriv=0.0; GSeg(sg).dMassTest=Max(1.0, 100.0*GSeg(sg).dMass); GSeg(sg).dTempDeriv=0.0; } for (sg=0; sg<NLSegments(); sg++) { LSeg(sg).dMassDeriv=0.0; LSeg(sg).dMassTest=Max(1.0, 100.0*LSeg(sg).dMass); LSeg(sg).dTempDeriv=0.0; } GSeg(0).dMassDeriv=Max(dQmGEntry, -GSeg(0).dMass/(ICGetTimeInc()*1.5)); LSeg(0).dMassDeriv=Max(dQmLEntry, -LSeg(0).dMass/(ICGetTimeInc()*1.5)); GSeg(LastFullGSeg()).dMassDeriv=Max(-dQmGExit, -GSeg(LastFullGSeg()).dMass/(ICGetTimeInc()*1.5)); LSeg(LastFullLSeg()).dMassDeriv=Max(-dQmLExit, -LSeg(LastFullLSeg()).dMass/(ICGetTimeInc()*1.5)); for (sg=1; sg<NFullGSegs(); sg++) { TPPGSegment &Sg1=GSeg(sg); double V=VelDampC*Sg1.dGasVelo + VelDampE*GasSeg[Max(1, sg-1)]->dGasVelo + VelDampE*GasSeg[Min(NFullGSegs()-1, sg+1)]->dGasVelo; GSeg(sg).SetVelocity(V); #if dbgPipeline if (dbgVelocities() && fDoDbgBrk) dbgpln("SgGVel %3i V:%14.6f", sg, GSeg(sg).dVelocity); else if (fabs(GSeg(sg).dVelocity)>100.0) { dbgpln("LARGE GAS VEL %3i V:%14.6f %s ", sg, GSeg(sg).dVelocity, FullObjTag()); } #endif GSeg(sg).dVelocity=Range(-100.0, GSeg(sg).dVelocity, 100.0); } GSeg(0).SetVelocity(0); GSeg(NFullGSegs()).SetVelocity(0); for (sg=1; sg<NFullLSegs(); sg++) { double V=VelDampC*LiqSeg[sg]->dLiqVelo + VelDampE*LiqSeg[Max(1, sg-1)]->dLiqVelo + VelDampE*LiqSeg[Min(NFullLSegs()-1, sg+1)]->dLiqVelo; LSeg(sg).SetVelocity(V); #if dbgPipeline if (dbgVelocities() && fDoDbgBrk) dbgpln("SgLVel %3i V:%14.6f", sg, LVelocity(LSeg(sg).Position())); else if (fabs(LSeg(sg).dVelocity)>100.0) { dbgpln("LARGE LIQ VEL %3i V:%14.6f %s ", sg, LSeg(sg).dVelocity, FullObjTag()); } #endif LSeg(sg).dVelocity=Range(-100.0, LSeg(sg).dVelocity, 100.0); } LSeg(0).SetVelocity(0); LSeg(NFullLSegs()).SetVelocity(0); int lsg=0; for (sg=0; sg<NFullGSegs(); sg++) { TPPGSegment &Sg=*GasSeg[sg]; double SegLen=GSegLength(sg); double TempDiff=dSeaTemp-Sg.dTemp; double SegPipeArea=SegLen*dDiam*PI; double UA=SegPipeArea*dHTC; double SteelMass=SegLen*SteelMassPerLen; // kJ/C double SteelHCap=SteelMass*0.449; // kJ/C double GasHCap=Sg.dMass*Sg.GProps.dGasCp; double LiqHCap=Sg.dLiqMass*Sg.MxProps.dLiqCp; double TotHCap=SteelHCap+GasHCap+LiqHCap; // Feed at Start if (sg==0 && (dQmGEntry+dQmLEntry)>0.0) { double FlwHCap=dQmGEntry*dCpGEntry+dQmLEntry*dCpLEntry; double TempChgRate=(TotHCap*Sg.dTemp+FlwHCap*dTempEntry)/GTZ(TotHCap+FlwHCap)-Sg.dTemp; Sg.dTempDeriv+=TempChgRate; } else if (sg==LastFullGSeg() && (dQmGExit+dQmLExit)<0.0) { double FlwHCap=-(dQmGExit*dCpGExit+dQmLExit*dCpLExit); double TempChgRate=(TotHCap*Sg.dTemp+FlwHCap*dTempExit)/GTZ(TotHCap+FlwHCap)-Sg.dTemp; Sg.dTempDeriv+=TempChgRate; } // Change due to loss to surrounding sea Sg.dTempDeriv+=TempDiff*UA/TotHCap; #if dbgPipeline if (dbgTempDerivs() && fDoDbgBrk) dbgp("SgTmp %3i T:%14.6f dT:%14.6f", sg, Sg.dTemp, Sg.dTempDeriv); #endif // Change due to movement of segment // heat xfer with steel if (sg>0) { double StartVel=GSegStartVel(sg); if (StartVel<0.0) { // start moving backwards TPPGSegment &SgS=*GasSeg[sg-1]; double SteelMassVel=StartVel*SteelMassPerLen; // kg/s double SteelHCapVel=SteelMassVel*0.449; // kJ/C double TempChgRate=(TotHCap*Sg.dTemp+fabs(SteelHCapVel)*SgS.dTemp)/GTZ(TotHCap+fabs(SteelHCapVel))-Sg.dTemp; Sg.dTempDeriv+=TempChgRate; #if dbgPipeline if (dbgTempDerivs() && fDoDbgBrk) dbgp("dTS:%14.6f", TempChgRate); if (fabs(TempChgRate)>100.0) { int xxx=0; } #endif } } if (sg<NFullGSegs()-1) { double EndVel=GSegEndVel(sg); if (EndVel>0.0 ) { //end moving forwards TPPGSegment &SgE=*GasSeg[sg+1]; double SteelMassVel=EndVel*SteelMassPerLen; // kg/s double SteelHCapVel=SteelMassVel*0.449; // kJ/C double TempChgRate=(TotHCap*Sg.dTemp+SteelHCapVel*SgE.dTemp)/GTZ(TotHCap+SteelHCapVel)-Sg.dTemp; Sg.dTempDeriv+=TempChgRate; #if dbgPipeline if (dbgTempDerivs() && fDoDbgBrk) dbgp("dTE:%14.6f", TempChgRate); #endif } } #if dbgPipeline if (dbgTempDerivs() && fDoDbgBrk) dbgpln(" >> dT:%14.6f %s", Sg.dTempDeriv, FullObjTag()); #endif for (;;) { if (LSegMid(lsg)>GSegEnd(sg) || lsg>=LastFullLSeg()) break; LiqSeg[lsg]->dTempDeriv=Sg.dTempDeriv; lsg++; } } // Overide Velocities of Slug Segments for (sg=0; sg<NFullLSegs()-1; sg++) { if (IsSlug(sg)) { TPPLSegment &Sg0=*LiqSeg[sg]; TPPLSegment &Sg1=*LiqSeg[sg+1]; double V=(Sg0.dVelocity+Sg1.dVelocity)*0.5; Sg0.SetVelocity(V); Sg1.SetVelocity(V); } } }; //-------------------------------------------------------------------------- void TwoPhasePipe::ConvergeStates() { if (bSimple) { MN_Lnk::ConvergeStates(); return; } MdlNode::ConvergeStates(); double Duty=0.0; } //-------------------------------------------------------------------------- void TwoPhasePipe::ApplyDerivs(double dTime, flag DoDbg) { if (bSimple) { MN_Lnk::ApplyDerivs(dTime, DoDbg); return; } for (int sg=0; sg<NGSegments(); sg++) { GSeg(sg).dMass+=GSeg(sg).dMassDeriv*dTime; GSeg(sg).dTemp+=GSeg(sg).dTempDeriv*dTime; GSeg(sg).dPosition+=GSeg(sg).dVelocity*dTime; } for (sg=0; sg<NLSegments(); sg++) { LSeg(sg).dMass+=LSeg(sg).dMassDeriv*dTime; LSeg(sg).dTemp+=LSeg(sg).dTempDeriv*dTime; LSeg(sg).dPosition+=LSeg(sg).dVelocity*dTime; } CDArray DLen, MinLen; DLen.SetSize(NFullLSegs()+1); MinLen.SetSize(NFullLSegs()+1); DLen[0]=0; DLen[NFullLSegs()]=0; //dbgpln("Filling ---------------------- "); for (sg=1; sg<NFullLSegs(); sg++) { double Filling = (LSeg(sg).dMass/LSeg(sg).MxProps.dLiqDens)/LSegVolume(sg); MinLen[sg]=(LSeg(sg).dMass/LSeg(sg).MxProps.dLiqDens)/(0.99*Area()); DLen[sg]=GEZ(MinLen[sg]-LSegLength(sg)); //dbgpln(" %3i Fill:%10.4f%% %10.2f L:%10.2f DL:%10.2f Vel:%10.2f",sg,Range(-9999.,Filling*100, 9990.),LSeg(sg).dPosition,LSegLength(sg),DLen[sg],LSeg(sg).dVelocity); } bool passesdone=false; for (int pass=0; pass<100 && !passesdone; pass++) { passesdone=true; DLen[0]=0; DLen[NFullLSegs()]=0; for (sg=1; sg<NFullLSegs()-1; sg++) { DLen[sg]=GEZ(MinLen[sg]-LSegLength(sg)); LSeg(sg).dPosition+=0.5*(DLen[sg-1]-DLen[sg]); if (DLen[sg]>1e-3) passesdone=false; } } //dbgpln(" Passes %i", pass); //for (sg=1; sg<NFullLSegs(); sg++) // { // double Filling = (LSeg(sg).dMass/LSeg(sg).MxProps.dLiqDens)/LSegVolume(sg); // dbgpln(" %3i Fill:%10.4f%% Pos:%10.2f L:%10.2f Vel:%10.2f", // sg,Range(-9999.,Filling*100, 9990.),LSeg(sg).dPosition, // LSegLength(sg),LSeg(sg).dVelocity); // } }; //-------------------------------------------------------------------------- void TwoPhasePipe::EvalDiscrete() { if (bSimple) { MN_Lnk::EvalDiscrete(); return; } CalcPressures(ICGetTimeInc()); EvaluateSegment(ICGetTimeInc()); DbgDump(ICGetTimeInc()); // Fix Liquid Temperatures if neccessary int lsg=0; for (int sg=0; sg<NFullGSegs(); sg++) { TPPGSegment &GSg=*GasSeg[sg]; for (;;) { if (LSegMid(lsg)>GSegEnd(sg) || lsg>=LastFullLSeg()) break; LiqSeg[lsg]->dTemp=GSg.dTemp; lsg++; } } CalcPressures(0.0); DbgDump(ICGetTimeInc()); } //-------------------------------------------------------------------------- void TwoPhasePipe::DbgDump(double dTime) { #if dbgPipeline if (dbgTPPDump() && fDoDbgBrk) { dbgpln("====================================================================================="); dbgpln("DTime %10.3f", dTime); dbgpln("Sect Start "); for (int i=0; i<Sect.GetSize(); i++) dbgpln("%2i] %6.0f ", i,SectionStart(i)); dbgpln("Join P T"); for (i=0; i<Join.GetSize(); i++) dbgpln("%2i] %14.6g %14.6g",i,Join[i]->dMeasP,Join[i]->dMeasT); dbgpln("Seg Age Pos Len Vel Mass Dens"); for (int sg=0; sg<NGSegments(); sg++) { TPPGSegment &Sg=*GasSeg[sg]; if (sg<NFullGSegs()) dbgpln("G:%3i] %3i %14.6g %14.6g %14.6g %14.6g %14.6g", sg, Sg.iAge, Sg.dPosition, GasSeg[sg+1]->dPosition-Sg.dPosition, Sg.dVelocity, Sg.dMass, Sg.GProps.dGasDens); else dbgpln("G:%3i] %3i %14.6g %14s %14.6g", sg, Sg.iAge,Sg.dPosition,"",Sg.dVelocity); } for (sg=0; sg<NLSegments(); sg++) { TPPLSegment &Sg=*LiqSeg[sg]; if (sg<NFullLSegs()) dbgpln("L:%3i] %3i %14.6g %14.6g %14.6g %14.6g %14.6g", sg, Sg.iAge, Sg.dPosition, LiqSeg[sg+1]->dPosition-Sg.dPosition, Sg.dVelocity, Sg.dMass, Sg.LProps.dLiqDens); else dbgpln("L:%3i] %3i %14.6g %14s %14.6g", sg, Sg.iAge,Sg.dPosition,"",Sg.dVelocity); } dbgpln("====================================================================================="); } #endif } //========================================================================== // // // //==========================================================================
[ [ [ 1, 4059 ] ] ]
e36dece399864f8fb4ce96c057ea5bfef589f058
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Shape/Compound/Collection/ExtendedMeshShape/hkpExtendedMeshShape.inl
163f6984a89a49801bf96dc5bc5b9e9efa425308
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
5,075
inl
/* * * 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-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ int hkpExtendedMeshShape::getNumTrianglesSubparts() const { return m_trianglesSubparts.getSize(); } int hkpExtendedMeshShape::getNumShapesSubparts() const { return m_shapesSubparts.getSize(); } hkpExtendedMeshShape::TrianglesSubpart& hkpExtendedMeshShape::getTrianglesSubpartAt( int i ) { HK_ASSERT2(0x3031b232, i < getNumTrianglesSubparts(), "You are trying to access a triangles-subpart which is not in the triangle subpart array"); return m_trianglesSubparts[i]; } const hkpExtendedMeshShape::TrianglesSubpart& hkpExtendedMeshShape::getTrianglesSubpartAt( int i ) const { HK_ASSERT2(0x2bb0d984, i < getNumTrianglesSubparts(), "You are trying to access a triangles-subpart which is not in the triangle subpart array"); return m_trianglesSubparts[i]; } hkpExtendedMeshShape::ShapesSubpart& hkpExtendedMeshShape::getShapesSubpartAt( int i ) { HK_ASSERT2(0x30312232, i < getNumShapesSubparts(), "You are trying to access a shapes-subpart which is not in the shape subpart array"); return m_shapesSubparts[i]; } const hkpExtendedMeshShape::ShapesSubpart& hkpExtendedMeshShape::getShapesSubpartAt( int i ) const { HK_ASSERT2(0x2bb05984, i < getNumShapesSubparts(), "You are trying to access a shapes-subpart which is not in the shape subpart array"); return m_shapesSubparts[i]; } hkInt32 hkpExtendedMeshShape::getSubPartIndex( hkpShapeKey key ) const { const hkUint32 subpartIndex = (key & 0x7fffffff) >> ( 32 - m_numBitsForSubpartIndex ); return subpartIndex; } hkpExtendedMeshShape::SubpartType hkpExtendedMeshShape::getSubpartType( hkpShapeKey key ) const { if ( !((key) & 0x80000000) ) { return SUBPART_TRIANGLES; } else { return SUBPART_SHAPE; } } const hkpExtendedMeshShape::Subpart& hkpExtendedMeshShape::getSubPart( hkpShapeKey key ) const { hkUint32 subpartIndex = getSubPartIndex(key); if ( getSubpartType(key) == SUBPART_TRIANGLES ) { return m_trianglesSubparts[ subpartIndex ]; } else { return m_shapesSubparts[ subpartIndex ]; } } HK_FORCE_INLINE hkInt32 hkpExtendedMeshShape::getSubpartShapeKeyBase( int subpartIndex ) const { if ( subpartIndex < m_trianglesSubparts.getSize() ) { return subpartIndex << ( 32 - m_numBitsForSubpartIndex ); } int h = subpartIndex - m_trianglesSubparts.getSize(); h = h << ( 32 - m_numBitsForSubpartIndex ); h |= 1<<31; return h; } hkInt32 hkpExtendedMeshShape::getTerminalIndexInSubPart( hkpShapeKey key ) const { hkInt32 terminalIndex = key & ( ~0U >> m_numBitsForSubpartIndex ); return terminalIndex; } hkInt32 hkpExtendedMeshShape::getNumBitsForSubpartIndex() const { return m_numBitsForSubpartIndex; } hkReal hkpExtendedMeshShape::getRadius() const { return m_triangleRadius; } void hkpExtendedMeshShape::setRadius(hkReal r ) { m_triangleRadius = r; } HK_FORCE_INLINE const hkVector4& hkpExtendedMeshShape::getScaling() const { return m_scaling; } HK_FORCE_INLINE hkpExtendedMeshShape::Subpart::Subpart(SubpartType type) { m_type = type; // materials (default is fine) //m_materialIndexStridingType = MATERIAL_INDICES_INVALID; m_materialIndexStridingType = MATERIAL_INDICES_INT8; m_materialIndexStriding = 0; m_materialStriding = 0; m_numMaterials = 1; m_materialBase = HK_NULL; m_materialIndexBase = HK_NULL; m_materialClass = HK_NULL; } HK_FORCE_INLINE hkpExtendedMeshShape::TrianglesSubpart::TrianglesSubpart(): Subpart( SUBPART_TRIANGLES ) { m_flipAlternateTriangles = 0; m_extrusion.setZero4(); m_userData = 0; // 'must set' values, defaults are error flags effectively for HK_ASSERTS in the cpp. #ifdef HK_DEBUG m_vertexBase = HK_NULL; m_vertexStriding = -1; m_numVertices = -1; m_indexBase = HK_NULL; m_stridingType = INDICES_INVALID; m_indexStriding = -1; m_numTriangleShapes = -1; m_triangleOffset = -1; #endif } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * 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. * */
[ [ [ 1, 162 ] ] ]
1efd09af8ffb82ece5cf99dd8c41b9b7dc7f090f
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/System/Win/MutexImpl.h
a63be1c636c9bfd56089980dc1c0bb7273e23224
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
651
h
//============================================================================ // Date : 22.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry ([email protected]) //============================================================================ #ifndef __MUTEXIMPL_H__ #define __MUTEXIMPL_H__ #include <windows.h> #include "Mutex.h" namespace System { class Mutex::MutexImpl : private Common::NoCopyable { public: MutexImpl(); ~MutexImpl(); void Lock(); void Unlock(); private: CRITICAL_SECTION Section; }; } #endif // !__MUTEXIMPL_H__
[ "TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277" ]
[ [ [ 1, 31 ] ] ]
ab1a5743b5ba09778d57e6a6f7bc60ae78a8a09e
6ee1038554d8897956a6bb48f465a2029a4777a9
/Controller.cc
9b948548d1dfc130a5fefb8277832bbcbaa5f61f
[]
no_license
talalbutt/ns3.9-vanet-highway
90372238f56c09c0f30c476c3be2a650d6f399a7
75552865065b3f663d33dcee82071fb5c845bf12
refs/heads/master
2020-03-23T18:12:24.972319
2011-06-27T05:48:54
2011-06-27T05:48:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,183
cc
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005-2009 Old Dominion University [ARBABI] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Hadi Arbabi <[email protected]> */ #include <iostream> #include <sstream> #include "Controller.h" #include <boost/algorithm/string.hpp> #include <sstream> #include <fstream> using namespace std; using namespace ns3; const double AMBU_DIST = 10000.0; double string_to_double( const std::string& s ) { std::istringstream i(s); double x; if (!(i >> x)) return 0; return x; } namespace ns3 { extern int laneChangeNb; extern int laneChangeITS; Controller::Controller() { T=-1.0; Plot=false; RecordAmbuPos=false; AmbuFile="./ambuX"; AmbuFileContent=""; this->destinationReached=false; this->timeToReachDest=0.0; this->ambulanceId = 0; this->srcX = 0.0; this->destX = 0.0; this->startTime = -1.0; this->emergencyDbThreshold = -0.5; //this->emergencyDbThreshold = -100.0; this->dstForDriverToReact = 100; this->packetMaxDist=0; this->packetAvgDist=0; this->packetNb=0; laneChangeNb = 0; laneChangeITS = 0; AverageDistanceBetweenVehicles = 100; AverageSpeed = 105; DesiredSpeed = 130; AmbuMaxSpeed = 165; AmbuInitialSpeed = 130; scenarioNb = 2; } Controller::Controller(Ptr<Highway> highway) { this->highway=highway; } void Controller::SetHighway(Ptr<Highway> highway) { this->highway=highway; } Ptr<Highway> Controller::GetHighway() { return this->highway; } bool Controller::InitVehicle(Ptr<Highway> highway, int& VID) { // Block the road with warning, 500 meters away, at the right most lane [lane=0, dir=1] /* Ptr<Obstacle> obstacle=CreateObject<Obstacle>(); obstacle->SetupWifi(highway->GetWifiHelper(), highway->GetYansWifiPhyHelper(), highway->GetNqosWifiMacHelper()); obstacle->SetVehicleId(VID++); obstacle->SetDirection(1); obstacle->SetLane(0); obstacle->SetPosition(Vector(1000, highway->GetYForLane(0,1), 0)); obstacle->SetLength(8); obstacle->SetWidth(2); obstacle->SetReceiveCallback(highway->GetReceiveDataCallback()); highway->AddVehicle(obstacle); Simulator::Schedule(Seconds(0.0), &Controller::BroadcastWarning, this, obstacle); */ /* // Create an ambulance car moving toward the blocked spot, remember its VehicleId will be 2 // We also show how we can assign this car new wifiphy instead of using default highway wifi, // for example a ambulance with a stronger transmission. // Remember all the vehicles must use the same shared wifi channel which already hold by highway. // Highway TxPower default value is 21.0 for (250m-300m) range, 30.0 makes the ambulance has higher range. // Also let ambulance car has a higher max speed. YansWifiPhyHelper ambulancePhyHelper = YansWifiPhyHelper::Default(); ambulancePhyHelper.SetChannel(highway->GetWifiChannel()); ambulancePhyHelper.Set("TxPowerStart",DoubleValue(30.0)); ambulancePhyHelper.Set("TxPowerEnd",DoubleValue(30.0)); Ptr<Vehicle> ambulance=CreateObject<Vehicle>(); ambulance->SetupWifi(highway->GetWifiHelper(), ambulancePhyHelper, highway->GetNqosWifiMacHelper()); ambulance->SetVehicleId(VID++); ambulance->SetDirection(1); ambulance->SetLane(1); ambulance->SetPosition(Vector(0.0, highway->GetYForLane(1,1), 0)); ambulance->SetVelocity(0.0); ambulance->SetAcceleration(0.0); Ptr<Model> ambulanceModel=highway->CreateSedanModel(); ambulanceModel->SetDesiredVelocity(40.0); // max speed 36(m/s) ambulance->SetModel(ambulanceModel); // or common sedan model: highway->GetSedanModel() ambulance->SetLaneChange(highway->GetSedanLaneChange()); ambulance->SetLength(4); ambulance->SetWidth(2); ambulance->SetReceiveCallback(highway->GetReceiveDataCallback()); highway->AddVehicle(ambulance); Simulator::Schedule(Seconds(0.0), &Controller::BroadcastWarning, this, ambulance); */ /* // create a vehicle on the road with wifi to setup the wifi on the highway YansWifiPhyHelper wifiVehiclePhyHelper = YansWifiPhyHelper::Default(); wifiVehiclePhyHelper.SetChannel(highway->GetWifiChannel()); wifiVehiclePhyHelper.Set("TxPowerStart",DoubleValue(30.0)); wifiVehiclePhyHelper.Set("TxPowerEnd",DoubleValue(30.0)); Ptr<Vehicle> wifiVehicle=CreateObject<Vehicle>(); wifiVehicle->SetupWifi(highway->GetWifiHelper(), wifiVehiclePhyHelper, highway->GetNqosWifiMacHelper()); wifiVehicle->SetVehicleId(VID++); wifiVehicle->SetDirection(1); wifiVehicle->SetLane(1); wifiVehicle->SetPosition(Vector(2000.0, highway->GetYForLane(1,1), 0)); wifiVehicle->SetVelocity(0.0); wifiVehicle->SetAcceleration(0.0); Ptr<Model> wifiVehicleModel=highway->CreateSedanModel(); wifiVehicleModel->SetDesiredVelocity(40.0); // max speed 36(m/s) wifiVehicle->SetModel(wifiVehicleModel); // or common sedan model: highway->GetSedanModel() wifiVehicle->SetLaneChange(highway->GetSedanLaneChange()); wifiVehicle->SetLength(4); wifiVehicle->SetWidth(2); wifiVehicle->SetReceiveCallback(highway->GetReceiveDataCallback()); highway->AddVehicle(wifiVehicle); */ this->JsonOutput("ambuFile", AmbuFile); if (scenarioNb == 1) { Simulator::Schedule(Seconds(1000.0), &Controller::StartAmbulanceVehicle, this, highway); highway->SetAutoInject(true); //cout << "\"ambuFileChar\":\"" << AmbuFile.c_str() << "\"," << endl; } else { // manually create the highway highway->SetAutoInject(false); this->DeployVehicles(highway, VID); } // Return true: a signal to highway that the lane lists (queues) in where obstacles and vehicles are being added // must be sorted based on their positions. // Return false: to ignore sorting (do not return false when vehicles are manually added to the highway). return true; } void Controller::DeployVehicles(Ptr<Highway> highway, int& VID) { // Deploy the vehicles RandomVariable RVx = NormalVariable(AverageDistanceBetweenVehicles,1000); RandomVariable RVs = NormalVariable(AverageSpeed*10.0/36.0,100); RandomVariable RVds = NormalVariable(DesiredSpeed*10.0/36.0,100); RandomVariable RV = UniformVariable(0.0,100.0); // For each lane for (int lane=0; lane<=1; lane++) { // while the X position is < 10 000 m. for (double x = AMBU_DIST/2-RVx.GetValue(); x>150; x -= RVx.GetValue()) { double s = RVs.GetValue(); if (s>180*10.0/36.0) s = 180*10.0/36.0; double ds = RVds.GetValue(); if (ds>180*10.0/36.0) ds = 180*10.0/36.0; bool hasWifi = (RV.GetValue() <= highway->GetPenetrationRate()) ? true : false; //cout << "[LANE " << lane << "][POS " << x << "][SPEED " << s*36.0/10.0 << "][DESIRED " << ds*36.0/10.0 << "][Wifi " << hasWifi << "]" << endl; // Create the vehicle Ptr<Vehicle> vehicle=CreateObject<Vehicle>(); if (hasWifi) { YansWifiPhyHelper vehiclePhyHelper = YansWifiPhyHelper::Default(); vehiclePhyHelper.SetChannel(highway->GetWifiChannel()); vehiclePhyHelper.Set("TxPowerStart",DoubleValue(30.0)); vehiclePhyHelper.Set("TxPowerEnd",DoubleValue(30.0)); vehicle->IsEquipped = true; vehicle->SetupWifi(highway->GetWifiHelper(), vehiclePhyHelper, highway->GetNqosWifiMacHelper()); } else { vehicle->IsEquipped = false; } vehicle->SetVehicleId(VID++); vehicle->SetDirection(1); vehicle->SetLane(lane); vehicle->SetPosition(Vector(x, highway->GetYForLane(lane,1), 0)); // (x = 1) vehicle->SetVelocity(s); //vehicle->SetAcceleration(5.0); Ptr<Model> vehicleModel=highway->CreateSedanModel(); vehicleModel->SetDesiredVelocity(ds); // max speed 36(m/s) vehicleModel->SetDeltaV(4.0); vehicleModel->SetAcceleration(0.5); vehicleModel->SetDeceleration(3.0); vehicle->SetModel(vehicleModel); // or common sedan model: highway->GetSedanModel() Ptr<LaneChange> vehicleLaneChangeModel = highway->CreateSedanLaneChangeModel(); //vehicleLaneChangeModel->SetDbThreshold(100.0); // no lane change vehicle->SetLaneChange(vehicleLaneChangeModel); vehicle->SetLength(4); vehicle->SetWidth(2); vehicle->SetReceiveCallback(highway->GetReceiveDataCallback()); vehicle->SetDevTxTraceCallback(highway->GetDevTxTraceCallback()); vehicle->SetDevRxTraceCallback(highway->GetDevRxTraceCallback()); vehicle->SetPhyRxOkTraceCallback(highway->GetPhyRxOkTraceCallback()); vehicle->SetPhyRxErrorTraceCallback(highway->GetPhyRxErrorTraceCallback()); vehicle->SetPhyTxTraceCallback(highway->GetPhyTxTraceCallback()); vehicle->SetPhyStateTraceCallback(highway->GetPhyStateTraceCallback()); highway->AddVehicle(vehicle); } } // Deploy the Emergency Vehicle (i.e.: ambulance) Ptr<Vehicle> ambulance=CreateObject<Vehicle>(); YansWifiPhyHelper ambulancePhyHelper = YansWifiPhyHelper::Default(); ambulancePhyHelper.SetChannel(highway->GetWifiChannel()); ambulancePhyHelper.Set("TxPowerStart",DoubleValue(40.0)); ambulancePhyHelper.Set("TxPowerEnd",DoubleValue(40.0)); ambulance->IsEquipped = true; ambulance->SetupWifi(highway->GetWifiHelper(), ambulancePhyHelper, highway->GetNqosWifiMacHelper()); ambulance->SetVehicleId(VID++); ambulance->SetDirection(1); int ambuLane = 1; ambulance->SetLane(ambuLane); this->JsonOutput("ambuLane", ambuLane); ambulance->SetPosition(Vector(1.0, highway->GetYForLane(ambuLane,1), 0)); // (x = 1) ambulance->SetVelocity(AmbuInitialSpeed*10.0/36.0); //ambulance->SetAcceleration(1.0); Ptr<Model> ambulanceModel=highway->CreateSedanModel(); ambulanceModel->SetDesiredVelocity(AmbuMaxSpeed*10.0/36.0); // max speed 36(m/s) ambulanceModel->SetDeltaV(8.0); ambulanceModel->SetAcceleration(1.0); ambulanceModel->SetDeceleration(6.0); ambulance->SetModel(ambulanceModel); // or common sedan model: highway->GetSedanModel() Ptr<LaneChange> ambulanceLaneChangeModel = highway->CreateSedanLaneChangeModel(); ambulanceLaneChangeModel->SetDbThreshold(1000000); // no lane change ambulance->SetLaneChange(ambulanceLaneChangeModel); ambulance->SetLength(4); ambulance->SetWidth(2); ambulance->SetReceiveCallback(highway->GetReceiveDataCallback()); ambulance->SetDevTxTraceCallback(highway->GetDevTxTraceCallback()); ambulance->SetDevRxTraceCallback(highway->GetDevRxTraceCallback()); ambulance->SetPhyRxOkTraceCallback(highway->GetPhyRxOkTraceCallback()); ambulance->SetPhyRxErrorTraceCallback(highway->GetPhyRxErrorTraceCallback()); ambulance->SetPhyTxTraceCallback(highway->GetPhyTxTraceCallback()); ambulance->SetPhyStateTraceCallback(highway->GetPhyStateTraceCallback()); highway->AddVehicle(ambulance); this->ambulanceId = ambulance->GetVehicleId(); double ambuX = ambulance->GetPosition().x; this->srcX = ambuX; this->destX = ambuX + AMBU_DIST; Simulator::Schedule(Seconds(0), &Controller::BroadcastWarning, this, ambulance); this->DebugDensity(); this->StartRecordingData(); } void Controller::JsonOutput(string name, int value) { cout << "\"" << name << "\":" << value << "," << endl; } void Controller::JsonOutput(string name, double value) { cout << "\"" << name << "\":" << value << "," << endl; } void Controller::JsonOutput(string name, string value) { cout << "\"" << name << "\":\"" << value << "\"," << endl; } void Controller::JsonOutputInitVehicles(int lane, std::list<Ptr<Vehicle> > vehicles) { // vehicles on lane 0 string vehiclesPos, vehiclesSpeed; ostringstream laneStr; laneStr << lane; string posName = "vehiclesPosLane"; posName.append(laneStr.str()); string speedName = "vehiclesSpeedLane"; speedName.append(laneStr.str()); string averageGapName = "averageGapOnLane"; averageGapName.append(laneStr.str()); averageGapName.append("_New"); string minGapName = "minGapLane"; minGapName.append(laneStr.str()); string maxGapName = "maxGapLane"; maxGapName.append(laneStr.str()); bool nouveau=true; int k=0; double previousPos=0; double gapTotal = 0; double minGap = 10000; double maxGap = 0; double currentGap = 0; double previousGap = 0; while (vehicles.size()>0) { ostringstream pos, vel; Ptr<Vehicle> v = vehicles.back(); vehicles.pop_back(); double currentPos = v->GetPosition().x; pos << currentPos; vel << v->GetVelocity(); if (nouveau==false) { k++; currentGap = abs(currentPos-previousPos); gapTotal += currentGap; if (currentGap>maxGap) maxGap = currentGap; if (currentGap<minGap) minGap = currentGap; vehiclesPos.append(" "); vehiclesSpeed.append(" "); } else { nouveau= false; } vehiclesPos.append(pos.str()); vehiclesSpeed.append(vel.str()); previousPos = currentPos; previousGap = currentGap; } double averageGap= 1.0*gapTotal/k; this->JsonOutput(posName, vehiclesPos); this->JsonOutput(speedName, vehiclesSpeed); this->JsonOutput(averageGapName, averageGap); this->JsonOutput(minGapName, minGap); this->JsonOutput(maxGapName, maxGap); } void Controller::StartRecordingData() { double now=Simulator::Now().GetSeconds(); this->startTime = now; if (!Plot) { // cout << "at t=" << now << " AMBULANCE (" << this->ambulanceId << // ") START RECORDING TIME! Position: " << ambuX << "m" // << " Speed: " << ambulance->GetVelocity() << endl; this->JsonOutput("startRecordingTime", now); } } void Controller::DebugDensity() { Ptr<Vehicle> ambu = highway->FindVehicle(this->ambulanceId); double ambuX = ambu->GetPosition().x; this->JsonOutput("ambuId", this->ambulanceId); this->JsonOutput("ambuStartX", ambuX); // Calculate the density //double length=highway->GetHighwayLength()-ambuX-1.0; int dir= 1; list< Ptr< Vehicle > > vehicles0 = highway->FindVehiclesInSegment(ambuX+1.0,this->destX, 0, dir); list< Ptr< Vehicle > > vehicles1 = highway->FindVehiclesInSegment(ambuX+1.0,this->destX, 1, dir); Ptr<Vehicle> last0 = vehicles0.front(); Ptr<Vehicle> last1 = vehicles1.front(); double density0 = (last0->GetPosition().x-ambuX-1.0)/vehicles0.size(); double density1 = (last1->GetPosition().x-ambuX-1.0)/vehicles1.size(); this->JsonOutput("vehiclesOnLane0", (int) vehicles0.size()); this->JsonOutput("averageGapOnLane0", density0); this->JsonOutput("lastVehicleXOnLane0", last0->GetPosition().x); this->JsonOutput("vehiclesOnLane1", (int) vehicles1.size()); this->JsonOutput("averageGapOnLane1", density1); this->JsonOutput("lastVehicleXOnLane1", last1->GetPosition().x); this->JsonOutputInitVehicles(0, vehicles0); this->JsonOutputInitVehicles(1, vehicles1); this->JsonOutput("ambuXwhenStart",ambuX); this->JsonOutput("ambuSpeedWhenStart",ambu->GetVelocity()); } void Controller::StartAmbulanceVehicle(Ptr<Highway> highway) { double xMin = 500; double xMax = 2000; int lane= 0; this->JsonOutput("ambuLane", lane); int dir= 1; list< Ptr< Vehicle > > vehicles = highway->FindVehiclesInSegment(xMin,xMax, lane, dir); int vehiclesFoundNb = vehicles.size(); if (vehiclesFoundNb>0) { int vehicle_i = int ( floor(vehiclesFoundNb/2.0) ); int i=0; while (i<vehicle_i) { vehicles.pop_front(); i++; } Ptr<Vehicle> ambulance=vehicles.front(); this->ambulanceId = ambulance->GetVehicleId(); double ambuX = ambulance->GetPosition().x; this->srcX = ambuX; this->destX = ambuX + 10000; if (!Plot) { // cout << "I chose vehicle " << vehicle_i << " among " << vehiclesFoundNb << " vehicles."<< endl; // cout << "ID " << this->ambulanceId << " Position: " << ambuX << endl; this->JsonOutput("vehicleChosen", vehicle_i); this->JsonOutput("vehicleChosenAmong", vehiclesFoundNb); this->DebugDensity(); } YansWifiPhyHelper ambulancePhyHelper = YansWifiPhyHelper::Default(); ambulancePhyHelper.SetChannel(highway->GetWifiChannel()); ambulancePhyHelper.Set("TxPowerStart",DoubleValue(30.0)); ambulancePhyHelper.Set("TxPowerEnd",DoubleValue(30.0)); ambulance->IsEquipped = true; ambulance->SetupWifi(highway->GetWifiHelper(), ambulancePhyHelper, highway->GetNqosWifiMacHelper()); //ambulance->SetVehicleId(); //ambulance->SetDirection(1); //ambulance->SetLane(1); //ambulance->SetPosition(Vector(0.0, highway->GetYForLane(1,1), 0)); //ambulance->SetVelocity(40.0); //ambulance->SetAcceleration(5.0); Ptr<Model> ambulanceModel=highway->CreateSedanModel(); ambulanceModel->SetDesiredVelocity(47.0); // max speed 36(m/s) ambulanceModel->SetDeltaV(10.0); ambulanceModel->SetAcceleration(1.0); ambulanceModel->SetDeceleration(6.0); ambulance->SetModel(ambulanceModel); // or common sedan model: highway->GetSedanModel() Ptr<LaneChange> ambulanceLaneChangeModel = highway->CreateSedanLaneChangeModel(); ambulanceLaneChangeModel->SetDbThreshold(100.0); // no lane change ambulance->SetLaneChange(ambulanceLaneChangeModel); ambulance->SetLength(4); ambulance->SetWidth(2); ambulance->SetReceiveCallback(highway->GetReceiveDataCallback()); ambulance->SetDevTxTraceCallback(highway->GetDevTxTraceCallback()); ambulance->SetDevRxTraceCallback(highway->GetDevRxTraceCallback()); ambulance->SetPhyRxOkTraceCallback(highway->GetPhyRxOkTraceCallback()); ambulance->SetPhyRxErrorTraceCallback(highway->GetPhyRxErrorTraceCallback()); ambulance->SetPhyTxTraceCallback(highway->GetPhyTxTraceCallback()); ambulance->SetPhyStateTraceCallback(highway->GetPhyStateTraceCallback()); Simulator::Schedule(Seconds(1), &Controller::BroadcastWarning, this, ambulance); // start recording data this->StartRecordingData(); } else { if (!Plot) { this->JsonOutput("vehicleChosenAmong", vehiclesFoundNb); this->JsonOutput("vehicleTotal", highway->GetLastVehicleId()); //cout << "NO VEHICLE FOUND IN RANGE [" << xMin << "," << xMax << "]" << endl; } Simulator::Stop(); } } void Controller::AddAmbulanceVehicle(Ptr<Highway> highway) { // select a random vehicle around position x=1000 // and define it as an ambulance in service //this->ambulanceId = highway->GetLastVehicleId()+1; this->ambulanceId = 0; YansWifiPhyHelper ambulancePhyHelper = YansWifiPhyHelper::Default(); ambulancePhyHelper.SetChannel(highway->GetWifiChannel()); ambulancePhyHelper.Set("TxPowerStart",DoubleValue(35.0)); ambulancePhyHelper.Set("TxPowerEnd",DoubleValue(35.0)); Ptr<Vehicle> ambulance=CreateObject<Vehicle>(); ambulance->SetupWifi(highway->GetWifiHelper(), ambulancePhyHelper, highway->GetNqosWifiMacHelper()); ambulance->SetVehicleId(this->ambulanceId); ambulance->SetDirection(1); ambulance->SetLane(1); ambulance->SetPosition(Vector(0.0, highway->GetYForLane(1,1), 0)); ambulance->SetVelocity(40.0); ambulance->SetAcceleration(2.0); Ptr<Model> ambulanceModel=highway->CreateSedanModel(); ambulanceModel->SetDesiredVelocity(47.0); // max speed 36(m/s) ambulance->SetModel(ambulanceModel); // or common sedan model: highway->GetSedanModel() Ptr<LaneChange> ambulanceLaneChangeModel = highway->CreateSedanLaneChangeModel(); ambulanceLaneChangeModel->SetDbThreshold(100.0); ambulance->SetLaneChange(ambulanceLaneChangeModel); ambulance->SetLength(4); ambulance->SetWidth(2); ambulance->SetReceiveCallback(highway->GetReceiveDataCallback()); highway->AddVehicle(ambulance); // Simulator::Schedule(Seconds(1), &Controller::BroadcastWarning, this, ambulance); } bool Controller::ControlVehicle(Ptr<Highway> highway, Ptr<Vehicle> vehicle, double dt) { if (RecordAmbuPos==true && vehicle->GetVehicleId()==this->ambulanceId) { /* ofstream outputFile; outputFile.open(AmbuFile.c_str(), ios_base::app); outputFile << now << " " << vehicle->GetPosition().x << endl; */ ostringstream pos, now; pos << vehicle->GetPosition().x; now << Simulator::Now().GetSeconds(); AmbuFileContent.append(now.str()); AmbuFileContent.append(" "); AmbuFileContent.append(pos.str()); AmbuFileContent.append("\n"); } // we aim to create outputs which are readable by gnuplot for visulization purpose // this can be happen at beginning of each simulation step here. else if(Plot==true) { bool newStep=false; double now=Simulator::Now().GetHighPrecision().GetDouble(); if(now > T) { T = now; newStep=true; } if(newStep==true) { if(T!=0.0) { cout << "e" << endl; //cout << "pause " << dt << endl; } float xrange = highway->GetHighwayLength(); float yrange = highway->GetLaneWidth()*highway->GetNumberOfLanes(); if(highway->GetTwoDirectional()) yrange=2*yrange + highway->GetMedianGap(); cout << "set xrange [0:"<< xrange <<"]" << endl; cout << "set yrange [0:"<< yrange <<"]" << endl; cout << "plot '-' w points" << endl; newStep=false; } if(newStep==false) { cout << vehicle->GetPosition().x << " " << vehicle->GetPosition().y << endl; } } /* if (!this->destinationReached && vehicle->GetVehicleId()==this->ambulanceId && this->startTime<=0 && vehicle->GetPosition().x >=this->srcX) { //this->startTime = Simulator::Now().GetHighPrecision().GetDouble(); double now=Simulator::Now().GetSeconds(); this->startTime = now; if (!Plot) cout << "at t=" << now << " AMBULANCE (" << vehicle->GetVehicleId() << ") START RECORDING TIME! Position: " << vehicle->GetPosition().x << "m" << " Speed: " << vehicle->GetVelocity() << endl; Simulator::Schedule(Seconds(1), &Controller::BroadcastWarning, this, vehicle); } */ // Change lane for a driver without wifi if(vehicle->GetVehicleId()!=this->ambulanceId && this->startTime>=0 && vehicle->GetLaneChange()->GetDbThreshold()!=this->emergencyDbThreshold && !this->destinationReached) { Ptr<Vehicle> ambulance = highway->FindVehicle(this->ambulanceId); double ambuX = ambulance->GetPosition().x; double myX = vehicle->GetPosition().x; double ambuLane = ambulance->GetLane(); double myLane = vehicle->GetLane(); double diff = myX - ambuX; if (myLane==ambuLane && myX >= ambuX && diff<=vehicle->GetDetectsVehicleDistance()) { if (false&&!Plot) { double now=Simulator::Now().GetSeconds(); cout << "at t=" << now << " veh " << vehicle->GetVehicleId() << " at " << diff << "m of the ambu tries to change lane (speed=" << vehicle->GetVelocity() << ")" << endl; } this->AskChangeLane(highway, vehicle); } } // to record when the ambulance reaches its destination else if(vehicle->GetVehicleId()==this->ambulanceId && vehicle->GetPosition().x >=this->destX && this->startTime>=0 && !this->destinationReached) { this->destinationReached = true; double now=Simulator::Now().GetSeconds(); //this->timeToReachDest = Simulator::Now().GetHighPrecision().GetDouble()-this->startTime; this->timeToReachDest = now-this->startTime; if (!Plot) { // cout << "at t=" << now << " AMBULANCE REACHED DEST in " << this->timeToReachDest // << "s! Position: " << vehicle->GetPosition().x << "m" << " Speed: " << vehicle->GetVelocity() << endl; this->JsonOutput("ambuReachedDestTime", now); this->JsonOutput("timeToReachDest", this->timeToReachDest); this->JsonOutput("ambuXwhenReached", vehicle->GetPosition().x); this->JsonOutput("ambuSpeedWhenReached", vehicle->GetVelocity()); this->JsonOutput("laneChangeNb", laneChangeNb); this->JsonOutput("laneChangeITS", laneChangeITS); } if (RecordAmbuPos==true) { // ofstream outputFile; // outputFile.open(AmbuFile.c_str(), ios_base::app); ofstream outputFile(AmbuFile.c_str()); outputFile << AmbuFileContent; } this->JsonOutput("packetMaxDist", this->packetMaxDist); this->JsonOutput("packetAvgDist", this->packetAvgDist); Simulator::Stop(); // Simulator::Destroy(); //vehicle->SetAcceleration(-2.0); // return true: a signal to highway that we aim to manually control the vechile //return true; } // return false: a signal to highway that lets the vehicle automatically be handled (using IDM/MOBIL rules) return false; } void Controller::BroadcastWarning(Ptr<Vehicle> veh) { double distance_to_dest = this->destX - veh->GetPosition().x; if (distance_to_dest>0) { stringstream msg; msg << veh->GetPosition().x << " " << veh->GetDirection() << " " << veh->GetLane(); /* msg << "ambu"//veh->GetVehicleId() //<< " " << veh->GetPosition().x << " is on the highway at x=" << veh->GetPosition().x << " dir=" << veh->GetDirection() << " lane=" << veh->GetLane(); */ if (false&&!Plot) { int vid=veh->GetVehicleId(); double now=Simulator::Now().GetSeconds(); cout << "at t=" << now << " vehicle " << vid << " is at pos=" << veh->GetPosition().x << ", dst to dest=" << distance_to_dest << "m to the destination, on lane " << veh->GetLane() << " at speed " << veh->GetVelocity() << "m/s" << " (desired:" << veh->GetModel()->GetDesiredVelocity() << ")" << endl; } Ptr<Packet> packet = Create<Packet>((uint8_t*) msg.str().c_str(), msg.str().length()); //cout << "Broadcast warning get Broadcast address..." << endl; veh->SendTo(veh->GetBroadcastAddress(), packet); //cout << " done! (" << veh->GetBroadcastAddress() << ")" << endl; Simulator::Schedule(Seconds(2.0),&Controller::BroadcastWarning, this, veh); } } void Controller::ReceiveData(Ptr<Vehicle> veh, Ptr<const Packet> packet, Address address) { int vid=veh->GetVehicleId(); if (vid == this->ambulanceId) { if (false&&!Plot) { double now=Simulator::Now().GetSeconds(); cout << "t=" << now << " veh " << vid << " received its own message (ambuId = "<< this->ambulanceId << ") :s" << endl; } } else { string data=string((char*)packet->PeekData()); stringstream ss (stringstream::in | stringstream::out); double obs_id, obs_x; ss << data; ss >> obs_id; ss >> obs_x; int lane = veh->GetLane(); double vehX = veh->GetPosition().x; vector<string> strs; boost::split(strs, data, boost::is_any_of("\t ")); double ambuX = string_to_double(strs.at(0)); double ambuLane = string_to_double(strs.at(2)); double now=Simulator::Now().GetSeconds(); //cout << "ambuX=" << ambuX << "ambuLane=" << ambuLane << endl; double dstToAmbu = abs(vehX - ambuX); if (dstToAmbu>this->packetMaxDist) this->packetMaxDist = dstToAmbu; if (this->packetAvgDist==0) this->packetAvgDist= dstToAmbu; else this->packetAvgDist = (this->packetAvgDist*this->packetNb+dstToAmbu)/(this->packetNb+1); this->packetNb++; if (lane==ambuLane && ambuX < vehX) { if(false&&!Plot) { cout << "t=" << now << " veh " << vid << " rec msg=[" << data << "] own pos=" << vehX << "m lane=" << lane << " speed= " << veh->GetVelocity() << "m/s" << " (desired:" << veh->GetModel()->GetDesiredVelocity() << ")"<<endl; cout << "\tOh my! I should change lane!!! \tdbThreshold=" << veh->GetLaneChange()->GetDbThreshold() << " politness=" << veh->GetLaneChange()->GetPolitenessFactor() << " gapMin=" << veh->GetLaneChange()->GetGapMin() << " biasRight= " << veh->GetLaneChange()->GetBiasRight() << endl; } //this->laneChangeITS++; this->AskChangeLane(highway, veh); } } } void Controller::AskChangeLane(Ptr<Highway> highway, Ptr<Vehicle> veh) { //this->laneChangeNb++; /* // create a new model and assign it Ptr<LaneChange> newLaneChangeModel = highway->CreateSedanLaneChangeModel(); newLaneChangeModel->SetDbThreshold(this->emergencyDbThreshold); newLaneChangeModel->SetGapMin(1); //newLaneChangeModel->SetPolitenessFactor(1); //newLaneChangeModel->SetBiasRight(100); veh->SetLaneChange(newLaneChangeModel); //std::list<Ptr<Vehicle> > vehi_list; //vehi_list.insert(vehi_list.begin(),veh); //this->highway->ChangeLane(&vehi_list);" */ // v2 double currentThreshold = veh->GetLaneChange()->GetDbThreshold(); if (currentThreshold>=0) { veh->GetLaneChange()->SetDbThreshold(this->emergencyDbThreshold); veh->GetLaneChange()->SetGapMin(1); veh->GetLaneChange()->SetMaxSafeBreakingDeceleration(24.0); } else if (veh->IsEquipped){ //} else { veh->GetLaneChange()->SetDbThreshold(currentThreshold+this->emergencyDbThreshold*2); } else { veh->GetLaneChange()->SetDbThreshold(currentThreshold+this->emergencyDbThreshold*0.2); } //veh->GetLaneChange()->SetBiasRight(100); } }
[ "thomas@thomas-HP-Compaq-8000-Elite-SFF-PC.(none)", "[email protected]" ]
[ [ [ 1, 25 ], [ 27, 30 ], [ 33, 42 ], [ 48, 51 ], [ 55, 59 ], [ 61, 61 ], [ 75, 162 ], [ 173, 179 ], [ 290, 299 ], [ 406, 409 ], [ 412, 428 ], [ 431, 436 ], [ 438, 440 ], [ 443, 449 ], [ 451, 453 ], [ 456, 471 ], [ 473, 498 ], [ 501, 524 ], [ 541, 542 ], [ 544, 587 ], [ 589, 607 ], [ 609, 621 ], [ 631, 631 ], [ 634, 670 ], [ 672, 703 ], [ 712, 722 ], [ 725, 733 ], [ 740, 747 ], [ 763, 765 ] ], [ [ 26, 26 ], [ 31, 32 ], [ 43, 47 ], [ 52, 54 ], [ 60, 60 ], [ 62, 74 ], [ 163, 172 ], [ 180, 289 ], [ 300, 405 ], [ 410, 411 ], [ 429, 430 ], [ 437, 437 ], [ 441, 442 ], [ 450, 450 ], [ 454, 455 ], [ 472, 472 ], [ 499, 500 ], [ 525, 540 ], [ 543, 543 ], [ 588, 588 ], [ 608, 608 ], [ 622, 630 ], [ 632, 633 ], [ 671, 671 ], [ 704, 711 ], [ 723, 724 ], [ 734, 739 ], [ 748, 762 ] ] ]
109c6b6b00ff7071a3a9318593b898d57b6736e6
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/imglib/memmap/source/memmaputils.cpp
bc105162726104b5a86cc0bab189eeace9ec473a
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,188
cpp
/* * Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "memmaputils.h" /** Constructor: MemmapUtils class Initilize the parameters to data members. @internalComponent @released */ MemmapUtils::MemmapUtils( ) : iHFile(0) { #ifdef WIN32 iHMMFile = 0; #endif } /** Destructor: MemmapUtils class Deallocates the memory for data members @internalComponent @released */ MemmapUtils::~MemmapUtils( ) { CloseMapFile(); DeleteMapFile(); } /** OpenMemMapPointer: Opens the memory map pointer @internalComponent @released @param aOffset - Starting offset of the memory map @param aSize - Size of the memory map */ void* MemmapUtils::OpenMemMapPointer(unsigned long aOffset, unsigned long aSize) { #ifdef WIN32 // Create map view pointer return (void*)MapViewOfFile(iHMMFile, FILE_MAP_ALL_ACCESS, 0, aOffset, aSize); #else return KStatFalse; #endif } /** CloseMemMapPointer: Closes the memory map pointer @internalComponent @released @param aData - Memory map pointer @param aSize - Size of the memory map */ int MemmapUtils::CloseMemMapPointer(void* aData, unsigned long aSize) { unsigned long statusFlg = KStatFalse; if(aData && iHFile) { #ifdef WIN32 statusFlg = FlushViewOfFile(aData, aSize); statusFlg &= FlushFileBuffers((HANDLE)_get_osfhandle(iHFile)); statusFlg &= UnmapViewOfFile(aData); #endif } if(statusFlg == (unsigned long)KStatFalse) { return KStatFalse; } return KStatTrue; } /** OpenMapFile: Opens the file for memory mapping @internalComponent @released */ int MemmapUtils::OpenMapFile() { GetMapFileName(iMapFileName); if(iMapFileName.empty()) { return KStatFalse; } #ifdef WIN32 iHFile = open((const char*)iMapFileName.data(), (_O_CREAT | _O_BINARY | _O_RDWR)); #endif if((iHFile == (-1)) || (!iHFile)) { Print(EAlways, "Cannot open the memory map file %s", (char*)iMapFileName.data()); iHFile = 0; return KStatFalse; } return KStatTrue; } /** IsMapFileOpen: Returns the open status of the memory map file @internalComponent @released */ int MemmapUtils::IsMapFileOpen() { return (iHFile) ? KStatTrue : KStatFalse; } /** CloseMapFile: Closes the file for memory mapping @internalComponent @released */ void MemmapUtils::CloseMapFile() { if(iHFile) { #ifdef WIN32 close(iHFile); #endif iHFile = 0; } } /** DeleteMapFile: Deletes the file for memory mapping @internalComponent @released */ void MemmapUtils::DeleteMapFile() { #ifdef WIN32 unlink((char*)iMapFileName.data()); #endif } /** CreateFileMapObject: Creates the map file object @internalComponent @released @param aSize - Size of the memory map */ int MemmapUtils::CreateFileMapObject(unsigned long aSize) { #ifdef WIN32 // Create memory map object for the given size of the file iHMMFile = CreateFileMapping((HANDLE)_get_osfhandle(iHFile), NULL, PAGE_READWRITE, 0, aSize, NULL); if(!iHMMFile || (iHMMFile == INVALID_HANDLE_VALUE)) { return KStatFalse; } #endif return KStatTrue; } /** CloseFileMapObject: Closes the map file object @internalComponent @released */ void MemmapUtils::CloseFileMapObject() { #ifdef WIN32 if(iHMMFile) { CloseHandle(iHMMFile); iHMMFile = 0; } #endif } /** GetMapFileName: Generates a temporary file name @internalComponent @released @param aFile - Returns the name of the temporary file */ void MemmapUtils::GetMapFileName(string& aFile) { char *fileName = 0; #ifdef WIN32 fileName = new char[MAX_PATH]; if(fileName) GetTempFileName(".", "MMAP", 0, fileName); aFile.assign(fileName); #endif if(fileName) delete[] fileName; }
[ "none@none" ]
[ [ [ 1, 237 ] ] ]
63737fb23501808058473771371bf205e2217fca
01fadae9f2a6d3f19bc843841a7faa9c40fc4a20
/CG/Cycle_CGHW2.cpp
b0b287ec09698554f41a307f80650b933f8bfc75
[]
no_license
passzenith/passzenithproject
9999da29ac8df269c41d280137113e1e2638542d
67dd08f4c3a046889319170a89b45478bfd662d2
refs/heads/master
2020-12-24T14:36:46.389657
2010-09-05T02:34:42
2010-09-05T02:34:42
32,310,266
0
0
null
null
null
null
UTF-8
C++
false
false
2,161
cpp
/* CG Assignment #2 By Noravee Sungpuag 50051291 Passarapa Kerdinntra 50051374 */ #include<GL/glut.h> #include <stdio.h> #include <conio.h> #include <time.h> int xCenter,yCenter,radius; int x=0; int y=0; void setPixel(int xC, int yC) { glBegin(GL_POINTS); glVertex2i(xC, yC); glEnd(); glFlush(); } void circleMidPoint(int xc, int yc, int radius) { int h = 1-radius; x=0; y=radius; void circlePlotPoints(int, int, int, int); circlePlotPoints(xc, yc, x, y); while(x < y) { x++; if(h < 0) { h += 2 * x + 3; } else { y--; h += 2 * (x - y) + 5; } circlePlotPoints(xc, yc, x, y); } } void circlePlotPoints(int xc, int yc, int x ,int y) { // Eight-Way Symmetry setPixel(xc + x , yc + y); setPixel(xc - x , yc + y); setPixel(xc + x , yc - y); setPixel(xc - x , yc - y); setPixel(xc + y , yc + x); setPixel(xc - y , yc + x); setPixel(xc + y , yc - x); setPixel(xc - y , yc - x); } void init(void) { glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_PROJECTION); gluOrtho2D(0.0,400.0,0.0,400.0); } void drawMyCircle(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0,0.0,0.0); glPointSize(3.0); //set corodinate at (200,200) circleMidPoint(xCenter+200, yCenter+200, radius); } void input() { scanf ("%d %d %d",&xCenter,&yCenter,&radius); } int main(int argc, char**argv) { input(); //xcenter ycenter radius clock_t cstart, cend; cstart = clock(); glutInit(&argc, argv); //glutInitWindowPosition(0,0); glutInitWindowSize(400,400); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutCreateWindow("Circle with Midpoint algorithm"); init(); glutDisplayFunc(drawMyCircle); cend = clock(); //printf("%d second(s)\n", cstart); //printf("%d second(s)\n", cend); //printf("%e second(s)\n", CLK_TCK); float dif = difftime(cend,cstart); printf("%.2f time\n",dif/CLK_TCK); glutMainLoop(); return 0; }
[ "passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633" ]
[ [ [ 1, 108 ] ] ]
48449d3f6c85be604311cce11acc385378020c8b
9b97e981165cf4a4a00694d51977445b6795499b
/MS-STS_WIN32/ui_mainwindow.h
2979eff294bb5e5b4a200526d4947c29ba044b7e
[]
no_license
trptrp/qtpcap
d81c821ceb5f06f321a96745ef05809f2b77ef7e
cdfbb3b97e75936175aa8b4bf4bc93cc9e1c734e
refs/heads/master
2021-01-02T09:43:05.593126
2010-11-24T08:39:33
2010-11-24T08:39:33
38,862,879
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created: Sat Oct 30 15:22:40 2010 ** by: Qt User Interface Compiler version 4.7.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QComboBox> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QMainWindow> #include <QtGui/QMenuBar> #include <QtGui/QPushButton> #include <QtGui/QStatusBar> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralwidget; QPushButton *pushButton; QComboBox *comboBox; QLabel *label; QMenuBar *menubar; QStatusBar *statusbar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QString::fromUtf8("MainWindow")); MainWindow->resize(620, 230); centralwidget = new QWidget(MainWindow); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); pushButton = new QPushButton(centralwidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(310, 120, 75, 23)); comboBox = new QComboBox(centralwidget); comboBox->setObjectName(QString::fromUtf8("comboBox")); comboBox->setGeometry(QRect(30, 40, 561, 22)); label = new QLabel(centralwidget); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(120, 130, 54, 12)); MainWindow->setCentralWidget(centralwidget); menubar = new QMenuBar(MainWindow); menubar->setObjectName(QString::fromUtf8("menubar")); menubar->setGeometry(QRect(0, 0, 620, 19)); MainWindow->setMenuBar(menubar); statusbar = new QStatusBar(MainWindow); statusbar->setObjectName(QString::fromUtf8("statusbar")); MainWindow->setStatusBar(statusbar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8)); pushButton->setText(QApplication::translate("MainWindow", "PushButton", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("MainWindow", "TextLabel", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "cn.wei.hp@5204a1b5-1fd8-8296-39ea-a28714a575d6" ]
[ [ [ 1, 83 ] ] ]
a8f50775c7f118e949d212642c1d666c84aebad5
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/app/Input_mode_toolbar.cpp
bfb98aba0aefeaafbf700de3c0ddf082ca00adaa
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,663
cpp
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Record_toolbar.cpp 98 2007-05-01 23:11:20Z miklosb $ */ #include <gui/app/Input_mode_toolbar.h> #include <QtGui/QColorGroup> //#include Input_mode_toolbar::Input_mode_toolbar(QWidget* parent): QToolBar(parent) { this->setObjectName("Input toolbar"); setMovable(false); point_button = new QPushButton("Point",this); point_button->setCheckable(true); point_button->setMaximumWidth(45); circle_button = new QPushButton("Circle",this); circle_button->setCheckable(true); circle_button->setMaximumWidth(45); //record_button->setFlat(true); addWidget(point_button); addWidget(circle_button); connect(point_button, SIGNAL(toggled(bool)), this, SLOT(point_button_pushed(bool))); connect(circle_button, SIGNAL(toggled(bool)), this, SLOT(circle_button_pushed(bool))); input_mode = POINT_INPUT_MODE; point_button->setChecked(true); emit input_mode_selected(input_mode); } void Input_mode_toolbar::point_button_pushed(bool checked) { if (checked) { if (circle_button->isChecked()) circle_button->setChecked(false); input_mode = POINT_INPUT_MODE; emit input_mode_selected(input_mode); } } void Input_mode_toolbar::circle_button_pushed(bool checked) { if (checked) { if (point_button->isChecked()) point_button->setChecked(false); input_mode = CIRCLE_INPUT_MODE; emit input_mode_selected(input_mode); } }
[ "balint.miklos@localhost" ]
[ [ [ 1, 50 ] ] ]
fd73429b4463aa3a0e089cc9b984239e7f420038
b5b57f95c6ee44fbb7d9c8ddda870c5338359e01
/common.cpp
b36ef042b29639d554d5db886ea5157a844f9182
[]
no_license
Objelisks/descendinghammer
bcaa81b086da65f4207339c2348cbcdb2c765e44
2cbd67bcfba5ee1008d58bde59cfee18f01166b6
refs/heads/master
2020-04-21T17:26:35.740409
2009-04-04T06:20:01
2009-04-04T06:20:01
32,121,262
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
#include "common.h" volatile int frameRate = 0; double rad(double deg) { return deg*PI/180.0; }; double deg(double rad) { return rad*180.0/PI; }; DrawableWrapper::DrawableWrapper(int _x, int _y, int _z, double _s, BITMAP* img, int c) { x=_x; y=_y; z=_z; s=_s; color=c; image=img; };
[ "supertyrian@ae15d362-055d-11de-a1f0-819f45317607" ]
[ [ [ 1, 23 ] ] ]
03c10355298cb4ea246956a67c15c6a6446f6bee
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/trees/OnionTree.cpp
8686d6c0d1d77611f0eaa070b927614855250389
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,144
cpp
/*** * hesperus: OnionTree.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include "OnionTree.h" #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> using boost::bad_lexical_cast; using boost::lexical_cast; #include <source/exceptions/Exception.h> #include <source/math/geom/GeomUtil.h> namespace hesp { //#################### CONSTRUCTORS #################### OnionTree::OnionTree(const std::vector<OnionNode_Ptr>& nodes, int mapCount) : m_nodes(nodes), m_mapCount(mapCount) { index_leaves(); } //#################### PUBLIC METHODS #################### const OnionLeaf *OnionTree::leaf(int n) const { return m_leaves[n]; } OnionTree_Ptr OnionTree::load_postorder_text(std::istream& is) { std::string line; std::getline(is, line); int mapCount; try { mapCount = lexical_cast<int,std::string>(line); } catch(bad_lexical_cast&) { throw Exception("The map count is not a number"); } std::getline(is, line); int nodeCount; try { nodeCount = lexical_cast<int,std::string>(line); } catch(bad_lexical_cast&) { throw Exception("The onion node count is not a number"); } std::vector<OnionNode_Ptr> nodes(nodeCount); int n = 0; while(n < nodeCount && std::getline(is, line)) { typedef boost::char_separator<char> sep; typedef boost::tokenizer<sep> tokenizer; tokenizer tok(line, sep(" ")); std::vector<std::string> tokens(tok.begin(), tok.end()); size_t tokenCount = tokens.size(); if(tokenCount < 2) throw Exception("Bad onion node: " + lexical_cast<std::string,int>(n)); if(tokens[1] == "B") { if(tokenCount != 11 || tokens[5] != "(" || tokens[10] != ")") throw Exception("Bad branch node: " + lexical_cast<std::string,int>(n)); int leftIndex, rightIndex; double a, b, c, d; try { leftIndex = lexical_cast<int,std::string>(tokens[2]); rightIndex = lexical_cast<int,std::string>(tokens[3]); a = lexical_cast<double,std::string>(tokens[6]); b = lexical_cast<double,std::string>(tokens[7]); c = lexical_cast<double,std::string>(tokens[8]); d = lexical_cast<double,std::string>(tokens[9]); } catch(bad_lexical_cast&) { throw Exception("One of the values was not a number in branch node: " + lexical_cast<std::string,int>(n)); } OnionNode_Ptr left = nodes[leftIndex]; OnionNode_Ptr right = nodes[rightIndex]; if(left && right) { Plane_Ptr splitter(new Plane(Vector3d(a,b,c), d)); nodes[n] = OnionNode_Ptr(new OnionBranch(n, splitter, left, right)); } else throw Exception("The onion nodes are not stored in postorder: the child nodes for this branch have not yet been loaded"); } else { // We're dealing with an onion leaf. if(tokenCount < 8 || tokens[1] != "(" || tokens[3] != ")" || tokens[6] != "[" || tokens[tokenCount-1] != "]") throw Exception("Bad leaf node: " + lexical_cast<std::string,int>(n)); if(tokens[2].length() != mapCount) throw Exception("Bad leaf solidity descriptor: " + lexical_cast<std::string,int>(n)); // Construct the solidity descriptor. boost::dynamic_bitset<> solidityDescriptor(mapCount); for(size_t i=0, len=tokens[2].length(); i<len; ++i) { if(tokens[2][i] == '0') solidityDescriptor.set(i, false); else if(tokens[2][i] == '1') solidityDescriptor.set(i, true); else throw Exception("Bad leaf solidity descriptor: " + lexical_cast<std::string,int>(n)); } // Read in any polygon indices. int polyCount; try { polyCount = lexical_cast<int,std::string>(tokens[5]); } catch(bad_lexical_cast&) { throw Exception("The leaf polygon count is not a number: " + lexical_cast<std::string,int>(n)); } std::vector<int> polyIndices; for(size_t i=7; i<tokenCount-1; ++i) { int polyIndex; try { polyIndex = lexical_cast<int,std::string>(tokens[i]); } catch(bad_lexical_cast&) { throw Exception("A polygon index is not a number in leaf: " + lexical_cast<std::string,int>(n)); } polyIndices.push_back(polyIndex); } nodes[n].reset(new OnionLeaf(n, solidityDescriptor, polyIndices)); } ++n; } return OnionTree_Ptr(new OnionTree(nodes, mapCount)); } int OnionTree::map_count() const { return m_mapCount; } void OnionTree::output_postorder_text(std::ostream& os) const { os << m_mapCount << '\n'; os << m_nodes.size() << '\n'; root()->output_postorder_text(os); } OnionNode_Ptr OnionTree::root() { return m_nodes.back(); } OnionNode_CPtr OnionTree::root() const { return m_nodes.back(); } //#################### PRIVATE METHODS #################### void OnionTree::index_leaves() { index_leaves_sub(root()); } void OnionTree::index_leaves_sub(const OnionNode_Ptr& node) { if(node->is_leaf()) { OnionLeaf *leaf = node->as_leaf(); int nextLeaf = static_cast<int>(m_leaves.size()); leaf->set_leaf_index(nextLeaf); m_leaves.push_back(leaf); } else { OnionBranch *branch = node->as_branch(); index_leaves_sub(branch->left()); index_leaves_sub(branch->right()); } } }
[ [ [ 1, 166 ] ] ]
cd84f4bc79aec1aa67179a51d1131c216c3b8be2
bd48897ed08ecfea35d8e00312dd4f9d239e95c4
/contest/run/E.cpp
f73327e52a3ed7b820e74c8be16148e68e0290a5
[]
no_license
blmarket/lib4bpp
ab83dbb95cc06e7b55ea2ca70012e341be580af1
2c676543de086458b93b1320b7b2ad7f556a24f7
refs/heads/master
2021-01-22T01:28:03.718350
2010-11-30T06:45:42
2010-11-30T06:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
cpp
#include <iostream> #include <queue> #include <set> #include <map> #include <vector> #define mp make_pair #define pb push_back #define sqr(x) ((x)*(x)) #define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int,int> PII; template<typename T> int size(const T &a) { return a.size(); } int n,k; VI data; long long solve1(void) { map<int,long long> M; int sum = 0; M[0]=1; for(int i=0;i<data.size();i++) { sum = (sum + data[i]) % k; M[sum]++; } long long ret=0; foreach(it,M) { ret += (it->second-1) * it->second / 2; ret %= 20091101; } return ret; } int solve2(void) { int ret=0; int sum=0; set<int> S; S.insert(0); for(int i=0;i<data.size();i++) { sum = (sum + data[i]) % k; if(S.count(sum)) { sum=0; ret++; S.clear(); } S.insert(sum); } return ret; } void process(void) { scanf("%d %d",&n,&k); data.resize(n); for(int i=0;i<n;i++) { scanf("%d",&data[i]); } cout << solve1() << " " << solve2() << endl; } int main(void) { int N; scanf("%d",&N); for(int i=1;i<=N;i++) { process(); } }
[ "blmarket@dbb752b6-32d3-11de-9d05-31133e6853b1" ]
[ [ [ 1, 85 ] ] ]
c1ad262e81409d77b19f4d34a43f0348308ce4de
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/chordtext.h
2ac7c5f548a34fd8187c897d68009bae09fe14f7
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
4,154
h
///////////////////////////////////////////////////////////////////////////// // Name: chordtext.h // Purpose: Stores and renders chord text // Author: Brad Larsen // Modified by: // Created: Jan 3, 2005 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifndef __CHORDTEXT_H__ #define __CHORDTEXT_H__ #include "chordname.h" /// Stores and renders chord text class ChordText : public PowerTabObject { friend class ChordTextTestSuite; // Constants public: // Default Constants static const wxByte DEFAULT_POSITION; ///< Default value for the position member variable protected: wxByte m_position; ///< Zero-based index of the position within the system where the chord text is anchored ChordName m_chordName; ///< Chord name data (see ChordName class for details) public: // Constructor/Destructor ChordText(); ChordText(wxUint32 position, const ChordName& chordName); ChordText(const ChordText& chordText); ~ChordText(); // Creation Functions /// Creates an exact duplicate of the object /// @return The duplicate object PowerTabObject* CloneObject() const {return (new ChordText(*this));} // Operators const ChordText& operator=(const ChordText& chordText); bool operator==(const ChordText& chordText) const; bool operator!=(const ChordText& chordText) const; // Serialization functions protected: bool DoSerialize(PowerTabOutputStream& stream); bool DoDeserialize(PowerTabInputStream& stream, wxWord version); public: // MFC Class Functions /// Gets the MFC Class Name for the object /// @return The MFC Class Name wxString GetMFCClassName() const {return (wxT("CChordText"));} /// Gets the MFC Class Schema for the object /// @return The MFC Class Schema wxWord GetMFCClassSchema() const {return ((wxWord)1);} // Position Functions /// Determines whether a position is valid /// @param position Position to validate /// @return True if the position is valid, false if not static bool IsValidPosition(wxUint32 position) {return ((position >= 0) && (position <= 255));} /// Sets the position within the system where the chord text is anchored /// @param position Zero-based index within the system where the chord text is anchored /// @return True if the position was set, false if not bool SetPosition(wxUint32 position) {wxCHECK(IsValidPosition(position), false); m_position = (wxByte)position; return (true);} /// Gets the position within the system where the chord text is anchored /// @return The position within the system where the chord text is anchored wxUint32 GetPosition() const {return (m_position);} // Chord Name Functions /// Sets the chord name void SetChordName(const ChordName& chordName) {m_chordName = chordName;} /// Gets the chord name /// @return The chord name ChordName GetChordName() const {return (m_chordName);} /// Gets a referenced to the chord name /// @return A reference to the chord name ChordName& GetChordNameRef() {return (m_chordName);} /// Gets a constant reference to the chord name /// @return A constant reference to the chord name const ChordName& GetChordNameConstRef() const {return (m_chordName);} /// Gets a pointer to the chord name /// @return A pointer to the chord name ChordName* GetChordNamePtr() {return (&m_chordName);} }; // Array Declarations WX_DEFINE_POWERTABARRAY(ChordText*, ChordTextArray); #endif
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 106 ] ] ]
44c1c2b2f96a420f4acb7409be064ec2f5e58dc3
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/WinService/GTest/stdafx.cpp
16c66f9d0a891abf9e725947e6fdd15d22753f35
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
GB18030
C++
false
false
265
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // GTest.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
d6bb27d83b9e0deb5ae16d43206f521cc87b5b07
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Utility/FileCollection.h
d20c4831bec97cb5328f386aaf7d75000da5eb52
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
1,783
h
/* FileCollection.h Written by Matthew Fisher A FileCollection stores a large number of files as a single file. It is similar to a tar file in functionality. */ #pragma once const UINT MaxFilenameLength = 512; struct FileCollectionHeader { UINT FileCount; }; struct FileCollectionFileHeader { char Filename[MaxFilenameLength]; UINT FileSize; }; struct FileCollectionFile { void GetFileLines(Vector<String> &Lines); String Filename; Vector<BYTE> Data; }; class FileCollection { public: FileCollection(); ~FileCollection(); void FreeMemory(); // // Save/Load collection to disk // void LoadAll(const String &Filename, bool Muddle = true); void SaveAll(const String &Filename, bool Muddle = true); void DumpCollectionToDisk(); // // Modify collection // void AddFileFromMemory(const String &FileCollectionName, const Vector<BYTE> &Data); void AddFileFromDisk(const String &FileCollectionName, const String &ExistingFilename); void RemoveFile(const String &FileCollectionName); FileCollectionFile* AddAndUpdateFile(const String &FileCollectionName, const String &ExistingFilename); FileCollectionFile* FindFile(const String &FileCollectionName); void GetFileLines(const String &Filename, Vector<String> &Lines); __forceinline UINT FileCount() { return _FileList.Length(); } __forceinline const FileCollectionFile& GetFile(UINT Index) { return *(_FileList[Index]); } private: void MuddleData(Vector<BYTE> &Data); Mutex _FileListMutex; Vector<FileCollectionFile *> _FileList; map<String, FileCollectionFile *, String::LexicographicComparison> _FileMap; };
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 68 ] ] ]
c10e68ce520d666b4f5f03b79ba8e8e59a93db33
0bb573926a584973e63de0ea6ecfa627fcc54710
/kinect_headtracking/KProgram.h
bb0be8676c66a955eabace8be14e91addc14bf69
[]
no_license
hadgiske/kinect-head-tracking
19157f9c3247e90f76975099b06a459642d5af7d
a9d0a76dc9274728e8404f91a4c91232065b7269
refs/heads/master
2021-01-20T02:15:24.608847
2011-01-07T01:31:27
2011-01-07T01:31:27
32,096,537
2
0
null
null
null
null
UTF-8
C++
false
false
696
h
#pragma once #include <cstdlib> #include <gl/glut.h> #include "defines.h" #include "KHeadTrack.h" #include "KGlutInput.h" #include "kKinect.h" class KProgram { // This to be the main-helper-class and thus it should only be static, so no constructor private: KProgram(void); ~KProgram(void); // Saves the window-handle of the main window static int mWindowHandle; public: // Sets up Glut for working static void initGlut(int argc, char* argv[]); static void glutDisplay(void); static void glutIdle(void); static void showWindow(void); static kKinect kinect; static KHeadTrack headtrack; static float x2; static float y2; static float z2; };
[ "eusebius90@17e18ffd-2d5c-bf65-2f45-b884abe9fe7f", "Sp3ssi@17e18ffd-2d5c-bf65-2f45-b884abe9fe7f" ]
[ [ [ 1, 1 ], [ 3, 6 ], [ 8, 9 ], [ 11, 26 ], [ 28, 28 ], [ 33, 34 ] ], [ [ 2, 2 ], [ 7, 7 ], [ 10, 10 ], [ 27, 27 ], [ 29, 32 ] ] ]
af0f39d724ec2188406e29bda2d68921ea526d26
a04058c189ce651b85f363c51f6c718eeb254229
/Src/HyperlinkHandler.hpp
3e7e5c3007e6adf06dc18bdd01706bc5ce7ce02f
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
6,236
hpp
#ifndef HYPERLINK_HANDLER_HPP__ #define HYPERLINK_HANDLER_HPP__ #include <Definition.hpp> #define urlSchemaHttp _T("http") #define urlSchemaDream _T("dream") #define urlSchemaMovie _T("movie") #define urlSchemaTheatre _T("theatre") #define urlSchemaLyricsForm _T("lyricsform") #define urlSchemaMenu _T("menu") #define urlSchemaRunModule _T("runmodule") #define urlSchemaAmazonPreferences _T("amazonpreferences") #define urlSchemaAmazonForm _T("amazonform") #define urlSchemaAmazonSearch _T("s+amazonsearch") #define urlSchemaSimpleFormWithDefinition _T("simpleform") #define urlSchemaNetflixForm _T("netflixform") #define urlSchemaListsOfBestsForm _T("listsofbestsform") #define urlSchemaEncyclopediaTerm _T("s+pediaterm") #define urlSchemaEncyclopediaRandom _T("s+pediarandom") #define urlSchemaEncyclopediaSearch _T("s+pediasearch") #define urlSchemaEncyclopediaLangs _T("s+pedialangs") #define urlSchemaEncyclopediaStats _T("s+pediastats") #define urlSchemaEncyclopedia _T("pedia") #define urlSchemaDict _T("dict") #define urlSchemaDictTerm _T("s+dictterm") #define urlSchemaDictRandom _T("s+dictrandom") #define urlSchemaDictForm _T("dictform") #define urlSchemaDictStats _T("s+dictstats") #define urlSchemaDictChangeDict _T("hs+dictstats:") #define urlSchemaDictChangeDictNonShip _T("hs+dictstats:private") #define urlSchemaEBookSearch _T("s+eBook-search") #define urlSchemaEBookDownload _T("s+eBook-download") #define urlSchemaEBookBrowse _T("s+eBook-browse") #define urlSchemaEBookHome _T("s+eBook-home") #define urlSchemaEBook _T("eBook") #define urlSchemaEBayForm _T("ebayform") #define urlSchemaClipboardCopy _T("clipbrdcopy") #define urlSeparatorSchema _T(':') #define urlSeparatorFlags _T('+') #define urlSeparatorSchemaStr _T(":") #define urlSeparatorFlagsStr _T("+") #define urlFlagServer _T('s') #define urlFlagClosePopup _T('c') #define urlFlagHistory _T('h') #define urlFlagHistoryInCache _T('H') #define pediaUrlPartSetLang _T("lang") #define pediaUrlPartHome _T("home") #define pediaUrlPartSearchDialog _T("search") #define pediaUrlPartShowArticle _T("article") #define ebookUrlPartSearch _T("search") #define ebookUrlPartMove _T("move") #define ebookUrlPartDelete _T("delete") #define ebookUrlPartCopy _T("copy") #define ebookUrlPartLaunch _T("launch") #define ebookUrlPartManage _T("manage") #define ebookUrlPartBrowse _T("browse") #define ebookUrlPartDownload _T("download") #define urlSchemaFlickr _T("flickr") #define flickrUrlPartAbout _T("about") const ArsLexis::char_t* hyperlinkData(const char_t* hyperlink, ulong_t& length); class HyperlinkHandler: public HyperlinkHandlerBase { public: typedef void (HyperlinkHandler::* HandlerFunction)(const char_t* hyperlink, ulong_t len, const Point*); private: static HandlerFunction findHandler(const char_t* schema, ulong_t len); static void closePopup(uint_t id); static void closePopup(); enum HandlerFlag { flagServerHyperlink = 1, flagClosePopupForm = 2, flagHistory = 4, flagHistoryInCache = 8 }; static uint_t interpretFlag(ArsLexis::char_t flag); void handleRunModule(const char_t* hyperlink, ulong_t len, const Point* point); void handleHttp(const char_t* hyperlink, ulong_t len, const Point* point); void handleDream(const char_t* hyperlink, ulong_t len, const Point* point); void handleMovie(const char_t* hyperlink, ulong_t len, const Point* point); void handleTheatre(const char_t* hyperlink, ulong_t len, const Point* point); void handleLyricsForm(const char_t* hyperlink, ulong_t len, const Point* point); void handleDictForm(const char_t* hyperlink, ulong_t len, const Point* point); void handleMenu(const char_t* hyperlink, ulong_t len, const Point* point); void handleAmazonForm(const char_t* hyperlink, ulong_t len, const Point* point); void handleAmazonPreferences(const char_t* hyperlink, ulong_t len, const Point* point); void handleSimpleFormWithDefinition(const char_t* hyperlink, ulong_t len, const Point* point); void handleClipboardCopy(const char_t* hyperlink, ulong_t len, const Point* point); void handleListsOfBestsForm(const char_t* hyperlink, ulong_t len, const Point* point); void handleEBayForm(const char_t* hyperlink, ulong_t len, const Point* point); void handlePedia(const char_t* hyperlink, ulong_t len, const Point* point); void handlePediaHome(const char_t* hyperlink, ulong_t len, const Point* point); void handlePediaLang(const char_t* hyperlink, ulong_t len, const Point* point); void handlePediaSearch(const char_t* hyperlink, ulong_t len, const Point* point); void handlePediaArticle(const char_t* hyperlink, ulong_t len, const Point* point); void handleEBook(const char_t* hyperlink, ulong_t len, const Point* point); void handleEBookDownload(const char_t* data, ulong_t len); void handleNetflixForm(const char_t* hyperlink, ulong_t len, const Point* point); void handleFlickr(const char_t* hyperlink, ulong_t len, const Point* point); public: void handleHyperlink(const char_t* hyperlink, ulong_t len, const Point* point); virtual ~HyperlinkHandler(); }; ArsLexis::String buildUrl(const ArsLexis::char_t* schema, const ArsLexis::char_t* data); #endif // HYPERLINK_HANDLER_HPP__
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c", "szymonk@a75a507b-23da-0310-9e0c-b29376b93a3c", "kjk@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 33 ], [ 37, 141 ] ], [ [ 34, 34 ], [ 36, 36 ] ], [ [ 35, 35 ] ] ]
91d50d42cb59417cd914b5668982a9e9c35a4092
cd61c8405fae2fa91760ef796a5f7963fa7dbd37
/Sauron/SonarUnitTests/LineSegmentTest.cpp
c55e17e94b579b5ff4a6659819c4d12bda5e09b9
[]
no_license
rafaelhdr/tccsauron
b61ec89bc9266601140114a37d024376a0366d38
027ecc2ab3579db1214d8a404d7d5fa6b1a64439
refs/heads/master
2016-09-05T23:05:57.117805
2009-12-14T09:41:58
2009-12-14T09:41:58
32,693,544
0
0
null
null
null
null
UTF-8
C++
false
false
8,419
cpp
#include "MathHelper.h" #include "LineSegment.h" #include "ariaUtil.h" using namespace System; using namespace System::Text; using namespace System::Collections::Generic; using namespace Microsoft::VisualStudio::TestTools::UnitTesting; namespace SonarUnitTests { [TestClass] public ref class LineSegmentTest { private: TestContext^ testContextInstance; public: /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext { Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get() { return testContextInstance; } System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value) { testContextInstance = value; } }; #pragma region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //static void MyClassInitialize(TestContext^ testContext) {}; // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //static void MyClassCleanup() {}; // //Use TestInitialize to run code before running each test //[TestInitialize()] //void MyTestInitialize() {}; // //Use TestCleanup to run code after each test has run //[TestCleanup()] //void MyTestCleanup() {}; // #pragma endregion [TestMethod] void TestSauronLine() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(36100, 3900, 43750, 3900); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(390.0, sauronLine.getRWall(), 0.0001); Assert::AreEqual(sauron::trigonometry::PI / 2, sauronLine.getTheta()); }; [TestMethod] void TestSauronLine_2() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(35970, 400, 35970, 1250); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(3597, sauronLine.getRWall(), 0.0001); Assert::AreEqual(0, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_3() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, -1000, -1000, 1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(100, sauronLine.getRWall(), 0.0001); Assert::AreEqual(sauron::trigonometry::PI, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_4() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, 1000, 1000, 1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(100, sauronLine.getRWall(), 0.0001); Assert::AreEqual(sauron::trigonometry::PI / 2, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_5() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(1000, 1000, 1000, -1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(100, sauronLine.getRWall(), 0.0001); Assert::AreEqual(0, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_6() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, -1000, 1000, -1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(100, sauronLine.getRWall(), 0.0001); Assert::AreEqual(-(sauron::trigonometry::PI / 2), sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_7() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-3000, 5000, 7000, -5000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(sauron::trigonometry::PI / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_8() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-7000, 5000, 3000, -5000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual((-3 *sauron::trigonometry::PI) / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_9() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-7000, -5000, 3000, 5000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual((3 *sauron::trigonometry::PI) / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_10() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-3000, -5000, 7000, 5000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual((-1*sauron::trigonometry::PI) / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_11() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, -1000, 1000, 1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(0, sauronLine.getRWall(), 0.0001); Assert::AreEqual((sauron::trigonometry::PI) / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_12() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, 1000, 1000, -1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(0, sauronLine.getRWall(), 0.0001); Assert::AreEqual((-1*sauron::trigonometry::PI) / 4, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_13() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(-1000, 0, 1000, 0); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(0, sauronLine.getRWall(), 0.0001); Assert::AreEqual(sauron::trigonometry::PI / 2, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_14() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(300, 0, 1000, 0); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(0, sauronLine.getRWall(), 0.0001); Assert::AreEqual(sauron::trigonometry::PI / 2, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestSauronLine_15() { // construtor do ArLineSegment em mm ArLineSegment lineSegment(0, -1000, 0, 1000); sauron::LineSegment sauronSegment(lineSegment); sauron::Line sauronLine = sauronSegment.getSauronLine(); Assert::AreEqual(0, sauronLine.getRWall(), 0.0001); Assert::AreEqual(0, sauronLine.getTheta(), 0.0001); }; [TestMethod] void TestContains() { // construtor do ArLineSegment em mm sauron::LineSegment lineSegment(0, 0, 20, 0); sauron::LineSegment segmentInside(5, 0, 15, 0); Assert::IsTrue(lineSegment.contains(segmentInside)); }; [TestMethod] void TestContains_2() { // construtor do ArLineSegment em mm sauron::LineSegment lineSegment(0, 0, 20, 0); sauron::LineSegment segmentInside(0, 0, 20, 0); Assert::IsTrue(lineSegment.contains(segmentInside)); }; [TestMethod] void TestContains_3() { // construtor do ArLineSegment em mm sauron::LineSegment lineSegment(0, 0, 20, 0); sauron::LineSegment segmentInside(0, 5, 21, 0); Assert::IsFalse(lineSegment.contains(segmentInside)); }; [TestMethod] void TestContains_4() { // construtor do ArLineSegment em mm sauron::LineSegment lineSegment(0, 0, 0, 20); sauron::LineSegment segmentInside(0, 5, 0, 10); Assert::IsTrue(lineSegment.contains(segmentInside)); }; }; }
[ "budsbd@8373e73c-ebb0-11dd-9ba5-89a75009fd5d" ]
[ [ [ 1, 254 ] ] ]
1db6640b357e6046547184dbb4b877f2c4918c77
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/date_time/src/gregorian/greg_names.hpp
87feec785b3e4a8690debb5b529d263d10b92aa2
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,378
hpp
/* Copyright (c) 2002-2004 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) * Author: Jeff Garland, Bart Garst * $Date: 2004/07/18 18:35:16 $ */ #ifndef DATE_TIME_SRC_GREG_NAMES_HPP___ #define DATE_TIME_SRC_GREG_NAMES_HPP___ #include "boost/date_time/gregorian/greg_month.hpp" #include "boost/date_time/special_defs.hpp" namespace boost { namespace gregorian { const char* const short_month_names[NumMonths]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec", "NAM"}; const char* const long_month_names[NumMonths]={"January","February","March","April","May","June","July","August","September","October","November","December","NotAMonth"}; const char* const special_value_names[date_time::NumSpecialValues]={"not-a-date-time","-infinity","+infinity","min_date_time","max_date_time","not_special"}; const char* const short_weekday_names[]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; const char* const long_weekday_names[]= {"Sunday","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; #ifndef BOOST_NO_STD_WSTRING const wchar_t* const w_short_month_names[NumMonths]={L"Jan",L"Feb",L"Mar",L"Apr",L"May",L"Jun",L"Jul",L"Aug",L"Sep",L"Oct",L"Nov",L"Dec",L"NAM"}; const wchar_t* const w_long_month_names[NumMonths]={L"January",L"February",L"March",L"April",L"May",L"June",L"July",L"August",L"September",L"October",L"November",L"December",L"NotAMonth"}; const wchar_t* const w_special_value_names[date_time::NumSpecialValues]={L"not-a-date-time",L"-infinity",L"+infinity",L"min_date_time",L"max_date_time",L"not_special"}; const wchar_t* const w_short_weekday_names[]={L"Sun", L"Mon", L"Tue", L"Wed", L"Thu", L"Fri", L"Sat"}; const wchar_t* const w_long_weekday_names[]= {L"Sunday",L"Monday",L"Tuesday", L"Wednesday", L"Thursday", L"Friday", L"Saturday"}; #endif // BOOST_NO_STD_WSTRING } } // boost::gregorian #endif // DATE_TIME_SRC_GREG_NAMES_HPP___
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 43 ] ] ]
0a38ac5c96c0aa22d3057e8ef39f954eb6cc7d49
8d3bc2c1c82dee5806c4503dd0fd32908c78a3a9
/samples/entity/component_health.cpp
6ab804589d538744f5aa5112d5cc0011ba0d9c04
[]
no_license
ryzom/werewolf2
2645d169381294788bab9a152c4071061063a152
a868205216973cf4d1c7d2a96f65f88360177b69
refs/heads/master
2020-03-22T20:08:32.123283
2010-03-05T21:43:32
2010-03-05T21:43:32
140,575,749
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
#include "component_health.h" bool ComponentHealth::handleEvent(EntityEvent event, Entity *subject) { nlinfo("Retrieving health: %d", subject->GetProperty<int>("MaxHealth").Get()); return true; }
[ [ [ 1, 6 ] ] ]
518131310403bc5238d9154cefa0694dd762c39d
e7788311c515f48118df40d1fd9f72d457bebff5
/SimpleEchoUDPServer/SimpleEchoUDPServer.cpp
997ee13dae26a4e768eec2b0e7dcec5833c6dbcc
[]
no_license
jbreslin33/dreamsock
3af9131bd8437a2996e37b8413c6c85adfe5dbb1
b6ee1bc1552266aef16970994493cc88fd172848
refs/heads/master
2021-01-02T09:31:59.704311
2010-12-21T05:28:21
2010-12-21T05:28:21
37,391,262
0
1
null
null
null
null
UTF-8
C++
false
false
3,865
cpp
/* Simple echo UDP server Teijo Hakala 2001 */ // Define _WINSOCKAPI_ so windows.h will not include old WinSock header. #ifndef _WINSOCKAPI_ #define _WINSOCKAPI_ #endif #include <windows.h> #include <winsock2.h> #include <stdio.h> // Declare the sockets we use. SOCKET Socket; int dreamSock_InitializeWinSock(void) { WORD versionRequested; WSADATA wsaData; DWORD bufferSize = 0; LPWSAPROTOCOL_INFO SelectedProtocol; int NumProtocols; // Start WinSock2. If it fails, we do not need to call WSACleanup() versionRequested = MAKEWORD(2, 0); int error = WSAStartup(versionRequested, &wsaData); if(error) { return 1; } else { // Confirm that the WinSock2 DLL supports the exact version // we want. If not, call WSACleanup(). if(LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) { WSACleanup(); return 1; } } // Call WSAEnumProtocols to figure out how big of a buffer we need NumProtocols = WSAEnumProtocols(NULL, NULL, &bufferSize); if( (NumProtocols != SOCKET_ERROR) && (WSAGetLastError() != WSAENOBUFS) ) { WSACleanup(); return 1; } // Allocate a buffer, call WSAEnumProtocols to get an array of // WSAPROTOCOL_INFO structs SelectedProtocol = (LPWSAPROTOCOL_INFO) malloc(bufferSize); if(SelectedProtocol == NULL) { WSACleanup(); return 1; } // Allocate memory for protocol list and define what protocols to look for int *protos = (int *) calloc(2, sizeof(int)); protos[0] = IPPROTO_TCP; protos[1] = IPPROTO_UDP; NumProtocols = WSAEnumProtocols(protos, SelectedProtocol, &bufferSize); free(protos); protos = NULL; free(SelectedProtocol); SelectedProtocol = NULL; if(NumProtocols == SOCKET_ERROR) { WSACleanup(); return 1; } return 0; } int InitSockets(void) { struct sockaddr *servAddr; struct sockaddr_in *inetServAddr; int error = 0; // Create the socket. Socket = socket(AF_INET, SOCK_DGRAM, 0); if(Socket < 0) { printf("error: socket() failed"); return -1; } // Allocate memory for the address structure and set it to zero. servAddr = (struct sockaddr *) malloc(sizeof(sockaddr)); memset((char *) servAddr, 0, sizeof(sockaddr)); // Fill the address structure. servAddr->sa_family = (u_short) AF_INET; inetServAddr = (struct sockaddr_in *) servAddr; inetServAddr->sin_port = htons((u_short) 9009); // Bind the address information to the socket. error = bind(Socket, servAddr, sizeof(sockaddr)); if(error == SOCKET_ERROR) { printf("error: bind() failed"); free(servAddr); return -1; } free(servAddr); servAddr = NULL; return 0; } void ServerProcess(void) { struct sockaddr_in inetClientAddr; int clientLen; int connectionOpen; char buf[2]; clientLen = sizeof(inetClientAddr); connectionOpen = 1; // Loop as long as connection is open. while(connectionOpen) { // Read the incoming data from the connected socket. if(recvfrom(Socket, buf, 2, 0, (struct sockaddr *) &inetClientAddr, &clientLen)) { // Set the received letter to upper-case and // make sure the string ends after that by setting the next // byte to NULL. buf[0] = toupper(buf[0]); buf[1] = '\0'; printf("Got message from client: %s\n", buf); // Send the feedback. if(sendto(Socket, buf, 2, 0, (struct sockaddr *) &inetClientAddr, clientLen) == SOCKET_ERROR) { connectionOpen = 0; } } else { connectionOpen = 0; } } } int main(void) { if(dreamSock_InitializeWinSock() != 0) { printf("Critical error, quitting\n"); return -1; } if(InitSockets() != 0) { printf("Critical error, quitting\n"); WSACleanup(); return -1; } ServerProcess(); WSACleanup(); return 0; }
[ "jbreslin33@localhost" ]
[ [ [ 1, 194 ] ] ]
bbe1fbe1d834c2545658e78a965cd5a3f8147ee3
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/Neuz/clord.h
9d4aff595bbec0f65ada808b34936146f3a411f2
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
2,255
h
#ifndef __CLORD_H__ #define __CLORD_H__ #if __VER >= 12 // __LORD #include "lord.h" // 아래의 클라이언트용 클래스들은 // 기본 클래스들을 상속 받는 후 // 후크 함수(Do...로 시작하는)들을 재정의 하여 // 화면 출력을 처리하게 한다 class CCLord : public CLord { public: CCLord(); virtual ~CCLord(); static CCLord* Instance( void ); virtual void CreateColleagues( void ); virtual void DestroyColleagues( void ); }; //////////////////////////////////////////////////////////////////////////////// class CCElection : public IElection { public: CCElection( CLord* pLord ); virtual ~CCElection(); void UpdateUI( void ); void State( void ); SPC GetRanker(int nRanking); time_t GetRestTimeBeginCandidacy( void ) { return GetBegin() - time_null(); } time_t GetRestTimeBeginVote( void ) { return GetBegin() + property.tCandidacy - time_null(); } time_t GetRestTimeEndVote( void ) { return GetBegin() + property.tCandidacy + property.tVote - time_null(); } void PrintCaption( const char* lpCaption ); protected: virtual BOOL DoTestBeginCandidacy( void ); virtual BOOL DoTestBeginVote( int & nRequirement ); virtual BOOL DoTestEndVote( u_long idPlayer ); virtual BOOL DoTestAddDeposit( u_long idPlayer, __int64 iDeposit, time_t tCreate ); virtual void DoAddDepositComplete( u_long idPlayer, __int64 iDeposit, time_t tCreate ); virtual void DoSetPlegeComplete( void ); virtual BOOL DoTestIncVote( u_long idPlayer, u_long idElector ); virtual void DoIncVoteComplete( void ); virtual void DoEndVoteComplete( void ); }; //////////////////////////////////////////////////////////////////////////////// class CLEvent : public ILordEvent { public: CLEvent( CLord* pLord ); virtual ~CLEvent(); void UpdateUI(); protected: virtual BOOL DoTestAddComponent( CLEComponent* pComponent ); virtual BOOL DoTestInitialize( void ); }; //////////////////////////////////////////////////////////////////////////////// namespace election { BOOL IsActivePlayer( u_long idPlayer ); }; //////////////////////////////////////////////////////////////////////////////// #endif // __LORD #endif // __CLORD_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 77 ] ] ]
9b8e851e71802c9cc217b4963973a3c44c3c572f
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/SceneData/Mesh/Channels/hkxEdgeSelectionChannel.h
f3130402df4c4d322a051c3509282dd4d0744b1f
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,745
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-2008 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 INC_EDGE_SELECTION_CHANNEL_H #define INC_EDGE_SELECTION_CHANNEL_H /// Meta information extern const class hkClass hkxEdgeSelectionChannelClass; /// Stores a selection of edges. Edges are specified by triangleIndex*3 + {0,1,2} . class hkxEdgeSelectionChannel { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA, hkxEdgeSelectionChannel ); HK_DECLARE_REFLECTION(); // // Members // public: hkInt32* m_selectedEdges; hkInt32 m_numSelectedEdges; }; #endif // INC_EDGE_SELECTION_CHANNEL_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * 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 * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 53 ] ] ]
8e04ef5019559fa95487ae45a4714b7027b60a23
7c51155f60ff037d1b8d6eea1797c7d17e1d95c2
/Demo/ExceptionThrower.cpp
c84d164694abb22dd557fdceaba3a71e2b91bad5
[]
no_license
BackupTheBerlios/ejvm
7258cd180256970d57399d0c153d00257dbb127c
626602de9ed55a825efeefd70970c36bcef0588d
refs/heads/master
2020-06-11T19:47:07.882834
2006-07-10T16:39:59
2006-07-10T16:39:59
39,960,044
0
0
null
null
null
null
UTF-8
C++
false
false
2,938
cpp
#include "ExceptionThrower.h" #include "Loader.h" #include "Object.h" #include "ClassData.h" ExceptionThrower* ExceptionThrower::exceptionThrowerInstance = NULL; Object* ExceptionThrower::exceptionObject = NULL; ExceptionThrower::ExceptionThrower() { } ExceptionThrower::~ExceptionThrower() { } ExceptionThrower* ExceptionThrower::getInstance() { //This method should be implemented , for now it returns NULL. if(exceptionThrowerInstance==NULL) exceptionThrowerInstance = new ExceptionThrower(); return exceptionThrowerInstance; } /** * @brief save the exception occured by any module. This excepion * should be checked latter by any other module wants to catch this * exception... */ //obj = new object void ExceptionThrower::throwException(const char * exceptionClassName, const char * message) { //This method should be implemented , for now it will be empty.. Loader * loadclass = Loader::getInstance(); ClassData* exceptionClassData = loadclass->getClassData(exceptionClassName); exceptionObject = new Object(exceptionClassData); } /** * This method takes an object of type java.lang.Throwable and throw it.... */ void ExceptionThrower::throwException(Object * throwableObj) { //This method should be implemented , for now it will be empty.. exceptionObject = throwableObj; } /** * This method takes a pointer to the class data of the exception class and instantiate an object of this class. * using the message to call the constructor of the Throwable object. */ void ExceptionThrower::throwException(ClassData* exceptionClassData, const char * message) { //This method should be implemented , for now it will be empty.. exceptionObject = new Object(exceptionClassData); } /** * This method returns The Exception Object describes the pending exception. * returns NULL if no pending exceptions. */ Object* ExceptionThrower::exceptionOccured() { //This method should be implemented , for now it will return NULL. return exceptionObject; } /**This method should call the printStackTrace method to the pending Excetion Object *Till we support the GNU classpath, this method will print *print the Class name of the pending Exception if any. *After the printing , this method should clear the pending exception. */ void ExceptionThrower::printPendingException() { //print the class name of the pending exception if any, for now if(exceptionObject==NULL) ;//printf("No pending Exception\n"); else { //printf("Exception of type: "); //printf((exceptionObject->getClassData())->getFQName()); //printf("is pending\n"); ; } exceptionObject=NULL; } /** This method clears any pending exception. */ void ExceptionThrower::clearPendingException() { //this method should be implemented , for now it is empty... exceptionObject=NULL; }
[ "almahallawy" ]
[ [ [ 1, 98 ] ] ]
82cf510c1b6c56da3fe440b6334c9ca7efd04b64
33cdd09e352529963fe8b28b04e0d2e33483777b
/trunk/LMPlugin/tiDCFrequencyI_Recordset.cpp
425295b7cf2db6163b27a42ca1e21ecf1a07c501
[]
no_license
BackupTheBerlios/reportasistent-svn
20e386c86b6990abafb679eeb9205f2aef1af1ac
209650c8cbb0c72a6e8489b0346327374356b57c
refs/heads/master
2020-06-04T16:28:21.972009
2010-05-18T12:06:48
2010-05-18T12:06:48
40,804,982
0
0
null
null
null
null
UTF-8
C++
false
false
2,444
cpp
// tiDCFrequencyI_Recordset.cpp : implementation file // /* This file is part of LM Report Asistent. Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova LM Report Asistent 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. LM Report Asistent is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LM Report Asistent; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tiDCFrequencyI_Recordset.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // tiDCFrequencyI_Recordset IMPLEMENT_DYNAMIC(tiDCFrequencyI_Recordset, CRecordset) tiDCFrequencyI_Recordset::tiDCFrequencyI_Recordset(CDatabase* pdb) : CRecordset(pdb) { //{{AFX_FIELD_INIT(tiDCFrequencyI_Recordset) m_DCFrequencyIID = 0; m_HypothesisDCID = 0; m_CedentTypeID = 0; m_TaskID = 0; m_Col = 0; m_Frequency = 0; m_nFields = 6; //}}AFX_FIELD_INIT m_nDefaultType = snapshot; } CString tiDCFrequencyI_Recordset::GetDefaultSQL() { return _T("[tiDCFrequencyI]"); } void tiDCFrequencyI_Recordset::DoFieldExchange(CFieldExchange* pFX) { //{{AFX_FIELD_MAP(tiDCFrequencyI_Recordset) pFX->SetFieldType(CFieldExchange::outputColumn); RFX_Long(pFX, _T("[DCFrequencyIID]"), m_DCFrequencyIID); RFX_Long(pFX, _T("[HypothesisDCID]"), m_HypothesisDCID); RFX_Long(pFX, _T("[CedentTypeID]"), m_CedentTypeID); RFX_Long(pFX, _T("[TaskID]"), m_TaskID); RFX_Long(pFX, _T("[Col]"), m_Col); RFX_Long(pFX, _T("[Frequency]"), m_Frequency); //}}AFX_FIELD_MAP } ///////////////////////////////////////////////////////////////////////////// // tiDCFrequencyI_Recordset diagnostics #ifdef _DEBUG void tiDCFrequencyI_Recordset::AssertValid() const { CRecordset::AssertValid(); } void tiDCFrequencyI_Recordset::Dump(CDumpContext& dc) const { CRecordset::Dump(dc); } #endif //_DEBUG
[ "chrzm@fded5620-0c03-0410-a24c-85322fa64ba0" ]
[ [ [ 1, 81 ] ] ]
2e61fba7b17a497d155bc72c106c8912e24a3192
21868e763ab7ee92486a16164ccf907328123c00
/completer.cpp
772b6a95f25cfcce8d886d71d3873791f9faff51
[]
no_license
nodesman/flare
73aacd54b5b59480901164f83905cf6cc77fe2bb
ba95fbfdeec1d557056054cbf007bf485c8144a6
refs/heads/master
2020-05-09T11:17:15.929029
2011-11-26T16:54:07
2011-11-26T16:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include "completer.h" #include <QCompleter> Completer::Completer(QWidget *parent) { }
[ [ [ 1, 7 ] ] ]
d9c9bfee44ad9369d0185b2bcbd71e91d03c01b8
877bad5999a3eeab5d6d20b5b69a273b730c5fd8
/TestKhoaLuan/DirectShowTVSample/WinCap/CDVProp.cpp
b0bd0df0e3be6d459f6e6bb80db7b530653e2fda
[]
no_license
eaglezhao/tracnghiemweb
ebdca23cb820769303d27204156a2999b8381e03
aaae7bb7b9393a8000d395c1d98dcfc389e3c4ed
refs/heads/master
2021-01-10T12:26:27.694468
2010-10-06T01:15:35
2010-10-06T01:15:35
45,880,587
1
0
null
null
null
null
UTF-8
C++
false
false
6,215
cpp
#include "stdafx.h" #include "CDVProp.h" //----------------------------------------------------------------------------- // Name: OnReceiveMsg() // Desc: Called whenever the dialog window receives a message. //----------------------------------------------------------------------------- CDVProp::OnReceiveMsg(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_MY_DEVICE_NOTIFY: OnDeviceNotify((LONG)wParam); break; case WM_TIMER: DisplayTimecode(); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_VTR_PLAY: OnVtrPlay(); break; case IDC_VTR_STOP: OnVtrStop(); break; case IDC_VTR_TRANSMIT: OnTransmit(); break; case IDC_VTR_REW: Rewind(); break; case IDC_VTR_FF: FastForward(); break; default: return FALSE; } return TRUE; } return FALSE; } //----------------------------------------------------------------------------- // Name: OnInitDialog() // Desc: Called when the dialog is initialized. //----------------------------------------------------------------------------- HRESULT CDVProp::OnInitDialog() { // Set the bitmaps on the buttons SetWindowBitmap(IDC_VTR_PLAY, IDB_PLAY); SetWindowBitmap(IDC_VTR_STOP, IDB_STOP); SetWindowBitmap(IDC_VTR_TRANSMIT, IDB_TRANSMIT); SetWindowBitmap(IDC_VTR_REW, IDB_VTR_REW); SetWindowBitmap(IDC_VTR_FF, IDB_VTR_FF); // Enable the VTR buttons if the device has a VTR transport. if (HasTransport()) { EnableVtrButtons(TRUE); } else { EnableVtrButtons(FALSE); } // If the device can read timecode, start the timer that updates our UI if (HasTimecode()) { m_Timer.Start(m_hDlg, 200); } else { m_Timer.Stop(); } m_hwndNotify = m_hDlg; // This is the window that receives device notifications return S_OK; }; //----------------------------------------------------------------------------- // Name: OnOK() // Desc: Called when the user clicks OK. //----------------------------------------------------------------------------- BOOL CDVProp::OnOK() { m_Timer.Stop(); return CNonModalDialog::OnOK(); } //----------------------------------------------------------------------------- // Name: OnVtrPlay() // Desc: Play the VTR transport //----------------------------------------------------------------------------- void CDVProp::OnVtrPlay() { if (m_pGraph) { // If previously we were transmitting from file to tape, it's time to rebuild the graph. if (m_bTransmit) { m_pGraph->TearDownGraph(); m_pGraph->RenderPreview(); m_bTransmit = false; } m_pGraph->Run(); } Play(); } //----------------------------------------------------------------------------- // Name: OnVtrStop() // Desc: Stop the VTR transport //----------------------------------------------------------------------------- void CDVProp::OnVtrStop() { if (m_pGraph) { m_pGraph->Stop(); } Stop(); } //----------------------------------------------------------------------------- // Name: OnTransmit() // Desc: Transmit from file to tape. //----------------------------------------------------------------------------- void CDVProp::OnTransmit() { _ASSERTE(HasDevice()); // Get a file name. TCHAR szFileName[MAX_PATH + 1]; szFileName[0] = '\0'; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = m_hDlg; ofn.lpstrFilter = TEXT("Avi\0*.avi\0"); ofn.nFilterIndex = 1; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAX_PATH + 1; ofn.lpstrTitle = TEXT("Select a DV File to Transmit"); ofn.Flags = OFN_FILEMUSTEXIST; if (!GetOpenFileName(&ofn)) { return; } // Try to build a transmit graph. HRESULT hr = m_pGraph->RenderTransmit(szFileName, (int)_tcslen(szFileName) + 1); if (SUCCEEDED(hr)) { m_bTransmit = true; // Start recording to tape. There's a delay, so don't run the graph yet. // We'll be notified when it starts recording and start the graph then. hr = Record(); } if (FAILED(hr)) { ReportError(0, TEXT("Cannot run transmit graph")); } } //----------------------------------------------------------------------------- // Name: OnDeviceNotify() // Desc: Called when the transport changes state. // // The notification thread posts a message to our window whenever it detects // a state change in the transport. //----------------------------------------------------------------------------- void CDVProp::OnDeviceNotify(LONG State) { // The external device changed state. SetWindowText(GetDlgItem(IDC_VTR_MODE), GetModeName(State)); if ((State == ED_MODE_RECORD) && m_pGraph) { m_pGraph->Run(); } } //----------------------------------------------------------------------------- // Name: DisplayTimecode() // Desc: Get the timecode from the device and display it. //----------------------------------------------------------------------------- void CDVProp::DisplayTimecode() { if (HasTimecode()) { DWORD dwHour = 0, dwMin = 0, dwSec = 0, dwFrame = 0; if (SUCCEEDED(GetTimecode(&dwHour, &dwMin, &dwSec, &dwFrame))) { TCHAR szBuf[32]; wsprintf(szBuf, "%.2d:%.2d:%.2d", dwHour, dwMin, dwSec); SetWindowText(GetDlgItem(IDC_TIMECODE), szBuf); } else { SetWindowText(GetDlgItem(IDC_TIMECODE), "???"); } } } //----------------------------------------------------------------------------- // Name: EnableVtrButtons() // Desc: Enable or disable the buttons that control the VTR. //----------------------------------------------------------------------------- void CDVProp::EnableVtrButtons(BOOL bEnable) { EnableWindow(GetDlgItem(IDC_VTR_PLAY), bEnable); EnableWindow(GetDlgItem(IDC_VTR_STOP), bEnable); EnableWindow(GetDlgItem(IDC_VTR_TRANSMIT), bEnable); EnableWindow(GetDlgItem(IDC_VTR_REW), bEnable); EnableWindow(GetDlgItem(IDC_VTR_FF), bEnable); }
[ [ [ 1, 242 ] ] ]
cb6efd7f6b4e5faf714db91f46dd893fe3294e43
96f796a966025265020459ca2a38346c3c292b1e
/Ansoply/DynamicBitmap.h
148e7d6d2ef8aa7ef598cb2ae9e9e7d467c3bfe9
[]
no_license
shanewfx/ansoply
222979843662ddb98fb444ce735d607e3033dd5e
99e91008048d0c1afbf80152d0dc173a15e068ee
refs/heads/master
2020-05-18T15:53:46.618329
2009-06-17T01:04:47
2009-06-17T01:04:47
32,243,359
1
0
null
null
null
null
UTF-8
C++
false
false
1,094
h
#pragma once #include "ansoplyobject.h" #include "project.h" #include <list> #include <string> #include <vector> using namespace std; class CDynamicBitmap : public CAnsoplyObject { friend class CMultiSAP; public: CDynamicBitmap(void); ~CDynamicBitmap(void); void SetSurface(IDirectDrawSurface7* pSurface); IDirectDrawSurface7* GetSurface(); LONG SetDynamicBitmap(LPCTSTR sBitmapFilePath, ULONG uAlpha, ULONG uTransparentColor, ULONG uX, ULONG uY, ULONG uWidth, ULONG uHeight, ULONG uOriginalSize, ULONG uMilli); void SetAlphaBlt(CAlphaBlt * pAlphaBlt) { m_pAlphaBlt = pAlphaBlt; } virtual void Draw(); public: IDirectDrawSurface7 * m_pDDS; list<BitmapType> m_BitmapList; ULONG m_uAlpha; ULONG m_uTransparentColor; //ULONG m_uX; //ULONG m_uY; //ULONG m_uWidth; //ULONG m_uHeight; ULONG m_uOriginalSize; // DWORD m_dwRender; ULONG m_MilliSec; vector<CString> m_bitmapFileArray; CAlphaBlt * m_pAlphaBlt; CMultiSAP * m_pMultiSAP; CRITICAL_SECTION m_CS; // CStringArray m_bitmapFileArray; };
[ "Gmagic10@26f92a05-6149-0410-981d-7deb1f891687", "gmagic10@26f92a05-6149-0410-981d-7deb1f891687" ]
[ [ [ 1, 2 ], [ 4, 12 ], [ 14, 20 ], [ 22, 31 ], [ 33, 34 ], [ 40, 40 ], [ 42, 45 ], [ 50, 51 ] ], [ [ 3, 3 ], [ 13, 13 ], [ 21, 21 ], [ 32, 32 ], [ 35, 39 ], [ 41, 41 ], [ 46, 49 ] ] ]
d7b164bbfdf47665dff93839e0c196cec5650e36
1ff9f78a9352b12ad34790a8fe521593f60b9d4f
/Template/Rectangle.cpp
565104c3af4bc79fc91bbcd3b7af5ad505b59522
[]
no_license
SamOatesUniversity/Year-2---Game-Engine-Construction---Sams-Super-Space-Shooter
33bd39b4d9bf43532a3a3a2386cef96f67132e1e
46022bc40cee89be1c733d28f8bda9fac3fcad9b
refs/heads/master
2021-01-20T08:48:41.912143
2011-01-19T23:52:25
2011-01-19T23:52:25
41,169,993
0
0
null
null
null
null
UTF-8
C++
false
false
2,375
cpp
#include "Rectangle.h" CRectangle::CRectangle( int x, int y, int w, int h ) { x_ = x; y_ = y; w_ = w; h_ = h; clipx1_ = x_; clipy1_ = y_; clipx2_ = x_ + w_; clipy2_ = y_ + h_; posx_ = 0; posy_ = 0; } CRectangle::~CRectangle( void ) { } bool CRectangle::isInDestination( CRectangle *destination ) { const int destX1 = destination->getAbsoluteX(); const int destY1 = destination->getAbsoluteY(); const int destX2 = destX1 + destination->getAbsoluteW(); const int destY2 = destY1 + destination->getAbsoluteH(); return ( (posx_ >= destX1) && (posx_ + w_ <= destX2) && (posy_ >= destY1) && (posy_ + h_ <= destY2) ); } bool CRectangle::outOfDestination( CRectangle *destination ) { const int destX1 = destination->getAbsoluteX(); const int destY1 = destination->getAbsoluteY(); const int destX2 = destX1 + destination->getAbsoluteW(); const int destY2 = destY1 + destination->getAbsoluteH(); return ( (posx_ + w_ < destX1) || (posx_ > destX2) || (posy_ + h_ < destY1) || (posy_ > destY2) ); } void CRectangle::clipTo( CRectangle *destination ) { //if its fully in the destination, don't clip, so exit and send indestination flag bool inDest = isInDestination( destination ); //if its fully out of the destination, don't clip, so exit and send outdestination flag. bool outDest = outOfDestination( destination ); if( !inDest || !outDest ) { //get x, y, w, h of the destination and temp store them const int destX1 = destination->getAbsoluteX(); const int destY1 = destination->getAbsoluteY(); const int destX2 = destX1 + destination->getAbsoluteW(); const int destY2 = destY1 + destination->getAbsoluteH(); //update the clip coordinates into destination space clipx1_ = x_ + posx_; clipy1_ = y_ + posy_; clipx2_ = x_ + w_ + posx_; clipy2_ = y_ + h_ + posy_; //clip the rectangle if( clipx1_ < destX1 ) clipx1_ = destX1; if( clipy1_ < destY1 ) clipy1_ = destY1; if( clipx2_ > destX2 ) clipx2_ = destX2; if( clipy2_ > destY2 ) clipy2_ = destY2; //convert back into souce space clipx1_ -= posx_; clipy1_ -= posy_; clipx2_ -= posx_; clipy2_ -= posy_; } } void CRectangle::update( int x, int y, int w, int h ) { x_ = x; y_ = y; w_ = w; h_ = h; clipx1_ = x_; clipy1_ = y_; clipx2_ = x_ + w_; clipy2_ = y_ + h_; }
[ [ [ 1, 88 ] ] ]
d97cdccb2ab986fdbae07be164560263618e94c5
44e10950b3bf454080553a5da36bf263e6a62f8f
/depends/include/Totem/Addons/TemplateEventHandler.cpp
7bba15331883385af6b2a414f1bdd04892c98a73
[]
no_license
ptrefall/ste6246tradingagent
a515d88683bf5f55f862c0b3e539ad6144a260bb
89c8e5667aec4c74aef3ffe47f19eb4a1b17b318
refs/heads/master
2020-05-18T03:50:47.216489
2011-12-20T19:02:32
2011-12-20T19:02:32
32,448,454
1
0
null
null
null
null
UTF-8
C++
false
false
2,189
cpp
#include <Totem/Addons/TemplateEventHandler.h> using namespace Totem; using namespace Addon; bool TemplateEventHandler::hasEvent(const T_HashedString &id, int num_params) { if(num_params == 0) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events0.find(id.getId()); if(it != events0.end()) return true; else return false; } else if(num_params == 1) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events1.find(id.getId()); if(it != events1.end()) return true; else return false; } else if(num_params == 2) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events2.find(id.getId()); if(it != events2.end()) return true; else return false; } else if(num_params == 3) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events3.find(id.getId()); if(it != events3.end()) return true; else return false; } else if(num_params == 4) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events4.find(id.getId()); if(it != events4.end()) return true; else return false; } else if(num_params == 5) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events5.find(id.getId()); if(it != events5.end()) return true; else return false; } else if(num_params == 6) { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events6.find(id.getId()); if(it != events6.end()) return true; else return false; } else { T_Map<T_HashedStringType, IEventSignal*>::Type::iterator it = events0.find(id.getId()); if(it != events0.end()) return true; it = events1.find(id.getId()); if(it != events1.end()) return true; it = events2.find(id.getId()); if(it != events2.end()) return true; it = events3.find(id.getId()); if(it != events3.end()) return true; it = events4.find(id.getId()); if(it != events4.end()) return true; it = events5.find(id.getId()); if(it != events5.end()) return true; it = events6.find(id.getId()); if(it != events6.end()) return true; return false; } }
[ "[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe" ]
[ [ [ 1, 90 ] ] ]
6945ae97b296f239bc504eb6b1c59fa29430fcc6
5f1779f2e881e8817e28bd323440e17add991155
/addons/amxmodx/scripting/uwc3xmod/tasks.inl
6949dfb55fc9aefb0d63b5e5ba5bf0c6713fc4be
[]
no_license
AminTaheri1/uwc3x
21410162c48c9e8f94e9dd338876d88e30b90bff
49258229e4e378b81862ab5e176c3e10fd2c9457
refs/heads/master
2021-01-18T20:12:17.876048
2011-01-03T21:01:02
2011-01-03T21:01:02
34,625,945
0
1
null
null
null
null
UTF-8
C++
false
false
77,273
inl
public __TaskShowHudChat(id) { id -= __HUDCHAT_TASKID_UPDATE; new message[__HUDCHAT_MAXMSGLEN]; new messages[((__HUDCHAT_MAXMSGLEN - 1) * __HUDCHAT_MAXLINES) + __HUDCHAT_MAXLINES]; new m, len; for(m = 0; m < __HUDCHAT_MSGCOUNT[id]; m++) { ArrayGetString(__HUDCHAT_MESSAGES[id], m, message, charsmax(message)); len += formatex(messages[len], charsmax(messages) - len, "%s%s", (len > 0) ? "^n" : "", message); } messages[len] = 0; set_hudmessage(__HUDCHAT_R, __HUDCHAT_G, __HUDCHAT_B, __HUDCHAT_POS_X, __HUDCHAT_POS_Y, 0, 0.0, (__HUDCHAT_UPDATEINTERVAL + 0.1), 0.0, 0.0, __HUDCHAT_CHANNEL); show_hudmessage(id, "%s", messages); } public __TaskRemoveHudChat(taskid) { new id = taskid - __HUDCHAT_TASKID_REMOVE; if(__HUDCHAT_MSGCOUNT[id] > 0) { ArrayDeleteItem(__HUDCHAT_MESSAGES[id], 0); if(--__HUDCHAT_MSGCOUNT[id] > 0) { set_task(__HUDCHAT_REMOVETIME, "__TaskRemoveHudChat", taskid); } } } /* GENERIC */ public Task_Reset_Immunity ( parm[2] ) { if( Util_Should_Msg_Client(parm[0]) ) { client_print ( parm[0], print_chat, "%L", parm[0], "RESISTANCE_ENDED", MOD, parm[1] ); } temp_immunity[ parm[0] ] = false; } public Initialize_Tasks ( ) { // set_task calls for functions needed by init or to run continuously set_task ( 10.0, "Check_UWC3X", TASK_CHECK_UWC3X, "", 0, "b" ); set_task ( 1.0, "Check_UWC3X", TASK_CHECK_UWC3X_AGAIN ); set_task ( 3.0, "XP_SetChoice", TASK_SET_XP_CHOICES ); set_task ( 0.6, "set_variables", TASK_SET_VARIABLES ); // TASK_Check_Duck used by decoy ultimate set_task ( 0.01, "TASK_Check_Duck", TASK_DO_NOW, "", 0, "b" ); // Task_Award_FrostNades used by Frost Nades skill - awards a frost nade every 30 seconds set_task ( 30.00, "Task_Award_FrostNades", TASK_DO_NOW, "", 0, "b" ); log_amx( "[UWC3X] Tasks Initialized [OK]"); } public Task_Award_FrostNades( ) { if( endround || freezetime ) return; new players[32]; new numplayers; get_players ( players, numplayers ); for ( new i=0; i< numplayers; ++i ) { new id = players[i]; if( !p_skills[id][SKILLIDX_ICENADE] || !is_user_alive(id) || !Util_IsValid_Team( id ) || !Util_Is_Valid_Player( id ) ) continue; new HasSmokeNade = 0; // Check their weapons and see if they already have a smoke grenade new weapons[32], num, j; get_user_weapons(id,weapons,num); for(j=0;j<num;j++) { if( IsWeaponSmokeGrenade( weapons[j] ) ) { //They do HasSmokeNade = 1; break; } } //if they dont, give them one if( !HasSmokeNade ) { // gimme gimme hasFrostNade[id] = 1; give_item(id,"weapon_smokegrenade"); if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ICEBOMB_GIVEN1", MOD ); client_print ( id, print_center, "%L", id, "ICEBOMB_GIVEN2" ); } } } } /* Gate */ public Task_Gate_User_Shopmenu ( parm[6] ) { // Opens a Gateway to Teleport the player back home new id = parm[5]; new origin[3]; new oldLocation[3]; new Float:forigin[3]; new Float:vicinity = 96.0; new entsFound[1]; origin[0] = parm[0]; origin[1] = parm[1]; origin[2] = parm[2]; forigin[0] = float ( parm[0] ); forigin[1] = float ( parm[1] ); forigin[2] = float ( parm[2] ); // Perform a final check to make sure this MOLE spot wasn't taken new numplayers = find_sphere_class ( 0, "player", vicinity, entsFound, 1, forigin ); if ( numplayers > 0 ) { if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_GATE_COLLAPSE", MOD ); } return PLUGIN_HANDLED; } get_user_origin ( id, oldLocation ); oldLocation[2] += 30; // [09-05-04] - Display gate sprite ( tele ) 1 cycle message_begin ( MSG_ALL, SVC_TEMPENTITY ); write_byte ( TE_SPRITE ); write_coord ( origin[0] ); write_coord ( origin[1] ); write_coord ( origin[2] ); write_short ( gatespr ); write_byte ( 10 ); write_byte ( 255 ); message_end ( ); // blast circles message_begin ( MSG_PAS, SVC_TEMPENTITY, oldLocation ); write_byte ( TE_BEAMCYLINDER ); write_coord ( oldLocation[0] ); write_coord ( oldLocation[1] ); write_coord ( oldLocation[2] + 10 ); write_coord ( oldLocation[0] ); write_coord ( oldLocation[1] ); write_coord ( oldLocation[2] + 10 + TELEPORT_RADIUS ); write_short ( m_iSpriteTexture ); write_byte ( 0 ); // startframe write_byte ( 0 ); // framerate write_byte ( 3 ); // life write_byte ( 60 ); // width write_byte ( 0 ); // noise write_byte ( 255 ); // red write_byte ( 255 ); // green write_byte ( 255 ); // blue write_byte ( 255 ); //brightness write_byte ( 0 ); // speed message_end ( ); set_user_origin ( id, origin ); if( Util_Should_Msg_Client( id ) ) { message_begin ( MSG_ONE, gmsgShake, { 0, 0, 0 }, id ); write_short ( 255<< 14 ); //ammount write_short ( 10 << 14 ); //lasts this long write_short ( 255<< 14 ); //frequency message_end ( ); } return PLUGIN_CONTINUE; } public Task_Gate_User ( parm[6] ) { // Opens a Gateway to Teleport the player back home new id = parm[5]; new origin[3]; new oldLocation[3]; new Float:forigin[3]; new Float:vicinity = 96.0; new entsFound[1]; origin[0] = parm[0]; origin[1] = parm[1]; origin[2] = parm[2]; forigin[0] = float ( parm[0] ); forigin[1] = float ( parm[1] ); forigin[2] = float ( parm[2] ); // Perform a final check to make sure this MOLE spot wasn't taken new numplayers = find_sphere_class ( 0, "player", vicinity, entsFound, 1, forigin ); if ( numplayers > 0 ) { if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_GATE_COLLAPSE", MOD ); } return PLUGIN_HANDLED; } --numgates[id]; if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIAMTE_GATE", MOD ); } ultimateused[id] = true; new cooldownparm[1]; cooldownparm[0] = id; get_user_origin ( id, oldLocation ); oldLocation[2] += 30; if( Util_Should_Msg_Client(id) ) { if ( file_exists ( "sound/uwc3x/massteleporttarget.wav" ) ==1 ) { emit_sound ( id, CHAN_ITEM, "uwc3x/massteleporttarget.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } else { emit_sound ( id, CHAN_ITEM, "x/x_shoot1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } // [09-05-04] - Display gate sprite ( tele ) 1 cycle message_begin ( MSG_ALL, SVC_TEMPENTITY ); write_byte ( TE_SPRITE ); write_coord ( origin[0] ); write_coord ( origin[1] ); write_coord ( origin[2] ); write_short ( gatespr ); write_byte ( 10 ); write_byte ( 255 ); message_end ( ); // blast circles message_begin ( MSG_PAS, SVC_TEMPENTITY, oldLocation ); write_byte ( TE_BEAMCYLINDER ); write_coord ( oldLocation[0] ); write_coord ( oldLocation[1] ); write_coord ( oldLocation[2] + 10 ); write_coord ( oldLocation[0] ); write_coord ( oldLocation[1] ); write_coord ( oldLocation[2] + 10 + TELEPORT_RADIUS ); write_short ( m_iSpriteTexture ); write_byte ( 0 ); // startframe write_byte ( 0 ); // framerate write_byte ( 3 ); // life write_byte ( 60 ); // width write_byte ( 0 ); // noise write_byte ( 255 ); // red write_byte ( 255 ); // green write_byte ( 255 ); // blue write_byte ( 255 ); //brightness write_byte ( 0 ); // speed message_end ( ); set_user_origin ( id, origin ); if( Util_Should_Msg_Client(id) ) { if ( file_exists ( "sound/uwc3x/massteleporttarget.wav" ) ==1 ) { emit_sound ( id, CHAN_ITEM, "uwc3x/massteleporttarget.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } else { emit_sound ( id, CHAN_ITEM, "x/x_shoot1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } if( Util_Should_Msg_Client( id ) ) { message_begin ( MSG_ONE, gmsgShake, { 0, 0, 0 }, id ); write_short ( 255<< 14 ); //ammount write_short ( 10 << 14 ); //lasts this long write_short ( 255<< 14 ); //frequency message_end ( ); } if( CVAR_DEBUG_MODE ) { new debugname[32]; get_user_name ( id, debugname, 31 ); client_print( id, print_console, "[%s DEBUG] Task_Gate_User -> Setting gateused[id] =true for player %s so now there is a 5 second delay", MOD, debugname ); log_amx( "[UWC3X] DEBUG :: Task_Gate_User -> Setting gateused[id] =true for player %s so now there is a 5 second delay", debugname ); } gateused[id] = true; set_task ( CVAR_GATE_COOLDOWN, "cooldownGate", TASK_COOLDOWN_RESET+id, cooldownparm, 1 ); return PLUGIN_CONTINUE; } /* voodoo */ public Task_Reset_Godmode ( parm[] ) { new id = parm[0]; new name[32]; get_user_name ( id, name, 31 ); if ( godshealth[id] < 1 ) { set_user_health_log ( id, 30 ); } else { set_user_health_log ( id, godshealth[id] ); } hasgodmode[id] = false; set_task ( CVAR_VOODOO_COOLDOWN, "cooldown", TASK_COOLDOWN_RESET + id, parm, 1 ); if( Util_Should_Msg_Client(id) ) { set_hudmessage ( 0, 100, 0, 0.05, 0.75, 2, 0.02, 10.0, 0.01, 0.1, 2 ); show_hudmessage ( id, "Your Voodoo has expired" ); } icon_controller ( id ); return PLUGIN_CONTINUE; } /* Teleport */ public Task_Blink_Controller ( parm[2] ) { new id = parm[0]; new newLocation[3]; new curLocation[3]; new oldLocation[3]; new origin[3]; if ( parm[1] == 1 ) { // Teleport failure check and unsticker new coolparm[1]; coolparm[0] = id; newLocation = savedNewLoc[id]; get_user_origin ( id, curLocation, 0 ); if ( newLocation[2] == curLocation[2] ) { // Teleportation Failure oldLocation = savedOldLoc[id]; if( Util_Should_Msg_Client(id) ) { set_hudmessage ( 255, 255, 10, -1.0, -0.4, 1, 0.5, 3.0, 0.2, 0.2, 5 ); show_hudmessage ( id, "%L", id, "ULTIMATE_TELEPORT_FAILED" ); } set_user_origin ( id, oldLocation ); parm[1] = 0; set_task ( 0.1, "Task_Blink_Controller", 0, parm, 2 ); set_task ( CVAR_BLINK_COOLDOWN, "cooldown", TASK_COOLDOWN_RESET + id ,coolparm, 1 ); } else { // Teleportation Success if not near player with immunity new teamname[32]; new players[32]; new numplayers; new targetorigin[3]; new targetid; new bool:teleportSuccess = true; get_user_origin ( id, origin ); get_user_team ( id, teamname, 31 ); get_players ( players, numplayers ); new idname[32]; get_user_name ( id, idname, 31 ); for ( new i=0; i< numplayers; ++i ) { targetid = players[i]; if ( Util_IsSame_Team ( id, targetid ) || Util_Player_Is_Spec ( targetid ) || !is_user_alive ( targetid ) ) { continue; } if ( playeritem[targetid] == IMMUNITY || Util_IsPlayer_Immune ( targetid, 2 ) ) { get_user_origin ( targetid, targetorigin ); if ( get_distance ( origin, targetorigin )<= CVAR_BLINK_RADIUS ) { oldLocation = savedOldLoc[id]; if( Util_Should_Msg_Client(id) ) { set_hudmessage ( 255, 255, 10, -1.0, -0.4, 1, 0.5, 5.0, 0.2, 0.2, 5 ); show_hudmessage( id , "%L", id, "ULTIMATE_TEPELORT_IMMUNE" ); } set_user_origin ( id, oldLocation ); parm[1] = 0; set_task ( 0.1, "Task_Blink_Controller", 0, parm, 2 ); set_task ( CVAR_TELEPORT_COOLDOWN, "cooldown", TASK_COOLDOWN_RESET + id, coolparm, 1 ); teleportSuccess = false; } } } if ( teleportSuccess ) { parm[1] = 2; // [08-05-04] - Added faster cooldown for Master Intellect new Float:tele_cool = CVAR_TELEPORT_COOLDOWN; if ( USE_ENH && ( p_attribs[id][ATTRIBIDX_INT] >= INT_TELEPORT_LEVEL ) ) { tele_cool = INT_TELEPORT_COOL; } else { tele_cool = CVAR_TELEPORT_COOLDOWN; } set_task ( tele_cool, "cooldown", TASK_COOLDOWN_RESET + id, coolparm, 1 ); // Call phase 2 of the blindness set_task ( 0.6, "Task_Blink_Controller", 0, parm, 2 ); // Sprays white bubbles everywhere get_user_origin ( id,origin ); message_begin ( MSG_BROADCAST, SVC_TEMPENTITY ); write_byte ( TE_SPRITETRAIL ); write_coord ( origin[0] ); write_coord ( origin[1] ); write_coord ( origin[2] + 40 ); write_coord ( origin[0] ); write_coord ( origin[1] ); write_coord ( origin[2] ); write_short ( flaresprite ); write_byte ( 30 ); // count write_byte ( 10 ); // life write_byte ( 1 ); // scale write_byte ( 50 ); // velocity write_byte ( 10 ); // randomness in velocity message_end ( ); if ( CVAR_BLINK_DIZINESS == 1 ) { if( Util_Should_Msg_Client( id ) ) { // This will cause Teleportation Dizziness ( like a flash grenade ) message_begin ( MSG_ONE,gmsgFade,{0,0,0},id ); write_short ( 1<<15 ); write_short ( 1<<10 ); write_short ( 1<<12 ); write_byte ( 255 ); write_byte ( 255 ); write_byte ( 255 ); write_byte ( 255 ); message_end ( ); } } } } } else if ( parm[1] == 2 ) { // Make the Teleport Blues hold.. if ( CVAR_BLINK_DIZINESS == 2 ) { if( Util_Should_Msg_Client( id ) ) { // use the magic #1 for "one client" message_begin ( MSG_ONE, gmsgFade, {0,0,0}, id ); write_short ( 1<<0 ); // fade lasts this long duration write_short ( 1<<0 ); // fade lasts this long hold time write_short ( 1<<2 ); // fade type HOLD write_byte ( 76 ); // fade red write_byte ( 163 ); // fade green write_byte ( 223 ); // fade blue write_byte ( 200 ); // fade alpha message_end ( ); } } parm[1] = 0; set_task ( 3.0, "Task_Blink_Controller", 0, parm, 2 ); } else { // Teleport Blueness goes away if ( CVAR_BLINK_DIZINESS == 2 ) { if( Util_Should_Msg_Client( id ) ) { // use the magic #1 for "one client" message_begin ( MSG_ONE, gmsgFade, {0,0,0}, id ); write_short ( 1<<12 );// fade lasts this long duration write_short ( 1<<8 ); // fade lasts this long hold time write_short ( FFADE_OUT ); // fade type OUT write_byte ( 76 ); // fade red write_byte ( 163 ); // fade green write_byte ( 223 ); // fade blue write_byte ( 200 ); // fade alpha message_end ( ); } } } return PLUGIN_CONTINUE; } public TASK_OOB_Check ( parm[2] ) { new id = parm[0]; new mapname[32], origin[3]; new bool:slay = false; get_mapname ( mapname, 32 ); get_user_origin ( id, origin ); new x = origin[0]; new y = origin[1]; new z = origin[2]; if ( !is_user_connected ( id ) ) { return; } new Float:porigin[3]; entity_get_vector ( id, EV_VEC_origin, porigin ); if ( PointContents ( porigin )==-6 ) { slay = true; } if ( equali ( mapname,"de_dust" ) ) { if ( z>220 ) { slay = true; } } else if ( equali ( mapname,"awp_assault" ) ) { if ( z>520 ) { if ( ( y>2400 && y<2600 ) ) slay = true; } } else if ( equali ( mapname,"de_dust_cz" ) ) { if ( z>220 ) slay = true; } else if ( equali ( mapname,"de_aztec_cz" ) ) { if ( z>300 ) slay = true; } else if ( equali ( mapname,"cs_assault_upc" ) ) { if ( z>650 ) slay = true; } else if ( equali ( mapname,"de_aztec" ) ) { if ( z>300 ) slay = true; } else if ( equali ( mapname,"de_cbble" ) ) { if ( z>315 ) { if ( ( x>-1320 && x<-1150 ) && ( y>2600 && y<2900 ) ) { return; } else { slay = true; } } } else if ( equali ( mapname,"de_cbble_cz" ) ) { if ( z>315 ) { if ( ( x>-1320 && x<-1150 ) && ( y>2600 && y<2900 ) ) { return; } else { slay = true; } } } else if ( equali ( mapname,"cs_assault" ) ) { if ( z>700 ) slay = true; } else if ( equali ( mapname,"cs_militia" ) ) { if ( z>500 ) slay = true; } else if ( equali ( mapname,"cs_militia_cz" ) ) { if ( z>500 ) slay = true; } else if ( equali ( mapname,"cs_italy" ) ) { if ( z>-220 ) { if ( y<-2128 ) { slay = true; } } else if ( z>250 ) { if ( ( x<-1000 && x>-1648 ) && ( y>1900 && y<2050 ) ) slay = true; else if ( ( x<-1552 && x>-1648 ) && ( y>1520 && y<2050 ) ) slay = true; } } else if ( equali ( mapname,"cs_italy_cz" ) ) { if ( y>2608 ) slay = true; } else if ( equali ( mapname,"de_dust2" ) ) { if ( z>270 ) slay = true; } else if ( equali ( mapname,"de_dust2_cz" ) ) { if ( z>270 ) slay = true; } else if ( equali ( mapname,"fy_dustworld" ) ) { if ( z>82 ) slay = true; } else if ( equali ( mapname,"fy_pool_day" ) ) { if ( z>190 ) slay = true; } else if ( equali ( mapname,"as_oilrig" ) ) { if ( x > 1530 && get_user_team ( id ) == TEAM_CT ) slay = true; else if ( x > 1700 ) slay = true; } else if ( equali ( mapname,"cs_mice_final" ) ) { if ( ( ( x >= 798 ) && ( x <= 860 ) ) && ( y <- 1430 ) ) slay = true; } if ( slay ) { new name[32]; get_user_name ( id, name, 31 ); if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_TELEPORT_SLAY", MOD ); } set_user_health_log ( id, -1 ); } } /* Flame strike */ public Task_FlameStrike_Spray ( args[] ) { //Task_FlameStrike_Spray message_begin ( MSG_BROADCAST, SVC_TEMPENTITY ); // Throws a shower of sprites or models write_byte ( 120 ) ; // start pos write_coord ( args[0] ) ; write_coord ( args[1] ); write_coord ( args[2] ); // velocity write_coord ( args[3] ); write_coord ( args[4] ); write_coord ( args[5] ); // spr write_short ( fire ) ; // count write_byte ( 8 ); // speed write_byte ( 70 ) ; // ( noise ) write_byte ( 100 ) ; // ( rendermode ) write_byte ( 5 ); message_end ( ); return PLUGIN_CONTINUE; } public TASK_Burn_Victim ( id, killer, tk ) { if ( FS_Is_Player_On_Fire ( id ) || Util_IsPlayer_Immune ( id , 5 ) ) { return PLUGIN_CONTINUE; } new hp, args[4]; hp = get_user_health ( id ); if ( hp > 250 ) { hp = 250; } // [08-06-04] - Added Fire Resistance Checks - K2mia //new Float:ftimer = 1.5; if ( USE_ENH && p_resists[id][RESISTIDX_FIRE] ) { new Float:chance_to_avoid = ( p_resists[id][RESISTIDX_FIRE] >= RESIST_MAX_VALUE ) ? 1.00 : ( float ( p_resists[id][RESISTIDX_FIRE] ) / float ( RESIST_MAX_VALUE ) ); new Float:randomnumber = random_float ( 0.0, 1.0 ); if ( randomnumber < chance_to_avoid ) { if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_FLAME_RESIST", MOD ); } if( Util_Should_Msg_Client( killer ) ) { client_print ( killer, print_chat, "%L", killer, "ULTIMATE_FLAME_DEFLECTED", MOD ); } return PLUGIN_CONTINUE; } else if ( ( randomnumber/2.0 ) < chance_to_avoid ) { if( Util_Should_Msg_Client(player_id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_FLAME_FAILED", MOD ); } if( Util_Should_Msg_Client(killer) ) { client_print ( killer, print_chat, "%L", killer, "ULTIMATE_FLAME_FAILED", MOD ); } args[0] = id; args[1] = killer; args[2] = tk; set_task ( 3.5, "EVENT_Set_On_Fire", TASK_ON_FIRE_NAPALM, args, 4, "a", ( hp / 10 ) ); return PLUGIN_CONTINUE; } } //Added this check for the Fire else { args[0] = id; args[1] = killer; args[2] = tk; set_task ( 3.5, "EVENT_Set_On_Fire", TASK_ON_FIRE_NAPALM, args, 4, "a", ( hp / 10 ) ); } return PLUGIN_CONTINUE; } public TASK_Check_BurnZone ( id, vec[3], aimvec[3], speed1, speed2, radius ) { new maxplayers, tbody, tid, ff = 0; get_user_aiming ( id, tid, tbody, 550 ); if ( cvar_exists ( "mp_friendlyfire" ) ) { new ffcvar = get_cvar_num ( "mp_friendlyfire" ); if ( ( ffcvar == 0 ) || ( ffcvar == 1 ) ) { ff = ffcvar; } } if( is_user_alive( tid ) ) { TASK_Burn_Victim ( tid, id, ff ) ; } new burnvec1[3],burnvec2[3],length1; burnvec1[0]=aimvec[0]-vec[0]; burnvec1[1]=aimvec[1]-vec[1]; burnvec1[2]=aimvec[2]-vec[2]; length1=sqrt ( burnvec1[0]*burnvec1[0]+burnvec1[1]*burnvec1[1]+burnvec1[2]*burnvec1[2] ); burnvec2[0] = burnvec1[0] * speed2/length1; burnvec2[1] = burnvec1[1] * speed2/length1; burnvec2[2] = burnvec1[2] * speed2/length1; burnvec1[0] = burnvec1[0] * speed1/length1; burnvec1[1] = burnvec1[1] * speed1/length1; burnvec1[2] = burnvec1[2] * speed1/length1; burnvec1[0] += vec[0]; burnvec1[1] += vec[1]; burnvec1[2] += vec[2]; burnvec2[0] += vec[0]; burnvec2[1] += vec[1]; burnvec2[2] += vec[2]; new target[32], idx, origin[3]; get_players( target, maxplayers ); for ( new i = 0; i <= maxplayers; i++ ) { idx = target[i]; // Testing to see if this solves the // Invalid player id 0 error if ( !Util_Is_Valid_Player( idx ) ) continue; new tempff = 0; if ( ff == 1 ) { if ( Util_IsSame_Team( idx, id) ) { tempff = 1; } } get_user_origin ( idx, origin ); FS_Should_Burn_Victim ( origin, burnvec1, burnvec2, radius, idx, id, tempff ); } return PLUGIN_CONTINUE; } /* DEPOWER */ public TASK_DEPOWER_Search ( parm[2] ) { new players[32], numofplayers, enemy, body, id = parm[0]; get_players ( players, numofplayers ); get_user_aiming ( id, enemy, body ); //If your team mate is not on your team, or your not aiming directly at him //Then you should keep looking - otherwise we have it if ( ( 0 < enemy <= MAX_PLAYERS ) && ( enemy != id ) && ( get_user_team ( id ) != get_user_team ( enemy ) ) && is_user_alive ( id ) && is_user_alive ( enemy ) ) { new name[32], name2[32]; get_user_name ( enemy, name, 31 ); get_user_name ( id, name2, 31 ); issearching[id] = false; ultimateused[id] = true; icon_controller ( id ); if( CVAR_DEPOWER_CANT_DROP ) { BlockPickup[id] = true; BlockPickup[enemy] = true; if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", enemy, "ULTIMATE_DEPOWER_ENEMY2", MOD ); } if( Util_Should_Msg_Client(enemy) ) { client_print ( enemy, print_chat, "%L", enemy, "ULTIMATE_DEPOWER_ENEMY2", MOD ); } } Ult_DEPOWER_REPLACE_GUNS( id ); if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_DEPOWER_YOU1", MOD, name ); if ( file_exists ( "sound/uwc3x/depowered.wav" ) == 1 ) { emit_sound ( id, CHAN_STATIC, "uwc3x/depowered.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } Ult_DEPOWER_REPLACE_GUNS( enemy ); if( Util_Should_Msg_Client(enemy) ) { client_print ( enemy, print_chat, "%L", enemy, "ULTIMATE_DEPOWER_ENEMY1", MOD, name2 ); if ( file_exists ( "sound/uwc3x/depowered.wav" ) == 1 ) { emit_sound ( enemy, CHAN_STATIC, "uwc3x/depowered.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } UsedDepower[id] = 1; new cooldownparm[2]; cooldownparm[0] = id; cooldownparm[1] = enemy; set_task ( CVAR_DEPOWER_COOLDOWN, "cooldown4", TASK_COOLDOWN4 + id, cooldownparm, 2 ); } else { //Keep searching issearching[id] = true; icon_controller ( id ); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if ( parm[1] > 0 && get_user_health ( id ) >=0 ) { set_task ( 0.1, "TASK_DEPOWER_Search", TASK_ULTIMATE_DEPOWER_SEARCH + id, parm, 3 ); } else { issearching[id] = false; icon_controller ( id ); } } return PLUGIN_CONTINUE; } /* TEAM SHIELD */ public TASK_SHIELD_Search( parm[2] ) { new players[32], numofplayers, body; //These are opposite of the functions - keep that in mind new id = parm[0]; //Player providing the shield new teammate; //Guy who is getting the shield get_players ( players, numofplayers ); get_user_aiming ( id, teammate, body ); //If your team mate is not on your team, or your not aiming directly at him //Then you should keep looking - otherwise we have it if ( is_user_connected ( id ) && is_user_connected ( teammate ) && is_user_alive ( id ) && is_user_alive ( teammate ) && ( !HasTeamShield[teammate] && !UsedTeamShield[id]) && ( 0 < teammate <= MAX_PLAYERS ) && ( teammate != id ) && ( get_user_team ( id ) == get_user_team ( teammate ) ) ) { new name[32], name2[32]; get_user_name ( teammate, name, 31 ); get_user_name ( id, name2, 31 ); issearching[id] = false; ultimateused[id] = true; icon_controller ( id ); if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_SIV_SHIELDER", name ); if ( file_exists ( "sound/uwc3x/divineshield.wav" ) == 1 ) { emit_sound ( id, CHAN_STATIC, "uwc3x/divineshield.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } if( Util_Should_Msg_Client( teammate ) ) { client_print ( teammate, print_chat, "%L", teammate, "ULTIMATE_SIV_PLAYER", name2 ); if ( file_exists ( "sound/uwc3x/divineshield.wav" ) == 1 ) { emit_sound ( teammate, CHAN_STATIC, "uwc3x/divineshield.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } HasTeamShield[teammate]=true; if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: TASK_SHIELD_Search -> TeamShield -> Shielder: %s Player: %s HasTeamShield[teammate]=true", name2, name ); } p_PlayerShieldedBy[teammate] = id; p_ShieldMaxDamageAbsorbed[teammate] = 0; UsedTeamShield[id] = 1; new parm[3]; parm[0] = teammate; //The guy with the shield parm[1] = id; //The guy who provided the shield parm[2] = 0; set_task ( 1.0, "TASK_SHIELD_CHECK", TASK_SHIELD_CHECK_ID + id, parm, 3 ); } else { //Keep searching issearching[id] = true; icon_controller ( id ); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if ( parm[1] > 0 && get_user_health ( id ) >=0 ) { set_task ( 0.1, "TASK_SHIELD_Search", TASK_ULTIMATE_SHIELD_SEARCH + id, parm, 3 ); } else { issearching[id] = false; icon_controller ( id ); } } return PLUGIN_CONTINUE; } public TASK_SHIELD_CHECK ( parm[3] ) { new id = parm[0]; //The guy with the shield new teammate = parm[1]; //The guy who provided the shield new shield_damage = parm[2]; if ( ( get_user_team ( id ) != get_user_team ( teammate ) ) || !is_user_connected ( id ) || !is_user_connected ( teammate ) ) { HasTeamShield[id]=false; //Remove teh Shield Check task if( task_exists(TASK_SHIELD_CHECK_ID + id) ) { remove_task( TASK_SHIELD_CHECK_ID + id ); } return PLUGIN_CONTINUE; } new MaxDamage = p_ShieldMaxDamage[p_skills[teammate][SKILLIDX_TEAMSHIELD]] new name[32], name2[32]; get_user_name ( id, name, 31 ); get_user_name ( teammate, name2, 31 ); if( shield_damage < MaxDamage ) { HasTeamShield[id]=true; if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: TASK_SHIELD_CHECK( ) -> TeamShield -> Setting HasTeamShield[teammate]=true"); } p_PlayerShieldedBy[id] = teammate; parm[2] = p_ShieldMaxDamageAbsorbed[id]; set_task ( 1.0, "TASK_SHIELD_CHECK", TASK_SHIELD_CHECK_ID + id, parm, 3 ); } else { //Tell them its done if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_SIV_SHIELDER_EXPIRED" ); } if( Util_Should_Msg_Client(teammate) ) { client_print ( teammate, print_chat, "%L", teammate, "ULTIMATE_SIV_PLAYER_EXPIRED", name2 ); } //REmove teh Shield Check task if( task_exists(TASK_SHIELD_CHECK_ID + id) ) { remove_task( TASK_SHIELD_CHECK_ID + id ); } //Reset the vars HasTeamShield[id]=false; if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: TASK_SHIELD_CHECK( ) -> TeamShield -> Setting HasTeamShield[teammate]=false -> Expired"); } //Set cooldown new cooldownparm[1]; cooldownparm[0] = teammate; //Now that its done, start the cooldown TeamShieldCooldown[teammate] = 1; set_task ( CVAR_TEAMSHIELD_COOLDOWN, "cooldown3", TASK_COOLDOWN3 + teammate, cooldownparm, 1 ); } return PLUGIN_CONTINUE; } /* Chain lightning */ public TASK_CHAIN_Search ( parm[2] ) { new id = parm[0]; new enemyz, body; get_user_aiming ( id, enemyz, body ); if ( 0 < enemyz <=32 && ( get_user_team ( enemyz ) != get_user_team ( id ) ) && playeritem[enemyz] != IMMUNITY && !hasblink[enemyz] && is_user_alive ( id ) && is_user_alive ( enemyz ) ) { ultimateused[id] = true; icon_controller ( id ); new linewidth = 80; new damage = 75; issearching[id] = false; // [08-05-04] - Added Electricity resistance check - K2mia new actual_damage = damage; if ( USE_ENH && p_resists[enemyz][RESISTIDX_ELECTRIC] ) { actual_damage = actual_damage - floatround ( ( float ( p_resists[enemyz][RESISTIDX_ELECTRIC] ) / float ( RESIST_MAX_VALUE ) ) * float ( actual_damage ) ); if ( p_resists[enemyz][RESISTIDX_ELECTRIC] == RESIST_MAX_VALUE ) { if( Util_Should_Msg_Client(enemyz) ) { client_print ( enemyz, print_chat, "%L", enemyz, "ULTIMATE_LGHTNG_RESISTALL", MOD ); } } else { if( Util_Should_Msg_Client(enemyz) ) { client_print ( enemyz, print_chat, "%L", enemyz, "ULTIMATE_LGHTNG_RESIST", MOD ); } } } EVENT_Do_Bolt ( id, enemyz, linewidth, actual_damage, id ); new lightparm[4]; lightparm[0]=enemyz; lightparm[1]=damage; lightparm[2]=linewidth; lightparm[3]=id; set_task ( 0.2, "TASK_CHAIN_Damage", TASK_CHAIN_DAMAGE, lightparm, 4 ); new cooldownparm[1]; cooldownparm[0] = id; set_task ( CVAR_LIGHTNING_COOLDOWN, "cooldown", TASK_COOLDOWN_RESET + id, cooldownparm, 1 ); } else { issearching[id] = true; icon_controller ( id ); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if ( parm[1] > 0 && get_user_health ( id )>=0 ) { set_task ( 0.1, "TASK_CHAIN_Search", TASK_ULTIMATE_CHAIN_SEARCH + id, parm, 2 ); } else { issearching[id] = false; icon_controller ( id ); } } return PLUGIN_CONTINUE; } public TASK_CHAIN_Damage ( parm[4] ) { // Chain Lightning new id = parm[0]; new caster = parm[3]; new origin[3], numberofplayers, players[32], targetorigin[3], i; new targetid = 0; new distancebetween = 0; new damage = parm[1]*2/3; new linewidth = parm[2]*2/3; new closestdistance = 0; new closestid = 0; get_user_origin ( id, origin ); get_players ( players, numberofplayers ); for ( i = 0; i < numberofplayers; ++i ) { targetid = players[i]; if ( get_user_team ( id ) != get_user_team ( targetid ) ) { continue; } if ( get_user_team ( id ) == get_user_team ( targetid ) && is_user_alive ( targetid ) && is_user_alive ( id ) ) { get_user_origin ( targetid, targetorigin ); distancebetween = get_distance ( origin, targetorigin ); if ( distancebetween < LIGHTNING_RANGE && playeritem[targetid] != IMMUNITY && !lightninghit[targetid] && !hasblink[targetid] && Util_IsPlayer_Immune ( targetid, 2 ) ) { if ( distancebetween < closestdistance || closestid == 0 ) { closestdistance = distancebetween; closestid = targetid; } } } } if ( closestid ) { new actual_damage = damage; // [08-05-04] - Added Electricity resistance check - K2mia if ( USE_ENH && p_resists[closestid][RESISTIDX_ELECTRIC] ) { actual_damage -= ( p_resists[closestid][RESISTIDX_ELECTRIC] / 100 ) * actual_damage; if ( p_resists[closestid][RESISTIDX_ELECTRIC] == RESIST_MAX_VALUE ) { if( is_user_connected( closestid ) && !is_user_bot( closestid ) ) { client_print ( closestid, print_chat, "%L", closestid, "ULTIMATE_LGHTNG_RESISTALL", MOD ); } } else { if( is_user_connected( closestid ) && !is_user_bot( closestid ) ) { client_print ( closestid, print_chat, "%L", closestid, "ULTIMATE_LGHTNG_RESIST", MOD ); } } } //Increase damage by 20% if they have the wisdom for it if( p_wisdom_lightningdamagebonus[id] ) { actual_damage += floatround( damage * WIS_LIGHTNINGDAMAGEBONUS ); if ( CVAR_DEBUG_MODE ) { client_print( id, print_console, "[%s DEBUG] Wisdom modified damage - NEW damage=( %d )", MOD, actual_damage ); } } EVENT_Do_Bolt ( id, closestid, linewidth, actual_damage, caster ); parm[0] = targetid; parm[1] = damage; parm[2] = linewidth; parm[3] = caster; set_task ( 0.2, "TASK_CHAIN_Damage", TASK_CHAIN_DAMAGE, parm, 4 ); } else { for ( i = 0; i < numberofplayers; ++i ) { targetid = players[i]; lightninghit[targetid] = false; } } return PLUGIN_CONTINUE; } /* Suicide Bomber */ //apacheexplode public TASK_Suicide_Explode ( parm[] ) { // Suicide Bomber new id = parm[0]; if ( ( get_user_team ( id ) == SPEC ) || !is_user_connected( id ) ) { return PLUGIN_CONTINUE; } new origin[3]; get_user_origin ( id, origin ); // random explosions message_begin ( MSG_PVS, SVC_TEMPENTITY, origin ); // This just makes a dynamic light now write_byte ( TE_EXPLOSION ); write_coord ( origin[0] + random_num ( -100, 100 ) ); write_coord ( origin[1] + random_num ( -100, 100 ) ); write_coord ( origin[2] + random_num ( -50, 50 ) ); write_short ( g_sModelIndexFireball ); // scale * 10 write_byte ( random_num ( 0,20 ) + 20 ); // framerate write_byte ( 12 ); write_byte ( TE_EXPLFLAG_NONE ); message_end ( ); // lots of smoke message_begin ( MSG_PVS, SVC_TEMPENTITY, origin ); write_byte ( TE_SMOKE ); write_coord ( origin[0] + random_num ( -100, 100 ) ); write_coord ( origin[1] + random_num ( -100, 100 ) ); write_coord ( origin[2] + random_num ( -50, 50 ) ); write_short ( g_sModelIndexSmoke ); write_byte ( 60 ); // scale * 10 write_byte ( 10 ); // framerate message_end ( ); new players[32], targetorigin[3], numberofplayers, i, targetid; new distancebetween, damage, multiplier; get_players ( players, numberofplayers ); for ( i = 0; i < numberofplayers; ++i ) { targetid = players[i]; if ( ( get_user_team ( targetid ) == SPEC ) || !is_user_alive ( targetid ) || !is_user_connected ( targetid ) ) { continue; } get_user_origin ( targetid, targetorigin ); distancebetween = get_distance ( origin, targetorigin ); if ( distancebetween < CVAR_EXPLODE_MAX_RANGE && Util_NotSame_Team ( id, targetid ) ) { if ( temp_immunity[targetid] || Util_IsPlayer_Immune ( targetid, 1 ) || Util_IsPlayer_Immune ( targetid, 2 ) ) { //They resistted temp_immunity[targetid] = false; if( Util_Should_Msg_Client( targetid ) ) { client_print ( targetid, print_chat, "%L", targetid, "ULTIMATE_SUICIDE_RESIST", MOD ); } new iparm[2]; iparm[0] = targetid; copy( iparm[1], 31, "Suicide Bomber" ); set_task ( 1.5, "Task_Reset_Immunity", TASK_RESET_IMMUNITY+targetid, iparm, 2 ); } else { //They did not resist multiplier = CVAR_EXPLODE_MAX_DAMAGE * CVAR_EXPLODE_MAX_DAMAGE / CVAR_EXPLODE_MAX_RANGE; damage = ( CVAR_EXPLODE_MAX_RANGE - distancebetween ) * multiplier; damage = sqrt ( damage ); if ( is_user_alive ( targetid ) ) { do_damage ( targetid, id, damage, 12, 3, 0, 0, 0 ); } } } if ( distancebetween < CVAR_EXPLODE_MAX_RANGE ) { if( Util_Should_Msg_Client( targetid ) ) { message_begin ( MSG_ONE, gmsgShake, {0, 0, 0}, targetid ); write_short ( 1<<14 );// amplitude write_short ( 1<<13 );// duration write_short ( 1<<14 );// frequency message_end ( ); } } } --parm[1]; if ( parm[1] > 0 ) { set_task ( 0.1, "TASK_Suicide_Explode", TASK_SUICIDE_EXPLODE_NOID, parm, 2 ); } return PLUGIN_CONTINUE; } public TASK_Destroy_Mine ( args[] ) { new id = args[0]; new ents = -1; ents = find_ent_by_owner(ents,"Mine",id) while (ents > 0) { remove_entity ( ents ); ents = find_ent_by_owner(ents,"Mine",id) } remove_entity ( args[1] ); } public TASK_Cleanup_Mine( args[]) { //new id = args[0]; new ent = args[1]; remove_entity(ent); } /* Decoy */ public TASK_Cleanup_Decoy ( args[] ) { new id = args[0]; new ent = args[1]; new Float:orig[3]; entity_get_vector ( ent, EV_VEC_origin, orig ); message_begin ( MSG_BROADCAST,SVC_TEMPENTITY ); write_byte ( 11 ); write_coord ( floatround ( orig[0] ) ); write_coord ( floatround ( orig[1] ) ); write_coord ( floatround ( orig[2] ) ); message_end ( ); decoy[id] = 0; remove_entity ( ent ); if( Util_Should_Msg_Client(id) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_DECOY_EXPIRED" ); } } public TASK_CHECK_USER_SPEED( ) { for ( new i = 1; i <= get_maxplayers ( ); ++i ) { if ( is_user_alive ( i ) ) { new speedparm[1]; speedparm[0] = i; Set_Speed( speedparm ); } } } public TASK_CHECK_FOOTSTEPS ( ) { for ( new i = 1; i <= get_maxplayers ( ); ++i ) { if ( is_user_alive ( i ) ) Set_Cat_Footsteps( i ); } } public TASK_Check_Duck ( ) { for ( new i = 1; i <= get_maxplayers ( ); ++i ) { if ( is_user_alive ( i ) ) { if ( decoy[i] ) { if ( get_user_button ( i )& IN_DUCK ) { if ( !pIsDucking[i] ) { pIsDucking[i] = true; DoOnce[i] = true; } } else { if ( pIsDucking[i] ) { //client_print ( i, print_chat, "Stopped ducking" ) pIsDucking[i] = false; DoOnce[i] = true; } } } } } return PLUGIN_CONTINUE; } public Task_Server_Frame ( ) { new id; new Float:vel[3]; new Float:speed; new Float:new_frame = get_gametime ( ); new Float:newAngle[3]; new Float:orig[3]; new Float:framerate = 30.0; new Float:MinBox[3]; new Float:MaxBox[3]; new Float:vRetVector[3]; new Float:tmpVec[3]; if ( ( new_frame - last_frame ) < ( 1.0 / framerate ) ) { return PLUGIN_CONTINUE; } last_frame = new_frame; for ( id=0; id < MAX_PLAYERS; id++ ) { if ( !decoy[id] || !is_user_connected ( id ) ) { continue; } if ( pIsDucking[id] ) { MinBox[0] = 0.0; MinBox[1] = 0.0; MinBox[2] = -20.0; //change to -40 for standing models MaxBox[0] = 0.0; MaxBox[1] = 0.0; MaxBox[2] = 0.0; } else { MinBox[0] = 0.0; MinBox[1] = 0.0; MinBox[2] = -40.0; //change to -20 for crouching models MaxBox[0] = 0.0; MaxBox[1] = 0.0; MaxBox[2] = 0.0; } entity_set_vector ( decoy[id], EV_VEC_mins, MinBox ); entity_get_vector ( id, EV_VEC_v_angle, vRetVector ); vRetVector[0] = float ( 0 ); entity_set_vector ( decoy[id], EV_VEC_angles, vRetVector ); entity_get_vector ( decoy[id], EV_VEC_velocity, vel ); if ( vel[0] != 0.0 && vel[1] != 0.0 ) { vel[2] = 0.0; vector_to_angle ( vel, newAngle ); } vel[2] = 0.0; speed = vector_length ( vel ); if ( speed <= 5 && pIsDucking[id] ) { if ( DoOnce[id] ) { entity_get_vector ( decoy[id], EV_VEC_origin, orig ); orig[2] = orig[2] - 20; entity_set_vector ( decoy[id], EV_VEC_origin, orig ); DoOnce[id] = false; } decoy_seq[id] = 2; entity_set_int ( decoy[id], EV_INT_sequence, 2 ); MinBox[0] = -20.0; MinBox[1] = -20.0; MinBox[2] = -20.0; MaxBox[0] = 20.0; MaxBox[1] = 20.0; MaxBox[2] = 40.0; entity_set_vector ( decoy[id], EV_VEC_mins, MinBox ); entity_set_vector ( decoy[id], EV_VEC_maxs, MaxBox ); tmpVec[0] = 40.0; tmpVec[1] = 40.0; tmpVec[2] = 80.0; entity_set_vector ( decoy[id], EV_VEC_size, tmpVec ); } else if ( speed <= 5 && !pIsDucking[id] ) { if ( DoOnce[id] ) { entity_get_vector ( decoy[id], EV_VEC_origin, orig ); orig[2] = orig[2] + 20; entity_set_vector ( decoy[id], EV_VEC_origin, orig ); DoOnce[id] = false; } decoy_seq[id] = 1; entity_set_int ( decoy[id], EV_INT_sequence, 1 ); MinBox[0] = -20.0; MinBox[1] = -20.0; MinBox[2] = -40.0; MaxBox[0] = 20.0; MaxBox[1] = 20.0; MaxBox[2] = 40.0; entity_set_vector ( decoy[id],EV_VEC_mins, MinBox ); entity_set_vector ( decoy[id],EV_VEC_maxs, MaxBox ); tmpVec[0] = 40.0; tmpVec[1] = 40.0; tmpVec[2] = 80.0; entity_set_vector ( decoy[id], EV_VEC_size, tmpVec ); } decoy_fstep[id] = 5.0; decoy_frame[id] += decoy_fstep[id]; if ( decoy_frame[id] >= 254.0 ) { decoy_frame[id] = 0.0; } entity_set_float ( decoy[id], EV_FL_frame, decoy_frame[id] ); } return PLUGIN_CONTINUE; } /* Entangle Roots */ public Task_Destroy_Roots ( args[] ) { remove_entity ( args[0] ); } public searchtarget(parm[2]) { new id = parm[0]; new enemy, body; get_user_aiming(id,enemy,body); if ( (0<enemy<=32) && (p_resists[enemy][RESISTIDX_MAGIC] >= RESIST_MAX_VALUE) || (!temp_immunity[enemy] && magic_saving_throw(enemy)) ) { temp_immunity[enemy] = true; if ( Util_Should_Msg_Client( enemy ) ) { client_print ( enemy, print_chat, "%L", enemy, "ULTIMATE_ENGANGLE_RESISTANT", MOD ); } new iparm[2]; iparm[0] = enemy; iparm[1] = 1; set_task ( 5.0, "Task_Reset_Immunity", TASK_RESET_IMMUNITY + id, iparm, 2 ); } if ( 0<enemy<=32 && !stunned[enemy] && get_user_team(id)!=get_user_team(enemy) && playeritem[enemy]!=IMMUNITY && !hasblink[enemy] && is_user_alive(id) && is_user_alive(enemy) && !temp_immunity[enemy] ) { issearching[id]=false; ultimateused[id]=true; icon_controller(id); if ( Util_Should_Msg_Client( id ) ) { if ( file_exists ( "sound/uwc3x/entanglingroots.wav" ) == 1 ) { emit_sound ( id, CHAN_STATIC, "uwc3x/entanglingroots.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } new waitparm[6]; waitparm[0]=enemy; waitparm[1]=100; waitparm[5]=floatround(get_user_maxspeed(enemy)); set_user_maxspeed(enemy,1.0); Task_Entangle_Stop(waitparm); stunned[enemy]=true; new cooldownparm[1]; cooldownparm[0]=id; set_task ( CVAR_ENTANGLE_COOLDOWN, "cooldown", 50 + id, cooldownparm, 1 ); } else { issearching[id]=true; icon_controller(id); new counter = parm[1]; while (counter >= 0) { counter -= 10; if (counter==0) emit_sound(id,CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM); } --parm[1] if (parm[1]>0 && get_user_health(id)>0) { set_task(0.1, "searchtarget", TASK_ULTIMATE_ENTANGLE_SEARCH+id, parm, 2); } else { issearching[id]=false; icon_controller(id); } } return PLUGIN_CONTINUE; } public Task_Entangle_Stop ( parm[6] ) { new id=parm[0]; new origin[3]; get_user_origin ( id, origin ); if ( origin[0] == parm[2] && origin[1] == parm[3] && origin[2] == parm[4] ) { new normalspeed = parm[5]; new resetparm[2]; resetparm[0] = id; resetparm[1] = normalspeed; set_task ( float ( parm[1]/10 ), "reset_maxspeed", TASK_RESET_MAXSPEED + id , resetparm, 2 ); new entangleparm[2]; entangleparm[0] = parm[0]; entangleparm[1] = parm[1]; Event_Entangle ( entangleparm ); } else { parm[2] = origin[0]; parm[3] = origin[1]; parm[4] = origin[2]; set_task ( 0.1, "Task_Entangle_Stop", TASK_ENTANGLE_STOP +id, parm, 6 ); } return PLUGIN_CONTINUE; } /* Constitution regeneration */ public con_heal( parm[] ) { new id = parm[0]; new heal = parm[1]; new Float:interval = CON_HEAL_INTERVAL; if ( !endround && is_user_alive( id ) && ( p_attribs[id][ATTRIBIDX_CON] > ATTRIB_BASE ) ) { new econ = (p_attribs[id][ATTRIBIDX_CON] - ATTRIB_BASE ); if ( econ != heal ) { parm[1] = econ; heal = econ ; } set_task( interval, "con_heal", id + CONSTITUTION_REGEN, parm, 2 ); } new health = 0; new bool:was_healed = false; health = maxhealth[id] + ( playeritem[id] == HEALTH ? HEALTHBONUS : 0 ); if ( get_user_health( id ) < health ) { was_healed = true; set_user_health_log( id, get_user_health( id ) + heal ); } // [09-26-04] Adjustment if maxhealth exceeded - K2mia if ( get_user_health( id ) > health ) { set_user_health_log( id, health ); } if (!was_healed) { return PLUGIN_CONTINUE; } new origin[3]; get_user_origin( id, origin ); if( playeritem[id] != CLOAK && ( !p_skills[id][SKILLIDX_INVIS] ) ) { message_begin( MSG_BROADCAST, SVC_TEMPENTITY ); write_byte( TE_IMPLOSION ); write_coord( origin[0] ); // initial position write_coord( origin[1] ); // initial position write_coord( origin[2] ); // initial position write_byte( 100 ); // radius write_byte( 8 ); // count write_byte( 1 ); // life message_end(); } return PLUGIN_CONTINUE; } public Task_Check_Const_Regen( id ) { // [08-04-04] - Constitution health regen code - K2mia if (p_attribs[id][ATTRIBIDX_CON] > ATTRIB_BASE) { // Remove running task for Con Health if (task_exists(id+1100)) { remove_task(id+1100); } new newparm[2]; newparm[0] = id; newparm[1] = ( p_attribs[id][ATTRIBIDX_CON] - ATTRIB_BASE ); set_task( 1.0, "con_heal", id + CONSTITUTION_REGEN, newparm, 2 ); } else { if (task_exists(id+1100)) { remove_task(id+1100); } } return PLUGIN_CONTINUE; } /* Check for leather skin or steel skin bonus */ public Task_Check_Skin_Bonus( id ) { // [09-04-04] - Modified for helmet and suit checks, maxarmor modifier - K2mia if (p_skills[id][SKILLIDX_LSKIN]) { // Set player adjusted max. armor for use with repair armor new abonusmult = 0; new abonus = 0; // If Steel Skin trained use improved armor bonus if (p_skills[id][SKILLIDX_SSKIN]) { helmet[id] = true; abonusmult = ARMORBONUS2; } else { helmet[id] = false; abonusmult = ARMORBONUS1; } if (p_level[id] > 30) abonus = (abonusmult * 6); else if (p_level[id] > 25) abonus = (abonusmult * 5); else if (p_level[id] > 20) abonus = (abonusmult * 4); else if (p_level[id] > 15) abonus = (abonusmult * 3); else if (p_level[id] > 10) abonus = (abonusmult * 2); else abonus = abonusmult; hassuit[id] = true; maxarmor[id] = (NORMALARMORMAX + abonus); } else { // Set player default max. armor for use with repair armor if (get_user_armor(id) > 0) { maxarmor[id] = 100; hassuit[id] = true; } else { maxarmor[id] = 0; } } return PLUGIN_CONTINUE; } /* MOLE AND FAN OF KNIVES */ public Task_Check_Fan( id ) { if ( p_skills[id][SKILLIDX_FAN] && is_user_alive( id ) ) { //Fan of Knives new Float:randomnumber = random_float( 0.0, 1.0 ); if ( randomnumber <= p_fan[p_skills[id][SKILLIDX_FAN]-1] ) { new parm[2]; parm[0] = id; parm[1] = 7; set_task( 0.1, "Check_spot", TASK_CHECK_SPOT + 12, parm, 2 ); } } } public Task_Transport2( parm[6] ) { // Teleports the MOLE to the opposing team's base (new version) new id = parm[5]; new origin[3]; new Float:forigin[3]; new Float:vicinity = 96.0; new entsFound[1]; origin[0] = parm[0]; origin[1] = parm[1]; origin[2] = parm[2]; forigin[0] = float( parm[0] ); forigin[1] = float( parm[1] ); forigin[2] = float( parm[2] ); // Perform a final check to make sure this MOLE spot wasn't taken new numplayers = find_sphere_class( 0, "player", vicinity, entsFound, 1, forigin ); if (numplayers > 0) { if (hasmole[id] && is_user_connected( id ) && !is_user_bot( id ) ) { client_print( id, print_chat, "%L", id, "MOLE_NO_SLOT" ); } else { if( Util_Should_Msg_Client(id) ) { client_print( id, print_chat, "%L", id, "MOLE_SLOT" ); } } return PLUGIN_HANDLED; } if( Util_Should_Msg_Client(id) ) { client_print( id, print_chat, "%L", id, "MOLE_READY", origin[0], origin[1], origin[2] ); } ismole[id] = true; changeskin( id, 0 ); set_user_origin( id, origin ); if( Util_Should_Msg_Client(id) ) { client_print( id, print_chat, "%L", id, "MOLE_BLIND", MOD ); message_begin( MSG_ONE, gMsgScreenFade, { 0, 0, 0 }, id ); write_short( 1<<15 ); write_short( 1<<10 ); write_short( 0 ); write_byte( 255 ); write_byte( 255 ); write_byte( 255 ); write_byte( 255 ); message_end(); message_begin(MSG_ONE,gmsgShake,{0,0,0},id); write_short( 255<<14 ); //ammount write_short( 10<<14 ); //lasts this long write_short( 255<<14 ); //frequency message_end(); } if ( playeritem2[id] == MOLE) { playeritem2[id] = 0; } hasmole[id] = false; return PLUGIN_CONTINUE; } public Check_spot( parm[] ) { new id = parm[0]; if (get_user_team(id) == 1) { mole_CT( id ); } else if (get_user_team(id) == 2) { mole_T( id ); } else { if( Util_Should_Msg_Client(id) ) { client_print( id, print_chat, "%L", id, "MOLE_JOIN_TEAM" ); } } return PLUGIN_HANDLED; } //Jumpkick public Task_Jumpkick_Cooldown( parm[] ) { new id = parm[0]; kickflag[id] = 0; } //TeamShield public Task_Teamshield_Cooldown( parm[] ) { //new id = parm[0]; } public Task_Reset_Shopmenu3( parm[] ) { new id = parm[0]; if( !is_user_connected( id ) || !is_user_alive( id ) ) return PLUGIN_HANDLED; new reset_item = parm[1]; playeritem3[id] = 0; if( reset_item == 1) { playerCanBuyitem3[id] = 1; if( Util_Should_Msg_Client(id) ) { set_hudmessage(0, 255, 255, 0.0, 0.55, 0, 6.0, 3.0, 0.1, 0.2, 1); show_hudmessage(id, "%L", id, "SM3_CAN_BUY", MOD); } } else if( reset_item == 2 ) { if( Util_Should_Msg_Client(id) ) { set_hudmessage(0, 255, 255, 0.0, 0.55, 0, 6.0, 5.0, 0.1, 0.2, 1); show_hudmessage(id, "%L", id, "SM3_VULNERABLE", MOD); } } else if( reset_item == 3 ) { set_entity_visibility ( id, 1 ); if( Util_Should_Msg_Client(id) ) { set_hudmessage(0, 255, 255, 0.0, 0.55, 0, 6.0, 3.0, 0.1, 0.2, 1); show_hudmessage(id, "%L", id, "SM3_VISIBLE", MOD); if ( file_exists( "sound/uwc3x/shopmenu/sm3_inv_done.wav" ) == 1 ) { emit_sound( id, CHAN_STATIC, "uwc3x/shopmenu/sm3_inv_done.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } return PLUGIN_CONTINUE; } public Task_Reset_Cripple( parm[] ) { new id = parm[0]; new enemy = parm[2]; stunned[id] = false; slowed[id] = false; crippletype[id] = 0; iscrippled[id] = 0; //Only care if they are alive and actually are crippled, otherwise dont reset if( is_user_alive( id ) && iscrippled[id] ) { if( Util_Should_Msg_Client_Alive( id ) ) { client_print( id, print_chat, "%L", id, "ULTIMATE_CRIPPLE_WORE_OFF1", MOD ); client_print( id, print_center, "%L", id, "ULTIMATE_CRIPPLE_WORE_OFF2" ); } if( Util_Should_Msg_Client_Alive( enemy ) ) { new idname[32]; get_user_name( id, idname, 31 ); client_print( enemy, print_chat, "%L", enemy, "ULTIMATE_CRIPPLE_WORE_OFF3", MOD, idname ); client_print( enemy, print_center, "%L", enemy, "ULTIMATE_CRIPPLE_WORE_OFF4", idname ); } //set_user_maxspeed(id,oldSpeed[id]); //oldSpeed[id] = 0.0; //new speedparm[1]; //speedparm[0] = id; //Set_Speed( speedparm ); //set_task( 0.1, "reset_maxspeed", TASK_RESET_MAXSPEED + id, parm, 3 ); } new normalspeed = floatround( get_user_maxspeed( id ) ); new parm[2]; parm[0] = id; parm[1] = normalspeed; set_task( 1.0, "reset_maxspeed", TASK_RESET_MAXSPEED+id, parm, 2 ); } // Locust Swarm public Task_locust_function( id ) { new parm[11]; parm[7]=id; new players[32], numberofplayers, i, player, possibility[MAX_PLAYERS], count = 0; get_players(players, numberofplayers); for (i = 0; i < numberofplayers; ++i) { player=players[i]; if( Util_Is_Valid_Player( player ) && Util_NotSame_Team(player,id) && is_user_alive(player) && ( playeritem[player]!=IMMUNITY || !hasblink[player] ) ) { possibility[count] = player; count++; } } if (count==0) { if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(id,"No valid targets found, please try again later!"); } log_amx( "[UWC3X] DEBUG :: Task_locust_function -> count=0"); return PLUGIN_CONTINUE; } parm[6] = 0 // Initialize target parameter //client_print(id, print_console, "DEBUG: before-count=(%d) parm6=(%d)", count, parm[6]) // Prevents target from being the server while (parm[6] == 0) { parm[6] = possibility[random_num(0, count)] } //client_print(id, print_console, "DEBUG: after-count=(%d) parm6=(%d)", count, parm[6]) if ( parm[6] > numberofplayers || !Util_Is_Valid_Player( parm[6] ) ) { if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(id,"No valid targets found!") return PLUGIN_CONTINUE } } new debugname[32]; get_user_name(parm[6],debugname,31); if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: Task_locust_function -> VALID Player=%d %s -> Moving on", parm[6], debugname ); } new origin[3], origin2[3]; get_user_origin(id,origin); get_user_origin(parm[6],origin2); parm[0]=origin[0]; parm[1]=origin[1]; parm[2]=origin[2]; ultimateused[id]=true; Task_locust_drawfunnels(parm); if( Util_Should_Msg_Client_Alive( id ) ) { if (file_exists("sound/uwc3x/locustswarmloopwav.wav")==1) { emit_sound(id, CHAN_ITEM, "uwc3x/locustswarmloopwav.wav", 1.0, ATTN_NORM, 0, PITCH_NORM); } } return PLUGIN_CONTINUE; } public Task_locust_drawfunnels(parm[]) { new MULTIPLIER = 150; // the lower the number the faster it reaches the target new id = parm[6]; new caster = parm[7]; new origin[3], funnel[3], name[32], name2[32]; get_user_name(id,name,31); get_user_name(caster,name2,31); if( Util_Should_Msg_Client_Alive( caster ) ) { if (file_exists("sound/uwc3x/locustswarmloopwav.wav")==1) { emit_sound(caster, CHAN_ITEM, "uwc3x/locustswarmloopwav.wav", 1.0,ATTN_NORM, 0, PITCH_NORM); } } if( Util_Should_Msg_Client_Alive( id ) ) { if (file_exists("sound/uwc3x/locustswarmloopwav.wav")==1) { emit_sound(id, CHAN_ITEM, "uwc3x/locustswarmloopwav.wav", 1.0,ATTN_NORM, 0, PITCH_NORM); } } if ( Util_IsPlayer_Immune ( id, 2 ) ) { if( Util_Should_Msg_Client_Alive( id ) ) { client_print( id, print_chat, "[%s] Your magic resistance protects you from a Locust Swarm", MOD); } if( Util_Should_Msg_Client_Alive( caster ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(caster,"Your locusts were resistsed by Player %s ", name ); } if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: Task_locust_drawfunnels -> Locusts Avoided Resistance Check - Caster=%s Player %s ", name2, name ); } ultimateused[caster]=true; icon_controller(caster); return PLUGIN_CONTINUE; } if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: Task_locust_drawfunnels -> Locusts Hit - Caster=%s Player %s", name2, name ); } get_user_origin(id,origin); funnel[0]=parm[0]; // Origin of the funnel funnel[1]=parm[1]; funnel[2]=parm[2]; message_begin( MSG_BROADCAST, SVC_TEMPENTITY ); write_byte( TE_LARGEFUNNEL ); write_coord(funnel[0]); // origin, x write_coord(funnel[1]); // origin, y write_coord(funnel[2]); // origin, z write_short(snow); // sprite (0 for none) write_short(0); // 0 for collapsing, 1 for sending outward message_end(); new xdist = diff(origin[0],funnel[0]); new ydist = diff(origin[1],funnel[1]); new zdist = diff(origin[2],funnel[2]); if (diff(origin[0],(funnel[0]-MULTIPLIER))<xdist) parm[0]=funnel[0]-MULTIPLIER; else if(diff(origin[0],(funnel[0]+MULTIPLIER))<xdist) parm[0]=funnel[0]+MULTIPLIER; else parm[0]=origin[0]; if (diff(origin[1],(funnel[1]-MULTIPLIER))<ydist) parm[1]=funnel[1]-MULTIPLIER; else if(diff(origin[1],(funnel[1]+MULTIPLIER))<ydist) parm[1]=funnel[1]+MULTIPLIER; else parm[1]=origin[1]; if (diff(origin[2],(funnel[2]-MULTIPLIER))<zdist) parm[2]=funnel[2]-MULTIPLIER; else if(diff(origin[2],(funnel[2]+MULTIPLIER))<zdist) parm[2]=funnel[2]+MULTIPLIER; else parm[2]=origin[2]; if (!endround) { if (!(xdist<50 && ydist<50 && zdist<50)) { set_task( 0.1, "Task_locust_drawfunnels", id+800, parm, 11 ); } else { new pDamageMultiplier = pDamageMultiplier = p_skills[caster][SKILLIDX_LOCUST]; new actual_damage = 20 * pDamageMultiplier; if( CVAR_DEBUG_MODE) { log_amx( "[UWC3X] DEBUG :: Task_locust_drawfunnels -> pDamageMultiplier=%d actual_damage=%d", pDamageMultiplier, actual_damage ); } do_damage(id, caster, actual_damage, 15, 3, 0, 0, 0); new Float:speed = get_user_maxspeed( id ); if(speed > 1.0 && speed != oldSpeed[id]) { oldSpeed[id] = speed; } set_user_maxspeed( id, LOCUSTSPEED ); if( Util_Should_Msg_Client_Alive( caster ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(caster,"Your locusts hurt Player %s ", name ); } new parm[2]; parm[0] = id; reset_maxspeed ( parm ); set_task( float( 2 * p_skills[caster][SKILLIDX_LOCUST]), "reset_maxspeed", TASK_RESET_MAXSPEED+id, parm, 1 ); ultimateused[caster]=true; icon_controller(caster); new cooldownparm[1]; cooldownparm[0]=caster; set_task(CVAR_LOCUST_COOLDOWN,"cooldown",50+id,cooldownparm,1); } } return PLUGIN_CONTINUE; } //Total Blindness public Task_Search_Flash( parm[2] ) { new id = parm[0]; new enemy, body; get_user_aiming(id,enemy,body); if( Util_Is_Valid_Player(enemy) && !stunned[enemy] && Util_NotSame_Team(id,enemy) && playeritem[enemy]!=IMMUNITY && !hasblink[enemy] && is_user_alive(id) && is_user_alive(enemy) && (p_resists[enemy][RESISTIDX_MAGIC] < RESIST_MAX_VALUE) && !magic_saving_throw(enemy) ) { issearching[id]=false; ultimateused[id]=true; icon_controller(id); new name[32], ename[32]; get_user_name( id , name, 31); get_user_name( enemy , ename, 31); if( Util_Should_Msg_Client_Alive( id ) ) { client_print(id, print_chat, "%L", id, "ULTIMATE_BLIND_YOU", MOD, ename); } if( Util_Should_Msg_Client_Alive( enemy ) ) { client_print(enemy, print_center, "%L", enemy, "ULTIMATE_BLIND_ENEMY", name); Task_Ult_Do_Flash( enemy ); } new cooldownparm[1]; cooldownparm[0]=id; set_task( CVAR_FLASH_COOLDOWN, "cooldown", 50+id, cooldownparm, 1); } else { issearching[id]=true; icon_controller(id); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if (parm[1]>0 && get_user_health(id)>0) { set_task(0.1, "Task_Search_Flash", 200+id, parm, 2); } else { issearching[id]=false; icon_controller(id); } } return PLUGIN_CONTINUE; } public Task_Ult_Do_Flash(id) { if( Util_Should_Msg_Client(id) ) { message_begin(MSG_ONE,gMsgScreenFade,{0,0,0},id); write_short( 2<<12 ); write_short( 2<<12 ); write_short( 1<<1 ); write_byte( 0 ); write_byte( 0 ); write_byte( 0 ); write_byte( 255 ); message_end(); if( Util_Should_Msg_Client_Alive( id ) ) { emit_sound(id,CHAN_BODY, "weapons/flashbang-2.wav", 1.0, ATTN_NORM, 0, PITCH_HIGH); } } } public reloadAmmo(id) { if (!Util_Is_Valid_Player(id)) return; if (gReloadTime[id] >= get_systime() - 1) return; gReloadTime[id] = get_systime(); new clip, ammo, wpn[32]; new wpnid = get_user_weapon(id, clip, ammo); if( !IsWeaponPrimary( wpnid ) && !IsWeaponSecondary( wpnid ) ) return; if (clip == 0) { get_weaponname(wpnid,wpn,31); new iWPNidx = -1; while((iWPNidx = find_ent_by_class(iWPNidx, wpn)) != 0) { if(id == entity_get_edict(iWPNidx, EV_ENT_owner)) { cs_set_weapon_ammo(iWPNidx, getMaxClipAmmo(wpnid)); break; } } } } public Task_Switch_UnlimitedAmmoOn( id ) { new name[32]; get_user_name( id , name, 31); new intTime = floatround( CVAR_UNLIMITED_AMMO_TIME ); if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(id,"You now have unlimited Ammo for %i seconds!", intTime ); client_print(id, print_chat, "%L", id, "ULTIMATE_UAMMO_YOU1", MOD, intTime ); } if ( CVAR_DEBUG_MODE ) { log_amx( "[UWC3X] Debug:: Task_Switch_UnlimitedAmmoOff -> unammo[ %s ] = ON ", name ); } unammo[id] = true; } public Task_Switch_UnlimitedAmmoOff( parm[] ) { new id = parm[0]; new name[32]; get_user_name( id , name, 31); if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(id,"Your unlimited Ammo is now gone, better reload fast!"); client_print(id, print_chat, "%L", id, "ULTIMATE_UAMMO_YOU2", MOD); } if ( CVAR_DEBUG_MODE ) { log_amx( "[UWC3X] Debug:: Task_Switch_UnlimitedAmmoOff -> unammo[ %s ] = OFF ", name ); } unammo[id] = false; } public Task_Search_BadAim( parm[] ) { new id = parm[0]; new enemy, body; get_user_aiming(id,enemy,body); if( Util_Is_Valid_Player(enemy) && !stunned[enemy] && Util_NotSame_Team(id,enemy) && playeritem[enemy]!=IMMUNITY && !hasblink[enemy] && is_user_alive(id) && is_user_alive(enemy) && !magic_saving_throw(enemy) ) { issearching[id]=false; ultimateused[id]=true; icon_controller(id); new name[32], ename[32]; get_user_name( id , name, 31); get_user_name( enemy , ename, 31); Task_Switch_BadAimOn( id, enemy ); new barTime = floatround( CVAR_BADAIM_TIME ); if( Util_Should_Msg_Client( enemy ) ) { message_begin ( MSG_ONE, 108, { 0, 0, 0 }, enemy ); // Bar ( thanks to bad-at-this ) // duration write_byte ( barTime ); // duration write_byte ( 0 ); message_end ( ); } new parm[2]; parm[0] = id; parm[1] = enemy; set_task ( CVAR_BADAIM_TIME, "Task_Switch_BadAimOff", TASK_RESET_BADAIM_ID + enemy, parm, 2 ); new cooldownparm[1]; cooldownparm[0]=id; set_task( CVAR_FLASH_COOLDOWN ,"cooldown",50+id,cooldownparm,1); } else { issearching[id]=true; icon_controller(id); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if (parm[1]>0 && get_user_health(id)>0) { set_task(0.1,"Task_Search_BadAim", 200+id, parm, 2); } else { issearching[id]=false; icon_controller(id); } } return PLUGIN_CONTINUE; } public Task_Switch_BadAimOn( id, enemy ) { new idname[32], ename[32]; get_user_name( id , idname, 31); get_user_name( enemy , ename, 31); badaim[enemy] = true; new intTime = floatround(CVAR_BADAIM_TIME); if( Util_Should_Msg_Client_Alive( enemy ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage( enemy,"You have been disoreinted by %s for %d seconds!!!!", idname, intTime ); client_print(enemy, print_chat, "%L", enemy, "ULTIMATE_BADAIM_ENEMY1", MOD, idname, intTime ); if ( file_exists( "sound/uwc3x/disorient-casted.wav" ) == 1 ) { emit_sound( enemy, CHAN_STATIC, "uwc3x/disorient-casted.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage( id,"%s has been disoriented for %d seconds!!!", ename, intTime ); client_print(id, print_chat, "%L", id, "ULTIMATE_BADAIM_YOU1", MOD, ename, intTime ); } } public Task_Switch_BadAimOff( parm[] ) { new id = parm[0]; new enemy = parm[1]; new idname[32], ename[32]; get_user_name( id , idname, 31); get_user_name( enemy , ename, 31); if( Util_Should_Msg_Client_Alive( enemy ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(enemy,"You are no longer disoriented!"); client_print(enemy, print_chat, "%L", enemy, "ULTIMATE_BADAIM_YOU3", MOD); } if( Util_Should_Msg_Client_Alive( id ) ) { set_hudmessage(178, 14, 41, -1.0, 0.3, 0, 1.0, 5.0, 0.1, 0.2, 5); show_hudmessage(id,"%s is no longer disoriented!", ename); client_print(id, print_chat, "%L", id, "ULTIMATE_BADAIM_ENEMY3", MOD, ename); } badaim[enemy] = false; } //Smite public TASK_Smite_Search( parm[] ) { new id = parm[0]; new enemy, body; get_user_aiming(id,enemy,body); if( Util_Is_Valid_Player(enemy) && !stunned[enemy] && Util_NotSame_Team(id,enemy) && playeritem[enemy]!=IMMUNITY && !hasblink[enemy] && is_user_alive(id) && is_user_alive(enemy) && !magic_saving_throw(enemy) ) { issearching[id]=false; ultimateused[id]=true; icon_controller(id); //Lightning bolt and sound - #1 Event_Smite( enemy ); new Float:damage = float( p_level[enemy] ) * 1.5; new actual_damage = floatround(damage); //Add wisdom modifier if( p_wisdom_lightningdamagebonus[id] ) { actual_damage += floatround( damage * WIS_LIGHTNINGDAMAGEBONUS ); if ( CVAR_DEBUG_MODE ) { client_print( id, print_console, "[%s DEBUG] Wisdom modified damage - NEW damage=( %d )", MOD, actual_damage ); } } if ( CVAR_DEBUG_MODE ) { client_print( id, print_console, "[%s DEBUG] Wisdom modified damage - NEW damage=( %d )", MOD, actual_damage ); } //Damage - done only once :) do_damage ( enemy, id, actual_damage, 26, 3, 0, 0, 0 ); //Lightning bolt and sound - #2 Event_Smite( enemy ); new cooldownparm[1]; cooldownparm[0]=id; set_task( CVAR_FLASH_COOLDOWN ,"cooldown",50+id,cooldownparm,1); } else { issearching[id]=true; icon_controller(id); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if (parm[1]>0 && get_user_health(id)>0) { set_task(0.1,"TASK_Smite_Search", 200+id, parm, 2); } else { issearching[id]=false; icon_controller(id); } } return PLUGIN_CONTINUE; } public TASK_EarthQuake_Search( parm[] ) { new id = parm[0]; new enemy, body; get_user_aiming(id,enemy,body); if( Util_Is_Valid_Player(enemy) && !stunned[enemy] && Util_NotSame_Team(id,enemy) && playeritem[enemy]!=IMMUNITY && !hasblink[enemy] && is_user_alive(id) && is_user_alive(enemy) && !magic_saving_throw(enemy) ) { issearching[id]=false; ultimateused[id]=true; icon_controller(id); new param[6], origin[3]; get_user_origin( enemy, origin ); param[0] = enemy; param[1] = 1 + p_skills[id][SKILLIDX_EARTHQUAKE]; param[2] = id param[3] = 1 new tMAX_RANGE = 150 * p_skills[id][SKILLIDX_EARTHQUAKE]; create_eq_blast(origin, tMAX_RANGE); set_task ( 0.2, "EarthQuake_DO", TASK_RESET_BADAIM_ID + enemy, param, 4 ); new cooldownparm[1]; cooldownparm[0]=id; set_task( CVAR_FLASH_COOLDOWN ,"cooldown",50+id,cooldownparm,1); } else { issearching[id]=true; icon_controller(id); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if (parm[1]>0 && get_user_health(id)>0) { set_task(0.1,"TASK_EarthQuake_Search", 200+id, parm, 2); } else { issearching[id]=false; icon_controller(id); } } return PLUGIN_CONTINUE; } public EarthQuake_DO( parm[] ) { new enemy = parm[0]; //original enemy new counterparam = parm[1]; //decremented counter new id = parm[2]; //original caster //Get the origin of the original enemy cast new origin[3]; get_user_origin( enemy, origin ); if( Util_Should_Msg_Client (enemy) ) { message_begin( MSG_ONE, gmsgShake, { 0, 0, 0 }, enemy ); write_short( 255<< 14 ); //ammount write_short( 10 << 14 ); //lasts this long write_short( 255<< 14 ); //frequency message_end( ); } new players[32], targetorigin[3], numberofplayers, i, targetid; new distancebetween, damage, multiplier; get_players ( players, numberofplayers ); new tMAX_RANGE = 150 * p_skills[id][SKILLIDX_EARTHQUAKE]; new tMAX_DAMAGE = 15 * p_skills[id][SKILLIDX_EARTHQUAKE]; for ( i = 0; i < numberofplayers; ++i ) { targetid = players[i]; if( !Util_Is_Valid_Player( targetid ) || Util_IsSame_Team( targetid, id ) || !is_user_alive ( targetid ) ) continue; if( !parm[3] && targetid == enemy) { //make sure we only hit the original enemy once with the ultimate through the loops continue; } //Make sure we hit the person only once if( quaked[targetid] == 1 ) { continue; } get_user_origin ( targetid, targetorigin ); distancebetween = get_distance ( origin, targetorigin ); if ( distancebetween < tMAX_RANGE && Util_NotSame_Team ( id, targetid ) ) { new idname[32], ename[32]; get_user_name( id, idname, 31 ); get_user_name( targetid, ename, 31 ); multiplier = tMAX_DAMAGE * tMAX_DAMAGE / tMAX_RANGE; damage = ( tMAX_RANGE - distancebetween ) * multiplier; damage = sqrt ( damage ); //Dont let Max Damage get higher then the max allowed if( damage > tMAX_DAMAGE ) damage = tMAX_DAMAGE; if ( temp_immunity[targetid] || Util_IsPlayer_Immune ( targetid, 2 ) ) { //They resistted temp_immunity[targetid] = true; if( !quaked[targetid] ) { if( Util_Should_Msg_Client_Alive( targetid ) ) { client_print ( targetid, print_chat, "%L", targetid, "ULTIMATE_EARTHQUAKE_RESIST1", MOD, idname ); client_print ( targetid, print_center, "%L", targetid, "ULTIMATE_EARTHQUAKE_RESIST2", idname ); } } if( Util_Should_Msg_Client_Alive( id ) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_EARTHQUAKE_RESIST3", MOD, ename ); client_print ( id, print_center, "%L", id, "ULTIMATE_EARTHQUAKE_RESIST4", ename ); } new iparm[2]; iparm[0] = targetid; copy( iparm[1], 31, "Earth Quake" ); set_task ( 1.5, "Task_Reset_Immunity", TASK_RESET_IMMUNITY+targetid, iparm, 2 ); //Deal half damage becuase of the resist if ( is_user_alive ( targetid ) ) { damage = floatround( damage * 0.5); do_damage ( targetid, id, damage, 27, 3, 0, 0, 0 ); quaked[targetid] = 1; if( targetid == enemy ) parm[3] = 0; } } else { if ( is_user_alive ( targetid ) ) { if( !quaked[targetid] ) { if( Util_Should_Msg_Client_Alive( targetid ) ) { client_print ( targetid, print_chat, "%L", targetid, "ULTIMATE_EARTHQUAKE_YOU1", MOD, idname ); client_print ( targetid, print_center, "%L", targetid, "ULTIMATE_EARTHQUAKE_YOU2", idname ); } } if( Util_Should_Msg_Client_Alive( id ) ) { client_print ( id, print_chat, "%L", id, "ULTIMATE_EARTHQUAKE_DAMAGE1", MOD, ename ); client_print ( id, print_center, "%L", id, "ULTIMATE_EARTHQUAKE_DAMAGE2", ename ); } do_damage ( targetid, id, damage, 27, 3, 0, 0, 0 ); quaked[targetid] = 1; if( targetid == enemy ) parm[3] = 0; } } } if ( distancebetween < tMAX_RANGE ) { if( Util_Should_Msg_Client( targetid ) ) { message_begin( MSG_ONE, gmsgShake, { 0, 0, 0 }, targetid ); write_short( 255<< 14 ); //ammount write_short( 10 << 14 ); //lasts this long write_short( 255<< 14 ); //frequency message_end( ); message_begin( MSG_ONE, gmsgShake, { 0, 0, 0 }, targetid ); write_short( 255<< 14 ); //ammount write_short( 10 << 14 ); //lasts this long write_short( 255<< 14 ); //frequency message_end( ); } } } --counterparam; if ( counterparam > 0 ) { parm[0] = enemy; //original enemy parm[1] = counterparam; //decremented counter parm[2] = id; //original caster set_task ( 0.1, "EarthQuake_DO", TASK_SUICIDE_EXPLODE_NOID, parm, 4 ); } else if( counterparam == 0) { //Now that we are done, reset everyones quaked status so they can be quaked once again later for( i = 0; i < numberofplayers; ++i ) { new quakeid = players[i]; quaked[quakeid] = 0; } } return PLUGIN_CONTINUE; } /* HOOK */ public TASK_hooktask(parm[]) { new id = parm[0]; if (CVAR_HOOK_STYLE == 0) hookstyle_classic(id); else if (CVAR_HOOK_STYLE == 1) hookstyle_reel(id,false); else if (CVAR_HOOK_STYLE == 2) hookstyle_reel(id,true); else if (CVAR_HOOK_STYLE == 3) hookstyle_cheapreel(id); if( CVAR_DEBUG_MODE ) { new debugname[32]; get_user_name ( id, debugname, 31 ); log_amx( "[UWC3X] DEBUG :: TASK_hooktask -> player %s - Hook style=%d", debugname, CVAR_HOOK_STYLE ); } } public TASK_GRAB_Search( parm[2] ) { //These are opposite of the functions - keep that in mind new id = parm[0]; //Player providing the shield grab[id]=-1 static target, trash target=0 get_user_aiming(id,target,trash) if(target && is_valid_ent2(target) && target!=id && !Util_IsSame_Team(target,id) && Util_IsValid_Team(target ) ) { issearching[id] = false; ultimateused[id] = true; icon_controller ( id ); //formerly target<=maxplayers if( Util_Is_Valid_Player( target ) || ( get_solidity(target)!=4) ) { if( !GrabResisted( target, id ) ) { if ( CVAR_DEBUG_MODE ) { client_print( id, print_console, "DEBUG :: TASK_GRAB_Search -> failed to resist" ); log_amx( "[UWC3X] DEBUG :: TASK_GRAB_Search -> failed to resist" ); } grabem(id,target); } else { if ( CVAR_DEBUG_MODE ) { client_print( id, print_console, "DEBUG :: grabem -> resisted" ); log_amx( "[UWC3X] Debug :: grabem -> resisted" ); } } } } else { //Keep searching issearching[id] = true; icon_controller ( id ); new counter = parm[1]; while ( counter >= 0 ) { counter -= 10; if ( counter == 0 ) { if( Util_Should_Msg_Client( id ) ) { emit_sound ( id, CHAN_ITEM, "turret/tu_ping.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); } } } --parm[1]; if ( parm[1] > 0 && get_user_health ( id ) >=0 ) { set_task ( 0.1, "TASK_GRAB_Search", TASK_HOOK + id, parm, 3 ); } else { issearching[id] = false; icon_controller ( id ); } } return PLUGIN_CONTINUE; } /* AMXX-Studio Notes - DO NOT MODIFY BELOW HERE *{\\ rtf1\\ ansi\\ deff0{\\ fonttbl{\\ f0\\ fnil Tahoma;}}\n\\ viewkind4\\ uc1\\ pard\\ lang1048\\ f0\\ fs16 \n\\ par } */
[ "hostcheap@840eb890-4279-fec9-49b3-ec91e02591cc", "stormzone.site@840eb890-4279-fec9-49b3-ec91e02591cc" ]
[ [ [ 1, 41 ], [ 43, 46 ], [ 48, 52 ], [ 54, 58 ], [ 60, 61 ], [ 63, 64 ], [ 66, 70 ], [ 72, 73 ], [ 75, 77 ], [ 79, 81 ], [ 83, 84 ], [ 86, 86 ], [ 88, 90 ], [ 92, 100 ], [ 102, 107 ], [ 109, 115 ], [ 117, 122 ], [ 124, 129 ], [ 131, 133 ], [ 135, 137 ], [ 139, 140 ], [ 142, 147 ], [ 149, 150 ], [ 152, 153 ], [ 155, 164 ], [ 166, 175 ], [ 177, 187 ], [ 189, 189 ], [ 191, 198 ], [ 200, 205 ], [ 207, 212 ], [ 214, 216 ], [ 218, 220 ], [ 222, 223 ], [ 225, 232 ], [ 234, 234 ], [ 236, 239 ], [ 241, 243 ], [ 245, 246 ], [ 248, 258 ], [ 260, 269 ], [ 271, 280 ], [ 282, 292 ], [ 294, 294 ], [ 296, 306 ], [ 308, 315 ], [ 317, 323 ], [ 325, 333 ], [ 335, 336 ], [ 338, 345 ], [ 347, 347 ], [ 349, 349 ], [ 351, 355 ], [ 357, 357 ], [ 359, 371 ], [ 373, 377 ], [ 379, 380 ], [ 382, 385 ], [ 387, 391 ], [ 393, 393 ], [ 395, 407 ], [ 409, 411 ], [ 413, 414 ], [ 416, 418 ], [ 420, 423 ], [ 425, 430 ], [ 432, 436 ], [ 438, 445 ], [ 447, 449 ], [ 451, 452 ], [ 454, 461 ], [ 463, 463 ], [ 465, 466 ], [ 468, 484 ], [ 486, 487 ], [ 489, 490 ], [ 492, 511 ], [ 513, 514 ], [ 516, 527 ], [ 529, 536 ], [ 539, 540 ], [ 543, 554 ], [ 556, 562 ], [ 564, 565 ], [ 567, 569 ], [ 571, 574 ], [ 576, 577 ], [ 579, 582 ], [ 584, 715 ], [ 717, 720 ], [ 722, 725 ], [ 727, 734 ], [ 768, 771 ], [ 773, 776 ], [ 778, 779 ], [ 781, 784 ], [ 786, 787 ], [ 789, 792 ], [ 794, 799 ], [ 801, 804 ], [ 806, 809 ], [ 811, 814 ], [ 816, 819 ], [ 821, 835 ], [ 837, 843 ], [ 845, 847 ], [ 849, 853 ], [ 855, 858 ], [ 860, 860 ], [ 862, 864 ], [ 866, 878 ], [ 880, 881 ], [ 883, 885 ], [ 887, 890 ], [ 892, 892 ], [ 894, 900 ], [ 902, 904 ], [ 906, 915 ], [ 917, 923 ], [ 925, 927 ], [ 929, 932 ], [ 934, 941 ], [ 943, 943 ], [ 945, 948 ], [ 950, 953 ], [ 955, 955 ], [ 957, 960 ], [ 962, 965 ], [ 967, 967 ], [ 969, 969 ], [ 971, 981 ], [ 983, 985 ], [ 987, 994 ], [ 996, 996 ], [ 998, 1007 ], [ 1009, 1009 ], [ 1011, 1018 ], [ 1020, 1022 ], [ 1024, 1025 ], [ 1027, 1033 ], [ 1035, 1037 ], [ 1039, 1041 ], [ 1043, 1047 ], [ 1049, 1051 ], [ 1053, 1057 ], [ 1059, 1063 ], [ 1065, 1067 ], [ 1069, 1072 ], [ 1074, 1077 ], [ 1079, 1082 ], [ 1084, 1086 ], [ 1088, 1095 ], [ 1097, 1097 ], [ 1099, 1107 ], [ 1109, 1109 ], [ 1111, 1115 ], [ 1117, 1119 ], [ 1121, 1123 ], [ 1125, 1129 ], [ 1131, 1132 ], [ 1134, 1135 ], [ 1137, 1138 ], [ 1140, 1146 ], [ 1148, 1162 ], [ 1164, 1168 ], [ 1170, 1175 ], [ 1177, 1179 ], [ 1181, 1184 ], [ 1186, 1186 ], [ 1188, 1196 ], [ 1198, 1204 ], [ 1206, 1210 ], [ 1212, 1226 ], [ 1228, 1228 ], [ 1230, 1234 ], [ 1236, 1236 ], [ 1238, 1246 ], [ 1248, 1250 ], [ 1252, 1259 ], [ 1261, 1261 ], [ 1263, 1272 ], [ 1274, 1288 ], [ 1290, 1291 ], [ 1293, 1295 ], [ 1297, 1300 ], [ 1302, 1315 ], [ 1317, 1323 ], [ 1325, 1339 ], [ 1341, 1344 ], [ 1346, 1350 ], [ 1352, 1356 ], [ 1358, 1358 ], [ 1360, 1383 ], [ 1385, 1386 ], [ 1388, 1389 ], [ 1391, 1392 ], [ 1394, 1397 ], [ 1399, 1400 ], [ 1403, 1403 ], [ 1405, 1406 ], [ 1408, 1409 ], [ 1411, 1418 ], [ 1420, 1421 ], [ 1423, 1423 ], [ 1425, 1427 ], [ 1429, 1432 ], [ 1434, 1435 ], [ 1437, 1442 ], [ 1444, 1447 ], [ 1449, 1449 ], [ 1451, 1460 ], [ 1462, 1465 ], [ 1467, 1468 ], [ 1470, 1481 ], [ 1483, 1483 ], [ 1485, 1488 ], [ 1490, 1503 ], [ 1505, 1517 ], [ 1519, 1520 ], [ 1522, 1522 ], [ 1524, 1530 ], [ 1532, 1532 ], [ 1534, 1534 ], [ 1536, 1564 ], [ 1566, 1607 ], [ 1609, 1612 ], [ 1614, 1614 ], [ 1616, 1621 ], [ 1623, 1640 ], [ 1642, 1643 ], [ 1645, 1645 ], [ 1647, 1648 ], [ 1650, 1654 ], [ 1656, 1657 ], [ 1659, 1667 ], [ 1669, 1670 ], [ 1672, 1677 ], [ 1679, 1680 ], [ 1682, 1693 ], [ 1695, 1696 ], [ 1698, 1703 ], [ 1705, 1706 ], [ 1708, 1712 ], [ 1714, 1715 ], [ 1717, 1720 ], [ 1722, 1723 ], [ 1725, 1725 ], [ 1727, 1739 ], [ 1808, 1815 ], [ 1817, 1823 ], [ 1825, 1836 ], [ 1838, 1846 ], [ 1848, 1850 ], [ 1852, 1859 ], [ 1861, 1862 ], [ 1864, 1865 ], [ 1867, 1872 ], [ 1874, 1878 ], [ 1880, 1883 ], [ 1885, 1886 ], [ 1888, 1899 ], [ 1901, 1904 ], [ 1906, 1913 ], [ 1915, 1917 ], [ 1919, 1927 ], [ 1929, 1935 ], [ 1937, 1942 ], [ 1944, 1954 ], [ 1956, 1967 ], [ 1969, 1970 ], [ 1972, 1985 ], [ 1987, 2015 ], [ 2017, 2019 ], [ 2021, 2023 ], [ 2025, 2026 ], [ 2028, 2040 ], [ 2042, 2043 ], [ 2045, 2048 ], [ 2051, 2053 ], [ 2055, 2057 ], [ 2059, 2067 ], [ 2069, 2074 ], [ 2076, 2079 ], [ 2081, 2087 ], [ 2089, 2103 ], [ 2105, 2120 ], [ 2122, 2125 ], [ 2169, 2179 ], [ 2181, 2188 ], [ 2190, 2193 ], [ 2195, 2197 ], [ 2199, 2205 ], [ 2207, 2211 ], [ 2213, 2222 ], [ 2224, 2226 ], [ 2228, 2233 ], [ 2235, 2241 ], [ 2243, 2245 ], [ 2247, 2247 ], [ 2249, 2249 ], [ 2251, 2255 ], [ 2257, 2257 ], [ 2259, 2267 ], [ 2269, 2270 ], [ 2272, 2275 ], [ 2277, 2284 ], [ 2286, 2292 ], [ 2294, 2304 ], [ 2306, 2312 ], [ 2314, 2320 ], [ 2322, 2327 ], [ 2329, 2333 ], [ 2335, 2338 ], [ 2340, 2343 ], [ 2345, 2349 ], [ 2351, 2353 ], [ 2355, 2362 ], [ 2364, 2366 ], [ 2368, 2373 ], [ 2375, 2380 ], [ 2382, 2387 ], [ 2389, 2403 ], [ 2405, 2405 ], [ 2407, 2411 ], [ 2413, 2413 ], [ 2415, 2419 ], [ 2421, 2423 ], [ 2425, 2425 ], [ 2427, 2433 ], [ 2435, 2439 ], [ 2441, 2442 ], [ 2449, 2451 ], [ 2453, 2455 ], [ 2457, 2460 ], [ 2462, 2476 ], [ 2478, 2480 ], [ 2482, 2489 ], [ 2491, 2491 ], [ 2493, 2502 ], [ 2504, 2507 ], [ 2509, 2510 ], [ 2512, 2532 ], [ 2534, 2535 ], [ 2537, 2537 ], [ 2539, 2540 ], [ 2542, 2543 ], [ 2545, 2564 ], [ 2566, 2566 ], [ 2568, 2573 ], [ 2575, 2578 ], [ 2580, 2587 ], [ 2589, 2594 ], [ 2596, 2599 ], [ 2602, 2609 ], [ 2611, 2615 ], [ 2617, 2620 ], [ 2622, 2622 ], [ 2624, 2626 ], [ 2628, 2630 ], [ 2632, 2635 ], [ 2637, 2639 ], [ 2641, 2641 ], [ 2643, 2651 ], [ 2653, 2655 ], [ 2657, 2664 ], [ 2666, 2666 ], [ 2668, 2685 ], [ 2687, 2688 ], [ 2690, 2694 ], [ 2696, 2696 ], [ 2698, 2698 ], [ 2700, 2700 ], [ 2702, 2716 ], [ 2718, 2723 ], [ 2725, 2730 ], [ 2732, 2740 ], [ 2742, 2743 ], [ 2745, 2747 ], [ 2749, 2752 ], [ 2754, 2757 ], [ 2759, 2763 ], [ 2765, 2768 ], [ 2770, 2771 ], [ 2773, 2774 ], [ 2776, 2784 ], [ 2786, 2788 ], [ 2790, 2797 ], [ 2799, 2799 ], [ 2801, 2818 ], [ 2820, 2824 ], [ 2826, 2831 ], [ 2833, 2835 ], [ 2837, 2845 ], [ 2847, 2849 ], [ 2851, 2858 ], [ 2860, 2860 ], [ 2862, 2880 ], [ 2882, 2884 ], [ 2887, 2894 ], [ 2896, 2900 ], [ 2902, 2904 ], [ 2906, 2907 ], [ 2909, 2913 ], [ 2915, 2919 ], [ 2921, 2922 ], [ 2924, 2928 ], [ 2930, 2932 ], [ 2934, 2936 ], [ 2938, 2941 ], [ 2943, 2950 ], [ 2952, 2956 ], [ 2958, 2958 ], [ 2960, 2962 ], [ 2964, 2969 ], [ 2971, 2978 ], [ 2980, 2987 ], [ 2989, 2993 ], [ 2995, 2996 ], [ 2998, 3002 ], [ 3004, 3012 ], [ 3014, 3021 ], [ 3023, 3023 ], [ 3025, 3029 ], [ 3031, 3041 ], [ 3043, 3051 ], [ 3053, 3054 ], [ 3058, 3063 ], [ 3065, 3074 ], [ 3076, 3080 ], [ 3082, 3091 ], [ 3093, 3110 ], [ 3112, 3114 ], [ 3116, 3123 ], [ 3125, 3125 ], [ 3127, 3136 ], [ 3138, 3138 ] ], [ [ 42, 42 ], [ 47, 47 ], [ 53, 53 ], [ 59, 59 ], [ 62, 62 ], [ 65, 65 ], [ 71, 71 ], [ 74, 74 ], [ 78, 78 ], [ 82, 82 ], [ 85, 85 ], [ 87, 87 ], [ 91, 91 ], [ 101, 101 ], [ 108, 108 ], [ 116, 116 ], [ 123, 123 ], [ 130, 130 ], [ 134, 134 ], [ 138, 138 ], [ 141, 141 ], [ 148, 148 ], [ 151, 151 ], [ 154, 154 ], [ 165, 165 ], [ 176, 176 ], [ 188, 188 ], [ 190, 190 ], [ 199, 199 ], [ 206, 206 ], [ 213, 213 ], [ 217, 217 ], [ 221, 221 ], [ 224, 224 ], [ 233, 233 ], [ 235, 235 ], [ 240, 240 ], [ 244, 244 ], [ 247, 247 ], [ 259, 259 ], [ 270, 270 ], [ 281, 281 ], [ 293, 293 ], [ 295, 295 ], [ 307, 307 ], [ 316, 316 ], [ 324, 324 ], [ 334, 334 ], [ 337, 337 ], [ 346, 346 ], [ 348, 348 ], [ 350, 350 ], [ 356, 356 ], [ 358, 358 ], [ 372, 372 ], [ 378, 378 ], [ 381, 381 ], [ 386, 386 ], [ 392, 392 ], [ 394, 394 ], [ 408, 408 ], [ 412, 412 ], [ 415, 415 ], [ 419, 419 ], [ 424, 424 ], [ 431, 431 ], [ 437, 437 ], [ 446, 446 ], [ 450, 450 ], [ 453, 453 ], [ 462, 462 ], [ 464, 464 ], [ 467, 467 ], [ 485, 485 ], [ 488, 488 ], [ 491, 491 ], [ 512, 512 ], [ 515, 515 ], [ 528, 528 ], [ 537, 538 ], [ 541, 542 ], [ 555, 555 ], [ 563, 563 ], [ 566, 566 ], [ 570, 570 ], [ 575, 575 ], [ 578, 578 ], [ 583, 583 ], [ 716, 716 ], [ 721, 721 ], [ 726, 726 ], [ 735, 767 ], [ 772, 772 ], [ 777, 777 ], [ 780, 780 ], [ 785, 785 ], [ 788, 788 ], [ 793, 793 ], [ 800, 800 ], [ 805, 805 ], [ 810, 810 ], [ 815, 815 ], [ 820, 820 ], [ 836, 836 ], [ 844, 844 ], [ 848, 848 ], [ 854, 854 ], [ 859, 859 ], [ 861, 861 ], [ 865, 865 ], [ 879, 879 ], [ 882, 882 ], [ 886, 886 ], [ 891, 891 ], [ 893, 893 ], [ 901, 901 ], [ 905, 905 ], [ 916, 916 ], [ 924, 924 ], [ 928, 928 ], [ 933, 933 ], [ 942, 942 ], [ 944, 944 ], [ 949, 949 ], [ 954, 954 ], [ 956, 956 ], [ 961, 961 ], [ 966, 966 ], [ 968, 968 ], [ 970, 970 ], [ 982, 982 ], [ 986, 986 ], [ 995, 995 ], [ 997, 997 ], [ 1008, 1008 ], [ 1010, 1010 ], [ 1019, 1019 ], [ 1023, 1023 ], [ 1026, 1026 ], [ 1034, 1034 ], [ 1038, 1038 ], [ 1042, 1042 ], [ 1048, 1048 ], [ 1052, 1052 ], [ 1058, 1058 ], [ 1064, 1064 ], [ 1068, 1068 ], [ 1073, 1073 ], [ 1078, 1078 ], [ 1083, 1083 ], [ 1087, 1087 ], [ 1096, 1096 ], [ 1098, 1098 ], [ 1108, 1108 ], [ 1110, 1110 ], [ 1116, 1116 ], [ 1120, 1120 ], [ 1124, 1124 ], [ 1130, 1130 ], [ 1133, 1133 ], [ 1136, 1136 ], [ 1139, 1139 ], [ 1147, 1147 ], [ 1163, 1163 ], [ 1169, 1169 ], [ 1176, 1176 ], [ 1180, 1180 ], [ 1185, 1185 ], [ 1187, 1187 ], [ 1197, 1197 ], [ 1205, 1205 ], [ 1211, 1211 ], [ 1227, 1227 ], [ 1229, 1229 ], [ 1235, 1235 ], [ 1237, 1237 ], [ 1247, 1247 ], [ 1251, 1251 ], [ 1260, 1260 ], [ 1262, 1262 ], [ 1273, 1273 ], [ 1289, 1289 ], [ 1292, 1292 ], [ 1296, 1296 ], [ 1301, 1301 ], [ 1316, 1316 ], [ 1324, 1324 ], [ 1340, 1340 ], [ 1345, 1345 ], [ 1351, 1351 ], [ 1357, 1357 ], [ 1359, 1359 ], [ 1384, 1384 ], [ 1387, 1387 ], [ 1390, 1390 ], [ 1393, 1393 ], [ 1398, 1398 ], [ 1401, 1402 ], [ 1404, 1404 ], [ 1407, 1407 ], [ 1410, 1410 ], [ 1419, 1419 ], [ 1422, 1422 ], [ 1424, 1424 ], [ 1428, 1428 ], [ 1433, 1433 ], [ 1436, 1436 ], [ 1443, 1443 ], [ 1448, 1448 ], [ 1450, 1450 ], [ 1461, 1461 ], [ 1466, 1466 ], [ 1469, 1469 ], [ 1482, 1482 ], [ 1484, 1484 ], [ 1489, 1489 ], [ 1504, 1504 ], [ 1518, 1518 ], [ 1521, 1521 ], [ 1523, 1523 ], [ 1531, 1531 ], [ 1533, 1533 ], [ 1535, 1535 ], [ 1565, 1565 ], [ 1608, 1608 ], [ 1613, 1613 ], [ 1615, 1615 ], [ 1622, 1622 ], [ 1641, 1641 ], [ 1644, 1644 ], [ 1646, 1646 ], [ 1649, 1649 ], [ 1655, 1655 ], [ 1658, 1658 ], [ 1668, 1668 ], [ 1671, 1671 ], [ 1678, 1678 ], [ 1681, 1681 ], [ 1694, 1694 ], [ 1697, 1697 ], [ 1704, 1704 ], [ 1707, 1707 ], [ 1713, 1713 ], [ 1716, 1716 ], [ 1721, 1721 ], [ 1724, 1724 ], [ 1726, 1726 ], [ 1740, 1807 ], [ 1816, 1816 ], [ 1824, 1824 ], [ 1837, 1837 ], [ 1847, 1847 ], [ 1851, 1851 ], [ 1860, 1860 ], [ 1863, 1863 ], [ 1866, 1866 ], [ 1873, 1873 ], [ 1879, 1879 ], [ 1884, 1884 ], [ 1887, 1887 ], [ 1900, 1900 ], [ 1905, 1905 ], [ 1914, 1914 ], [ 1918, 1918 ], [ 1928, 1928 ], [ 1936, 1936 ], [ 1943, 1943 ], [ 1955, 1955 ], [ 1968, 1968 ], [ 1971, 1971 ], [ 1986, 1986 ], [ 2016, 2016 ], [ 2020, 2020 ], [ 2024, 2024 ], [ 2027, 2027 ], [ 2041, 2041 ], [ 2044, 2044 ], [ 2049, 2050 ], [ 2054, 2054 ], [ 2058, 2058 ], [ 2068, 2068 ], [ 2075, 2075 ], [ 2080, 2080 ], [ 2088, 2088 ], [ 2104, 2104 ], [ 2121, 2121 ], [ 2126, 2168 ], [ 2180, 2180 ], [ 2189, 2189 ], [ 2194, 2194 ], [ 2198, 2198 ], [ 2206, 2206 ], [ 2212, 2212 ], [ 2223, 2223 ], [ 2227, 2227 ], [ 2234, 2234 ], [ 2242, 2242 ], [ 2246, 2246 ], [ 2248, 2248 ], [ 2250, 2250 ], [ 2256, 2256 ], [ 2258, 2258 ], [ 2268, 2268 ], [ 2271, 2271 ], [ 2276, 2276 ], [ 2285, 2285 ], [ 2293, 2293 ], [ 2305, 2305 ], [ 2313, 2313 ], [ 2321, 2321 ], [ 2328, 2328 ], [ 2334, 2334 ], [ 2339, 2339 ], [ 2344, 2344 ], [ 2350, 2350 ], [ 2354, 2354 ], [ 2363, 2363 ], [ 2367, 2367 ], [ 2374, 2374 ], [ 2381, 2381 ], [ 2388, 2388 ], [ 2404, 2404 ], [ 2406, 2406 ], [ 2412, 2412 ], [ 2414, 2414 ], [ 2420, 2420 ], [ 2424, 2424 ], [ 2426, 2426 ], [ 2434, 2434 ], [ 2440, 2440 ], [ 2443, 2448 ], [ 2452, 2452 ], [ 2456, 2456 ], [ 2461, 2461 ], [ 2477, 2477 ], [ 2481, 2481 ], [ 2490, 2490 ], [ 2492, 2492 ], [ 2503, 2503 ], [ 2508, 2508 ], [ 2511, 2511 ], [ 2533, 2533 ], [ 2536, 2536 ], [ 2538, 2538 ], [ 2541, 2541 ], [ 2544, 2544 ], [ 2565, 2565 ], [ 2567, 2567 ], [ 2574, 2574 ], [ 2579, 2579 ], [ 2588, 2588 ], [ 2595, 2595 ], [ 2600, 2601 ], [ 2610, 2610 ], [ 2616, 2616 ], [ 2621, 2621 ], [ 2623, 2623 ], [ 2627, 2627 ], [ 2631, 2631 ], [ 2636, 2636 ], [ 2640, 2640 ], [ 2642, 2642 ], [ 2652, 2652 ], [ 2656, 2656 ], [ 2665, 2665 ], [ 2667, 2667 ], [ 2686, 2686 ], [ 2689, 2689 ], [ 2695, 2695 ], [ 2697, 2697 ], [ 2699, 2699 ], [ 2701, 2701 ], [ 2717, 2717 ], [ 2724, 2724 ], [ 2731, 2731 ], [ 2741, 2741 ], [ 2744, 2744 ], [ 2748, 2748 ], [ 2753, 2753 ], [ 2758, 2758 ], [ 2764, 2764 ], [ 2769, 2769 ], [ 2772, 2772 ], [ 2775, 2775 ], [ 2785, 2785 ], [ 2789, 2789 ], [ 2798, 2798 ], [ 2800, 2800 ], [ 2819, 2819 ], [ 2825, 2825 ], [ 2832, 2832 ], [ 2836, 2836 ], [ 2846, 2846 ], [ 2850, 2850 ], [ 2859, 2859 ], [ 2861, 2861 ], [ 2881, 2881 ], [ 2885, 2886 ], [ 2895, 2895 ], [ 2901, 2901 ], [ 2905, 2905 ], [ 2908, 2908 ], [ 2914, 2914 ], [ 2920, 2920 ], [ 2923, 2923 ], [ 2929, 2929 ], [ 2933, 2933 ], [ 2937, 2937 ], [ 2942, 2942 ], [ 2951, 2951 ], [ 2957, 2957 ], [ 2959, 2959 ], [ 2963, 2963 ], [ 2970, 2970 ], [ 2979, 2979 ], [ 2988, 2988 ], [ 2994, 2994 ], [ 2997, 2997 ], [ 3003, 3003 ], [ 3013, 3013 ], [ 3022, 3022 ], [ 3024, 3024 ], [ 3030, 3030 ], [ 3042, 3042 ], [ 3052, 3052 ], [ 3055, 3057 ], [ 3064, 3064 ], [ 3075, 3075 ], [ 3081, 3081 ], [ 3092, 3092 ], [ 3111, 3111 ], [ 3115, 3115 ], [ 3124, 3124 ], [ 3126, 3126 ], [ 3137, 3137 ], [ 3139, 3142 ] ] ]
b6a9f14569441310bcaae03592359448ae6a0e8d
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/src/algorithms/features/IFeaturesMatcher.hpp
09d427a99d5517610ef0b84d7fa0465f2639bc9a
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
931
hpp
#if !defined(IFEATURES_MATCHER_HEADER_INCLUDED) #define IFEATURES_MATCHER_HEADER_INCLUDED // Noisy features matching // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // Headers #include "ScoredMatch.hpp" #include <vector> namespace uniclop { using namespace std; // ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~= // Classes definition template <typename F> // F is the feature type class IFeaturesMatcher { // will return a list of ScoredMatches public: virtual vector< ScoredMatch >& match(const vector<F>& features_vector_a, const vector<F>& features_vector_b) = 0; ///< since the matcher stores pointers to the features we have to be extra carefull of not ///< changing the features_vector content could invalidate the pointers ! }; } #endif // IFEATURES_MATCHER_HEADER_INCLUDED
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 37 ] ] ]
9ea9a60c44b30c718c3e519dab35b83801f3d3b1
4d838ba98a21fc4593652e66eb7df0fac6282ef6
/CaveProj/Player.h
05ca002a90944dbbd49afd088e0f733189d4091f
[]
no_license
davidhart/ProceduralCaveEditor
39ed0cf4ab4acb420fa2ad4af10f9546c138a83a
31264591f2dcd250299049c826aeca18fc52880e
refs/heads/master
2021-01-17T15:10:09.100572
2011-05-03T19:24:06
2011-05-03T19:24:06
69,302,913
0
0
null
null
null
null
UTF-8
C++
false
false
759
h
#pragma once #ifndef _PLAYER_H_ #define _PLAYER_H_ #include "Vector.h" #include "Camera.h" #include <vector> class Environment; class RenderWindow; class Player { public: Player(Environment& environment); void Load(RenderWindow& renderWindow); void Update(const Vector2f& movement, const Vector2f& rotation, float dt, bool fly, bool jump); void Reset(); inline Camera& GetCamera() { return _camera; } inline const Vector3f& Position() const { return _camera.Position(); } bool NearChest(const Vector3f& chestPos); private: std::vector<Vector3f> _samplePositions; float _radius; float _height; Environment& _environment; Vector3f _position; Vector3f _velocity; Camera _camera; bool _onGround; }; #endif
[ [ [ 1, 36 ] ] ]
d9058cdfcaac430882d8ed4f2686215033f0423e
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/datamodl.hpp
0435b1ef7c2388c3ac508a0b57e1dafbd7041558
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
2,638
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'DataModl.pas' rev: 6.00 #ifndef DataModlHPP #define DataModlHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <DBTables.hpp> // Pascal unit #include <DB.hpp> // Pascal unit #include <Dialogs.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Datamodl { //-- type declarations ------------------------------------------------------- class DELPHICLASS TDataMod; class PASCALIMPLEMENTATION TDataMod : public Classes::TDataModule { typedef Classes::TDataModule inherited; __published: Dbtables::TTable* Table1; Dbtables::TQuery* Query1; Dbtables::TTable* Table2; Dbtables::TQuery* Query2; Db::TDataSource* DataSource1; Db::TDataSource* DataSource2; void __fastcall DataModuleCreate(System::TObject* Sender); public: bool MultiQuery; bool CreateTable; Classes::TMemoryStream* __fastcall CreateRes(const AnsiString ModuleName); Classes::TMemoryStream* __fastcall CreateHdrSource(const AnsiString FilePath, const AnsiString FormName); Classes::TMemoryStream* __fastcall CreateCppSource(const AnsiString FilePath, const AnsiString FormName); Classes::TMemoryStream* __fastcall CreateSource(const AnsiString FilePath, const AnsiString FormName); public: #pragma option push -w-inl /* TDataModule.Create */ inline __fastcall virtual TDataMod(Classes::TComponent* AOwner) : Classes::TDataModule(AOwner) { } #pragma option pop #pragma option push -w-inl /* TDataModule.CreateNew */ inline __fastcall virtual TDataMod(Classes::TComponent* AOwner, int Dummy) : Classes::TDataModule(AOwner, Dummy) { } #pragma option pop #pragma option push -w-inl /* TDataModule.Destroy */ inline __fastcall virtual ~TDataMod(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Datamodl */ using namespace Datamodl; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // DataModl
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 75 ] ] ]
5bd827a4738402511f27bc2894b2acadfea3ce19
d7040d1802ff8d69100c8d90b0191b8f7087eed8
/刘晋德_短信集成/Phone/Phone/MessageDlg.h
9a0ea2ac8a85a240e7d2a79f1c9dbf5db12911b3
[]
no_license
radtek/scu-phone
689fa50e785c01e2154959f46d1edad3926f3efb
4cbe8f803858ded7a92238af91b8fecfe58f348f
refs/heads/master
2020-12-31T07:44:04.107424
2011-05-08T10:35:40
2011-05-08T10:35:40
58,142,165
0
0
null
null
null
null
GB18030
C++
false
false
1,295
h
#pragma once #include "afxwin.h" #include "afxcmn.h" // MessageDlg 对话框 class MessageDlg : public CDialog { DECLARE_DYNAMIC(MessageDlg) public: MessageDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~MessageDlg(); // 对话框数据 enum { IDD = IDD_Main_Messagedlg }; private: int m_currentTab; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult); CListBox SMS_listbox_shoujian; CListBox SMS_listbox_caogao; CListBox SMS_listbox_fajian; CTabCtrl SMS_tabctrl; virtual BOOL OnInitDialog(); CString SMS_TextContent; afx_msg void OnBnClickedButton2(); CString SMS_PhoneNM; afx_msg void OnBnClickedButton1(); CButton BT_fasong; CButton BT_cuncaogao; CButton BT_huifu; CButton BT_xinduanxin; CButton BT_qingkong; CButton BT_shanchu; afx_msg void OnEnChangeEdit1(); afx_msg void OnEnChangeEdit2(); afx_msg void OnBnClickedButton5(); afx_msg void OnCbnSelchangeCombo1(); CComboBox SMS_ComboCtrl; afx_msg void OnBnClickedButton3(); afx_msg void OnBnClickedButton7(); afx_msg void OnLbnDblclkList1(); afx_msg void OnLbnDblclkList2(); afx_msg void OnBnClickedButton4(); };
[ [ [ 1, 52 ] ] ]
e79a0601f512a7d15d3bbbadac22859d78308259
135522f4ca53fda5a5f5eac5b79a3f5f8f2c089f
/EasyWar/Sound.cpp
ef0c98446284c0b86d4ef464352fc98e1af090b2
[]
no_license
weimingtom/easywar
b0a006a59cc059131ba30c6aa8fd238643a201de
5279851c0c23af51b2273b2076d05f44a50bc2c7
refs/heads/master
2021-01-09T21:58:26.257817
2009-12-13T02:52:06
2009-12-13T02:52:06
44,422,879
1
0
null
null
null
null
GB18030
C++
false
false
2,198
cpp
#include "stdafx.h" #include "Sound.h" Sound* Sound::m_me = NULL; Sound::Sound() { } Sound::~Sound() { } //获取本类的单件 Sound* Sound::GetSingle() { if( m_me == NULL ) { m_me = new Sound(); } return m_me; } //摧毁函数 void Sound::Destroy() { if( m_me ) { Mix_CloseAudio(); FreeAllSE(); FreeAllBGM(); delete m_me; m_me = NULL; } } //初始化音频设备 bool Sound::InitDevice() { int TMP_FREQ = MIX_DEFAULT_FREQUENCY; Uint16 TMP_FORMAT = MIX_DEFAULT_FORMAT; int TMP_CHUNK_SIZE = 512; //4通道混音 int result = Mix_OpenAudio(TMP_FREQ,TMP_FORMAT,MAX_CHANNEL,TMP_CHUNK_SIZE); m_curChannel = 0; return result == 1 ? true : false; } //释放所有的SE void Sound::FreeAllSE() { size_t len = m_allSE.size(); for( size_t i(0); i< len; i++ ) { Mix_FreeChunk( m_allSE[i] ); } m_allSE.clear(); } //释放所有的BGM void Sound::FreeAllBGM() { size_t len = m_allBGM.size(); for( size_t i(0); i< len; i++ ) { Mix_FreeMusic( m_allBGM[i] ); } m_allBGM.clear(); } //播放音效 void Sound::PlaySE( int num, int loop ) { Mix_PlayChannel( m_curChannel++, m_allSE[num], loop ); if( m_curChannel >= MAX_CHANNEL ) { m_curChannel = 0; } } //播放背景音乐 void Sound::PlayBGM( int num, int loop ) { Mix_PlayMusic( m_allBGM[num], loop ); } //加载一个音效声音 int Sound::LoadSE( const char* fileName ) { Mix_Chunk* music; music = Mix_LoadWAV( fileName ); //加载失败 if( music == NULL ) { return -1; } m_allSE.push_back( music ); return (int)m_allSE.size() - 1; } //加载一个背景音乐 int Sound::LoadBGM( const char* fileName ) { Mix_Music* music; music = Mix_LoadMUS( fileName ); //加载失败 if( music == NULL ) { return -1; } m_allBGM.push_back( music ); return (int)m_allBGM.size() - 1; } //暂停BGM的播放 void Sound::StopBGM() { Mix_FadeOutMusic( 1000 ); } //暂停SE的播放 void Sound::StopSE() { Mix_FadeOutChannel( 0, 0 ); Mix_FadeOutChannel( 1, 0 ); Mix_FadeOutChannel( 2, 0 ); Mix_FadeOutChannel( 3, 0 ); }
[ "xujia1985@d64887d6-d1e9-11de-a205-5990a31c5447" ]
[ [ [ 1, 149 ] ] ]
e60d4c7bef8a27abc64c8996ba211f5fc4cc3dd1
53be98f8be4a38b11f5d25f0914295660660bfcc
/Source/main.cxx
b6293ddcbd165e6e3c617c454dfb6ab1fba24e49
[]
no_license
midas-journal/midas-journal-786
ec0f3e3b67a79a9cd82eff3a393b4418604b980f
6730ce90c4bbc63146089f40b036f78227203b28
refs/heads/master
2021-01-19T16:57:29.080520
2011-08-22T13:48:17
2011-08-22T13:48:17
2,248,756
0
0
null
null
null
null
UTF-8
C++
false
false
3,840
cxx
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: main.cxx,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #define _SCL_SECURE_NO_WARNINGS #define NO_TESTING #include "itkWin32Header.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkSimpleFilterWatcher.h" #include "itkSimpleProjectionImageFilter.h" // Projection ============================================= template <typename TPixel, unsigned int VDimension> int mainProjection(int argc, char * argv []) { try { // Read command-line parameters if ( argc < 4 ) { std::cout << "USAGE: " << argv[0] << " "; std::cout << "InputFilename OutputFilename Strategy "; std::cout << "ProjectionDimension"; std::cout << std::endl; return EXIT_FAILURE; } int arg = 1; char* InputFilename = argv[arg++]; char* OutputFilename = argv[arg++]; itk::ProjectionStrategy Strategy = static_cast<itk::ProjectionStrategy>( atoi(argv[arg++]) ); unsigned int ProjectionDimension = atoi( argv[arg++] ); std::cout << "Test=" << "Projection" << std::endl; std::cout << "PixelType=" << typeid(TPixel).name() << std::endl; std::cout << "Dimension=" << VDimension << std::endl; std::cout << "InputFilename=" << InputFilename << std::endl; std::cout << "OutputFilename=" << OutputFilename << std::endl; std::cout << "Strategy=" << Strategy << std::endl; std::cout << "ProjectionDimension=" << ProjectionDimension << std::endl; // Helpful typedefs typedef TPixel PixelType; static const unsigned int InputDimension = VDimension; static const unsigned int OutputDimension = VDimension - 1; typedef itk::Image<PixelType, InputDimension> InputImageType; typedef itk::Image<PixelType, OutputDimension> OutputImageType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::SimpleProjectionImageFilter<InputImageType,OutputImageType> ProjectionType; typedef itk::ImageFileWriter<OutputImageType> WriterType; // Read input typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(InputFilename); reader->Update(); typename InputImageType::Pointer input = reader->GetOutput(); input->DisconnectPipeline(); // Filter typename ProjectionType::Pointer filter = ProjectionType::New(); filter->SetStrategy(Strategy); filter->SetInput(input); filter->SetProjectionDimension(ProjectionDimension); filter->Update(); // Write output typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(OutputFilename); writer->SetInput(filter->GetOutput()); writer->Update(); return EXIT_SUCCESS; } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } int main(int argc, char *argv[]) { try { mainProjection<unsigned char, 3>(argc, argv); } catch (itk::ExceptionObject &ex) { std::cerr << ex << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
[ [ [ 1, 113 ] ] ]
82881d42562d97a272d662077d47a54e54b8c629
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/QtGui/qprintengine.h
4b41d120bea921aec165af5b46c48577dab8c3b7
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,646
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, 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.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPRINTENGINE_H #define QPRINTENGINE_H #include <QtCore/qvariant.h> #include <QtGui/qprinter.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_PRINTER class Q_GUI_EXPORT QPrintEngine { public: virtual ~QPrintEngine() {} enum PrintEnginePropertyKey { PPK_CollateCopies, PPK_ColorMode, PPK_Creator, PPK_DocumentName, PPK_FullPage, PPK_NumberOfCopies, PPK_Orientation, PPK_OutputFileName, PPK_PageOrder, PPK_PageRect, PPK_PageSize, PPK_PaperRect, PPK_PaperSource, PPK_PrinterName, PPK_PrinterProgram, PPK_Resolution, PPK_SelectionOption, PPK_SupportedResolutions, PPK_WindowsPageSize, PPK_FontEmbedding, PPK_SuppressSystemPrintStatus, PPK_Duplex, PPK_PaperSources, PPK_CustomPaperSize, PPK_PageMargins, PPK_PaperSize = PPK_PageSize, PPK_CustomBase = 0xff00 }; virtual void setProperty(PrintEnginePropertyKey key, const QVariant &value) = 0; virtual QVariant property(PrintEnginePropertyKey key) const = 0; virtual bool newPage() = 0; virtual bool abort() = 0; virtual int metric(QPaintDevice::PaintDeviceMetric) const = 0; virtual QPrinter::PrinterState printerState() const = 0; #ifdef Q_WS_WIN virtual HDC getPrinterDC() const { return 0; } virtual void releasePrinterDC(HDC) const { } #endif }; #endif // QT_NO_PRINTER QT_END_NAMESPACE QT_END_HEADER #endif // QPRINTENGINE_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 117 ] ] ]
8e3ed6d63e5dce6ef5cec748284a2bce4f58890a
adc59ef30a9ded0fa3dba3be1bb5ae4ecb713172
/cylinder.cpp
c22a2e82f8212500f2bc624767ba138abdd7cb68
[]
no_license
NIA/D3DShadows
b4e864022204cec0a097b1c453c630d21a373dec
3a6f84d24413e2bcecc4d76984fa88b45205695d
refs/heads/master
2016-09-05T11:20:25.554675
2009-11-30T03:41:06
2009-11-30T03:41:06
386,517
1
0
null
null
null
null
UTF-8
C++
false
false
7,754
cpp
#include "cylinder.h" const Index CYLINDER_EDGES_PER_BASE = 300; const Index CYLINDER_EDGES_PER_HEIGHT = 250; const Index CYLINDER_EDGES_PER_CAP = 100; const Index CYLINDER_VERTICES_COUNT = (CYLINDER_EDGES_PER_BASE)*((CYLINDER_EDGES_PER_HEIGHT + 1) + 2 + 2*(CYLINDER_EDGES_PER_CAP -1)) // vertices per CYLINDER_EDGES_PER_HEIGHT+1 levels plus last ans first levels again, plus CYLINDER_EDGES_PER_CAP-1 levels per each of 2 caps + 2 // plus centers of 2 caps + CYLINDER_EDGES_PER_HEIGHT; // plus jump between top and bottom const DWORD CYLINDER_INDICES_COUNT = 2*(CYLINDER_EDGES_PER_BASE + 1)*(CYLINDER_EDGES_PER_HEIGHT + 2*(CYLINDER_EDGES_PER_CAP - 1)) // indices per CYLINDER_EDGES_PER_HEIGHT levels plus CYLINDER_EDGES_PER_CAP-1 levels per each of 2 caps + 2*(2*CYLINDER_EDGES_PER_BASE + 1) // plus 2 ends of caps + CYLINDER_EDGES_PER_HEIGHT + 2; // plus jump between top and bottom namespace { struct GENERATION_PARAMS { // output buffers SkinningVertex *res_vertices; Index *res_indices; // sizes float radius; float height; // colors const D3DCOLOR *colors; unsigned colors_count; // options bool radial_strips; // radial (depending on step) or vertical (depending on level) color distribution bool vertical; // vertical (for cylinder side) or horisontal (for caps) moving whe generating bool top; // for cap generation: is it top or bottom cap. Ignored when vertical == true }; void generate_levels(Index &vertex, DWORD &index, const GENERATION_PARAMS &params) { const float STEP_ANGLE = 2*D3DX_PI/CYLINDER_EDGES_PER_BASE; const float STEP_UP = params.height/CYLINDER_EDGES_PER_HEIGHT; const float STEP_RADIAL = params.radius/CYLINDER_EDGES_PER_CAP; Index levels_count = params.vertical ? CYLINDER_EDGES_PER_HEIGHT + 1 : CYLINDER_EDGES_PER_CAP; Index levels_or_steps_count = params.radial_strips ? CYLINDER_EDGES_PER_BASE : levels_count; _ASSERT(params.colors_count != 0); Index part_size = (levels_or_steps_count + params.colors_count)/params.colors_count; // `+ colors_count' just for excluding a bound of interval [0, colors_count) D3DXVECTOR3 normal_if_horisontal = D3DXVECTOR3(0, 0, params.top ? 1.0f : -1.0f); float z_if_horisontal = params.top ? params.height : 0.0f; float weight_if_horisontal = params.top ? 1.0f : 0.0f; for( Index level = 0; level < levels_count; ++level ) { for( Index step = 0; step < CYLINDER_EDGES_PER_BASE; ++step ) { float radius = params.vertical ? params.radius : (params.radius - STEP_RADIAL*level); float z, weight; D3DXVECTOR3 normal; if (params.vertical) { z = level*STEP_UP; weight = static_cast<float>(level)/CYLINDER_EDGES_PER_HEIGHT; normal = D3DXVECTOR3( cos(step*STEP_ANGLE), sin(step*STEP_ANGLE), 0 ); } else { normal = normal_if_horisontal; z = z_if_horisontal; weight = weight_if_horisontal; } D3DXVECTOR3 position = D3DXVECTOR3( radius*cos(step*STEP_ANGLE), radius*sin(step*STEP_ANGLE), z); D3DCOLOR color = params.radial_strips ? params.colors[step/part_size] : params.colors[level/part_size]; if( level == 0 && !params.vertical) { // first level for horisontal is just copy of: // * last vertices (for top cap) // OR // * first vertices (for bottom cap) unsigned copy_from = params.top ? vertex - CYLINDER_EDGES_PER_BASE : step; params.res_vertices[vertex] = params.res_vertices[copy_from]; params.res_vertices[vertex].set_normal( normal ); params.res_vertices[vertex].color = color; ++vertex; continue; } params.res_vertices[vertex] = SkinningVertex(position, color, weight, normal); if( level != 0 ) { params.res_indices[index++] = vertex - CYLINDER_EDGES_PER_BASE; // from previous level params.res_indices[index++] = vertex; // from current level if( step == CYLINDER_EDGES_PER_BASE - 1 ) // last step { params.res_indices[index++] = vertex - 2*CYLINDER_EDGES_PER_BASE + 1; // first from previuos level params.res_indices[index++] = vertex - CYLINDER_EDGES_PER_BASE + 1; // first from current level } } ++vertex; } } if( !params.vertical ) { // for caps: add center vertex and triangles with it D3DXVECTOR3 position = D3DXVECTOR3( 0, 0, z_if_horisontal ); params.res_vertices[vertex] = SkinningVertex( position, params.colors[0], weight_if_horisontal, normal_if_horisontal ); for( Index step = 0; step < CYLINDER_EDGES_PER_BASE; ++step ) { params.res_indices[index++] = vertex - CYLINDER_EDGES_PER_BASE + step; params.res_indices[index++] = vertex; } params.res_indices[index++] = vertex - CYLINDER_EDGES_PER_BASE; ++vertex; } } } void cylinder( float radius, float height, const D3DCOLOR *colors, unsigned colors_count, SkinningVertex *res_vertices, Index *res_indices) // Writes data into arrays given as `res_vertices' and `res_indices', { Index vertex = 0; // current vertex DWORD index = 0; // current index _ASSERT(res_vertices != NULL); _ASSERT(res_indices != NULL); _ASSERT(CYLINDER_EDGES_PER_BASE != 0); _ASSERT(CYLINDER_EDGES_PER_HEIGHT != 0); _ASSERT(CYLINDER_EDGES_PER_CAP != 0); GENERATION_PARAMS params; // output buffers params.res_vertices = res_vertices; params.res_indices = res_indices; // sizes params.radius = radius; params.height = height; // colors params.colors = colors; params.colors_count = colors_count; // options params.radial_strips = false; params.vertical = true; generate_levels(vertex, index, params); // Cap params.radial_strips = true; params.vertical = false; params.top = true; generate_levels(vertex, index, params); // Go from last level to first inside cylinder const float STEP_UP = params.height/CYLINDER_EDGES_PER_HEIGHT; for( unsigned level = CYLINDER_EDGES_PER_HEIGHT; level != 0; --level ) { res_vertices[vertex] = SkinningVertex( D3DXVECTOR3(0, 0, level*STEP_UP), static_cast<float>(level)/CYLINDER_EDGES_PER_HEIGHT, D3DXVECTOR3(0,0,1.0f) ); res_indices[index++] = vertex; ++vertex; } for( unsigned i = 0; i < VERTICES_PER_TRIANGLE-1; ++i ) { // making degenerate triangle res_indices[index++] = vertex; } params.top = false; generate_levels(vertex, index, params); }
[ [ [ 1, 171 ] ] ]
e08a57c8ff23bc0647a5376ddc09ceb03180cce5
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestsettingpage/inc/bctestsettingpagecase.h
22a86dc271368fdc7e4bd48eadbfa200f9fd443b
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,500
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: test case * */ #ifndef C_BCTEST_SETTINGPAGECASE_H #define C_BCTEST_SETTINGPAGECASE_H #include "bctestcase.h" class CBCTestSettingPageContainer; class CCoeControl; /** * test case for various list classes */ class CBCTestSettingPageCase: public CBCTestCase { public: // constructor and destructor /** * Symbian 2nd static constructor */ static CBCTestSettingPageCase* NewL( CBCTestSettingPageContainer* aContainer ); /** * Destructor */ virtual ~CBCTestSettingPageCase(); public: // from CBCTestCase /** * Execute corresponding test functions for UI command * @param aCmd, UI command */ void RunL( TInt aCmd ); protected: // new functions /** * Build autotest script */ void BuildScriptL(); /** * Create control or allocate resource for test * @param aCmd UI command, maybe you need to do some work * for different outline */ void PrepareCaseL( TInt aCmd ); /** * Release resource used in test */ void ReleaseCaseL(); /** * Test functions */ void TestCheckBoxSettingPageL(); void TestPasswordSettingPageL(); void TestTextSettingPageL(); void TestSliderSettingPageL(); void TestVolumeSettingPageL(); void TestRadioButtonSettingPageL(); void TestSettingItemListL(); void TestMFneSettingPageL(); void TestSettingPageL(); void TestDescArrayL(); void TestAllL(); private: // constructor /** * C++ default constructor */ CBCTestSettingPageCase( CBCTestSettingPageContainer* aContainer ); /** * Symbian 2nd constructor */ void ConstructL(); private: // data /** * Pointer to a control, maybe you need one in your test * own */ CCoeControl* iControl; /** * Pointer to container. * not own */ CBCTestSettingPageContainer* iContainer; }; #endif // C_BCTEST_SETTINGPAGECASE_H
[ "none@none" ]
[ [ [ 1, 115 ] ] ]
34a8d86e854aaf53db087cdaee5765b6d6cb78bf
6dd76b2926b02d80da4c01769659b4f8a21dd54e
/JudyArray/Stdafx.cpp
7629b7703c4d78331828f2b454f703751ef5a0e1
[]
no_license
dump247/JudyArray
b33b9af4fb830bc85c64cca7b9a37ae9caddaccf
a2351759ddf79de377f39140cd64e9e8fa5501f8
refs/heads/master
2020-04-06T07:02:35.742181
2011-03-23T08:48:17
2011-03-23T08:48:17
1,471,037
2
0
null
null
null
null
UTF-8
C++
false
false
1,040
cpp
// _________________ // // Copyright (C) 2011 Cory Thomas // // This program is free software; you can redistribute it and/or modify it // under the term of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // _________________ // stdafx.cpp : source file that includes just the standard includes // JudyArray.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 17 ] ], [ [ 18, 24 ] ] ]
edfd6350fb6eb79697b893fae42cdf89f7a086bf
19b8f2132768c8c52238180e15815cbd4243b41d
/EDA fase II/EDA II Fase 900/900/main.cpp
21af359a2ec20b0e6d8ec67ffddf3c160bc5a7ef
[]
no_license
Greatfox/Programas-EDA
604ae99e2576ecfae8a0a2965834d1206f41fb02
73d5d5961e041c27aadea0314f066e21e6d87807
refs/heads/master
2016-09-03T02:23:10.221535
2011-12-16T04:44:39
2011-12-16T04:44:39
2,279,239
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include <stdio.h> long long fibo[51]; void fibonacci () { int i = 1; fibo[0] = 1, fibo[1] = 1; while (i++ < 51) { fibo[i] = fibo[i-1] + fibo[i-2]; } } int main () { int n; fibonacci(); while (scanf ("%d", &n)) { if (n == 0) return 0; printf ("%d\n", fibo[n]); } return 0; }
[ [ [ 1, 25 ] ] ]