hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
ca0ee500e8332c1c3587b2856f247843ca929274
6,963
h
C
src/SpecialEffects/SpecialEffects/DIBSectionLite.h
xingyun86/ppshuaispecialeffects
28c5232c1665bb5fecabba8c48f18ba814648d1d
[ "MIT" ]
null
null
null
src/SpecialEffects/SpecialEffects/DIBSectionLite.h
xingyun86/ppshuaispecialeffects
28c5232c1665bb5fecabba8c48f18ba814648d1d
[ "MIT" ]
null
null
null
src/SpecialEffects/SpecialEffects/DIBSectionLite.h
xingyun86/ppshuaispecialeffects
28c5232c1665bb5fecabba8c48f18ba814648d1d
[ "MIT" ]
null
null
null
#if !defined(AFX_CDIBSECTIONLITE_H__35D9F3D4_B960_11D2_A981_2C4476000000__INCLUDED_) #define AFX_CDIBSECTIONLITE_H__35D9F3D4_B960_11D2_A981_2C4476000000__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DIBSectionLite.h : header file // // Copyright ?Dundas Software Ltd. 1999, All Rights Reserved // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // NO Derived from CWnd // NO Is a CWnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource (template) // YES Persistent objects (saveable on disk) // YES Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // DIBSection is DIBSection wrapper class for Win32 platforms. // This class provides a simple interface to DIBSections including loading, // saving and displaying DIBsections. // // Using DIBSection : // This class is very simple to use. The bitmap can be set using either SetBitmap() // (which accepts either a Device dependant or device independant bitmap, or a // resource ID) or by using Load(), which allows an image to be loaded from disk. // To display the bitmap simply use Draw or Stretch. // // eg. // // CDIBSectionLite dibsection; // dibsection.Load(_T("image.bmp")); // dibsection.Draw(pDC, CPoint(0,0)); // pDC is of type CDC* // // CDIBSectionLite dibsection; // dibsection.SetBitmap(IDB_BITMAP); // dibsection.Draw(pDC, CPoint(0,0)); // pDC is of type CDC* // // The CDIBSectionLite API includes many methods to extract information about the // image, as well as palette options for getting and setting the current palette. // // Author: Chris Maunder (cmaunder@dundas.com) // Date : 12 April 1999 //#include <afx.h> #include <afxctl.h> #include <afxwin.h> #include <vfw.h> #pragma comment(lib, "vfw32") ///////////////////////////////////////////////////////////////////////////// // defines #define DS_BITMAP_FILEMARKER ((WORD) ('M' << 8) | 'B') // is always "BM" = 0x4D42 #define BMGRADIENT_DIRECTION_HORZ 0 #define BMGRADIENT_DIRECTION_VERT 1 ///////////////////////////////////////////////////////////////////////////// // BITMAPINFO wrapper struct DIBINFO : public BITMAPINFO { RGBQUAD arColors[255]; // Color table info - adds an extra 255 entries to palette operator LPBITMAPINFO() { return (LPBITMAPINFO) this; } operator LPBITMAPINFOHEADER() { return &bmiHeader; } RGBQUAD* ColorTable() { return bmiColors; } }; ///////////////////////////////////////////////////////////////////////////// // LOGPALETTE wrapper struct PALETTEINFO : public LOGPALETTE { PALETTEENTRY arPalEntries[255]; // Palette entries PALETTEINFO() { palVersion = (WORD) 0x300; } operator LPLOGPALETTE() { return (LPLOGPALETTE) this; } operator LPPALETTEENTRY() { return (LPPALETTEENTRY) (palPalEntry); } }; ///////////////////////////////////////////////////////////////////////////// // CDIBSectionLite object class CDIBSectionLite : public CObject { // Construction public: CDIBSectionLite(); virtual ~CDIBSectionLite(); void DeleteObject(); // static helpers public: static int BytesPerLine(int nWidth, int nBitsPerPixel); static int NumColorEntries(int nBitsPerPixel); static PALETTEENTRY ms_StdColours[]; static BOOL UsesPalette(CDC* pDC) { return (pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE); } static BOOL CreateHalftonePalette(CPalette& palette, int nNumColours); // Attributes public: HBITMAP GetSafeHandle() const { return (this)? m_hBitmap : NULL; } CSize GetSize() const { return CSize(GetWidth(), GetHeight()); } int GetHeight() const { return m_DIBinfo.bmiHeader.biHeight; } int GetWidth() const { return m_DIBinfo.bmiHeader.biWidth; } int GetPlanes() const { return m_DIBinfo.bmiHeader.biPlanes; } int GetBitCount() const { return m_DIBinfo.bmiHeader.biBitCount; } LPVOID GetDIBits() { return m_ppvBits; } LPBITMAPINFO GetBitmapInfo() { return (BITMAPINFO*) m_DIBinfo; } DWORD GetImageSize() const { return m_DIBinfo.bmiHeader.biSizeImage; } LPBITMAPINFOHEADER GetBitmapInfoHeader() { return (BITMAPINFOHEADER*) m_DIBinfo; } void CreateGradientBmp (COLORREF clrBack, COLORREF clrStart, COLORREF clrEnd, int iWidth, int iHeight, int iDirection); void Create32BitFromPicture (CPictureHolder* pPicture, int iWidth, int iHeight); COLORREF FixColorRef (COLORREF clr); BOOL SetBitmap(UINT nIDResource); BOOL SetBitmap(LPCTSTR lpszResourceName); BOOL SetBitmap(HBITMAP hBitmap, CPalette* pPalette = NULL); BOOL SetBitmap(LPBITMAPINFO lpBitmapInfo, LPVOID lpBits = NULL); CPalette *GetPalette() { return &m_Palette; } BOOL SetPalette(CPalette* pPalette); BOOL SetLogPalette(LOGPALETTE* pLogPalette); BOOL SetDither(BOOL bDither); BOOL GetDither(); // Operations public: BOOL Load(LPCTSTR lpszFileName); BOOL Save(LPCTSTR lpszFileName); BOOL Draw(CDC* pDC, CPoint ptDest, BOOL bForceBackground = FALSE); BOOL Stretch(CDC* pDC, CPoint ptDest, CSize size, BOOL bForceBackground = FALSE); // Overrideables // Implementation public: #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Implementation protected: void _ShowLastError(); BOOL CreatePalette(); BOOL FillDIBColorTable(UINT nNumColours, RGBQUAD *pRGB); protected: HBITMAP m_hBitmap; // Handle to DIBSECTION DIBINFO m_DIBinfo; // Bitmap header & color table info void *m_ppvBits; // Pointer to bitmap bits UINT m_iColorDataType; // color data type (palette or RGB values) UINT m_iColorTableSize; // Size of color table CPalette m_Palette; // Color palette BOOL m_bDither; // Use DrawDib routines for dithering? HDRAWDIB m_hDrawDib; // handle to a DrawDib DC private: HBITMAP m_hOldBitmap; // Storage for previous bitmap in Memory DC }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CDIBSECTIONLITE_H__35D9F3D4_B960_11D2_A981_2C4476000000__INCLUDED_)
34.98995
98
0.603906
[ "object" ]
ca0f1fc2476c30993d39061f71225e8517de5377
10,282
h
C
src/z3solver.h
mikhailramalho/camada
e63d1c0bb318049741f67903867d44980479bf61
[ "Apache-2.0" ]
2
2021-01-29T12:11:43.000Z
2021-05-18T16:17:19.000Z
src/z3solver.h
mikhailramalho/camada
e63d1c0bb318049741f67903867d44980479bf61
[ "Apache-2.0" ]
19
2021-05-09T12:41:02.000Z
2021-06-08T07:19:16.000Z
src/z3solver.h
mikhailramalho/camada
e63d1c0bb318049741f67903867d44980479bf61
[ "Apache-2.0" ]
1
2020-06-08T15:47:55.000Z
2020-06-08T15:47:55.000Z
/************************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * **************************************************************************/ #ifndef Z3SOLVER_H_ #define Z3SOLVER_H_ #include "camadaimpl.h" #include <z3++.h> namespace camada { using Z3ContextRef = std::shared_ptr<z3::context>; /// Wrapper for Z3 Sort class Z3Sort : public SolverSort<Z3ContextRef, z3::sort> { public: using SolverSort<Z3ContextRef, z3::sort>::SolverSort; virtual ~Z3Sort() override = default; unsigned getWidthFromSolver() const override; void dump() const override; }; // end class Z3Sort class Z3Expr : public SolverExpr<Z3ContextRef, z3::expr> { public: using SolverExpr<Z3ContextRef, z3::expr>::SolverExpr; virtual ~Z3Expr() override = default; /// Comparison of Expr equality, not model equivalence. bool equal_to(SMTExpr const &Other) const override; void dump() const override; }; // end class Z3Expr class Z3Solver : public SMTSolverImpl { public: Z3ContextRef Context; z3::solver Solver; explicit Z3Solver(); explicit Z3Solver(Z3ContextRef C, const z3::solver &S); ~Z3Solver() override = default; void addConstraintImpl(const SMTExprRef &Exp) override; SMTExprRef newExprRefImpl(const SMTExpr &Exp) const override; SMTSortRef mkBoolSortImpl() override; SMTSortRef mkBVSortImpl(unsigned BitWidth) override; SMTSortRef mkRMSortImpl() override; SMTSortRef mkFPSortImpl(const unsigned ExpWidth, const unsigned SigWidth) override; SMTSortRef mkBVFPSortImpl(const unsigned ExpWidth, const unsigned SigWidth) override; SMTSortRef mkBVRMSortImpl() override; SMTSortRef mkArraySortImpl(const SMTSortRef &IndexSort, const SMTSortRef &ElemSort) override; SMTExprRef mkBVNegImpl(const SMTExprRef &Exp) override; SMTExprRef mkBVNotImpl(const SMTExprRef &Exp) override; SMTExprRef mkNotImpl(const SMTExprRef &Exp) override; SMTExprRef mkBVAddImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSubImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVMulImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSRemImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVURemImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSDivImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVUDivImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVShlImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVAshrImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVLshrImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVXorImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVOrImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVAndImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVXnorImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVNorImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVNandImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVUltImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSltImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVUgtImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSgtImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVUleImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSleImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVUgeImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVSgeImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkImpliesImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkAndImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkOrImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkXorImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkEqualImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkIteImpl(const SMTExprRef &Cond, const SMTExprRef &T, const SMTExprRef &F) override; SMTExprRef mkBVSignExtImpl(unsigned i, const SMTExprRef &Exp) override; SMTExprRef mkBVZeroExtImpl(unsigned i, const SMTExprRef &Exp) override; SMTExprRef mkBVExtractImpl(unsigned High, unsigned Low, const SMTExprRef &Exp) override; SMTExprRef mkBVConcatImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkBVRedOrImpl(const SMTExprRef &Exp) override; SMTExprRef mkBVRedAndImpl(const SMTExprRef &Exp) override; SMTExprRef mkArraySelectImpl(const SMTExprRef &Array, const SMTExprRef &Index) override; SMTExprRef mkArrayStoreImpl(const SMTExprRef &Array, const SMTExprRef &Index, const SMTExprRef &Element) override; SMTExprRef mkFPAbsImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPNegImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPIsInfiniteImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPIsNaNImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPIsDenormalImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPIsNormalImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPIsZeroImpl(const SMTExprRef &Exp) override; SMTExprRef mkFPMulImpl(const SMTExprRef &LHS, const SMTExprRef &RHS, const SMTExprRef &R) override; SMTExprRef mkFPDivImpl(const SMTExprRef &LHS, const SMTExprRef &RHS, const SMTExprRef &R) override; SMTExprRef mkFPRemImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPAddImpl(const SMTExprRef &LHS, const SMTExprRef &RHS, const SMTExprRef &R) override; SMTExprRef mkFPSubImpl(const SMTExprRef &LHS, const SMTExprRef &RHS, const SMTExprRef &R) override; SMTExprRef mkFPSqrtImpl(const SMTExprRef &Exp, const SMTExprRef &R) override; SMTExprRef mkFPFMAImpl(const SMTExprRef &X, const SMTExprRef &Y, const SMTExprRef &Z, const SMTExprRef &R) override; SMTExprRef mkFPLtImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPGtImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPLeImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPGeImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPEqualImpl(const SMTExprRef &LHS, const SMTExprRef &RHS) override; SMTExprRef mkFPtoFPImpl(const SMTExprRef &From, const SMTSortRef &To, const SMTExprRef &R) override; SMTExprRef mkSBVtoFPImpl(const SMTExprRef &From, const SMTSortRef &To, const SMTExprRef &R) override; SMTExprRef mkUBVtoFPImpl(const SMTExprRef &From, const SMTSortRef &To, const SMTExprRef &R) override; SMTExprRef mkFPtoSBVImpl(const SMTExprRef &From, unsigned ToWidth) override; SMTExprRef mkFPtoUBVImpl(const SMTExprRef &From, unsigned ToWidth) override; SMTExprRef mkFPtoIntegralImpl(const SMTExprRef &From, const SMTExprRef &R) override; bool getBoolImpl(const SMTExprRef &Exp) override; std::string getBVInBinImpl(const SMTExprRef &Exp) override; std::string getFPInBinImpl(const SMTExprRef &Exp) override; SMTExprRef getArrayElementImpl(const SMTExprRef &Array, const SMTExprRef &Index) override; SMTExprRef mkBoolImpl(const bool b) override; SMTExprRef mkBVFromDecImpl(const int64_t Int, const SMTSortRef &Sort) override; SMTExprRef mkBVFromBinImpl(const std::string &Int, const SMTSortRef &Sort) override; SMTExprRef mkSymbolImpl(const std::string &Name, const SMTSortRef &Sort) override; SMTExprRef mkFPFromBinImpl(const std::string &FP, unsigned EWidth) override; SMTExprRef mkRMImpl(const RM &R) override; SMTExprRef mkNaNImpl(const bool Sgn, const unsigned ExpWidth, const unsigned SigWidth) override; SMTExprRef mkInfImpl(const bool Sgn, const unsigned ExpWidth, const unsigned SigWidth) override; SMTExprRef mkBVToIEEEFPImpl(const SMTExprRef &Exp, const SMTSortRef &To) override; SMTExprRef mkIEEEFPToBVImpl(const SMTExprRef &Exp) override; SMTExprRef mkArrayConstImpl(const SMTSortRef &IndexSort, const SMTExprRef &InitValue) override; checkResult checkImpl() override; void resetImpl() override; std::string getSolverNameAndVersion() const override; void dumpImpl() override; void dumpModelImpl() override; }; // end class Z3Solver } // namespace camada #endif
34.972789
80
0.699864
[ "model" ]
ca109c75ff1bfed46f7c785025e3b6316e184c78
12,093
h
C
sdk/js/include/nsIInlineSpellChecker.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/js/include/nsIInlineSpellChecker.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/js/include/nsIInlineSpellChecker.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM d:/firefox-5.0.1/mozilla-release/editor/txtsvc/public/nsIInlineSpellChecker.idl */ #ifndef __gen_nsIInlineSpellChecker_h__ #define __gen_nsIInlineSpellChecker_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsISelection; /* forward declaration */ class nsIEditor; /* forward declaration */ class nsIEditorSpellCheck; /* forward declaration */ /* starting interface: nsIInlineSpellChecker */ #define NS_IINLINESPELLCHECKER_IID_STR "07be036a-2355-4a92-b150-5c9b7e9fdf2f" #define NS_IINLINESPELLCHECKER_IID \ {0x07be036a, 0x2355, 0x4a92, \ { 0xb1, 0x50, 0x5c, 0x9b, 0x7e, 0x9f, 0xdf, 0x2f }} class NS_NO_VTABLE NS_SCRIPTABLE nsIInlineSpellChecker : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IINLINESPELLCHECKER_IID) /* readonly attribute nsIEditorSpellCheck spellChecker; */ NS_SCRIPTABLE NS_IMETHOD GetSpellChecker(nsIEditorSpellCheck **aSpellChecker) = 0; /* [noscript] void init (in nsIEditor aEditor); */ NS_IMETHOD Init(nsIEditor *aEditor) = 0; /* [noscript] void cleanup (in boolean aDestroyingFrames); */ NS_IMETHOD Cleanup(PRBool aDestroyingFrames) = 0; /* attribute boolean enableRealTimeSpell; */ NS_SCRIPTABLE NS_IMETHOD GetEnableRealTimeSpell(PRBool *aEnableRealTimeSpell) = 0; NS_SCRIPTABLE NS_IMETHOD SetEnableRealTimeSpell(PRBool aEnableRealTimeSpell) = 0; /* void spellCheckAfterEditorChange (in long aAction, in nsISelection aSelection, in nsIDOMNode aPreviousSelectedNode, in long aPreviousSelectedOffset, in nsIDOMNode aStartNode, in long aStartOffset, in nsIDOMNode aEndNode, in long aEndOffset); */ NS_SCRIPTABLE NS_IMETHOD SpellCheckAfterEditorChange(PRInt32 aAction, nsISelection *aSelection, nsIDOMNode *aPreviousSelectedNode, PRInt32 aPreviousSelectedOffset, nsIDOMNode *aStartNode, PRInt32 aStartOffset, nsIDOMNode *aEndNode, PRInt32 aEndOffset) = 0; /* void spellCheckRange (in nsIDOMRange aSelection); */ NS_SCRIPTABLE NS_IMETHOD SpellCheckRange(nsIDOMRange *aSelection) = 0; /* nsIDOMRange getMisspelledWord (in nsIDOMNode aNode, in long aOffset); */ NS_SCRIPTABLE NS_IMETHOD GetMisspelledWord(nsIDOMNode *aNode, PRInt32 aOffset, nsIDOMRange **_retval NS_OUTPARAM) = 0; /* void replaceWord (in nsIDOMNode aNode, in long aOffset, in AString aNewword); */ NS_SCRIPTABLE NS_IMETHOD ReplaceWord(nsIDOMNode *aNode, PRInt32 aOffset, const nsAString & aNewword) = 0; /* void addWordToDictionary (in AString aWord); */ NS_SCRIPTABLE NS_IMETHOD AddWordToDictionary(const nsAString & aWord) = 0; /* void ignoreWord (in AString aWord); */ NS_SCRIPTABLE NS_IMETHOD IgnoreWord(const nsAString & aWord) = 0; /* void ignoreWords ([array, size_is (aCount)] in wstring aWordsToIgnore, in unsigned long aCount); */ NS_SCRIPTABLE NS_IMETHOD IgnoreWords(const PRUnichar **aWordsToIgnore, PRUint32 aCount) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIInlineSpellChecker, NS_IINLINESPELLCHECKER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIINLINESPELLCHECKER \ NS_SCRIPTABLE NS_IMETHOD GetSpellChecker(nsIEditorSpellCheck **aSpellChecker); \ NS_IMETHOD Init(nsIEditor *aEditor); \ NS_IMETHOD Cleanup(PRBool aDestroyingFrames); \ NS_SCRIPTABLE NS_IMETHOD GetEnableRealTimeSpell(PRBool *aEnableRealTimeSpell); \ NS_SCRIPTABLE NS_IMETHOD SetEnableRealTimeSpell(PRBool aEnableRealTimeSpell); \ NS_SCRIPTABLE NS_IMETHOD SpellCheckAfterEditorChange(PRInt32 aAction, nsISelection *aSelection, nsIDOMNode *aPreviousSelectedNode, PRInt32 aPreviousSelectedOffset, nsIDOMNode *aStartNode, PRInt32 aStartOffset, nsIDOMNode *aEndNode, PRInt32 aEndOffset); \ NS_SCRIPTABLE NS_IMETHOD SpellCheckRange(nsIDOMRange *aSelection); \ NS_SCRIPTABLE NS_IMETHOD GetMisspelledWord(nsIDOMNode *aNode, PRInt32 aOffset, nsIDOMRange **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD ReplaceWord(nsIDOMNode *aNode, PRInt32 aOffset, const nsAString & aNewword); \ NS_SCRIPTABLE NS_IMETHOD AddWordToDictionary(const nsAString & aWord); \ NS_SCRIPTABLE NS_IMETHOD IgnoreWord(const nsAString & aWord); \ NS_SCRIPTABLE NS_IMETHOD IgnoreWords(const PRUnichar **aWordsToIgnore, PRUint32 aCount); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIINLINESPELLCHECKER(_to) \ NS_SCRIPTABLE NS_IMETHOD GetSpellChecker(nsIEditorSpellCheck **aSpellChecker) { return _to GetSpellChecker(aSpellChecker); } \ NS_IMETHOD Init(nsIEditor *aEditor) { return _to Init(aEditor); } \ NS_IMETHOD Cleanup(PRBool aDestroyingFrames) { return _to Cleanup(aDestroyingFrames); } \ NS_SCRIPTABLE NS_IMETHOD GetEnableRealTimeSpell(PRBool *aEnableRealTimeSpell) { return _to GetEnableRealTimeSpell(aEnableRealTimeSpell); } \ NS_SCRIPTABLE NS_IMETHOD SetEnableRealTimeSpell(PRBool aEnableRealTimeSpell) { return _to SetEnableRealTimeSpell(aEnableRealTimeSpell); } \ NS_SCRIPTABLE NS_IMETHOD SpellCheckAfterEditorChange(PRInt32 aAction, nsISelection *aSelection, nsIDOMNode *aPreviousSelectedNode, PRInt32 aPreviousSelectedOffset, nsIDOMNode *aStartNode, PRInt32 aStartOffset, nsIDOMNode *aEndNode, PRInt32 aEndOffset) { return _to SpellCheckAfterEditorChange(aAction, aSelection, aPreviousSelectedNode, aPreviousSelectedOffset, aStartNode, aStartOffset, aEndNode, aEndOffset); } \ NS_SCRIPTABLE NS_IMETHOD SpellCheckRange(nsIDOMRange *aSelection) { return _to SpellCheckRange(aSelection); } \ NS_SCRIPTABLE NS_IMETHOD GetMisspelledWord(nsIDOMNode *aNode, PRInt32 aOffset, nsIDOMRange **_retval NS_OUTPARAM) { return _to GetMisspelledWord(aNode, aOffset, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ReplaceWord(nsIDOMNode *aNode, PRInt32 aOffset, const nsAString & aNewword) { return _to ReplaceWord(aNode, aOffset, aNewword); } \ NS_SCRIPTABLE NS_IMETHOD AddWordToDictionary(const nsAString & aWord) { return _to AddWordToDictionary(aWord); } \ NS_SCRIPTABLE NS_IMETHOD IgnoreWord(const nsAString & aWord) { return _to IgnoreWord(aWord); } \ NS_SCRIPTABLE NS_IMETHOD IgnoreWords(const PRUnichar **aWordsToIgnore, PRUint32 aCount) { return _to IgnoreWords(aWordsToIgnore, aCount); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIINLINESPELLCHECKER(_to) \ NS_SCRIPTABLE NS_IMETHOD GetSpellChecker(nsIEditorSpellCheck **aSpellChecker) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSpellChecker(aSpellChecker); } \ NS_IMETHOD Init(nsIEditor *aEditor) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(aEditor); } \ NS_IMETHOD Cleanup(PRBool aDestroyingFrames) { return !_to ? NS_ERROR_NULL_POINTER : _to->Cleanup(aDestroyingFrames); } \ NS_SCRIPTABLE NS_IMETHOD GetEnableRealTimeSpell(PRBool *aEnableRealTimeSpell) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEnableRealTimeSpell(aEnableRealTimeSpell); } \ NS_SCRIPTABLE NS_IMETHOD SetEnableRealTimeSpell(PRBool aEnableRealTimeSpell) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetEnableRealTimeSpell(aEnableRealTimeSpell); } \ NS_SCRIPTABLE NS_IMETHOD SpellCheckAfterEditorChange(PRInt32 aAction, nsISelection *aSelection, nsIDOMNode *aPreviousSelectedNode, PRInt32 aPreviousSelectedOffset, nsIDOMNode *aStartNode, PRInt32 aStartOffset, nsIDOMNode *aEndNode, PRInt32 aEndOffset) { return !_to ? NS_ERROR_NULL_POINTER : _to->SpellCheckAfterEditorChange(aAction, aSelection, aPreviousSelectedNode, aPreviousSelectedOffset, aStartNode, aStartOffset, aEndNode, aEndOffset); } \ NS_SCRIPTABLE NS_IMETHOD SpellCheckRange(nsIDOMRange *aSelection) { return !_to ? NS_ERROR_NULL_POINTER : _to->SpellCheckRange(aSelection); } \ NS_SCRIPTABLE NS_IMETHOD GetMisspelledWord(nsIDOMNode *aNode, PRInt32 aOffset, nsIDOMRange **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMisspelledWord(aNode, aOffset, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ReplaceWord(nsIDOMNode *aNode, PRInt32 aOffset, const nsAString & aNewword) { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceWord(aNode, aOffset, aNewword); } \ NS_SCRIPTABLE NS_IMETHOD AddWordToDictionary(const nsAString & aWord) { return !_to ? NS_ERROR_NULL_POINTER : _to->AddWordToDictionary(aWord); } \ NS_SCRIPTABLE NS_IMETHOD IgnoreWord(const nsAString & aWord) { return !_to ? NS_ERROR_NULL_POINTER : _to->IgnoreWord(aWord); } \ NS_SCRIPTABLE NS_IMETHOD IgnoreWords(const PRUnichar **aWordsToIgnore, PRUint32 aCount) { return !_to ? NS_ERROR_NULL_POINTER : _to->IgnoreWords(aWordsToIgnore, aCount); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsInlineSpellChecker : public nsIInlineSpellChecker { public: NS_DECL_ISUPPORTS NS_DECL_NSIINLINESPELLCHECKER nsInlineSpellChecker(); private: ~nsInlineSpellChecker(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsInlineSpellChecker, nsIInlineSpellChecker) nsInlineSpellChecker::nsInlineSpellChecker() { /* member initializers and constructor code */ } nsInlineSpellChecker::~nsInlineSpellChecker() { /* destructor code */ } /* readonly attribute nsIEditorSpellCheck spellChecker; */ NS_IMETHODIMP nsInlineSpellChecker::GetSpellChecker(nsIEditorSpellCheck **aSpellChecker) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void init (in nsIEditor aEditor); */ NS_IMETHODIMP nsInlineSpellChecker::Init(nsIEditor *aEditor) { return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] void cleanup (in boolean aDestroyingFrames); */ NS_IMETHODIMP nsInlineSpellChecker::Cleanup(PRBool aDestroyingFrames) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean enableRealTimeSpell; */ NS_IMETHODIMP nsInlineSpellChecker::GetEnableRealTimeSpell(PRBool *aEnableRealTimeSpell) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsInlineSpellChecker::SetEnableRealTimeSpell(PRBool aEnableRealTimeSpell) { return NS_ERROR_NOT_IMPLEMENTED; } /* void spellCheckAfterEditorChange (in long aAction, in nsISelection aSelection, in nsIDOMNode aPreviousSelectedNode, in long aPreviousSelectedOffset, in nsIDOMNode aStartNode, in long aStartOffset, in nsIDOMNode aEndNode, in long aEndOffset); */ NS_IMETHODIMP nsInlineSpellChecker::SpellCheckAfterEditorChange(PRInt32 aAction, nsISelection *aSelection, nsIDOMNode *aPreviousSelectedNode, PRInt32 aPreviousSelectedOffset, nsIDOMNode *aStartNode, PRInt32 aStartOffset, nsIDOMNode *aEndNode, PRInt32 aEndOffset) { return NS_ERROR_NOT_IMPLEMENTED; } /* void spellCheckRange (in nsIDOMRange aSelection); */ NS_IMETHODIMP nsInlineSpellChecker::SpellCheckRange(nsIDOMRange *aSelection) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMRange getMisspelledWord (in nsIDOMNode aNode, in long aOffset); */ NS_IMETHODIMP nsInlineSpellChecker::GetMisspelledWord(nsIDOMNode *aNode, PRInt32 aOffset, nsIDOMRange **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* void replaceWord (in nsIDOMNode aNode, in long aOffset, in AString aNewword); */ NS_IMETHODIMP nsInlineSpellChecker::ReplaceWord(nsIDOMNode *aNode, PRInt32 aOffset, const nsAString & aNewword) { return NS_ERROR_NOT_IMPLEMENTED; } /* void addWordToDictionary (in AString aWord); */ NS_IMETHODIMP nsInlineSpellChecker::AddWordToDictionary(const nsAString & aWord) { return NS_ERROR_NOT_IMPLEMENTED; } /* void ignoreWord (in AString aWord); */ NS_IMETHODIMP nsInlineSpellChecker::IgnoreWord(const nsAString & aWord) { return NS_ERROR_NOT_IMPLEMENTED; } /* void ignoreWords ([array, size_is (aCount)] in wstring aWordsToIgnore, in unsigned long aCount); */ NS_IMETHODIMP nsInlineSpellChecker::IgnoreWords(const PRUnichar **aWordsToIgnore, PRUint32 aCount) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #define MOZ_INLINESPELLCHECKER_CONTRACTID "@mozilla.org/spellchecker-inline;1" #endif /* __gen_nsIInlineSpellChecker_h__ */
52.350649
448
0.804432
[ "object" ]
ca15cc84cdb7890e64a9fa949ea6cebfd2e7d452
800
h
C
c++/PCG/src/online/Brender/cpp/Brenderable.h
sueda/redmax
0a8864e882cbb8afe471314829d591790b915e56
[ "MIT" ]
63
2019-05-09T03:25:37.000Z
2022-01-17T07:05:35.000Z
c++/PCG/src/online/Brender/cpp/Brenderable.h
sueda/redmax
0a8864e882cbb8afe471314829d591790b915e56
[ "MIT" ]
1
2019-05-13T23:17:13.000Z
2019-05-22T10:49:52.000Z
c++/PCG/src/online/Brender/cpp/Brenderable.h
sueda/redmax
0a8864e882cbb8afe471314829d591790b915e56
[ "MIT" ]
8
2019-05-06T02:03:12.000Z
2021-07-07T11:01:27.000Z
/* * @author: Gustavo Lopez 10-21-17 * * @version: 1.0 */ #pragma once #include <string> #include <fstream> #include <vector> #include <memory> #include "BrenderManager.h" class Brenderable { public: enum BranderableType { Truncate, Append, ResetAppend }; Brenderable() {}; virtual ~Brenderable() {}; virtual int getBrenderCount() const { return 1; }; virtual std::vector<std::string> getBrenderNames() const { return std::vector<std::string>(1, ""); }; virtual std::vector<std::string> getBrenderExtensions() const { return std::vector<std::string>(1, ""); }; virtual std::vector<int> getBrenderTypes() const { return std::vector<int>(1, Truncate); }; virtual void exportBrender(std::vector< std::shared_ptr< std::ofstream > > outfiles, int frame, double time) const = 0; private: };
25.806452
120
0.69625
[ "vector" ]
ca16796bd47637a9eff22373e5b3d55dae568021
250,878
h
C
protobuf/src/google/protobuf/map_unittest.pb.h
wissunpower/WeizenbierGame
34f027c43055dfa6b05e62ca0b6c31271af013f3
[ "Unlicense" ]
null
null
null
protobuf/src/google/protobuf/map_unittest.pb.h
wissunpower/WeizenbierGame
34f027c43055dfa6b05e62ca0b6c31271af013f3
[ "Unlicense" ]
null
null
null
protobuf/src/google/protobuf/map_unittest.pb.h
wissunpower/WeizenbierGame
34f027c43055dfa6b05e62ca0b6c31271af013f3
[ "Unlicense" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/map_unittest.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fmap_5funittest_2eproto #define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fmap_5funittest_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3017000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3017003 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/map.h> // IWYU pragma: export #include <google/protobuf/map_entry.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include "google/protobuf/unittest.pb.h" // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fmap_5funittest_2eproto PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[52] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fmap_5funittest_2eproto; namespace protobuf_unittest { class MessageContainingEnumCalledType; struct MessageContainingEnumCalledTypeDefaultTypeInternal; extern MessageContainingEnumCalledTypeDefaultTypeInternal _MessageContainingEnumCalledType_default_instance_; class MessageContainingEnumCalledType_TypeEntry_DoNotUse; struct MessageContainingEnumCalledType_TypeEntry_DoNotUseDefaultTypeInternal; extern MessageContainingEnumCalledType_TypeEntry_DoNotUseDefaultTypeInternal _MessageContainingEnumCalledType_TypeEntry_DoNotUse_default_instance_; class MessageContainingMapCalledEntry; struct MessageContainingMapCalledEntryDefaultTypeInternal; extern MessageContainingMapCalledEntryDefaultTypeInternal _MessageContainingMapCalledEntry_default_instance_; class MessageContainingMapCalledEntry_EntryEntry_DoNotUse; struct MessageContainingMapCalledEntry_EntryEntry_DoNotUseDefaultTypeInternal; extern MessageContainingMapCalledEntry_EntryEntry_DoNotUseDefaultTypeInternal _MessageContainingMapCalledEntry_EntryEntry_DoNotUse_default_instance_; class TestArenaMap; struct TestArenaMapDefaultTypeInternal; extern TestArenaMapDefaultTypeInternal _TestArenaMap_default_instance_; class TestArenaMap_MapBoolBoolEntry_DoNotUse; struct TestArenaMap_MapBoolBoolEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapBoolBoolEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapBoolBoolEntry_DoNotUse_default_instance_; class TestArenaMap_MapFixed32Fixed32Entry_DoNotUse; struct TestArenaMap_MapFixed32Fixed32Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapFixed32Fixed32Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapFixed32Fixed32Entry_DoNotUse_default_instance_; class TestArenaMap_MapFixed64Fixed64Entry_DoNotUse; struct TestArenaMap_MapFixed64Fixed64Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapFixed64Fixed64Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapFixed64Fixed64Entry_DoNotUse_default_instance_; class TestArenaMap_MapInt32BytesEntry_DoNotUse; struct TestArenaMap_MapInt32BytesEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32BytesEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32BytesEntry_DoNotUse_default_instance_; class TestArenaMap_MapInt32DoubleEntry_DoNotUse; struct TestArenaMap_MapInt32DoubleEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32DoubleEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32DoubleEntry_DoNotUse_default_instance_; class TestArenaMap_MapInt32EnumEntry_DoNotUse; struct TestArenaMap_MapInt32EnumEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32EnumEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32EnumEntry_DoNotUse_default_instance_; class TestArenaMap_MapInt32FloatEntry_DoNotUse; struct TestArenaMap_MapInt32FloatEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32FloatEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32FloatEntry_DoNotUse_default_instance_; class TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse; struct TestArenaMap_MapInt32ForeignMessageEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32ForeignMessageEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse_default_instance_; class TestArenaMap_MapInt32Int32Entry_DoNotUse; struct TestArenaMap_MapInt32Int32Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt32Int32Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt32Int32Entry_DoNotUse_default_instance_; class TestArenaMap_MapInt64Int64Entry_DoNotUse; struct TestArenaMap_MapInt64Int64Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapInt64Int64Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapInt64Int64Entry_DoNotUse_default_instance_; class TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse; struct TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse_default_instance_; class TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse; struct TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse_default_instance_; class TestArenaMap_MapSint32Sint32Entry_DoNotUse; struct TestArenaMap_MapSint32Sint32Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapSint32Sint32Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapSint32Sint32Entry_DoNotUse_default_instance_; class TestArenaMap_MapSint64Sint64Entry_DoNotUse; struct TestArenaMap_MapSint64Sint64Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapSint64Sint64Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapSint64Sint64Entry_DoNotUse_default_instance_; class TestArenaMap_MapStringStringEntry_DoNotUse; struct TestArenaMap_MapStringStringEntry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapStringStringEntry_DoNotUseDefaultTypeInternal _TestArenaMap_MapStringStringEntry_DoNotUse_default_instance_; class TestArenaMap_MapUint32Uint32Entry_DoNotUse; struct TestArenaMap_MapUint32Uint32Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapUint32Uint32Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapUint32Uint32Entry_DoNotUse_default_instance_; class TestArenaMap_MapUint64Uint64Entry_DoNotUse; struct TestArenaMap_MapUint64Uint64Entry_DoNotUseDefaultTypeInternal; extern TestArenaMap_MapUint64Uint64Entry_DoNotUseDefaultTypeInternal _TestArenaMap_MapUint64Uint64Entry_DoNotUse_default_instance_; class TestMap; struct TestMapDefaultTypeInternal; extern TestMapDefaultTypeInternal _TestMap_default_instance_; class TestMapSubmessage; struct TestMapSubmessageDefaultTypeInternal; extern TestMapSubmessageDefaultTypeInternal _TestMapSubmessage_default_instance_; class TestMap_MapBoolBoolEntry_DoNotUse; struct TestMap_MapBoolBoolEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapBoolBoolEntry_DoNotUseDefaultTypeInternal _TestMap_MapBoolBoolEntry_DoNotUse_default_instance_; class TestMap_MapFixed32Fixed32Entry_DoNotUse; struct TestMap_MapFixed32Fixed32Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapFixed32Fixed32Entry_DoNotUseDefaultTypeInternal _TestMap_MapFixed32Fixed32Entry_DoNotUse_default_instance_; class TestMap_MapFixed64Fixed64Entry_DoNotUse; struct TestMap_MapFixed64Fixed64Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapFixed64Fixed64Entry_DoNotUseDefaultTypeInternal _TestMap_MapFixed64Fixed64Entry_DoNotUse_default_instance_; class TestMap_MapInt32AllTypesEntry_DoNotUse; struct TestMap_MapInt32AllTypesEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32AllTypesEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32AllTypesEntry_DoNotUse_default_instance_; class TestMap_MapInt32BytesEntry_DoNotUse; struct TestMap_MapInt32BytesEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32BytesEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32BytesEntry_DoNotUse_default_instance_; class TestMap_MapInt32DoubleEntry_DoNotUse; struct TestMap_MapInt32DoubleEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32DoubleEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32DoubleEntry_DoNotUse_default_instance_; class TestMap_MapInt32EnumEntry_DoNotUse; struct TestMap_MapInt32EnumEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32EnumEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32EnumEntry_DoNotUse_default_instance_; class TestMap_MapInt32FloatEntry_DoNotUse; struct TestMap_MapInt32FloatEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32FloatEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32FloatEntry_DoNotUse_default_instance_; class TestMap_MapInt32ForeignMessageEntry_DoNotUse; struct TestMap_MapInt32ForeignMessageEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32ForeignMessageEntry_DoNotUseDefaultTypeInternal _TestMap_MapInt32ForeignMessageEntry_DoNotUse_default_instance_; class TestMap_MapInt32Int32Entry_DoNotUse; struct TestMap_MapInt32Int32Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt32Int32Entry_DoNotUseDefaultTypeInternal _TestMap_MapInt32Int32Entry_DoNotUse_default_instance_; class TestMap_MapInt64Int64Entry_DoNotUse; struct TestMap_MapInt64Int64Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapInt64Int64Entry_DoNotUseDefaultTypeInternal _TestMap_MapInt64Int64Entry_DoNotUse_default_instance_; class TestMap_MapSfixed32Sfixed32Entry_DoNotUse; struct TestMap_MapSfixed32Sfixed32Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapSfixed32Sfixed32Entry_DoNotUseDefaultTypeInternal _TestMap_MapSfixed32Sfixed32Entry_DoNotUse_default_instance_; class TestMap_MapSfixed64Sfixed64Entry_DoNotUse; struct TestMap_MapSfixed64Sfixed64Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapSfixed64Sfixed64Entry_DoNotUseDefaultTypeInternal _TestMap_MapSfixed64Sfixed64Entry_DoNotUse_default_instance_; class TestMap_MapSint32Sint32Entry_DoNotUse; struct TestMap_MapSint32Sint32Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapSint32Sint32Entry_DoNotUseDefaultTypeInternal _TestMap_MapSint32Sint32Entry_DoNotUse_default_instance_; class TestMap_MapSint64Sint64Entry_DoNotUse; struct TestMap_MapSint64Sint64Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapSint64Sint64Entry_DoNotUseDefaultTypeInternal _TestMap_MapSint64Sint64Entry_DoNotUse_default_instance_; class TestMap_MapStringForeignMessageEntry_DoNotUse; struct TestMap_MapStringForeignMessageEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapStringForeignMessageEntry_DoNotUseDefaultTypeInternal _TestMap_MapStringForeignMessageEntry_DoNotUse_default_instance_; class TestMap_MapStringStringEntry_DoNotUse; struct TestMap_MapStringStringEntry_DoNotUseDefaultTypeInternal; extern TestMap_MapStringStringEntry_DoNotUseDefaultTypeInternal _TestMap_MapStringStringEntry_DoNotUse_default_instance_; class TestMap_MapUint32Uint32Entry_DoNotUse; struct TestMap_MapUint32Uint32Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapUint32Uint32Entry_DoNotUseDefaultTypeInternal _TestMap_MapUint32Uint32Entry_DoNotUse_default_instance_; class TestMap_MapUint64Uint64Entry_DoNotUse; struct TestMap_MapUint64Uint64Entry_DoNotUseDefaultTypeInternal; extern TestMap_MapUint64Uint64Entry_DoNotUseDefaultTypeInternal _TestMap_MapUint64Uint64Entry_DoNotUse_default_instance_; class TestMessageMap; struct TestMessageMapDefaultTypeInternal; extern TestMessageMapDefaultTypeInternal _TestMessageMap_default_instance_; class TestMessageMap_MapInt32MessageEntry_DoNotUse; struct TestMessageMap_MapInt32MessageEntry_DoNotUseDefaultTypeInternal; extern TestMessageMap_MapInt32MessageEntry_DoNotUseDefaultTypeInternal _TestMessageMap_MapInt32MessageEntry_DoNotUse_default_instance_; class TestRecursiveMapMessage; struct TestRecursiveMapMessageDefaultTypeInternal; extern TestRecursiveMapMessageDefaultTypeInternal _TestRecursiveMapMessage_default_instance_; class TestRecursiveMapMessage_AEntry_DoNotUse; struct TestRecursiveMapMessage_AEntry_DoNotUseDefaultTypeInternal; extern TestRecursiveMapMessage_AEntry_DoNotUseDefaultTypeInternal _TestRecursiveMapMessage_AEntry_DoNotUse_default_instance_; class TestRequiredMessageMap; struct TestRequiredMessageMapDefaultTypeInternal; extern TestRequiredMessageMapDefaultTypeInternal _TestRequiredMessageMap_default_instance_; class TestRequiredMessageMap_MapFieldEntry_DoNotUse; struct TestRequiredMessageMap_MapFieldEntry_DoNotUseDefaultTypeInternal; extern TestRequiredMessageMap_MapFieldEntry_DoNotUseDefaultTypeInternal _TestRequiredMessageMap_MapFieldEntry_DoNotUse_default_instance_; class TestSameTypeMap; struct TestSameTypeMapDefaultTypeInternal; extern TestSameTypeMapDefaultTypeInternal _TestSameTypeMap_default_instance_; class TestSameTypeMap_Map1Entry_DoNotUse; struct TestSameTypeMap_Map1Entry_DoNotUseDefaultTypeInternal; extern TestSameTypeMap_Map1Entry_DoNotUseDefaultTypeInternal _TestSameTypeMap_Map1Entry_DoNotUse_default_instance_; class TestSameTypeMap_Map2Entry_DoNotUse; struct TestSameTypeMap_Map2Entry_DoNotUseDefaultTypeInternal; extern TestSameTypeMap_Map2Entry_DoNotUseDefaultTypeInternal _TestSameTypeMap_Map2Entry_DoNotUse_default_instance_; } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> ::protobuf_unittest::MessageContainingEnumCalledType* Arena::CreateMaybeMessage<::protobuf_unittest::MessageContainingEnumCalledType>(Arena*); template<> ::protobuf_unittest::MessageContainingEnumCalledType_TypeEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::MessageContainingEnumCalledType_TypeEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::MessageContainingMapCalledEntry* Arena::CreateMaybeMessage<::protobuf_unittest::MessageContainingMapCalledEntry>(Arena*); template<> ::protobuf_unittest::MessageContainingMapCalledEntry_EntryEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::MessageContainingMapCalledEntry_EntryEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapBoolBoolEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapBoolBoolEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapFixed32Fixed32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapFixed32Fixed32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapFixed64Fixed64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapFixed64Fixed64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32BytesEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32BytesEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32DoubleEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32DoubleEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32EnumEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32EnumEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32FloatEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32FloatEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt32Int32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt32Int32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapInt64Int64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapInt64Int64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapSint32Sint32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapSint32Sint32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapSint64Sint64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapSint64Sint64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapStringStringEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapStringStringEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapUint32Uint32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapUint32Uint32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestArenaMap_MapUint64Uint64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestArenaMap_MapUint64Uint64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap>(Arena*); template<> ::protobuf_unittest::TestMapSubmessage* Arena::CreateMaybeMessage<::protobuf_unittest::TestMapSubmessage>(Arena*); template<> ::protobuf_unittest::TestMap_MapBoolBoolEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapBoolBoolEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapFixed32Fixed32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapFixed32Fixed32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapFixed64Fixed64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapFixed64Fixed64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32AllTypesEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32AllTypesEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32BytesEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32BytesEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32DoubleEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32DoubleEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32EnumEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32EnumEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32FloatEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32FloatEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32ForeignMessageEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32ForeignMessageEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt32Int32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt32Int32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapInt64Int64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapInt64Int64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapSfixed32Sfixed32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapSfixed32Sfixed32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapSfixed64Sfixed64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapSfixed64Sfixed64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapSint32Sint32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapSint32Sint32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapSint64Sint64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapSint64Sint64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapStringForeignMessageEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapStringForeignMessageEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapStringStringEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapStringStringEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapUint32Uint32Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapUint32Uint32Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMap_MapUint64Uint64Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMap_MapUint64Uint64Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestMessageMap* Arena::CreateMaybeMessage<::protobuf_unittest::TestMessageMap>(Arena*); template<> ::protobuf_unittest::TestMessageMap_MapInt32MessageEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestMessageMap_MapInt32MessageEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestRecursiveMapMessage* Arena::CreateMaybeMessage<::protobuf_unittest::TestRecursiveMapMessage>(Arena*); template<> ::protobuf_unittest::TestRecursiveMapMessage_AEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestRecursiveMapMessage_AEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestRequiredMessageMap* Arena::CreateMaybeMessage<::protobuf_unittest::TestRequiredMessageMap>(Arena*); template<> ::protobuf_unittest::TestRequiredMessageMap_MapFieldEntry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestRequiredMessageMap_MapFieldEntry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestSameTypeMap* Arena::CreateMaybeMessage<::protobuf_unittest::TestSameTypeMap>(Arena*); template<> ::protobuf_unittest::TestSameTypeMap_Map1Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestSameTypeMap_Map1Entry_DoNotUse>(Arena*); template<> ::protobuf_unittest::TestSameTypeMap_Map2Entry_DoNotUse* Arena::CreateMaybeMessage<::protobuf_unittest::TestSameTypeMap_Map2Entry_DoNotUse>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace protobuf_unittest { enum MessageContainingEnumCalledType_Type : int { MessageContainingEnumCalledType_Type_TYPE_FOO = 0, MessageContainingEnumCalledType_Type_MessageContainingEnumCalledType_Type_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), MessageContainingEnumCalledType_Type_MessageContainingEnumCalledType_Type_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool MessageContainingEnumCalledType_Type_IsValid(int value); constexpr MessageContainingEnumCalledType_Type MessageContainingEnumCalledType_Type_Type_MIN = MessageContainingEnumCalledType_Type_TYPE_FOO; constexpr MessageContainingEnumCalledType_Type MessageContainingEnumCalledType_Type_Type_MAX = MessageContainingEnumCalledType_Type_TYPE_FOO; constexpr int MessageContainingEnumCalledType_Type_Type_ARRAYSIZE = MessageContainingEnumCalledType_Type_Type_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* MessageContainingEnumCalledType_Type_descriptor(); template<typename T> inline const std::string& MessageContainingEnumCalledType_Type_Name(T enum_t_value) { static_assert(::std::is_same<T, MessageContainingEnumCalledType_Type>::value || ::std::is_integral<T>::value, "Incorrect type passed to function MessageContainingEnumCalledType_Type_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( MessageContainingEnumCalledType_Type_descriptor(), enum_t_value); } inline bool MessageContainingEnumCalledType_Type_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, MessageContainingEnumCalledType_Type* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<MessageContainingEnumCalledType_Type>( MessageContainingEnumCalledType_Type_descriptor(), name, value); } enum MapEnum : int { MAP_ENUM_FOO = 0, MAP_ENUM_BAR = 1, MAP_ENUM_BAZ = 2, MapEnum_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::min(), MapEnum_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::PROTOBUF_NAMESPACE_ID::int32>::max() }; bool MapEnum_IsValid(int value); constexpr MapEnum MapEnum_MIN = MAP_ENUM_FOO; constexpr MapEnum MapEnum_MAX = MAP_ENUM_BAZ; constexpr int MapEnum_ARRAYSIZE = MapEnum_MAX + 1; const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* MapEnum_descriptor(); template<typename T> inline const std::string& MapEnum_Name(T enum_t_value) { static_assert(::std::is_same<T, MapEnum>::value || ::std::is_integral<T>::value, "Incorrect type passed to function MapEnum_Name."); return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( MapEnum_descriptor(), enum_t_value); } inline bool MapEnum_Parse( ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, MapEnum* value) { return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<MapEnum>( MapEnum_descriptor(), name, value); } // =================================================================== class TestMap_MapInt32Int32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> SuperType; TestMap_MapInt32Int32Entry_DoNotUse(); explicit constexpr TestMap_MapInt32Int32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32Int32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32Int32Entry_DoNotUse& other); static const TestMap_MapInt32Int32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32Int32Entry_DoNotUse*>(&_TestMap_MapInt32Int32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt64Int64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> SuperType; TestMap_MapInt64Int64Entry_DoNotUse(); explicit constexpr TestMap_MapInt64Int64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt64Int64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt64Int64Entry_DoNotUse& other); static const TestMap_MapInt64Int64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt64Int64Entry_DoNotUse*>(&_TestMap_MapInt64Int64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapUint32Uint32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> SuperType; TestMap_MapUint32Uint32Entry_DoNotUse(); explicit constexpr TestMap_MapUint32Uint32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapUint32Uint32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapUint32Uint32Entry_DoNotUse& other); static const TestMap_MapUint32Uint32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapUint32Uint32Entry_DoNotUse*>(&_TestMap_MapUint32Uint32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapUint64Uint64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> SuperType; TestMap_MapUint64Uint64Entry_DoNotUse(); explicit constexpr TestMap_MapUint64Uint64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapUint64Uint64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapUint64Uint64Entry_DoNotUse& other); static const TestMap_MapUint64Uint64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapUint64Uint64Entry_DoNotUse*>(&_TestMap_MapUint64Uint64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapSint32Sint32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> SuperType; TestMap_MapSint32Sint32Entry_DoNotUse(); explicit constexpr TestMap_MapSint32Sint32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapSint32Sint32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapSint32Sint32Entry_DoNotUse& other); static const TestMap_MapSint32Sint32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapSint32Sint32Entry_DoNotUse*>(&_TestMap_MapSint32Sint32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapSint64Sint64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> SuperType; TestMap_MapSint64Sint64Entry_DoNotUse(); explicit constexpr TestMap_MapSint64Sint64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapSint64Sint64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapSint64Sint64Entry_DoNotUse& other); static const TestMap_MapSint64Sint64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapSint64Sint64Entry_DoNotUse*>(&_TestMap_MapSint64Sint64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapFixed32Fixed32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> SuperType; TestMap_MapFixed32Fixed32Entry_DoNotUse(); explicit constexpr TestMap_MapFixed32Fixed32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapFixed32Fixed32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapFixed32Fixed32Entry_DoNotUse& other); static const TestMap_MapFixed32Fixed32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapFixed32Fixed32Entry_DoNotUse*>(&_TestMap_MapFixed32Fixed32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapFixed64Fixed64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> SuperType; TestMap_MapFixed64Fixed64Entry_DoNotUse(); explicit constexpr TestMap_MapFixed64Fixed64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapFixed64Fixed64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapFixed64Fixed64Entry_DoNotUse& other); static const TestMap_MapFixed64Fixed64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapFixed64Fixed64Entry_DoNotUse*>(&_TestMap_MapFixed64Fixed64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapSfixed32Sfixed32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> SuperType; TestMap_MapSfixed32Sfixed32Entry_DoNotUse(); explicit constexpr TestMap_MapSfixed32Sfixed32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapSfixed32Sfixed32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapSfixed32Sfixed32Entry_DoNotUse& other); static const TestMap_MapSfixed32Sfixed32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapSfixed32Sfixed32Entry_DoNotUse*>(&_TestMap_MapSfixed32Sfixed32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapSfixed64Sfixed64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> SuperType; TestMap_MapSfixed64Sfixed64Entry_DoNotUse(); explicit constexpr TestMap_MapSfixed64Sfixed64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapSfixed64Sfixed64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapSfixed64Sfixed64Entry_DoNotUse& other); static const TestMap_MapSfixed64Sfixed64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapSfixed64Sfixed64Entry_DoNotUse*>(&_TestMap_MapSfixed64Sfixed64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32FloatEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> SuperType; TestMap_MapInt32FloatEntry_DoNotUse(); explicit constexpr TestMap_MapInt32FloatEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32FloatEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32FloatEntry_DoNotUse& other); static const TestMap_MapInt32FloatEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32FloatEntry_DoNotUse*>(&_TestMap_MapInt32FloatEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32DoubleEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> SuperType; TestMap_MapInt32DoubleEntry_DoNotUse(); explicit constexpr TestMap_MapInt32DoubleEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32DoubleEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32DoubleEntry_DoNotUse& other); static const TestMap_MapInt32DoubleEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32DoubleEntry_DoNotUse*>(&_TestMap_MapInt32DoubleEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapBoolBoolEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> SuperType; TestMap_MapBoolBoolEntry_DoNotUse(); explicit constexpr TestMap_MapBoolBoolEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapBoolBoolEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapBoolBoolEntry_DoNotUse& other); static const TestMap_MapBoolBoolEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapBoolBoolEntry_DoNotUse*>(&_TestMap_MapBoolBoolEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapStringStringEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> SuperType; TestMap_MapStringStringEntry_DoNotUse(); explicit constexpr TestMap_MapStringStringEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapStringStringEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapStringStringEntry_DoNotUse& other); static const TestMap_MapStringStringEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapStringStringEntry_DoNotUse*>(&_TestMap_MapStringStringEntry_DoNotUse_default_instance_); } static bool ValidateKey(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestMap.MapStringStringEntry.key"); } static bool ValidateValue(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestMap.MapStringStringEntry.value"); } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32BytesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> SuperType; TestMap_MapInt32BytesEntry_DoNotUse(); explicit constexpr TestMap_MapInt32BytesEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32BytesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32BytesEntry_DoNotUse& other); static const TestMap_MapInt32BytesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32BytesEntry_DoNotUse*>(&_TestMap_MapInt32BytesEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32EnumEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> SuperType; TestMap_MapInt32EnumEntry_DoNotUse(); explicit constexpr TestMap_MapInt32EnumEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32EnumEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32EnumEntry_DoNotUse& other); static const TestMap_MapInt32EnumEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32EnumEntry_DoNotUse*>(&_TestMap_MapInt32EnumEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32ForeignMessageEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestMap_MapInt32ForeignMessageEntry_DoNotUse(); explicit constexpr TestMap_MapInt32ForeignMessageEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32ForeignMessageEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32ForeignMessageEntry_DoNotUse& other); static const TestMap_MapInt32ForeignMessageEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32ForeignMessageEntry_DoNotUse*>(&_TestMap_MapInt32ForeignMessageEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapStringForeignMessageEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapStringForeignMessageEntry_DoNotUse, std::string, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapStringForeignMessageEntry_DoNotUse, std::string, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestMap_MapStringForeignMessageEntry_DoNotUse(); explicit constexpr TestMap_MapStringForeignMessageEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapStringForeignMessageEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapStringForeignMessageEntry_DoNotUse& other); static const TestMap_MapStringForeignMessageEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapStringForeignMessageEntry_DoNotUse*>(&_TestMap_MapStringForeignMessageEntry_DoNotUse_default_instance_); } static bool ValidateKey(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestMap.MapStringForeignMessageEntry.key"); } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap_MapInt32AllTypesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32AllTypesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMap_MapInt32AllTypesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestMap_MapInt32AllTypesEntry_DoNotUse(); explicit constexpr TestMap_MapInt32AllTypesEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMap_MapInt32AllTypesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMap_MapInt32AllTypesEntry_DoNotUse& other); static const TestMap_MapInt32AllTypesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMap_MapInt32AllTypesEntry_DoNotUse*>(&_TestMap_MapInt32AllTypesEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMap final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestMap) */ { public: inline TestMap() : TestMap(nullptr) {} ~TestMap() override; explicit constexpr TestMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestMap(const TestMap& from); TestMap(TestMap&& from) noexcept : TestMap() { *this = ::std::move(from); } inline TestMap& operator=(const TestMap& from) { CopyFrom(from); return *this; } inline TestMap& operator=(TestMap&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestMap& default_instance() { return *internal_default_instance(); } static inline const TestMap* internal_default_instance() { return reinterpret_cast<const TestMap*>( &_TestMap_default_instance_); } static constexpr int kIndexInFileMessages = 19; friend void swap(TestMap& a, TestMap& b) { a.Swap(&b); } inline void Swap(TestMap* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestMap* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestMap* New() const final { return new TestMap(); } TestMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestMap>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestMap& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestMap& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestMap"; } protected: explicit TestMap(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMapInt32Int32FieldNumber = 1, kMapInt64Int64FieldNumber = 2, kMapUint32Uint32FieldNumber = 3, kMapUint64Uint64FieldNumber = 4, kMapSint32Sint32FieldNumber = 5, kMapSint64Sint64FieldNumber = 6, kMapFixed32Fixed32FieldNumber = 7, kMapFixed64Fixed64FieldNumber = 8, kMapSfixed32Sfixed32FieldNumber = 9, kMapSfixed64Sfixed64FieldNumber = 10, kMapInt32FloatFieldNumber = 11, kMapInt32DoubleFieldNumber = 12, kMapBoolBoolFieldNumber = 13, kMapStringStringFieldNumber = 14, kMapInt32BytesFieldNumber = 15, kMapInt32EnumFieldNumber = 16, kMapInt32ForeignMessageFieldNumber = 17, kMapStringForeignMessageFieldNumber = 18, kMapInt32AllTypesFieldNumber = 19, }; // map<int32, int32> map_int32_int32 = 1; int map_int32_int32_size() const; private: int _internal_map_int32_int32_size() const; public: void clear_map_int32_int32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_int32_int32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_int32_int32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_int32_int32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_int32_int32(); // map<int64, int64> map_int64_int64 = 2; int map_int64_int64_size() const; private: int _internal_map_int64_int64_size() const; public: void clear_map_int64_int64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_int64_int64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_int64_int64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_int64_int64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_int64_int64(); // map<uint32, uint32> map_uint32_uint32 = 3; int map_uint32_uint32_size() const; private: int _internal_map_uint32_uint32_size() const; public: void clear_map_uint32_uint32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& _internal_map_uint32_uint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* _internal_mutable_map_uint32_uint32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& map_uint32_uint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* mutable_map_uint32_uint32(); // map<uint64, uint64> map_uint64_uint64 = 4; int map_uint64_uint64_size() const; private: int _internal_map_uint64_uint64_size() const; public: void clear_map_uint64_uint64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& _internal_map_uint64_uint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* _internal_mutable_map_uint64_uint64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& map_uint64_uint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* mutable_map_uint64_uint64(); // map<sint32, sint32> map_sint32_sint32 = 5; int map_sint32_sint32_size() const; private: int _internal_map_sint32_sint32_size() const; public: void clear_map_sint32_sint32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_sint32_sint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_sint32_sint32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_sint32_sint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_sint32_sint32(); // map<sint64, sint64> map_sint64_sint64 = 6; int map_sint64_sint64_size() const; private: int _internal_map_sint64_sint64_size() const; public: void clear_map_sint64_sint64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_sint64_sint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_sint64_sint64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_sint64_sint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_sint64_sint64(); // map<fixed32, fixed32> map_fixed32_fixed32 = 7; int map_fixed32_fixed32_size() const; private: int _internal_map_fixed32_fixed32_size() const; public: void clear_map_fixed32_fixed32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& _internal_map_fixed32_fixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* _internal_mutable_map_fixed32_fixed32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& map_fixed32_fixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* mutable_map_fixed32_fixed32(); // map<fixed64, fixed64> map_fixed64_fixed64 = 8; int map_fixed64_fixed64_size() const; private: int _internal_map_fixed64_fixed64_size() const; public: void clear_map_fixed64_fixed64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& _internal_map_fixed64_fixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* _internal_mutable_map_fixed64_fixed64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& map_fixed64_fixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* mutable_map_fixed64_fixed64(); // map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9; int map_sfixed32_sfixed32_size() const; private: int _internal_map_sfixed32_sfixed32_size() const; public: void clear_map_sfixed32_sfixed32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_sfixed32_sfixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_sfixed32_sfixed32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_sfixed32_sfixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_sfixed32_sfixed32(); // map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10; int map_sfixed64_sfixed64_size() const; private: int _internal_map_sfixed64_sfixed64_size() const; public: void clear_map_sfixed64_sfixed64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_sfixed64_sfixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_sfixed64_sfixed64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_sfixed64_sfixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_sfixed64_sfixed64(); // map<int32, float> map_int32_float = 11; int map_int32_float_size() const; private: int _internal_map_int32_float_size() const; public: void clear_map_int32_float(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& _internal_map_int32_float() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* _internal_mutable_map_int32_float(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& map_int32_float() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* mutable_map_int32_float(); // map<int32, double> map_int32_double = 12; int map_int32_double_size() const; private: int _internal_map_int32_double_size() const; public: void clear_map_int32_double(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& _internal_map_int32_double() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* _internal_mutable_map_int32_double(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& map_int32_double() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* mutable_map_int32_double(); // map<bool, bool> map_bool_bool = 13; int map_bool_bool_size() const; private: int _internal_map_bool_bool_size() const; public: void clear_map_bool_bool(); private: const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& _internal_map_bool_bool() const; ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* _internal_mutable_map_bool_bool(); public: const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& map_bool_bool() const; ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* mutable_map_bool_bool(); // map<string, string> map_string_string = 14; int map_string_string_size() const; private: int _internal_map_string_string_size() const; public: void clear_map_string_string(); private: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& _internal_map_string_string() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* _internal_mutable_map_string_string(); public: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& map_string_string() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* mutable_map_string_string(); // map<int32, bytes> map_int32_bytes = 15; int map_int32_bytes_size() const; private: int _internal_map_int32_bytes_size() const; public: void clear_map_int32_bytes(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& _internal_map_int32_bytes() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* _internal_mutable_map_int32_bytes(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& map_int32_bytes() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* mutable_map_int32_bytes(); // map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16; int map_int32_enum_size() const; private: int _internal_map_int32_enum_size() const; public: void clear_map_int32_enum(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& _internal_map_int32_enum() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* _internal_mutable_map_int32_enum(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& map_int32_enum() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* mutable_map_int32_enum(); // map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17; int map_int32_foreign_message_size() const; private: int _internal_map_int32_foreign_message_size() const; public: void clear_map_int32_foreign_message(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& _internal_map_int32_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* _internal_mutable_map_int32_foreign_message(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& map_int32_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* mutable_map_int32_foreign_message(); // map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18; int map_string_foreign_message_size() const; private: int _internal_map_string_foreign_message_size() const; public: void clear_map_string_foreign_message(); private: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >& _internal_map_string_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >* _internal_mutable_map_string_foreign_message(); public: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >& map_string_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >* mutable_map_string_foreign_message(); // map<int32, .protobuf_unittest.TestAllTypes> map_int32_all_types = 19; int map_int32_all_types_size() const; private: int _internal_map_int32_all_types_size() const; public: void clear_map_int32_all_types(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& _internal_map_int32_all_types() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* _internal_mutable_map_int32_all_types(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& map_int32_all_types() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* mutable_map_int32_all_types(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> map_int32_int32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> map_int64_int64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> map_uint32_uint32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> map_uint64_uint64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> map_sint32_sint32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> map_sint64_sint64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> map_fixed32_fixed32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> map_fixed64_fixed64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> map_sfixed32_sfixed32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> map_sfixed64_sfixed64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> map_int32_float_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> map_int32_double_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> map_bool_bool_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> map_string_string_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> map_int32_bytes_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> map_int32_enum_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_int32_foreign_message_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapStringForeignMessageEntry_DoNotUse, std::string, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_string_foreign_message_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMap_MapInt32AllTypesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_int32_all_types_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestMapSubmessage final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestMapSubmessage) */ { public: inline TestMapSubmessage() : TestMapSubmessage(nullptr) {} ~TestMapSubmessage() override; explicit constexpr TestMapSubmessage(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestMapSubmessage(const TestMapSubmessage& from); TestMapSubmessage(TestMapSubmessage&& from) noexcept : TestMapSubmessage() { *this = ::std::move(from); } inline TestMapSubmessage& operator=(const TestMapSubmessage& from) { CopyFrom(from); return *this; } inline TestMapSubmessage& operator=(TestMapSubmessage&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestMapSubmessage& default_instance() { return *internal_default_instance(); } static inline const TestMapSubmessage* internal_default_instance() { return reinterpret_cast<const TestMapSubmessage*>( &_TestMapSubmessage_default_instance_); } static constexpr int kIndexInFileMessages = 20; friend void swap(TestMapSubmessage& a, TestMapSubmessage& b) { a.Swap(&b); } inline void Swap(TestMapSubmessage* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestMapSubmessage* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestMapSubmessage* New() const final { return new TestMapSubmessage(); } TestMapSubmessage* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestMapSubmessage>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestMapSubmessage& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestMapSubmessage& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestMapSubmessage* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestMapSubmessage"; } protected: explicit TestMapSubmessage(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kTestMapFieldNumber = 1, }; // .protobuf_unittest.TestMap test_map = 1; bool has_test_map() const; private: bool _internal_has_test_map() const; public: void clear_test_map(); const ::protobuf_unittest::TestMap& test_map() const; PROTOBUF_MUST_USE_RESULT ::protobuf_unittest::TestMap* release_test_map(); ::protobuf_unittest::TestMap* mutable_test_map(); void set_allocated_test_map(::protobuf_unittest::TestMap* test_map); private: const ::protobuf_unittest::TestMap& _internal_test_map() const; ::protobuf_unittest::TestMap* _internal_mutable_test_map(); public: void unsafe_arena_set_allocated_test_map( ::protobuf_unittest::TestMap* test_map); ::protobuf_unittest::TestMap* unsafe_arena_release_test_map(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestMapSubmessage) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::protobuf_unittest::TestMap* test_map_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestMessageMap_MapInt32MessageEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMessageMap_MapInt32MessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestMessageMap_MapInt32MessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestMessageMap_MapInt32MessageEntry_DoNotUse(); explicit constexpr TestMessageMap_MapInt32MessageEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestMessageMap_MapInt32MessageEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestMessageMap_MapInt32MessageEntry_DoNotUse& other); static const TestMessageMap_MapInt32MessageEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestMessageMap_MapInt32MessageEntry_DoNotUse*>(&_TestMessageMap_MapInt32MessageEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestMessageMap final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestMessageMap) */ { public: inline TestMessageMap() : TestMessageMap(nullptr) {} ~TestMessageMap() override; explicit constexpr TestMessageMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestMessageMap(const TestMessageMap& from); TestMessageMap(TestMessageMap&& from) noexcept : TestMessageMap() { *this = ::std::move(from); } inline TestMessageMap& operator=(const TestMessageMap& from) { CopyFrom(from); return *this; } inline TestMessageMap& operator=(TestMessageMap&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestMessageMap& default_instance() { return *internal_default_instance(); } static inline const TestMessageMap* internal_default_instance() { return reinterpret_cast<const TestMessageMap*>( &_TestMessageMap_default_instance_); } static constexpr int kIndexInFileMessages = 22; friend void swap(TestMessageMap& a, TestMessageMap& b) { a.Swap(&b); } inline void Swap(TestMessageMap* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestMessageMap* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestMessageMap* New() const final { return new TestMessageMap(); } TestMessageMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestMessageMap>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestMessageMap& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestMessageMap& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestMessageMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestMessageMap"; } protected: explicit TestMessageMap(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMapInt32MessageFieldNumber = 1, }; // map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1; int map_int32_message_size() const; private: int _internal_map_int32_message_size() const; public: void clear_map_int32_message(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& _internal_map_int32_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* _internal_mutable_map_int32_message(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& map_int32_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* mutable_map_int32_message(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestMessageMap_MapInt32MessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_int32_message_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestSameTypeMap_Map1Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestSameTypeMap_Map1Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestSameTypeMap_Map1Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> SuperType; TestSameTypeMap_Map1Entry_DoNotUse(); explicit constexpr TestSameTypeMap_Map1Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestSameTypeMap_Map1Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestSameTypeMap_Map1Entry_DoNotUse& other); static const TestSameTypeMap_Map1Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestSameTypeMap_Map1Entry_DoNotUse*>(&_TestSameTypeMap_Map1Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestSameTypeMap_Map2Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestSameTypeMap_Map2Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestSameTypeMap_Map2Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> SuperType; TestSameTypeMap_Map2Entry_DoNotUse(); explicit constexpr TestSameTypeMap_Map2Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestSameTypeMap_Map2Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestSameTypeMap_Map2Entry_DoNotUse& other); static const TestSameTypeMap_Map2Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestSameTypeMap_Map2Entry_DoNotUse*>(&_TestSameTypeMap_Map2Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestSameTypeMap final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestSameTypeMap) */ { public: inline TestSameTypeMap() : TestSameTypeMap(nullptr) {} ~TestSameTypeMap() override; explicit constexpr TestSameTypeMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestSameTypeMap(const TestSameTypeMap& from); TestSameTypeMap(TestSameTypeMap&& from) noexcept : TestSameTypeMap() { *this = ::std::move(from); } inline TestSameTypeMap& operator=(const TestSameTypeMap& from) { CopyFrom(from); return *this; } inline TestSameTypeMap& operator=(TestSameTypeMap&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestSameTypeMap& default_instance() { return *internal_default_instance(); } static inline const TestSameTypeMap* internal_default_instance() { return reinterpret_cast<const TestSameTypeMap*>( &_TestSameTypeMap_default_instance_); } static constexpr int kIndexInFileMessages = 25; friend void swap(TestSameTypeMap& a, TestSameTypeMap& b) { a.Swap(&b); } inline void Swap(TestSameTypeMap* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestSameTypeMap* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestSameTypeMap* New() const final { return new TestSameTypeMap(); } TestSameTypeMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestSameTypeMap>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestSameTypeMap& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestSameTypeMap& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestSameTypeMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestSameTypeMap"; } protected: explicit TestSameTypeMap(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMap1FieldNumber = 1, kMap2FieldNumber = 2, }; // map<int32, int32> map1 = 1; int map1_size() const; private: int _internal_map1_size() const; public: void clear_map1(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map1() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map1(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map1() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map1(); // map<int32, int32> map2 = 2; int map2_size() const; private: int _internal_map2_size() const; public: void clear_map2(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map2() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map2(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map2() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map2(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestSameTypeMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestSameTypeMap_Map1Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> map1_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestSameTypeMap_Map2Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> map2_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestRequiredMessageMap_MapFieldEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestRequiredMessageMap_MapFieldEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestRequiredMessageMap_MapFieldEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestRequiredMessageMap_MapFieldEntry_DoNotUse(); explicit constexpr TestRequiredMessageMap_MapFieldEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestRequiredMessageMap_MapFieldEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestRequiredMessageMap_MapFieldEntry_DoNotUse& other); static const TestRequiredMessageMap_MapFieldEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestRequiredMessageMap_MapFieldEntry_DoNotUse*>(&_TestRequiredMessageMap_MapFieldEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestRequiredMessageMap final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestRequiredMessageMap) */ { public: inline TestRequiredMessageMap() : TestRequiredMessageMap(nullptr) {} ~TestRequiredMessageMap() override; explicit constexpr TestRequiredMessageMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestRequiredMessageMap(const TestRequiredMessageMap& from); TestRequiredMessageMap(TestRequiredMessageMap&& from) noexcept : TestRequiredMessageMap() { *this = ::std::move(from); } inline TestRequiredMessageMap& operator=(const TestRequiredMessageMap& from) { CopyFrom(from); return *this; } inline TestRequiredMessageMap& operator=(TestRequiredMessageMap&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestRequiredMessageMap& default_instance() { return *internal_default_instance(); } static inline const TestRequiredMessageMap* internal_default_instance() { return reinterpret_cast<const TestRequiredMessageMap*>( &_TestRequiredMessageMap_default_instance_); } static constexpr int kIndexInFileMessages = 27; friend void swap(TestRequiredMessageMap& a, TestRequiredMessageMap& b) { a.Swap(&b); } inline void Swap(TestRequiredMessageMap* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestRequiredMessageMap* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestRequiredMessageMap* New() const final { return new TestRequiredMessageMap(); } TestRequiredMessageMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestRequiredMessageMap>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestRequiredMessageMap& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestRequiredMessageMap& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestRequiredMessageMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestRequiredMessageMap"; } protected: explicit TestRequiredMessageMap(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMapFieldFieldNumber = 1, }; // map<int32, .protobuf_unittest.TestRequired> map_field = 1; int map_field_size() const; private: int _internal_map_field_size() const; public: void clear_map_field(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >& _internal_map_field() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >* _internal_mutable_map_field(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >& map_field() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >* mutable_map_field(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestRequiredMessageMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestRequiredMessageMap_MapFieldEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_field_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32Int32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> SuperType; TestArenaMap_MapInt32Int32Entry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32Int32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32Int32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32Int32Entry_DoNotUse& other); static const TestArenaMap_MapInt32Int32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32Int32Entry_DoNotUse*>(&_TestArenaMap_MapInt32Int32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt64Int64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> SuperType; TestArenaMap_MapInt64Int64Entry_DoNotUse(); explicit constexpr TestArenaMap_MapInt64Int64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt64Int64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt64Int64Entry_DoNotUse& other); static const TestArenaMap_MapInt64Int64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt64Int64Entry_DoNotUse*>(&_TestArenaMap_MapInt64Int64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapUint32Uint32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> SuperType; TestArenaMap_MapUint32Uint32Entry_DoNotUse(); explicit constexpr TestArenaMap_MapUint32Uint32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapUint32Uint32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapUint32Uint32Entry_DoNotUse& other); static const TestArenaMap_MapUint32Uint32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapUint32Uint32Entry_DoNotUse*>(&_TestArenaMap_MapUint32Uint32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapUint64Uint64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> SuperType; TestArenaMap_MapUint64Uint64Entry_DoNotUse(); explicit constexpr TestArenaMap_MapUint64Uint64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapUint64Uint64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapUint64Uint64Entry_DoNotUse& other); static const TestArenaMap_MapUint64Uint64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapUint64Uint64Entry_DoNotUse*>(&_TestArenaMap_MapUint64Uint64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapSint32Sint32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> SuperType; TestArenaMap_MapSint32Sint32Entry_DoNotUse(); explicit constexpr TestArenaMap_MapSint32Sint32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapSint32Sint32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapSint32Sint32Entry_DoNotUse& other); static const TestArenaMap_MapSint32Sint32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapSint32Sint32Entry_DoNotUse*>(&_TestArenaMap_MapSint32Sint32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapSint64Sint64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> SuperType; TestArenaMap_MapSint64Sint64Entry_DoNotUse(); explicit constexpr TestArenaMap_MapSint64Sint64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapSint64Sint64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapSint64Sint64Entry_DoNotUse& other); static const TestArenaMap_MapSint64Sint64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapSint64Sint64Entry_DoNotUse*>(&_TestArenaMap_MapSint64Sint64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapFixed32Fixed32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> SuperType; TestArenaMap_MapFixed32Fixed32Entry_DoNotUse(); explicit constexpr TestArenaMap_MapFixed32Fixed32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapFixed32Fixed32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapFixed32Fixed32Entry_DoNotUse& other); static const TestArenaMap_MapFixed32Fixed32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapFixed32Fixed32Entry_DoNotUse*>(&_TestArenaMap_MapFixed32Fixed32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapFixed64Fixed64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> SuperType; TestArenaMap_MapFixed64Fixed64Entry_DoNotUse(); explicit constexpr TestArenaMap_MapFixed64Fixed64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapFixed64Fixed64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapFixed64Fixed64Entry_DoNotUse& other); static const TestArenaMap_MapFixed64Fixed64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapFixed64Fixed64Entry_DoNotUse*>(&_TestArenaMap_MapFixed64Fixed64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> SuperType; TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse(); explicit constexpr TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse& other); static const TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse*>(&_TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> SuperType; TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse(); explicit constexpr TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse& other); static const TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse*>(&_TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32FloatEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> SuperType; TestArenaMap_MapInt32FloatEntry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32FloatEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32FloatEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32FloatEntry_DoNotUse& other); static const TestArenaMap_MapInt32FloatEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32FloatEntry_DoNotUse*>(&_TestArenaMap_MapInt32FloatEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32DoubleEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> SuperType; TestArenaMap_MapInt32DoubleEntry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32DoubleEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32DoubleEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32DoubleEntry_DoNotUse& other); static const TestArenaMap_MapInt32DoubleEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32DoubleEntry_DoNotUse*>(&_TestArenaMap_MapInt32DoubleEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapBoolBoolEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> SuperType; TestArenaMap_MapBoolBoolEntry_DoNotUse(); explicit constexpr TestArenaMap_MapBoolBoolEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapBoolBoolEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapBoolBoolEntry_DoNotUse& other); static const TestArenaMap_MapBoolBoolEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapBoolBoolEntry_DoNotUse*>(&_TestArenaMap_MapBoolBoolEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapStringStringEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> SuperType; TestArenaMap_MapStringStringEntry_DoNotUse(); explicit constexpr TestArenaMap_MapStringStringEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapStringStringEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapStringStringEntry_DoNotUse& other); static const TestArenaMap_MapStringStringEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapStringStringEntry_DoNotUse*>(&_TestArenaMap_MapStringStringEntry_DoNotUse_default_instance_); } static bool ValidateKey(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestArenaMap.MapStringStringEntry.key"); } static bool ValidateValue(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestArenaMap.MapStringStringEntry.value"); } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32BytesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> SuperType; TestArenaMap_MapInt32BytesEntry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32BytesEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32BytesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32BytesEntry_DoNotUse& other); static const TestArenaMap_MapInt32BytesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32BytesEntry_DoNotUse*>(&_TestArenaMap_MapInt32BytesEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32EnumEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> SuperType; TestArenaMap_MapInt32EnumEntry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32EnumEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32EnumEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32EnumEntry_DoNotUse& other); static const TestArenaMap_MapInt32EnumEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32EnumEntry_DoNotUse*>(&_TestArenaMap_MapInt32EnumEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse(); explicit constexpr TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse& other); static const TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse*>(&_TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestArenaMap final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestArenaMap) */ { public: inline TestArenaMap() : TestArenaMap(nullptr) {} ~TestArenaMap() override; explicit constexpr TestArenaMap(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestArenaMap(const TestArenaMap& from); TestArenaMap(TestArenaMap&& from) noexcept : TestArenaMap() { *this = ::std::move(from); } inline TestArenaMap& operator=(const TestArenaMap& from) { CopyFrom(from); return *this; } inline TestArenaMap& operator=(TestArenaMap&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestArenaMap& default_instance() { return *internal_default_instance(); } static inline const TestArenaMap* internal_default_instance() { return reinterpret_cast<const TestArenaMap*>( &_TestArenaMap_default_instance_); } static constexpr int kIndexInFileMessages = 45; friend void swap(TestArenaMap& a, TestArenaMap& b) { a.Swap(&b); } inline void Swap(TestArenaMap* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestArenaMap* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestArenaMap* New() const final { return new TestArenaMap(); } TestArenaMap* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestArenaMap>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestArenaMap& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestArenaMap& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestArenaMap* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestArenaMap"; } protected: explicit TestArenaMap(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kMapInt32Int32FieldNumber = 1, kMapInt64Int64FieldNumber = 2, kMapUint32Uint32FieldNumber = 3, kMapUint64Uint64FieldNumber = 4, kMapSint32Sint32FieldNumber = 5, kMapSint64Sint64FieldNumber = 6, kMapFixed32Fixed32FieldNumber = 7, kMapFixed64Fixed64FieldNumber = 8, kMapSfixed32Sfixed32FieldNumber = 9, kMapSfixed64Sfixed64FieldNumber = 10, kMapInt32FloatFieldNumber = 11, kMapInt32DoubleFieldNumber = 12, kMapBoolBoolFieldNumber = 13, kMapStringStringFieldNumber = 14, kMapInt32BytesFieldNumber = 15, kMapInt32EnumFieldNumber = 16, kMapInt32ForeignMessageFieldNumber = 17, }; // map<int32, int32> map_int32_int32 = 1; int map_int32_int32_size() const; private: int _internal_map_int32_int32_size() const; public: void clear_map_int32_int32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_int32_int32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_int32_int32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_int32_int32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_int32_int32(); // map<int64, int64> map_int64_int64 = 2; int map_int64_int64_size() const; private: int _internal_map_int64_int64_size() const; public: void clear_map_int64_int64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_int64_int64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_int64_int64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_int64_int64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_int64_int64(); // map<uint32, uint32> map_uint32_uint32 = 3; int map_uint32_uint32_size() const; private: int _internal_map_uint32_uint32_size() const; public: void clear_map_uint32_uint32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& _internal_map_uint32_uint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* _internal_mutable_map_uint32_uint32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& map_uint32_uint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* mutable_map_uint32_uint32(); // map<uint64, uint64> map_uint64_uint64 = 4; int map_uint64_uint64_size() const; private: int _internal_map_uint64_uint64_size() const; public: void clear_map_uint64_uint64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& _internal_map_uint64_uint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* _internal_mutable_map_uint64_uint64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& map_uint64_uint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* mutable_map_uint64_uint64(); // map<sint32, sint32> map_sint32_sint32 = 5; int map_sint32_sint32_size() const; private: int _internal_map_sint32_sint32_size() const; public: void clear_map_sint32_sint32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_sint32_sint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_sint32_sint32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_sint32_sint32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_sint32_sint32(); // map<sint64, sint64> map_sint64_sint64 = 6; int map_sint64_sint64_size() const; private: int _internal_map_sint64_sint64_size() const; public: void clear_map_sint64_sint64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_sint64_sint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_sint64_sint64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_sint64_sint64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_sint64_sint64(); // map<fixed32, fixed32> map_fixed32_fixed32 = 7; int map_fixed32_fixed32_size() const; private: int _internal_map_fixed32_fixed32_size() const; public: void clear_map_fixed32_fixed32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& _internal_map_fixed32_fixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* _internal_mutable_map_fixed32_fixed32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& map_fixed32_fixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* mutable_map_fixed32_fixed32(); // map<fixed64, fixed64> map_fixed64_fixed64 = 8; int map_fixed64_fixed64_size() const; private: int _internal_map_fixed64_fixed64_size() const; public: void clear_map_fixed64_fixed64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& _internal_map_fixed64_fixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* _internal_mutable_map_fixed64_fixed64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& map_fixed64_fixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* mutable_map_fixed64_fixed64(); // map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9; int map_sfixed32_sfixed32_size() const; private: int _internal_map_sfixed32_sfixed32_size() const; public: void clear_map_sfixed32_sfixed32(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_map_sfixed32_sfixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_map_sfixed32_sfixed32(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& map_sfixed32_sfixed32() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_map_sfixed32_sfixed32(); // map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10; int map_sfixed64_sfixed64_size() const; private: int _internal_map_sfixed64_sfixed64_size() const; public: void clear_map_sfixed64_sfixed64(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& _internal_map_sfixed64_sfixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* _internal_mutable_map_sfixed64_sfixed64(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& map_sfixed64_sfixed64() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* mutable_map_sfixed64_sfixed64(); // map<int32, float> map_int32_float = 11; int map_int32_float_size() const; private: int _internal_map_int32_float_size() const; public: void clear_map_int32_float(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& _internal_map_int32_float() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* _internal_mutable_map_int32_float(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& map_int32_float() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* mutable_map_int32_float(); // map<int32, double> map_int32_double = 12; int map_int32_double_size() const; private: int _internal_map_int32_double_size() const; public: void clear_map_int32_double(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& _internal_map_int32_double() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* _internal_mutable_map_int32_double(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& map_int32_double() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* mutable_map_int32_double(); // map<bool, bool> map_bool_bool = 13; int map_bool_bool_size() const; private: int _internal_map_bool_bool_size() const; public: void clear_map_bool_bool(); private: const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& _internal_map_bool_bool() const; ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* _internal_mutable_map_bool_bool(); public: const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& map_bool_bool() const; ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* mutable_map_bool_bool(); // map<string, string> map_string_string = 14; int map_string_string_size() const; private: int _internal_map_string_string_size() const; public: void clear_map_string_string(); private: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& _internal_map_string_string() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* _internal_mutable_map_string_string(); public: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& map_string_string() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* mutable_map_string_string(); // map<int32, bytes> map_int32_bytes = 15; int map_int32_bytes_size() const; private: int _internal_map_int32_bytes_size() const; public: void clear_map_int32_bytes(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& _internal_map_int32_bytes() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* _internal_mutable_map_int32_bytes(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& map_int32_bytes() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* mutable_map_int32_bytes(); // map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16; int map_int32_enum_size() const; private: int _internal_map_int32_enum_size() const; public: void clear_map_int32_enum(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& _internal_map_int32_enum() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* _internal_mutable_map_int32_enum(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& map_int32_enum() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* mutable_map_int32_enum(); // map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17; int map_int32_foreign_message_size() const; private: int _internal_map_int32_foreign_message_size() const; public: void clear_map_int32_foreign_message(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& _internal_map_int32_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* _internal_mutable_map_int32_foreign_message(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& map_int32_foreign_message() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* mutable_map_int32_foreign_message(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestArenaMap) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32Int32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> map_int32_int32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt64Int64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> map_int64_int64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapUint32Uint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32> map_uint32_uint32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapUint64Uint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT64> map_uint64_uint64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapSint32Sint32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT32> map_sint32_sint32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapSint64Sint64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SINT64> map_sint64_sint64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapFixed32Fixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED32> map_fixed32_fixed32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapFixed64Fixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FIXED64> map_fixed64_fixed64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapSfixed32Sfixed32Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED32> map_sfixed32_sfixed32_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapSfixed64Sfixed64Entry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_SFIXED64> map_sfixed64_sfixed64_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32FloatEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT> map_int32_float_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32DoubleEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, double, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_DOUBLE> map_int32_double_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapBoolBoolEntry_DoNotUse, bool, bool, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BOOL> map_bool_bool_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapStringStringEntry_DoNotUse, std::string, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> map_string_string_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32BytesEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, std::string, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_BYTES> map_int32_bytes_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32EnumEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM> map_int32_enum_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestArenaMap_MapInt32ForeignMessageEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> map_int32_foreign_message_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class MessageContainingEnumCalledType_TypeEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<MessageContainingEnumCalledType_TypeEntry_DoNotUse, std::string, ::protobuf_unittest::MessageContainingEnumCalledType, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<MessageContainingEnumCalledType_TypeEntry_DoNotUse, std::string, ::protobuf_unittest::MessageContainingEnumCalledType, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; MessageContainingEnumCalledType_TypeEntry_DoNotUse(); explicit constexpr MessageContainingEnumCalledType_TypeEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit MessageContainingEnumCalledType_TypeEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const MessageContainingEnumCalledType_TypeEntry_DoNotUse& other); static const MessageContainingEnumCalledType_TypeEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const MessageContainingEnumCalledType_TypeEntry_DoNotUse*>(&_MessageContainingEnumCalledType_TypeEntry_DoNotUse_default_instance_); } static bool ValidateKey(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.MessageContainingEnumCalledType.TypeEntry.key"); } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class MessageContainingEnumCalledType final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.MessageContainingEnumCalledType) */ { public: inline MessageContainingEnumCalledType() : MessageContainingEnumCalledType(nullptr) {} ~MessageContainingEnumCalledType() override; explicit constexpr MessageContainingEnumCalledType(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); MessageContainingEnumCalledType(const MessageContainingEnumCalledType& from); MessageContainingEnumCalledType(MessageContainingEnumCalledType&& from) noexcept : MessageContainingEnumCalledType() { *this = ::std::move(from); } inline MessageContainingEnumCalledType& operator=(const MessageContainingEnumCalledType& from) { CopyFrom(from); return *this; } inline MessageContainingEnumCalledType& operator=(MessageContainingEnumCalledType&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const MessageContainingEnumCalledType& default_instance() { return *internal_default_instance(); } static inline const MessageContainingEnumCalledType* internal_default_instance() { return reinterpret_cast<const MessageContainingEnumCalledType*>( &_MessageContainingEnumCalledType_default_instance_); } static constexpr int kIndexInFileMessages = 47; friend void swap(MessageContainingEnumCalledType& a, MessageContainingEnumCalledType& b) { a.Swap(&b); } inline void Swap(MessageContainingEnumCalledType* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(MessageContainingEnumCalledType* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline MessageContainingEnumCalledType* New() const final { return new MessageContainingEnumCalledType(); } MessageContainingEnumCalledType* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<MessageContainingEnumCalledType>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const MessageContainingEnumCalledType& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const MessageContainingEnumCalledType& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MessageContainingEnumCalledType* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.MessageContainingEnumCalledType"; } protected: explicit MessageContainingEnumCalledType(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef MessageContainingEnumCalledType_Type Type; static constexpr Type TYPE_FOO = MessageContainingEnumCalledType_Type_TYPE_FOO; static inline bool Type_IsValid(int value) { return MessageContainingEnumCalledType_Type_IsValid(value); } static constexpr Type Type_MIN = MessageContainingEnumCalledType_Type_Type_MIN; static constexpr Type Type_MAX = MessageContainingEnumCalledType_Type_Type_MAX; static constexpr int Type_ARRAYSIZE = MessageContainingEnumCalledType_Type_Type_ARRAYSIZE; static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Type_descriptor() { return MessageContainingEnumCalledType_Type_descriptor(); } template<typename T> static inline const std::string& Type_Name(T enum_t_value) { static_assert(::std::is_same<T, Type>::value || ::std::is_integral<T>::value, "Incorrect type passed to function Type_Name."); return MessageContainingEnumCalledType_Type_Name(enum_t_value); } static inline bool Type_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Type* value) { return MessageContainingEnumCalledType_Type_Parse(name, value); } // accessors ------------------------------------------------------- enum : int { kTypeFieldNumber = 1, }; // map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1; int type_size() const; private: int _internal_type_size() const; public: void clear_type(); private: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >& _internal_type() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >* _internal_mutable_type(); public: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >& type() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >* mutable_type(); // @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingEnumCalledType) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< MessageContainingEnumCalledType_TypeEntry_DoNotUse, std::string, ::protobuf_unittest::MessageContainingEnumCalledType, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> type_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class MessageContainingMapCalledEntry_EntryEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<MessageContainingMapCalledEntry_EntryEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<MessageContainingMapCalledEntry_EntryEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> SuperType; MessageContainingMapCalledEntry_EntryEntry_DoNotUse(); explicit constexpr MessageContainingMapCalledEntry_EntryEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit MessageContainingMapCalledEntry_EntryEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const MessageContainingMapCalledEntry_EntryEntry_DoNotUse& other); static const MessageContainingMapCalledEntry_EntryEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const MessageContainingMapCalledEntry_EntryEntry_DoNotUse*>(&_MessageContainingMapCalledEntry_EntryEntry_DoNotUse_default_instance_); } static bool ValidateKey(void*) { return true; } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class MessageContainingMapCalledEntry final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.MessageContainingMapCalledEntry) */ { public: inline MessageContainingMapCalledEntry() : MessageContainingMapCalledEntry(nullptr) {} ~MessageContainingMapCalledEntry() override; explicit constexpr MessageContainingMapCalledEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); MessageContainingMapCalledEntry(const MessageContainingMapCalledEntry& from); MessageContainingMapCalledEntry(MessageContainingMapCalledEntry&& from) noexcept : MessageContainingMapCalledEntry() { *this = ::std::move(from); } inline MessageContainingMapCalledEntry& operator=(const MessageContainingMapCalledEntry& from) { CopyFrom(from); return *this; } inline MessageContainingMapCalledEntry& operator=(MessageContainingMapCalledEntry&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const MessageContainingMapCalledEntry& default_instance() { return *internal_default_instance(); } static inline const MessageContainingMapCalledEntry* internal_default_instance() { return reinterpret_cast<const MessageContainingMapCalledEntry*>( &_MessageContainingMapCalledEntry_default_instance_); } static constexpr int kIndexInFileMessages = 49; friend void swap(MessageContainingMapCalledEntry& a, MessageContainingMapCalledEntry& b) { a.Swap(&b); } inline void Swap(MessageContainingMapCalledEntry* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(MessageContainingMapCalledEntry* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline MessageContainingMapCalledEntry* New() const final { return new MessageContainingMapCalledEntry(); } MessageContainingMapCalledEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<MessageContainingMapCalledEntry>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const MessageContainingMapCalledEntry& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const MessageContainingMapCalledEntry& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MessageContainingMapCalledEntry* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.MessageContainingMapCalledEntry"; } protected: explicit MessageContainingMapCalledEntry(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kEntryFieldNumber = 1, }; // map<int32, int32> entry = 1; int entry_size() const; private: int _internal_entry_size() const; public: void clear_entry(); private: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& _internal_entry() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* _internal_mutable_entry(); public: const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& entry() const; ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* mutable_entry(); // @@protoc_insertion_point(class_scope:protobuf_unittest.MessageContainingMapCalledEntry) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< MessageContainingMapCalledEntry_EntryEntry_DoNotUse, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32> entry_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // ------------------------------------------------------------------- class TestRecursiveMapMessage_AEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestRecursiveMapMessage_AEntry_DoNotUse, std::string, ::protobuf_unittest::TestRecursiveMapMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> { public: typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry<TestRecursiveMapMessage_AEntry_DoNotUse, std::string, ::protobuf_unittest::TestRecursiveMapMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> SuperType; TestRecursiveMapMessage_AEntry_DoNotUse(); explicit constexpr TestRecursiveMapMessage_AEntry_DoNotUse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); explicit TestRecursiveMapMessage_AEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); void MergeFrom(const TestRecursiveMapMessage_AEntry_DoNotUse& other); static const TestRecursiveMapMessage_AEntry_DoNotUse* internal_default_instance() { return reinterpret_cast<const TestRecursiveMapMessage_AEntry_DoNotUse*>(&_TestRecursiveMapMessage_AEntry_DoNotUse_default_instance_); } static bool ValidateKey(std::string* s) { return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast<int>(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "protobuf_unittest.TestRecursiveMapMessage.AEntry.key"); } static bool ValidateValue(void*) { return true; } using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; }; // ------------------------------------------------------------------- class TestRecursiveMapMessage final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestRecursiveMapMessage) */ { public: inline TestRecursiveMapMessage() : TestRecursiveMapMessage(nullptr) {} ~TestRecursiveMapMessage() override; explicit constexpr TestRecursiveMapMessage(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); TestRecursiveMapMessage(const TestRecursiveMapMessage& from); TestRecursiveMapMessage(TestRecursiveMapMessage&& from) noexcept : TestRecursiveMapMessage() { *this = ::std::move(from); } inline TestRecursiveMapMessage& operator=(const TestRecursiveMapMessage& from) { CopyFrom(from); return *this; } inline TestRecursiveMapMessage& operator=(TestRecursiveMapMessage&& from) noexcept { if (this == &from) return *this; if (GetOwningArena() == from.GetOwningArena()) { InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return default_instance().GetMetadata().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return default_instance().GetMetadata().reflection; } static const TestRecursiveMapMessage& default_instance() { return *internal_default_instance(); } static inline const TestRecursiveMapMessage* internal_default_instance() { return reinterpret_cast<const TestRecursiveMapMessage*>( &_TestRecursiveMapMessage_default_instance_); } static constexpr int kIndexInFileMessages = 51; friend void swap(TestRecursiveMapMessage& a, TestRecursiveMapMessage& b) { a.Swap(&b); } inline void Swap(TestRecursiveMapMessage* other) { if (other == this) return; if (GetOwningArena() == other->GetOwningArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(TestRecursiveMapMessage* other) { if (other == this) return; GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline TestRecursiveMapMessage* New() const final { return new TestRecursiveMapMessage(); } TestRecursiveMapMessage* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<TestRecursiveMapMessage>(arena); } using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const TestRecursiveMapMessage& from); using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const TestRecursiveMapMessage& from); private: static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from); public: PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(TestRecursiveMapMessage* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "protobuf_unittest.TestRecursiveMapMessage"; } protected: explicit TestRecursiveMapMessage(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned = false); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: static const ClassData _class_data_; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kAFieldNumber = 1, }; // map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1; int a_size() const; private: int _internal_a_size() const; public: void clear_a(); private: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >& _internal_a() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >* _internal_mutable_a(); public: const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >& a() const; ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >* mutable_a(); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestRecursiveMapMessage) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::MapField< TestRecursiveMapMessage_AEntry_DoNotUse, std::string, ::protobuf_unittest::TestRecursiveMapMessage, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> a_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_google_2fprotobuf_2fmap_5funittest_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestMap // map<int32, int32> map_int32_int32 = 1; inline int TestMap::_internal_map_int32_int32_size() const { return map_int32_int32_.size(); } inline int TestMap::map_int32_int32_size() const { return _internal_map_int32_int32_size(); } inline void TestMap::clear_map_int32_int32() { map_int32_int32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::_internal_map_int32_int32() const { return map_int32_int32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::map_int32_int32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_int32) return _internal_map_int32_int32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::_internal_mutable_map_int32_int32() { return map_int32_int32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::mutable_map_int32_int32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_int32) return _internal_mutable_map_int32_int32(); } // map<int64, int64> map_int64_int64 = 2; inline int TestMap::_internal_map_int64_int64_size() const { return map_int64_int64_.size(); } inline int TestMap::map_int64_int64_size() const { return _internal_map_int64_int64_size(); } inline void TestMap::clear_map_int64_int64() { map_int64_int64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::_internal_map_int64_int64() const { return map_int64_int64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::map_int64_int64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int64_int64) return _internal_map_int64_int64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::_internal_mutable_map_int64_int64() { return map_int64_int64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::mutable_map_int64_int64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int64_int64) return _internal_mutable_map_int64_int64(); } // map<uint32, uint32> map_uint32_uint32 = 3; inline int TestMap::_internal_map_uint32_uint32_size() const { return map_uint32_uint32_.size(); } inline int TestMap::map_uint32_uint32_size() const { return _internal_map_uint32_uint32_size(); } inline void TestMap::clear_map_uint32_uint32() { map_uint32_uint32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestMap::_internal_map_uint32_uint32() const { return map_uint32_uint32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestMap::map_uint32_uint32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_uint32_uint32) return _internal_map_uint32_uint32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestMap::_internal_mutable_map_uint32_uint32() { return map_uint32_uint32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestMap::mutable_map_uint32_uint32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_uint32_uint32) return _internal_mutable_map_uint32_uint32(); } // map<uint64, uint64> map_uint64_uint64 = 4; inline int TestMap::_internal_map_uint64_uint64_size() const { return map_uint64_uint64_.size(); } inline int TestMap::map_uint64_uint64_size() const { return _internal_map_uint64_uint64_size(); } inline void TestMap::clear_map_uint64_uint64() { map_uint64_uint64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestMap::_internal_map_uint64_uint64() const { return map_uint64_uint64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestMap::map_uint64_uint64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_uint64_uint64) return _internal_map_uint64_uint64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestMap::_internal_mutable_map_uint64_uint64() { return map_uint64_uint64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestMap::mutable_map_uint64_uint64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_uint64_uint64) return _internal_mutable_map_uint64_uint64(); } // map<sint32, sint32> map_sint32_sint32 = 5; inline int TestMap::_internal_map_sint32_sint32_size() const { return map_sint32_sint32_.size(); } inline int TestMap::map_sint32_sint32_size() const { return _internal_map_sint32_sint32_size(); } inline void TestMap::clear_map_sint32_sint32() { map_sint32_sint32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::_internal_map_sint32_sint32() const { return map_sint32_sint32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::map_sint32_sint32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sint32_sint32) return _internal_map_sint32_sint32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::_internal_mutable_map_sint32_sint32() { return map_sint32_sint32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::mutable_map_sint32_sint32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sint32_sint32) return _internal_mutable_map_sint32_sint32(); } // map<sint64, sint64> map_sint64_sint64 = 6; inline int TestMap::_internal_map_sint64_sint64_size() const { return map_sint64_sint64_.size(); } inline int TestMap::map_sint64_sint64_size() const { return _internal_map_sint64_sint64_size(); } inline void TestMap::clear_map_sint64_sint64() { map_sint64_sint64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::_internal_map_sint64_sint64() const { return map_sint64_sint64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::map_sint64_sint64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sint64_sint64) return _internal_map_sint64_sint64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::_internal_mutable_map_sint64_sint64() { return map_sint64_sint64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::mutable_map_sint64_sint64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sint64_sint64) return _internal_mutable_map_sint64_sint64(); } // map<fixed32, fixed32> map_fixed32_fixed32 = 7; inline int TestMap::_internal_map_fixed32_fixed32_size() const { return map_fixed32_fixed32_.size(); } inline int TestMap::map_fixed32_fixed32_size() const { return _internal_map_fixed32_fixed32_size(); } inline void TestMap::clear_map_fixed32_fixed32() { map_fixed32_fixed32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestMap::_internal_map_fixed32_fixed32() const { return map_fixed32_fixed32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestMap::map_fixed32_fixed32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_fixed32_fixed32) return _internal_map_fixed32_fixed32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestMap::_internal_mutable_map_fixed32_fixed32() { return map_fixed32_fixed32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestMap::mutable_map_fixed32_fixed32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_fixed32_fixed32) return _internal_mutable_map_fixed32_fixed32(); } // map<fixed64, fixed64> map_fixed64_fixed64 = 8; inline int TestMap::_internal_map_fixed64_fixed64_size() const { return map_fixed64_fixed64_.size(); } inline int TestMap::map_fixed64_fixed64_size() const { return _internal_map_fixed64_fixed64_size(); } inline void TestMap::clear_map_fixed64_fixed64() { map_fixed64_fixed64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestMap::_internal_map_fixed64_fixed64() const { return map_fixed64_fixed64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestMap::map_fixed64_fixed64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_fixed64_fixed64) return _internal_map_fixed64_fixed64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestMap::_internal_mutable_map_fixed64_fixed64() { return map_fixed64_fixed64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestMap::mutable_map_fixed64_fixed64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_fixed64_fixed64) return _internal_mutable_map_fixed64_fixed64(); } // map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9; inline int TestMap::_internal_map_sfixed32_sfixed32_size() const { return map_sfixed32_sfixed32_.size(); } inline int TestMap::map_sfixed32_sfixed32_size() const { return _internal_map_sfixed32_sfixed32_size(); } inline void TestMap::clear_map_sfixed32_sfixed32() { map_sfixed32_sfixed32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::_internal_map_sfixed32_sfixed32() const { return map_sfixed32_sfixed32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestMap::map_sfixed32_sfixed32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sfixed32_sfixed32) return _internal_map_sfixed32_sfixed32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::_internal_mutable_map_sfixed32_sfixed32() { return map_sfixed32_sfixed32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestMap::mutable_map_sfixed32_sfixed32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sfixed32_sfixed32) return _internal_mutable_map_sfixed32_sfixed32(); } // map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10; inline int TestMap::_internal_map_sfixed64_sfixed64_size() const { return map_sfixed64_sfixed64_.size(); } inline int TestMap::map_sfixed64_sfixed64_size() const { return _internal_map_sfixed64_sfixed64_size(); } inline void TestMap::clear_map_sfixed64_sfixed64() { map_sfixed64_sfixed64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::_internal_map_sfixed64_sfixed64() const { return map_sfixed64_sfixed64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestMap::map_sfixed64_sfixed64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sfixed64_sfixed64) return _internal_map_sfixed64_sfixed64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::_internal_mutable_map_sfixed64_sfixed64() { return map_sfixed64_sfixed64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestMap::mutable_map_sfixed64_sfixed64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sfixed64_sfixed64) return _internal_mutable_map_sfixed64_sfixed64(); } // map<int32, float> map_int32_float = 11; inline int TestMap::_internal_map_int32_float_size() const { return map_int32_float_.size(); } inline int TestMap::map_int32_float_size() const { return _internal_map_int32_float_size(); } inline void TestMap::clear_map_int32_float() { map_int32_float_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& TestMap::_internal_map_int32_float() const { return map_int32_float_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& TestMap::map_int32_float() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_float) return _internal_map_int32_float(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* TestMap::_internal_mutable_map_int32_float() { return map_int32_float_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* TestMap::mutable_map_int32_float() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_float) return _internal_mutable_map_int32_float(); } // map<int32, double> map_int32_double = 12; inline int TestMap::_internal_map_int32_double_size() const { return map_int32_double_.size(); } inline int TestMap::map_int32_double_size() const { return _internal_map_int32_double_size(); } inline void TestMap::clear_map_int32_double() { map_int32_double_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& TestMap::_internal_map_int32_double() const { return map_int32_double_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& TestMap::map_int32_double() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_double) return _internal_map_int32_double(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* TestMap::_internal_mutable_map_int32_double() { return map_int32_double_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* TestMap::mutable_map_int32_double() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_double) return _internal_mutable_map_int32_double(); } // map<bool, bool> map_bool_bool = 13; inline int TestMap::_internal_map_bool_bool_size() const { return map_bool_bool_.size(); } inline int TestMap::map_bool_bool_size() const { return _internal_map_bool_bool_size(); } inline void TestMap::clear_map_bool_bool() { map_bool_bool_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& TestMap::_internal_map_bool_bool() const { return map_bool_bool_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& TestMap::map_bool_bool() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_bool_bool) return _internal_map_bool_bool(); } inline ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* TestMap::_internal_mutable_map_bool_bool() { return map_bool_bool_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* TestMap::mutable_map_bool_bool() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_bool_bool) return _internal_mutable_map_bool_bool(); } // map<string, string> map_string_string = 14; inline int TestMap::_internal_map_string_string_size() const { return map_string_string_.size(); } inline int TestMap::map_string_string_size() const { return _internal_map_string_string_size(); } inline void TestMap::clear_map_string_string() { map_string_string_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& TestMap::_internal_map_string_string() const { return map_string_string_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& TestMap::map_string_string() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_string_string) return _internal_map_string_string(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* TestMap::_internal_mutable_map_string_string() { return map_string_string_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* TestMap::mutable_map_string_string() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_string_string) return _internal_mutable_map_string_string(); } // map<int32, bytes> map_int32_bytes = 15; inline int TestMap::_internal_map_int32_bytes_size() const { return map_int32_bytes_.size(); } inline int TestMap::map_int32_bytes_size() const { return _internal_map_int32_bytes_size(); } inline void TestMap::clear_map_int32_bytes() { map_int32_bytes_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& TestMap::_internal_map_int32_bytes() const { return map_int32_bytes_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& TestMap::map_int32_bytes() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_bytes) return _internal_map_int32_bytes(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* TestMap::_internal_mutable_map_int32_bytes() { return map_int32_bytes_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* TestMap::mutable_map_int32_bytes() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_bytes) return _internal_mutable_map_int32_bytes(); } // map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16; inline int TestMap::_internal_map_int32_enum_size() const { return map_int32_enum_.size(); } inline int TestMap::map_int32_enum_size() const { return _internal_map_int32_enum_size(); } inline void TestMap::clear_map_int32_enum() { map_int32_enum_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& TestMap::_internal_map_int32_enum() const { return map_int32_enum_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& TestMap::map_int32_enum() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_enum) return _internal_map_int32_enum(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* TestMap::_internal_mutable_map_int32_enum() { return map_int32_enum_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* TestMap::mutable_map_int32_enum() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_enum) return _internal_mutable_map_int32_enum(); } // map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17; inline int TestMap::_internal_map_int32_foreign_message_size() const { return map_int32_foreign_message_.size(); } inline int TestMap::map_int32_foreign_message_size() const { return _internal_map_int32_foreign_message_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& TestMap::_internal_map_int32_foreign_message() const { return map_int32_foreign_message_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& TestMap::map_int32_foreign_message() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_foreign_message) return _internal_map_int32_foreign_message(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* TestMap::_internal_mutable_map_int32_foreign_message() { return map_int32_foreign_message_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* TestMap::mutable_map_int32_foreign_message() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_foreign_message) return _internal_mutable_map_int32_foreign_message(); } // map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18; inline int TestMap::_internal_map_string_foreign_message_size() const { return map_string_foreign_message_.size(); } inline int TestMap::map_string_foreign_message_size() const { return _internal_map_string_foreign_message_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >& TestMap::_internal_map_string_foreign_message() const { return map_string_foreign_message_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >& TestMap::map_string_foreign_message() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_string_foreign_message) return _internal_map_string_foreign_message(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >* TestMap::_internal_mutable_map_string_foreign_message() { return map_string_foreign_message_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::ForeignMessage >* TestMap::mutable_map_string_foreign_message() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_string_foreign_message) return _internal_mutable_map_string_foreign_message(); } // map<int32, .protobuf_unittest.TestAllTypes> map_int32_all_types = 19; inline int TestMap::_internal_map_int32_all_types_size() const { return map_int32_all_types_.size(); } inline int TestMap::map_int32_all_types_size() const { return _internal_map_int32_all_types_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& TestMap::_internal_map_int32_all_types() const { return map_int32_all_types_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& TestMap::map_int32_all_types() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_all_types) return _internal_map_int32_all_types(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* TestMap::_internal_mutable_map_int32_all_types() { return map_int32_all_types_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* TestMap::mutable_map_int32_all_types() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_all_types) return _internal_mutable_map_int32_all_types(); } // ------------------------------------------------------------------- // TestMapSubmessage // .protobuf_unittest.TestMap test_map = 1; inline bool TestMapSubmessage::_internal_has_test_map() const { return this != internal_default_instance() && test_map_ != nullptr; } inline bool TestMapSubmessage::has_test_map() const { return _internal_has_test_map(); } inline void TestMapSubmessage::clear_test_map() { if (GetArenaForAllocation() == nullptr && test_map_ != nullptr) { delete test_map_; } test_map_ = nullptr; } inline const ::protobuf_unittest::TestMap& TestMapSubmessage::_internal_test_map() const { const ::protobuf_unittest::TestMap* p = test_map_; return p != nullptr ? *p : reinterpret_cast<const ::protobuf_unittest::TestMap&>( ::protobuf_unittest::_TestMap_default_instance_); } inline const ::protobuf_unittest::TestMap& TestMapSubmessage::test_map() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestMapSubmessage.test_map) return _internal_test_map(); } inline void TestMapSubmessage::unsafe_arena_set_allocated_test_map( ::protobuf_unittest::TestMap* test_map) { if (GetArenaForAllocation() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(test_map_); } test_map_ = test_map; if (test_map) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:protobuf_unittest.TestMapSubmessage.test_map) } inline ::protobuf_unittest::TestMap* TestMapSubmessage::release_test_map() { ::protobuf_unittest::TestMap* temp = test_map_; test_map_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); if (GetArenaForAllocation() == nullptr) { delete old; } #else // PROTOBUF_FORCE_COPY_IN_RELEASE if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } #endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } inline ::protobuf_unittest::TestMap* TestMapSubmessage::unsafe_arena_release_test_map() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestMapSubmessage.test_map) ::protobuf_unittest::TestMap* temp = test_map_; test_map_ = nullptr; return temp; } inline ::protobuf_unittest::TestMap* TestMapSubmessage::_internal_mutable_test_map() { if (test_map_ == nullptr) { auto* p = CreateMaybeMessage<::protobuf_unittest::TestMap>(GetArenaForAllocation()); test_map_ = p; } return test_map_; } inline ::protobuf_unittest::TestMap* TestMapSubmessage::mutable_test_map() { ::protobuf_unittest::TestMap* _msg = _internal_mutable_test_map(); // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestMapSubmessage.test_map) return _msg; } inline void TestMapSubmessage::set_allocated_test_map(::protobuf_unittest::TestMap* test_map) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { delete test_map_; } if (test_map) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper<::protobuf_unittest::TestMap>::GetOwningArena(test_map); if (message_arena != submessage_arena) { test_map = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, test_map, submessage_arena); } } else { } test_map_ = test_map; // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestMapSubmessage.test_map) } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestMessageMap // map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1; inline int TestMessageMap::_internal_map_int32_message_size() const { return map_int32_message_.size(); } inline int TestMessageMap::map_int32_message_size() const { return _internal_map_int32_message_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& TestMessageMap::_internal_map_int32_message() const { return map_int32_message_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >& TestMessageMap::map_int32_message() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestMessageMap.map_int32_message) return _internal_map_int32_message(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* TestMessageMap::_internal_mutable_map_int32_message() { return map_int32_message_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestAllTypes >* TestMessageMap::mutable_map_int32_message() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMessageMap.map_int32_message) return _internal_mutable_map_int32_message(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestSameTypeMap // map<int32, int32> map1 = 1; inline int TestSameTypeMap::_internal_map1_size() const { return map1_.size(); } inline int TestSameTypeMap::map1_size() const { return _internal_map1_size(); } inline void TestSameTypeMap::clear_map1() { map1_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestSameTypeMap::_internal_map1() const { return map1_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestSameTypeMap::map1() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestSameTypeMap.map1) return _internal_map1(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestSameTypeMap::_internal_mutable_map1() { return map1_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestSameTypeMap::mutable_map1() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestSameTypeMap.map1) return _internal_mutable_map1(); } // map<int32, int32> map2 = 2; inline int TestSameTypeMap::_internal_map2_size() const { return map2_.size(); } inline int TestSameTypeMap::map2_size() const { return _internal_map2_size(); } inline void TestSameTypeMap::clear_map2() { map2_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestSameTypeMap::_internal_map2() const { return map2_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestSameTypeMap::map2() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestSameTypeMap.map2) return _internal_map2(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestSameTypeMap::_internal_mutable_map2() { return map2_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestSameTypeMap::mutable_map2() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestSameTypeMap.map2) return _internal_mutable_map2(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestRequiredMessageMap // map<int32, .protobuf_unittest.TestRequired> map_field = 1; inline int TestRequiredMessageMap::_internal_map_field_size() const { return map_field_.size(); } inline int TestRequiredMessageMap::map_field_size() const { return _internal_map_field_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >& TestRequiredMessageMap::_internal_map_field() const { return map_field_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >& TestRequiredMessageMap::map_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestRequiredMessageMap.map_field) return _internal_map_field(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >* TestRequiredMessageMap::_internal_mutable_map_field() { return map_field_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::TestRequired >* TestRequiredMessageMap::mutable_map_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestRequiredMessageMap.map_field) return _internal_mutable_map_field(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestArenaMap // map<int32, int32> map_int32_int32 = 1; inline int TestArenaMap::_internal_map_int32_int32_size() const { return map_int32_int32_.size(); } inline int TestArenaMap::map_int32_int32_size() const { return _internal_map_int32_int32_size(); } inline void TestArenaMap::clear_map_int32_int32() { map_int32_int32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::_internal_map_int32_int32() const { return map_int32_int32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::map_int32_int32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_int32) return _internal_map_int32_int32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::_internal_mutable_map_int32_int32() { return map_int32_int32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::mutable_map_int32_int32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_int32) return _internal_mutable_map_int32_int32(); } // map<int64, int64> map_int64_int64 = 2; inline int TestArenaMap::_internal_map_int64_int64_size() const { return map_int64_int64_.size(); } inline int TestArenaMap::map_int64_int64_size() const { return _internal_map_int64_int64_size(); } inline void TestArenaMap::clear_map_int64_int64() { map_int64_int64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::_internal_map_int64_int64() const { return map_int64_int64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::map_int64_int64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int64_int64) return _internal_map_int64_int64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::_internal_mutable_map_int64_int64() { return map_int64_int64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::mutable_map_int64_int64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int64_int64) return _internal_mutable_map_int64_int64(); } // map<uint32, uint32> map_uint32_uint32 = 3; inline int TestArenaMap::_internal_map_uint32_uint32_size() const { return map_uint32_uint32_.size(); } inline int TestArenaMap::map_uint32_uint32_size() const { return _internal_map_uint32_uint32_size(); } inline void TestArenaMap::clear_map_uint32_uint32() { map_uint32_uint32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestArenaMap::_internal_map_uint32_uint32() const { return map_uint32_uint32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestArenaMap::map_uint32_uint32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_uint32_uint32) return _internal_map_uint32_uint32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestArenaMap::_internal_mutable_map_uint32_uint32() { return map_uint32_uint32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestArenaMap::mutable_map_uint32_uint32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_uint32_uint32) return _internal_mutable_map_uint32_uint32(); } // map<uint64, uint64> map_uint64_uint64 = 4; inline int TestArenaMap::_internal_map_uint64_uint64_size() const { return map_uint64_uint64_.size(); } inline int TestArenaMap::map_uint64_uint64_size() const { return _internal_map_uint64_uint64_size(); } inline void TestArenaMap::clear_map_uint64_uint64() { map_uint64_uint64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestArenaMap::_internal_map_uint64_uint64() const { return map_uint64_uint64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestArenaMap::map_uint64_uint64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_uint64_uint64) return _internal_map_uint64_uint64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestArenaMap::_internal_mutable_map_uint64_uint64() { return map_uint64_uint64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestArenaMap::mutable_map_uint64_uint64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_uint64_uint64) return _internal_mutable_map_uint64_uint64(); } // map<sint32, sint32> map_sint32_sint32 = 5; inline int TestArenaMap::_internal_map_sint32_sint32_size() const { return map_sint32_sint32_.size(); } inline int TestArenaMap::map_sint32_sint32_size() const { return _internal_map_sint32_sint32_size(); } inline void TestArenaMap::clear_map_sint32_sint32() { map_sint32_sint32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::_internal_map_sint32_sint32() const { return map_sint32_sint32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::map_sint32_sint32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sint32_sint32) return _internal_map_sint32_sint32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::_internal_mutable_map_sint32_sint32() { return map_sint32_sint32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::mutable_map_sint32_sint32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sint32_sint32) return _internal_mutable_map_sint32_sint32(); } // map<sint64, sint64> map_sint64_sint64 = 6; inline int TestArenaMap::_internal_map_sint64_sint64_size() const { return map_sint64_sint64_.size(); } inline int TestArenaMap::map_sint64_sint64_size() const { return _internal_map_sint64_sint64_size(); } inline void TestArenaMap::clear_map_sint64_sint64() { map_sint64_sint64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::_internal_map_sint64_sint64() const { return map_sint64_sint64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::map_sint64_sint64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sint64_sint64) return _internal_map_sint64_sint64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::_internal_mutable_map_sint64_sint64() { return map_sint64_sint64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::mutable_map_sint64_sint64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sint64_sint64) return _internal_mutable_map_sint64_sint64(); } // map<fixed32, fixed32> map_fixed32_fixed32 = 7; inline int TestArenaMap::_internal_map_fixed32_fixed32_size() const { return map_fixed32_fixed32_.size(); } inline int TestArenaMap::map_fixed32_fixed32_size() const { return _internal_map_fixed32_fixed32_size(); } inline void TestArenaMap::clear_map_fixed32_fixed32() { map_fixed32_fixed32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestArenaMap::_internal_map_fixed32_fixed32() const { return map_fixed32_fixed32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >& TestArenaMap::map_fixed32_fixed32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_fixed32_fixed32) return _internal_map_fixed32_fixed32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestArenaMap::_internal_mutable_map_fixed32_fixed32() { return map_fixed32_fixed32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::uint32 >* TestArenaMap::mutable_map_fixed32_fixed32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_fixed32_fixed32) return _internal_mutable_map_fixed32_fixed32(); } // map<fixed64, fixed64> map_fixed64_fixed64 = 8; inline int TestArenaMap::_internal_map_fixed64_fixed64_size() const { return map_fixed64_fixed64_.size(); } inline int TestArenaMap::map_fixed64_fixed64_size() const { return _internal_map_fixed64_fixed64_size(); } inline void TestArenaMap::clear_map_fixed64_fixed64() { map_fixed64_fixed64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestArenaMap::_internal_map_fixed64_fixed64() const { return map_fixed64_fixed64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >& TestArenaMap::map_fixed64_fixed64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_fixed64_fixed64) return _internal_map_fixed64_fixed64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestArenaMap::_internal_mutable_map_fixed64_fixed64() { return map_fixed64_fixed64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::uint64, ::PROTOBUF_NAMESPACE_ID::uint64 >* TestArenaMap::mutable_map_fixed64_fixed64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_fixed64_fixed64) return _internal_mutable_map_fixed64_fixed64(); } // map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9; inline int TestArenaMap::_internal_map_sfixed32_sfixed32_size() const { return map_sfixed32_sfixed32_.size(); } inline int TestArenaMap::map_sfixed32_sfixed32_size() const { return _internal_map_sfixed32_sfixed32_size(); } inline void TestArenaMap::clear_map_sfixed32_sfixed32() { map_sfixed32_sfixed32_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::_internal_map_sfixed32_sfixed32() const { return map_sfixed32_sfixed32_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& TestArenaMap::map_sfixed32_sfixed32() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sfixed32_sfixed32) return _internal_map_sfixed32_sfixed32(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::_internal_mutable_map_sfixed32_sfixed32() { return map_sfixed32_sfixed32_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* TestArenaMap::mutable_map_sfixed32_sfixed32() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sfixed32_sfixed32) return _internal_mutable_map_sfixed32_sfixed32(); } // map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10; inline int TestArenaMap::_internal_map_sfixed64_sfixed64_size() const { return map_sfixed64_sfixed64_.size(); } inline int TestArenaMap::map_sfixed64_sfixed64_size() const { return _internal_map_sfixed64_sfixed64_size(); } inline void TestArenaMap::clear_map_sfixed64_sfixed64() { map_sfixed64_sfixed64_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::_internal_map_sfixed64_sfixed64() const { return map_sfixed64_sfixed64_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >& TestArenaMap::map_sfixed64_sfixed64() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sfixed64_sfixed64) return _internal_map_sfixed64_sfixed64(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::_internal_mutable_map_sfixed64_sfixed64() { return map_sfixed64_sfixed64_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int64, ::PROTOBUF_NAMESPACE_ID::int64 >* TestArenaMap::mutable_map_sfixed64_sfixed64() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sfixed64_sfixed64) return _internal_mutable_map_sfixed64_sfixed64(); } // map<int32, float> map_int32_float = 11; inline int TestArenaMap::_internal_map_int32_float_size() const { return map_int32_float_.size(); } inline int TestArenaMap::map_int32_float_size() const { return _internal_map_int32_float_size(); } inline void TestArenaMap::clear_map_int32_float() { map_int32_float_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& TestArenaMap::_internal_map_int32_float() const { return map_int32_float_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >& TestArenaMap::map_int32_float() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_float) return _internal_map_int32_float(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* TestArenaMap::_internal_mutable_map_int32_float() { return map_int32_float_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, float >* TestArenaMap::mutable_map_int32_float() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_float) return _internal_mutable_map_int32_float(); } // map<int32, double> map_int32_double = 12; inline int TestArenaMap::_internal_map_int32_double_size() const { return map_int32_double_.size(); } inline int TestArenaMap::map_int32_double_size() const { return _internal_map_int32_double_size(); } inline void TestArenaMap::clear_map_int32_double() { map_int32_double_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& TestArenaMap::_internal_map_int32_double() const { return map_int32_double_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >& TestArenaMap::map_int32_double() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_double) return _internal_map_int32_double(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* TestArenaMap::_internal_mutable_map_int32_double() { return map_int32_double_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, double >* TestArenaMap::mutable_map_int32_double() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_double) return _internal_mutable_map_int32_double(); } // map<bool, bool> map_bool_bool = 13; inline int TestArenaMap::_internal_map_bool_bool_size() const { return map_bool_bool_.size(); } inline int TestArenaMap::map_bool_bool_size() const { return _internal_map_bool_bool_size(); } inline void TestArenaMap::clear_map_bool_bool() { map_bool_bool_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& TestArenaMap::_internal_map_bool_bool() const { return map_bool_bool_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >& TestArenaMap::map_bool_bool() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_bool_bool) return _internal_map_bool_bool(); } inline ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* TestArenaMap::_internal_mutable_map_bool_bool() { return map_bool_bool_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< bool, bool >* TestArenaMap::mutable_map_bool_bool() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_bool_bool) return _internal_mutable_map_bool_bool(); } // map<string, string> map_string_string = 14; inline int TestArenaMap::_internal_map_string_string_size() const { return map_string_string_.size(); } inline int TestArenaMap::map_string_string_size() const { return _internal_map_string_string_size(); } inline void TestArenaMap::clear_map_string_string() { map_string_string_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& TestArenaMap::_internal_map_string_string() const { return map_string_string_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& TestArenaMap::map_string_string() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_string_string) return _internal_map_string_string(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* TestArenaMap::_internal_mutable_map_string_string() { return map_string_string_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* TestArenaMap::mutable_map_string_string() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_string_string) return _internal_mutable_map_string_string(); } // map<int32, bytes> map_int32_bytes = 15; inline int TestArenaMap::_internal_map_int32_bytes_size() const { return map_int32_bytes_.size(); } inline int TestArenaMap::map_int32_bytes_size() const { return _internal_map_int32_bytes_size(); } inline void TestArenaMap::clear_map_int32_bytes() { map_int32_bytes_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& TestArenaMap::_internal_map_int32_bytes() const { return map_int32_bytes_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >& TestArenaMap::map_int32_bytes() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_bytes) return _internal_map_int32_bytes(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* TestArenaMap::_internal_mutable_map_int32_bytes() { return map_int32_bytes_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, std::string >* TestArenaMap::mutable_map_int32_bytes() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_bytes) return _internal_mutable_map_int32_bytes(); } // map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16; inline int TestArenaMap::_internal_map_int32_enum_size() const { return map_int32_enum_.size(); } inline int TestArenaMap::map_int32_enum_size() const { return _internal_map_int32_enum_size(); } inline void TestArenaMap::clear_map_int32_enum() { map_int32_enum_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& TestArenaMap::_internal_map_int32_enum() const { return map_int32_enum_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >& TestArenaMap::map_int32_enum() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_enum) return _internal_map_int32_enum(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* TestArenaMap::_internal_mutable_map_int32_enum() { return map_int32_enum_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::MapEnum >* TestArenaMap::mutable_map_int32_enum() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_enum) return _internal_mutable_map_int32_enum(); } // map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17; inline int TestArenaMap::_internal_map_int32_foreign_message_size() const { return map_int32_foreign_message_.size(); } inline int TestArenaMap::map_int32_foreign_message_size() const { return _internal_map_int32_foreign_message_size(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& TestArenaMap::_internal_map_int32_foreign_message() const { return map_int32_foreign_message_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >& TestArenaMap::map_int32_foreign_message() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message) return _internal_map_int32_foreign_message(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* TestArenaMap::_internal_mutable_map_int32_foreign_message() { return map_int32_foreign_message_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::protobuf_unittest::ForeignMessage >* TestArenaMap::mutable_map_int32_foreign_message() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message) return _internal_mutable_map_int32_foreign_message(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // MessageContainingEnumCalledType // map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1; inline int MessageContainingEnumCalledType::_internal_type_size() const { return type_.size(); } inline int MessageContainingEnumCalledType::type_size() const { return _internal_type_size(); } inline void MessageContainingEnumCalledType::clear_type() { type_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >& MessageContainingEnumCalledType::_internal_type() const { return type_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >& MessageContainingEnumCalledType::type() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MessageContainingEnumCalledType.type) return _internal_type(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >* MessageContainingEnumCalledType::_internal_mutable_type() { return type_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::MessageContainingEnumCalledType >* MessageContainingEnumCalledType::mutable_type() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MessageContainingEnumCalledType.type) return _internal_mutable_type(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // MessageContainingMapCalledEntry // map<int32, int32> entry = 1; inline int MessageContainingMapCalledEntry::_internal_entry_size() const { return entry_.size(); } inline int MessageContainingMapCalledEntry::entry_size() const { return _internal_entry_size(); } inline void MessageContainingMapCalledEntry::clear_entry() { entry_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& MessageContainingMapCalledEntry::_internal_entry() const { return entry_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >& MessageContainingMapCalledEntry::entry() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MessageContainingMapCalledEntry.entry) return _internal_entry(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* MessageContainingMapCalledEntry::_internal_mutable_entry() { return entry_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::int32 >* MessageContainingMapCalledEntry::mutable_entry() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MessageContainingMapCalledEntry.entry) return _internal_mutable_entry(); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // TestRecursiveMapMessage // map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1; inline int TestRecursiveMapMessage::_internal_a_size() const { return a_.size(); } inline int TestRecursiveMapMessage::a_size() const { return _internal_a_size(); } inline void TestRecursiveMapMessage::clear_a() { a_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >& TestRecursiveMapMessage::_internal_a() const { return a_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >& TestRecursiveMapMessage::a() const { // @@protoc_insertion_point(field_map:protobuf_unittest.TestRecursiveMapMessage.a) return _internal_a(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >* TestRecursiveMapMessage::_internal_mutable_a() { return a_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::protobuf_unittest::TestRecursiveMapMessage >* TestRecursiveMapMessage::mutable_a() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestRecursiveMapMessage.a) return _internal_mutable_a(); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::protobuf_unittest::MessageContainingEnumCalledType_Type> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::protobuf_unittest::MessageContainingEnumCalledType_Type>() { return ::protobuf_unittest::MessageContainingEnumCalledType_Type_descriptor(); } template <> struct is_proto_enum< ::protobuf_unittest::MapEnum> : ::std::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::protobuf_unittest::MapEnum>() { return ::protobuf_unittest::MapEnum_descriptor(); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fmap_5funittest_2eproto
49.172481
257
0.760983
[ "object" ]
ca1bcdd3f57027393b20a62f5dae016d270f9cd5
5,245
h
C
alljoyn/services/about/ios/inc/alljoyn/about/AJNAboutIconClient.h
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
37
2015-01-18T21:27:23.000Z
2018-01-12T00:33:43.000Z
alljoyn/services/about/ios/inc/alljoyn/about/AJNAboutIconClient.h
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
14
2015-02-24T11:44:01.000Z
2020-07-20T18:48:44.000Z
alljoyn/services/about/ios/inc/alljoyn/about/AJNAboutIconClient.h
WigWagCo/alljoyn
1b148edd934882ca32fd319af86a5a927f9d35a7
[ "0BSD" ]
29
2015-01-23T16:40:52.000Z
2019-10-21T12:22:30.000Z
/****************************************************************************** * Copyright (c) 2013-2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #import <Foundation/Foundation.h> #import "AJNBusAttachment.h" #import "AJNSessionOptions.h" /** AJNAboutIconClient enables the user of the class to interact with the remote AboutServiceIcon instance. */ @interface AJNAboutIconClient : NSObject /** Designated initializer. Create an AboutIconClient Object using the passed AJNBusAttachment. @param bus A reference to the AJNBusAttachment. */ - (id)initWithBus:(AJNBusAttachment *)bus; /** Populate a given parameter with the icon url for a specified bus name. @param busName Unique or well-known name of AllJoyn bus. @param url The url of the icon[out]. @return ER_OK if successful. */ - (QStatus)urlFromBusName:(NSString *)busName url:(NSString **)url; /** Populate a given parameter with the icon url for a specified bus name and session id. @param busName Unique or well-known name of AllJoyn bus. @param url The url of the icon[out]. @param sessionId The session received after joining AllJoyn session. @return ER_OK if successful. */ - (QStatus)urlFromBusName:(NSString *)busName url:(NSString **)url sessionId:(AJNSessionId)sessionId; /** Populate a given parameter with the icon content and the content size for a specified bus name. @param busName Unique or well-known name of AllJoyn bus. @param content The retrieved content of the icon payload [out]. @param contentSize The size of the content payload [out]. @return ER_OK if successful. */ - (QStatus)contentFromBusName:(NSString *)busName content:(uint8_t **)content contentSize:(size_t&)contentSize; /** Populate a given parameter with the icon content and the content size for a specified bus name and session id. @param busName Unique or well-known name of AllJoyn bus. @param content The retrieved content of the icon payload [out]. @param contentSize The size of the content payload [out]. @param sessionId The session received after joining AllJoyn session. @return ER_OK if successful. */ - (QStatus)contentFromBusName:(NSString *)busName content:(uint8_t **)content contentSize:(size_t&)contentSize sessionId:(AJNSessionId)sessionId; /** Populate a given parameters with the version of the AboutIcontClient for a specified bus name. @param busName Unique or well-known name of AllJoyn bus. @param version The AboutIcontClient version[out]. @return ER_OK if successful. */ - (QStatus)versionFromBusName:(NSString *)busName version:(int&)version; /** Populate a given parameters with the version of the AboutIcontClient for a specified bus name and session id. @param busName Unique or well-known name of AllJoyn bus. @param version The AboutIcontClient version[out]. @param sessionId the session received after joining AllJoyn session. @return ER_OK if successful. */ - (QStatus)versionFromBusName:(NSString *)busName version:(int&)version sessionId:(AJNSessionId)sessionId; /** Populate a given parameter with the icon mime type for a specified bus name. @param busName Unique or well-known name of AllJoyn bus. @param mimeType The icon's mime type [out]. @return ER_OK if successful. */ - (QStatus)mimeTypeFromBusName:(NSString *)busName mimeType:(NSString **)mimeType; /** Populate a given parameter with the icon mime type for a specified bus name and session id. @param busName Unique or well-known name of AllJoyn bus. @param mimeType The icon's mime type [out]. @param sessionId The session received after joining AllJoyn session. @return ER_OK if successful. */ - (QStatus)mimeTypeFromBusName:(NSString *)busName mimeType:(NSString **)mimeType sessionId:(AJNSessionId)sessionId; /** Populate a given parameter with the icon size for a specified bus name. @param busName Unique or well-known name of AllJoyn bus. @param size The size of the icon [out]. @return ER_OK if successful. */ - (QStatus)sizeFromBusName:(NSString *)busName size:(size_t&)size; /** Populate a given parameter with the icon size for a specified bus name and session id. @param busName Unique or well-known name of AllJoyn bus. @param size The size of the icon [out]. @param sessionId The session received after joining AllJoyn session. @return ER_OK if successful. */ - (QStatus)sizeFromBusName:(NSString *)busName size:(size_t&)size sessionId:(AJNSessionId)sessionId; @end
43.347107
145
0.740896
[ "object" ]
ca1c26bc8ebb4676907b7d4d40e15b379dd8f727
1,413
h
C
Phase 1 , 2/first_follow (1).h
MohamedBakrAli/Compiler
d36d8d3acb52f0023198346dbf312b5618c60d9e
[ "MIT" ]
1
2019-08-12T17:08:06.000Z
2019-08-12T17:08:06.000Z
Phase 1 , 2/first_follow (1).h
MohamedBakrAli/Java-Compiler
d36d8d3acb52f0023198346dbf312b5618c60d9e
[ "MIT" ]
null
null
null
Phase 1 , 2/first_follow (1).h
MohamedBakrAli/Java-Compiler
d36d8d3acb52f0023198346dbf312b5618c60d9e
[ "MIT" ]
1
2018-09-10T12:55:38.000Z
2018-09-10T12:55:38.000Z
#ifndef FIRST_FOLLOW_H #define FIRST_FOLLOW_H #include <fstream> #include <sstream> #include <iostream> #include <string> #include <vector> #include "convert_to_LL1.h" using namespace std; class first_follow { public: first_follow(); ~first_follow(); void print(); void read_from_file(); void apply_first(); void apply_follow(); vector <pair < string,string > > get_first_array(); vector <pair < string,string > > get_follow_array(); vector <string> get_terminal(); vector <string> get_nonterminal(); void get_follow(); private: void check1(int i, int j); void check2(int i, int j); void check3(int i, int j); bool is_terminal(string x); string get_first(string left, string part); void parse(string line); string remove_spaces(string str); vector <string> nonTerminal; vector <string> Terminal; vector <string> remove_empty_element(vector<string> araf); vector<string> _split(const string &s, char delim); vector <pair < string,string > > productions_; vector <pair < string,string > > first; vector <pair < string,string > > follow; int count_epison,epison_occur; convert_to_LL1 LL1_recovery; }; #endif // FIRST_FOLLOW_H
25.690909
67
0.600849
[ "vector" ]
ca1ca2618d80ffe11dc000def3eee639f6a14ab8
40,281
c
C
source/blender/blenkernel/intern/mball_tessellate.c
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
116
2015-11-02T16:36:53.000Z
2021-06-08T20:36:18.000Z
source/blender/blenkernel/intern/mball_tessellate.c
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
39
2016-04-25T12:18:34.000Z
2021-03-01T19:06:36.000Z
source/blender/blenkernel/intern/mball_tessellate.c
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
19
2016-01-24T14:24:00.000Z
2020-07-19T05:26:24.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. */ /** \file * \ingroup bke */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <float.h> #include "MEM_guardedalloc.h" #include "DNA_object_types.h" #include "DNA_meta_types.h" #include "DNA_scene_types.h" #include "BLI_listbase.h" #include "BLI_math.h" #include "BLI_string_utils.h" #include "BLI_utildefines.h" #include "BLI_memarena.h" #include "BKE_global.h" #include "BKE_displist.h" #include "BKE_mball_tessellate.h" /* own include */ #include "BKE_scene.h" #include "DEG_depsgraph.h" #include "DEG_depsgraph_query.h" #include "BLI_strict_flags.h" /* experimental (faster) normal calculation */ // #define USE_ACCUM_NORMAL /* Data types */ typedef struct corner { /* corner of a cube */ int i, j, k; /* (i, j, k) is index within lattice */ float co[3], value; /* location and function value */ struct corner *next; } CORNER; typedef struct cube { /* partitioning cell (cube) */ int i, j, k; /* lattice location of cube */ CORNER *corners[8]; /* eight corners */ } CUBE; typedef struct cubes { /* linked list of cubes acting as stack */ CUBE cube; /* a single cube */ struct cubes *next; /* remaining elements */ } CUBES; typedef struct centerlist { /* list of cube locations */ int i, j, k; /* cube location */ struct centerlist *next; /* remaining elements */ } CENTERLIST; typedef struct edgelist { /* list of edges */ int i1, j1, k1, i2, j2, k2; /* edge corner ids */ int vid; /* vertex id */ struct edgelist *next; /* remaining elements */ } EDGELIST; typedef struct intlist { /* list of integers */ int i; /* an integer */ struct intlist *next; /* remaining elements */ } INTLIST; typedef struct intlists { /* list of list of integers */ INTLIST *list; /* a list of integers */ struct intlists *next; /* remaining elements */ } INTLISTS; typedef struct Box { /* an AABB with pointer to metalelem */ float min[3], max[3]; const MetaElem *ml; } Box; typedef struct MetaballBVHNode { /* BVH node */ Box bb[2]; /* AABB of children */ struct MetaballBVHNode *child[2]; } MetaballBVHNode; typedef struct process { /* parameters, storage */ float thresh, size; /* mball threshold, single cube size */ float delta; /* small delta for calculating normals */ unsigned int converge_res; /* converge procedure resolution (more = slower) */ MetaElem **mainb; /* array of all metaelems */ unsigned int totelem, mem; /* number of metaelems */ MetaballBVHNode metaball_bvh; /* The simplest bvh */ Box allbb; /* Bounding box of all metaelems */ MetaballBVHNode **bvh_queue; /* Queue used during bvh traversal */ unsigned int bvh_queue_size; CUBES *cubes; /* stack of cubes waiting for polygonization */ CENTERLIST **centers; /* cube center hash table */ CORNER **corners; /* corner value hash table */ EDGELIST **edges; /* edge and vertex id hash table */ int (*indices)[4]; /* output indices */ unsigned int totindex; /* size of memory allocated for indices */ unsigned int curindex; /* number of currently added indices */ float (*co)[3], (*no)[3]; /* surface vertices - positions and normals */ unsigned int totvertex; /* memory size */ unsigned int curvertex; /* currently added vertices */ /* memory allocation from common pool */ MemArena *pgn_elements; } PROCESS; /* Forward declarations */ static int vertid(PROCESS *process, const CORNER *c1, const CORNER *c2); static void add_cube(PROCESS *process, int i, int j, int k); static void make_face(PROCESS *process, int i1, int i2, int i3, int i4); static void converge(PROCESS *process, const CORNER *c1, const CORNER *c2, float r_p[3]); /* ******************* SIMPLE BVH ********************* */ static void make_box_union(const BoundBox *a, const Box *b, Box *r_out) { r_out->min[0] = min_ff(a->vec[0][0], b->min[0]); r_out->min[1] = min_ff(a->vec[0][1], b->min[1]); r_out->min[2] = min_ff(a->vec[0][2], b->min[2]); r_out->max[0] = max_ff(a->vec[6][0], b->max[0]); r_out->max[1] = max_ff(a->vec[6][1], b->max[1]); r_out->max[2] = max_ff(a->vec[6][2], b->max[2]); } static void make_box_from_metaelem(Box *r, const MetaElem *ml) { copy_v3_v3(r->max, ml->bb->vec[6]); copy_v3_v3(r->min, ml->bb->vec[0]); r->ml = ml; } /** * Partitions part of mainb array [start, end) along axis s. Returns i, * where centroids of elements in the [start, i) segment lie "on the right side" of div, * and elements in the [i, end) segment lie "on the left" */ static unsigned int partition_mainb( MetaElem **mainb, unsigned int start, unsigned int end, unsigned int s, float div) { unsigned int i = start, j = end - 1; div *= 2.0f; while (1) { while (i < j && div > (mainb[i]->bb->vec[6][s] + mainb[i]->bb->vec[0][s])) { i++; } while (j > i && div < (mainb[j]->bb->vec[6][s] + mainb[j]->bb->vec[0][s])) { j--; } if (i >= j) { break; } SWAP(MetaElem *, mainb[i], mainb[j]); i++; j--; } if (i == start) { i++; } return i; } /** * Recursively builds a BVH, dividing elements along the middle of the longest axis of allbox. */ static void build_bvh_spatial(PROCESS *process, MetaballBVHNode *node, unsigned int start, unsigned int end, const Box *allbox) { unsigned int part, j, s; float dim[3], div; /* Maximum bvh queue size is number of nodes which are made, equals calls to this function. */ process->bvh_queue_size++; dim[0] = allbox->max[0] - allbox->min[0]; dim[1] = allbox->max[1] - allbox->min[1]; dim[2] = allbox->max[2] - allbox->min[2]; s = 0; if (dim[1] > dim[0] && dim[1] > dim[2]) { s = 1; } else if (dim[2] > dim[1] && dim[2] > dim[0]) { s = 2; } div = allbox->min[s] + (dim[s] / 2.0f); part = partition_mainb(process->mainb, start, end, s, div); make_box_from_metaelem(&node->bb[0], process->mainb[start]); node->child[0] = NULL; if (part > start + 1) { for (j = start; j < part; j++) { make_box_union(process->mainb[j]->bb, &node->bb[0], &node->bb[0]); } node->child[0] = BLI_memarena_alloc(process->pgn_elements, sizeof(MetaballBVHNode)); build_bvh_spatial(process, node->child[0], start, part, &node->bb[0]); } node->child[1] = NULL; if (part < end) { make_box_from_metaelem(&node->bb[1], process->mainb[part]); if (part < end - 1) { for (j = part; j < end; j++) { make_box_union(process->mainb[j]->bb, &node->bb[1], &node->bb[1]); } node->child[1] = BLI_memarena_alloc(process->pgn_elements, sizeof(MetaballBVHNode)); build_bvh_spatial(process, node->child[1], part, end, &node->bb[1]); } } else { INIT_MINMAX(node->bb[1].min, node->bb[1].max); } } /* ******************** ARITH ************************* */ /** * BASED AT CODE (but mostly rewritten) : * C code from the article * "An Implicit Surface Polygonizer" * by Jules Bloomenthal, jbloom@beauty.gmu.edu * in "Graphics Gems IV", Academic Press, 1994 * * Authored by Jules Bloomenthal, Xerox PARC. * Copyright (c) Xerox Corporation, 1991. All rights reserved. * Permission is granted to reproduce, use and distribute this code for * any and all purposes, provided that this notice appears in all copies. */ #define L 0 /* left direction: -x, -i */ #define R 1 /* right direction: +x, +i */ #define B 2 /* bottom direction: -y, -j */ #define T 3 /* top direction: +y, +j */ #define N 4 /* near direction: -z, -k */ #define F 5 /* far direction: +z, +k */ #define LBN 0 /* left bottom near corner */ #define LBF 1 /* left bottom far corner */ #define LTN 2 /* left top near corner */ #define LTF 3 /* left top far corner */ #define RBN 4 /* right bottom near corner */ #define RBF 5 /* right bottom far corner */ #define RTN 6 /* right top near corner */ #define RTF 7 /* right top far corner */ /** * the LBN corner of cube (i, j, k), corresponds with location * (i-0.5)*size, (j-0.5)*size, (k-0.5)*size) */ #define HASHBIT (5) #define HASHSIZE (size_t)(1 << (3 * HASHBIT)) /*! < hash table size (32768) */ #define HASH(i, j, k) ((((((i)&31) << 5) | ((j)&31)) << 5) | ((k)&31)) #define MB_BIT(i, bit) (((i) >> (bit)) & 1) // #define FLIP(i, bit) ((i) ^ 1 << (bit)) /* flip the given bit of i */ /* ******************** DENSITY COPMPUTATION ********************* */ /** * Computes density from given metaball at given position. * Metaball equation is: ``(1 - r^2 / R^2)^3 * s`` * * r = distance from center * R = metaball radius * s - metaball stiffness */ static float densfunc(const MetaElem *ball, float x, float y, float z) { float dist2; float dvec[3] = {x, y, z}; mul_m4_v3((float(*)[4])ball->imat, dvec); switch (ball->type) { case MB_BALL: /* do nothing */ break; case MB_CUBE: if (dvec[2] > ball->expz) { dvec[2] -= ball->expz; } else if (dvec[2] < -ball->expz) { dvec[2] += ball->expz; } else { dvec[2] = 0.0; } ATTR_FALLTHROUGH; case MB_PLANE: if (dvec[1] > ball->expy) { dvec[1] -= ball->expy; } else if (dvec[1] < -ball->expy) { dvec[1] += ball->expy; } else { dvec[1] = 0.0; } ATTR_FALLTHROUGH; case MB_TUBE: if (dvec[0] > ball->expx) { dvec[0] -= ball->expx; } else if (dvec[0] < -ball->expx) { dvec[0] += ball->expx; } else { dvec[0] = 0.0; } break; case MB_ELIPSOID: dvec[0] /= ball->expx; dvec[1] /= ball->expy; dvec[2] /= ball->expz; break; /* *** deprecated, could be removed?, do-versioned at least *** */ case MB_TUBEX: if (dvec[0] > ball->len) { dvec[0] -= ball->len; } else if (dvec[0] < -ball->len) { dvec[0] += ball->len; } else { dvec[0] = 0.0; } break; case MB_TUBEY: if (dvec[1] > ball->len) { dvec[1] -= ball->len; } else if (dvec[1] < -ball->len) { dvec[1] += ball->len; } else { dvec[1] = 0.0; } break; case MB_TUBEZ: if (dvec[2] > ball->len) { dvec[2] -= ball->len; } else if (dvec[2] < -ball->len) { dvec[2] += ball->len; } else { dvec[2] = 0.0; } break; /* *** end deprecated *** */ } /* ball->rad2 is inverse of squared rad */ dist2 = 1.0f - (len_squared_v3(dvec) * ball->rad2); /* ball->s is negative if metaball is negative */ return (dist2 < 0.0f) ? 0.0f : (ball->s * dist2 * dist2 * dist2); } /** * Computes density at given position form all metaballs which contain this point in their box. * Traverses BVH using a queue. */ static float metaball(PROCESS *process, float x, float y, float z) { int i; float dens = 0.0f; unsigned int front = 0, back = 0; MetaballBVHNode *node; process->bvh_queue[front++] = &process->metaball_bvh; while (front != back) { node = process->bvh_queue[back++]; for (i = 0; i < 2; i++) { if ((node->bb[i].min[0] <= x) && (node->bb[i].max[0] >= x) && (node->bb[i].min[1] <= y) && (node->bb[i].max[1] >= y) && (node->bb[i].min[2] <= z) && (node->bb[i].max[2] >= z)) { if (node->child[i]) { process->bvh_queue[front++] = node->child[i]; } else { dens += densfunc(node->bb[i].ml, x, y, z); } } } } return process->thresh - dens; } /** * Adds face to indices, expands memory if needed. */ static void make_face(PROCESS *process, int i1, int i2, int i3, int i4) { int *cur; #ifdef USE_ACCUM_NORMAL float n[3]; #endif if (UNLIKELY(process->totindex == process->curindex)) { process->totindex += 4096; process->indices = MEM_reallocN(process->indices, sizeof(int[4]) * process->totindex); } cur = process->indices[process->curindex++]; /* displists now support array drawing, we treat tri's as fake quad */ cur[0] = i1; cur[1] = i2; cur[2] = i3; cur[3] = i4; #ifdef USE_ACCUM_NORMAL if (i4 == i3) { normal_tri_v3(n, process->co[i1], process->co[i2], process->co[i3]); accumulate_vertex_normals_v3(process->no[i1], process->no[i2], process->no[i3], NULL, n, process->co[i1], process->co[i2], process->co[i3], NULL); } else { normal_quad_v3(n, process->co[i1], process->co[i2], process->co[i3], process->co[i4]); accumulate_vertex_normals_v3(process->no[i1], process->no[i2], process->no[i3], process->no[i4], n, process->co[i1], process->co[i2], process->co[i3], process->co[i4]); } #endif } /* Frees allocated memory */ static void freepolygonize(PROCESS *process) { if (process->corners) { MEM_freeN(process->corners); } if (process->edges) { MEM_freeN(process->edges); } if (process->centers) { MEM_freeN(process->centers); } if (process->mainb) { MEM_freeN(process->mainb); } if (process->bvh_queue) { MEM_freeN(process->bvh_queue); } if (process->pgn_elements) { BLI_memarena_free(process->pgn_elements); } } /* **************** POLYGONIZATION ************************ */ /**** Cubical Polygonization (optional) ****/ #define LB 0 /* left bottom edge */ #define LT 1 /* left top edge */ #define LN 2 /* left near edge */ #define LF 3 /* left far edge */ #define RB 4 /* right bottom edge */ #define RT 5 /* right top edge */ #define RN 6 /* right near edge */ #define RF 7 /* right far edge */ #define BN 8 /* bottom near edge */ #define BF 9 /* bottom far edge */ #define TN 10 /* top near edge */ #define TF 11 /* top far edge */ static INTLISTS *cubetable[256]; static char faces[256]; /* edge: LB, LT, LN, LF, RB, RT, RN, RF, BN, BF, TN, TF */ static int corner1[12] = { LBN, LTN, LBN, LBF, RBN, RTN, RBN, RBF, LBN, LBF, LTN, LTF, }; static int corner2[12] = { LBF, LTF, LTN, LTF, RBF, RTF, RTN, RTF, RBN, RBF, RTN, RTF, }; static int leftface[12] = { B, L, L, F, R, T, N, R, N, B, T, F, }; /* face on left when going corner1 to corner2 */ static int rightface[12] = { L, T, N, L, B, R, R, F, B, F, N, T, }; /* face on right when going corner1 to corner2 */ /** * triangulate the cube directly, without decomposition */ static void docube(PROCESS *process, CUBE *cube) { INTLISTS *polys; CORNER *c1, *c2; int i, index = 0, count, indexar[8]; /* Determine which case cube falls into. */ for (i = 0; i < 8; i++) { if (cube->corners[i]->value > 0.0f) { index += (1 << i); } } /* Using faces[] table, adds neighboring cube if surface intersects face in this direction. */ if (MB_BIT(faces[index], 0)) { add_cube(process, cube->i - 1, cube->j, cube->k); } if (MB_BIT(faces[index], 1)) { add_cube(process, cube->i + 1, cube->j, cube->k); } if (MB_BIT(faces[index], 2)) { add_cube(process, cube->i, cube->j - 1, cube->k); } if (MB_BIT(faces[index], 3)) { add_cube(process, cube->i, cube->j + 1, cube->k); } if (MB_BIT(faces[index], 4)) { add_cube(process, cube->i, cube->j, cube->k - 1); } if (MB_BIT(faces[index], 5)) { add_cube(process, cube->i, cube->j, cube->k + 1); } /* Using cubetable[], determines polygons for output. */ for (polys = cubetable[index]; polys; polys = polys->next) { INTLIST *edges; count = 0; /* Sets needed vertex id's lying on the edges. */ for (edges = polys->list; edges; edges = edges->next) { c1 = cube->corners[corner1[edges->i]]; c2 = cube->corners[corner2[edges->i]]; indexar[count] = vertid(process, c1, c2); count++; } /* Adds faces to output. */ if (count > 2) { switch (count) { case 3: make_face(process, indexar[2], indexar[1], indexar[0], indexar[0]); /* triangle */ break; case 4: make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]); break; case 5: make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]); make_face(process, indexar[4], indexar[3], indexar[0], indexar[0]); /* triangle */ break; case 6: make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]); make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]); break; case 7: make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]); make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]); make_face(process, indexar[6], indexar[5], indexar[0], indexar[0]); /* triangle */ break; } } } } /** * return corner with the given lattice location * set (and cache) its function value */ static CORNER *setcorner(PROCESS *process, int i, int j, int k) { /* for speed, do corner value caching here */ CORNER *c; int index; /* does corner exist? */ index = HASH(i, j, k); c = process->corners[index]; for (; c != NULL; c = c->next) { if (c->i == i && c->j == j && c->k == k) { return c; } } c = BLI_memarena_alloc(process->pgn_elements, sizeof(CORNER)); c->i = i; c->co[0] = ((float)i - 0.5f) * process->size; c->j = j; c->co[1] = ((float)j - 0.5f) * process->size; c->k = k; c->co[2] = ((float)k - 0.5f) * process->size; c->value = metaball(process, c->co[0], c->co[1], c->co[2]); c->next = process->corners[index]; process->corners[index] = c; return c; } /** * return next clockwise edge from given edge around given face */ static int nextcwedge(int edge, int face) { switch (edge) { case LB: return (face == L) ? LF : BN; case LT: return (face == L) ? LN : TF; case LN: return (face == L) ? LB : TN; case LF: return (face == L) ? LT : BF; case RB: return (face == R) ? RN : BF; case RT: return (face == R) ? RF : TN; case RN: return (face == R) ? RT : BN; case RF: return (face == R) ? RB : TF; case BN: return (face == B) ? RB : LN; case BF: return (face == B) ? LB : RF; case TN: return (face == T) ? LT : RN; case TF: return (face == T) ? RT : LF; } return 0; } /** * \return the face adjoining edge that is not the given face */ static int otherface(int edge, int face) { int other = leftface[edge]; return face == other ? rightface[edge] : other; } /** * create the 256 entry table for cubical polygonization */ static void makecubetable(void) { static bool is_done = false; int i, e, c, done[12], pos[8]; if (is_done) { return; } is_done = true; for (i = 0; i < 256; i++) { for (e = 0; e < 12; e++) { done[e] = 0; } for (c = 0; c < 8; c++) { pos[c] = MB_BIT(i, c); } for (e = 0; e < 12; e++) { if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) { INTLIST *ints = NULL; INTLISTS *lists = MEM_callocN(sizeof(INTLISTS), "mball_intlist"); int start = e, edge = e; /* get face that is to right of edge from pos to neg corner: */ int face = pos[corner1[e]] ? rightface[e] : leftface[e]; while (1) { edge = nextcwedge(edge, face); done[edge] = 1; if (pos[corner1[edge]] != pos[corner2[edge]]) { INTLIST *tmp = ints; ints = MEM_callocN(sizeof(INTLIST), "mball_intlist"); ints->i = edge; ints->next = tmp; /* add edge to head of list */ if (edge == start) { break; } face = otherface(edge, face); } } lists->list = ints; /* add ints to head of table entry */ lists->next = cubetable[i]; cubetable[i] = lists; } } } for (i = 0; i < 256; i++) { INTLISTS *polys; faces[i] = 0; for (polys = cubetable[i]; polys; polys = polys->next) { INTLIST *edges; for (edges = polys->list; edges; edges = edges->next) { if (edges->i == LB || edges->i == LT || edges->i == LN || edges->i == LF) { faces[i] |= 1 << L; } if (edges->i == RB || edges->i == RT || edges->i == RN || edges->i == RF) { faces[i] |= 1 << R; } if (edges->i == LB || edges->i == RB || edges->i == BN || edges->i == BF) { faces[i] |= 1 << B; } if (edges->i == LT || edges->i == RT || edges->i == TN || edges->i == TF) { faces[i] |= 1 << T; } if (edges->i == LN || edges->i == RN || edges->i == BN || edges->i == TN) { faces[i] |= 1 << N; } if (edges->i == LF || edges->i == RF || edges->i == BF || edges->i == TF) { faces[i] |= 1 << F; } } } } } void BKE_mball_cubeTable_free(void) { int i; INTLISTS *lists, *nlists; INTLIST *ints, *nints; for (i = 0; i < 256; i++) { lists = cubetable[i]; while (lists) { nlists = lists->next; ints = lists->list; while (ints) { nints = ints->next; MEM_freeN(ints); ints = nints; } MEM_freeN(lists); lists = nlists; } cubetable[i] = NULL; } } /**** Storage ****/ /** * Inserts cube at lattice i, j, k into hash table, marking it as "done" */ static int setcenter(PROCESS *process, CENTERLIST *table[], const int i, const int j, const int k) { int index; CENTERLIST *newc, *l, *q; index = HASH(i, j, k); q = table[index]; for (l = q; l != NULL; l = l->next) { if (l->i == i && l->j == j && l->k == k) { return 1; } } newc = BLI_memarena_alloc(process->pgn_elements, sizeof(CENTERLIST)); newc->i = i; newc->j = j; newc->k = k; newc->next = q; table[index] = newc; return 0; } /** * Sets vid of vertex lying on given edge. */ static void setedge(PROCESS *process, int i1, int j1, int k1, int i2, int j2, int k2, int vid) { int index; EDGELIST *newe; if (i1 > i2 || (i1 == i2 && (j1 > j2 || (j1 == j2 && k1 > k2)))) { int t = i1; i1 = i2; i2 = t; t = j1; j1 = j2; j2 = t; t = k1; k1 = k2; k2 = t; } index = HASH(i1, j1, k1) + HASH(i2, j2, k2); newe = BLI_memarena_alloc(process->pgn_elements, sizeof(EDGELIST)); newe->i1 = i1; newe->j1 = j1; newe->k1 = k1; newe->i2 = i2; newe->j2 = j2; newe->k2 = k2; newe->vid = vid; newe->next = process->edges[index]; process->edges[index] = newe; } /** * \return vertex id for edge; return -1 if not set */ static int getedge(EDGELIST *table[], int i1, int j1, int k1, int i2, int j2, int k2) { EDGELIST *q; if (i1 > i2 || (i1 == i2 && (j1 > j2 || (j1 == j2 && k1 > k2)))) { int t = i1; i1 = i2; i2 = t; t = j1; j1 = j2; j2 = t; t = k1; k1 = k2; k2 = t; } q = table[HASH(i1, j1, k1) + HASH(i2, j2, k2)]; for (; q != NULL; q = q->next) { if (q->i1 == i1 && q->j1 == j1 && q->k1 == k1 && q->i2 == i2 && q->j2 == j2 && q->k2 == k2) { return q->vid; } } return -1; } /** * Adds a vertex, expands memory if needed. */ static void addtovertices(PROCESS *process, const float v[3], const float no[3]) { if (process->curvertex == process->totvertex) { process->totvertex += 4096; process->co = MEM_reallocN(process->co, process->totvertex * sizeof(float[3])); process->no = MEM_reallocN(process->no, process->totvertex * sizeof(float[3])); } copy_v3_v3(process->co[process->curvertex], v); copy_v3_v3(process->no[process->curvertex], no); process->curvertex++; } #ifndef USE_ACCUM_NORMAL /** * Computes normal from density field at given point. * * \note Doesn't do normalization! */ static void vnormal(PROCESS *process, const float point[3], float r_no[3]) { const float delta = process->delta; const float f = metaball(process, point[0], point[1], point[2]); r_no[0] = metaball(process, point[0] + delta, point[1], point[2]) - f; r_no[1] = metaball(process, point[0], point[1] + delta, point[2]) - f; r_no[2] = metaball(process, point[0], point[1], point[2] + delta) - f; } #endif /* USE_ACCUM_NORMAL */ /** * \return the id of vertex between two corners. * * If it wasn't previously computed, does #converge() and adds vertex to process. */ static int vertid(PROCESS *process, const CORNER *c1, const CORNER *c2) { float v[3], no[3]; int vid = getedge(process->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k); if (vid != -1) { return vid; /* previously computed */ } converge(process, c1, c2, v); /* position */ #ifdef USE_ACCUM_NORMAL zero_v3(no); #else vnormal(process, v, no); #endif addtovertices(process, v, no); /* save vertex */ vid = (int)process->curvertex - 1; setedge(process, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k, vid); return vid; } /** * Given two corners, computes approximation of surface intersection point between them. * In case of small threshold, do bisection. */ static void converge(PROCESS *process, const CORNER *c1, const CORNER *c2, float r_p[3]) { float tmp, dens; unsigned int i; float c1_value, c1_co[3]; float c2_value, c2_co[3]; if (c1->value < c2->value) { c1_value = c2->value; copy_v3_v3(c1_co, c2->co); c2_value = c1->value; copy_v3_v3(c2_co, c1->co); } else { c1_value = c1->value; copy_v3_v3(c1_co, c1->co); c2_value = c2->value; copy_v3_v3(c2_co, c2->co); } for (i = 0; i < process->converge_res; i++) { interp_v3_v3v3(r_p, c1_co, c2_co, 0.5f); dens = metaball(process, r_p[0], r_p[1], r_p[2]); if (dens > 0.0f) { c1_value = dens; copy_v3_v3(c1_co, r_p); } else { c2_value = dens; copy_v3_v3(c2_co, r_p); } } tmp = -c1_value / (c2_value - c1_value); interp_v3_v3v3(r_p, c1_co, c2_co, tmp); } /** * Adds cube at given lattice position to cube stack of process. */ static void add_cube(PROCESS *process, int i, int j, int k) { CUBES *ncube; int n; /* test if cube has been found before */ if (setcenter(process, process->centers, i, j, k) == 0) { /* push cube on stack: */ ncube = BLI_memarena_alloc(process->pgn_elements, sizeof(CUBES)); ncube->next = process->cubes; process->cubes = ncube; ncube->cube.i = i; ncube->cube.j = j; ncube->cube.k = k; /* set corners of initial cube: */ for (n = 0; n < 8; n++) { ncube->cube.corners[n] = setcorner( process, i + MB_BIT(n, 2), j + MB_BIT(n, 1), k + MB_BIT(n, 0)); } } } static void next_lattice(int r[3], const float pos[3], const float size) { r[0] = (int)ceil((pos[0] / size) + 0.5f); r[1] = (int)ceil((pos[1] / size) + 0.5f); r[2] = (int)ceil((pos[2] / size) + 0.5f); } static void prev_lattice(int r[3], const float pos[3], const float size) { next_lattice(r, pos, size); r[0]--; r[1]--; r[2]--; } static void closest_latice(int r[3], const float pos[3], const float size) { r[0] = (int)floorf(pos[0] / size + 1.0f); r[1] = (int)floorf(pos[1] / size + 1.0f); r[2] = (int)floorf(pos[2] / size + 1.0f); } /** * Find at most 26 cubes to start polygonization from. */ static void find_first_points(PROCESS *process, const unsigned int em) { const MetaElem *ml; int center[3], lbn[3], rtf[3], it[3], dir[3], add[3]; float tmp[3], a, b; ml = process->mainb[em]; mid_v3_v3v3(tmp, ml->bb->vec[0], ml->bb->vec[6]); closest_latice(center, tmp, process->size); prev_lattice(lbn, ml->bb->vec[0], process->size); next_lattice(rtf, ml->bb->vec[6], process->size); for (dir[0] = -1; dir[0] <= 1; dir[0]++) { for (dir[1] = -1; dir[1] <= 1; dir[1]++) { for (dir[2] = -1; dir[2] <= 1; dir[2]++) { if (dir[0] == 0 && dir[1] == 0 && dir[2] == 0) { continue; } copy_v3_v3_int(it, center); b = setcorner(process, it[0], it[1], it[2])->value; do { it[0] += dir[0]; it[1] += dir[1]; it[2] += dir[2]; a = b; b = setcorner(process, it[0], it[1], it[2])->value; if (a * b < 0.0f) { add[0] = it[0] - dir[0]; add[1] = it[1] - dir[1]; add[2] = it[2] - dir[2]; DO_MIN(it, add); add_cube(process, add[0], add[1], add[2]); break; } } while ((it[0] > lbn[0]) && (it[1] > lbn[1]) && (it[2] > lbn[2]) && (it[0] < rtf[0]) && (it[1] < rtf[1]) && (it[2] < rtf[2])); } } } } /** * The main polygonization proc. * Allocates memory, makes cubetable, * finds starting surface points * and processes cubes on the stack until none left. */ static void polygonize(PROCESS *process) { CUBE c; unsigned int i; process->centers = MEM_callocN(HASHSIZE * sizeof(CENTERLIST *), "mbproc->centers"); process->corners = MEM_callocN(HASHSIZE * sizeof(CORNER *), "mbproc->corners"); process->edges = MEM_callocN(2 * HASHSIZE * sizeof(EDGELIST *), "mbproc->edges"); process->bvh_queue = MEM_callocN(sizeof(MetaballBVHNode *) * process->bvh_queue_size, "Metaball BVH Queue"); makecubetable(); for (i = 0; i < process->totelem; i++) { find_first_points(process, i); } while (process->cubes != NULL) { c = process->cubes->cube; process->cubes = process->cubes->next; docube(process, &c); } } /** * Iterates over ALL objects in the scene and all of its sets, including * making all duplis(not only metas). Copies metas to mainb array. * Computes bounding boxes for building BVH. */ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Object *ob) { Scene *sce_iter = scene; Base *base; Object *bob; MetaBall *mb; const MetaElem *ml; float obinv[4][4], obmat[4][4]; unsigned int i; int obnr, zero_size = 0; char obname[MAX_ID_NAME]; SceneBaseIter iter; copy_m4_m4(obmat, ob->obmat); /* to cope with duplicators from BKE_scene_base_iter_next */ invert_m4_m4(obinv, ob->obmat); BLI_split_name_num(obname, &obnr, ob->id.name + 2, '.'); /* make main array */ BKE_scene_base_iter_next(depsgraph, &iter, &sce_iter, 0, NULL, NULL); while (BKE_scene_base_iter_next(depsgraph, &iter, &sce_iter, 1, &base, &bob)) { if (bob->type == OB_MBALL) { zero_size = 0; ml = NULL; if (bob == ob && (base->flag_legacy & OB_FROMDUPLI) == 0) { mb = ob->data; if (mb->editelems) { ml = mb->editelems->first; } else { ml = mb->elems.first; } } else { char name[MAX_ID_NAME]; int nr; BLI_split_name_num(name, &nr, bob->id.name + 2, '.'); if (STREQ(obname, name)) { mb = bob->data; if (mb->editelems) { ml = mb->editelems->first; } else { ml = mb->elems.first; } } } /* when metaball object has zero scale, then MetaElem to this MetaBall * will not be put to mainb array */ if (has_zero_axis_m4(bob->obmat)) { zero_size = 1; } else if (bob->parent) { struct Object *pob = bob->parent; while (pob) { if (has_zero_axis_m4(pob->obmat)) { zero_size = 1; break; } pob = pob->parent; } } if (zero_size) { while (ml) { ml = ml->next; } } else { while (ml) { if (!(ml->flag & MB_HIDE)) { float pos[4][4], rot[4][4]; float expx, expy, expz; float tempmin[3], tempmax[3]; MetaElem *new_ml; /* make a copy because of duplicates */ new_ml = BLI_memarena_alloc(process->pgn_elements, sizeof(MetaElem)); *(new_ml) = *ml; new_ml->bb = BLI_memarena_alloc(process->pgn_elements, sizeof(BoundBox)); new_ml->mat = BLI_memarena_alloc(process->pgn_elements, 4 * 4 * sizeof(float)); new_ml->imat = BLI_memarena_alloc(process->pgn_elements, 4 * 4 * sizeof(float)); /* too big stiffness seems only ugly due to linear interpolation * no need to have possibility for too big stiffness */ if (ml->s > 10.0f) { new_ml->s = 10.0f; } else { new_ml->s = ml->s; } /* if metaball is negative, set stiffness negative */ if (new_ml->flag & MB_NEGATIVE) { new_ml->s = -new_ml->s; } /* Translation of MetaElem */ unit_m4(pos); pos[3][0] = ml->x; pos[3][1] = ml->y; pos[3][2] = ml->z; /* Rotation of MetaElem is stored in quat */ quat_to_mat4(rot, ml->quat); /* Matrix multiply is as follows: * basis object space -> * world -> * ml object space -> * position -> * rotation -> * ml local space */ mul_m4_series((float(*)[4])new_ml->mat, obinv, bob->obmat, pos, rot); /* ml local space -> basis object space */ invert_m4_m4((float(*)[4])new_ml->imat, (float(*)[4])new_ml->mat); /* rad2 is inverse of squared radius */ new_ml->rad2 = 1 / (ml->rad * ml->rad); /* initial dimensions = radius */ expx = ml->rad; expy = ml->rad; expz = ml->rad; switch (ml->type) { case MB_BALL: break; case MB_CUBE: /* cube is "expanded" by expz, expy and expx */ expz += ml->expz; ATTR_FALLTHROUGH; case MB_PLANE: /* plane is "expanded" by expy and expx */ expy += ml->expy; ATTR_FALLTHROUGH; case MB_TUBE: /* tube is "expanded" by expx */ expx += ml->expx; break; case MB_ELIPSOID: /* ellipsoid is "stretched" by exp* */ expx *= ml->expx; expy *= ml->expy; expz *= ml->expz; break; } /* untransformed Bounding Box of MetaElem */ /* TODO, its possible the elem type has been changed and the exp* * values can use a fallback. */ copy_v3_fl3(new_ml->bb->vec[0], -expx, -expy, -expz); /* 0 */ copy_v3_fl3(new_ml->bb->vec[1], +expx, -expy, -expz); /* 1 */ copy_v3_fl3(new_ml->bb->vec[2], +expx, +expy, -expz); /* 2 */ copy_v3_fl3(new_ml->bb->vec[3], -expx, +expy, -expz); /* 3 */ copy_v3_fl3(new_ml->bb->vec[4], -expx, -expy, +expz); /* 4 */ copy_v3_fl3(new_ml->bb->vec[5], +expx, -expy, +expz); /* 5 */ copy_v3_fl3(new_ml->bb->vec[6], +expx, +expy, +expz); /* 6 */ copy_v3_fl3(new_ml->bb->vec[7], -expx, +expy, +expz); /* 7 */ /* transformation of Metalem bb */ for (i = 0; i < 8; i++) { mul_m4_v3((float(*)[4])new_ml->mat, new_ml->bb->vec[i]); } /* find max and min of transformed bb */ INIT_MINMAX(tempmin, tempmax); for (i = 0; i < 8; i++) { DO_MINMAX(new_ml->bb->vec[i], tempmin, tempmax); } /* set only point 0 and 6 - AABB of Metaelem */ copy_v3_v3(new_ml->bb->vec[0], tempmin); copy_v3_v3(new_ml->bb->vec[6], tempmax); /* add new_ml to mainb[] */ if (UNLIKELY(process->totelem == process->mem)) { process->mem = process->mem * 2 + 10; process->mainb = MEM_reallocN(process->mainb, sizeof(MetaElem *) * process->mem); } process->mainb[process->totelem++] = new_ml; } ml = ml->next; } } } } /* compute AABB of all Metaelems */ if (process->totelem > 0) { copy_v3_v3(process->allbb.min, process->mainb[0]->bb->vec[0]); copy_v3_v3(process->allbb.max, process->mainb[0]->bb->vec[6]); for (i = 1; i < process->totelem; i++) { make_box_union(process->mainb[i]->bb, &process->allbb, &process->allbb); } } } void BKE_mball_polygonize(Depsgraph *depsgraph, Scene *scene, Object *ob, ListBase *dispbase) { MetaBall *mb; DispList *dl; unsigned int a; PROCESS process = {0}; bool is_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER; mb = ob->data; process.thresh = mb->thresh; if (process.thresh < 0.001f) { process.converge_res = 16; } else if (process.thresh < 0.01f) { process.converge_res = 8; } else if (process.thresh < 0.1f) { process.converge_res = 4; } else { process.converge_res = 2; } if (!is_render && (mb->flag == MB_UPDATE_NEVER)) { return; } if ((G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) && mb->flag == MB_UPDATE_FAST) { return; } if (is_render) { process.size = mb->rendersize; } else { process.size = mb->wiresize; if ((G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) && mb->flag == MB_UPDATE_HALFRES) { process.size *= 2.0f; } } process.delta = process.size * 0.001f; process.pgn_elements = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "Metaball memarena"); /* initialize all mainb (MetaElems) */ init_meta(depsgraph, &process, scene, ob); if (process.totelem > 0) { build_bvh_spatial(&process, &process.metaball_bvh, 0, process.totelem, &process.allbb); /* Don't polygonize metaballs with too high resolution (base mball to small) * note: Eps was 0.0001f but this was giving problems for blood animation for durian, * using 0.00001f. */ if (ob->scale[0] > 0.00001f * (process.allbb.max[0] - process.allbb.min[0]) || ob->scale[1] > 0.00001f * (process.allbb.max[1] - process.allbb.min[1]) || ob->scale[2] > 0.00001f * (process.allbb.max[2] - process.allbb.min[2])) { polygonize(&process); /* add resulting surface to displist */ if (process.curindex) { dl = MEM_callocN(sizeof(DispList), "mballdisp"); BLI_addtail(dispbase, dl); dl->type = DL_INDEX4; dl->nr = (int)process.curvertex; dl->parts = (int)process.curindex; dl->index = (int *)process.indices; for (a = 0; a < process.curvertex; a++) { normalize_v3(process.no[a]); } dl->verts = (float *)process.co; dl->nors = (float *)process.no; } } } freepolygonize(&process); }
27.495563
98
0.544624
[ "object" ]
ca2980262db1917bdf5314fc52f406001bb7d606
8,749
h
C
sdk/js/include/nsIDOMSVGLengthList.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/js/include/nsIDOMSVGLengthList.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/js/include/nsIDOMSVGLengthList.h
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM d:/firefox-5.0.1/mozilla-release/dom/interfaces/svg/nsIDOMSVGLengthList.idl */ #ifndef __gen_nsIDOMSVGLengthList_h__ #define __gen_nsIDOMSVGLengthList_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIDOMSVGLength; /* forward declaration */ /* starting interface: nsIDOMSVGLengthList */ #define NS_IDOMSVGLENGTHLIST_IID_STR "f8c89734-d6b4-4a56-bdf5-1ce1104dc1ab" #define NS_IDOMSVGLENGTHLIST_IID \ {0xf8c89734, 0xd6b4, 0x4a56, \ { 0xbd, 0xf5, 0x1c, 0xe1, 0x10, 0x4d, 0xc1, 0xab }} class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGLengthList : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGLENGTHLIST_IID) /* readonly attribute unsigned long numberOfItems; */ NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) = 0; /* readonly attribute unsigned long length; */ NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) = 0; /* void clear (); */ NS_SCRIPTABLE NS_IMETHOD Clear(void) = 0; /* nsIDOMSVGLength initialize (in nsIDOMSVGLength newItem); */ NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; /* nsIDOMSVGLength getItem (in unsigned long index); */ NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; /* nsIDOMSVGLength insertItemBefore (in nsIDOMSVGLength newItem, in unsigned long index); */ NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; /* nsIDOMSVGLength replaceItem (in nsIDOMSVGLength newItem, in unsigned long index); */ NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; /* nsIDOMSVGLength removeItem (in unsigned long index); */ NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; /* nsIDOMSVGLength appendItem (in nsIDOMSVGLength newItem); */ NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGLengthList, NS_IDOMSVGLENGTHLIST_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMSVGLENGTHLIST \ NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems); \ NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength); \ NS_SCRIPTABLE NS_IMETHOD Clear(void); \ NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMSVGLENGTHLIST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) { return _to GetNumberOfItems(aNumberOfItems); } \ NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) { return _to GetLength(aLength); } \ NS_SCRIPTABLE NS_IMETHOD Clear(void) { return _to Clear(); } \ NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to Initialize(newItem, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to GetItem(index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to InsertItemBefore(newItem, index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to ReplaceItem(newItem, index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to RemoveItem(index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return _to AppendItem(newItem, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMSVGLENGTHLIST(_to) \ NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNumberOfItems(aNumberOfItems); } \ NS_SCRIPTABLE NS_IMETHOD GetLength(PRUint32 *aLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLength(aLength); } \ NS_SCRIPTABLE NS_IMETHOD Clear(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Clear(); } \ NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Initialize(newItem, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetItem(index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->InsertItemBefore(newItem, index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceItem(newItem, index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveItem(index, _retval); } \ NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->AppendItem(newItem, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMSVGLengthList : public nsIDOMSVGLengthList { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMSVGLENGTHLIST nsDOMSVGLengthList(); private: ~nsDOMSVGLengthList(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMSVGLengthList, nsIDOMSVGLengthList) nsDOMSVGLengthList::nsDOMSVGLengthList() { /* member initializers and constructor code */ } nsDOMSVGLengthList::~nsDOMSVGLengthList() { /* destructor code */ } /* readonly attribute unsigned long numberOfItems; */ NS_IMETHODIMP nsDOMSVGLengthList::GetNumberOfItems(PRUint32 *aNumberOfItems) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long length; */ NS_IMETHODIMP nsDOMSVGLengthList::GetLength(PRUint32 *aLength) { return NS_ERROR_NOT_IMPLEMENTED; } /* void clear (); */ NS_IMETHODIMP nsDOMSVGLengthList::Clear() { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength initialize (in nsIDOMSVGLength newItem); */ NS_IMETHODIMP nsDOMSVGLengthList::Initialize(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength getItem (in unsigned long index); */ NS_IMETHODIMP nsDOMSVGLengthList::GetItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength insertItemBefore (in nsIDOMSVGLength newItem, in unsigned long index); */ NS_IMETHODIMP nsDOMSVGLengthList::InsertItemBefore(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength replaceItem (in nsIDOMSVGLength newItem, in unsigned long index); */ NS_IMETHODIMP nsDOMSVGLengthList::ReplaceItem(nsIDOMSVGLength *newItem, PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength removeItem (in unsigned long index); */ NS_IMETHODIMP nsDOMSVGLengthList::RemoveItem(PRUint32 index, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIDOMSVGLength appendItem (in nsIDOMSVGLength newItem); */ NS_IMETHODIMP nsDOMSVGLengthList::AppendItem(nsIDOMSVGLength *newItem, nsIDOMSVGLength **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMSVGLengthList_h__ */
46.047368
216
0.792891
[ "object" ]
ca2f0f02c741d3ad45febbb884dfc004c1115ecc
14,830
c
C
src/coap_tinydtls.c
syafiq/libcoap-smack
b3acb320785f3d50a8c1e1a06057d5a4392407df
[ "OpenSSL" ]
2
2021-10-05T02:34:18.000Z
2022-01-18T15:22:41.000Z
src/coap_tinydtls.c
syafiq/libcoap-smack
b3acb320785f3d50a8c1e1a06057d5a4392407df
[ "OpenSSL" ]
1
2021-06-24T04:27:40.000Z
2021-06-24T04:27:40.000Z
src/coap_tinydtls.c
syafiq/libcoap-smack
b3acb320785f3d50a8c1e1a06057d5a4392407df
[ "OpenSSL" ]
2
2021-06-24T04:08:28.000Z
2022-03-07T06:37:24.000Z
/* * coap_tinydtls.c -- Datagram Transport Layer Support for libcoap with tinydtls * * Copyright (C) 2016 Olaf Bergmann <bergmann@tzi.org> * * This file is part of the CoAP library libcoap. Please see README for terms * of use. */ #include "coap_internal.h" #ifdef HAVE_LIBTINYDTLS /* We want TinyDTLS versions of these, not libcoap versions */ #undef PACKAGE_BUGREPORT #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_URL #undef PACKAGE_VERSION #include <tinydtls.h> #include <dtls.h> #include <dtls_debug.h> static dtls_tick_t dtls_tick_0 = 0; static coap_tick_t coap_tick_0 = 0; int coap_dtls_is_supported(void) { return 1; } void coap_dtls_startup(void) { dtls_init(); dtls_ticks(&dtls_tick_0); coap_ticks(&coap_tick_0); } void coap_dtls_set_log_level(int level) { dtls_set_log_level(level); } int coap_dtls_get_log_level(void) { return dtls_get_log_level(); } static void get_session_addr(const session_t *s, coap_address_t *a) { #ifdef WITH_CONTIKI a->addr = s->addr; a->port = s->port; #else if (s->addr.sa.sa_family == AF_INET6) { a->size = (socklen_t)sizeof(a->addr.sin6); a->addr.sin6 = s->addr.sin6; } else if (s->addr.sa.sa_family == AF_INET) { a->size = (socklen_t)sizeof(a->addr.sin); a->addr.sin = s->addr.sin; } else { a->size = (socklen_t)s->size; a->addr.sa = s->addr.sa; } #endif } static void put_session_addr(const coap_address_t *a, session_t *s) { #ifdef WITH_CONTIKI s->size = (unsigned char)sizeof(s->addr); s->addr = a->addr; s->port = a->port; #else if (a->addr.sa.sa_family == AF_INET6) { s->size = (socklen_t)sizeof(s->addr.sin6); s->addr.sin6 = a->addr.sin6; } else if (a->addr.sa.sa_family == AF_INET) { s->size = (socklen_t)sizeof(s->addr.sin); s->addr.sin = a->addr.sin; } else { s->size = (socklen_t)a->size; s->addr.sa = a->addr.sa; } #endif } static int dtls_send_to_peer(struct dtls_context_t *dtls_context, session_t *dtls_session, uint8 *data, size_t len) { coap_context_t *coap_context = (coap_context_t *)dtls_get_app_data(dtls_context); coap_session_t *coap_session; coap_address_t remote_addr; get_session_addr(dtls_session, &remote_addr); coap_session = coap_session_get_by_peer(coap_context, &remote_addr, dtls_session->ifindex); if (!coap_session) { coap_log(LOG_WARNING, "dtls_send_to_peer: cannot find local interface\n"); return -3; } return (int)coap_session_send(coap_session, data, len); } static int dtls_application_data(struct dtls_context_t *dtls_context, session_t *dtls_session, uint8 *data, size_t len) { coap_context_t *coap_context = (coap_context_t *)dtls_get_app_data(dtls_context); coap_session_t *coap_session; coap_address_t remote_addr; get_session_addr(dtls_session, &remote_addr); coap_session = coap_session_get_by_peer(coap_context, &remote_addr, dtls_session->ifindex); if (!coap_session) { coap_log(LOG_DEBUG, "dropped message that was received on invalid interface\n"); return -1; } return coap_handle_dgram(coap_context, coap_session, data, len); } static int coap_event_dtls = 0; static int dtls_event(struct dtls_context_t *dtls_context, session_t *dtls_session, dtls_alert_level_t level, uint16_t code) { (void)dtls_context; (void)dtls_session; if (level == DTLS_ALERT_LEVEL_FATAL) coap_event_dtls = COAP_EVENT_DTLS_ERROR; /* handle DTLS events */ switch (code) { case DTLS_ALERT_CLOSE_NOTIFY: { coap_event_dtls = COAP_EVENT_DTLS_CLOSED; break; } case DTLS_EVENT_CONNECTED: { coap_event_dtls = COAP_EVENT_DTLS_CONNECTED; break; } case DTLS_EVENT_RENEGOTIATE: { coap_event_dtls = COAP_EVENT_DTLS_RENEGOTIATE; break; } default: ; } return 0; } /* This function is the "key store" for tinyDTLS. It is called to * retrieve a key for the given identity within this particular * session. */ static int get_psk_info(struct dtls_context_t *dtls_context, const session_t *dtls_session, dtls_credentials_type_t type, const uint8_t *id, size_t id_len, unsigned char *result, size_t result_length) { coap_context_t *coap_context; coap_session_t *coap_session; int fatal_error = DTLS_ALERT_INTERNAL_ERROR; size_t identity_length; static int client = 0; static uint8_t psk[128]; static size_t psk_len = 0; coap_address_t remote_addr; if (type == DTLS_PSK_KEY && client) { if (psk_len > result_length) { coap_log(LOG_WARNING, "cannot set psk -- buffer too small\n"); goto error; } memcpy(result, psk, psk_len); client = 0; return (int)psk_len; } client = 0; coap_context = (coap_context_t *)dtls_get_app_data(dtls_context); get_session_addr(dtls_session, &remote_addr); coap_session = coap_session_get_by_peer(coap_context, &remote_addr, dtls_session->ifindex); if (!coap_session) { coap_log(LOG_DEBUG, "cannot get PSK, session not found\n"); goto error; } switch (type) { case DTLS_PSK_IDENTITY: if (id_len) coap_log(LOG_DEBUG, "got psk_identity_hint: '%.*s'\n", (int)id_len, id); if (!coap_context || !coap_context->get_client_psk) goto error; identity_length = 0; psk_len = coap_context->get_client_psk(coap_session, (const uint8_t*)id, id_len, (uint8_t*)result, &identity_length, result_length, psk, sizeof(psk)); if (!psk_len) { coap_log(LOG_WARNING, "no PSK identity for given realm\n"); fatal_error = DTLS_ALERT_CLOSE_NOTIFY; goto error; } client = 1; return (int)identity_length; case DTLS_PSK_KEY: if (coap_context->get_server_psk) return (int)coap_context->get_server_psk(coap_session, (const uint8_t*)id, id_len, (uint8_t*)result, result_length); return 0; break; case DTLS_PSK_HINT: client = 0; if (coap_context->get_server_hint) return (int)coap_context->get_server_hint(coap_session, (uint8_t *)result, result_length); return 0; default: coap_log(LOG_WARNING, "unsupported request type: %d\n", type); } error: client = 0; return dtls_alert_fatal_create(fatal_error); } static dtls_handler_t cb = { .write = dtls_send_to_peer, .read = dtls_application_data, .event = dtls_event, .get_psk_info = get_psk_info, #ifdef WITH_ECC .get_ecdsa_key = NULL, .verify_ecdsa_key = NULL #endif }; void * coap_dtls_new_context(struct coap_context_t *coap_context) { struct dtls_context_t *dtls_context = dtls_new_context(coap_context); if (!dtls_context) goto error; dtls_set_handler(dtls_context, &cb); return dtls_context; error: coap_dtls_free_context(dtls_context); return NULL; } void coap_dtls_free_context(void *handle) { if (handle) { struct dtls_context_t *dtls_context = (struct dtls_context_t *)handle; dtls_free_context(dtls_context); } } static session_t * coap_dtls_new_session(coap_session_t *session) { session_t *dtls_session = coap_malloc_type(COAP_DTLS_SESSION, sizeof(session_t)); if (dtls_session) { /* create tinydtls session object from remote address and local * endpoint handle */ dtls_session_init(dtls_session); put_session_addr(&session->addr_info.remote, dtls_session); dtls_session->ifindex = session->ifindex; coap_log(LOG_DEBUG, "***new session %p\n", (void *)dtls_session); } return dtls_session; } void *coap_dtls_new_server_session(coap_session_t *session) { return coap_dtls_new_session(session); } void *coap_dtls_new_client_session(coap_session_t *session) { dtls_peer_t *peer; session_t *dtls_session = coap_dtls_new_session(session); if (!dtls_session) return NULL; peer = dtls_get_peer((struct dtls_context_t *)session->context->dtls_context, dtls_session); if (!peer) { /* The peer connection does not yet exist. */ /* dtls_connect() returns a value greater than zero if a new * connection attempt is made, 0 for session reuse. */ if (dtls_connect((struct dtls_context_t *)session->context->dtls_context, dtls_session) >= 0) { peer = dtls_get_peer((struct dtls_context_t *)session->context->dtls_context, dtls_session); } } if (!peer) { /* delete existing session because the peer object has been invalidated */ coap_free_type(COAP_DTLS_SESSION, dtls_session); dtls_session = NULL; } return dtls_session; } void coap_dtls_session_update_mtu(coap_session_t *session) { (void)session; } void coap_dtls_free_session(coap_session_t *coap_session) { struct dtls_context_t *ctx; if (coap_session->context == NULL) return; ctx = (struct dtls_context_t *)coap_session->context->dtls_context; if (coap_session->tls && ctx) { dtls_peer_t *peer = dtls_get_peer(ctx, (session_t *)coap_session->tls); if ( peer ) dtls_reset_peer(ctx, peer); else dtls_close(ctx, (session_t *)coap_session->tls); coap_log(LOG_DEBUG, "***removed session %p\n", coap_session->tls); coap_free_type(COAP_DTLS_SESSION, coap_session->tls); coap_session->tls = NULL; coap_handle_event(coap_session->context, COAP_EVENT_DTLS_CLOSED, coap_session); } } int coap_dtls_send(coap_session_t *session, const uint8_t *data, size_t data_len ) { int res; uint8_t *data_rw; coap_log(LOG_DEBUG, "call dtls_write\n"); coap_event_dtls = -1; /* Need to do this to not get a compiler warning about const parameters */ memcpy (&data_rw, &data, sizeof(data_rw)); res = dtls_write((struct dtls_context_t *)session->context->dtls_context, (session_t *)session->tls, data_rw, data_len); if (res < 0) coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n"); if (coap_event_dtls >= 0) { /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */ if (coap_event_dtls != COAP_EVENT_DTLS_CLOSED) coap_handle_event(session->context, coap_event_dtls, session); if (coap_event_dtls == COAP_EVENT_DTLS_CONNECTED) coap_session_connected(session); else if (coap_event_dtls == COAP_EVENT_DTLS_CLOSED || coap_event_dtls == COAP_EVENT_DTLS_ERROR) coap_session_disconnected(session, COAP_NACK_TLS_FAILED); } return res; } int coap_dtls_is_context_timeout(void) { return 1; } coap_tick_t coap_dtls_get_context_timeout(void *dtls_context) { clock_time_t next = 0; dtls_check_retransmit((struct dtls_context_t *)dtls_context, &next); if (next > 0) return ((coap_tick_t)(next - dtls_tick_0)) * COAP_TICKS_PER_SECOND / DTLS_TICKS_PER_SECOND + coap_tick_0; return 0; } coap_tick_t coap_dtls_get_timeout(coap_session_t *session, coap_tick_t now) { (void)session; (void)now; return 0; } void coap_dtls_handle_timeout(coap_session_t *session) { (void)session; return; } int coap_dtls_receive(coap_session_t *session, const uint8_t *data, size_t data_len ) { session_t *dtls_session = (session_t *)session->tls; int err; uint8_t *data_rw; coap_event_dtls = -1; /* Need to do this to not get a compiler warning about const parameters */ memcpy (&data_rw, &data, sizeof(data_rw)); err = dtls_handle_message( (struct dtls_context_t *)session->context->dtls_context, dtls_session, data_rw, (int)data_len); if (err){ coap_event_dtls = COAP_EVENT_DTLS_ERROR; } if (coap_event_dtls >= 0) { /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */ if (coap_event_dtls != COAP_EVENT_DTLS_CLOSED) coap_handle_event(session->context, coap_event_dtls, session); if (coap_event_dtls == COAP_EVENT_DTLS_CONNECTED) coap_session_connected(session); else if (coap_event_dtls == COAP_EVENT_DTLS_CLOSED || coap_event_dtls == COAP_EVENT_DTLS_ERROR) coap_session_disconnected(session, COAP_NACK_TLS_FAILED); } return err; } int coap_dtls_hello(coap_session_t *session, const uint8_t *data, size_t data_len ) { session_t dtls_session; struct dtls_context_t *dtls_context = (struct dtls_context_t *)session->context->dtls_context; uint8_t *data_rw; dtls_session_init(&dtls_session); put_session_addr(&session->addr_info.remote, &dtls_session); dtls_session.ifindex = session->ifindex; /* Need to do this to not get a compiler warning about const parameters */ memcpy (&data_rw, &data, sizeof(data_rw)); int res = dtls_handle_message(dtls_context, &dtls_session, data_rw, (int)data_len); if (res >= 0) { if (dtls_get_peer(dtls_context, &dtls_session)) res = 1; else res = 0; } return res; } unsigned int coap_dtls_get_overhead(coap_session_t *session) { (void)session; return 13 + 8 + 8; } #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else /* __GNUC__ */ #define UNUSED #endif /* __GNUC__ */ int coap_tls_is_supported(void) { return 0; } coap_tls_version_t * coap_get_tls_library_version(void) { static coap_tls_version_t version; const char *vers = dtls_package_version(); version.version = 0; if (vers) { long int p1, p2 = 0, p3 = 0; char* endptr; p1 = strtol(vers, &endptr, 10); if (*endptr == '.') { p2 = strtol(endptr+1, &endptr, 10); if (*endptr == '.') { p3 = strtol(endptr+1, &endptr, 10); } } version.version = (p1 << 16) | (p2 << 8) | p3; } version.built_version = version.version; version.type = COAP_TLS_LIBRARY_TINYDTLS; return &version; } int coap_dtls_context_set_pki(coap_context_t *ctx UNUSED, coap_dtls_pki_t* setup_data UNUSED, coap_dtls_role_t role UNUSED ) { return 0; } int coap_dtls_context_set_pki_root_cas(struct coap_context_t *ctx UNUSED, const char *ca_file UNUSED, const char *ca_path UNUSED ) { return 0; } int coap_dtls_context_set_psk(coap_context_t *ctx UNUSED, const char *hint UNUSED, coap_dtls_role_t role UNUSED ) { return 1; } int coap_dtls_context_check_keys_enabled(coap_context_t *ctx UNUSED) { return 1; } void *coap_tls_new_client_session(coap_session_t *session UNUSED, int *connected UNUSED) { return NULL; } void *coap_tls_new_server_session(coap_session_t *session UNUSED, int *connected UNUSED) { return NULL; } void coap_tls_free_session(coap_session_t *coap_session UNUSED) { } ssize_t coap_tls_write(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED ) { return -1; } ssize_t coap_tls_read(coap_session_t *session UNUSED, uint8_t *data UNUSED, size_t data_len UNUSED ) { return -1; } #undef UNUSED #else /* !HAVE_LIBTINYDTLS */ #ifdef __clang__ /* Make compilers happy that do not like empty modules. As this function is * never used, we ignore -Wunused-function at the end of compiling this file */ #pragma GCC diagnostic ignored "-Wunused-function" #endif static inline void dummy(void) { } #endif /* HAVE_LIBTINYDTLS */
26.34103
154
0.715442
[ "object" ]
ca3ac26ba3afa108209ceb032acfd6475f8a5127
3,040
h
C
modules/perception/base/distortion_model.h
jzjonah/apollo
bc534789dc0548bf2d27f8d72fe255d5c5e4f951
[ "Apache-2.0" ]
22,688
2017-07-04T23:17:19.000Z
2022-03-31T18:56:48.000Z
modules/perception/base/distortion_model.h
Songjiarui3313/apollo
df9113ae656e28e5374db32529d68e59455058a0
[ "Apache-2.0" ]
4,804
2017-07-04T22:30:12.000Z
2022-03-31T12:58:21.000Z
modules/perception/base/distortion_model.h
Songjiarui3313/apollo
df9113ae656e28e5374db32529d68e59455058a0
[ "Apache-2.0" ]
9,985
2017-07-04T22:01:17.000Z
2022-03-31T14:18:16.000Z
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include "modules/perception/base/camera.h" namespace apollo { namespace perception { namespace base { class BaseCameraDistortionModel { public: BaseCameraDistortionModel() = default; virtual ~BaseCameraDistortionModel() = default; // @brief: project a point from camera space to image plane // @params[IN] point3d: 3d point in camera space; // @return: 2d point in image plane // @note: the input point should be in front of the camera, // i.e. point3d[2] > 0 virtual Eigen::Vector2f Project(const Eigen::Vector3f& point3d) = 0; virtual std::shared_ptr<BaseCameraModel> get_camera_model() = 0; virtual std::string name() const = 0; virtual bool set_params(size_t width, size_t height, const Eigen::VectorXf& params) = 0; size_t get_height() const { return height_; } size_t get_width() const { return width_; } protected: size_t width_ = 0; size_t height_ = 0; }; /* TODO(all): to remove typedef std::shared_ptr<BaseCameraDistortionModel> BaseCameraDistortionModelPtr; typedef std::shared_ptr<const BaseCameraDistortionModel> BaseCameraDistortionModelConstPtr; */ class BrownCameraDistortionModel : public BaseCameraDistortionModel { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW public: BrownCameraDistortionModel() = default; ~BrownCameraDistortionModel() = default; Eigen::Vector2f Project(const Eigen::Vector3f& point3d) override; std::shared_ptr<BaseCameraModel> get_camera_model() override; std::string name() const override { return "BrownCameraDistortionModel"; } bool set_params(size_t width, size_t height, const Eigen::VectorXf& params) override; inline Eigen::Matrix3f get_intrinsic_params() const { return intrinsic_params_; } inline Eigen::Matrix<float, 5, 1> get_distort_params() const { return distort_params_; } protected: Eigen::Matrix3f intrinsic_params_; Eigen::Matrix<float, 5, 1> distort_params_; }; using BrownCameraDistortionModelPtr = std::shared_ptr<BrownCameraDistortionModel>; using BrownCameraDistortionModelConstPtr = std::shared_ptr<const BrownCameraDistortionModel>; } // namespace base } // namespace perception } // namespace apollo
31.340206
80
0.701316
[ "3d" ]
ca3cb10b36882f0f81081ae8a2ff27047420a5c4
8,495
h
C
ImageProcessingFilters/ItkManualThresholdTemplate.h
dream3d/ImageProcessing
7720ec74cf7c3aa2e58a29d8d7c529762865eb5e
[ "BSD-2-Clause" ]
1
2015-11-12T20:15:42.000Z
2015-11-12T20:15:42.000Z
ImageProcessingFilters/ItkManualThresholdTemplate.h
dream3d/ImageProcessing
7720ec74cf7c3aa2e58a29d8d7c529762865eb5e
[ "BSD-2-Clause" ]
null
null
null
ImageProcessingFilters/ItkManualThresholdTemplate.h
dream3d/ImageProcessing
7720ec74cf7c3aa2e58a29d8d7c529762865eb5e
[ "BSD-2-Clause" ]
6
2015-03-10T18:58:54.000Z
2020-04-02T16:53:41.000Z
/* ============================================================================ * Copyright (c) 2014 William Lenthe * Copyright (c) 2014 DREAM3D Consortium * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of William Lenthe or any of the DREAM3D Consortium contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was partially written under United States Air Force Contract number * FA8650-10-D-5210 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #pragma once //#include <vector> #include <memory> #include <QtCore/QString> #include "SIMPLib/SIMPLib.h" #include "SIMPLib/Filtering/AbstractFilter.h" class IDataArray; using IDataArrayWkPtrType = std::weak_ptr<IDataArray>; #include "ImageProcessing/ImageProcessingConstants.h" //#include "TemplateUtilities.h" #include "ImageProcessing/ImageProcessingDLLExport.h" /** * @class ManualThresholdTemplate ManualThresholdTemplate.h ImageProcessing/ImageProcessingFilters/ManualThresholdTemplate.h * @brief * @author * @date * @version 1.0 */ class ImageProcessing_EXPORT ItkManualThresholdTemplate : public AbstractFilter { Q_OBJECT // Start Python bindings declarations PYB11_BEGIN_BINDINGS(ItkManualThresholdTemplate SUPERCLASS AbstractFilter) PYB11_FILTER() PYB11_SHARED_POINTERS(ItkManualThresholdTemplate) PYB11_FILTER_NEW_MACRO(ItkManualThresholdTemplate) PYB11_PROPERTY(DataArrayPath SelectedCellArrayArrayPath READ getSelectedCellArrayArrayPath WRITE setSelectedCellArrayArrayPath) PYB11_PROPERTY(QString NewCellArrayName READ getNewCellArrayName WRITE setNewCellArrayName) PYB11_PROPERTY(bool SaveAsNewArray READ getSaveAsNewArray WRITE setSaveAsNewArray) PYB11_PROPERTY(int ManualParameter READ getManualParameter WRITE setManualParameter) PYB11_END_BINDINGS() // End Python bindings declarations public: using Self = ItkManualThresholdTemplate; using Pointer = std::shared_ptr<Self>; using ConstPointer = std::shared_ptr<const Self>; using WeakPointer = std::weak_ptr<Self>; using ConstWeakPointer = std::weak_ptr<const Self>; static Pointer NullPointer(); static std::shared_ptr<ItkManualThresholdTemplate> New(); /** * @brief Returns the name of the class for ItkManualThresholdTemplate */ QString getNameOfClass() const override; /** * @brief Returns the name of the class for ItkManualThresholdTemplate */ static QString ClassName(); ~ItkManualThresholdTemplate() override; /** * @brief Setter property for SelectedCellArrayArrayPath */ void setSelectedCellArrayArrayPath(const DataArrayPath& value); /** * @brief Getter property for SelectedCellArrayArrayPath * @return Value of SelectedCellArrayArrayPath */ DataArrayPath getSelectedCellArrayArrayPath() const; Q_PROPERTY(DataArrayPath SelectedCellArrayArrayPath READ getSelectedCellArrayArrayPath WRITE setSelectedCellArrayArrayPath) /** * @brief Setter property for NewCellArrayName */ void setNewCellArrayName(const QString& value); /** * @brief Getter property for NewCellArrayName * @return Value of NewCellArrayName */ QString getNewCellArrayName() const; Q_PROPERTY(QString NewCellArrayName READ getNewCellArrayName WRITE setNewCellArrayName) /** * @brief Setter property for SaveAsNewArray */ void setSaveAsNewArray(bool value); /** * @brief Getter property for SaveAsNewArray * @return Value of SaveAsNewArray */ bool getSaveAsNewArray() const; Q_PROPERTY(bool SaveAsNewArray READ getSaveAsNewArray WRITE setSaveAsNewArray) /** * @brief Setter property for ManualParameter */ void setManualParameter(int value); /** * @brief Getter property for ManualParameter * @return Value of ManualParameter */ int getManualParameter() const; Q_PROPERTY(int ManualParameter READ getManualParameter WRITE setManualParameter) /** * @brief getCompiledLibraryName Returns the name of the Library that this filter is a part of * @return */ QString getCompiledLibraryName() const override; /** * @brief This returns a string that is displayed in the GUI. It should be readable * and understandable by humans. */ QString getHumanLabel() const override; /** * @brief This returns the group that the filter belonds to. You can select * a different group if you want. The string returned here will be displayed * in the GUI for the filter */ QString getGroupName() const override; /** * @brief This returns a string that is displayed in the GUI and helps to sort the filters into * a subgroup. It should be readable and understandable by humans. */ QString getSubGroupName() const override; /** * @brief getUuid Return the unique identifier for this filter. * @return A QUuid object. */ QUuid getUuid() const override; /** * @brief This method will instantiate all the end user settable options/parameters * for this filter */ void setupFilterParameters() override; /** * @brief This method will read the options from a file * @param reader The reader that is used to read the options from a file * @param index The index to read the information from */ void readFilterParameters(AbstractFilterParametersReader* reader, int index) override; /** * @brief Reimplemented from @see AbstractFilter class */ void execute() override; /** * @brief newFilterInstance Returns a new instance of the filter optionally copying the filter parameters from the * current filter to the new instance. * @param copyFilterParameters * @return */ AbstractFilter::Pointer newFilterInstance(bool copyFilterParameters) const override; // virtual void ManualThresholdTemplate::template_execute(); protected: ItkManualThresholdTemplate(); /** * @brief dataCheck Checks for the appropriate parameter values and availability of arrays */ void dataCheck() override; /** * @brief Initializes all the private instance variables. */ void initialize(); private: IDataArrayWkPtrType m_SelectedCellArrayPtr; void* m_SelectedCellArray = nullptr; IDataArrayWkPtrType m_NewCellArrayPtr; void* m_NewCellArray = nullptr; DataArrayPath m_SelectedCellArrayArrayPath = {"", "", ""}; QString m_NewCellArrayName = {""}; bool m_SaveAsNewArray = {true}; int m_ManualParameter = {128}; public: ItkManualThresholdTemplate(const ItkManualThresholdTemplate&) = delete; // Copy Constructor Not Implemented ItkManualThresholdTemplate(ItkManualThresholdTemplate&&) = delete; // Move Constructor Not Implemented ItkManualThresholdTemplate& operator=(const ItkManualThresholdTemplate&) = delete; // Copy Assignment Not Implemented ItkManualThresholdTemplate& operator=(ItkManualThresholdTemplate&&) = delete; // Move Assignment Not Implemented };
35.693277
131
0.722778
[ "object", "vector" ]
ca3cf395d1059e27111f851b1317f0839c1d8b10
908
h
C
src/exception/product_exception.h
bdmendes/feup-aeda-project
09d4fa484bc2be176992139fc925524cbaa6766d
[ "MIT" ]
null
null
null
src/exception/product_exception.h
bdmendes/feup-aeda-project
09d4fa484bc2be176992139fc925524cbaa6766d
[ "MIT" ]
9
2020-11-15T01:03:41.000Z
2020-11-20T21:12:06.000Z
src/exception/product_exception.h
bdmendes/feup-aeda-project
09d4fa484bc2be176992139fc925524cbaa6766d
[ "MIT" ]
2
2021-02-08T23:36:03.000Z
2021-02-09T19:40:32.000Z
#ifndef FEUP_AEDA_PROJECT_PRODUCTEXCEPTIONS_H #define FEUP_AEDA_PROJECT_PRODUCTEXCEPTIONS_H #include <string> #include <iostream> /** * Class relative to the exception of a nonexistent product. */ class ProductDoesNotExist : public std::invalid_argument{ public: /** * Creates a new ProductDoesNotExist exceptionobject. * * @param name the name * @param price the price */ ProductDoesNotExist(const std::string& name, float price); }; /** * Class relative to the exception of an invalid product position on some list. */ class InvalidProductPosition : public std::invalid_argument{ public: /** * Creates a new InvalidProductPosition object. * * @param position the position * @param size the products list size */ InvalidProductPosition(unsigned long position, unsigned long size); }; #endif //FEUP_AEDA_PROJECT_PRODUCTEXCEPTIONS_H
23.894737
79
0.721366
[ "object" ]
ca3ed935e007a8cf0fe24a41ae678169dc1fee1f
3,943
h
C
numerics/src/FrictionContact/fc3d_nonsmooth_Newton_natural_map.h
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
null
null
null
numerics/src/FrictionContact/fc3d_nonsmooth_Newton_natural_map.h
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
null
null
null
numerics/src/FrictionContact/fc3d_nonsmooth_Newton_natural_map.h
fperignon/sandbox
649f09d6db7bbd84c2418de74eb9453c0131f070
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2020 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FRICTIONCONTACT3D_nonsmooth_Newton_NaturalMap_H #define FRICTIONCONTACT3D_nonsmooth_Newton_NaturalMap_H /*!\file fc3d_nonsmooth_Newton_natural_map.h \brief Typedef and functions declarations related to natural map formulation for 3 dimension frictional contact problems in Local Coordinates. Subroutines used when the friction-contact 3D problem is written using natural map [...] where M is an n by n matrix, q an n-dimensional vector, reaction an n-dimensional vector and velocity an n-dimensional vector. We consider a "global" (ie for several contacts) problem, used to initialize the static global variables. */ #include "NumericsFwd.h" // for SolverOptions, FrictionContactProblem #include "SiconosConfig.h" // for BUILD_AS_CPP // IWYU pragma: keep #if defined(__cplusplus) && !defined(BUILD_AS_CPP) extern "C" { #endif /** The natural map function signature for a 3x3 block. */ typedef void (*NaturalMapFun3x3Ptr)(double* reaction, double* velocity, double mu, double* rho, double* F, double* A, double* B); /** Nonsmooth Newton solver based on the Natural--Map function for the * local (reduced) frictional contact problem in the dense form * \param problem the problem to solve in dense or sparse block form * \param reaction solution and initial guess for reaction * \param velocity solution and initial guess for velocity * \param info returned info * \param options the solver options */ void fc3d_nonsmooth_Newton_NaturalMap( FrictionContactProblem* problem, double *reaction, double *velocity, int *info, SolverOptions *options); /** The natural map function for several contacts. On each contact, the specified natural map function in iparam[9] is called. \param problemSize the number of contacts. \param computeACFun3x3 the block 3x3 natural map function. \param reaction3D the reactions at each contact (size: 3 x problemSize) \param velocity3D the velocities at each contact (size: 3 x problemSize) \param mu the mu parameter (size : problemSize) \param rho3D the rho parameters (size : 3 x problemSize) \param output_blocklist3 the computed natural map function (size : 3 x problemSize) \param output_blocklist3x3_1 the computed A part of gradient (size : 9 x problemSize) \param output_blocklist3x3_2 the computed B param of gradient (size : 9 x problemSize) */ void fc3d_NaturalMapFunction( unsigned int problemSize, NaturalMapFun3x3Ptr computeACFun3x3, double *reaction3D, double *velocity3D, double *mu, double *rho3D, double *output_blocklist3, double *output_blocklist3x3_1, double *output_blocklist3x3_2); int fc3d_nonsmooth_Newton_NaturalMap_compute_error( FrictionContactProblem* problem, double *z , double *w, double tolerance, SolverOptions * options, double * error); #if defined(__cplusplus) && !defined(BUILD_AS_CPP) } #endif #endif
36.850467
92
0.693888
[ "vector", "3d" ]
ca454d140a7591e4e97f65d8cd90a7654c1c0e69
2,684
h
C
include/org/apache/lucene/search/similarities/BasicModelIn.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
9
2016-01-13T05:38:05.000Z
2020-06-04T23:05:03.000Z
include/org/apache/lucene/search/similarities/BasicModelIn.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
4
2016-05-12T10:40:53.000Z
2016-06-11T19:08:33.000Z
include/org/apache/lucene/search/similarities/BasicModelIn.h
lukhnos/objclucene
29c7189a0b30ab3d3dd4c8ed148235ee296128b7
[ "MIT" ]
5
2016-01-13T05:37:39.000Z
2019-07-27T16:53:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: ./core/src/java/org/apache/lucene/search/similarities/BasicModelIn.java // #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelIn") #ifdef RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModelIn #define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelIn 0 #else #define INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelIn 1 #endif #undef RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModelIn #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if !defined (OrgApacheLuceneSearchSimilaritiesBasicModelIn_) && (INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelIn || defined(INCLUDE_OrgApacheLuceneSearchSimilaritiesBasicModelIn)) #define OrgApacheLuceneSearchSimilaritiesBasicModelIn_ #define RESTRICT_OrgApacheLuceneSearchSimilaritiesBasicModel 1 #define INCLUDE_OrgApacheLuceneSearchSimilaritiesBasicModel 1 #include "org/apache/lucene/search/similarities/BasicModel.h" @class OrgApacheLuceneSearchExplanation; @class OrgApacheLuceneSearchSimilaritiesBasicStats; /*! @brief The basic tf-idf model of randomness. */ @interface OrgApacheLuceneSearchSimilaritiesBasicModelIn : OrgApacheLuceneSearchSimilaritiesBasicModel #pragma mark Public /*! @brief Sole constructor: parameter-free */ - (instancetype __nonnull)init; - (OrgApacheLuceneSearchExplanation *)explainWithOrgApacheLuceneSearchSimilaritiesBasicStats:(OrgApacheLuceneSearchSimilaritiesBasicStats *)stats withFloat:(jfloat)tfn; - (jfloat)scoreWithOrgApacheLuceneSearchSimilaritiesBasicStats:(OrgApacheLuceneSearchSimilaritiesBasicStats *)stats withFloat:(jfloat)tfn; - (NSString *)description; @end J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchSimilaritiesBasicModelIn) FOUNDATION_EXPORT void OrgApacheLuceneSearchSimilaritiesBasicModelIn_init(OrgApacheLuceneSearchSimilaritiesBasicModelIn *self); FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesBasicModelIn *new_OrgApacheLuceneSearchSimilaritiesBasicModelIn_init(void) NS_RETURNS_RETAINED; FOUNDATION_EXPORT OrgApacheLuceneSearchSimilaritiesBasicModelIn *create_OrgApacheLuceneSearchSimilaritiesBasicModelIn_init(void); J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchSimilaritiesBasicModelIn) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchSimilaritiesBasicModelIn")
37.802817
190
0.831967
[ "model" ]
ca4abc0b0491058be1b3817850e70108bb0d8219
45,819
c
C
uCOS-III/os_tmr.c
Githubnew-app/RT-Thread-wrapper-of-uCOS-III
3d01cb69add03ad08a42848e7d9eb7384a1ce58d
[ "Apache-2.0" ]
1
2021-05-14T09:25:59.000Z
2021-05-14T09:25:59.000Z
uCOS-III/os_tmr.c
Githubnew-app/RT-Thread-wrapper-of-uCOS-III
3d01cb69add03ad08a42848e7d9eb7384a1ce58d
[ "Apache-2.0" ]
null
null
null
uCOS-III/os_tmr.c
Githubnew-app/RT-Thread-wrapper-of-uCOS-III
3d01cb69add03ad08a42848e7d9eb7384a1ce58d
[ "Apache-2.0" ]
1
2021-05-14T09:31:54.000Z
2021-05-14T09:31:54.000Z
/* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2020-06-30 Meco Man the first verion */ /* ********************************************************************************************************* * uC/OS-III * The Real-Time Kernel * * Copyright 2009-2020 Silicon Laboratories Inc. www.silabs.com * * SPDX-License-Identifier: APACHE-2.0 * * This software is subject to an open source license and is distributed by * Silicon Laboratories Inc. pursuant to the terms of the Apache License, * Version 2.0 available at www.apache.org/licenses/LICENSE-2.0. * ********************************************************************************************************* */ /* ************************************************************************************************************************ * uC/OS-III * The Real-Time Kernel * * (c) Copyright 2009-2012; Micrium, Inc.; Weston, FL * All rights reserved. Protected by international copyright laws. * * TIMER MANAGEMENT * * File : OS_TMR.C * By : JJL * Version : V3.03.00 * * LICENSING TERMS: * --------------- * uC/OS-III is provided in source form for FREE short-term evaluation, for educational use or * for peaceful research. If you plan or intend to use uC/OS-III in a commercial application/ * product then, you need to contact Micrium to properly license uC/OS-III for its use in your * application/product. We provide ALL the source code for your convenience and to help you * experience uC/OS-III. The fact that the source is provided does NOT mean that you can use * it commercially without paying a licensing fee. * * Knowledge of the source code may NOT be used to develop a similar product. * * Please help us continue to provide the embedded community with the finest software available. * Your honesty is greatly appreciated. * * You can contact us at www.micrium.com, or by phone at +1 (954) 217-2036. ************************************************************************************************************************ */ #include "os.h" /* ************************************************************************************************************************ * Note(s) : 1)RTT和uCOS-III在定时器时钟源的设计不同: * ・RTT的定时器时钟频率与操作系统ostick频率相同 * ・uCOS-III的定时器时钟由ostick分频得到,分频系数为OS_CFG_TMR_TASK_RATE_HZ * 函数内部已经对上述两个操作系统定义的做出了转换 ************************************************************************************************************************ */ #if OS_CFG_TMR_EN > 0u /* ************************************************************************************************************************ * LOCAL PROTOTYPES ************************************************************************************************************************ */ static void OS_TmrCallback(void *p_ara); /* ************************************************************************************************************************ * CREATE A TIMER * * Description: This function is called by your application code to create a timer. * * Arguments : p_tmr Is a pointer to a timer control block * * p_name Is a pointer to an ASCII string that is used to name the timer. Names are useful for * debugging. * * dly Initial delay. * If the timer is configured for ONE-SHOT mode, this is the timeout used * If the timer is configured for PERIODIC mode, this is the first timeout to wait for * before the timer starts entering periodic mode * * period The 'period' being repeated for the timer. * If you specified 'OS_OPT_TMR_PERIODIC' as an option, when the timer expires, it will * automatically restart with the same period. * * opt Specifies either: * * OS_OPT_TMR_ONE_SHOT The timer counts down only once * OS_OPT_TMR_PERIODIC The timer counts down and then reloads itself * * p_callback Is a pointer to a callback function that will be called when the timer expires. The * callback function must be declared as follows: * * void MyCallback (OS_TMR *p_tmr, void *p_arg); * * p_callback_arg Is an argument (a pointer) that is passed to the callback function when it is called. * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE * OS_ERR_ILLEGAL_CREATE_RUN_TIME if you are trying to create the timer after you called * OSSafetyCriticalStart(). * OS_ERR_OBJ_CREATED if the timer has already been created * OS_ERR_OBJ_PTR_NULL is 'p_tmr' is a NULL pointer * OS_ERR_OBJ_TYPE if the object type is invalid * OS_ERR_OPT_INVALID you specified an invalid option * OS_ERR_TMR_INVALID_CALLBACK You specified an invalid callback for a periodic timer * OS_ERR_TMR_INVALID_DLY you specified an invalid delay * OS_ERR_TMR_INVALID_PERIOD you specified an invalid period * OS_ERR_TMR_ISR if the call was made from an ISR * * Returns : none * * Note(s) : 1) This function only creates the timer. In other words, the timer is not started when created. To * start the timer, call OSTmrStart(). * ************************************************************************************************************************ */ void OSTmrCreate (OS_TMR *p_tmr, CPU_CHAR *p_name, OS_TICK dly, OS_TICK period, OS_OPT opt, OS_TMR_CALLBACK_PTR p_callback, void *p_callback_arg, OS_ERR *p_err) { rt_uint8_t rt_flag; rt_tick_t time, time2; CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return; } #endif #ifdef OS_SAFETY_CRITICAL_IEC61508 if (OSSafetyCriticalStartFlag == DEF_TRUE) { *p_err = OS_ERR_ILLEGAL_CREATE_RUN_TIME; return; } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { *p_err = OS_ERR_TMR_ISR; return; } #endif #if OS_CFG_ARG_CHK_EN > 0u if(p_tmr == RT_NULL) /* 检查指针是否为空 */ { *p_err = OS_ERR_OBJ_PTR_NULL; return; } switch (opt) { case OS_OPT_TMR_PERIODIC: if (period == (OS_TICK)0) { *p_err = OS_ERR_TMR_INVALID_PERIOD; return; } if (p_callback == (OS_TMR_CALLBACK_PTR)0) { /* No point in a periodic timer without a callback */ *p_err = OS_ERR_TMR_INVALID_CALLBACK; return; } break; case OS_OPT_TMR_ONE_SHOT: if (dly == (OS_TICK)0) { *p_err = OS_ERR_TMR_INVALID_DLY; return; } break; default: *p_err = OS_ERR_OPT_INVALID; return; } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u if(rt_object_get_type(&p_tmr->Tmr.parent) == RT_Object_Class_Timer) /* 判断内核对象是否已经是定时器,即是否已经创建过 */ { *p_err = OS_ERR_OBJ_CREATED; return; } #endif /* uCOS-III原版定时器回调函数就是在定时器线程中调用的,而非在中断中调用, 因此要使用RTT的RT_TIMER_FLAG_SOFT_TIMER选项,在此之前应将宏定义RT_USING_TIMER_SOFT置1 */ if(opt == OS_OPT_TMR_ONE_SHOT) { rt_flag = RT_TIMER_FLAG_ONE_SHOT|RT_TIMER_FLAG_SOFT_TIMER; time = dly * (OS_CFG_TICK_RATE_HZ / OS_CFG_TMR_TASK_RATE_HZ); /* RTT和uCOS-III在定时器时钟源的设计不同,需要进行转换*/ } else if(opt == OS_OPT_TMR_PERIODIC) { rt_flag = RT_TIMER_FLAG_PERIODIC|RT_TIMER_FLAG_SOFT_TIMER; time = period * (OS_CFG_TICK_RATE_HZ / OS_CFG_TMR_TASK_RATE_HZ); } else { *p_err = OS_ERR_OPT_INVALID; return; } CPU_CRITICAL_ENTER(); p_tmr->State = (OS_STATE )OS_TMR_STATE_STOPPED; /* Initialize the timer fields */ p_tmr->CallbackPtr = (OS_TMR_CALLBACK_PTR)p_callback; p_tmr->CallbackPtrArg = (void *)p_callback_arg; p_tmr->Opt = (OS_OPT )opt; p_tmr->Period = (OS_TICK )period; p_tmr->Dly = (OS_TICK )dly; p_tmr->_dly = (OS_TICK )dly; /* 该变量为兼容层内部使用,用于带有延迟的周期延时 */ p_tmr->_set_dly = (OS_TICK )0; /* 该变量为兼容层内部使用,用于配合3.08版本中OSTmrSet函数 */ p_tmr->_set_period = (OS_TICK )0; /* 该变量为兼容层内部使用,用于配合3.08版本中OSTmrSet函数 */ #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Match = (OS_TICK )0; p_tmr->Remain = (OS_TICK )0; p_tmr->Type = (OS_OBJ_TYPE )OS_OBJ_TYPE_TMR; #if OS_CFG_DBG_EN > 0u p_tmr->NamePtr = (CPU_CHAR *)p_name; p_tmr->DbgPrevPtr = (OS_TMR *)0; p_tmr->DbgPrevPtr = (OS_TMR *)0; #endif #endif CPU_CRITICAL_EXIT(); if(p_tmr->Opt==OS_OPT_TMR_PERIODIC && p_tmr->_dly && p_tmr->Period) { /*带有延迟的周期延时,先延时一次延迟部分,该部分延时完毕后,周期部分由回调函数重新装填*/ time2 = p_tmr->Dly * (OS_CFG_TICK_RATE_HZ / OS_CFG_TMR_TASK_RATE_HZ); rt_timer_init(&p_tmr->Tmr, (const char*)p_name, OS_TmrCallback, p_tmr, /* 将p_tmr作为参数传到回调函数中 */ time2, RT_TIMER_FLAG_ONE_SHOT|RT_TIMER_FLAG_SOFT_TIMER); } else { rt_timer_init(&p_tmr->Tmr, (const char*)p_name, OS_TmrCallback, p_tmr, /* 将p_tmr作为参数传到回调函数中 */ time, rt_flag); } *p_err = OS_ERR_NONE; /* rt_timer_init没有返回错误码 */ #ifndef PKG_USING_UCOSIII_WRAPPER_TINY CPU_CRITICAL_ENTER(); #if OS_CFG_DBG_EN > 0u OS_TmrDbgListAdd(p_tmr); #endif OSTmrQty++; /* Keep track of the number of timers created */ CPU_CRITICAL_EXIT(); #endif } /* ************************************************************************************************************************ * DELETE A TIMER * * Description: This function is called by your application code to delete a timer. * * Arguments : p_tmr Is a pointer to the timer to stop and delete. * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_OBJ_TYPE 'p_tmr' is not pointing to a timer * OS_ERR_ILLEGAL_DEL_RUN_TIME If you are trying to delete the timer after you called * OSStart() * OS_ERR_TMR_INVALID 'p_tmr' is a NULL pointer * OS_ERR_TMR_ISR if the function was called from an ISR * OS_ERR_TMR_INACTIVE if the timer was not created * OS_ERR_TMR_INVALID_STATE the timer is in an invalid state * * Returns : DEF_TRUE if the timer was deleted * DEF_FALSE if not or upon an error ************************************************************************************************************************ */ #if OS_CFG_TMR_DEL_EN > 0u CPU_BOOLEAN OSTmrDel (OS_TMR *p_tmr, OS_ERR *p_err) { rt_err_t rt_err; CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return (DEF_FALSE); } #endif #ifdef OS_SAFETY_CRITICAL_IEC61508 if (OSSafetyCriticalStartFlag == OS_TRUE) { *p_err = OS_ERR_ILLEGAL_DEL_RUN_TIME; return (OS_FALSE); } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { *p_err = OS_ERR_TMR_ISR; return DEF_FALSE; } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return (OS_FALSE); } #endif #if OS_CFG_ARG_CHK_EN > 0u if(p_tmr == RT_NULL) /* 检查指针是否为空 */ { *p_err = OS_ERR_TMR_INVALID; return DEF_FALSE; } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u /*判断内核对象是否为定时器*/ if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer) { *p_err = OS_ERR_OBJ_TYPE; return DEF_FALSE; } #endif switch (p_tmr->State) { case OS_TMR_STATE_RUNNING: case OS_TMR_STATE_STOPPED: /* Timer has not started or ... */ case OS_TMR_STATE_COMPLETED: /* ... timer has completed the ONE-SHOT time */ break; case OS_TMR_STATE_UNUSED: /* Already deleted */ *p_err = OS_ERR_TMR_INACTIVE; return (DEF_FALSE); default: *p_err = OS_ERR_TMR_INVALID_STATE; return (DEF_FALSE); } rt_err = rt_timer_detach(&p_tmr->Tmr); *p_err = rt_err_to_ucosiii(rt_err); if(rt_err == RT_EOK) { CPU_CRITICAL_ENTER(); #ifndef PKG_USING_UCOSIII_WRAPPER_TINY #if OS_CFG_DBG_EN > 0u OS_TmrDbgListRemove(p_tmr); #endif OSTmrQty--; #endif OS_TmrClr(p_tmr); CPU_CRITICAL_EXIT(); return DEF_TRUE; } else { return DEF_FALSE; } } #endif /* ************************************************************************************************************************ * GET HOW MUCH TIME IS LEFT BEFORE A TIMER EXPIRES * * Description: This function is called to get the number of ticks before a timer times out. * * Arguments : p_tmr Is a pointer to the timer to obtain the remaining time from. * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE * OS_ERR_OBJ_TYPE 'p_tmr' is not pointing to a timer * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_TMR_INVALID 'p_tmr' is a NULL pointer * OS_ERR_TMR_ISR if the call was made from an ISR * OS_ERR_TMR_INACTIVE 'p_tmr' points to a timer that is not active * OS_ERR_TMR_INVALID_STATE the timer is in an invalid state * * Returns : The time remaining for the timer to expire. The time represents 'timer' increments. In other words, if * OS_TmrTask() is signaled every 1/10 of a second then the returned value represents the number of 1/10 of * a second remaining before the timer expires. ************************************************************************************************************************ */ OS_TICK OSTmrRemainGet (OS_TMR *p_tmr, OS_ERR *p_err) { OS_TICK remain; #ifndef PKG_USING_UCOSIII_WRAPPER_TINY CPU_SR_ALLOC(); #endif #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return ((OS_TICK)0); } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { *p_err = OS_ERR_TMR_ISR; return 0; } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return (0u); } #endif #if OS_CFG_ARG_CHK_EN > 0u if(p_tmr == RT_NULL) /* 检查指针是否为空 */ { *p_err = OS_ERR_TMR_INVALID; return 0; } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u /*判断内核对象是否为定时器*/ if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer) { *p_err = OS_ERR_OBJ_TYPE; return 0; } #endif switch (p_tmr->State) { case OS_TMR_STATE_RUNNING: *p_err = OS_ERR_NONE; remain = (p_tmr->Tmr.timeout_tick - rt_tick_get()) / (OS_CFG_TICK_RATE_HZ / OS_CFG_TMR_TASK_RATE_HZ); #ifndef PKG_USING_UCOSIII_WRAPPER_TINY CPU_CRITICAL_ENTER(); p_tmr->Remain = remain; CPU_CRITICAL_EXIT(); #endif case OS_TMR_STATE_STOPPED: if (p_tmr->Opt == OS_OPT_TMR_PERIODIC) { if (p_tmr->Dly == 0u) { remain = p_tmr->Period; } else { remain = p_tmr->Dly; } } else { remain = p_tmr->Dly; } #ifndef PKG_USING_UCOSIII_WRAPPER_TINY CPU_CRITICAL_ENTER(); p_tmr->Remain = remain; CPU_CRITICAL_EXIT(); #endif *p_err = OS_ERR_NONE; case OS_TMR_STATE_COMPLETED: *p_err = OS_ERR_NONE; remain = 0; case OS_TMR_STATE_UNUSED: *p_err = OS_ERR_TMR_INACTIVE; remain = 0; default: *p_err = OS_ERR_TMR_INVALID_STATE; remain = 0; } return (remain); } /* ************************************************************************************************************************ * SET A TIMER * * Description: This function is called by your application code to set a timer. * * Arguments : p_tmr Is a pointer to a timer control block * * dly Initial delay. * If the timer is configured for ONE-SHOT mode, this is the timeout used * If the timer is configured for PERIODIC mode, this is the first timeout to wait for * before the timer starts entering periodic mode * * period The 'period' being repeated for the timer. * If you specified 'OS_OPT_TMR_PERIODIC' as an option, when the timer expires, it will * automatically restart with the same period. * * p_callback Is a pointer to a callback function that will be called when the timer expires. The * callback function must be declared as follows: * * void MyCallback (OS_TMR *p_tmr, void *p_arg); * * p_callback_arg Is an argument (a pointer) that is passed to the callback function when it is called. * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE The timer was configured as expected * OS_ERR_OBJ_TYPE If the object type is invalid * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_TMR_INVALID If 'p_tmr' is a NULL pointer or invalid option * OS_ERR_TMR_INVALID_CALLBACK you specified an invalid callback for a periodic timer * OS_ERR_TMR_INVALID_DLY You specified an invalid delay * OS_ERR_TMR_INVALID_PERIOD You specified an invalid period * OS_ERR_TMR_ISR If the call was made from an ISR * * Returns : none * * Note(s) : 1) This function can be called on a running timer. The change to the delay and period will only * take effect after the current period or delay has passed. Change to the callback will take * effect immediately. ************************************************************************************************************************ */ void OSTmrSet (OS_TMR *p_tmr, OS_TICK dly, OS_TICK period, OS_TMR_CALLBACK_PTR p_callback, void *p_callback_arg, OS_ERR *p_err) { CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return; } #endif #if (OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u) if (OSIntNestingCtr > 0u) { /* See if trying to call from an ISR */ *p_err = OS_ERR_TMR_ISR; return; } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return; } #endif #if (OS_CFG_ARG_CHK_EN > 0u) if (p_tmr == (OS_TMR *)0) { /* Validate 'p_tmr' */ *p_err = OS_ERR_TMR_INVALID; return; } #endif #if (OS_CFG_OBJ_TYPE_CHK_EN > 0u) if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer) { *p_err = OS_ERR_OBJ_TYPE; return; } #endif #if (OS_CFG_ARG_CHK_EN > 0u) switch (p_tmr->Opt) { case OS_OPT_TMR_PERIODIC: if (period == 0u) { *p_err = OS_ERR_TMR_INVALID_PERIOD; return; } if (p_callback == (OS_TMR_CALLBACK_PTR)0) { /* No point in a periodic timer without a callback */ *p_err = OS_ERR_TMR_INVALID_CALLBACK; return; } break; case OS_OPT_TMR_ONE_SHOT: if (dly == 0u) { *p_err = OS_ERR_TMR_INVALID_DLY; return; } break; default: *p_err = OS_ERR_TMR_INVALID; return; } #endif CPU_CRITICAL_ENTER(); p_tmr->_set_dly = dly; /* Convert Timer Delay to ticks */ p_tmr->_set_period = period; /* Convert Timer Period to ticks */ p_tmr->CallbackPtr = p_callback; p_tmr->CallbackPtrArg = p_callback_arg; CPU_CRITICAL_EXIT(); *p_err = OS_ERR_NONE; } /* ************************************************************************************************************************ * START A TIMER * * Description: This function is called by your application code to start a timer. * * Arguments : p_tmr Is a pointer to an OS_TMR * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE * OS_ERR_OBJ_TYPE if 'p_tmr' is not pointing to a timer * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_TMR_INVALID * OS_ERR_TMR_INACTIVE if the timer was not created * OS_ERR_TMR_INVALID_STATE the timer is in an invalid state * OS_ERR_TMR_ISR if the call was made from an ISR * * Returns : DEF_TRUE is the timer was started * DEF_FALSE if not or upon an error * ************************************************************************************************************************ */ CPU_BOOLEAN OSTmrStart (OS_TMR *p_tmr, OS_ERR *p_err) { rt_err_t rt_err; CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return (DEF_FALSE); } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { *p_err = OS_ERR_TMR_ISR; return DEF_FALSE; } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return (OS_FALSE); } #endif #if OS_CFG_ARG_CHK_EN > 0u if(p_tmr == RT_NULL) /* 检查指针是否为空 */ { *p_err = OS_ERR_TMR_INVALID; return DEF_FALSE; } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer) /* 判断内核对象是否为定时器 */ { *p_err = OS_ERR_OBJ_TYPE; return DEF_FALSE; } #endif switch (p_tmr->State) { case OS_TMR_STATE_RUNNING: /* Restart the timer */ case OS_TMR_STATE_STOPPED: /* Start the timer */ case OS_TMR_STATE_COMPLETED: break; case OS_TMR_STATE_UNUSED: /* Timer not created */ *p_err = OS_ERR_TMR_INACTIVE; return (DEF_FALSE); default: *p_err = OS_ERR_TMR_INVALID_STATE; return (DEF_FALSE); } rt_err = rt_timer_start(&p_tmr->Tmr); *p_err = rt_err_to_ucosiii(rt_err); if(rt_err == RT_EOK) { CPU_CRITICAL_ENTER(); #ifndef PKG_USING_UCOSIII_WRAPPER_TINY if (p_tmr->Dly == 0u) { p_tmr->Remain = p_tmr->Period; } else { p_tmr->Remain = p_tmr->Dly; } p_tmr->Match = p_tmr->Tmr.timeout_tick; #endif p_tmr->State = OS_TMR_STATE_RUNNING; CPU_CRITICAL_EXIT(); return DEF_TRUE; } else { return DEF_FALSE; } } /* ************************************************************************************************************************ * FIND OUT WHAT STATE A TIMER IS IN * * Description: This function is called to determine what state the timer is in: * * OS_TMR_STATE_UNUSED the timer has not been created * OS_TMR_STATE_STOPPED the timer has been created but has not been started or has been stopped * OS_TMR_STATE_COMPLETED the timer is in ONE-SHOT mode and has completed it's timeout * OS_TMR_STATE_RUNNING the timer is currently running * * Arguments : p_tmr Is a pointer to the desired timer * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * * OS_ERR_NONE * OS_ERR_OBJ_TYPE if 'p_tmr' is not pointing to a timer * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_TMR_INVALID 'p_tmr' is a NULL pointer * OS_ERR_TMR_INVALID_STATE if the timer is not in a valid state * OS_ERR_TMR_ISR if the call was made from an ISR * * Returns : The current state of the timer (see description). ************************************************************************************************************************ */ OS_STATE OSTmrStateGet (OS_TMR *p_tmr, OS_ERR *p_err) { OS_STATE state; CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return (OS_TMR_STATE_UNUSED); } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if (OSIntNestingCtr > (OS_NESTING_CTR)0) { /* See if trying to call from an ISR */ *p_err = OS_ERR_TMR_ISR; return (OS_TMR_STATE_UNUSED); } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return (OS_TMR_STATE_UNUSED); } #endif #if OS_CFG_ARG_CHK_EN > 0u if (p_tmr == (OS_TMR *)0) { *p_err = OS_ERR_TMR_INVALID; return (OS_TMR_STATE_UNUSED); } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer){/* Make sure timer was created */ *p_err = OS_ERR_OBJ_TYPE; return (OS_TMR_STATE_UNUSED); } #endif CPU_CRITICAL_ENTER(); state = p_tmr->State; CPU_CRITICAL_EXIT(); switch (state) { case OS_TMR_STATE_UNUSED: case OS_TMR_STATE_STOPPED: case OS_TMR_STATE_COMPLETED: case OS_TMR_STATE_RUNNING: *p_err = OS_ERR_NONE; break; default: *p_err = OS_ERR_TMR_INVALID_STATE; break; } return (state); } /* ************************************************************************************************************************ * STOP A TIMER * * Description: This function is called by your application code to stop a timer. * * Arguments : p_tmr Is a pointer to the timer to stop. * * opt Allows you to specify an option to this functions which can be: * * OS_OPT_TMR_NONE Do nothing special but stop the timer * OS_OPT_TMR_CALLBACK Execute the callback function, pass it the callback argument * specified when the timer was created. * OS_OPT_TMR_CALLBACK_ARG Execute the callback function, pass it the callback argument * specified in THIS function call * * callback_arg Is a pointer to a 'new' callback argument that can be passed to the callback function * instead of the timer's callback argument. In other words, use 'callback_arg' passed in * THIS function INSTEAD of p_tmr->OSTmrCallbackArg * * p_err Is a pointer to an error code. '*p_err' will contain one of the following: * OS_ERR_NONE * OS_ERR_OBJ_TYPE if 'p_tmr' is not pointing to a timer * OS_ERR_OPT_INVALID if you specified an invalid option for 'opt' * OS_ERR_OS_NOT_RUNNING If uC/OS-III is not running yet * OS_ERR_TMR_INACTIVE if the timer was not created * OS_ERR_TMR_INVALID 'p_tmr' is a NULL pointer * OS_ERR_TMR_INVALID_STATE the timer is in an invalid state * OS_ERR_TMR_ISR if the function was called from an ISR * OS_ERR_TMR_NO_CALLBACK if the timer does not have a callback function defined * OS_ERR_TMR_STOPPED if the timer was already stopped * * Returns : DEF_TRUE If we stopped the timer (if the timer is already stopped, we also return DEF_TRUE) * DEF_FALSE If not ************************************************************************************************************************ */ CPU_BOOLEAN OSTmrStop (OS_TMR *p_tmr, OS_OPT opt, void *p_callback_arg, OS_ERR *p_err) { rt_err_t rt_err; OS_TMR_CALLBACK_PTR p_fnct; OS_ERR err; CPU_SR_ALLOC(); #ifdef OS_SAFETY_CRITICAL if (p_err == (OS_ERR *)0) { OS_SAFETY_CRITICAL_EXCEPTION(); return (DEF_FALSE); } #endif #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { *p_err = OS_ERR_TMR_ISR; return DEF_FALSE; } #endif #if (OS_CFG_INVALID_OS_CALLS_CHK_EN > 0u) if (OSRunning != OS_STATE_OS_RUNNING) { /* Is the kernel running? */ *p_err = OS_ERR_OS_NOT_RUNNING; return (OS_FALSE); } #endif #if OS_CFG_ARG_CHK_EN > 0u if(p_tmr == RT_NULL) /* 检查指针是否为空 */ { *p_err = OS_ERR_TMR_INVALID; return DEF_FALSE; } #endif #if OS_CFG_OBJ_TYPE_CHK_EN > 0u if(rt_object_get_type(&p_tmr->Tmr.parent) != RT_Object_Class_Timer)/* 判断内核对象是否为定时器 */ { *p_err = OS_ERR_OBJ_TYPE; return DEF_FALSE; } #endif rt_err = rt_timer_stop(&p_tmr->Tmr); if(rt_err == -RT_ERROR) { *p_err = OS_ERR_TMR_STOPPED; /* 返回-RT_ERROR 时则说明已经处于停止状态 */ return DEF_FALSE; } CPU_CRITICAL_ENTER(); p_tmr->State = OS_TMR_STATE_STOPPED; /* 标记目前定时器状态已经停止 */ #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Remain = 0u; #endif p_fnct = p_tmr->CallbackPtr; /* Execute callback function ... */ CPU_CRITICAL_EXIT(); switch (p_tmr->State) { case OS_TMR_STATE_RUNNING: break; case OS_TMR_STATE_COMPLETED: /* Timer has already completed the ONE-SHOT or */ case OS_TMR_STATE_STOPPED: /* ... timer has not started yet. */ *p_err = OS_ERR_TMR_STOPPED; return (DEF_TRUE); case OS_TMR_STATE_UNUSED: /* Timer was not created */ *p_err = OS_ERR_TMR_INACTIVE; return (DEF_FALSE); default: *p_err = OS_ERR_TMR_INVALID_STATE; return (DEF_FALSE); } *p_err = OS_ERR_NONE; OSSchedLock(&err); switch (opt) { case OS_OPT_TMR_CALLBACK: if (p_fnct != (OS_TMR_CALLBACK_PTR)0) { /* ... if available */ (*p_fnct)((void *)p_tmr, p_tmr->CallbackPtrArg);/* Use callback arg when timer was created */ } else { *p_err = OS_ERR_TMR_NO_CALLBACK; } break; case OS_OPT_TMR_CALLBACK_ARG: if (p_fnct != (OS_TMR_CALLBACK_PTR)0) { (*p_fnct)((void *)p_tmr, p_callback_arg); /* .. using the 'callback_arg' provided in call */ } else { *p_err = OS_ERR_TMR_NO_CALLBACK; } break; case OS_OPT_TMR_NONE: break; default: OSSchedUnlock(&err); *p_err = OS_ERR_OPT_INVALID; return (DEF_FALSE); } OSSchedUnlock(&err); if(*p_err != OS_ERR_NONE) { return DEF_FALSE; } else { return DEF_TRUE; } } /* ************************************************************************************************************************ * CLEAR TIMER FIELDS * * Description: This function is called to clear all timer fields. * * Argument(s): p_tmr is a pointer to the timer to clear * ----- * * Returns : none * * Note(s) : 1) This function is INTERNAL to uC/OS-III and your application MUST NOT call it. ************************************************************************************************************************ */ void OS_TmrClr (OS_TMR *p_tmr) { p_tmr->State = OS_TMR_STATE_UNUSED; /* Clear timer fields */ #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Type = OS_OBJ_TYPE_NONE; #if (OS_CFG_DBG_EN > 0u) p_tmr->NamePtr = (CPU_CHAR *)((void *)"?TMR"); #endif #endif p_tmr->CallbackPtr = (OS_TMR_CALLBACK_PTR)0; p_tmr->CallbackPtrArg = (void *)0; p_tmr->Opt = (OS_OPT )0; #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Match = (OS_TICK )0; p_tmr->Remain = (OS_TICK )0; #endif p_tmr->Period = (OS_TICK )0; p_tmr->Dly = (OS_TICK )0; p_tmr->_set_dly = (OS_TICK )0; /* 该变量为兼容层内部使用,用于配合3.08版本中OSTmrSet函数 */ p_tmr->_set_period = (OS_TICK )0; /* 该变量为兼容层内部使用,用于配合3.08版本中OSTmrSet函数 */ p_tmr->_dly = (OS_TICK )0; /* 该变量为兼容层内部使用,用于带有延迟的周期延时 */ #if OS_CFG_DBG_EN > 0u && !defined PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->DbgPrevPtr = (OS_TMR *)0; p_tmr->DbgNextPtr = (OS_TMR *)0; #endif } /* ************************************************************************************************************************ * ADD/REMOVE TIMER TO/FROM DEBUG TABLE * * Description: These functions are called by uC/OS-III to add or remove a timer to/from a timer debug table. * * Arguments : p_tmr is a pointer to the timer to add/remove * * Returns : none * * Note(s) : These functions are INTERNAL to uC/OS-III and your application should not call it. ************************************************************************************************************************ */ #if OS_CFG_DBG_EN > 0u && !defined PKG_USING_UCOSIII_WRAPPER_TINY void OS_TmrDbgListAdd (OS_TMR *p_tmr) { p_tmr->DbgPrevPtr = (OS_TMR *)0; if (OSTmrDbgListPtr == (OS_TMR *)0) { p_tmr->DbgNextPtr = (OS_TMR *)0; } else { p_tmr->DbgNextPtr = OSTmrDbgListPtr; OSTmrDbgListPtr->DbgPrevPtr = p_tmr; } OSTmrDbgListPtr = p_tmr; } void OS_TmrDbgListRemove (OS_TMR *p_tmr) { OS_TMR *p_tmr_next; OS_TMR *p_tmr_prev; p_tmr_prev = p_tmr->DbgPrevPtr; p_tmr_next = p_tmr->DbgNextPtr; if (p_tmr_prev == (OS_TMR *)0) { OSTmrDbgListPtr = p_tmr_next; if (p_tmr_next != (OS_TMR *)0) { p_tmr_next->DbgPrevPtr = (OS_TMR *)0; } p_tmr->DbgNextPtr = (OS_TMR *)0; } else if (p_tmr_next == (OS_TMR *)0) { p_tmr_prev->DbgNextPtr = (OS_TMR *)0; p_tmr->DbgPrevPtr = (OS_TMR *)0; } else { p_tmr_prev->DbgNextPtr = p_tmr_next; p_tmr_next->DbgPrevPtr = p_tmr_prev; p_tmr->DbgNextPtr = (OS_TMR *)0; p_tmr->DbgPrevPtr = (OS_TMR *)0; } } #endif /* ************************************************************************************************************************ * INITIALIZE THE TIMER MANAGER * * Description: This function is called by OSInit() to initialize the timer manager module. * * Argument(s): p_err is a pointer to a variable that will contain an error code returned by this function. * * OS_ERR_NONE * OS_ERR_TMR_STK_INVALID if you didn't specify a stack for the timer task * OS_ERR_TMR_STK_SIZE_INVALID if you didn't allocate enough space for the timer stack * OS_ERR_PRIO_INVALID if you specified the same priority as the idle task * OS_ERR_xxx any error code returned by OSTaskCreate() * * Returns : none * * Note(s) : 1) This function is INTERNAL to uC/OS-III and your application MUST NOT call it. ************************************************************************************************************************ */ void OS_TmrInit (OS_ERR *p_err) { #ifndef PKG_USING_UCOSIII_WRAPPER_TINY OSTmrQty = (OS_OBJ_QTY)0; #if OS_CFG_DBG_EN > 0u OSTmrDbgListPtr = (OS_TMR *)0; #endif #endif } /* ************************************************************************************************************************ * 内部回调函数 * * Description: 由于RT-Thread的定时器回调函数参数只有一个,而uCOS-III的定时器回调函数参数有两个,因此需要 * 先由RTT调用内部回调函数,再由内部回调函数调用uCOS-III的回调函数,以此完成参数的转换。 ************************************************************************************************************************ */ static void OS_TmrCallback(void *p_ara) { OS_TMR *p_tmr; OS_ERR err; OS_TMR_CALLBACK_PTR callback; void * arg; OS_OPT opt; OS_TICK dly; OS_TICK period; CPU_SR_ALLOC(); p_tmr = (OS_TMR*)p_ara; #if OS_CFG_CALLED_FROM_ISR_CHK_EN > 0u if(OSIntNestingCtr > (OS_NESTING_CTR)0) /* 检查是否在中断中运行 */ { RT_DEBUG_LOG(OS_CFG_DBG_EN,("uCOS-III的定时器是在任务中运行的,不可以在RTT的Hard模式下运行\n")); return; } #endif if(p_tmr->Opt==OS_OPT_TMR_PERIODIC && p_tmr->_dly && p_tmr->Period) { /*带有延迟的周期延时,延迟延时已经完毕,开始进行正常周期延时*/ CPU_CRITICAL_ENTER(); p_tmr->_dly = 0; /* 延迟部分清零,防止再进入本条件分支语句 */ p_tmr->Tmr.init_tick = p_tmr->Period * (OS_CFG_TICK_RATE_HZ / OS_CFG_TMR_TASK_RATE_HZ); p_tmr->Tmr.timeout_tick = rt_tick_get() + p_tmr->Tmr.init_tick; p_tmr->Tmr.parent.flag |= RT_TIMER_FLAG_PERIODIC; /* 定时器设置为周期模式 */ #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Match = rt_tick_get() + p_tmr->Tmr.init_tick; p_tmr->Remain = p_tmr->Period; #endif CPU_CRITICAL_EXIT(); rt_timer_start(&(p_tmr->Tmr)); /* 开启定时器 */ } else if(p_tmr->Opt == OS_OPT_TMR_ONE_SHOT) { CPU_CRITICAL_ENTER(); p_tmr->State = OS_TMR_STATE_COMPLETED; #ifndef PKG_USING_UCOSIII_WRAPPER_TINY p_tmr->Remain = 0; #endif CPU_CRITICAL_EXIT(); } else if(p_tmr->Opt == OS_OPT_TMR_PERIODIC) { #ifndef PKG_USING_UCOSIII_WRAPPER_TINY CPU_CRITICAL_ENTER(); p_tmr->Match = rt_tick_get() + p_tmr->Tmr.init_tick; p_tmr->Remain = p_tmr->Period; CPU_CRITICAL_EXIT(); #endif } /*调用真正uCOS-III的软件定时器回调函数*/ OSSchedLock(&err); p_tmr->CallbackPtr((void *)p_tmr, p_tmr->CallbackPtrArg); OSSchedUnlock(&err); /*开始处理OSTmrSet函数的设置*/ if(p_tmr->_set_dly || p_tmr->_set_period) /* 检查是否调用OSTmrSet函数 */ { OSTmrStop(p_tmr,OS_OPT_TMR_NONE,0,&err); /* 停止当前定时器 */ callback = p_tmr->CallbackPtr; arg = p_tmr->CallbackPtrArg; opt = p_tmr->Opt; dly = p_tmr->_set_dly; period = p_tmr->_set_period; OSTmrDel(p_tmr,&err); /* 删除老定时器,_set_dly/_set_period会在此函数中清零 */ OSTmrCreate(p_tmr, p_tmr->Tmr.parent.name, /* 创建新定时器,并装填新的参数 */ dly, period, opt, callback, arg, &err); OSTmrStart(p_tmr, &err); /* 启动装填新参数的定时器 */ } } #endif
37.929636
124
0.479364
[ "object" ]
ca52879d1f5523cd520b5a50b22e1fbc94130712
2,517
c
C
ConfProfile/jni/strongswan/src/conftest/hooks/set_ike_version.c
Infoss/conf-profile-4-android
619bd63095bb0f5a67616436d5510d24a233a339
[ "MIT" ]
2
2017-10-16T07:51:18.000Z
2019-06-16T12:07:52.000Z
strongswan/strongswan-5.3.2/src/conftest/hooks/set_ike_version.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
5
2016-01-25T18:04:42.000Z
2016-02-25T08:54:56.000Z
strongswan/strongswan-5.3.2/src/conftest/hooks/set_ike_version.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
2
2016-01-25T17:14:17.000Z
2016-02-13T20:14:09.000Z
/* * Copyright (C) 2010 Martin Willi * Copyright (C) 2010 revosec AG * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include "hook.h" #include <encoding/payloads/unknown_payload.h> typedef struct private_set_ike_version_t private_set_ike_version_t; /** * Private data of an set_ike_version_t object. */ struct private_set_ike_version_t { /** * Implements the hook_t interface. */ hook_t hook; /** * Alter requests or responses? */ bool req; /** * ID of message to alter. */ int id; /** * Major version to set */ int major; /** * Minor version to set */ int minor; /** * Higher version supported? */ bool higher; }; METHOD(listener_t, message, bool, private_set_ike_version_t *this, ike_sa_t *ike_sa, message_t *message, bool incoming, bool plain) { if (!incoming && plain && message->get_request(message) == this->req && message->get_message_id(message) == this->id) { DBG1(DBG_CFG, "setting IKE version of message ID %d to %d.%d", this->id, this->major, this->minor); message->set_major_version(message, this->major); message->set_minor_version(message, this->minor); if (this->higher) { message->set_version_flag(message); } } return TRUE; } METHOD(hook_t, destroy, void, private_set_ike_version_t *this) { free(this); } /** * Create the IKE_AUTH fill hook */ hook_t *set_ike_version_hook_create(char *name) { private_set_ike_version_t *this; INIT(this, .hook = { .listener = { .message = _message, }, .destroy = _destroy, }, .req = conftest->test->get_bool(conftest->test, "hooks.%s.request", TRUE, name), .id = conftest->test->get_int(conftest->test, "hooks.%s.id", 0, name), .major = conftest->test->get_int(conftest->test, "hooks.%s.major", 2, name), .minor = conftest->test->get_int(conftest->test, "hooks.%s.minor", 0, name), .higher = conftest->test->get_bool(conftest->test, "hooks.%s.higher", FALSE, name), ); return &this->hook; }
22.473214
77
0.671434
[ "object" ]
ca545f263dcddb85955c3e86bcd08931853c3aa1
26,035
c
C
tmp1/c55x-sim2/foo/c5535_bsl_revc/ezdsp5535_v1/c55xx_csl/src/csl_intc.c
jwestmoreland/eZdsp-DBG-sim
f6eacd75d4f928dec9c751545e9e919d052e4ade
[ "MIT" ]
1
2020-08-27T11:31:13.000Z
2020-08-27T11:31:13.000Z
tmp1/c55x-sim2/foo/c5535_bsl_revc/ezdsp5535_v1/c55xx_csl/src/csl_intc.c
jwestmoreland/eZdsp-DBG-sim
f6eacd75d4f928dec9c751545e9e919d052e4ade
[ "MIT" ]
null
null
null
tmp1/c55x-sim2/foo/c5535_bsl_revc/ezdsp5535_v1/c55xx_csl/src/csl_intc.c
jwestmoreland/eZdsp-DBG-sim
f6eacd75d4f928dec9c751545e9e919d052e4ade
[ "MIT" ]
null
null
null
/* ============================================================================ * Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005, 2008 * * Use of this software is controlled by the terms and conditions found in the * license agreement under which this software has been supplied. * ============================================================================ */ /** @file csl_intc.c * * @brief INTC functional layer API source file * * Path: \\(CSLPATH)\\src */ /* ============================================================================ * Revision History * ================ * * ============================================================================ */ #include "csl_intc.h" #include <stdio.h> // resolve NULL /** ============================================================================ * @n@b IRQ_init * * @b Description * @n This is the initialization function for INTC module. This function * initializes the CSL INTC data structures * * * @b Arguments * @verbatim dispatchTable - Dispatch table biosPresent - DspBios is present or not * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_init is successful * @li CSL_ESYS_INVPARAMS - Invalid parameter * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n Initializes CSL data structures * * * @b Modifies * @n 1. The status variable * @n 2. Update CSL_IrqDataObj structure * * @b Example * @verbatim CSL_Status status; CSL_IRQ_Dispatch dispatchTable ... status = IRQ_init(&dispatchTable,0); ... @endverbatim * ============================================================================ */ CSL_Status IRQ_init ( CSL_IRQ_Dispatch *dispatchTable, Uint16 biosPresent ) { int i; if( INV == dispatchTable ) { return CSL_ESYS_INVPARAMS; } CSL_IRQ_DATA.IrqDispatchTable = dispatchTable; for (i=0; i<=IRQ_EVENT_CNT-1; i++) CSL_IRQ_DATA.IrqIntTable[i] = i; for(i=0; i<= IRQ_EVENT_CNT-1; i++) CSL_IRQ_DATA.IrqEventTable[i] = IRQ_MASK32(i); CSL_IRQ_DATA.biosPresent = biosPresent; return CSL_SOK; } /** ============================================================================ * @n@b IRQ_clear * * @b Description * @n This function acknowledge the interrupt by clearing * the corresponding Interrupt flag . * * @b Arguments * @verbatim eventId Event Id for the peripheral in IFR Register @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - INTC_close is successful * @li CSL_ESYS_INVPARAMS - Invalid handle * * <b> Pre Condition </b> * @n IRQ_setVecs and IRQ_plug API should be called * before calling this API * * <b> Post Condition </b> * @n IFR Register bit will be cleared * * @b Modifies * @n 1. The status variable * @n 2. IFR Register * @b Example * @verbatim Uint16 EventId; CSL_status status; ... status = IRQ_clear(EventId); @endverbatim * ============================================================================ */ CSL_Status IRQ_clear ( Uint16 EventId ) { Uint16 bit; Bool old_intm; /* Wrong Event Id */ if (SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } old_intm = IRQ_globalDisable(); bit = EventId; if(EventId > RCV2_EVENT) { /* IFR1 Register */ bit = bit - XMT3_EVENT; CSL_FINSR(CSL_CPU_REGS->IFR1, bit, bit,CSL_INTC_BIT_SET); } else { /* IFR0 Register */ CSL_FINSR(CSL_CPU_REGS->IFR0, bit, bit,CSL_INTC_BIT_SET); } IRQ_globalRestore(old_intm); return CSL_SOK; } /** ============================================================================ * @n@b IRQ_clearAll * * @b Description * @n This function clears all the interrupts. Both IFR0 and IFR1 are cleared * by this function. * * @b Arguments * @verbatim None @endverbatim * * <b> Return Value </b> None * * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n Clears All the interrupt * * @b Modifies * @n Interrupt Flag Registers * * @b Example * @verbatim IRQ_clearAll(); @endverbatim * ============================================================================ */ void IRQ_clearAll(void) { /* Clear IFR0 */ CSL_CPU_REGS->IFR0 = CSL_INTC_IFR_RESET; /* Clear IFR1 */ CSL_CPU_REGS->IFR1 = CSL_INTC_IFR_RESET; } /** ============================================================================ * @n@b IRQ_config * * @b Description * @n This API function is used to update ISR function * and its arguments passed in config structure for * the corresponding event in dispatch table * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers . config Config structure * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_config call is successful * @li CSL_ESYS_BADHANDLE - Invalid handle * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_init API should be called before this API call * * <b> Post Condition </b> * @n It updates CSL_IrqDataObj structure * @b Modifies * @n 1. The status variable * @n 2. Hardware Registers * * @b Example * @verbatim interrupt void ISR_routine(void); CSL_Status status; // Adress for interrupt vector table extern void VECSTART(void); IRQ_Config config; Uint16 EventId; status = IRQ_init(); ... // to set the interrupt vector table address IRQ_setVecs((Uint32)&VECSTART); ... config.funcAddr = &ISR_routine; status = IRQ_config(EventId,&config); ... @endverbatim * ============================================================================ */ CSL_Status IRQ_config ( Uint16 EventId, CSL_IRQ_Config *config ) { if(NULL == config) { return CSL_ESYS_INVPARAMS; } /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } CSL_IRQ_DATA.IrqDispatchTable[EventId].funcAddr = config->funcAddr; CSL_IRQ_DATA.IrqDispatchTable[EventId].funcArg = config->funcArg; CSL_IRQ_DATA.IrqDispatchTable[EventId].ierMask = config->ierMask ; CSL_IRQ_DATA.IrqDispatchTable[EventId].cacheCtrl = config->cacheCtrl; return CSL_SOK; } /** ============================================================================ * @n@b IRQ_getConfig * * @b Description * @n It reads the configuration values (function address,arguments etc) * from global IRQ data object structure * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers config Config structure @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_getConfig is successfull * * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_config should be called before calling this API * * <b> Post Condition </b> * @n The configuration structure will be populated * * @b Modifies * @n 1.status * 2.config structure * @b Example * @verbatim // Global IRQ object structure CSL_IrqDataObj CSL_IrqData; CSL_Status status; IRQ_Config config; Uint16 EventId; ... status = IRQ_config(EventId,&config); ... status = IRQ_getConfig(EventId,&config); @endverbatim * ============================================================================ */ CSL_Status IRQ_getConfig ( Uint16 EventId, CSL_IRQ_Config *config ) { if(NULL == config) { return CSL_ESYS_INVPARAMS; } /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } config->funcAddr = (IRQ_IsrPtr)CSL_IRQ_DATA.IrqDispatchTable[EventId].funcAddr; config->funcArg = CSL_IRQ_DATA.IrqDispatchTable[EventId].funcArg ; config->ierMask = CSL_IRQ_DATA.IrqDispatchTable[EventId].ierMask; config->cacheCtrl = CSL_IRQ_DATA.IrqDispatchTable[EventId].cacheCtrl; return CSL_SOK; } /** ============================================================================ * @n@b IRQ_disable * * @b Description * @n It disables the corresponding interrupt in IER Register and * also return the previous bit mask value * * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers * @endverbatim * * <b> Return Value </b> * IER Register value before enabling * * <b> Pre Condition </b> * @n IRQ_setVecs andIRQ_plug API should be called * before calling this API * * <b> Post Condition </b> * @n It disabled the corresponding interrupt bit in IER Register * * @b Modifies * @n IER h/w Registers * * @b Example * @verbatim Uint16 EventId; int old_IER; old_IER = IRQ_disable(EventId); @endverbatim * ============================================================================ */ int IRQ_disable ( Uint16 EventId ) { Uint16 bit; int old_flag; Bool old_intm; /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } bit = EventId; old_intm = IRQ_globalDisable(); /* EventId greater than 15 */ if (EventId > RCV2_EVENT) { bit = bit - XMT3_EVENT; old_flag = CSL_FEXTR(CSL_CPU_REGS->IER1,bit,bit) ; CSL_FINSR(CSL_CPU_REGS->IER1, bit,bit,CSL_INTC_BIT_RESET); } /* EventId less than 15 */ else { old_flag = CSL_FEXTR(CSL_CPU_REGS->IER0,bit,bit) ; CSL_FINSR(CSL_CPU_REGS->IER0, bit,bit,CSL_INTC_BIT_RESET); } IRQ_globalRestore(old_intm); return old_flag; } /** ============================================================================ * @n@b IRQ_disableAll * * @b Description * @n This function disables all the interrupts avaible on C5505 DSP. Both * IER0 and IER1 are cleared by this function * * @b Arguments * @verbatim None * @endverbatim * * <b> Return Value </b> * None * * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n Disables all the interrupts * * @b Modifies * @n Interrupt Enable Registers * * @b Example * @verbatim IRQ_disableAll(); @endverbatim * ============================================================================ */ void IRQ_disableAll (void) { /* Clear IER0 */ CSL_CPU_REGS->IER0 = CSL_CPU_IER0_RESETVAL; /* Clear IER1 */ CSL_CPU_REGS->IER1 = CSL_CPU_IER1_RESETVAL; } /** ============================================================================ * @n@b IRQ_enable * * @b Description * @n It enables the corresponding interrupt bit in IER Register and * also return the previous bit mask value * * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers * @endverbatim * * <b> Return Value </b> * IER Register value before enabling * * <b> Pre Condition </b> * @n IRQ_setVecs andIRQ_plug API should be called * before calling this API * * <b> Post Condition </b> * @n It set the corresponding interrupt bit to 1 in IER Register * * @b Modifies * @n IER CPU Registers * * @b Example * @verbatim Uint16 EventId; int old_IER; old_IER = IRQ_enable(EventId); @endverbatim * ============================================================================ */ int IRQ_enable ( Uint16 EventId ) { Uint16 bit; int old_flag; Bool old_intm; /* Wrong Event Id */ if (SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } bit= EventId ; old_intm = IRQ_globalDisable(); if (EventId > RCV2_EVENT) { bit = bit - XMT3_EVENT; old_flag = CSL_FEXTR (CSL_CPU_REGS->IER1,bit,bit); CSL_FINSR (CSL_CPU_REGS->IER1, bit,bit,CSL_INTC_BIT_SET); } else { old_flag = CSL_FEXTR (CSL_CPU_REGS->IER0,bit,bit); CSL_FINSR (CSL_CPU_REGS->IER0, bit, bit,CSL_INTC_BIT_SET); } IRQ_globalRestore(old_intm); return old_flag; } /** ============================================================================ * @n@b IRQ_restore * * @b Description * @n It restores the given value in IER Register passed in API * * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers value bit value - 1 or 0 * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK always returns * * <b> Pre Condition </b> * @n IRQ_enable or IRQ_disable should be called before calling this API * * <b> Post Condition </b> * @n It configures the given bit value in IER Register * * @b Modifies * @n IER CPU Registers * * @b Example * @verbatim Uint16 EventId; int value; CSL_Status status; value = IRQ_enable(EventId); .. status = IRQ_restore(EventId,value); @endverbatim * ============================================================================ */ CSL_Status IRQ_restore( Uint16 EventId, int value ) { Uint16 bit; Bool old_intm; /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } bit = EventId; old_intm = IRQ_globalDisable(); if(EventId > RCV2_EVENT) { bit = bit - XMT3_EVENT; CSL_FINSR (CSL_CPU_REGS->IER1, bit, bit,value); } else { CSL_FINSR (CSL_CPU_REGS->IER0, bit, bit,value); } IRQ_globalRestore(old_intm); return CSL_SOK; } /** ============================================================================ * @n@b IRQ_getArg * * @b Description * @n It gets the ISR function arguments correspond to eventId * * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_enable is successful * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_init,IRQ_config should be called before calling this API * * <b> Post Condition </b> * @n * @b Modifies * @n arg variable * * @b Example * @verbatim Uint16 EventId; Uint32 arg; CSL_Status status; status = IRQ_getArg(EventId,&arg); @endverbatim * ============================================================================ */ CSL_Status IRQ_getArg( Uint16 EventId, Uint32 *arg ) { if(NULL == arg) { return CSL_ESYS_INVPARAMS; } /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } *arg = CSL_IRQ_DATA.IrqDispatchTable[EventId].funcArg ; return CSL_SOK; } /** ============================================================================ * @n@b IRQ_setArg * * @b Description * @n It sets the ISR function arguments correspond to the eventId * * @b Arguments * @verbatim EventId Id for peripheral in IFR and IMR Registers val value for ISR arguments * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_enable is successful * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_init should be called before calling this API * * <b> Post Condition </b> * @n * @b Modifies * @n status * * @b Example * @verbatim // Global IRQ object structure CSL_IrqDataObj CSL_IrqData; Uint16 EventId; Uint32 val; CSL_Status status; status = IRQ_setArg(EventId,val); @endverbatim * ============================================================================ */ CSL_Status IRQ_setArg( Uint16 EventId, Uint32 val ) { /* Wrong Event Id */ if (SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } CSL_IRQ_DATA.IrqDispatchTable[EventId].funcArg = val; return CSL_SOK; } /** ============================================================================ * @n@b IRQ_map * * @b Description * @n It initialize the interrupt table with the event mask value for * the corresponding event id * @b Arguments * @verbatim EventId Id for peripheral in IFR and IER Registers * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_enable is successful * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_init should be called before calling this API * * <b> Post Condition </b> * @n * @b Modifies * @n CSL_IrqData structure * * @b Example * @verbatim Uint16 EventId; CSL_Status status; status = IRQ_map(EventId); @endverbatim * ============================================================================ */ CSL_Status IRQ_map( Uint16 EventId ) { /* Wrong Event Id */ if (SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } CSL_IRQ_DATA.IrqIntTable[EventId] = IRQ_MASK32(EventId); return CSL_SOK; } /** ============================================================================ * @n@b IRQ_setVecs * * @b Description * @n It stores the Interrupt vector table address in Interrupt vector * pointer DSP and Interrupt vector pointer host Registers * * @b Arguments * @verbatim Ivpd Interrupt Vector Pointer Address * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_enable is successful * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n It sets IVPD and IVPH CPU Registers * @b Modifies * @n IVPD and IVPH CPU Registers * * @b Example * @verbatim // Interrupt Vector Table Address Uint32 Ivpd; CSL_Status status; status = IRQ_setVecs(Ivpd); @endverbatim * ============================================================================ */ CSL_Status IRQ_setVecs( Uint32 Ivpd ) { Bool old_intm; Uint16 val = (Uint16)((Ivpd & CSL_CPU_IVPD_MASK) >> CSL_CPU_IVPD_SHIFT); old_intm = IRQ_globalDisable(); CSL_CPU_REGS->IVPD = val; CSL_CPU_REGS->IVPH = val; IRQ_globalRestore(old_intm); return CSL_SOK; } /** ============================================================================ * @n@b IRQ_test * * @b Description * @n It gets the status bit for the particular Interupt from IFR Registers * * @b Arguments * @verbatim EventId Interrupt Vector Pointer Address * IntStatus to store Interrupt Status bit in IFR Register * @endverbatim * * <b> Return Value </b> CSL_Status * @li CSL_SOK - IRQ_enable is successful * @li CSL_ESYS_BADHANDLE - The handle is passed is * invalid * @li CSL_ESYS_INVPARAMS - Invalid parameter * * <b> Pre Condition </b> * @n IRQ_init should be called before calling this API * * <b> Post Condition </b> * @n It stores the IFR bit value in IntStatus variable * @b Modifies * @n 1. IntStatus - to store Interrupt flag bit * @n * * @b Example * @verbatim Uint16 EventId; CSL_Status status; bool IntStatus; status = IRQ_test(EventId,&IntStatus); @endverbatim * ============================================================================ */ CSL_Status IRQ_test( Uint16 EventId, Bool *IntStatus ) { Uint16 bit; Bool old_intm; if(NULL == IntStatus) { return CSL_ESYS_INVPARAMS; } /* Wrong Event Id */ if(SINT31_EVENT < EventId) { return CSL_ESYS_INVPARAMS; } bit= EventId ; old_intm = IRQ_globalDisable(); if(EventId > RCV2_EVENT) { bit = bit - XMT3_EVENT; *IntStatus = CSL_FEXTR(CSL_CPU_REGS->IFR1, bit, bit); } else { *IntStatus = CSL_FEXTR(CSL_CPU_REGS->IFR0, bit, bit); } IRQ_globalRestore(old_intm); return CSL_SOK; } /** ============================================================================ * @n@b IRQ_globalDisable * * @b Description * @n It disables the interrupt globally by disabling INTM bit and also * return the previous mask value for INTM bit * * @b Arguments * @verbatim * @endverbatim * * <b> Return Value </b> Bool * @li Old INTM bit value * * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n set INTM bit to 1 in ST1 CPU Register * @b Modifies * 1. ST1 CPU Register * @b Example * @verbatim Bool oldMask; .... oldMask = IRQ_globalDisable(); @endverbatim * ============================================================================ */ Bool IRQ_globalDisable() { Bool value; value = CSL_FEXT(CSL_CPU_REGS->ST1_55, CPU_ST1_55_INTM); asm("\tNOP ;====> CODE AUTO-GENERATED by CSL"); // #ifdef ALGEBRAIC // asm("\tBIT (ST1,#ST1_INTM) = #1 ;====> CODE AUTO-GENERATED by CSL"); // #else asm("\tBSET INTM ;====> CODE AUTO-GENERATED by CSL"); // #endif return value; } /** ============================================================================ * @n@b IRQ_globalEnable * * @b Description * @n It enables the interrupt globally by enabling INTM bit and also * return the previous mask value for INTM bit * * @b Arguments * @verbatim * @endverbatim * * <b> Return Value </b> Bool * @li Old INTM bit value * * <b> Pre Condition </b> * @n None * * <b> Post Condition </b> * @n set INTM bit to 0 in ST1 CPU Register * @b Modifies * 1.ST1 CPU Register * @b Example * @verbatim Bool oldMask; .... oldMask = IRQ_globalEnable(); @endverbatim * ============================================================================ */ Bool IRQ_globalEnable() { Bool value; value = CSL_FEXT(CSL_CPU_REGS->ST1_55, CPU_ST1_55_INTM); asm("\tNOP ;====> CODE AUTO-GENERATED by CSL"); // #ifdef ALGEBRAIC // asm("\tBIT (ST1,#ST1_INTM) = #0 ;====> CODE AUTO-GENERATED by CSL"); // #else asm("\tBCLR INTM ;====> CODE AUTO-GENERATED by CSL"); // #endif return value; } /** ============================================================================ * @n@b IRQ_globalRestore * * @b Description * @n It sets INTM bit to the value passed in the API * * @b Arguments * @verbatim val - INTM bit value * @endverbatim * * <b> Return Value </b> void * * <b> Pre Condition </b> * @n IRQ_globalDisable or IRQ_globalEnable should be called * * <b> Post Condition </b> * @n set or clear INTM bit in ST1 CPU Register * @b Modifies * 1. ST1 CPU Register * @b Example * @verbatim Bool val; .... IRQ_globalRestore(val); @endverbatim * ============================================================================ */ void IRQ_globalRestore( Bool value ) { if(value) { asm("\tNOP ;====> CODE AUTO-GENERATED by CSL"); // #ifdef ALGEBRAIC // asm("\tBIT (ST1,#ST1_INTM) = #1 ;====> CODE AUTO-GENERATED by CSL"); // #else asm("\tBSET INTM ;====> CODE AUTO-GENERATED by CSL"); // #endif } else { asm("\tNOP ;====> CODE AUTO-GENERATED by CSL"); // #ifdef ALGEBRAIC // asm("\tBIT (ST1,#ST1_INTM) = #0 ;====> CODE AUTO-GENERATED by CSL"); // #else asm("\tBCLR INTM ;====> CODE AUTO-GENERATED by CSL"); // #endif } }
25.325875
80
0.495218
[ "object", "vector" ]
ca5820c2c4d672b1a6de7514762d5719d8ca3a28
10,113
h
C
source/client/process_impl.h
wjuan-AFK/nighthawk
f56d9c43414d649295db2ed8a584a36017aa165b
[ "Apache-2.0" ]
1
2021-09-16T08:43:16.000Z
2021-09-16T08:43:16.000Z
source/client/process_impl.h
ybbbby/nighthawk
d7e7cae122e74a0013892183370a9c86ff1a83c2
[ "Apache-2.0" ]
null
null
null
source/client/process_impl.h
ybbbby/nighthawk
d7e7cae122e74a0013892183370a9c86ff1a83c2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <map> #include "envoy/api/api.h" #include "envoy/network/address.h" #include "envoy/stats/store.h" #include "envoy/tracing/http_tracer.h" #include "nighthawk/client/client_worker.h" #include "nighthawk/client/factories.h" #include "nighthawk/client/options.h" #include "nighthawk/client/output_collector.h" #include "nighthawk/client/process.h" #include "nighthawk/common/statistic.h" #include "external/envoy/source/common/access_log/access_log_manager_impl.h" #include "external/envoy/source/common/common/logger.h" #include "external/envoy/source/common/common/random_generator.h" #include "external/envoy/source/common/event/real_time_system.h" #include "external/envoy/source/common/grpc/context_impl.h" #include "external/envoy/source/common/http/context_impl.h" #include "external/envoy/source/common/protobuf/message_validator_impl.h" #include "external/envoy/source/common/quic/quic_stat_names.h" #include "external/envoy/source/common/router/context_impl.h" #include "external/envoy/source/common/secret/secret_manager_impl.h" #include "external/envoy/source/common/stats/allocator_impl.h" #include "external/envoy/source/common/stats/thread_local_store.h" #include "external/envoy/source/common/thread_local/thread_local_impl.h" #include "external/envoy/source/common/upstream/cluster_manager_impl.h" #include "external/envoy/source/exe/platform_impl.h" #include "external/envoy/source/exe/process_wide.h" #include "external/envoy/source/extensions/transport_sockets/tls/context_manager_impl.h" #include "external/envoy/source/server/config_validation/admin.h" #include "external/envoy_api/envoy/config/bootstrap/v3/bootstrap.pb.h" #include "source/client/benchmark_client_impl.h" #include "source/client/factories_impl.h" #include "source/client/flush_worker_impl.h" namespace Nighthawk { namespace Client { class ClusterManagerFactory; /** * Only a single instance is allowed at a time machine-wide in this implementation. * Running multiple instances at the same might introduce noise into the measurements. * If there turns out to be a desire to run multiple instances at the same time, we could * introduce a --lock-name option. Note that multiple instances in the same process may * be problematic because of Envoy enforcing a single runtime instance. */ class ProcessImpl : public Process, public Envoy::Logger::Loggable<Envoy::Logger::Id::main> { public: /** * Instantiates a ProcessImpl * @param options provides the options configuration to be used. * @param time_system provides the Envoy::Event::TimeSystem implementation that will be used. * @param process_wide optional parameter which can be used to pass a pre-setup reference to * an active Envoy::ProcessWide instance. ProcessImpl will add a reference to this when passed, * and hold on that that throughout its lifetime. * If this parameter is not supplied, ProcessImpl will contruct its own Envoy::ProcessWide * instance. */ ProcessImpl(const Options& options, Envoy::Event::TimeSystem& time_system, const std::shared_ptr<Envoy::ProcessWide>& process_wide = nullptr); ~ProcessImpl() override; /** * @return uint32_t the concurrency we determined should run at based on configuration and * available machine resources. */ uint32_t determineConcurrency() const; /** * Runs the process. * * @param collector output collector implementation which will collect and hold the native output * format. * @return true iff execution should be considered successful. */ bool run(OutputCollector& collector) override; /** * Should be called before destruction to cleanly shut down. */ void shutdown() override; bool requestExecutionCancellation() override; private: /** * @brief Creates a cluster for usage by a remote request source. * * @param uri The parsed uri of the remote request source. * @param worker_number The worker number that we are creating this cluster for. * @param config The bootstrap configuration that will be modified. */ void addRequestSourceCluster(const Uri& uri, int worker_number, envoy::config::bootstrap::v3::Bootstrap& config) const; void addTracingCluster(envoy::config::bootstrap::v3::Bootstrap& bootstrap, const Uri& uri) const; void setupTracingImplementation(envoy::config::bootstrap::v3::Bootstrap& bootstrap, const Uri& uri) const; void createBootstrapConfiguration(envoy::config::bootstrap::v3::Bootstrap& bootstrap, const std::vector<UriPtr>& uris, const UriPtr& request_source_uri, int number_of_workers) const; void maybeCreateTracingDriver(const envoy::config::trace::v3::Tracing& configuration); void configureComponentLogLevels(spdlog::level::level_enum level); /** * Prepare the ProcessImpl instance by creating and configuring the workers it needs for execution * of the load test. * * @param concurrency the amount of workers that should be created. */ void createWorkers(const uint32_t concurrency, const absl::optional<Envoy::SystemTime>& schedule); std::vector<StatisticPtr> vectorizeStatisticPtrMap(const StatisticPtrMap& statistics) const; std::vector<StatisticPtr> mergeWorkerStatistics(const std::vector<ClientWorkerPtr>& workers) const; void setupForHRTimers(); /** * If there are sinks configured in bootstrap, populate stats_sinks with sinks * created through NighthawkStatsSinkFactory and add them to store_root_. * * @param bootstrap the bootstrap configuration which include the stats sink configuration. * @param stats_sinks a Sink list to be populated. */ void setupStatsSinks(const envoy::config::bootstrap::v3::Bootstrap& bootstrap, std::list<std::unique_ptr<Envoy::Stats::Sink>>& stats_sinks); bool runInternal(OutputCollector& collector, const std::vector<UriPtr>& uris, const UriPtr& request_source_uri, const UriPtr& tracing_uri, const absl::optional<Envoy::SystemTime>& schedule); /** * Compute the offset at which execution should start. We adhere to the scheduled start passed in * as an argument when specified, otherwise we need a delay that will be sufficient for all the * workers to get up and running. * * @param time_system Time system used to obtain the current time. * @param scheduled_start Optional scheduled start. * @param concurrency The number of workers that will be used during execution. * @return Envoy::MonotonicTime Time at which execution should start. */ static Envoy::MonotonicTime computeFirstWorkerStart(Envoy::Event::TimeSystem& time_system, const absl::optional<Envoy::SystemTime>& scheduled_start, const uint32_t concurrency); /** * We offset the start of each thread so that workers will execute tasks evenly spaced in * time. Let's assume we have two workers w0/w1, which should maintain a combined global pace of * 1000Hz. w0 and w1 both run at 500Hz, but ideally their execution is evenly spaced in time, * and not overlapping. Workers start offsets can be computed like * "worker_number*(1/global_frequency))", which would yield T0+[0ms, 1ms]. This helps reduce * batching/queueing effects, both initially, but also by calibrating the linear rate limiter we * currently have to a precise starting time, which helps later on. * * @param concurrency The number of workers that will be used during execution. * @param rps Anticipated requests per second during execution. * @return std::chrono::nanoseconds The delay that should be used as an offset between each * independent worker execution start. */ static std::chrono::nanoseconds computeInterWorkerDelay(const uint32_t concurrency, const uint32_t rps); const envoy::config::core::v3::Node node_; const Envoy::Protobuf::RepeatedPtrField<std::string> node_context_params_; std::shared_ptr<Envoy::ProcessWide> process_wide_; Envoy::PlatformImpl platform_impl_; Envoy::Event::TimeSystem& time_system_; Envoy::Stats::SymbolTableImpl symbol_table_; Envoy::Stats::AllocatorImpl stats_allocator_; Envoy::ThreadLocal::InstanceImpl tls_; Envoy::Stats::ThreadLocalStoreImpl store_root_; Envoy::Quic::QuicStatNames quic_stat_names_; Envoy::Api::ApiPtr api_; Envoy::Event::DispatcherPtr dispatcher_; std::vector<ClientWorkerPtr> workers_; const BenchmarkClientFactoryImpl benchmark_client_factory_; const TerminationPredicateFactoryImpl termination_predicate_factory_; const SequencerFactoryImpl sequencer_factory_; const RequestSourceFactoryImpl request_generator_factory_; const Options& options_; Envoy::Init::ManagerImpl init_manager_; Envoy::LocalInfo::LocalInfoPtr local_info_; Envoy::Random::RandomGeneratorImpl generator_; Envoy::Server::ConfigTrackerImpl config_tracker_; Envoy::Secret::SecretManagerImpl secret_manager_; Envoy::Http::ContextImpl http_context_; Envoy::Grpc::ContextImpl grpc_context_; Envoy::Thread::MutexBasicLockable access_log_lock_; Envoy::Singleton::ManagerPtr singleton_manager_; Envoy::AccessLog::AccessLogManagerImpl access_log_manager_; std::unique_ptr<Envoy::Extensions::TransportSockets::Tls::ContextManagerImpl> ssl_context_manager_; std::unique_ptr<ClusterManagerFactory> cluster_manager_factory_; Envoy::Upstream::ClusterManagerPtr cluster_manager_{}; std::unique_ptr<Envoy::Runtime::ScopedLoaderSingleton> runtime_singleton_; Envoy::Init::WatcherImpl init_watcher_; Envoy::Tracing::HttpTracerSharedPtr http_tracer_; Envoy::Server::ValidationAdmin admin_; Envoy::ProtobufMessage::ProdValidationContextImpl validation_context_; bool shutdown_{true}; Envoy::Thread::MutexBasicLockable workers_lock_; bool cancelled_{false}; std::unique_ptr<FlushWorkerImpl> flush_worker_; Envoy::Router::ContextImpl router_context_; }; } // namespace Client } // namespace Nighthawk
47.478873
100
0.755068
[ "vector" ]
ca636e3104d481f04218439068b9a2c6da5d79fc
2,414
h
C
third_party/agg/include/agg_vpgen_clip_polygon.h
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
11
2018-11-10T11:14:11.000Z
2021-12-27T17:17:08.000Z
third_party/agg/include/agg_vpgen_clip_polygon.h
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
27
2018-11-11T00:06:25.000Z
2021-06-24T06:43:38.000Z
third_party/agg/include/agg_vpgen_clip_polygon.h
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
7
2018-11-10T20:32:49.000Z
2021-03-15T18:03:42.000Z
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.3 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- #ifndef AGG_VPGEN_CLIP_POLYGON_INCLUDED #define AGG_VPGEN_CLIP_POLYGON_INCLUDED #include "agg_basics.h" namespace agg { //======================================================vpgen_clip_polygon // // See Implementation agg_vpgen_clip_polygon.cpp // class vpgen_clip_polygon { public: vpgen_clip_polygon() : m_clip_box(0, 0, 1, 1), m_x1(0), m_y1(0), m_clip_flags(0), m_num_vertices(0), m_vertex(0), m_cmd(path_cmd_move_to) { } void clip_box(double x1, double y1, double x2, double y2) { m_clip_box.x1 = x1; m_clip_box.y1 = y1; m_clip_box.x2 = x2; m_clip_box.y2 = y2; m_clip_box.normalize(); } double x1() const { return m_clip_box.x1; } double y1() const { return m_clip_box.y1; } double x2() const { return m_clip_box.x2; } double y2() const { return m_clip_box.y2; } static bool auto_close() { return true; } static bool auto_unclose() { return false; } void reset(); void move_to(double x, double y); void line_to(double x, double y); unsigned vertex(double* x, double* y); private: unsigned clipping_flags(double x, double y); private: rect_d m_clip_box; double m_x1; double m_y1; unsigned m_clip_flags; double m_x[4]; double m_y[4]; unsigned m_num_vertices; unsigned m_vertex; unsigned m_cmd; }; } #endif
28.738095
78
0.504143
[ "geometry" ]
ca6d88bcdaaf254aa0cbcde1c2d6b9e1aedf633c
5,435
h
C
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealFixLen.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
7
2021-06-07T16:37:38.000Z
2022-03-20T06:15:15.000Z
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealFixLen.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
null
null
null
Sources/CAudioKit/Devoloop/include/FFTReal/FFTRealFixLen.h
kylestew/AudioKit
4ce9bb325f6576ac2a4141d6e72428dd13d8239d
[ "MIT" ]
2
2021-08-07T00:36:50.000Z
2021-12-28T01:18:08.000Z
/***************************************************************************** FFTRealFixLen.h By Laurent de Soras --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined(ffft_FFTRealFixLen_CURRENT_CODEHEADER) #error Recursive inclusion of FFTRealFixLen code header. #endif #define ffft_FFTRealFixLen_CURRENT_CODEHEADER #if !defined(ffft_FFTRealFixLen_CODEHEADER_INCLUDED) #define ffft_FFTRealFixLen_CODEHEADER_INCLUDED #include "ffft/FFTRealPassDirect.h" #include "ffft/FFTRealPassInverse.h" #include "ffft/FFTRealSelect.h" #include "ffft/def.h" #include <cassert> #include <cmath> namespace std {} namespace ffft { template <int LL2> FFTRealFixLen<LL2>::FFTRealFixLen() : _buffer(FFT_LEN), _br_data(BR_ARR_SIZE), _trigo_data(TRIGO_TABLE_ARR_SIZE), _trigo_osc() { build_br_lut(); build_trigo_lut(); build_trigo_osc(); } template <int LL2> long FFTRealFixLen<LL2>::get_length() const { return (FFT_LEN); } // General case template <int LL2> void FFTRealFixLen<LL2>::do_fft(DataType f[], const DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); assert(FFT_LEN_L2 >= 3); // Do the transform in several passes const DataType *cos_ptr = &_trigo_data[0]; const long *br_ptr = &_br_data[0]; FFTRealPassDirect<FFT_LEN_L2 - 1>::process(FFT_LEN, f, &_buffer[0], x, cos_ptr, TRIGO_TABLE_ARR_SIZE, br_ptr, &_trigo_osc[0]); } // 4-point FFT template <> inline void FFTRealFixLen<2>::do_fft(DataType f[], const DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); f[1] = x[0] - x[2]; f[3] = x[1] - x[3]; const DataType b_0 = x[0] + x[2]; const DataType b_2 = x[1] + x[3]; f[0] = b_0 + b_2; f[2] = b_0 - b_2; } // 2-point FFT template <> inline void FFTRealFixLen<1>::do_fft(DataType f[], const DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); f[0] = x[0] + x[1]; f[1] = x[0] - x[1]; } // 1-point FFT template <> inline void FFTRealFixLen<0>::do_fft(DataType f[], const DataType x[]) { assert(f != 0); assert(x != 0); f[0] = x[0]; } // General case template <int LL2> void FFTRealFixLen<LL2>::do_ifft(const DataType f[], DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); assert(FFT_LEN_L2 >= 3); // Do the transform in several passes DataType *s_ptr = FFTRealSelect<FFT_LEN_L2 & 1>::sel_bin(&_buffer[0], x); DataType *d_ptr = FFTRealSelect<FFT_LEN_L2 & 1>::sel_bin(x, &_buffer[0]); const DataType *cos_ptr = &_trigo_data[0]; const long *br_ptr = &_br_data[0]; FFTRealPassInverse<FFT_LEN_L2 - 1>::process(FFT_LEN, d_ptr, s_ptr, f, cos_ptr, TRIGO_TABLE_ARR_SIZE, br_ptr, &_trigo_osc[0]); } // 4-point IFFT template <> inline void FFTRealFixLen<2>::do_ifft(const DataType f[], DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); const DataType b_0 = f[0] + f[2]; const DataType b_2 = f[0] - f[2]; x[0] = b_0 + f[1] * 2; x[2] = b_0 - f[1] * 2; x[1] = b_2 + f[3] * 2; x[3] = b_2 - f[3] * 2; } // 2-point IFFT template <> inline void FFTRealFixLen<1>::do_ifft(const DataType f[], DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); x[0] = f[0] + f[1]; x[1] = f[0] - f[1]; } // 1-point IFFT template <> inline void FFTRealFixLen<0>::do_ifft(const DataType f[], DataType x[]) { assert(f != 0); assert(x != 0); assert(x != f); x[0] = f[0]; } template <int LL2> void FFTRealFixLen<LL2>::rescale(DataType x[]) const { assert(x != 0); const DataType mul = DataType(1.0 / FFT_LEN); if (FFT_LEN < 4) { long i = FFT_LEN - 1; do { x[i] *= mul; --i; } while (i >= 0); } else { assert((FFT_LEN & 3) == 0); // Could be optimized with SIMD instruction sets (needs alignment check) long i = FFT_LEN - 4; do { x[i + 0] *= mul; x[i + 1] *= mul; x[i + 2] *= mul; x[i + 3] *= mul; i -= 4; } while (i >= 0); } } template <int LL2> void FFTRealFixLen<LL2>::build_br_lut() { _br_data[0] = 0; for (long cnt = 1; cnt < BR_ARR_SIZE; ++cnt) { long index = cnt << 2; long br_index = 0; int bit_cnt = FFT_LEN_L2; do { br_index <<= 1; br_index += (index & 1); index >>= 1; --bit_cnt; } while (bit_cnt > 0); _br_data[cnt] = br_index; } } template <int LL2> void FFTRealFixLen<LL2>::build_trigo_lut() { const double mul = (0.5 * PI) / TRIGO_TABLE_ARR_SIZE; for (long i = 0; i < TRIGO_TABLE_ARR_SIZE; ++i) { using namespace std; _trigo_data[i] = DataType(cos(i * mul)); } } template <int LL2> void FFTRealFixLen<LL2>::build_trigo_osc() { for (int i = 0; i < NBR_TRIGO_OSC; ++i) { OscType &osc = _trigo_osc[i]; const long len = static_cast<long>(TRIGO_TABLE_ARR_SIZE) << (i + 1); const double mul = (0.5 * PI) / len; osc.set_step(mul); } } } #endif #undef ffft_FFTRealFixLen_CURRENT_CODEHEADER
22.836134
80
0.583625
[ "transform" ]
ca6f3d95f5c3f7a710dd9763fd41b7b29644edea
6,509
h
C
moveit_core/dynamics_solver/include/moveit/dynamics_solver/dynamics_solver.h
mamoll/moveit2
37f85e817266b536044aa5812c7ac841ae16a8c3
[ "BSD-3-Clause" ]
1
2021-04-26T00:46:04.000Z
2021-04-26T00:46:04.000Z
moveit_core/dynamics_solver/include/moveit/dynamics_solver/dynamics_solver.h
mamoll/moveit2
37f85e817266b536044aa5812c7ac841ae16a8c3
[ "BSD-3-Clause" ]
3
2021-11-27T10:17:21.000Z
2021-12-03T22:11:07.000Z
moveit_core/dynamics_solver/include/moveit/dynamics_solver/dynamics_solver.h
mamoll/moveit2
37f85e817266b536044aa5812c7ac841ae16a8c3
[ "BSD-3-Clause" ]
2
2021-11-23T09:09:51.000Z
2022-02-28T19:48:22.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Sachin Chitta */ #pragma once // KDL #include <kdl/chain.hpp> #include <kdl/chainidsolver_recursive_newton_euler.hpp> #include <moveit/robot_state/robot_state.h> #include <geometry_msgs/msg/vector3.hpp> #include <geometry_msgs/msg/wrench.hpp> #include <memory> /** \brief This namespace includes the dynamics_solver library */ namespace dynamics_solver { MOVEIT_CLASS_FORWARD(DynamicsSolver) /** * This solver currently computes the required torques given a * joint configuration, velocities, accelerations and external wrenches * acting on the links of a robot */ class DynamicsSolver { public: /** * @brief Initialize the dynamics solver * @param urdf_model The urdf model for the robot * @param srdf_model The srdf model for the robot * @param group_name The name of the group to compute stuff for * @return False if initialization failed */ DynamicsSolver(const moveit::core::RobotModelConstPtr& robot_model, const std::string& group_name, const geometry_msgs::msg::Vector3& gravity_vector); /** * @brief Get the torques (the order of all input and output is the same * as the order of joints for this group in the RobotModel) * @param joint_angles The joint angles (desired joint configuration) * this must have size = number of joints in the group * @param joint_velocities The desired joint velocities * this must have size = number of joints in the group * @param joint_accelerations The desired joint accelerations * this must have size = number of joints in the group * @param wrenches External wrenches acting on the links of the robot * this must have size = number of links in the group * @param torques Computed set of torques are filled in here * this must have size = number of joints in the group * @return False if any of the input vectors are of the wrong size */ bool getTorques(const std::vector<double>& joint_angles, const std::vector<double>& joint_velocities, const std::vector<double>& joint_accelerations, const std::vector<geometry_msgs::msg::Wrench>& wrenches, std::vector<double>& torques) const; /** * @brief Get the maximum payload for this group (in kg). Payload is * the weight that this group can hold when the weight is attached to the origin * of the last link of this group. (The order of joint_angles vector is the same * as the order of joints for this group in the RobotModel) * @param joint_angles The joint angles (desired joint configuration) * this must have size = number of joints in the group * @param payload The computed maximum payload * @param joint_saturated The first saturated joint and the maximum payload * @return False if the input set of joint angles is of the wrong size */ bool getMaxPayload(const std::vector<double>& joint_angles, double& payload, unsigned int& joint_saturated) const; /** * @brief Get torques corresponding to a particular payload value. Payload is * the weight that this group can hold when the weight is attached to the origin * of the last link of this group. * @param joint_angles The joint angles (desired joint configuration) * this must have size = number of joints in the group * @param payload The payload for which to compute torques (in kg) * @param joint_torques The resulting joint torques * @return False if the input vectors are of the wrong size */ bool getPayloadTorques(const std::vector<double>& joint_angles, double payload, std::vector<double>& joint_torques) const; /** * @brief Get maximum torques for this group * @return Vector of max torques */ const std::vector<double>& getMaxTorques() const; /** * @brief Get the kinematic model * @return kinematic model */ const moveit::core::RobotModelConstPtr& getRobotModel() const { return robot_model_; } const moveit::core::JointModelGroup* getGroup() const { return joint_model_group_; } private: std::shared_ptr<KDL::ChainIdSolver_RNE> chain_id_solver_; // KDL chain inverse dynamics KDL::Chain kdl_chain_; // KDL chain moveit::core::RobotModelConstPtr robot_model_; const moveit::core::JointModelGroup* joint_model_group_; moveit::core::RobotStatePtr state_; // robot state std::string base_name_, tip_name_; // base name, tip name unsigned int num_joints_, num_segments_; // number of joints in group, number of segments in group std::vector<double> max_torques_; // vector of max torques double gravity_; // Norm of the gravity vector passed in initialize() }; } // namespace dynamics_solver
42.822368
116
0.710708
[ "vector", "model" ]
ca6f8580e255487d16f97ba84d7dd2821a8dd7c3
301
h
C
SmartHome-Lower/light.h
yxwangcs/SmartHome
05394dd68b4fc3f34bba4014c76640a24895a646
[ "MIT" ]
null
null
null
SmartHome-Lower/light.h
yxwangcs/SmartHome
05394dd68b4fc3f34bba4014c76640a24895a646
[ "MIT" ]
null
null
null
SmartHome-Lower/light.h
yxwangcs/SmartHome
05394dd68b4fc3f34bba4014c76640a24895a646
[ "MIT" ]
null
null
null
#ifndef LIGHT_H #define LIGHT_H #include <QObject> #include "model.h" class Light : public Model { Q_OBJECT public: Light(unsigned short io8255, Interface * parent); ~Light(); void setup(); void changeStatus(unsigned char data); private: unsigned char io8255; }; #endif
13.681818
53
0.674419
[ "model" ]
ca748721edfc574e753f3dddc242f82bc85ef9d3
1,256
h
C
element_desc.h
viniciusmalloc/cafezinho
32bdde1f36071b5dcd81d72fabbd1219bdc1a743
[ "MIT" ]
3
2017-10-04T13:43:09.000Z
2018-10-05T13:31:57.000Z
element_desc.h
viniciusmalloc/cafezinho
32bdde1f36071b5dcd81d72fabbd1219bdc1a743
[ "MIT" ]
null
null
null
element_desc.h
viniciusmalloc/cafezinho
32bdde1f36071b5dcd81d72fabbd1219bdc1a743
[ "MIT" ]
null
null
null
#ifndef element_desc_h #define element_desc_h #include <iostream> #include <string> #include <vector> using namespace std; typedef enum { SUM, SUB, MULTIPLY, DIVIDE, EQUAL, DIFFERENT, MINOR, MORE, NEGATIVE, REST, NEGATE, AND, OR, CONDITIONAL, LESS_EQUAL, GREATER_EQUAL } Operator; typedef enum { VAR_EMPTY, VAR_INTEGER, VAR_ERROR, VAR_CHAR, VAR_STRING } VarType; typedef enum { ASSIGN, IDENTIFIER, STATEMENT, ID_ARRAY, IF, ELSE, WHILE, UNARY, BINARY, TERNARY, BLOCK, DECLARATION, FUNC_DECLARATION, FUNC_CALL, VARIABLE, ARRAY_VARIABLE, LIST_VARIABLE, INTEGER, CHAR, STRING, NEW_LINE, READ, WRITE, START, EMPTY, RETURN, EXPRESSION, EXPRESSION_LIST } NodeType; struct Element { vector<Element*> list; int lineNum, intValue, level; char charValue; string* name; Operator operatorType; NodeType nodeType; VarType varType; Element* id; //constructor Element() { name = new string(""); intValue = -1; } }; #endif
14.776471
34
0.552548
[ "vector" ]
ca75ad923af7883162ead308ee0e606b73e02c96
1,236
h
C
AllChapters/Code/DualQuaternion.h
percentcer/Hands-On-Game-Animation-Programming
52f9bdb9db964192bfdddc512c6a40055830f17a
[ "MIT" ]
103
2020-05-22T09:17:54.000Z
2022-03-29T07:31:05.000Z
AllChapters/Code/DualQuaternion.h
PacktPublishing/Game-Animation-Programming
62c589661c51aaa83c4d060b0475b26b31e53a1d
[ "MIT" ]
2
2020-10-14T20:09:58.000Z
2021-02-07T05:15:41.000Z
AllChapters/Code/DualQuaternion.h
PacktPublishing/Game-Animation-Programming
62c589661c51aaa83c4d060b0475b26b31e53a1d
[ "MIT" ]
32
2020-06-15T20:15:28.000Z
2022-03-27T07:22:09.000Z
#ifndef _H_DUALQUATERNION_ #define _H_DUALQUATERNION_ #include "quat.h" #include "Transform.h" struct DualQuaternion { union { struct { quat real; quat dual; }; float v[8]; }; inline DualQuaternion() : real(0, 0, 0, 1), dual(0, 0, 0, 0) { } inline DualQuaternion(const quat& r, const quat& d) : real(r), dual(d) { } }; DualQuaternion operator+(const DualQuaternion& l, const DualQuaternion& r); DualQuaternion operator*(const DualQuaternion& dq, float f); // Multiplication order is left to right // Left to right is the OPPOSITE of matrices and quaternions DualQuaternion operator*(const DualQuaternion& l, const DualQuaternion& r); bool operator==(const DualQuaternion& l, const DualQuaternion& r); bool operator!=(const DualQuaternion& l, const DualQuaternion& r); float dot(const DualQuaternion& l, const DualQuaternion& r); DualQuaternion conjugate(const DualQuaternion& dq); DualQuaternion normalized(const DualQuaternion& dq); void normalize(DualQuaternion& dq); DualQuaternion transformToDualQuat(const Transform& t); Transform dualQuatToTransform(const DualQuaternion& dq); vec3 transformVector(const DualQuaternion& dq, const vec3& v); vec3 transformPoint(const DualQuaternion& dq, const vec3& v); #endif
34.333333
75
0.761327
[ "transform" ]
ca778b8c740f1bb68fd75fcc9407daa5cf9b2ccc
3,162
h
C
src/demo/demowrapper.h
yamokosk/tinysg
0243220bf5e015981257e261acfb6e764f296de2
[ "MIT" ]
2
2017-06-04T17:58:02.000Z
2019-10-02T11:33:20.000Z
src/demo/demowrapper.h
yamokosk/tinysg
0243220bf5e015981257e261acfb6e764f296de2
[ "MIT" ]
null
null
null
src/demo/demowrapper.h
yamokosk/tinysg
0243220bf5e015981257e261acfb6e764f296de2
[ "MIT" ]
1
2021-12-18T08:49:12.000Z
2021-12-18T08:49:12.000Z
/************************************************************************* * SceneML, Copyright (C) 2007, 2008 J.D. Yamokoski * All rights reserved. * Email: yamokosk at gmail dot com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. The text of the GNU Lesser General * Public License is included with this library in the file LICENSE.TXT. * * 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 file LICENSE.TXT for * more details. * *************************************************************************/ /* * demowrapper.h * * Created on: Jul 9, 2009 * Author: yamokosk */ #ifndef DEMOWRAPPER_H_ #define DEMOWRAPPER_H_ #include <string> #include <sstream> #include <iostream> // TinySG includes #include <TinySG.h> #include <NodeUtils.h> using namespace tinysg; #if defined( TSG_HAVE_LOG4CXX ) #include <log4cxx/logger.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/helpers/exception.h> using namespace log4cxx; using namespace log4cxx::helpers; #define TSG_LOG_INFO(expr) \ LOG4CXX_INFO(logger, expr); #define TSG_LOG_WARN(expr) \ LOG4CXX_WARN(logger, __FUNCTION__ << "(): " << expr); #define TSG_LOG_ERROR(expr) \ LOG4CXX_ERROR(logger, __FUNCTION__ << "(): " << expr); #else #include <iostream> #include <cstdio> #define TSG_LOG_INFO(expr) #define TSG_LOG_WARN(expr) \ std::cerr << __FUNCTION__ << "(): " << expr << std::endl; #define TSG_LOG_ERROR(expr) \ std::cerr << __FUNCTION__ << "(): " << expr << std::endl; #endif #define VERIFY( statement ) \ if ( (statement) ) \ { \ std::cout << "TRUE: " << #statement << std::endl; \ } else { \ std::cout << "Error! This is FALSE: " << #statement << std::endl; \ } #define TRACE \ std::cout << __FUNCTION__ << "(): " << __LINE__ << std::endl; /* * Overview * * Creates a very simple scene graph, attaches some 3D (ODE) objects to the * graph, and does a few collision queries. * * Details * * Support for ODE (Open dynamics engine) comes pre-built with TinySG, along * with support for another distance query algorithm (see other demo for details). * This demo shows how to create a very simple scene graph depicted below: * * World * / \ * n1 n2 * / * n3 * * This just represents the graph's connectivity. Physically the nodes will be located * as follows: * * +y * ^ * | * | * | * - n2(2,1) * | * | * | * | * - n1(1,1) n3(3,1) * | * | * | * | * *---------|---------|---------|--> +x */ void createSimpleGraph(SceneGraph& graph); // Defined by the individual demo programs bool rundemo(int argc, char **argv); #endif /* DEMOWRAPPER_H_ */
24.703125
86
0.601518
[ "3d" ]
ca8afd17e9c378c3012ae7aed77cd269f2364acd
1,537
h
C
ui/gfx/gl/gl_surface.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
ui/gfx/gl/gl_surface.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
ui/gfx/gl/gl_surface.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_GL_GL_SURFACE_H_ #define UI_GFX_GL_GL_SURFACE_H_ #pragma once #include "build/build_config.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/size.h" namespace gfx { // Encapsulates a surface that can be rendered to with GL, hiding platform // specific management. class GLSurface { public: GLSurface() {} virtual ~GLSurface() {} // (Re)create the surface. TODO(apatrick): This is an ugly hack to allow the // EGL surface associated to be recreated without destroying the associated // context. The implementation of this function for other GLSurface derived // classes is in a pending changelist. virtual bool Initialize(); // Destroys the surface. virtual void Destroy() = 0; // Returns true if this surface is offscreen. virtual bool IsOffscreen() = 0; // Swaps front and back buffers. This has no effect for off-screen // contexts. virtual bool SwapBuffers() = 0; // Get the size of the surface. virtual gfx::Size GetSize() = 0; // Get the underlying platform specific surface "handle". virtual void* GetHandle() = 0; // Returns the internal frame buffer object name if the surface is backed by // FBO. Otherwise returns 0. virtual unsigned int GetBackingFrameBufferObject(); private: DISALLOW_COPY_AND_ASSIGN(GLSurface); }; } // namespace gfx #endif // UI_GFX_GL_GL_SURFACE_H_
27.945455
78
0.732596
[ "object" ]
ca8ce4dc7e529e031a9272319277bea3d3854f2a
96,483
h
C
bpptree.h
mm304321141/zzz_lib
4cff725872a7a8073c13084004e1899f2cb8b981
[ "MIT" ]
56
2015-10-14T10:40:24.000Z
2021-08-29T16:11:37.000Z
bpptree.h
mm304321141/zzz_lib
4cff725872a7a8073c13084004e1899f2cb8b981
[ "MIT" ]
1
2017-12-06T06:51:49.000Z
2017-12-12T06:25:36.000Z
bpptree.h
mm304321141/zzz_lib
4cff725872a7a8073c13084004e1899f2cb8b981
[ "MIT" ]
16
2015-11-19T05:36:33.000Z
2020-08-29T19:09:52.000Z
#pragma once #include <cstdint> #include <algorithm> #include <memory> #include <cstring> #include <type_traits> #include <tuple> #include <vector> namespace b_plus_plus_tree_detail { class move_trivial_tag { }; class move_assign_tag { }; template<class T> struct is_trivial_expand : public std::is_trivial<T> { }; template<class K, class V> struct is_trivial_expand<std::pair<K, V>> : public std::conditional<std::is_trivial<K>::value && std::is_trivial<V>::value, std::true_type, std::false_type>::type { }; template<class iterator_t> struct get_tag { typedef typename std::conditional<is_trivial_expand<typename std::iterator_traits<iterator_t>::value_type>::value, move_trivial_tag, move_assign_tag>::type type; }; template<class iterator_t, class in_value_t, class tag_t> void construct_one(iterator_t where, in_value_t &&value, tag_t) { typedef typename std::iterator_traits<iterator_t>::value_type iterator_value_t; ::new(std::addressof(*where)) iterator_value_t(std::forward<in_value_t>(value)); } template<class iterator_t> void destroy_one(iterator_t where, move_trivial_tag) { } template<class iterator_t> void destroy_one(iterator_t where, move_assign_tag) { typedef typename std::iterator_traits<iterator_t>::value_type iterator_value_t; where->~iterator_value_t(); } template<class iterator_t> void destroy_range(iterator_t destroy_begin, iterator_t destroy_end, move_trivial_tag) { } template<class iterator_t> void destroy_range(iterator_t destroy_begin, iterator_t destroy_end, move_assign_tag) { for(; destroy_begin != destroy_end; ++destroy_begin) { destroy_one(destroy_begin, move_assign_tag()); } } template<class iterator_from_t, class iterator_to_t> void move_forward(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_forward(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_assign_tag) { std::move(move_begin, move_end, to_begin); } template<class iterator_from_t, class iterator_to_t> void move_backward(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_backward(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_assign_tag) { std::move_backward(move_begin, move_end, to_begin + (move_end - move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_construct(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_construct(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_assign_tag) { std::uninitialized_copy(std::make_move_iterator(move_begin), std::make_move_iterator(move_end), to_begin); } template<class iterator_t> void move_next_to_and_construct(iterator_t move_begin, iterator_t move_end, iterator_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_t> void move_next_to_and_construct(iterator_t move_begin, iterator_t move_end, iterator_t to_begin, move_assign_tag) { typedef typename std::iterator_traits<iterator_t>::value_type iterator_value_t; if(to_begin < move_end) { iterator_t split = move_end - (to_begin - move_begin); move_construct(split, move_end, move_end, move_assign_tag()); move_backward(move_begin, split, to_begin, move_assign_tag()); } else { move_construct(move_begin, move_end, to_begin, move_assign_tag()); std::uninitialized_fill(move_end, to_begin, iterator_value_t()); } } template<class iterator_from_t, class iterator_to_t> void move_and_destroy(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_and_destroy(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_assign_tag) { for(; move_begin != move_end; ++move_begin) { *to_begin++ = std::move(*move_begin); destroy_one(move_begin, move_assign_tag()); } } template<class iterator_from_t, class iterator_to_t> void move_construct_and_destroy(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*to_begin, &*move_begin, count * sizeof(*move_begin)); } template<class iterator_from_t, class iterator_to_t> void move_construct_and_destroy(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin, move_assign_tag) { for(; move_begin != move_end; ++move_begin) { construct_one(to_begin++, std::move(*move_begin), move_assign_tag()); destroy_one(move_begin, move_assign_tag()); } } template<class iterator_t, class in_value_t> void move_next_and_insert_one(iterator_t move_begin, iterator_t move_end, in_value_t &&value, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*(move_begin + 1), &*move_begin, count * sizeof(*move_begin)); *move_begin = std::forward<in_value_t>(value); } template<class iterator_t, class in_value_t> void move_next_and_insert_one(iterator_t move_begin, iterator_t move_end, in_value_t &&value, move_assign_tag) { if(move_begin == move_end) { construct_one(move_begin, std::forward<in_value_t>(value), move_assign_tag()); } else { iterator_t from_end = std::prev(move_end); construct_one(move_end, std::move(*from_end), move_assign_tag()); move_backward(move_begin, from_end, move_begin + 1, move_assign_tag()); *move_begin = std::forward<in_value_t>(value); } } template<class iterator_t> void move_prev_and_destroy_one(iterator_t move_begin, iterator_t move_end, move_trivial_tag) { std::ptrdiff_t count = move_end - move_begin; std::memmove(&*(move_begin - 1), &*move_begin, count * sizeof(*move_begin)); } template<class iterator_t> void move_prev_and_destroy_one(iterator_t move_begin, iterator_t move_end, move_assign_tag) { move_forward(move_begin, move_end, move_begin - 1, move_assign_tag()); destroy_one(move_end - 1, move_assign_tag()); } } template<class config_t> class b_plus_plus_tree { public: typedef typename config_t::key_type key_type; typedef typename config_t::mapped_type mapped_type; typedef typename config_t::value_type value_type; typedef typename config_t::storage_type storage_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef typename config_t::key_compare key_compare; typedef typename config_t::allocator_type allocator_type; typedef value_type &reference; typedef value_type const &const_reference; typedef value_type *pointer; typedef value_type const *const_pointer; protected: struct node_t { node_t *parent; size_t size; size_t level; }; struct inner_node_t : public node_t { typedef key_type item_type; enum { max = ((config_t::memory_block_size - sizeof(node_t) - sizeof(size_t) - sizeof(nullptr)) / (sizeof(key_type) + sizeof(nullptr))), min = max / 2, }; size_t used; node_t *children[max + 1]; key_type item[max]; size_t &bound() { return used; } size_t bound() const { return used; } bool is_full() const { return used == max; } bool is_few() const { return used <= min; } bool is_underflow() const { return used < min; } }; struct leaf_node_t : public node_t { typedef storage_type item_type; enum { max = (config_t::memory_block_size - sizeof(node_t) - sizeof(nullptr) * 2) / sizeof(storage_type), min = max / 2, }; node_t *prev; node_t *next; storage_type item[max]; size_t &bound() { return node_t::size; } size_t bound() const { return node_t::size; } bool is_full() const { return node_t::size == max; } bool is_few() const { return node_t::size <= min; } bool is_underflow() const { return node_t::size < min; } }; template<class, class> struct status_select_t { status_select_t() : inner_count(), leaf_count() { } size_type inner_count; size_type leaf_count; std::vector<size_type, typename allocator_type::template rebind<size_type>::other> level_count; static const size_type inner_bound = inner_node_t::max; static const size_type leaf_bound = leaf_node_t::max; }; template<class unused_t> struct status_select_t<std::false_type, unused_t> { status_select_t() { } }; typedef status_select_t<typename config_t::status_type::type, void> status_t; template<class, class> struct status_control_select_t { static void change_leaf(status_t &status, difference_type value) { status.leaf_count += value; if(status.level_count.empty()) { status.level_count.resize(1, 0); } status.level_count[0] += value; if(value < 0) { while(status.level_count.back() == 0) { status.level_count.pop_back(); } } } static void change_inner(status_t &status, difference_type value, size_type level) { status.inner_count += value; if(status.level_count.size() <= level) { status.level_count.resize(level + 1, 0); } status.level_count[level] += value; if(value < 0) { while(status.level_count.back() == 0) { status.level_count.pop_back(); } } } }; template<class unused_t> struct status_control_select_t<std::false_type, unused_t> { static void change_leaf(status_t &, difference_type) { } static void change_inner(status_t &status, difference_type value, size_type level) { } }; typedef status_control_select_t<typename config_t::status_type::type, void> status_control_t; typedef typename std::aligned_union<config_t::memory_block_size, inner_node_t, leaf_node_t>::type memory_node_t; typedef typename allocator_type::template rebind<memory_node_t>::other node_allocator_t; struct root_node_t : public node_t, public key_compare, public node_allocator_t, public status_t { template<class any_key_compare, class any_allocator_t> root_node_t(any_key_compare &&comp, any_allocator_t &&alloc) : key_compare(std::forward<any_key_compare>(comp)), node_allocator_t(std::forward<any_allocator_t>(alloc)), status_t() { static_assert(inner_node_t::max >= 4, "low memory_block_size"); static_assert(leaf_node_t::max >= 4, "low memory_block_size"); static_assert(sizeof(inner_node_t) <= config_t::memory_block_size, "bad memory size"); static_assert(sizeof(leaf_node_t) <= config_t::memory_block_size, "bad memory size"); node_t::parent = left = right = this; node_t::size = 0; node_t::level = 0; } node_t *left; node_t *right; }; struct key_stack_t { typename std::aligned_storage<sizeof(key_type), std::alignment_of<key_type>::value>::type key_pod; key_stack_t() { } key_stack_t(key_stack_t &&key) { ::new(&key_pod) key_type(std::move(key.key())); } key_stack_t(key_stack_t const &key) { ::new(&key_pod) key_type(key.key()); } key_stack_t(key_type &&key) { ::new(&key_pod) key_type(std::move(key)); } key_stack_t(key_type const &key) { ::new(&key_pod) key_type(key); } operator key_type &() { return *reinterpret_cast<key_type *>(&key_pod); } operator key_type const &() const { return *reinterpret_cast<key_type const *>(&key_pod); } operator key_type &&() { return std::move(*reinterpret_cast<key_type *>(&key_pod)); } key_type &key() { return *reinterpret_cast<key_type *>(&key_pod); } key_type const &key() const { return *reinterpret_cast<key_type const *>(&key_pod); } key_type *operator &() { return reinterpret_cast<key_type *>(&key_pod); } key_stack_t &operator = (key_stack_t &&other) { key() = std::move(other.key()); return *this; } key_stack_t &operator = (key_stack_t const &other) { key() = other.key(); return *this; } key_stack_t &operator = (key_type &&other) { key() = std::move(other); return *this; } key_stack_t &operator = (key_type const &other) { key() = other; return *this; } }; enum result_flags_t { btree_ok = 0, btree_not_found = 1, btree_update_lastkey = 2, btree_fixmerge = 4 }; struct result_t { result_flags_t flags; key_stack_t last_key; explicit result_t(result_flags_t f = btree_ok) : flags(result_flags_t(f & ~btree_update_lastkey)), last_key() { } result_t(result_t &&other) : flags(other.flags), last_key() { if(other.has(btree_update_lastkey)) { ::new(&last_key) key_type(std::move(other.last_key.key())); } } template<class in_key_t> result_t(result_flags_t f, in_key_t &&k) : flags(result_flags_t(f | btree_update_lastkey)), last_key(std::forward<in_key_t>(k)) { } ~result_t() { if(has(btree_update_lastkey)) { (&last_key)->~key_type(); } } bool has(result_flags_t f) const { return (flags & f) != 0; } result_t &operator |= (result_t &&other) { if(other.has(btree_update_lastkey)) { if(has(btree_update_lastkey)) { last_key.key() = std::move(other.last_key.key()); } else { ::new(&last_key) key_type(std::move(other.last_key.key())); } } flags = result_flags_t(flags | other.flags); return *this; } result_t &operator = (result_t &&other) { if(other.has(btree_update_lastkey)) { if(has(btree_update_lastkey)) { last_key.key() = std::move(other.last_key.key()); } else { ::new(&last_key) key_type(std::move(other.last_key.key())); } } else { if(has(btree_update_lastkey)) { last_key.key().~key_type(); } } flags = other.flags; return *this; } }; typedef std::pair<leaf_node_t *, size_type> pair_pos_t; template<class k_t, class v_t> struct get_key_select_t { key_type const &operator()(key_type const &value) { return value; } key_type const &operator()(storage_type const &value) { return config_t::get_key(value); } key_type const &operator()(pair_pos_t pos) { return (*this)(pos.first->item[pos.second]); } }; template<class k_t> struct get_key_select_t<k_t, k_t> { key_type const &operator()(key_type const &value) { return config_t::get_key(value); } key_type const &operator()(pair_pos_t pos) { return (*this)(pos.first->item[pos.second]); } }; typedef get_key_select_t<key_type, storage_type> get_key_t; enum { binary_search_limit = 16 * 1024 }; public: class iterator { public: typedef std::random_access_iterator_tag iterator_category; typedef typename b_plus_plus_tree::value_type value_type; typedef typename b_plus_plus_tree::difference_type difference_type; typedef typename b_plus_plus_tree::reference reference; typedef typename b_plus_plus_tree::pointer pointer; public: iterator(node_t *in_node, size_type in_where) : node(in_node), where(in_where) { } iterator(pair_pos_t pos, b_plus_plus_tree *self) : node(pos.first == nullptr ? static_cast<node_t *>(&self->root_) : static_cast<node_t *>(pos.first)), where(pos.second) { } iterator(iterator const &) = default; iterator &operator += (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, diff); return *this; } iterator &operator -= (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, -diff); return *this; } iterator operator + (difference_type diff) const { iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, diff); return ret; } iterator operator - (difference_type diff) const { iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, -diff); return ret; } difference_type operator - (iterator const &other) const { return static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(node, where)) - static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(other.node, other.where)); } iterator &operator++() { b_plus_plus_tree::advance_next_(node, where); return *this; } iterator &operator--() { b_plus_plus_tree::advance_prev_(node, where); return *this; } iterator operator++(int) { iterator save(*this); ++*this; return save; } iterator operator--(int) { iterator save(*this); --*this; return save; } reference operator *() const { return reinterpret_cast<reference>(static_cast<leaf_node_t *>(node)->item[where]); } pointer operator->() const { return reinterpret_cast<pointer>(static_cast<leaf_node_t *>(node)->item + where); } reference operator[](difference_type index) const { return *(*this + index); } bool operator > (iterator const &other) const { return *this - other > 0; } bool operator < (iterator const &other) const { return *this - other < 0; } bool operator >= (iterator const &other) const { return *this - other >= 0; } bool operator <= (iterator const &other) const { return *this - other <= 0; } bool operator == (iterator const &other) const { return node == other.node && where == other.where; } bool operator != (iterator const &other) const { return node != other.node || where != other.where; } private: friend class b_plus_plus_tree; node_t *node; size_type where; }; class const_iterator { public: typedef std::random_access_iterator_tag iterator_category; typedef typename b_plus_plus_tree::value_type value_type; typedef typename b_plus_plus_tree::difference_type difference_type; typedef typename b_plus_plus_tree::reference reference; typedef typename b_plus_plus_tree::const_reference const_reference; typedef typename b_plus_plus_tree::pointer pointer; typedef typename b_plus_plus_tree::const_pointer const_pointer; public: const_iterator(node_t *in_node, size_type in_where) : node(in_node), where(in_where) { } const_iterator(pair_pos_t pos, b_plus_plus_tree const *self) : node(pos.first == nullptr ? self->root_.parent->parent : pos.first), where(pos.second) { } const_iterator(iterator const &it) : node(it.node), where(it.where) { } const_iterator(const_iterator const &) = default; const_iterator &operator += (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, diff); return *this; } const_iterator &operator -= (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, -diff); return *this; } const_iterator operator + (difference_type diff) const { const_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, diff); return ret; } const_iterator operator - (difference_type diff) const { const_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, -diff); return ret; } difference_type operator - (const_iterator const &other) const { return static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(node, where)) - static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(other.node, other.where)); } const_iterator &operator++() { b_plus_plus_tree::advance_next_(node, where); return *this; } const_iterator &operator--() { b_plus_plus_tree::advance_prev_(node, where); return *this; } const_iterator operator++(int) { const_iterator save(*this); ++*this; return save; } const_iterator operator--(int) { const_iterator save(*this); --*this; return save; } const_reference operator *() const { return reinterpret_cast<const_reference>(static_cast<leaf_node_t *>(node)->item[where]); } const_pointer operator->() const { return reinterpret_cast<const_pointer>(static_cast<leaf_node_t *>(node)->item + where); } const_reference operator[](difference_type index) const { return *(*this + index); } bool operator > (const_iterator const &other) const { return *this - other > 0; } bool operator < (const_iterator const &other) const { return *this - other < 0; } bool operator >= (const_iterator const &other) const { return *this - other >= 0; } bool operator <= (const_iterator const &other) const { return *this - other <= 0; } bool operator == (const_iterator const &other) const { return node == other.node && where == other.where; } bool operator != (const_iterator const &other) const { return node != other.node || where != other.where; } private: friend class b_plus_plus_tree; node_t *node; size_type where; }; class reverse_iterator { public: typedef std::random_access_iterator_tag iterator_category; typedef typename b_plus_plus_tree::value_type value_type; typedef typename b_plus_plus_tree::difference_type difference_type; typedef typename b_plus_plus_tree::reference reference; typedef typename b_plus_plus_tree::pointer pointer; public: reverse_iterator(node_t *in_node, size_type in_where) : node(in_node), where(in_where) { } reverse_iterator(pair_pos_t pos, b_plus_plus_tree *self) : node(pos.first == nullptr ? static_cast<node_t *>(&self->root_) : static_cast<node_t *>(pos.first)), where(pos.second) { } explicit reverse_iterator(iterator const &other) : node(other.node), where(other.where) { ++*this; } reverse_iterator(reverse_iterator const &) = default; reverse_iterator &operator += (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, -diff); return *this; } reverse_iterator &operator -= (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, diff); return *this; } reverse_iterator operator + (difference_type diff) const { reverse_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, -diff); return ret; } reverse_iterator operator - (difference_type diff) const { reverse_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, diff); return ret; } difference_type operator - (reverse_iterator const &other) const { return static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(other.node, other.where)) - static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(node, where)); } reverse_iterator &operator++() { b_plus_plus_tree::advance_prev_(node, where); return *this; } reverse_iterator &operator--() { b_plus_plus_tree::advance_next_(node, where); return *this; } reverse_iterator operator++(int) { reverse_iterator save(*this); ++*this; return save; } reverse_iterator operator--(int) { reverse_iterator save(*this); --*this; return save; } reference operator *() const { return reinterpret_cast<reference>(static_cast<leaf_node_t *>(node)->item[where]); } pointer operator->() const { return reinterpret_cast<pointer>(static_cast<leaf_node_t *>(node)->item + where); } reference operator[](difference_type index) const { return *(*this + index); } bool operator > (reverse_iterator const &other) const { return *this - other > 0; } bool operator < (reverse_iterator const &other) const { return *this - other < 0; } bool operator >= (reverse_iterator const &other) const { return *this - other >= 0; } bool operator <= (reverse_iterator const &other) const { return *this - other <= 0; } bool operator == (reverse_iterator const &other) const { return node == other.node && where == other.where; } bool operator != (reverse_iterator const &other) const { return node != other.node || where != other.where; } iterator base() const { return ++iterator(node, where); } private: friend class b_plus_plus_tree; node_t *node; size_type where; }; class const_reverse_iterator { public: typedef std::random_access_iterator_tag iterator_category; typedef typename b_plus_plus_tree::value_type value_type; typedef typename b_plus_plus_tree::difference_type difference_type; typedef typename b_plus_plus_tree::reference reference; typedef typename b_plus_plus_tree::const_reference const_reference; typedef typename b_plus_plus_tree::pointer pointer; typedef typename b_plus_plus_tree::const_pointer const_pointer; public: const_reverse_iterator(node_t *in_node, size_type in_where) : node(in_node), where(in_where) { } const_reverse_iterator(pair_pos_t pos, b_plus_plus_tree const *self) : node(pos.first == nullptr ? self->root_.parent->parent : pos.first), where(pos.second) { } explicit const_reverse_iterator(const_iterator const &other) : node(other.node), where(other.where) { ++*this; } const_reverse_iterator(reverse_iterator const &other) : node(other.node), where(other.where) { } const_reverse_iterator(reverse_iterator it) : node(it.node), where(it.where) { } const_reverse_iterator(const_reverse_iterator const &) = default; const_reverse_iterator &operator += (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, -diff); return *this; } const_reverse_iterator &operator -= (difference_type diff) { b_plus_plus_tree::advance_step_(node, where, diff); return *this; } const_reverse_iterator operator + (difference_type diff) const { const_reverse_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, -diff); return ret; } const_reverse_iterator operator - (difference_type diff) const { const_reverse_iterator ret = *this; b_plus_plus_tree::advance_step_(ret.node, ret.where, diff); return ret; } difference_type operator - (const_reverse_iterator const &other) const { return static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(other.node, other.where)) - static_cast<difference_type>(b_plus_plus_tree::calculate_rank_(node, where)); } const_reverse_iterator &operator++() { b_plus_plus_tree::advance_prev_(node, where); return *this; } const_reverse_iterator &operator--() { b_plus_plus_tree::advance_next_(node, where); return *this; } const_reverse_iterator operator++(int) { const_reverse_iterator save(*this); ++*this; return save; } const_reverse_iterator operator--(int) { const_reverse_iterator save(*this); --*this; return save; } const_reference operator *() const { return reinterpret_cast<const_reference>(static_cast<leaf_node_t *>(node)->item[where]); } const_pointer operator->() const { return reinterpret_cast<const_pointer>(static_cast<leaf_node_t *>(node)->item + where); } const_reference operator[](difference_type index) const { return *(*this + index); } bool operator > (const_reverse_iterator const &other) const { return *this - other > 0; } bool operator < (const_reverse_iterator const &other) const { return *this - other < 0; } bool operator >= (const_reverse_iterator const &other) const { return *this - other >= 0; } bool operator <= (const_reverse_iterator const &other) const { return *this - other <= 0; } bool operator == (const_reverse_iterator const &other) const { return node == other.node && where == other.where; } bool operator != (const_reverse_iterator const &other) const { return node != other.node || where != other.where; } const_iterator base() const { return ++iterator(node, where); } private: friend class b_plus_plus_tree; node_t *node; size_type where; }; typedef typename std::conditional<config_t::unique_type::value, std::pair<iterator, bool>, iterator>::type insert_result_t; typedef std::pair<iterator, bool> pair_ib_t; protected: typedef std::pair<pair_pos_t, bool> pair_posi_t; template<class unique_type> typename std::enable_if<unique_type::value, insert_result_t>::type result_(pair_posi_t posi) { return std::make_pair(iterator(posi.first.first, posi.first.second), posi.second); } template<class unique_type> typename std::enable_if<!unique_type::value, insert_result_t>::type result_(pair_posi_t posi) { return iterator(posi.first.first, posi.first.second); } public: //empty b_plus_plus_tree() : root_(key_compare(), allocator_type()) { } //empty explicit b_plus_plus_tree(key_compare const &comp, allocator_type const &alloc = allocator_type()) : root_(comp, alloc) { } //empty explicit b_plus_plus_tree(allocator_type const &alloc) : root_(key_compare(), alloc) { } //range template <class iterator_t> b_plus_plus_tree(iterator_t begin, iterator_t end, key_compare const &comp = key_compare(), allocator_type const &alloc = allocator_type()) : root_(comp, alloc) { insert(begin, end); } //range template <class iterator_t> b_plus_plus_tree(iterator_t begin, iterator_t end, allocator_type const &alloc) : root_(key_compare(), alloc) { insert(begin, end); } //copy b_plus_plus_tree(b_plus_plus_tree const &other) : root_(other.get_comparator_(), other.get_node_allocator_()) { insert(other.begin(), other.end()); } //copy b_plus_plus_tree(b_plus_plus_tree const &other, allocator_type const &alloc) : root_(other.get_comparator_(), alloc) { insert(other.begin(), other.end()); } //move b_plus_plus_tree(b_plus_plus_tree &&other) : root_(key_compare(), node_allocator_t()) { swap(other); } //move b_plus_plus_tree(b_plus_plus_tree &&other, allocator_type const &alloc) : root_(key_compare(), alloc) { insert(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end())); } //initializer list b_plus_plus_tree(std::initializer_list<value_type> il, key_compare const &comp = key_compare(), allocator_type const &alloc = allocator_type()) : b_plus_plus_tree(il.begin(), il.end(), comp, alloc) { } //initializer list b_plus_plus_tree(std::initializer_list<value_type> il, allocator_type const &alloc) : b_plus_plus_tree(il.begin(), il.end(), key_compare(), alloc) { } //destructor ~b_plus_plus_tree() { clear(); } //copy b_plus_plus_tree &operator = (b_plus_plus_tree const &other) { if(this == &other) { return *this; } clear(); get_comparator_() = other.get_comparator_(); get_node_allocator_() = other.get_node_allocator_(); insert(other.begin(), other.end()); return *this; } //move b_plus_plus_tree &operator = (b_plus_plus_tree &&other) { if(this == &other) { return *this; } swap(other); return *this; } //initializer list b_plus_plus_tree &operator = (std::initializer_list<value_type> il) { clear(); insert(il.begin(), il.end()); return *this; } allocator_type get_allocator() const { return root_; } void swap(b_plus_plus_tree &other) { std::swap(root_, other.root_); fix_root_(); other.fix_root_(); } typedef std::pair<iterator, iterator> pair_ii_t; typedef std::pair<const_iterator, const_iterator> pair_cici_t; //single element insert_result_t insert(value_type const &value) { return result_<typename config_t::unique_type>(insert_nohint_<false>(value)); } //single element template<class in_value_t> typename std::enable_if<std::is_convertible<in_value_t, value_type>::value, insert_result_t>::type insert(in_value_t &&value) { return result_<typename config_t::unique_type>(insert_nohint_<false>(std::forward<in_value_t>(value))); } //with hint iterator insert(const_iterator hint, value_type const &value) { return result_<std::false_type>(insert_hint_(hint.node->size == 0 ? nullptr : static_cast<leaf_node_t *>(hint.node), hint.where, value)); } //with hint template<class in_value_t> typename std::enable_if<std::is_convertible<in_value_t, value_type>::value, insert_result_t>::type insert(const_iterator hint, in_value_t &&value) { return result_<typename config_t::unique_type>(insert_hint_(hint.node->size == 0 ? nullptr : static_cast<leaf_node_t *>(hint.node), hint.where, std::forward<in_value_t>(value))); } //range template<class iterator_t> void insert(iterator_t begin, iterator_t end) { for(; begin != end; ++begin) { emplace_hint(cend(), *begin); } } //initializer list void insert(std::initializer_list<value_type> il) { insert(il.begin(), il.end()); } //single element template<class ...args_t> insert_result_t emplace(args_t &&...args) { return result_<typename config_t::unique_type>(insert_nohint_<false>(std::move(storage_type(std::forward<args_t>(args)...)))); } //with hint template<class ...args_t> insert_result_t emplace_hint(const_iterator hint, args_t &&...args) { return result_<typename config_t::unique_type>(insert_hint_(hint.node->size == 0 ? nullptr : static_cast<leaf_node_t *>(hint.node), hint.where, std::move(storage_type(std::forward<args_t>(args)...)))); } template<class in_key_type> iterator find(in_key_type const &key) { pair_pos_t pos = lower_bound_(key); return (pos.first == nullptr || pos.second >= pos.first->bound() || get_comparator_()(key, get_key_t()(pos.first->item[pos.second]))) ? iterator(&root_, 0) : iterator(pos.first, pos.second); } template<class in_key_type> const_iterator find(in_key_type const &key) const { pair_pos_t pos = lower_bound_(key); return (pos.first == nullptr || pos.second >= pos.first->bound() || get_comparator_()(key, get_key_t()(pos.first->item[pos.second]))) ? iterator(root_.parent->parent, 0) : iterator(pos.first, pos.second); } template<class in_key_t, class = typename std::enable_if<std::is_convertible<in_key_t, key_type>::value && config_t::unique_type::value && !std::is_same<key_type, storage_type>::value, void>::type> mapped_type &operator[](in_key_t &&key) { pair_pos_t pos = lower_bound_(key); if(pos.first == nullptr || pos.second >= pos.first->bound() || get_comparator_()(key, get_key_t()(pos.first->item[pos.second]))) { pos = insert_hint_(pos.first, pos.second, std::make_pair(key, mapped_type())).first; } return pos.first->item[pos.second].second; } iterator erase(const_iterator it) { if(root_.parent->size == 0) { return end(); } size_type pos_at = rank(it); erase_pos_(static_cast<leaf_node_t *>(it.node), it.where); return at(pos_at); } size_type erase(key_type const &key) { if(root_.parent->size == 0) { return 0; } size_type count = 0; leaf_node_t *leaf_node; size_type where; while(true) { std::tie(leaf_node, where) = lower_bound_(key); if(leaf_node == nullptr || get_comparator_()(key, get_key_t()(leaf_node->item[where]))) { break; } erase_pos_(leaf_node, where); ++count; if(config_t::unique_type::value) { break; } } return count; } iterator erase(const_iterator erase_begin, const_iterator erase_end) { if(erase_begin == cbegin() && erase_end == cend()) { clear(); return begin(); } else { size_type pos_begin = rank(erase_begin), pos_end = rank(erase_end); while(pos_begin != pos_end) { erase(at(--pos_end)); } return at(pos_begin); } } template<class in_key_type> size_type count(in_key_type const &key) const { if(config_t::unique_type::value) { return find(key) == end() ? 0 : 1; } else { pair_cici_t range = equal_range(key); return std::distance(range.first, range.second); } } size_type count(key_type const &min, key_type const &max) const { if(get_comparator_()(max, min)) { return 0; } pair_cici_t range = b_plus_plus_tree::range(min, max); return std::distance(range.first, range.second); } pair_ii_t range(key_type const &min, key_type const &max) { if(get_comparator_()(max, min)) { return pair_ii_t(end(), end()); } return pair_ii_t(iterator(lower_bound_(min), this), iterator(upper_bound_(max), this)); } pair_cici_t range(key_type const &min, key_type const &max) const { if(get_comparator_()(max, min)) { return pair_cici_t(cend(), cend()); } return pair_cici_t(const_iterator(lower_bound_(min), this), const_iterator(upper_bound_(max), this)); } //reverse index when index < 0 pair_ii_t slice(difference_type slice_begin = 0, difference_type slice_end = 0) { difference_type s_size = size(); if(slice_begin < 0) { slice_begin = std::max<difference_type>(s_size + slice_begin, 0); } if(slice_end <= 0) { slice_end = s_size + slice_end; } if(slice_begin > slice_end || slice_begin >= s_size) { return pair_ii_t(end(), end()); } return pair_ii_t(at(slice_begin), at(slice_end)); } //reverse index when index < 0 pair_cici_t slice(difference_type slice_begin = 0, difference_type slice_end = 0) const { difference_type s_size = size(); if(slice_begin < 0) { slice_begin = std::max<difference_type>(s_size + slice_begin, 0); } if(slice_end <= 0) { slice_end = s_size + slice_end; } if(slice_begin > slice_end || slice_begin >= s_size) { return pair_cici_t(cend(), cend()); } return pair_cici_t(at(slice_begin), at(slice_end)); } template<class in_key_type> iterator lower_bound(in_key_type const &key) { return iterator(lower_bound_(key), this); } template<class in_key_type> const_iterator lower_bound(in_key_type const &key) const { return const_iterator(lower_bound_(key), this); } template<class in_key_type> iterator upper_bound(in_key_type const &key) { return iterator(upper_bound_(key), this); } template<class in_key_type> const_iterator upper_bound(in_key_type const &key) const { return const_iterator(upper_bound_(key), this); } template<class in_key_type> pair_ii_t equal_range(in_key_type const &key) { return pair_ii_t(iterator(lower_bound_(key), this), iterator(upper_bound_(key), this)); } template<class in_key_type> pair_cici_t equal_range(in_key_type const &key) const { return pair_cici_t(const_iterator(lower_bound_(key), this), const_iterator(upper_bound_(key), this)); } iterator begin() { return iterator(root_.left, 0); } iterator end() { return iterator(&root_, 0); } const_iterator begin() const { return iterator(root_.left, 0); } const_iterator end() const { return const_iterator(root_.parent->parent, 0); } const_iterator cbegin() const { return iterator(root_.left, 0); } const_iterator cend() const { return const_iterator(root_.parent->parent, 0); } reverse_iterator rbegin() { return reverse_iterator(root_.right, root_.right->size == 0 ? 0 : static_cast<leaf_node_t *>(root_.right)->bound() - 1); } reverse_iterator rend() { return reverse_iterator(&root_, 0); } const_reverse_iterator rbegin() const { return const_reverse_iterator(root_.right, root_.right->size == 0 ? 0 : static_cast<leaf_node_t *>(root_.right)->bound() - 1); } const_reverse_iterator rend() const { return const_reverse_iterator(root_.parent->parent, 0); } const_reverse_iterator crbegin() const { return const_reverse_iterator(root_.right, root_.right->size == 0 ? 0 : static_cast<leaf_node_t *>(root_.right)->bound() - 1); } const_reverse_iterator crend() const { return const_reverse_iterator(root_.parent->parent, 0); } reference front() { return reinterpret_cast<reference>(static_cast<leaf_node_t *>(root_.left)->item[0]); } reference back() { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); return reinterpret_cast<reference>(tail->item[tail->bound() - 1]); } const_reference front() const { return reinterpret_cast<const_reference>(static_cast<leaf_node_t *>(root_.left)->item[0]); } const_reference back() const { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); return reinterpret_cast<const_reference>(tail->item[tail->bound() - 1]); } bool empty() const { return root_.parent->size == 0; } void clear() { if(root_.parent != &root_) { free_node_<true>(root_.parent); root_.parent = root_.left = root_.right = &root_; } } size_type size() const { return root_.parent->size; } size_type max_size() const { return node_allocator_t(get_node_allocator_()).max_size(); } //if(index >= size) return end iterator at(size_type index) { return iterator(access_index_(root_.parent, index), this); } //if(index >= size) return end const_iterator at(size_type index) const { return const_iterator(access_index_(root_.parent, index), this); } //rank(begin) == 0, key rank size_type rank(key_type const &key) const { return calculate_key_rank_<true>(key); } //rank(begin) == 0, rank of iterator static size_type rank(const_iterator where) { return calculate_rank_(where.node, where.where); } //rank(begin) == 0, key rank current best size_type lower_rank(key_type const &key) const { return calculate_key_rank_<true>(key); } //rank(begin) == 0, key rank when insert size_type upper_rank(key_type const &key) const { return calculate_key_rank_<false>(key); } status_t const &status() const { static_assert(config_t::status_type::value, "status disabled"); return root_; } //WARNING : DON'T CALL THIS FUNCTION ! void adjust(difference_type offset) { adjust_pointer_(root_.parent, offset); adjust_pointer_(root_.left, offset); adjust_pointer_(root_.right, offset); if(root_.parent->size > 0) { adjust_node_(root_.parent, offset); } } protected: root_node_t root_; protected: key_compare &get_comparator_() { return root_; } key_compare const &get_comparator_() const { return root_; } node_allocator_t &get_node_allocator_() { return root_; } node_allocator_t const &get_node_allocator_() const { return root_; } void fix_root_() { if(root_.parent->size == 0) { root_.parent = root_.left = root_.right = &root_; } else { root_.parent->parent = &root_; static_cast<leaf_node_t *>(root_.left)->prev = &root_; static_cast<leaf_node_t *>(root_.right)->next = &root_; } } void adjust_node_(node_t *node, difference_type offset) { adjust_pointer_(node->parent, offset); if(node->level == 0) { leaf_node_t *leaf_node = static_cast<leaf_node_t *>(node); adjust_pointer_(leaf_node->prev, offset); adjust_pointer_(leaf_node->next, offset); } else { inner_node_t *inner_node = static_cast<inner_node_t *>(node); for(size_t i = 0; i < inner_node->bound(); ++i) { adjust_pointer_(inner_node->children[i], offset); adjust_node_(inner_node->children[i], offset); } adjust_pointer_(inner_node->children[inner_node->bound()], offset); adjust_node_(inner_node->children[inner_node->bound()], offset); } } template<class T> void adjust_pointer_(T *&ptr, difference_type offset) { ptr = reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(ptr) + offset); } inner_node_t *alloc_inner_node_(node_t *parent, size_type level) { inner_node_t *node = reinterpret_cast<inner_node_t *>(get_node_allocator_().allocate(1)); node->parent = parent; node->size = 0; node->level = level; node->used = 0; status_control_t::change_inner(root_, 1, level); return node; } leaf_node_t *alloc_leaf_node_() { leaf_node_t *node = reinterpret_cast<leaf_node_t *>(get_node_allocator_().allocate(1)); node->parent = nullptr; node->size = 0; node->level = 0; node->prev = nullptr; node->next = nullptr; status_control_t::change_leaf(root_, 1); return node; } template<class in_node_t> void dealloc_node_(in_node_t *node) { destroy_range_(node->item, node->item + node->bound()); get_node_allocator_().deallocate(reinterpret_cast<memory_node_t *>(node), 1); } template<bool is_recursive> void free_node_(node_t *node) { if(node->level == 0) { dealloc_node_(static_cast<leaf_node_t *>(node)); status_control_t::change_leaf(root_, -1); } else { inner_node_t *inner_node = static_cast<inner_node_t *>(node); if(is_recursive) { for(size_type i = 0; i <= inner_node->bound(); ++i) { free_node_<is_recursive>(inner_node->children[i]); } } status_control_t::change_inner(root_, -1, inner_node->level); dealloc_node_(inner_node); } } pair_pos_t advance_next_(pair_pos_t pos) { if(pos.first == nullptr) { if(root_.parent->size == 0) { return std::make_pair(nullptr, 0); } else { return std::make_pair(static_cast<leaf_node_t *>(root_.left), 0); } } else { if(pos.second + 1 >= pos.first->bound()) { return std::make_pair(pos.first->next->size == 0 ? nullptr : static_cast<leaf_node_t *>(pos.first->next), 0); } else { return std::make_pair(pos.first, pos.second + 1); } } } pair_pos_t advance_prev_(pair_pos_t pos) { if(pos.second == 0) { leaf_node_t *leaf_node = root_.parent->size == 0 ? nullptr : static_cast<leaf_node_t *>(pos.first->prev); return std::make_pair(leaf_node, leaf_node == nullptr ? 0 : leaf_node->bound() - 1); } else { return std::make_pair(pos.first, pos.second - 1); } } static void advance_next_(node_t *&node, size_type &where) { if(node->size == 0) { node = static_cast<root_node_t *>(node)->left; } else { leaf_node_t *leaf_node = static_cast<leaf_node_t *>(node); if(++where >= leaf_node->bound()) { node = leaf_node->next; where = 0; } } } static void advance_prev_(node_t *&node, size_type &where) { if(where == 0) { node = node->size == 0 ? static_cast<root_node_t *>(node)->right : static_cast<leaf_node_t *>(node)->prev; where = node->size == 0 ? 0 : static_cast<leaf_node_t *>(node)->bound() - 1; } else { --where; } } static void advance_step_(node_t *&node, size_type &where, difference_type step) { if(node->size == 0) { if(step == 0) { return; } else if(step > 0) { --step; advance_next_(node, where); } else { ++step; advance_prev_(node, where); } if(node->size == 0) { return; } } step += where; if(step == 0) { where = 0; return; } if(step > 0) { while(size_type(step) >= node->size) { if(node->parent->size == 0) { node = node->parent; where = 0; return; } inner_node_t *parent = static_cast<inner_node_t *>(node->parent); for(node_t **child = parent->children; ; ++child) { if(*child == node) { node = parent; break; } else { step += (*child)->size; } } } } else { do { if(node->parent->size == 0) { node = node->parent; where = 0; return; } inner_node_t *parent = static_cast<inner_node_t *>(node->parent); for(node_t **child = parent->children; ; ++child) { if(*child == node) { node = parent; break; } else { step += (*child)->size; } } } while(step < 0); } while(node->level > 0) { inner_node_t *inner_node = static_cast<inner_node_t *>(node); for(node_t **child = inner_node->children; ; ++child) { if(size_type(step) >= (*child)->size) { step -= (*child)->size; } else { node = *child; break; } } } where = step; } template<bool is_leftish> size_type calculate_key_rank_(key_type const &key) const { node_t *node = root_.parent; if(node->size == 0) { return root_.parent->size; } size_type rank = 0; while(node->level > 0) { inner_node_t const *inner_node = static_cast<inner_node_t const *>(node); size_type where; if(std::is_scalar<key_type>::value) { for(where = 0; where < inner_node->bound(); ++where) { if(is_leftish ? !get_comparator_()(get_key_t()(inner_node->item[where]), key) : get_comparator_()(key, get_key_t()(inner_node->item[where]))) { break; } else { rank += inner_node->children[where]->size; } } } else { where = is_leftish ? lower_bound_(inner_node, key) : upper_bound_(inner_node, key); for(size_type i = 0; i < where; ++i) { rank += inner_node->children[i]->size; } } node = inner_node->children[where]; } return rank + (is_leftish ? lower_bound_(static_cast<leaf_node_t *>(node), key) : upper_bound_(static_cast<leaf_node_t *>(node), key)); } static size_type calculate_rank_(node_t *node, size_type where) { if(node->size == 0) { return node->parent->size; } else { size_type rank; std::tie(std::ignore, rank) = advance_root_(node, where); return rank; } } static std::pair<node_t *, size_type> advance_root_(node_t *node, size_type where) { while(node->parent->size != 0) { inner_node_t *parent = static_cast<inner_node_t *>(node->parent); for(size_type i = 0; ; ++i) { if(parent->children[i] == node) { node = parent; break; } else { where += parent->children[i]->size; } } } return std::make_pair(node, where); } static pair_pos_t access_index_(node_t *node, size_type index) { if(index >= node->size) { return std::make_pair(nullptr, 0); } while(node->level > 0) { inner_node_t *inner_node = static_cast<inner_node_t *>(node); for(node_t **child = inner_node->children; ; ++child) { if(index >= (*child)->size) { index -= (*child)->size; } else { node = *child; break; } } } return std::make_pair(static_cast<leaf_node_t *>(node), index); } template<class node_type, class in_key_key> size_type lower_bound_(node_type *node, in_key_key const &key) const { if(std::is_scalar<key_type>::value && size_type(node_type::max * sizeof(typename node_type::item_type)) <= size_type(binary_search_limit)) { return std::find_if(node->item, node->item + node->bound(), [&](typename node_type::item_type const &item)->bool { return !get_comparator_()(get_key_t()(item), key); }) - node->item; } else { return std::lower_bound(node->item, node->item + node->bound(), key, [&](typename node_type::item_type const &left, in_key_key const &right)->bool { return get_comparator_()(get_key_t()(left), right); }) - node->item; } } template<class node_type, class in_key_key> size_type upper_bound_(node_type *node, in_key_key const &key) const { if(std::is_scalar<key_type>::value && size_type(node_type::max * sizeof(typename node_type::item_type)) <= size_type(binary_search_limit)) { return std::find_if(node->item, node->item + node->bound(), [&](typename node_type::item_type const &item)->bool { return get_comparator_()(key, get_key_t()(item)); }) - node->item; } else { return std::upper_bound(node->item, node->item + node->bound(), key, [&](in_key_key const &left, typename node_type::item_type const &right)->bool { return get_comparator_()(left, get_key_t()(right)); }) - node->item; } } template<class in_key_key> pair_pos_t lower_bound_(in_key_key const &key) const { node_t *node = root_.parent; if(node->size == 0) { return std::make_pair(nullptr, 0); } while(node->level > 0) { inner_node_t const *inner_node = static_cast<inner_node_t const *>(node); size_type where = lower_bound_(inner_node, key); node = inner_node->children[where]; } leaf_node_t *leaf_node = static_cast<leaf_node_t *>(node); size_type where = lower_bound_(leaf_node, key); if(where >= leaf_node->bound()) { return std::make_pair(nullptr, 0); } else { return std::make_pair(leaf_node, where); } } template<class in_key_key> pair_pos_t upper_bound_(in_key_key const &key) const { node_t *node = root_.parent; if(node->size == 0) { return std::make_pair(nullptr, 0); } while(node->level > 0) { inner_node_t const *inner_node = static_cast<inner_node_t const *>(node); size_type where = upper_bound_(inner_node, key); node = inner_node->children[where]; } leaf_node_t *leaf_node = static_cast<leaf_node_t *>(node); size_type where = upper_bound_(leaf_node, key); if(where >= leaf_node->bound()) { return std::make_pair(nullptr, 0); } else { return std::make_pair(leaf_node, where); } } template<class iterator_t, class in_value_t> static void construct_one_(iterator_t where, in_value_t &&value) { b_plus_plus_tree_detail::construct_one(where, std::forward<in_value_t>(value), typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } template<class iterator_t> static void destroy_one_(iterator_t where) { b_plus_plus_tree_detail::destroy_one(where, typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } template<class iterator_t> static void destroy_range_(iterator_t destroy_begin, iterator_t destroy_end) { b_plus_plus_tree_detail::destroy_range(destroy_begin, destroy_end, typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } template<class iterator_from_t, class iterator_to_t> static void move_forward_(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin) { b_plus_plus_tree_detail::move_forward(move_begin, move_end, to_begin, typename b_plus_plus_tree_detail::get_tag<iterator_from_t>::type()); } template<class iterator_from_t, class iterator_to_t> static void move_construct_(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin) { b_plus_plus_tree_detail::move_construct(move_begin, move_end, to_begin, typename b_plus_plus_tree_detail::get_tag<iterator_from_t>::type()); } template<class iterator_t> static void move_next_to_and_construct_(iterator_t move_begin, iterator_t move_end, iterator_t to_begin) { b_plus_plus_tree_detail::move_next_to_and_construct(move_begin, move_end, to_begin, typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } template<class iterator_from_t, class iterator_to_t> static void move_and_destroy_(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin) { b_plus_plus_tree_detail::move_and_destroy(move_begin, move_end, to_begin, typename b_plus_plus_tree_detail::get_tag<iterator_from_t>::type()); } template<class iterator_from_t, class iterator_to_t> static void move_construct_and_destroy_(iterator_from_t move_begin, iterator_from_t move_end, iterator_to_t to_begin) { b_plus_plus_tree_detail::move_construct_and_destroy(move_begin, move_end, to_begin, typename b_plus_plus_tree_detail::get_tag<iterator_from_t>::type()); } template<class iterator_t, class in_value_t> static void move_next_and_insert_one_(iterator_t move_begin, iterator_t move_end, in_value_t &&value) { b_plus_plus_tree_detail::move_next_and_insert_one(move_begin, move_end, std::forward<in_value_t>(value), typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } template<class iterator_t> static void move_prev_and_destroy_one_(iterator_t move_begin, iterator_t move_end) { b_plus_plus_tree_detail::move_prev_and_destroy_one(move_begin, move_end, typename b_plus_plus_tree_detail::get_tag<iterator_t>::type()); } static size_type update_parent_(node_t **update_begin, node_t **update_end, node_t *parent) { size_type count = 0; while(update_begin != update_end) { node_t *node = *update_begin++; count += node->size; node->parent = parent; } return count; } template<class in_value_t> pair_posi_t insert_first_(in_value_t &&value) { leaf_node_t *node = alloc_leaf_node_(); construct_one_(node->item, std::forward<in_value_t>(value)); node->bound() = 1; root_.parent = root_.left = root_.right = node; node->parent = node->next = node->prev = &root_; return std::make_pair(std::make_pair(node, 0), true); } template<class in_value_t> pair_posi_t insert_hint_(leaf_node_t *leaf_node, size_type where, in_value_t &&value) { bool is_leftish = false; pair_pos_t other; if(root_.parent->size == 0) { return insert_first_(std::forward<in_value_t>(value)); } else if(config_t::unique_type::value) { if(leaf_node == root_.left && where == 0) { if(get_comparator_()(get_key_t()(value), get_key_t()(leaf_node->item[where]))) { return insert_pos_(leaf_node, 0, std::forward<in_value_t>(value)); } } else if(leaf_node == nullptr) { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); if(get_comparator_()(get_key_t()(tail->item[tail->bound() - 1]), get_key_t()(value))) { return insert_pos_(tail, tail->bound(), std::forward<in_value_t>(value)); } } else if(get_comparator_()(get_key_t()(value), get_key_t()(leaf_node->item[where])) && get_comparator_()(get_key_t()(other = advance_prev_(std::make_pair(leaf_node, where))), get_key_t()(value))) { return insert_pos_(leaf_node, where, std::forward<in_value_t>(value)); } else if(get_comparator_()(get_key_t()(leaf_node->item[where]), get_key_t()(value)) && ((other = advance_next_(std::make_pair(leaf_node, where))).first == nullptr || get_comparator_()(get_key_t()(value), get_key_t()(other)))) { if(other.first == nullptr) { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); return insert_pos_(tail, tail->bound(), std::forward<in_value_t>(value)); } else { return insert_pos_(other.first, other.second, std::forward<in_value_t>(value)); } } } else { if(leaf_node == root_.left && where == 0) { if(!get_comparator_()(get_key_t()(leaf_node->item[where]), get_key_t()(value))) { return insert_pos_(leaf_node, 0, std::forward<in_value_t>(value)); } is_leftish = true; } else if(leaf_node == nullptr) { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); if(!get_comparator_()(get_key_t()(value), get_key_t()(tail->item[tail->bound() - 1]))) { return insert_pos_(tail, tail->bound(), std::forward<in_value_t>(value)); } } else if(!get_comparator_()(get_key_t()(leaf_node->item[where]), get_key_t()(value)) && !get_comparator_()(get_key_t()(value), get_key_t()(other = advance_prev_(std::make_pair(leaf_node, where))))) { return insert_pos_(leaf_node, where, std::forward<in_value_t>(value)); } else if(!get_comparator_()(get_key_t()(value), get_key_t()(leaf_node->item[where])) && ((other = advance_next_(std::make_pair(leaf_node, where))).first == nullptr || !get_comparator_()(get_key_t()(other), get_key_t()(value)))) { if(other.first == nullptr) { leaf_node_t *tail = static_cast<leaf_node_t *>(root_.right); return insert_pos_(tail, tail->bound(), std::forward<in_value_t>(value)); } else { return insert_pos_(other.first, other.second, std::forward<in_value_t>(value)); } } else { is_leftish = true; } } if(is_leftish) { return insert_nohint_<true>(std::forward<in_value_t>(value)); } else { return insert_nohint_<false>(std::forward<in_value_t>(value)); } } template<class in_value_t> pair_posi_t insert_pos_(leaf_node_t *leaf_node, size_type where, in_value_t &&value) { key_stack_t key_out; node_t *split_node = nullptr; inner_node_t *parent = nullptr; size_type parent_where; if(leaf_node->is_full()) { parent_where = get_parent_(leaf_node, parent); split_leaf_node_(leaf_node, &key_out, split_node); if(where >= leaf_node->bound()) { where -= leaf_node->bound(); leaf_node = static_cast<leaf_node_t *>(split_node); } } move_next_and_insert_one_(leaf_node->item + where, leaf_node->item + leaf_node->bound(), std::forward<in_value_t>(value)); ++leaf_node->bound(); if(split_node != nullptr && leaf_node != split_node && where == leaf_node->bound() - 1) { key_out = get_key_t()(leaf_node->item[where]); } if(split_node == nullptr) { for(node_t *node_parent = leaf_node->parent; node_parent->size != 0; node_parent = node_parent->parent) { ++node_parent->size; } } else { insert_pos_descend_(parent, parent_where, std::move(key_out), split_node); } return std::make_pair(std::make_pair(leaf_node, where), true); } void insert_pos_descend_(inner_node_t *inner_node, size_type where, key_stack_t &&key_out, node_t *new_child) { if(inner_node == nullptr) { inner_node_t *new_root = alloc_inner_node_(&root_, root_.parent->level + 1); construct_one_(new_root->item, std::move(key_out.key())); destroy_one_(&key_out); new_root->children[0] = root_.parent; new_root->children[1] = new_child; new_root->bound() = 1; new_root->size = update_parent_(new_root->children, new_root->children + 2, new_root); root_.parent = new_root; return; } key_stack_t split_key_out; node_t *split_node = nullptr; inner_node_t *parent = nullptr; size_type parent_where; ++inner_node->size; do { if(inner_node->is_full()) { parent_where = get_parent_(inner_node, parent); split_inner_node_(inner_node, &split_key_out, split_node, where); inner_node_t *split_tree_node = static_cast<inner_node_t *>(split_node); if(where == inner_node->bound() + 1 && inner_node->bound() < split_tree_node->bound()) { construct_one_(inner_node->item + inner_node->bound(), std::move(split_key_out.key())); inner_node->children[inner_node->bound() + 1] = split_tree_node->children[0]; ++inner_node->bound(); inner_node->size = inner_node->size + split_tree_node->children[0]->size - new_child->size; split_tree_node->size = split_tree_node->size - split_tree_node->children[0]->size + new_child->size; split_tree_node->children[0]->parent = inner_node; new_child->parent = split_tree_node; split_tree_node->children[0] = new_child; split_key_out = std::move(key_out.key()); destroy_one_(&key_out); break; } else if(where >= size_type(inner_node->bound() + 1)) { where -= inner_node->bound() + 1; inner_node->size -= new_child->size; split_tree_node->size += new_child->size; inner_node = split_tree_node; } } move_next_and_insert_one_(inner_node->item + where, inner_node->item + inner_node->bound(), std::move(key_out.key())); destroy_one_(&key_out); std::move_backward(inner_node->children + where, inner_node->children + inner_node->bound() + 1, inner_node->children + inner_node->bound() + 2); inner_node->children[where + 1] = new_child; inner_node->bound()++; new_child->parent = inner_node; } while(false); if(split_node == nullptr) { for(node_t *node_parent = inner_node->parent; node_parent->size != 0; node_parent = node_parent->parent) { ++node_parent->size; } } else { insert_pos_descend_(parent, parent_where, std::move(split_key_out), split_node); } } template<bool is_leftish, class in_value_t> pair_posi_t insert_nohint_(in_value_t &&value) { if(root_.parent->size == 0) { return insert_first_(std::forward<in_value_t>(value)); } leaf_node_t *leaf_node; size_type where; std::tie(leaf_node, where) = is_leftish ? lower_bound_(get_key_t()(value)) : upper_bound_(get_key_t()(value)); if(leaf_node == nullptr) { leaf_node = static_cast<leaf_node_t *>(root_.right); where = leaf_node->bound(); } if(config_t::unique_type::value && (where > 0 || leaf_node->prev != &root_)) { if(where == 0) { leaf_node_t *prev_leaf_node = static_cast<leaf_node_t *>(leaf_node->prev); if(!get_comparator_()(get_key_t()(prev_leaf_node->item[prev_leaf_node->bound() - 1]), get_key_t()(value))) { return std::make_pair(std::make_pair(prev_leaf_node, prev_leaf_node->bound() - 1), false); } } else { if(!get_comparator_()(get_key_t()(leaf_node->item[where - 1]), get_key_t()(value))) { return std::make_pair(std::make_pair(leaf_node, where - 1), false); } } } return insert_pos_(leaf_node, where, std::forward<in_value_t>(value)); } void split_inner_node_(inner_node_t *inner_node, key_type *key_ptr, node_t *&new_node, size_type where) { size_type mid = (inner_node->bound() >> 1); if(where <= mid && mid > inner_node->bound() - (mid + 1)) { --mid; } inner_node_t *new_inner_node = alloc_inner_node_(inner_node->parent, inner_node->level); new_inner_node->bound() = inner_node->bound() - (mid + 1); move_construct_and_destroy_(inner_node->item + mid + 1, inner_node->item + inner_node->bound(), new_inner_node->item); std::copy(inner_node->children + mid + 1, inner_node->children + inner_node->bound() + 1, new_inner_node->children); inner_node->bound() = mid; construct_one_(key_ptr, inner_node->item[mid]); destroy_one_(inner_node->item + mid); size_type count = update_parent_(new_inner_node->children, new_inner_node->children + new_inner_node->bound() + 1, new_inner_node); new_inner_node->size = count; inner_node->size -= count; new_node = new_inner_node; } void split_leaf_node_(leaf_node_t *leaf_node, key_type *key_ptr, node_t *&new_node) { size_type mid = (leaf_node->bound() >> 1); leaf_node_t *new_leaf_node = alloc_leaf_node_(); new_leaf_node->bound() = leaf_node->bound() - mid; new_leaf_node->next = leaf_node->next; if(new_leaf_node->next->size == 0) { root_.right = new_leaf_node; } else { static_cast<leaf_node_t *>(new_leaf_node->next)->prev = new_leaf_node; } move_construct_and_destroy_(leaf_node->item + mid, leaf_node->item + leaf_node->bound(), new_leaf_node->item); leaf_node->bound() = mid; leaf_node->next = new_leaf_node; new_leaf_node->prev = leaf_node; construct_one_(key_ptr, get_key_t()(leaf_node->item[leaf_node->bound() - 1])); new_node = new_leaf_node; } result_t merge_leaves_(leaf_node_t *left, leaf_node_t *right, inner_node_t *parent) { (void)parent; move_construct_and_destroy_(right->item, right->item + right->bound(), left->item + left->bound()); left->bound() += right->bound(); left->next = right->next; if(left->next != &root_) { static_cast<leaf_node_t *>(left->next)->prev = left; } else { root_.right = left; } right->bound() = 0; right->parent = nullptr; return result_t(btree_fixmerge); } static result_t shift_left_leaf_(leaf_node_t *left, leaf_node_t *right, inner_node_t *parent, size_type parent_where) { size_type shiftnum = (right->bound() - left->bound()) >> 1; move_construct_(right->item, right->item + shiftnum, left->item + left->bound()); left->bound() += shiftnum; move_forward_(right->item + shiftnum, right->item + right->bound(), right->item); destroy_range_(right->item + right->bound() - shiftnum, right->item + right->bound()); right->bound() -= shiftnum; if(parent_where < parent->bound()) { parent->item[parent_where] = get_key_t()(left->item[left->bound() - 1]); return result_t(btree_ok); } else { return result_t(btree_update_lastkey, get_key_t()(left->item[left->bound() - 1])); } } static void shift_right_leaf_(leaf_node_t *left, leaf_node_t *right, inner_node_t *parent, size_type parent_where) { size_type shiftnum = (left->bound() - right->bound()) >> 1; move_next_to_and_construct_(right->item, right->item + right->bound(), right->item + shiftnum); right->bound() += shiftnum; move_and_destroy_(left->item + left->bound() - shiftnum, left->item + left->bound(), right->item); left->bound() -= shiftnum; parent->item[parent_where] = get_key_t()(left->item[left->bound() - 1]); } static result_t merge_inners_(inner_node_t *left, inner_node_t *right, inner_node_t *parent, size_type parent_where) { construct_one_(left->item + left->bound(), parent->item[parent_where]); ++left->bound(); move_construct_and_destroy_(right->item, right->item + right->bound(), left->item + left->bound()); std::copy(right->children, right->children + right->bound() + 1, left->children + left->bound()); left->size += update_parent_(left->children + left->bound(), left->children + left->bound() + right->bound() + 1, left); left->bound() += right->bound(); right->bound() = 0; right->size = 0; right->parent = nullptr; return result_t(btree_fixmerge); } static void shift_left_inner_(inner_node_t *left, inner_node_t *right, inner_node_t *parent, size_type parent_where) { size_type shiftnum = (right->bound() - left->bound()) >> 1; construct_one_(left->item + left->bound(), parent->item[parent_where]); ++left->bound(); move_construct_(right->item, right->item + shiftnum - 1, left->item + left->bound()); std::copy(right->children, right->children + shiftnum, left->children + left->bound()); size_t count = update_parent_(left->children + left->bound(), left->children + left->bound() + shiftnum, left); left->bound() += shiftnum - 1; left->size += count; parent->item[parent_where] = right->item[shiftnum - 1]; move_forward_(right->item + shiftnum, right->item + right->bound(), right->item); destroy_range_(right->item + right->bound() - shiftnum, right->item + right->bound()); std::copy(right->children + shiftnum, right->children + right->bound() + 1, right->children); right->bound() -= shiftnum; right->size -= count; } static void shift_right_inner_(inner_node_t *left, inner_node_t *right, inner_node_t *parent, size_type parent_where) { size_type shiftnum = (left->bound() - right->bound()) >> 1; move_next_to_and_construct_(right->item, right->item + right->bound(), right->item + shiftnum); std::copy_backward(right->children, right->children + right->bound() + 1, right->children + right->bound() + 1 + shiftnum); right->bound() += shiftnum; right->item[shiftnum - 1] = parent->item[parent_where]; move_and_destroy_(left->item + left->bound() - shiftnum + 1, left->item + left->bound(), right->item); std::copy(left->children + left->bound() - shiftnum + 1, left->children + left->bound() + 1, right->children); size_t count = update_parent_(right->children, right->children + shiftnum, right); parent->item[parent_where] = left->item[left->bound() - shiftnum]; left->bound() -= shiftnum; left->size -= count; right->size += count; } size_type get_parent_(node_t *node, inner_node_t *&parent) { if(node->parent->size == 0) { parent = nullptr; return 0; } parent = static_cast<inner_node_t *>(node->parent); for(node_t **child = parent->children; ; ++child) { if(*child == node) { return child - parent->children; } } return 0; } template<class in_node_t> in_node_t *get_left_(in_node_t *node) { inner_node_t *parent; size_type where = get_parent_(node, parent); if(parent == nullptr) { return nullptr; } if(where == 0) { in_node_t *left_parent = get_left_(parent); return left_parent == nullptr ? nullptr : static_cast<in_node_t *>(left_parent->children[left_parent->bound() - 1]); } else { return static_cast<in_node_t *>(parent->children[where - 1]); } } template<class in_node_t> in_node_t *get_right_(in_node_t *node) { inner_node_t *parent; size_type where = get_parent_(node, parent); if(parent == nullptr) { return nullptr; } if(where == parent->bound()) { in_node_t *right_parent = get_right_(parent); return right_parent == nullptr ? nullptr : static_cast<in_node_t *>(right_parent->children[0]); } else { return static_cast<in_node_t *>(parent->children[where + 1]); } } template<class in_node_t> void get_left_right_parent_(inner_node_t *parent, size_type where, in_node_t *&left, inner_node_t *&left_parent, in_node_t *&right, inner_node_t *&right_parent) { if(parent == nullptr) { left = right = nullptr; left_parent = right_parent = nullptr; return; } if(where == 0) { left_parent = get_left_(parent); left = left_parent == nullptr ? nullptr : static_cast<in_node_t *>(left_parent->children[left_parent->bound() - 1]); } else { left_parent = parent; left = static_cast<in_node_t *>(parent->children[where - 1]); } if(where == parent->bound()) { right_parent = get_right_(parent); right = right_parent == nullptr ? nullptr : static_cast<in_node_t *>(right_parent->children[0]); } else { right_parent = parent; right = static_cast<in_node_t *>(parent->children[where + 1]); } } void erase_pos_(leaf_node_t *leaf_node, size_type where) { move_prev_and_destroy_one_(leaf_node->item + where + 1, leaf_node->item + leaf_node->bound()); leaf_node->bound()--; result_t result(btree_ok); inner_node_t *parent = nullptr; size_type parent_where; if(where == leaf_node->bound()) { parent_where = get_parent_(leaf_node, parent); if(parent != nullptr && parent_where < parent->bound()) { parent->item[parent_where] = get_key_t()(leaf_node->item[leaf_node->bound() - 1]); } else if(leaf_node->bound() >= 1) { result |= result_t(btree_update_lastkey, get_key_t()(leaf_node->item[leaf_node->bound() - 1])); } } if(leaf_node->is_underflow() && !(leaf_node == root_.parent && leaf_node->bound() >= 1)) { if(parent == nullptr) { parent_where = get_parent_(leaf_node, parent); } leaf_node_t *leaf_left, *leaf_right; inner_node_t *left_parent, *right_parent; get_left_right_parent_(parent, parent_where, leaf_left, left_parent, leaf_right, right_parent); if(leaf_left == nullptr && leaf_right == nullptr) { free_node_<false>(root_.parent); root_.parent = root_.left = root_.right = &root_; return; } else if((leaf_left == nullptr || leaf_left->is_few()) && (leaf_right == nullptr || leaf_right->is_few())) { if(left_parent == parent) { result |= merge_leaves_(leaf_left, leaf_node, left_parent); } else { result |= merge_leaves_(leaf_node, leaf_right, right_parent); } } else if((leaf_left != nullptr && leaf_left->is_few()) && (leaf_right != nullptr && !leaf_right->is_few())) { if(right_parent == parent) { result |= shift_left_leaf_(leaf_node, leaf_right, right_parent, parent_where); } else { result |= merge_leaves_(leaf_left, leaf_node, left_parent); } } else if((leaf_left != nullptr && !leaf_left->is_few()) && (leaf_right != nullptr && leaf_right->is_few())) { if(left_parent == parent) { shift_right_leaf_(leaf_left, leaf_node, left_parent, parent_where - 1); } else { result |= merge_leaves_(leaf_node, leaf_right, right_parent); } } else if(left_parent == right_parent) { if(leaf_left->bound() <= leaf_right->bound()) { result |= shift_left_leaf_(leaf_node, leaf_right, right_parent, parent_where); } else { shift_right_leaf_(leaf_left, leaf_node, left_parent, parent_where - 1); } } else { if(left_parent == parent) { shift_right_leaf_(leaf_left, leaf_node, left_parent, parent_where - 1); } else { result |= shift_left_leaf_(leaf_node, leaf_right, right_parent, parent_where); } } } if(result.has(result_flags_t(btree_update_lastkey | btree_fixmerge))) { if(parent != nullptr) { erase_pos_descend_(parent, parent_where, std::move(result)); } } else { for(node_t *node_parent = leaf_node->parent; node_parent->size != 0; node_parent = node_parent->parent) { --node_parent->size; } } } void erase_pos_descend_(inner_node_t *inner_node, size_type where, result_t &&result) { --inner_node->size; result_t self_result(btree_ok); inner_node_t *parent = nullptr; size_type parent_where; if(result.has(btree_update_lastkey)) { parent_where = get_parent_(inner_node, parent); if(parent != nullptr && parent_where < parent->bound()) { parent->item[parent_where] = std::move(result.last_key.key()); } else { self_result |= result_t(btree_update_lastkey, std::move(result.last_key)); } } if(result.has(btree_fixmerge)) { if(parent == nullptr) { parent_where = get_parent_(inner_node, parent); } if(inner_node->children[where]->parent != nullptr) { ++where; } free_node_<false>(inner_node->children[where]); move_prev_and_destroy_one_(inner_node->item + where, inner_node->item + inner_node->bound()); std::copy(inner_node->children + where + 1, inner_node->children + inner_node->bound() + 1, inner_node->children + where); --inner_node->bound(); if(inner_node->level == 1) { --where; leaf_node_t *child = static_cast<leaf_node_t *>(inner_node->children[where]); inner_node->item[where] = get_key_t()(child->item[child->bound() - 1]); } } if(inner_node->is_underflow() && !(inner_node == root_.parent && inner_node->bound() >= 1)) { inner_node_t *inner_left, *inner_right; inner_node_t *left_parent, *right_parent; get_left_right_parent_(parent, parent_where, inner_left, left_parent, inner_right, right_parent); if(inner_left == nullptr && inner_right == nullptr) { root_.parent = inner_node->children[0]; root_.parent->parent = &root_; inner_node->bound() = 0; free_node_<false>(inner_node); return; } else if((inner_left == nullptr || inner_left->is_few()) && (inner_right == nullptr || inner_right->is_few())) { if(left_parent == parent) { self_result |= merge_inners_(inner_left, inner_node, left_parent, parent_where - 1); } else { self_result |= merge_inners_(inner_node, inner_right, right_parent, parent_where); } } else if((inner_left != nullptr && inner_left->is_few()) && (inner_right != nullptr && !inner_right->is_few())) { if(right_parent == parent) { shift_left_inner_(inner_node, inner_right, right_parent, parent_where); } else { self_result |= merge_inners_(inner_left, inner_node, left_parent, parent_where - 1); } } else if((inner_left != nullptr && !inner_left->is_few()) && (inner_right != nullptr && inner_right->is_few())) { if(left_parent == parent) { shift_right_inner_(inner_left, inner_node, left_parent, parent_where - 1); } else { self_result |= merge_inners_(inner_node, inner_right, right_parent, parent_where); } } else if(left_parent == right_parent) { if(inner_left->bound() <= inner_right->bound()) { shift_left_inner_(inner_node, inner_right, right_parent, parent_where); } else { shift_right_inner_(inner_left, inner_node, left_parent, parent_where - 1); } } else { if(left_parent == parent) { shift_right_inner_(inner_left, inner_node, left_parent, parent_where - 1); } else { shift_left_inner_(inner_node, inner_right, right_parent, parent_where); } } } if(self_result.has(result_flags_t(btree_update_lastkey | btree_fixmerge))) { if(parent != nullptr) { erase_pos_descend_(parent, parent_where, std::move(self_result)); } } else { for(node_t *node_parent = inner_node->parent; node_parent->size != 0; node_parent = node_parent->parent) { --node_parent->size; } } } };
36.285446
242
0.567634
[ "vector" ]
ca8de6ce253fecccd370505209ce70a683f21de7
16,446
c
C
ports/rp2/machine_pin.c
oojBuffalo/micropython
5cc2dd4f5d708ded1ceb05d7755c004e4fec7295
[ "MIT" ]
null
null
null
ports/rp2/machine_pin.c
oojBuffalo/micropython
5cc2dd4f5d708ded1ceb05d7755c004e4fec7295
[ "MIT" ]
null
null
null
ports/rp2/machine_pin.c
oojBuffalo/micropython
5cc2dd4f5d708ded1ceb05d7755c004e4fec7295
[ "MIT" ]
null
null
null
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016-2021 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/mphal.h" #include "shared/runtime/mpirq.h" #include "modmachine.h" #include "extmod/virtpin.h" #include "hardware/irq.h" #include "hardware/regs/intctrl.h" #include "hardware/structs/iobank0.h" #include "hardware/structs/padsbank0.h" #define GPIO_MODE_IN (0) #define GPIO_MODE_OUT (1) #define GPIO_MODE_OPEN_DRAIN (2) #define GPIO_MODE_ALT (3) // These can be or'd together. #define GPIO_PULL_UP (1) #define GPIO_PULL_DOWN (2) #define GPIO_IRQ_ALL (0xf) // Macros to access the state of the hardware. #define GPIO_GET_FUNCSEL(id) ((iobank0_hw->io[(id)].ctrl & IO_BANK0_GPIO0_CTRL_FUNCSEL_BITS) >> IO_BANK0_GPIO0_CTRL_FUNCSEL_LSB) #define GPIO_IS_OUT(id) (sio_hw->gpio_oe & (1 << (id))) #define GPIO_IS_PULL_UP(id) (padsbank0_hw->io[(id)] & PADS_BANK0_GPIO0_PUE_BITS) #define GPIO_IS_PULL_DOWN(id) (padsbank0_hw->io[(id)] & PADS_BANK0_GPIO0_PDE_BITS) // Open drain behaviour is simulated. #define GPIO_IS_OPEN_DRAIN(id) (machine_pin_open_drain_mask & (1 << (id))) typedef struct _machine_pin_obj_t { mp_obj_base_t base; uint32_t id; } machine_pin_obj_t; typedef struct _machine_pin_irq_obj_t { mp_irq_obj_t base; uint32_t flags; uint32_t trigger; } machine_pin_irq_obj_t; STATIC const mp_irq_methods_t machine_pin_irq_methods; STATIC const machine_pin_obj_t machine_pin_obj[NUM_BANK0_GPIOS] = { {{&machine_pin_type}, 0}, {{&machine_pin_type}, 1}, {{&machine_pin_type}, 2}, {{&machine_pin_type}, 3}, {{&machine_pin_type}, 4}, {{&machine_pin_type}, 5}, {{&machine_pin_type}, 6}, {{&machine_pin_type}, 7}, {{&machine_pin_type}, 8}, {{&machine_pin_type}, 9}, {{&machine_pin_type}, 10}, {{&machine_pin_type}, 11}, {{&machine_pin_type}, 12}, {{&machine_pin_type}, 13}, {{&machine_pin_type}, 14}, {{&machine_pin_type}, 15}, {{&machine_pin_type}, 16}, {{&machine_pin_type}, 17}, {{&machine_pin_type}, 18}, {{&machine_pin_type}, 19}, {{&machine_pin_type}, 20}, {{&machine_pin_type}, 21}, {{&machine_pin_type}, 22}, {{&machine_pin_type}, 23}, {{&machine_pin_type}, 24}, {{&machine_pin_type}, 25}, {{&machine_pin_type}, 26}, {{&machine_pin_type}, 27}, {{&machine_pin_type}, 28}, {{&machine_pin_type}, 29}, }; // Mask with "1" indicating that the corresponding pin is in simulated open-drain mode. uint32_t machine_pin_open_drain_mask; STATIC void gpio_irq(void) { for (int i = 0; i < 4; ++i) { uint32_t intr = iobank0_hw->intr[i]; if (intr) { for (int j = 0; j < 8; ++j) { if (intr & 0xf) { uint32_t gpio = 8 * i + j; gpio_acknowledge_irq(gpio, intr & 0xf); machine_pin_irq_obj_t *irq = MP_STATE_PORT(machine_pin_irq_obj[gpio]); if (irq != NULL && (intr & irq->trigger)) { irq->flags = intr & irq->trigger; mp_irq_handler(&irq->base); } } intr >>= 4; } } } } void machine_pin_init(void) { memset(MP_STATE_PORT(machine_pin_irq_obj), 0, sizeof(MP_STATE_PORT(machine_pin_irq_obj))); irq_set_exclusive_handler(IO_IRQ_BANK0, gpio_irq); irq_set_enabled(IO_IRQ_BANK0, true); } void machine_pin_deinit(void) { for (int i = 0; i < NUM_BANK0_GPIOS; ++i) { gpio_set_irq_enabled(i, GPIO_IRQ_ALL, false); } irq_set_enabled(IO_IRQ_BANK0, false); irq_remove_handler(IO_IRQ_BANK0, gpio_irq); } STATIC void machine_pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { machine_pin_obj_t *self = self_in; uint funcsel = GPIO_GET_FUNCSEL(self->id); qstr mode_qst; if (funcsel == GPIO_FUNC_SIO) { if (GPIO_IS_OPEN_DRAIN(self->id)) { mode_qst = MP_QSTR_OPEN_DRAIN; } else if (GPIO_IS_OUT(self->id)) { mode_qst = MP_QSTR_OUT; } else { mode_qst = MP_QSTR_IN; } } else { mode_qst = MP_QSTR_ALT; } mp_printf(print, "Pin(%u, mode=%q", self->id, mode_qst); bool pull_up = false; if (GPIO_IS_PULL_UP(self->id)) { mp_printf(print, ", pull=%q", MP_QSTR_PULL_UP); pull_up = true; } if (GPIO_IS_PULL_DOWN(self->id)) { if (pull_up) { mp_printf(print, "|%q", MP_QSTR_PULL_DOWN); } else { mp_printf(print, ", pull=%q", MP_QSTR_PULL_DOWN); } } if (funcsel != GPIO_FUNC_SIO) { mp_printf(print, ", alt=%u", funcsel); } mp_printf(print, ")"); } // pin.init(mode, pull=None, *, value=None, alt=FUNC_SIO) STATIC mp_obj_t machine_pin_obj_init_helper(const machine_pin_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_mode, ARG_pull, ARG_value, ARG_alt }; static const mp_arg_t allowed_args[] = { { MP_QSTR_mode, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE}}, { MP_QSTR_pull, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE}}, { MP_QSTR_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE}}, { MP_QSTR_alt, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = GPIO_FUNC_SIO}}, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // set initial value (do this before configuring mode/pull) if (args[ARG_value].u_obj != mp_const_none) { gpio_put(self->id, mp_obj_is_true(args[ARG_value].u_obj)); } // configure mode if (args[ARG_mode].u_obj != mp_const_none) { mp_int_t mode = mp_obj_get_int(args[ARG_mode].u_obj); if (mode == GPIO_MODE_IN) { mp_hal_pin_input(self->id); } else if (mode == GPIO_MODE_OUT) { mp_hal_pin_output(self->id); } else if (mode == GPIO_MODE_OPEN_DRAIN) { mp_hal_pin_open_drain(self->id); } else { // Alternate function. gpio_set_function(self->id, args[ARG_alt].u_int); machine_pin_open_drain_mask &= ~(1 << self->id); } } // configure pull (unconditionally because None means no-pull) uint32_t pull = 0; if (args[ARG_pull].u_obj != mp_const_none) { pull = mp_obj_get_int(args[ARG_pull].u_obj); } gpio_set_pulls(self->id, pull & GPIO_PULL_UP, pull & GPIO_PULL_DOWN); return mp_const_none; } // constructor(id, ...) mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true); // get the wanted pin object int wanted_pin = mp_obj_get_int(args[0]); if (!(0 <= wanted_pin && wanted_pin < MP_ARRAY_SIZE(machine_pin_obj))) { mp_raise_ValueError("invalid pin"); } const machine_pin_obj_t *self = &machine_pin_obj[wanted_pin]; if (n_args > 1 || n_kw > 0) { // pin mode given, so configure this GPIO mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); machine_pin_obj_init_helper(self, n_args - 1, args + 1, &kw_args); } return MP_OBJ_FROM_PTR(self); } // fast method for getting/setting pin value STATIC mp_obj_t machine_pin_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); machine_pin_obj_t *self = self_in; if (n_args == 0) { // get pin return MP_OBJ_NEW_SMALL_INT(gpio_get(self->id)); } else { // set pin bool value = mp_obj_is_true(args[0]); if (GPIO_IS_OPEN_DRAIN(self->id)) { MP_STATIC_ASSERT(GPIO_IN == 0 && GPIO_OUT == 1); gpio_set_dir(self->id, 1 - value); } else { gpio_put(self->id, value); } return mp_const_none; } } // pin.init(mode, pull) STATIC mp_obj_t machine_pin_obj_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { return machine_pin_obj_init_helper(args[0], n_args - 1, args + 1, kw_args); } MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_init_obj, 1, machine_pin_obj_init); // pin.value([value]) STATIC mp_obj_t machine_pin_value(size_t n_args, const mp_obj_t *args) { return machine_pin_call(args[0], n_args - 1, 0, args + 1); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_pin_value_obj, 1, 2, machine_pin_value); // pin.low() STATIC mp_obj_t machine_pin_low(mp_obj_t self_in) { machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in); if (GPIO_IS_OPEN_DRAIN(self->id)) { gpio_set_dir(self->id, GPIO_OUT); } else { gpio_clr_mask(1u << self->id); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_low_obj, machine_pin_low); // pin.high() STATIC mp_obj_t machine_pin_high(mp_obj_t self_in) { machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in); if (GPIO_IS_OPEN_DRAIN(self->id)) { gpio_set_dir(self->id, GPIO_IN); } else { gpio_set_mask(1u << self->id); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_high_obj, machine_pin_high); // pin.toggle() STATIC mp_obj_t machine_pin_toggle(mp_obj_t self_in) { machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in); if (GPIO_IS_OPEN_DRAIN(self->id)) { if (GPIO_IS_OUT(self->id)) { gpio_set_dir(self->id, GPIO_IN); } else { gpio_set_dir(self->id, GPIO_OUT); } } else { gpio_xor_mask(1u << self->id); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_toggle_obj, machine_pin_toggle); STATIC machine_pin_irq_obj_t *machine_pin_get_irq(mp_hal_pin_obj_t pin) { // Get the IRQ object. machine_pin_irq_obj_t *irq = MP_STATE_PORT(machine_pin_irq_obj[pin]); // Allocate the IRQ object if it doesn't already exist. if (irq == NULL) { irq = m_new_obj(machine_pin_irq_obj_t); irq->base.base.type = &mp_irq_type; irq->base.methods = (mp_irq_methods_t *)&machine_pin_irq_methods; irq->base.parent = MP_OBJ_FROM_PTR(&machine_pin_obj[pin]); irq->base.handler = mp_const_none; irq->base.ishard = false; MP_STATE_PORT(machine_pin_irq_obj[pin]) = irq; } return irq; } void mp_hal_pin_interrupt(mp_hal_pin_obj_t pin, mp_obj_t handler, mp_uint_t trigger, bool hard) { machine_pin_irq_obj_t *irq = machine_pin_get_irq(pin); // Disable all IRQs while data is updated. gpio_set_irq_enabled(pin, GPIO_IRQ_ALL, false); // Update IRQ data. irq->base.handler = handler; irq->base.ishard = hard; irq->flags = 0; irq->trigger = trigger; // Enable IRQ if a handler is given. if (handler != mp_const_none && trigger != MP_HAL_PIN_TRIGGER_NONE) { gpio_set_irq_enabled(pin, trigger, true); } } // pin.irq(handler=None, trigger=IRQ_FALLING|IRQ_RISING, hard=False) STATIC mp_obj_t machine_pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_handler, ARG_trigger, ARG_hard }; static const mp_arg_t allowed_args[] = { { MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_trigger, MP_ARG_INT, {.u_int = MP_HAL_PIN_TRIGGER_FALL | MP_HAL_PIN_TRIGGER_RISE} }, { MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} }, }; machine_pin_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); machine_pin_irq_obj_t *irq = machine_pin_get_irq(self->id); if (n_args > 1 || kw_args->used != 0) { // Update IRQ data. mp_obj_t handler = args[ARG_handler].u_obj; mp_uint_t trigger = args[ARG_trigger].u_int; bool hard = args[ARG_hard].u_bool; mp_hal_pin_interrupt(self->id, handler, trigger, hard); } return MP_OBJ_FROM_PTR(irq); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_irq_obj, 1, machine_pin_irq); STATIC const mp_rom_map_elem_t machine_pin_locals_dict_table[] = { // instance methods { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_pin_init_obj) }, { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&machine_pin_value_obj) }, { MP_ROM_QSTR(MP_QSTR_low), MP_ROM_PTR(&machine_pin_low_obj) }, { MP_ROM_QSTR(MP_QSTR_high), MP_ROM_PTR(&machine_pin_high_obj) }, { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&machine_pin_low_obj) }, { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&machine_pin_high_obj) }, { MP_ROM_QSTR(MP_QSTR_toggle), MP_ROM_PTR(&machine_pin_toggle_obj) }, { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&machine_pin_irq_obj) }, // class constants { MP_ROM_QSTR(MP_QSTR_IN), MP_ROM_INT(GPIO_MODE_IN) }, { MP_ROM_QSTR(MP_QSTR_OUT), MP_ROM_INT(GPIO_MODE_OUT) }, { MP_ROM_QSTR(MP_QSTR_OPEN_DRAIN), MP_ROM_INT(GPIO_MODE_OPEN_DRAIN) }, { MP_ROM_QSTR(MP_QSTR_ALT), MP_ROM_INT(GPIO_MODE_ALT) }, { MP_ROM_QSTR(MP_QSTR_PULL_UP), MP_ROM_INT(GPIO_PULL_UP) }, { MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(GPIO_PULL_DOWN) }, { MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(GPIO_IRQ_EDGE_RISE) }, { MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(GPIO_IRQ_EDGE_FALL) }, }; STATIC MP_DEFINE_CONST_DICT(machine_pin_locals_dict, machine_pin_locals_dict_table); STATIC mp_uint_t pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { (void)errcode; machine_pin_obj_t *self = self_in; switch (request) { case MP_PIN_READ: { return gpio_get(self->id); } case MP_PIN_WRITE: { gpio_put(self->id, arg); return 0; } } return -1; } STATIC const mp_pin_p_t pin_pin_p = { .ioctl = pin_ioctl, }; const mp_obj_type_t machine_pin_type = { { &mp_type_type }, .name = MP_QSTR_Pin, .print = machine_pin_print, .make_new = mp_pin_make_new, .call = machine_pin_call, .protocol = &pin_pin_p, .locals_dict = (mp_obj_t)&machine_pin_locals_dict, }; STATIC mp_uint_t machine_pin_irq_trigger(mp_obj_t self_in, mp_uint_t new_trigger) { machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in); machine_pin_irq_obj_t *irq = MP_STATE_PORT(machine_pin_irq_obj[self->id]); gpio_set_irq_enabled(self->id, GPIO_IRQ_ALL, false); irq->flags = 0; irq->trigger = new_trigger; gpio_set_irq_enabled(self->id, new_trigger, true); return 0; } STATIC mp_uint_t machine_pin_irq_info(mp_obj_t self_in, mp_uint_t info_type) { machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in); machine_pin_irq_obj_t *irq = MP_STATE_PORT(machine_pin_irq_obj[self->id]); if (info_type == MP_IRQ_INFO_FLAGS) { return irq->flags; } else if (info_type == MP_IRQ_INFO_TRIGGERS) { return irq->trigger; } return 0; } STATIC const mp_irq_methods_t machine_pin_irq_methods = { .trigger = machine_pin_irq_trigger, .info = machine_pin_irq_info, }; mp_hal_pin_obj_t mp_hal_get_pin_obj(mp_obj_t obj) { if (!mp_obj_is_type(obj, &machine_pin_type)) { mp_raise_ValueError(MP_ERROR_TEXT("expecting a Pin")); } machine_pin_obj_t *pin = MP_OBJ_TO_PTR(obj); return pin->id; }
35.597403
136
0.675301
[ "object" ]
ca92b8b1eadb7aa3f7633f269a85526bf2c0fa87
23,916
c
C
src/common/tiles.c
NLAFET/StarNEig
d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286
[ "BSD-3-Clause" ]
12
2019-04-28T17:13:04.000Z
2021-12-24T12:30:19.000Z
src/common/tiles.c
NLAFET/StarNEig
d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286
[ "BSD-3-Clause" ]
null
null
null
src/common/tiles.c
NLAFET/StarNEig
d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286
[ "BSD-3-Clause" ]
4
2019-04-30T12:14:12.000Z
2020-04-14T09:41:23.000Z
/// /// @file /// /// @brief This file contains the definition of a tile packing helper subsystem /// that is used throughout all components of the library. /// /// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University /// /// @internal LICENSE /// /// Copyright (c) 2019-2020, Umeå Universitet /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived from this /// software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE /// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE /// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR /// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF /// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN /// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// #include <starneig_config.h> #include <starneig/configuration.h> #include "tiles.h" #include "common.h" #include "scratch.h" /// /// @brief Re-sizes packing helper structure array if necessary. /// /// @param[in] k number of handles to back /// @param[in,out] helper packing helper structure /// static void prep_packing_helper(int k, struct packing_helper *helper) { int left = helper->size - helper->count; if (left < k) { int new_size = helper->size + k - left + 10; struct starpu_data_descr *new_descrs = malloc(new_size*sizeof(struct starpu_data_descr)); memcpy(new_descrs, helper->descrs, helper->size*sizeof(struct starpu_data_descr)); free(helper->descrs); helper->descrs = new_descrs; packing_mode_flag_t *new_flags = malloc(new_size*sizeof(packing_mode_flag_t)); memcpy(new_flags, helper->flags, helper->size*sizeof(packing_mode_flag_t)); free(helper->flags); helper->flags = new_flags; helper->size = new_size; } } /// /// @brief Pre-fills packing info structure. /// /// @param[in] rbegin first row that belongs to the window /// @param[in] rend last row that belongs to the window + 1 /// @param[in] cbegin first column that belongs to the window /// @param[in] cend last column that belongs to the window + 1 /// @param[in] matrix matrix descriptor /// @param[out] info packing information /// @param[in] flag packing mode flag /// static void prefill_packing_info( int rbegin, int rend, int cbegin, int cend, const starneig_matrix_t matrix, struct packing_info *info, packing_mode_flag_t flag) { STARNEIG_ASSERT(0 <= rbegin && rend <= STARNEIG_MATRIX_M(matrix)); STARNEIG_ASSERT(0 <= cbegin && cend <= STARNEIG_MATRIX_N(matrix)); int rbbegin = STARNEIG_MATRIX_TILE_IDX(rbegin, matrix); int cbbegin = STARNEIG_MATRIX_TILE_IDY(cbegin, matrix); info->flag = flag; info->elemsize = STARNEIG_MATRIX_ELEMSIZE(matrix); info->bm = STARNEIG_MATRIX_BM(matrix); info->bn = STARNEIG_MATRIX_BN(matrix); info->rbegin = STARNEIG_MATRIX_RBEGIN(matrix) + rbegin - rbbegin*STARNEIG_MATRIX_BM(matrix); info->rend = STARNEIG_MATRIX_RBEGIN(matrix) + rend - rbbegin*STARNEIG_MATRIX_BM(matrix); info->cbegin = STARNEIG_MATRIX_CBEGIN(matrix) + cbegin - cbbegin*STARNEIG_MATRIX_BN(matrix); info->cend = STARNEIG_MATRIX_CBEGIN(matrix) + cend - cbbegin*STARNEIG_MATRIX_BN(matrix); info->m = STARNEIG_MATRIX_M(matrix); info->n = STARNEIG_MATRIX_N(matrix); info->roffset = rbegin; info->coffset = cbegin; info->handles = 0; } static void pack_window_full( enum starpu_data_access_mode mode, int rbegin, int rend, int cbegin, int cend, starneig_matrix_t matrix, struct packing_helper *helper, struct packing_info *info, packing_mode_flag_t flag) { STARNEIG_ASSERT(!(flag & PACKING_MODE_SUBMIT_UNREGISTER)); int rbbegin = STARNEIG_MATRIX_TILE_IDX(rbegin, matrix); int rbend = STARNEIG_MATRIX_TILE_IDX(rend-1, matrix) + 1; int cbbegin = STARNEIG_MATRIX_TILE_IDY(cbegin, matrix); int cbend = STARNEIG_MATRIX_TILE_IDY(cend-1, matrix) + 1; prep_packing_helper((rbend-rbbegin)*(cbend-cbbegin), helper); prefill_packing_info(rbegin, rend, cbegin, cend, matrix, info, flag); struct starpu_data_descr *descrs = helper->descrs + helper->count; packing_mode_flag_t *flags = helper->flags + helper->count; int k = 0; for (int i = cbbegin; i < cbend; i++) { for (int j = rbbegin; j < rbend; j++) { descrs[k].handle = starneig_matrix_get_tile(j, i, matrix); descrs[k].mode = mode; flags[k] = PACKING_MODE_DEFAULT; k++; } } helper->count += k; info->handles = k; #ifdef STARNEIG_ENABLE_EVENTS info->event_label = matrix->event_label; info->event_enabled = matrix->event_enabled; info->event_roffset = matrix->event_roffset; info->event_coffset = matrix->event_coffset; #endif } static void pack_window_upper_hess( enum starpu_data_access_mode mode, int begin, int end, starneig_matrix_t matrix, struct packing_helper *helper, struct packing_info *info, packing_mode_flag_t flag) { STARNEIG_ASSERT(!(flag & PACKING_MODE_SUBMIT_UNREGISTER)); STARNEIG_ASSERT( STARNEIG_MATRIX_RBEGIN(matrix) == STARNEIG_MATRIX_CBEGIN(matrix)); int rbbegin = STARNEIG_MATRIX_TILE_IDX(begin, matrix); int rbend = STARNEIG_MATRIX_TILE_IDX(end-1, matrix) + 1; int cbbegin = STARNEIG_MATRIX_TILE_IDY(begin, matrix); int cbend = STARNEIG_MATRIX_TILE_IDY(end-1, matrix) + 1; int tiles = 0; for (int i = cbbegin; i < cbend; i++) for (int j = rbbegin; j < rbend; j++) if ( j*STARNEIG_MATRIX_BM(matrix) <= (i+1)*STARNEIG_MATRIX_BN(matrix)) tiles++; prep_packing_helper(tiles, helper); prefill_packing_info(begin, end, begin, end, matrix, info, flag); struct starpu_data_descr *descrs = helper->descrs + helper->count; packing_mode_flag_t *flags = helper->flags + helper->count; int k = 0; for (int i = cbbegin; i < cbend; i++) { for (int j = rbbegin; j < rbend; j++) { if ( j*STARNEIG_MATRIX_BM(matrix) <= (i+1)*STARNEIG_MATRIX_BN(matrix)) { descrs[k].handle = starneig_matrix_get_tile(j, i, matrix); descrs[k].mode = mode; flags[k] = PACKING_MODE_DEFAULT; k++; } } } helper->count += k; info->handles = k; #ifdef STARNEIG_ENABLE_EVENTS info->event_label = matrix->event_label; info->event_enabled = matrix->event_enabled; info->event_roffset = matrix->event_roffset; info->event_coffset = matrix->event_coffset; #endif } static void pack_window_upper_triag( enum starpu_data_access_mode mode, int begin, int end, starneig_matrix_t matrix, struct packing_helper *helper, struct packing_info *info, packing_mode_flag_t flag) { STARNEIG_ASSERT(!(flag & PACKING_MODE_SUBMIT_UNREGISTER)); STARNEIG_ASSERT( STARNEIG_MATRIX_RBEGIN(matrix) == STARNEIG_MATRIX_CBEGIN(matrix)); int rbbegin = STARNEIG_MATRIX_TILE_IDX(begin, matrix); int rbend = STARNEIG_MATRIX_TILE_IDX(end-1, matrix) + 1; int cbbegin = STARNEIG_MATRIX_TILE_IDY(begin, matrix); int cbend = STARNEIG_MATRIX_TILE_IDY(end-1, matrix) + 1; int tiles = 0; for (int i = cbbegin; i < cbend; i++) for (int j = rbbegin; j < rbend; j++) if ( j*STARNEIG_MATRIX_BM(matrix) <= (i+1)*STARNEIG_MATRIX_BN(matrix)-1) tiles++; prep_packing_helper(tiles, helper); prefill_packing_info(begin, end, begin, end, matrix, info, flag); struct starpu_data_descr *descrs = helper->descrs + helper->count; packing_mode_flag_t *flags = helper->flags + helper->count; int k = 0; for (int i = cbbegin; i < cbend; i++) { for (int j = rbbegin; j < rbend; j++) { if (j*STARNEIG_MATRIX_BM(matrix) <= (i+1)*STARNEIG_MATRIX_BN(matrix)-1) { descrs[k].handle = starneig_matrix_get_tile(j, i, matrix); descrs[k].mode = mode; flags[k] = PACKING_MODE_DEFAULT; k++; } } } helper->count += k; info->handles = k; #ifdef STARNEIG_ENABLE_EVENTS info->event_label = matrix->event_label; info->event_enabled = matrix->event_enabled; info->event_roffset = matrix->event_roffset; info->event_coffset = matrix->event_coffset; #endif } static void join_tiles_full( int rbegin, int rend, int cbegin, int cend, int bm, int bn, size_t in_ld, size_t out_ld, size_t elemsize, struct starpu_matrix_interface **in, void *out, int reverse) { // first tile row and last tile row + 1 int tr_begin = rbegin / bm; int tr_end = (rend - 1) / bm + 1; // first tile column and last tile column + 1 int tc_begin = cbegin / bn; int tc_end = (cend - 1) / bn + 1; // // go through all tiles that make up the window // for (int i = tc_begin; i < tc_end; i++) { // vertical bounds inside the current tile int _cbegin = MAX(0, cbegin - i * bn); int _cend = MIN(bn, cend - i * bn); // vertical offset inside the output buffer int column_offset = MAX(0, i * bn - cbegin); for (int j = tr_begin; j < tr_end; j++) { // horizontal bounds inside the current tile int _rbegin = MAX(0, rbegin - j * bm); int _rend = MIN(bm, rend - j * bm); // horizontal offset inside the output buffer int row_offset = MAX(0, j * bm - rbegin); // // copy // void *ptr_ = (void *) STARPU_MATRIX_GET_PTR(in[i*in_ld+j]); size_t _ld = STARPU_MATRIX_GET_LD(in[i*in_ld+j]); if (reverse) starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, out_ld, _ld, elemsize, out + (column_offset*out_ld + row_offset)*elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize); else starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, _ld, out_ld, elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize, out + (column_offset*out_ld + row_offset)*elemsize); } } } static void join_tiles_upper_hess( int rbegin, int rend, int cbegin, int cend, int bm, int bn, size_t out_ld, size_t elemsize, struct starpu_matrix_interface **in, void *out, int reverse) { // // initialize the lower left corner of the output buffer to zero // if (!reverse) { int n = cend - cbegin; for (int i = 0; i < n; i++) { int m = (rend-rbegin)-i; memset(out+(i*out_ld+i)*elemsize, 0, m*elemsize); } } // first tile row and last tile row + 1 int tr_begin = rbegin / bm; int tr_end = (rend - 1) / bm + 1; // first tile column and last tile column + 1 int tc_begin = cbegin / bn; int tc_end = (cend - 1) / bn + 1; // // go through all tiles that make up the window // int tid = 0; for (int i = tc_begin; i < tc_end; i++) { // vertical bounds inside the current tile int _cbegin = MAX(0, cbegin - i * bn); int _cend = MIN(bn, cend - i * bn); // vertical offset inside the output buffer int column_offset = MAX(0, i * bn - cbegin); for (int j = tr_begin; j < tr_end; j++) { if (cbegin+(i+1)*bn < rbegin+j*bm) continue; // horizontal bounds inside the current tile int _rbegin = MAX(0, rbegin - j * bm); int _rend = MIN(bm, rend - j * bm); // horizontal offset inside the output buffer int row_offset = MAX(0, j * bm - rbegin); // // copy // void *ptr_ = (void *) STARPU_MATRIX_GET_PTR(in[tid]); size_t _ld = STARPU_MATRIX_GET_LD(in[tid]); if (reverse) starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, out_ld, _ld, elemsize, out + (column_offset*out_ld + row_offset)*elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize); else starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, _ld, out_ld, elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize, out + (column_offset*out_ld + row_offset)*elemsize); tid++; } } } static void join_tiles_upper_triag( int rbegin, int rend, int cbegin, int cend, int bm, int bn, size_t out_ld, size_t elemsize, struct starpu_matrix_interface **in, void *out, int reverse) { // // initialize the lower left corner of the output buffer to zero // if (!reverse) { int n = cend - cbegin; for (int i = 0; i < n; i++) { int m = (rend-rbegin)-i; memset(out+(i*out_ld+i)*elemsize, 0, m*elemsize); } } // first tile row and last tile row + 1 int tr_begin = rbegin / bm; int tr_end = (rend - 1) / bm + 1; // first tile column and last tile column + 1 int tc_begin = cbegin / bn; int tc_end = (cend - 1) / bn + 1; // // go through all tiles that make up the window // int tid = 0; for (int i = tc_begin; i < tc_end; i++) { // vertical bounds inside the current tile int _cbegin = MAX(0, cbegin - i * bn); int _cend = MIN(bn, cend - i * bn); // vertical offset inside the output buffer int column_offset = MAX(0, i * bn - cbegin); for (int j = tr_begin; j < tr_end; j++) { if (cbegin+(i+1)*bn <= rbegin+j*bm) continue; // horizontal bounds inside the current tile int _rbegin = MAX(0, rbegin - j * bm); int _rend = MIN(bm, rend - j * bm); // horizontal offset inside the output buffer int row_offset = MAX(0, j * bm - rbegin); // // copy // void *ptr_ = (void *) STARPU_MATRIX_GET_PTR(in[tid]); size_t _ld = STARPU_MATRIX_GET_LD(in[tid]); if (reverse) starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, out_ld, _ld, elemsize, out + (column_offset*out_ld + row_offset)*elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize); else starneig_copy_matrix( _rend - _rbegin, _cend - _cbegin, _ld, out_ld, elemsize, ptr_ + (_cbegin*_ld + _rbegin)*elemsize, out + (column_offset*out_ld + row_offset)*elemsize); tid++; } } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// void starneig_init_empty_packing_info(struct packing_info *info) { memset(info, 0, sizeof(struct packing_info)); } void starneig_init_empty_range_packing_info(struct range_packing_info *info) { memset(info, 0, sizeof(struct range_packing_info)); } struct packing_helper * starneig_init_packing_helper() { struct packing_helper *helper = malloc(sizeof(struct packing_helper)); memset(helper, 0, sizeof(struct packing_helper)); prep_packing_helper(10, helper); return helper; } void starneig_free_packing_helper(struct packing_helper *helper) { if (helper == NULL) return; for (int i = 0; i < helper->count; i++) if (helper->flags[i] & PACKING_MODE_SUBMIT_UNREGISTER) starpu_data_unregister_submit(helper->descrs[i].handle); starneig_scratch_flush(); free(helper->descrs); free(helper->flags); free(helper); } void starneig_pack_handle( enum starpu_data_access_mode mode, starpu_data_handle_t handle, struct packing_helper *helper, packing_mode_flag_t flag) { prep_packing_helper(1, helper); helper->descrs[helper->count].handle = handle; helper->descrs[helper->count].mode = mode; helper->flags[helper->count] = flag; helper->count++; } void starneig_pack_scratch_matrix( int m, int n, size_t elemsize, struct packing_helper *helper) { starpu_data_handle_t handle; starpu_matrix_data_register(&handle, -1, 0, m, m, n, elemsize); starneig_pack_handle( STARPU_SCRATCH, handle, helper, PACKING_MODE_SUBMIT_UNREGISTER); } void starneig_pack_cached_scratch_matrix( int m, int n, size_t elemsize, struct packing_helper *helper) { starpu_data_handle_t handle = starneig_scratch_get_matrix(m, n, elemsize); starneig_pack_handle( STARPU_SCRATCH, handle, helper, PACKING_MODE_DEFAULT); } void starneig_pack_range( enum starpu_data_access_mode mode, int begin, int end, starneig_vector_t vector, struct packing_helper *helper, struct range_packing_info *info, packing_mode_flag_t flag) { if (vector == NULL) { starneig_init_empty_range_packing_info(info); return; } STARNEIG_ASSERT(!(flag & PACKING_MODE_SUBMIT_UNREGISTER)); int bbegin = begin / starneig_vector_get_tile_size(vector); int bend = (end-1) / starneig_vector_get_tile_size(vector) + 1; prep_packing_helper(bend - bbegin , helper); struct starpu_data_descr *descrs = helper->descrs + helper->count; packing_mode_flag_t *flags = helper->flags + helper->count; int k = 0; for (int i = bbegin; i < bend; i++) { descrs[k].handle = starneig_vector_get_tile(i, vector); descrs[k].mode = mode; flags[k] = flag; k++; } helper->count += k; info->flag = flag; info->elemsize = starneig_vector_get_elemsize(vector); info->bm = starneig_vector_get_tile_size(vector); info->begin = begin - bbegin*starneig_vector_get_tile_size(vector); info->end = end - bbegin*starneig_vector_get_tile_size(vector); info->m = starneig_vector_get_rows(vector); info->offset = begin; info->handles = k; } void starneig_join_range( struct range_packing_info const *packing_info, struct starpu_vector_interface **in, void *out, int reverse) { if (packing_info->handles == 0) return; // first tile row and last tile row + 1 int t_begin = packing_info->begin / packing_info->bm; int t_end = (packing_info->end - 1) / packing_info->bm + 1; // // go through all tiles that make up the window // for (int i = t_begin; i < t_end; i++) { // horizontal bounds inside the current tile int _begin = MAX(0, packing_info->begin - i * packing_info->bm); int _end = MIN(packing_info->bm, packing_info->end - i * packing_info->bm); // horizontal offset inside the output buffer int row_offset = MAX(0, i * packing_info->bm - packing_info->begin); // copy void *ptr = (void *) STARPU_VECTOR_GET_PTR(in[i]); if (reverse) memcpy(ptr+_begin*packing_info->elemsize, out+row_offset*packing_info->elemsize, (_end-_begin)*packing_info->elemsize); else memcpy(out+row_offset*packing_info->elemsize, ptr+_begin*packing_info->elemsize, (_end-_begin)*packing_info->elemsize); } } void starneig_pack_window( enum starpu_data_access_mode mode, int rbegin, int rend, int cbegin, int cend, starneig_matrix_t matrix, struct packing_helper *helper, struct packing_info *info, packing_mode_flag_t flag) { if (matrix == NULL) { starneig_init_empty_packing_info(info); return; } pack_window_full( mode, rbegin, rend, cbegin, cend, matrix, helper, info, flag); } void starneig_join_window( struct packing_info const *packing_info, size_t ld, struct starpu_matrix_interface **in, void *out, int reverse) { if (packing_info->handles == 0) return; join_tiles_full( packing_info->rbegin, packing_info->rend, packing_info->cbegin, packing_info->cend, packing_info->bm, packing_info->bn, divceil(packing_info->rend, packing_info->bm), ld, packing_info->elemsize, in, out, reverse); } void starneig_join_sub_window( int rbegin, int rend, int cbegin, int cend, struct packing_info const *packing_info, size_t ld, struct starpu_matrix_interface **in, void *out, int reverse) { if (packing_info->handles == 0) return; join_tiles_full( packing_info->rbegin+rbegin, packing_info->rbegin+rend, packing_info->cbegin+cbegin, packing_info->cbegin+cend, packing_info->bm, packing_info->bn, divceil(packing_info->rend, packing_info->bm), ld, packing_info->elemsize, in, out, reverse); } void starneig_pack_diag_window( enum starpu_data_access_mode mode, int begin, int end, starneig_matrix_t matrix, struct packing_helper *helper, struct packing_info *info, packing_mode_flag_t flag) { if (matrix == NULL) { starneig_init_empty_packing_info(info); return; } if (flag & PACKING_MODE_UPPER_HESSENBERG) pack_window_upper_hess(mode, begin, end, matrix, helper, info, flag); else if (flag & PACKING_MODE_UPPER_TRIANGULAR) pack_window_upper_triag(mode, begin, end, matrix, helper, info, flag); else pack_window_full( mode, begin, end, begin, end, matrix, helper, info, flag); } void starneig_join_diag_window( struct packing_info const *packing_info, size_t ld, struct starpu_matrix_interface **in, void *out, int reverse) { if (packing_info->handles == 0) return; if (packing_info->flag & PACKING_MODE_UPPER_HESSENBERG) join_tiles_upper_hess( packing_info->rbegin, packing_info->rend, packing_info->cbegin, packing_info->cend, packing_info->bm, packing_info->bn, ld, packing_info->elemsize, in, out, reverse); else if (packing_info->flag & PACKING_MODE_UPPER_TRIANGULAR) join_tiles_upper_triag( packing_info->rbegin, packing_info->rend, packing_info->cbegin, packing_info->cend, packing_info->bm, packing_info->bn, ld, packing_info->elemsize, in, out, reverse); else join_tiles_full( packing_info->rbegin, packing_info->rend, packing_info->cbegin, packing_info->cend, packing_info->bm, packing_info->bn, divceil(packing_info->rend, packing_info->bm), ld, packing_info->elemsize, in, out, reverse); }
33.448951
80
0.625481
[ "vector" ]
a997df1e16d0b986dd1380a4c6150326976d2c6d
1,979
h
C
include/util/graph.h
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
20
2015-02-25T22:38:29.000Z
2021-10-02T17:56:03.000Z
include/util/graph.h
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
2
2016-02-10T16:45:34.000Z
2018-09-25T03:48:10.000Z
include/util/graph.h
sandysa/A-MultiObjective-Approach-to-Mitigate-Negative-Side-Effects
9d124078848dde7d03266982494f59cc27c007e0
[ "MIT" ]
4
2016-02-26T22:05:41.000Z
2020-05-22T20:42:22.000Z
#ifndef MDPLIB_GRAPH_H #define MDPLIB_GRAPH_H #include <vector> #include <unordered_set> #include <unordered_map> #include <queue> #include <list> #include <limits> #include <cassert> #define vc_vertex first #define vc_cost second const double gr_infinity = std::numeric_limits<double>::max(); typedef std::pair<int, double> vertexCost; class Graph { private: std::vector< std::unordered_map<int, double> > adjList; public: Graph() {} Graph(int numVertices) { for (int i = 0; i < numVertices; i++) { adjList.push_back(std::unordered_map<int, double> () ); } } Graph(Graph& g) { adjList = g.adjList; } Graph& operator=(const Graph& rhs) { if (this == &rhs) return *this; adjList = rhs.adjList; return *this; } double weight(unsigned int i, unsigned int j) { assert(i >= 0 && i < adjList.size() && j >= 0 && j < adjList.size()); if (adjList[i].find(j) == adjList[i].end()) return gr_infinity; else return adjList[i][j]; } bool connect(unsigned int i, unsigned int j, double weight) { assert(i >= 0 && i < adjList.size() && j >= 0 && j < adjList.size()); adjList[i][j] = weight; } std::unordered_map<int, double>& neighbors(unsigned int i) { assert(i >= 0 && i < adjList.size()); return adjList[i]; } int numVertices() { return adjList.size(); } }; class cmpVertexDijkstra { public: bool operator() (const vertexCost& lhs, const vertexCost&rhs) const { return (lhs.vc_cost > rhs.vc_cost); } }; /** * Returns the single source shortest distances from the given vertex to all * vertices on the given graph. */ std::vector<double> dijkstra(Graph g, int v0); /** * Checks if vertex v can be reached from vertex u in the given graph. */ bool reachable(Graph g, int u, int v); #endif // MDPLIB_GRAPH_H
20.614583
77
0.593734
[ "vector" ]
a99eb7aacb85048edef6769d774ec5355b7c4ba8
4,063
h
C
Gems/PhysX/Code/Source/Joint/PhysXJointUtils.h
Shorotshishir/o3de
b0c522be5196a7166cb6f13d3ddf8dae75ef06c1
[ "Apache-2.0", "MIT" ]
8
2021-08-31T02:14:19.000Z
2021-12-28T19:20:59.000Z
Gems/PhysX/Code/Source/Joint/PhysXJointUtils.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
8
2021-07-12T13:55:00.000Z
2021-10-04T14:53:21.000Z
Gems/PhysX/Code/Source/Joint/PhysXJointUtils.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
1
2021-07-09T06:02:14.000Z
2021-07-09T06:02:14.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Math/Quaternion.h> #include <AzCore/Math/Transform.h> #include <AzCore/Math/Vector3.h> #include <PxPhysicsAPI.h> namespace PhysX { namespace JointConstants { // Setting joint limits to very small values can cause extreme stability problems, so clamp above a small // threshold. static const float MinSwingLimitDegrees = 1.0f; // Minimum range between lower and upper twist limits. static const float MinTwistLimitRangeDegrees = 1.0f; } // namespace JointConstants namespace Utils { using PxJointUniquePtr = AZStd::unique_ptr<physx::PxJoint, AZStd::function<void(physx::PxJoint*)>>; bool IsAtLeastOneDynamic(AzPhysics::SimulatedBody* body0, AzPhysics::SimulatedBody* body1); physx::PxRigidActor* GetPxRigidActor(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle worldBodyHandle); AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle( AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle); namespace PxJointFactories { PxJointUniquePtr CreatePxD6Joint(const PhysX::D6JointLimitConfiguration& configuration, AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle parentBodyHandle, AzPhysics::SimulatedBodyHandle childBodyHandle); PxJointUniquePtr CreatePxFixedJoint(const PhysX::FixedJointConfiguration& configuration, AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle parentBodyHandle, AzPhysics::SimulatedBodyHandle childBodyHandle); PxJointUniquePtr CreatePxBallJoint(const PhysX::BallJointConfiguration& configuration, AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle parentBodyHandle, AzPhysics::SimulatedBodyHandle childBodyHandle); PxJointUniquePtr CreatePxHingeJoint(const PhysX::HingeJointConfiguration& configuration, AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle parentBodyHandle, AzPhysics::SimulatedBodyHandle childBodyHandle); } // namespace PxActorFactories namespace Joints { bool IsD6SwingValid(float swingAngleY, float swingAngleZ, float swingLimitY, float swingLimitZ); void AppendD6SwingConeToLineBuffer( const AZ::Quaternion& parentLocalRotation, float swingAngleY, float swingAngleZ, float swingLimitY, float swingLimitZ, float scale, AZ::u32 angularSubdivisions, AZ::u32 radialSubdivisions, AZStd::vector<AZ::Vector3>& lineBufferOut, AZStd::vector<bool>& lineValidityBufferOut); void AppendD6TwistArcToLineBuffer( const AZ::Quaternion& parentLocalRotation, float twistAngle, float twistLimitLower, float twistLimitUpper, float scale, AZ::u32 angularSubdivisions, AZ::u32 radialSubdivisions, AZStd::vector<AZ::Vector3>& lineBufferOut, AZStd::vector<bool>& lineValidityBufferOut); void AppendD6CurrentTwistToLineBuffer( const AZ::Quaternion& parentLocalRotation, float twistAngle, float twistLimitLower, float twistLimitUpper, float scale, AZStd::vector<AZ::Vector3>& lineBufferOut, AZStd::vector<bool>& lineValidityBufferOut); } // namespace Joints } // namespace Utils } // namespace PhysX
40.63
129
0.648536
[ "vector", "transform", "3d" ]
a99f97aadec145bcf991f22df611be8a1f5d26f6
9,430
h
C
src/drivers/sensors/sensors.h
bitsoftwang/LPC11U_LPC13U_CodeBase
a0e1a75bfb9865225b0d9f66c9eb7e4945ebea9f
[ "BSD-3-Clause" ]
30
2015-01-11T04:18:50.000Z
2019-09-22T17:26:51.000Z
src/drivers/sensors/sensors.h
ADTL/LPC11U_LPC13U_CodeBase
1e366fb390f1af3e087495b88f574b69b62e86c4
[ "BSD-3-Clause" ]
null
null
null
src/drivers/sensors/sensors.h
ADTL/LPC11U_LPC13U_CodeBase
1e366fb390f1af3e087495b88f574b69b62e86c4
[ "BSD-3-Clause" ]
25
2015-01-11T04:17:41.000Z
2021-04-03T14:29:10.000Z
/**************************************************************************/ /*! @defgroup Sensors Sensors @brief Sensor API to abstract basic sensor parameters and sensor data (sensor 'events') into a common type using standardized SI units for measurements. @details Basic sensor properties are defined by \ref sensor_t, and sensor readings are defined as 'events' using \ref sensors_event_t. Some common helper functions to work with sensors and sensor events like serializing data are provided in sensors.c. */ /**************************************************************************/ /**************************************************************************/ /*! @file sensors.h @author K. Townsend (microBuilder.eu) @brief Shared types and helper functions for working with sensors @ingroup Sensors @details This module is responsible for defining a common type for sensors (\ref sensor_t) and sensor data (\ref sensors_event_t). By using a common type for any sensor or sensor event that data can easily be logged in a universal way, without having to understand the specific properties and limitations of the sensor(s) being used. All sensor event units are also standardized on specific SI units to make comparing data across different sensor models easier. @section LICENSE Software License Agreement (BSD License) Copyright (c) 2013, Kevin Townsend All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /**************************************************************************/ #ifndef _SENSORS_H_ #define _SENSORS_H_ #ifdef __cplusplus extern "C" { #endif #include "projectconfig.h" /* Intentionally modeled after sensors.h in the Android API: * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ /* Constants */ #define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ #define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ #define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ #define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) #define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */ #define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */ #define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ #define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */ #define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */ /** Sensor types */ typedef enum { SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ SENSOR_TYPE_MAGNETIC_FIELD = (2), SENSOR_TYPE_ORIENTATION = (3), SENSOR_TYPE_GYROSCOPE = (4), SENSOR_TYPE_LIGHT = (5), SENSOR_TYPE_PRESSURE = (6), SENSOR_TYPE_PROXIMITY = (8), SENSOR_TYPE_GRAVITY = (9), SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */ SENSOR_TYPE_ROTATION_VECTOR = (11), SENSOR_TYPE_RELATIVE_HUMIDITY = (12), SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), SENSOR_TYPE_VOLTAGE = (15), SENSOR_TYPE_CURRENT = (16), SENSOR_TYPE_COLOR = (17) } sensors_type_t; /** struct sensors_vec_s is used to return a vector in a common format. */ typedef struct { union { float v[3]; struct { float x; float y; float z; }; /* Orientation sensors */ struct { float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -180°<=roll<=180° */ float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */ float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */ }; }; int8_t status; uint8_t reserved[3]; } sensors_vec_t; /** Sensor axis */ typedef enum { SENSOR_AXIS_X = (1), SENSOR_AXIS_Y = (2), SENSOR_AXIS_Z = (3) } sensors_axis_t; /** struct sensors_color_s is used to return color data in a common format. */ typedef struct { union { float c[3]; /* RGB color space */ struct { float r; /**< Red component */ float g; /**< Green component */ float b; /**< Blue component */ }; }; uint32_t rgba; /**< 24-bit RGBA value */ } sensors_color_t; /* Sensor event (36 bytes) */ /** struct sensor_event_s is used to provide a single sensor event in a common format. */ typedef struct { int32_t version; /**< must be sizeof(struct sensors_event_t) */ int32_t sensor_id; /**< unique sensor identifier */ int32_t type; /**< sensor type */ int32_t reserved0; /**< reserved */ int32_t timestamp; /**< time is in milliseconds */ union { float data[4]; sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */ sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ sensors_vec_t orientation; /**< orientation values are in degrees */ sensors_vec_t gyro; /**< gyroscope values are in rad/s */ float temperature; /**< temperature is in degrees centigrade (Celsius) */ float distance; /**< distance in centimeters */ float light; /**< light in SI lux units */ float pressure; /**< pressure in hectopascal (hPa) */ float relative_humidity; /**< relative humidity in percent */ float current; /**< current in milliamps (mA) */ float voltage; /**< voltage in volts (V) */ sensors_color_t color; /**< color in RGB component values */ }; } sensors_event_t; /* Sensor details (40 bytes) */ /** struct sensor_s is used to describe basic information about a specific sensor. */ typedef struct { char name[12]; /**< sensor name */ int32_t version; /**< version of the hardware + driver */ int32_t sensor_id; /**< unique sensor identifier */ int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ float max_value; /**< maximum value of this sensor's value in SI units */ float min_value; /**< minimum value of this sensor's value in SI units */ float resolution; /**< smallest difference between two values reported by this sensor */ int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */ } sensor_t; size_t sensorsSerializeSensor(uint8_t *buffer, const sensor_t *sensor); size_t sensorsSerializeSensorsEvent(uint8_t *buffer, const sensors_event_t *event); size_t sensorsLogSensor(char *buffer, const size_t len, const sensor_t *sensor); size_t sensorsLogSensorsEvent(char *buffer, const size_t len, const sensors_event_t *event); #ifdef __cplusplus } #endif #endif
46
174
0.605514
[ "vector" ]
a9a209806774fb67c211e1c0bbcac9661302181f
16,178
h
C
source/blender/makesdna/DNA_view3d_types.h
sambler/myblender
241cc5e8469efc67320f0be942115dacca281096
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2016-10-01T22:48:11.000Z
2018-08-14T17:29:04.000Z
source/blender/makesdna/DNA_view3d_types.h
segfault87/blender
77c7440540626828b080444165a28887c255594e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/makesdna/DNA_view3d_types.h
segfault87/blender
77c7440540626828b080444165a28887c255594e
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. */ /** \file * \ingroup DNA */ #ifndef __DNA_VIEW3D_TYPES_H__ #define __DNA_VIEW3D_TYPES_H__ struct BoundBox; struct Object; struct RenderEngine; struct SmoothView3DStore; struct SpaceLink; struct ViewDepths; struct bGPdata; struct wmTimer; #include "DNA_defs.h" #include "DNA_listBase.h" #include "DNA_image_types.h" #include "DNA_object_types.h" #include "DNA_movieclip_types.h" typedef struct RegionView3D { /** GL_PROJECTION matrix. */ float winmat[4][4]; /** GL_MODELVIEW matrix. */ float viewmat[4][4]; /** Inverse of viewmat. */ float viewinv[4][4]; /** Viewmat*winmat. */ float persmat[4][4]; /** Inverse of persmat. */ float persinv[4][4]; /** Offset/scale for camera glsl texcoords. */ float viewcamtexcofac[4]; /** viewmat/persmat multiplied with object matrix, while drawing and selection. */ float viewmatob[4][4]; float persmatob[4][4]; /** User defined clipping planes. */ float clip[6][4]; /** Clip in object space, * means we can test for clipping in editmode without first going into worldspace. */ float clip_local[6][4]; struct BoundBox *clipbb; /** Allocated backup of its self while in localview. */ struct RegionView3D *localvd; struct RenderEngine *render_engine; struct ViewDepths *depths; /** Animated smooth view. */ struct SmoothView3DStore *sms; struct wmTimer *smooth_timer; /** Transform gizmo matrix. */ float twmat[4][4]; /** min/max dot product on twmat xyz axis. */ float tw_axis_min[3], tw_axis_max[3]; float tw_axis_matrix[3][3]; float gridview DNA_DEPRECATED; /** View rotation, must be kept normalized. */ float viewquat[4]; /** Distance from 'ofs' along -viewinv[2] vector, where result is negative as is 'ofs'. */ float dist; /** Camera view offsets, 1.0 = viewplane moves entire width/height. */ float camdx, camdy; /** Runtime only. */ float pixsize; /** * View center & orbit pivot, negative of worldspace location, * also matches -viewinv[3][0:3] in ortho mode. */ float ofs[3]; /** Viewport zoom on the camera frame, see BKE_screen_view3d_zoom_to_fac. */ float camzoom; /** * Check if persp/ortho view, since 'persp' cant be used for this since * it can have cameras assigned as well. (only set in #view3d_winmatrix_set) */ char is_persp; char persp; char view; char viewlock; /** Options for quadview (store while out of quad view). */ char viewlock_quad; char _pad[3]; /** Normalized offset for locked view: (-1, -1) bottom left, (1, 1) upper right. */ float ofs_lock[2]; /** XXX can easily get rid of this (Julian). */ short twdrawflag; short rflag; /** Last view (use when switching out of camera view). */ float lviewquat[4]; /** Lpersp can never be set to 'RV3D_CAMOB'. */ short lpersp, lview; /** Active rotation from NDOF or elsewhere. */ float rot_angle; float rot_axis[3]; } RegionView3D; typedef struct View3DCursor { float location[3]; float rotation_quaternion[4]; float rotation_euler[3]; float rotation_axis[3], rotation_angle; short rotation_mode; char _pad[6]; } View3DCursor; /** 3D Viewport Shading settings. */ typedef struct View3DShading { /** Shading type (OB_SOLID, ..). */ char type; /** Runtime, for toggle between rendered viewport. */ char prev_type; char prev_type_wire; char color_type; short flag; char light; char background_type; char cavity_type; char wire_color_type; char _pad[2]; /** FILE_MAXFILE. */ char studio_light[256]; /** FILE_MAXFILE. */ char lookdev_light[256]; /** FILE_MAXFILE. */ char matcap[256]; float shadow_intensity; float single_color[3]; float studiolight_rot_z; float studiolight_background; float studiolight_intensity; float object_outline_color[3]; float xray_alpha; float xray_alpha_wire; float cavity_valley_factor; float cavity_ridge_factor; float background_color[3]; float curvature_ridge_factor; float curvature_valley_factor; /* Render pass displayed in the viewport. Is an `eScenePassType` where one bit is set */ int render_pass; char _pad2[4]; struct IDProperty *prop; } View3DShading; /** 3D Viewport Overlay settings. */ typedef struct View3DOverlay { int flag; /** Edit mode settings. */ int edit_flag; float normals_length; float backwire_opacity; /** Paint mode settings. */ int paint_flag; /** Weight paint mode settings. */ int wpaint_flag; /** Alpha for texture, weight, vertex paint overlay. */ float texture_paint_mode_opacity; float vertex_paint_mode_opacity; float weight_paint_mode_opacity; float sculpt_mode_mask_opacity; /** Armature edit/pose mode settings. */ int _pad3; float xray_alpha_bone; /** Other settings. */ float wireframe_threshold; /** Grease pencil settings. */ float gpencil_paper_opacity; float gpencil_grid_opacity; float gpencil_fade_layer; } View3DOverlay; typedef struct View3D_Runtime { /** Nkey panel stores stuff here. */ void *properties_storage; } View3D_Runtime; /** 3D ViewPort Struct. */ typedef struct View3D { struct SpaceLink *next, *prev; /** Storage of regions for inactive spaces. */ ListBase regionbase; char spacetype; char link_flag; char _pad0[6]; /* End 'SpaceLink' header. */ float viewquat[4] DNA_DEPRECATED; float dist DNA_DEPRECATED; /** Size of bundles in reconstructed data. */ float bundle_size; /** Display style for bundle. */ char bundle_drawtype; char drawtype DNA_DEPRECATED; char _pad3[1]; /** Multiview current eye - for internal use. */ char multiview_eye; int object_type_exclude_viewport; int object_type_exclude_select; short persp DNA_DEPRECATED; short view DNA_DEPRECATED; struct Object *camera, *ob_centre; rctf render_border; /** Allocated backup of its self while in localview. */ struct View3D *localvd; /** Optional string for armature bone to define center, MAXBONENAME. */ char ob_centre_bone[64]; unsigned short local_view_uuid; char _pad6[2]; int layact DNA_DEPRECATED; unsigned short local_collections_uuid; short _pad7[3]; /** Optional bool for 3d cursor to define center. */ short ob_centre_cursor; short scenelock; short gp_flag; short flag; int flag2; float lens, grid; float clip_start, clip_end; float ofs[3] DNA_DEPRECATED; char _pad[1]; /** Transform gizmo info. */ /** #V3D_GIZMO_SHOW_* */ char gizmo_flag; char gizmo_show_object; char gizmo_show_armature; char gizmo_show_empty; char gizmo_show_light; char gizmo_show_camera; char gridflag; short gridlines; /** Number of subdivisions in the grid between each highlighted grid line. */ short gridsubdiv; /** Actually only used to define the opacity of the grease pencil vertex in edit mode. */ float vertex_opacity; /* XXX deprecated? */ /** Grease-Pencil Data (annotation layers). */ struct bGPdata *gpd DNA_DEPRECATED; /** Stereoscopy settings. */ short stereo3d_flag; char stereo3d_camera; char _pad4; float stereo3d_convergence_factor; float stereo3d_volume_alpha; float stereo3d_convergence_alpha; /** Display settings. */ View3DShading shading; View3DOverlay overlay; /** Runtime evaluation data (keep last). */ View3D_Runtime runtime; } View3D; /** #View3D.stereo3d_flag */ #define V3D_S3D_DISPCAMERAS (1 << 0) #define V3D_S3D_DISPPLANE (1 << 1) #define V3D_S3D_DISPVOLUME (1 << 2) /** #View3D.flag */ #define V3D_LOCAL_COLLECTIONS (1 << 0) #define V3D_FLAG_UNUSED_1 (1 << 1) /* cleared */ #define V3D_HIDE_HELPLINES (1 << 2) #define V3D_INVALID_BACKBUF (1 << 3) #define V3D_FLAG_UNUSED_10 (1 << 10) /* cleared */ #define V3D_SELECT_OUTLINE (1 << 11) #define V3D_FLAG_UNUSED_12 (1 << 12) /* cleared */ #define V3D_GLOBAL_STATS (1 << 13) #define V3D_DRAW_CENTERS (1 << 15) /** #RegionView3D.persp */ #define RV3D_ORTHO 0 #define RV3D_PERSP 1 #define RV3D_CAMOB 2 /** #RegionView3D.rflag */ #define RV3D_CLIPPING (1 << 2) #define RV3D_NAVIGATING (1 << 3) #define RV3D_GPULIGHT_UPDATE (1 << 4) #define RV3D_PAINTING (1 << 5) /*#define RV3D_IS_GAME_ENGINE (1 << 5) */ /* UNUSED */ /** * Disable zbuffer offset, skip calls to #ED_view3d_polygon_offset. * Use when precise surface depth is needed and picking bias isn't, see T45434). */ #define RV3D_ZOFFSET_DISABLED 64 /** #RegionView3D.viewlock */ #define RV3D_LOCKED (1 << 0) #define RV3D_BOXVIEW (1 << 1) #define RV3D_BOXCLIP (1 << 2) /** #RegionView3D.viewlock_quad */ #define RV3D_VIEWLOCK_INIT (1 << 7) /** #RegionView3D.view */ #define RV3D_VIEW_USER 0 #define RV3D_VIEW_FRONT 1 #define RV3D_VIEW_BACK 2 #define RV3D_VIEW_LEFT 3 #define RV3D_VIEW_RIGHT 4 #define RV3D_VIEW_TOP 5 #define RV3D_VIEW_BOTTOM 6 #define RV3D_VIEW_CAMERA 8 #define RV3D_VIEW_IS_AXIS(view) (((view) >= RV3D_VIEW_FRONT) && ((view) <= RV3D_VIEW_BOTTOM)) /** #View3D.flag2 (int) */ #define V3D_HIDE_OVERLAYS (1 << 2) #define V3D_FLAG2_UNUSED_3 (1 << 3) /* cleared */ #define V3D_SHOW_ANNOTATION (1 << 4) #define V3D_LOCK_CAMERA (1 << 5) #define V3D_FLAG2_UNUSED_6 (1 << 6) /* cleared */ #define V3D_SHOW_RECONSTRUCTION (1 << 7) #define V3D_SHOW_CAMERAPATH (1 << 8) #define V3D_SHOW_BUNDLENAME (1 << 9) #define V3D_FLAG2_UNUSED_10 (1 << 10) /* cleared */ #define V3D_RENDER_BORDER (1 << 11) #define V3D_FLAG2_UNUSED_12 (1 << 12) /* cleared */ #define V3D_FLAG2_UNUSED_13 (1 << 13) /* cleared */ #define V3D_FLAG2_UNUSED_14 (1 << 14) /* cleared */ #define V3D_FLAG2_UNUSED_15 (1 << 15) /* cleared */ /** #View3D.gp_flag (short) */ #define V3D_GP_SHOW_PAPER (1 << 0) /* Activate paper to cover all viewport */ #define V3D_GP_SHOW_GRID (1 << 1) /* Activate paper grid */ #define V3D_GP_SHOW_EDIT_LINES (1 << 2) #define V3D_GP_SHOW_MULTIEDIT_LINES (1 << 3) #define V3D_GP_SHOW_ONION_SKIN (1 << 4) /* main switch at view level */ #define V3D_GP_FADE_NOACTIVE_LAYERS (1 << 5) /* fade layers not active */ #define V3D_GP_FADE_NOACTIVE_GPENCIL (1 << 6) /* Fade other GPencil objects */ /** #View3DShading.light */ enum { V3D_LIGHTING_FLAT = 0, V3D_LIGHTING_STUDIO = 1, V3D_LIGHTING_MATCAP = 2, }; /** #View3DShading.flag */ enum { V3D_SHADING_OBJECT_OUTLINE = (1 << 0), V3D_SHADING_XRAY = (1 << 1), V3D_SHADING_SHADOW = (1 << 2), V3D_SHADING_SCENE_LIGHTS = (1 << 3), V3D_SHADING_SPECULAR_HIGHLIGHT = (1 << 4), V3D_SHADING_CAVITY = (1 << 5), V3D_SHADING_MATCAP_FLIP_X = (1 << 6), V3D_SHADING_SCENE_WORLD = (1 << 7), V3D_SHADING_XRAY_WIREFRAME = (1 << 8), V3D_SHADING_WORLD_ORIENTATION = (1 << 9), V3D_SHADING_BACKFACE_CULLING = (1 << 10), V3D_SHADING_DEPTH_OF_FIELD = (1 << 11), V3D_SHADING_SCENE_LIGHTS_RENDER = (1 << 12), V3D_SHADING_SCENE_WORLD_RENDER = (1 << 13), }; /** #View3DShading.color_type */ enum { V3D_SHADING_MATERIAL_COLOR = 0, V3D_SHADING_RANDOM_COLOR = 1, V3D_SHADING_SINGLE_COLOR = 2, V3D_SHADING_TEXTURE_COLOR = 3, V3D_SHADING_OBJECT_COLOR = 4, V3D_SHADING_VERTEX_COLOR = 5, /* Is used to display the object using the error color. For example when in * solid texture paint mode without any textures configured */ V3D_SHADING_ERROR_COLOR = 999, }; /** #View3DShading.background_type */ enum { V3D_SHADING_BACKGROUND_THEME = 0, V3D_SHADING_BACKGROUND_WORLD = 1, V3D_SHADING_BACKGROUND_VIEWPORT = 2, }; /** #View3DShading.cavity_type */ enum { V3D_SHADING_CAVITY_SSAO = 0, V3D_SHADING_CAVITY_CURVATURE = 1, V3D_SHADING_CAVITY_BOTH = 2, }; /** #View3DOverlay.flag */ enum { V3D_OVERLAY_FACE_ORIENTATION = (1 << 0), V3D_OVERLAY_HIDE_CURSOR = (1 << 1), V3D_OVERLAY_BONE_SELECT = (1 << 2), V3D_OVERLAY_LOOK_DEV = (1 << 3), V3D_OVERLAY_WIREFRAMES = (1 << 4), V3D_OVERLAY_HIDE_TEXT = (1 << 5), V3D_OVERLAY_HIDE_MOTION_PATHS = (1 << 6), V3D_OVERLAY_ONION_SKINS = (1 << 7), V3D_OVERLAY_HIDE_BONES = (1 << 8), V3D_OVERLAY_HIDE_OBJECT_XTRAS = (1 << 9), V3D_OVERLAY_HIDE_OBJECT_ORIGINS = (1 << 10), }; /** #View3DOverlay.edit_flag */ enum { V3D_OVERLAY_EDIT_VERT_NORMALS = (1 << 0), V3D_OVERLAY_EDIT_LOOP_NORMALS = (1 << 1), V3D_OVERLAY_EDIT_FACE_NORMALS = (1 << 2), V3D_OVERLAY_EDIT_OCCLUDE_WIRE = (1 << 3), V3D_OVERLAY_EDIT_WEIGHT = (1 << 4), V3D_OVERLAY_EDIT_EDGES = (1 << 5), V3D_OVERLAY_EDIT_FACES = (1 << 6), V3D_OVERLAY_EDIT_FACE_DOT = (1 << 7), V3D_OVERLAY_EDIT_SEAMS = (1 << 8), V3D_OVERLAY_EDIT_SHARP = (1 << 9), V3D_OVERLAY_EDIT_CREASES = (1 << 10), V3D_OVERLAY_EDIT_BWEIGHTS = (1 << 11), V3D_OVERLAY_EDIT_FREESTYLE_EDGE = (1 << 12), V3D_OVERLAY_EDIT_FREESTYLE_FACE = (1 << 13), V3D_OVERLAY_EDIT_STATVIS = (1 << 14), V3D_OVERLAY_EDIT_EDGE_LEN = (1 << 15), V3D_OVERLAY_EDIT_EDGE_ANG = (1 << 16), V3D_OVERLAY_EDIT_FACE_ANG = (1 << 17), V3D_OVERLAY_EDIT_FACE_AREA = (1 << 18), V3D_OVERLAY_EDIT_INDICES = (1 << 19), V3D_OVERLAY_EDIT_CU_HANDLES = (1 << 20), V3D_OVERLAY_EDIT_CU_NORMALS = (1 << 21), }; /** #View3DOverlay.paint_flag */ enum { V3D_OVERLAY_PAINT_WIRE = (1 << 0), }; /** #View3DOverlay.wpaint_flag */ enum { V3D_OVERLAY_WPAINT_CONTOURS = (1 << 0), }; /** #View3D.around */ enum { /* center of the bounding box */ V3D_AROUND_CENTER_BOUNDS = 0, /* center from the sum of all points divided by the total */ V3D_AROUND_CENTER_MEDIAN = 3, /* pivot around the 2D/3D cursor */ V3D_AROUND_CURSOR = 1, /* pivot around each items own origin */ V3D_AROUND_LOCAL_ORIGINS = 2, /* pivot around the active items origin */ V3D_AROUND_ACTIVE = 4, }; /** #View3d.gridflag */ #define V3D_SHOW_FLOOR (1 << 0) #define V3D_SHOW_X (1 << 1) #define V3D_SHOW_Y (1 << 2) #define V3D_SHOW_Z (1 << 3) #define V3D_SHOW_ORTHO_GRID (1 << 4) /** #TransformOrientationSlot.type */ enum { V3D_ORIENT_GLOBAL = 0, V3D_ORIENT_LOCAL = 1, V3D_ORIENT_NORMAL = 2, V3D_ORIENT_VIEW = 3, V3D_ORIENT_GIMBAL = 4, V3D_ORIENT_CURSOR = 5, V3D_ORIENT_CUSTOM = 1024, /** Runtime only, never saved to DNA. */ V3D_ORIENT_CUSTOM_MATRIX = (V3D_ORIENT_CUSTOM - 1), }; /** #View3d.gizmo_flag */ enum { /** All gizmos. */ V3D_GIZMO_HIDE = (1 << 0), V3D_GIZMO_HIDE_NAVIGATE = (1 << 1), V3D_GIZMO_HIDE_CONTEXT = (1 << 2), V3D_GIZMO_HIDE_TOOL = (1 << 3), }; /** #View3d.gizmo_show_object */ enum { V3D_GIZMO_SHOW_OBJECT_TRANSLATE = (1 << 0), V3D_GIZMO_SHOW_OBJECT_ROTATE = (1 << 1), V3D_GIZMO_SHOW_OBJECT_SCALE = (1 << 2), }; /** #View3d.gizmo_show_armature */ enum { /** Currently unused (WIP gizmo). */ V3D_GIZMO_SHOW_ARMATURE_BBONE = (1 << 0), /** Not yet implemented. */ V3D_GIZMO_SHOW_ARMATURE_ROLL = (1 << 1), }; /** #View3d.gizmo_show_empty */ enum { V3D_GIZMO_SHOW_EMPTY_IMAGE = (1 << 0), V3D_GIZMO_SHOW_EMPTY_FORCE_FIELD = (1 << 1), }; /** #View3d.gizmo_show_light */ enum { /** Use for both spot & area size. */ V3D_GIZMO_SHOW_LIGHT_SIZE = (1 << 0), V3D_GIZMO_SHOW_LIGHT_LOOK_AT = (1 << 1), }; /** #View3d.gizmo_show_camera */ enum { /** Also used for ortho size. */ V3D_GIZMO_SHOW_CAMERA_LENS = (1 << 0), V3D_GIZMO_SHOW_CAMERA_DOF_DIST = (1 << 2), }; /** Settings for offscreen rendering */ enum { V3D_OFSDRAW_NONE = (0), V3D_OFSDRAW_SHOW_ANNOTATION = (1 << 0), V3D_OFSDRAW_OVERRIDE_SCENE_SETTINGS = (1 << 1), }; #define RV3D_CAMZOOM_MIN -30 #define RV3D_CAMZOOM_MAX 600 /** #BKE_screen_view3d_zoom_to_fac() values above */ #define RV3D_CAMZOOM_MIN_FACTOR 0.1657359312880714853f #define RV3D_CAMZOOM_MAX_FACTOR 44.9852813742385702928f #endif
26.740496
93
0.702126
[ "render", "object", "vector", "transform", "3d", "solid" ]
a9a53f5094a25c1856bd2b8ee66d2047aaa14626
108,184
h
C
lib/ccv.h
OSSDC/ccv
a3ad07adf4d9dae969e10a991d975ffd1ae3b16b
[ "CC-BY-4.0", "CC0-1.0" ]
null
null
null
lib/ccv.h
OSSDC/ccv
a3ad07adf4d9dae969e10a991d975ffd1ae3b16b
[ "CC-BY-4.0", "CC0-1.0" ]
null
null
null
lib/ccv.h
OSSDC/ccv
a3ad07adf4d9dae969e10a991d975ffd1ae3b16b
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-05-12T11:29:49.000Z
2021-05-12T11:29:49.000Z
/********************************************************** * C-based/Cached/Core Computer Vision Library * Liu Liu, 2010-02-01 **********************************************************/ #ifndef GUARD_ccv_h #define GUARD_ccv_h #define _WITH_GETLINE #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <float.h> #include <math.h> #include <assert.h> #if !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__NetBSD__) #include <alloca.h> #endif #define CCV_PI (3.141592653589793) #define ccmalloc malloc #define cccalloc calloc #define ccrealloc realloc #define ccfree free #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #include <sys/param.h> #if defined(__APPLE__) || defined(BSD) || _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 #define ccmemalign posix_memalign #else #define ccmemalign(memptr, alignment, size) (*memptr = memalign(alignment, size)) #endif #else #define ccmemalign(memptr, alignment, size) (*memptr = ccmalloc(size)) #endif // Include toll-free bridging for ccv_nnc_tensor_t #define CCV_NNC_TENSOR_TFB (1) #include "nnc/ccv_nnc_tfb.h" /* Doxygen will ignore these, otherwise it has problem to process warn_unused_result directly. */ #define CCV_WARN_UNUSED(x) x __attribute__((warn_unused_result)) enum { CCV_8U = 0x01000, CCV_32S = 0x02000, CCV_32F = 0x04000, CCV_64S = 0x08000, CCV_64F = 0x10000, CCV_16F = 0x20000, // We can still squeeze in 2 more types. (0xFF000 are for data types). }; enum { CCV_C1 = 0x001, CCV_C2 = 0x002, CCV_C3 = 0x003, CCV_C4 = 0x004, }; static const int _ccv_get_data_type_size[] = { -1, 1, 4, -1, 4, -1, -1, -1, 8, -1, -1, -1, -1, -1, -1, -1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2 }; #define CCV_GET_DATA_TYPE(x) ((x) & 0xFF000) #define CCV_GET_DATA_TYPE_SIZE(x) _ccv_get_data_type_size[CCV_GET_DATA_TYPE(x) >> 12] #define CCV_MAX_CHANNEL (0xFFF) #define CCV_GET_CHANNEL(x) ((x) & 0xFFF) #define CCV_GET_STEP(cols, type) (((cols) * CCV_GET_DATA_TYPE_SIZE(type) * CCV_GET_CHANNEL(type) + 3) & -4) #define CCV_ALL_DATA_TYPE (CCV_8U | CCV_32S | CCV_32F | CCV_64S | CCV_64F) enum { CCV_MATRIX_DENSE = 0x00100000, CCV_MATRIX_SPARSE = 0x00200000, CCV_MATRIX_CSR = 0x00400000, CCV_MATRIX_CSC = 0x00800000, }; enum { CCV_GARBAGE = 0x80000000, // matrix is in cache (not used by any functions) CCV_REUSABLE = 0x40000000, // matrix can be recycled CCV_UNMANAGED = 0x20000000, // matrix is allocated by user, therefore, cannot be freed by ccv_matrix_free/ccv_matrix_free_immediately CCV_NO_DATA_ALLOC = 0x10000000, // matrix is allocated as header only, but with no data section, therefore, you have to free the data section separately CCV_TAPE_ALLOC = 0x08000000, // matrix is allocated on a tape. CCV_PINNED_MEM = 0x04000000, // matrix is pinned in CUDA. }; #define CCV_GET_TAPE_ALLOC(type) ((type) & CCV_TAPE_ALLOC) enum { CCV_DENSE_VECTOR = 0x02000000, CCV_SPARSE_VECTOR = 0x01000000, }; typedef struct { uint8_t ifbit; uint32_t i; } ccv_sparse_matrix_index_t; typedef struct { int step; int prime_index; uint32_t size; uint32_t rnum; union { ccv_sparse_matrix_index_t* index; ccv_numeric_data_t data; }; } ccv_sparse_matrix_vector_t; enum { CCV_SPARSE_ROW_MAJOR = 0x00, CCV_SPARSE_COL_MAJOR = 0x01, }; typedef struct { int type; int refcount; uint64_t sig; int rows; int cols; int major; int prime_index; uint32_t size; uint32_t rnum; union { unsigned char u8; int i32; float f32; int64_t i64; double f64; void* p; } tb; ccv_sparse_matrix_index_t* index; ccv_sparse_matrix_vector_t* vector; } ccv_sparse_matrix_t; typedef void ccv_matrix_t; /** * @defgroup ccv_cache cache mechanism * This class implements a trie-based LRU cache that is then used for ccv application-wide cache in [ccv_memory.c](/lib/ccv-memory). * @{ */ typedef void(*ccv_cache_index_free_f)(void*); typedef union { struct { uint64_t bitmap; uint64_t set; uint64_t age; } branch; struct { uint64_t sign; uint64_t off; uint64_t type; } terminal; } ccv_cache_index_t; typedef struct { ccv_cache_index_t origin; uint32_t rnum; uint32_t age; size_t up; size_t size; ccv_cache_index_free_f ffree[16]; } ccv_cache_t; /* I made it as generic as possible */ /** * Setup a cache strcture to work with. * @param cache The allocated cache. * @param up The upper limit of cache size in bytes. * @param cache_types The number of cache types in this one cache instance. * @param ffree The function that will be used to free cached object. */ void ccv_cache_init(ccv_cache_t* cache, size_t up, int cache_types, ccv_cache_index_free_f ffree, ...); /** * Get an object from cache for its signature. 0 if cannot find the object. * @param cache The cache. * @param sign The signature. * @param type The type of the object. * @return The pointer to the object. */ void* ccv_cache_get(ccv_cache_t* cache, uint64_t sign, uint8_t* type); /** * Put an object to cache with its signature, size, and type * @param cache The cache. * @param sign The signature. * @param x The pointer to the object. * @param size The size of the object. * @param type The type of the object. * @return 0 - success, 1 - replace, -1 - failure. */ int ccv_cache_put(ccv_cache_t* cache, uint64_t sign, void* x, uint32_t size, uint8_t type); /** * Get an object from cache for its signature and then remove that object from the cache. 0 if cannot find the object. * @param cache The cache. * @param sign The signature. * @param type The type of the object. * @return The pointer to the object. */ void* ccv_cache_out(ccv_cache_t* cache, uint64_t sign, uint8_t* type); /** * Delete an object from cache for its signature and free it. * @param cache The cache. * @param sign The signature. * @return -1 if cannot find the object, otherwise return 0. */ int ccv_cache_delete(ccv_cache_t* cache, uint64_t sign); /** * Clean up the cache, free all objects inside and other memory space occupied. * @param cache The cache. */ void ccv_cache_cleanup(ccv_cache_t* cache); /** * For current implementation (trie-based LRU cache), it is an alias for ccv_cache_cleanup. * @param cache The cache. */ void ccv_cache_close(ccv_cache_t* cache); /** @} */ /* deprecated methods, often these implemented in another way and no longer suitable for newer computer architecture */ /* 0 */ typedef struct { int type; int refcount; uint64_t sig; int rows; int cols; int nnz; union { unsigned char u8; int i32; float f32; int64_t i64; double f64; void* p; } tb; int* index; int* offset; ccv_numeric_data_t data; } ccv_compressed_sparse_matrix_t; #define ccv_clamp(x, a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); typeof (x) _x = (x); (_x < _a) ? _a : ((_x > _b) ? _b : _x); }) #define ccv_min(a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); (_a < _b) ? _a : _b; }) #define ccv_max(a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); (_a > _b) ? _a : _b; }) /** * @defgroup ccv_memory memory alloc/dealloc * @{ */ #define ccv_compute_dense_matrix_size(rows, cols, type) (((sizeof(ccv_dense_matrix_t) + 15) & -16) + (((cols) * CCV_GET_DATA_TYPE_SIZE(type) * CCV_GET_CHANNEL(type) + 3) & -4) * (rows)) /** * Check the input matrix, if it is the allowed type, return it, otherwise create one with prefer_type. * @param x The matrix to check. * @param rows Rows of the matrix. * @param cols Columns of the matrix. * @param types Allowed types, it can be a mask of multiple types, e.g. CCV_8U | CCV_32S allows both 8-bit unsigned integer type and 32-bit signed integer type. * @param prefer_type The default type, it can be only one type. * @param sig The signature, using 0 if you don't know what it is. * @return The returned matrix object that satisfies the requirements. */ CCV_WARN_UNUSED(ccv_dense_matrix_t*) ccv_dense_matrix_renew(ccv_dense_matrix_t* x, int rows, int cols, int types, int prefer_type, uint64_t sig); /** * Create a dense matrix with rows, cols, and type. * @param rows Rows of the matrix. * @param cols Columns of the matrix. * @param type Matrix supports 4 data types - CCV_8U, CCV_32S, CCV_64S, CCV_32F, CCV_64F and up to 255 channels. e.g. CCV_32F | 31 will create a matrix with float (32-bit float point) data type with 31 channels (the default type for ccv_hog). * @param data If 0, ccv will create the matrix by allocating memory itself. Otherwise, it will use the memory region referenced by 'data'. * @param sig The signature, using 0 if you don't know what it is. * @return The newly created matrix object. */ CCV_WARN_UNUSED(ccv_dense_matrix_t*) ccv_dense_matrix_new(int rows, int cols, int type, void* data, uint64_t sig); /** * This method will return a dense matrix allocated on stack, with a data pointer to a custom memory region. * @param rows Rows of the matrix. * @param cols Columns of the matrix. * @param type The type of matrix. * @param data The data pointer that stores the actual matrix, it cannot be 0. * @param sig The signature, using 0 if you don't know what it is. * @return static matrix structs. */ ccv_dense_matrix_t ccv_dense_matrix(int rows, int cols, int type, void* data, uint64_t sig); /** * Mark the current matrix as mutable. Under the hood, it will set matrix signature to 0, and mark the matrix as non-collectable. * @param mat The supplied matrix that will be marked as mutable. */ void ccv_make_matrix_mutable(ccv_matrix_t* mat); /** * Mark the current matrix as immutable. Under the hood, it will generate a signature for the matrix, and mark it as non-collectable. For the convention, if the matrix is marked as immutable, you shouldn't change the content of the matrix, otherwise it will cause surprising behavior. If you want to change the content of the matrix, mark it as mutable first. * @param mat The supplied matrix that will be marked as immutable. **/ void ccv_make_matrix_immutable(ccv_matrix_t* mat); /** * Create a sparse matrix. ccv uses a double hash table for memory-efficient and quick-access sparse matrix. * @param rows Rows of the matrix. * @param cols Columns of the matrix. * @param type The type of the matrix, the same as dense matrix. * @param major Either CCV_SPARSE_ROW_MAJOR or CCV_SPARSE_COL_MAJOR, it determines the underlying data structure of the sparse matrix (either using row or column as the first-level hash table). * @param sig The signature, using 0 if you don't know what it is. * @return The newly created sparse matrix object. */ CCV_WARN_UNUSED(ccv_sparse_matrix_t*) ccv_sparse_matrix_new(int rows, int cols, int type, int major, uint64_t sig); /** * Skip garbage-collecting process and free the matrix immediately. * @param mat The matrix. */ void ccv_matrix_free_immediately(ccv_matrix_t* mat); /** * In principal, you should always use this method to free a matrix. If you enabled cache in ccv, this method won't immediately free up memory space of the matrix. Instead, it will push the matrix to a cache if applicable so that if you want to create the same matrix again, ccv can shortcut the required matrix/image processing and return it from the cache. * @param mat The matrix. */ void ccv_matrix_free(ccv_matrix_t* mat); #define CCV_SPARSE_FOREACH_X(mat, block, for_block) \ do { \ uint32_t _i_, _j_; \ const uint32_t _size_ = (mat)->size; \ __attribute__((unused)) const size_t _c_ = CCV_GET_CHANNEL((mat)->type); \ if ((mat)->type & CCV_DENSE_VECTOR) \ { \ for (_i_ = 0; _i_ < _size_; _i_++) \ { \ ccv_sparse_matrix_index_t* const _idx_ = (mat)->index + _i_; \ ccv_sparse_matrix_vector_t* const _v_ = (mat)->vector + _i_; \ if (_idx_->ifbit <= 1 || !_v_->size) \ continue; \ for (_j_ = 0; _j_ < _v_->size; _j_++) \ { \ block(_idx_->i, _j_, _j_ * _c_, _v_->data, for_block); \ } \ } \ } else { \ const size_t _idx_size_ = sizeof(ccv_sparse_matrix_index_t) + ((CCV_GET_DATA_TYPE_SIZE((mat)->type) * CCV_GET_CHANNEL((mat)->type) + 3) & -4); \ for (_i_ = 0; _i_ < _size_; _i_++) \ { \ ccv_sparse_matrix_index_t* const _idx_ = (mat)->index + _i_; \ ccv_sparse_matrix_vector_t* const _v_ = (mat)->vector + _i_; \ if (_idx_->ifbit <= 1 || !_v_->rnum) \ continue; \ uint8_t* const _vidx_ = (uint8_t*)_v_->index; \ for (_j_ = 0; _j_ < _v_->size; _j_++) \ { \ ccv_sparse_matrix_index_t* const _idx_j_ = (ccv_sparse_matrix_index_t*)(_vidx_ + _idx_size_ * _j_); \ if (_idx_j_->ifbit <= 1) \ continue; \ ccv_numeric_data_t _d_ = { .u8 = (uint8_t*)(_idx_j_ + 1) }; \ block(_idx_->i, _idx_j_->i, 0, _d_, for_block); \ } \ } \ } \ } while (0) #define _ccv_sparse_get_32s_vector_rmj(_i_, _j_, _k_, _v_, block) block((_i_), (_j_), (_v_.i32 + (_k_))) #define _ccv_sparse_get_32f_vector_rmj(_i_, _j_, _k_, _v_, block) block((_i_), (_j_), (_v_.f32 + (_k_))) #define _ccv_sparse_get_64s_vector_rmj(_i_, _j_, _k_, _v_, block) block((_i_), (_j_), (_v_.i64 + (_k_))) #define _ccv_sparse_get_64f_vector_rmj(_i_, _j_, _k_, _v_, block) block((_i_), (_j_), (_v_.f64 + (_k_))) #define _ccv_sparse_get_8u_vector_rmj(_i_, _j_, _k_, _v_, block) block((_i_), (_j_), (_v_.u8 + (_k_))) #define _ccv_sparse_get_32s_vector_cmj(_i_, _j_, _k_, _v_, block) block((_j_), (_i_), (_v_.i32 + (_k_))) #define _ccv_sparse_get_32f_vector_cmj(_i_, _j_, _k_, _v_, block) block((_j_), (_i_), (_v_.f32 + (_k_))) #define _ccv_sparse_get_64s_vector_cmj(_i_, _j_, _k_, _v_, block) block((_j_), (_i_), (_v_.i64 + (_k_))) #define _ccv_sparse_get_64f_vector_cmj(_i_, _j_, _k_, _v_, block) block((_j_), (_i_), (_v_.f64 + (_k_))) #define _ccv_sparse_get_8u_vector_cmj(_i_, _j_, _k_, _v_, block) block((_j_), (_i_), (_v_.u8 + (_k_))) /** * This method enables you to loop over non-zero (or assigned) positions in a sparse matrix. * @param mat The sparse matrix. * @param block(row, col, value) a macro to loop over, row, col is the position (depends on if it is row major or col major), value is the typed array. */ #define CCV_SPARSE_FOREACH(mat, block) \ do { if ((mat)->major & CCV_SPARSE_COL_MAJOR) { switch (CCV_GET_DATA_TYPE((mat)->type)) { \ case CCV_32S: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_32s_vector_cmj, block); break; } \ case CCV_32F: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_32f_vector_cmj, block); break; } \ case CCV_64S: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_64s_vector_cmj, block); break; } \ case CCV_64F: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_64f_vector_cmj, block); break; } \ default: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_8u_vector_cmj, block); } } \ } else { switch (CCV_GET_DATA_TYPE((mat)->type)) { \ case CCV_32S: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_32s_vector_rmj, block); break; } \ case CCV_32F: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_32f_vector_rmj, block); break; } \ case CCV_64S: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_64s_vector_rmj, block); break; } \ case CCV_64F: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_64f_vector_rmj, block); break; } \ default: { CCV_SPARSE_FOREACH_X(mat, _ccv_sparse_get_8u_vector_rmj, block); } } } \ } while (0) #define CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, block, for_block) \ do { \ int _i_; \ __attribute__((unused)) const size_t _c_ = CCV_GET_CHANNEL((mat)->type); \ if ((mat)->type & CCV_DENSE_VECTOR) \ { \ for (_i_ = 0; _i_ < (vector)->size; _i_++) \ { \ block(_i_, _i_ * _c_, (vector)->data, for_block); \ } \ } else { \ const size_t _idx_size_ = sizeof(ccv_sparse_matrix_index_t) + ((CCV_GET_DATA_TYPE_SIZE((mat)->type) * CCV_GET_CHANNEL((mat)->type) + 3) & -4); \ uint8_t* const _vidx_ = (uint8_t*)(vector)->index; \ for (_i_ = 0; _i_ < (vector)->size; _i_++) \ { \ ccv_sparse_matrix_index_t* const _idx_i_ = (ccv_sparse_matrix_index_t*)(_vidx_ + _idx_size_ * _i_); \ if (_idx_i_->ifbit <= 1) \ continue; \ ccv_numeric_data_t _d_ = { .u8 = (uint8_t*)(_idx_i_ + 1) }; \ block(_idx_i_->i, 0, _d_, for_block); \ } \ } \ } while (0) #define _ccv_sparse_get_32s_cell(_i_, _k_, _d_, block) block((_i_), (_d_.i32 + (_k_))) #define _ccv_sparse_get_32f_cell(_i_, _k_, _d_, block) block((_i_), (_d_.f32 + (_k_))) #define _ccv_sparse_get_64s_cell(_i_, _k_, _d_, block) block((_i_), (_d_.i64 + (_k_))) #define _ccv_sparse_get_64f_cell(_i_, _k_, _d_, block) block((_i_), (_d_.f64 + (_k_))) #define _ccv_sparse_get_8u_cell(_i_, _k_, _d_, block) block((_i_), (_d_.u8 + (_k_))) /** * This method enables you to loop over non-zero (or assigned) positions in one vector of a sparse matrix (you can use ccv_get_sparse_matrix_vector method) * @param mat The sparse matrix. * @param vector The vector within the sparse matrix. * @param block(index, value) a macro to loop over, index is the position (depends on if it is row major or col major), value is the typed array. */ #define CCV_SPARSE_VECTOR_FOREACH(mat, vector, block) \ do { switch (CCV_GET_DATA_TYPE((mat)->type)) { \ case CCV_32S: { CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, _ccv_sparse_get_32s_cell, block); break; } \ case CCV_32F: { CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, _ccv_sparse_get_32f_cell, block); break; } \ case CCV_64S: { CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, _ccv_sparse_get_64s_cell, block); break; } \ case CCV_64F: { CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, _ccv_sparse_get_64f_cell, block); break; } \ default: { CCV_SPARSE_VECTOR_FOREACH_X(mat, vector, _ccv_sparse_get_8u_cell, block); } } \ } while (0) /** * Generate a matrix signature based on input message and other signatures. This is the core method for ccv cache. In short, ccv does a given image processing by first generating an appropriate signature for that operation. It requires 1). an operation-specific message, which can be generated by concatenate the operation name and parameters. 2). the signature of input matrix(es). After that, ccv will look-up matrix in cache with the newly generated signature. If it exists, ccv will return that matrix and skip the whole operation. * @param msg The concatenated message. * @param len Message length. * @param sig_start The input matrix(es) signature, end the list with 0. * @return The generated 64-bit signature. */ uint64_t ccv_cache_generate_signature(const char* msg, int len, uint64_t sig_start, ...); #define CCV_DEFAULT_CACHE_SIZE (1024 * 1024 * 64) /** * Drain up the cache. */ void ccv_drain_cache(void); /** * Drain up and disable the application-wide cache. */ void ccv_disable_cache(void); /** * Enable a application-wide cache for ccv at default memory bound (64MiB). */ void ccv_enable_default_cache(void); /** * Enable a application-wide cache for ccv. The cache is bounded by given memory size. * @param size The upper limit of the cache, in bytes. */ void ccv_enable_cache(size_t size); #define ccv_get_dense_matrix_cell_by(type, x, row, col, ch) \ (((type) & CCV_32S) ? (void*)((x)->data.i32 + ((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)) : \ (((type) & CCV_32F) ? (void*)((x)->data.f32+ ((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)) : \ (((type) & CCV_64S) ? (void*)((x)->data.i64+ ((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)) : \ (((type) & CCV_64F) ? (void*)((x)->data.f64 + ((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)) : \ (void*)((x)->data.u8 + (row) * (x)->step + (col) * CCV_GET_CHANNEL(type) + (ch)))))) #define ccv_get_dense_matrix_cell(x, row, col, ch) ccv_get_dense_matrix_cell_by((x)->type, x, row, col, ch) /* this is for simplicity in code, I am sick of x->data.f64[i * x->cols + j] stuff, this is clearer, and compiler * can optimize away the if structures */ #define ccv_get_dense_matrix_cell_value_by(type, x, row, col, ch) \ (((type) & CCV_32S) ? (x)->data.i32[((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)] : \ (((type) & CCV_32F) ? (x)->data.f32[((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)] : \ (((type) & CCV_64S) ? (x)->data.i64[((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)] : \ (((type) & CCV_64F) ? (x)->data.f64[((row) * (x)->cols + (col)) * CCV_GET_CHANNEL(type) + (ch)] : \ (x)->data.u8[(row) * (x)->step + (col) * CCV_GET_CHANNEL(type) + (ch)])))) #define ccv_get_dense_matrix_cell_value(x, row, col, ch) ccv_get_dense_matrix_cell_value_by((x)->type, x, row, col, ch) #define ccv_get_value(type, ptr, i) \ (((type) & CCV_32S) ? ((int*)(ptr))[(i)] : \ (((type) & CCV_32F) ? ((float*)(ptr))[(i)] : \ (((type) & CCV_64S) ? ((int64_t*)(ptr))[(i)] : \ (((type) & CCV_64F) ? ((double*)(ptr))[(i)] : \ ((unsigned char*)(ptr))[(i)])))) #define ccv_set_value(type, ptr, i, value, factor) switch (CCV_GET_DATA_TYPE((type))) { \ case CCV_32S: ((int*)(ptr))[(i)] = (int)(value) >> factor; break; \ case CCV_32F: ((float*)(ptr))[(i)] = (float)value; break; \ case CCV_64S: ((int64_t*)(ptr))[(i)] = (int64_t)(value) >> factor; break; \ case CCV_64F: ((double*)(ptr))[(i)] = (double)value; break; \ default: ((unsigned char*)(ptr))[(i)] = ccv_clamp((int)(value) >> factor, 0, 255); } /** @} */ /** * @defgroup ccv_io basic IO utilities * @{ */ enum { // modifier for converting to gray-scale CCV_IO_GRAY = 0x100, // modifier for converting to color CCV_IO_RGB_COLOR = 0x300, }; enum { // modifier for not copy the data over when read raw in-memory data CCV_IO_NO_COPY = 0x10000, }; enum { // read self-describe in-memory data CCV_IO_ANY_STREAM = 0x010, CCV_IO_BMP_STREAM = 0x011, CCV_IO_JPEG_STREAM = 0x012, CCV_IO_PNG_STREAM = 0x013, CCV_IO_PLAIN_STREAM = 0x014, CCV_IO_DEFLATE_STREAM = 0x015, // read self-describe on-disk data CCV_IO_ANY_FILE = 0x020, CCV_IO_BMP_FILE = 0x021, CCV_IO_JPEG_FILE = 0x022, CCV_IO_PNG_FILE = 0x023, CCV_IO_BINARY_FILE = 0x024, // read not-self-describe in-memory data (a.k.a. raw data) // you need to specify rows, cols, or scanline for these data CCV_IO_ANY_RAW = 0x040, CCV_IO_RGB_RAW = 0x041, CCV_IO_RGBA_RAW = 0x042, CCV_IO_ARGB_RAW = 0x043, CCV_IO_BGR_RAW = 0x044, CCV_IO_BGRA_RAW = 0x045, CCV_IO_ABGR_RAW = 0x046, CCV_IO_GRAY_RAW = 0x047, }; enum { CCV_IO_FINAL = 0x00, CCV_IO_CONTINUE, CCV_IO_ERROR, CCV_IO_ATTEMPTED, CCV_IO_UNKNOWN, }; /** * @file ccv_doxygen.h * @fn int ccv_read(const char* in, ccv_dense_matrix_t** x, int type) * Read image from a file. This function has soft dependencies on [LibJPEG](http://libjpeg.sourceforge.net/) and [LibPNG](http://www.libpng.org/pub/png/libpng.html). No these libraries, no JPEG nor PNG read support. However, ccv does support BMP read natively (it is a simple format after all). * @param in The file name. * @param x The output image. * @param type CCV_IO_ANY_FILE, accept any file format. CCV_IO_GRAY, convert to grayscale image. CCV_IO_RGB_COLOR, convert to color image. */ /** * @fn int ccv_read(const void* data, ccv_dense_matrix_t** x, int type, int size) * Read image from a a region of memory that conforms a specific image format. This function has soft dependencies on [LibJPEG](http://libjpeg.sourceforge.net/) and [LibPNG](http://www.libpng.org/pub/png/libpng.html). No these libraries, no JPEG nor PNG read support. However, ccv does support BMP read natively (it is a simple format after all). * @param data The data memory. * @param x The output image. * @param type CCV_IO_ANY_STREAM, accept any file format. CCV_IO_GRAY, convert to grayscale image. CCV_IO_RGB_COLOR, convert to color image. * @param size The size of that data memory region. */ /** * @fn int ccv_read(const void* data, ccv_dense_matrix_t** x, int type, int rows, int cols, int scanline) * Read image from a region of memory that assumes specific layout (RGB, GRAY, BGR, RGBA, ARGB, RGBA, ABGR, BGRA). By default, this method will create a matrix and copy data over to that matrix. With CCV_IO_NO_COPY, it will create a matrix that has data block pointing to the original data memory region. It is your responsibility to release that data memory at an appropriate time after release the matrix. * @param data The data memory. * @param x The output image. * @param type CCV_IO_ANY_RAW, CCV_IO_RGB_RAW, CCV_IO_BGR_RAW, CCV_IO_RGBA_RAW, CCV_IO_ARGB_RAW, CCV_IO_BGRA_RAW, CCV_IO_ABGR_RAW, CCV_IO_GRAY_RAW. These in conjunction can be used with CCV_IO_NO_COPY. * @param rows How many rows in the given data memory region. * @param cols How many columns in the given data memory region. * @param scanline The size of a single column in the given data memory region (or known as "bytes per row"). */ int ccv_read_impl(const void* in, ccv_dense_matrix_t** x, int type, int rows, int cols, int scanline); #define ccv_read_n(in, x, type, rows, cols, scanline, ...) \ ccv_read_impl(in, x, type, rows, cols, scanline) #define ccv_read(in, x, type, ...) \ ccv_read_n(in, x, type, ##__VA_ARGS__, 0, 0, 0) // this is a way to implement function-signature based dispatch, you can call either // ccv_read(in, x, type) or ccv_read(in, x, type, rows, cols, scanline) // notice that you can implement this with va_* functions, but that is not type-safe /** * Write image to a file. This function has soft dependencies on [LibJPEG](http://libjpeg.sourceforge.net/) and [LibPNG](http://www.libpng.org/pub/png/libpng.html). No these libraries, no JPEG nor PNG write support. * @param mat The input image. * @param out The file name. * @param len The output bytes. * @param type CCV_IO_PNG_FILE, save to PNG format. CCV_IO_JPEG_FILE, save to JPEG format. * @param conf configuration. */ int ccv_write(ccv_dense_matrix_t* mat, char* out, int* len, int type, void* conf); /** @} */ /** * @defgroup ccv_algebra linear algebra * @{ */ double ccv_trace(ccv_matrix_t* mat); enum { CCV_L1_NORM = 0x01, // |dx| + |dy| CCV_L2_NORM = 0x02, // sqrt(dx^2 + dy^2) CCV_GSEDT = 0x04, // Generalized Squared Euclidean Distance Transform: // a * dx + b * dy + c * dx^2 + d * dy^2, when combined with CCV_L1_NORM: // a * |dx| + b * |dy| + c * dx^2 + d * dy^2 CCV_NEGATIVE = 0x08, // negative distance computation (from positive (min) to negative (max)) CCV_POSITIVE = 0x00, // positive distance computation (the default) }; enum { CCV_NO_PADDING = 0x00, CCV_PADDING_ZERO = 0x01, CCV_PADDING_EXTEND = 0x02, CCV_PADDING_MIRROR = 0x04, }; enum { CCV_SIGNED = 0x00, CCV_UNSIGNED = 0x01, }; double ccv_norm(ccv_matrix_t* mat, int type); /** * Normalize a matrix and return the normalize factor. * @param a The input matrix. * @param b The output matrix. * @param btype The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param flag CCV_L1 or CCV_L2, for L1 or L2 normalization. * @return L1 or L2 sum. */ double ccv_normalize(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int flag); /** * Generate the [Summed Area Table](https://en.wikipedia.org/wiki/Summed_area_table). * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param padding_pattern CCV_NO_PADDING - the first row and the first column in the output matrix is the same as the input matrix. CCV_PADDING_ZERO - the first row and the first column in the output matrix is zero, thus, the output matrix size is 1 larger than the input matrix. */ void ccv_sat(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int padding_pattern); /** * Dot product of two matrix. * @param a The input matrix. * @param b The other input matrix. * @return Dot product. */ double ccv_dot(ccv_matrix_t* a, ccv_matrix_t* b); /** * Return the sum of all elements in the matrix. * @param mat The input matrix. * @param flag CCV_UNSIGNED - compute fabs(x) of the elements first and then sum up. CCV_SIGNED - compute the sum normally. */ double ccv_sum(ccv_matrix_t* mat, int flag); /** * Return the sum of all elements in the matrix. * @param mat The input matrix. * @return Element variance of the input matrix. */ double ccv_variance(ccv_matrix_t* mat); /** * Do element-wise matrix multiplication. * @param a The input matrix. * @param b The input matrix. * @param c The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_multiply(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type); /** * Matrix addition. * @param a The input matrix. * @param b The input matrix. * @param c The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_add(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type); /** * Matrix subtraction. * @param a The input matrix. * @param b The input matrix. * @param c The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_subtract(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type); /** * Scale given matrix by factor of **ds**. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param ds The scale factor, `b = a * ds` */ void ccv_scale(ccv_matrix_t* a, ccv_matrix_t** b, int type, double ds); enum { CCV_A_TRANSPOSE = 0x01, CCV_B_TRANSPOSE = 0X02, CCV_C_TRANSPOSE = 0X04, }; /** * General purpose matrix multiplication. This function has a hard dependency on [cblas](http://www.netlib.org/blas/) library. * * As general as it is, it computes: * * alpha * A * B + beta * C * * whereas A, B, C are matrix, and alpha, beta are scalar. * * @param a The input matrix. * @param b The input matrix. * @param alpha The multiplication factor. * @param c The input matrix. * @param beta The multiplication factor. * @param transpose CCV_A_TRANSPOSE, CCV_B_TRANSPOSE to indicate if matrix A or B need to be transposed first before multiplication. * @param d The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_gemm(ccv_matrix_t* a, ccv_matrix_t* b, double alpha, ccv_matrix_t* c, double beta, int transpose, ccv_matrix_t** d, int type); /** @} */ typedef struct { int left; int top; int right; int bottom; } ccv_margin_t; inline static ccv_margin_t ccv_margin(int left, int top, int right, int bottom) { ccv_margin_t margin; margin.left = left; margin.top = top; margin.right = right; margin.bottom = bottom; return margin; } /* matrix build blocks / utility functions ccv_util.c */ /** * @defgroup ccv_util data structure utilities * @{ */ /** * Check and get dense matrix from general matrix structure. * @param mat A general matrix. */ ccv_dense_matrix_t* ccv_get_dense_matrix(ccv_matrix_t* mat); /** * Check and get sparse matrix from general matrix structure. * @param mat A general matrix. */ ccv_sparse_matrix_t* ccv_get_sparse_matrix(ccv_matrix_t* mat); /** * Get vector for a sparse matrix. * @param mat The sparse matrix. * @param index The index of that vector. */ ccv_sparse_matrix_vector_t* ccv_get_sparse_matrix_vector(const ccv_sparse_matrix_t* mat, int index); /** * Get cell for a vector of a sparse matrix. * @param mat The sparse matrix. * @param vector The vector. * @param index The index of the cell. */ ccv_numeric_data_t ccv_get_sparse_matrix_cell_from_vector(const ccv_sparse_matrix_t* mat, ccv_sparse_matrix_vector_t* vector, int index); /** * Get cell from a sparse matrix. * @param mat The sparse matrix. * @param row The row index. * @param col The column index. */ ccv_numeric_data_t ccv_get_sparse_matrix_cell(const ccv_sparse_matrix_t* mat, int row, int col); /** * Set cell for a sparse matrix. * @param mat The sparse matrix. * @param row The row index. * @param col The column index. * @param data The data pointer. */ void ccv_set_sparse_matrix_cell(ccv_sparse_matrix_t* mat, int row, int col, const void* data); /** * Transform a sparse matrix into compressed representation. * @param mat The sparse matrix. * @param csm The compressed matrix. */ void ccv_compress_sparse_matrix(const ccv_sparse_matrix_t* mat, ccv_compressed_sparse_matrix_t** csm); /** * Transform a compressed matrix into a sparse matrix. * @param csm The compressed matrix. * @param smt The sparse matrix. */ void ccv_decompress_sparse_matrix(const ccv_compressed_sparse_matrix_t* csm, ccv_sparse_matrix_t** smt); /** * Offset input matrix by x, y. * @param a The input matrix. * @param b The output matrix. * @param btype The type of output matrix, if 0, ccv will use the input matrix type. * @param y b(0, 0) = a(x, y). * @param x b(0, 0) = a(x, y). */ void ccv_move(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int y, int x); /** * Compare if two matrix are equal (with type). Return 0 if it is. * @param a The input matrix a. * @param b The input matrix b. */ int ccv_matrix_eq(ccv_matrix_t* a, ccv_matrix_t* b); /** * Slice an input matrix given x, y and row, column size. * @param a The input matrix. * @param b The output matrix. * @param btype The type of output matrix, if 0, ccv will use the input matrix type. * @param y y coordinate. * @param x x coordinate. * @param rows Row size of targeted matrix. * @param cols Column size of targeted matrix. */ void ccv_slice(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int y, int x, int rows, int cols); /** * Add border to the input matrix. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param margin Left, top, right, bottom width for the border. */ void ccv_border(ccv_matrix_t* a, ccv_matrix_t** b, int type, ccv_margin_t margin); /** * Convert a input matrix into a matrix within visual range, so that one can output it into PNG file for inspection. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_visualize(ccv_matrix_t* a, ccv_matrix_t** b, int type); /** * If a given matrix has multiple channels, this function will compute a new matrix that each cell in the new matrix is the sum of all channels in the same cell of the given matrix. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param flag ccv reserved this for now. */ void ccv_flatten(ccv_matrix_t* a, ccv_matrix_t** b, int type, int flag); /** * Zero out a given matrix. * @param mat The given matrix. */ void ccv_zero(ccv_matrix_t* mat); /** * Compute a new matrix that each element is first left shifted and then right shifted. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param lr Left shift amount. * @param rr Right shift amount. */ void ccv_shift(ccv_matrix_t* a, ccv_matrix_t** b, int type, int lr, int rr); /** * Check if any nan value in the given matrix, and return its position. * @param a The given matrix. */ int ccv_any_nan(ccv_matrix_t *a); /** * Return a temporary ccv_dense_matrix_t matrix that is pointing to a given matrix data section but with different rows and cols. Useful to use part of the given matrix do computations without paying memory copy performance penalty. * @param a The given matrix. * @param y The y offset to the given matrix. * @param x The x offset to the given matrix. * @param rows The number of rows of the new matrix. * @param cols The number of cols of the new matrix. */ ccv_dense_matrix_t ccv_reshape(ccv_dense_matrix_t* a, int y, int x, int rows, int cols); // 32-bit float to 16-bit float void ccv_float_to_half_precision(float* f, uint16_t* h, size_t len); void ccv_half_precision_to_float(uint16_t* h, float* f, size_t len); /* basic data structures ccv_util.c */ typedef struct { int width; int height; } ccv_size_t; inline static ccv_size_t ccv_size(int width, int height) { ccv_size_t size; size.width = width; size.height = height; return size; } inline static int ccv_size_is_zero(ccv_size_t size) { return size.width == 0 && size.height == 0; } typedef struct { int x; int y; int width; int height; } ccv_rect_t; inline static ccv_rect_t ccv_rect(int x, int y, int width, int height) { ccv_rect_t rect; rect.x = x; rect.y = y; rect.width = width; rect.height = height; return rect; } inline static int ccv_rect_is_zero(ccv_rect_t rect) { return rect.x == 0 && rect.y == 0 && rect.width == 0 && rect.height == 0; } typedef struct { float x; float y; float width; float height; } ccv_decimal_rect_t; inline static ccv_decimal_rect_t ccv_decimal_rect(float x, float y, float width, float height) { ccv_decimal_rect_t rect; rect.x = x; rect.y = y; rect.width = width; rect.height = height; return rect; } typedef struct { int type; uint64_t sig; int refcount; int rnum; int size; int rsize; void* data; } ccv_array_t; /** * Create a new, self-growing array. * @param rnum The initial capacity of the array. * @param rsize The size of each element in the array. * @param sig The signature for this array. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_array_new(int rsize, int rnum, uint64_t sig); /** * Push a new element into the array. * @param array The array. * @param r The pointer to new element, it will then be copied into the array. */ void ccv_array_push(ccv_array_t* array, const void* r); typedef int(*ccv_array_group_f)(const void*, const void*, void*); /** * Group elements in the array from its similarity. * @param array The array. * @param index The output index, same group element will have the same index. * @param gfunc int ccv_array_group_f(const void* a, const void* b, void* data). Return 1 if a and b are in the same group. * @param data Any extra user data. */ int ccv_array_group(ccv_array_t* array, ccv_array_t** index, ccv_array_group_f gfunc, void* data); void ccv_make_array_immutable(ccv_array_t* array); void ccv_make_array_mutable(ccv_array_t* array); /** * Zero out the array, it won't change the array->rnum however. * @param array The array. */ void ccv_array_zero(ccv_array_t* array); /** * Resize the array, it will change the array->rnum and zero init the rest. * @param array The array. * @param rnum The expanded size of the array. */ void ccv_array_resize(ccv_array_t* array, int rnum); /** * Clear the array, it will reset the array->rnum to 0. * @param array The array. */ void ccv_array_clear(ccv_array_t* array); /** * Free up the array immediately. * @param array The array. */ void ccv_array_free_immediately(ccv_array_t* array); /** * Free up the array. If array's signature is non-zero, we may put it into cache so that later on, we can shortcut and return this array directly. * @param array The array. */ void ccv_array_free(ccv_array_t* array); /** * Get a specific element from an array * @param a The array. * @param i The index of the element in the array. */ #define ccv_array_get(a, i) ((void*)(((char*)((a)->data)) + (size_t)(a)->rsize * (size_t)(i))) typedef struct { int x, y; } ccv_point_t; inline static ccv_point_t ccv_point(int x, int y) { ccv_point_t point; point.x = x; point.y = y; return point; } typedef struct { float x, y; } ccv_decimal_point_t; inline static ccv_decimal_point_t ccv_decimal_point(float x, float y) { ccv_decimal_point_t point; point.x = x; point.y = y; return point; } typedef struct { float x, y, a, b; float roll, pitch, yaw; } ccv_decimal_pose_t; inline static ccv_decimal_pose_t ccv_decimal_pose(float x, float y, float a, float b, float roll, float pitch, float yaw) { ccv_decimal_pose_t pose; pose.x = x; pose.y = y; pose.a = a; pose.b = b; pose.roll = roll; pose.pitch = pitch; pose.yaw = yaw; return pose; } typedef struct { ccv_rect_t rect; int size; ccv_array_t* set; long m10, m01, m11, m20, m02; } ccv_contour_t; /** * Create a new contour object. * @param set The initial capacity of the contour. */ ccv_contour_t* ccv_contour_new(int set); /** * Push a point into the contour object. * @param contour The contour. * @param point The point. */ void ccv_contour_push(ccv_contour_t* contour, ccv_point_t point); /** * Free up the contour object. * @param contour The contour. */ void ccv_contour_free(ccv_contour_t* contour); /** @} */ /* numerical algorithms ccv_numeric.c */ /** * @defgroup ccv_numeric numerical algorithms * @{ */ /* clarification about algebra and numerical algorithms: * when using the word "algebra", I assume the operation is well established in Mathematic sense * and can be calculated with a straight-forward, finite sequence of operation. The "numerical" * in other word, refer to a class of algorithm that can only approximate/or iteratively found the * solution. Thus, "invert" would be classified as numerical because of the sense that in some case, * it can only be "approximate" (in least-square sense), so to "solve". */ void ccv_invert(ccv_matrix_t* a, ccv_matrix_t** b, int type); void ccv_solve(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** d, int type); void ccv_eigen(ccv_dense_matrix_t* a, ccv_dense_matrix_t** vector, ccv_dense_matrix_t** lambda, int type, double epsilon); typedef struct { double interp; /**< Interpolate value. */ double extrap; /**< Extrapolate value. */ int max_iter; /**< Maximum iterations. */ double ratio; /**< Increase ratio. */ double rho; /**< Decrease ratio. */ double sig; /**< Sigma. */ } ccv_minimize_param_t; extern const ccv_minimize_param_t ccv_minimize_default_params; typedef int(*ccv_minimize_f)(const ccv_dense_matrix_t* x, double* f, ccv_dense_matrix_t* df, void*); /** * Linear-search to minimize function with partial derivatives. It is formed after [minimize.m](http://www.gatsby.ucl.ac.uk/~edward/code/minimize/example.html). * @param x The input vector. * @param length The length of line. * @param red The step size. * @param func (int ccv_minimize_f)(const ccv_dense_matrix_t* x, double* f, ccv_dense_matrix_t* df, void* data). Compute the function value, and its partial derivatives. * @param params A **ccv_minimize_param_t** structure that defines various aspect of the minimize function. * @param data Any extra user data. */ void ccv_minimize(ccv_dense_matrix_t* x, int length, double red, ccv_minimize_f func, ccv_minimize_param_t params, void* data); /** * Convolve on dense matrix a with dense matrix b. This function has a soft dependency on [FFTW3](http://fftw.org/). If no FFTW3 exists, ccv will use [KissFFT](http://sourceforge.net/projects/kissfft/) shipped with it. FFTW3 is about 35% faster than KissFFT. * @param a Dense matrix a. * @param b Dense matrix b. * @param d The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param padding_pattern ccv doesn't support padding pattern for now. */ void ccv_filter(ccv_dense_matrix_t* a, ccv_dense_matrix_t* b, ccv_dense_matrix_t** d, int type, int padding_pattern); typedef double(*ccv_filter_kernel_f)(double x, double y, void*); /** * Fill a given dense matrix with a kernel function. * @param x The matrix to be filled with. * @param func (double ccv_filter_kernel_f(double x, double y, void* data), compute the value with given x, y. * @param data Any extra user data. */ void ccv_filter_kernel(ccv_dense_matrix_t* x, ccv_filter_kernel_f func, void* data); /* modern numerical algorithms */ /** * [Distance transform](https://en.wikipedia.org/wiki/Distance_transform). The current implementation follows [Distance Transforms of Sampled Functions](http://www.cs.cornell.edu/~dph/papers/dt.pdf). The dynamic programming technique has O(n) time complexity. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param x The x coordinate offset. * @param x_type The type of output x coordinate offset, if 0, ccv will default to CCV_32S | CCV_C1. * @param y The y coordinate offset. * @param y_type The type of output x coordinate offset, if 0, ccv will default to CCV_32S | CCV_C1. * @param dx The x coefficient. * @param dy The y coefficient. * @param dxx The x^2 coefficient. * @param dyy The y^2 coefficient. * @param flag CCV_GSEDT, generalized squared Euclidean distance transform. CCV_NEGATIVE, negate value in input matrix for computation; effectively, this enables us to compute the maximum distance transform rather than minimum (default one). */ void ccv_distance_transform(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, ccv_dense_matrix_t** x, int x_type, ccv_dense_matrix_t** y, int y_type, double dx, double dy, double dxx, double dyy, int flag); /** @} */ void ccv_sparse_coding(ccv_matrix_t* x, int k, ccv_matrix_t** A, int typeA, ccv_matrix_t** y, int typey); void ccv_compressive_sensing_reconstruct(ccv_matrix_t* a, ccv_matrix_t* x, ccv_matrix_t** y, int type); /** * @defgroup ccv_basic basic image pre-processing utilities * The utilities in this file provides basic pre-processing which, most-likely, are the first steps for computer vision algorithms. * @{ */ /** * Compute image with [Sobel operator](https://en.wikipedia.org/wiki/Sobel_operator). * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param dx The window size of Sobel operator on x-axis, specially optimized for 1, 3 * @param dy The window size of Sobel operator on y-axis, specially optimized for 1, 3 */ void ccv_sobel(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int dx, int dy); /** * Compute the gradient (angle and magnitude) at each pixel. * @param a The input matrix. * @param theta The output matrix of angle at each pixel. * @param ttype The type of output matrix, if 0, ccv will defaults to CCV_32F. * @param m The output matrix of magnitude at each pixel. * @param mtype The type of output matrix, if 0, ccv will defaults to CCV_32F. * @param dx The window size of the underlying Sobel operator used on x-axis, specially optimized for 1, 3 * @param dy The window size of the underlying Sobel operator used on y-axis, specially optimized for 1, 3 */ void ccv_gradient(ccv_dense_matrix_t* a, ccv_dense_matrix_t** theta, int ttype, ccv_dense_matrix_t** m, int mtype, int dx, int dy); enum { CCV_FLIP_X = 0x01, CCV_FLIP_Y = 0x02, }; /** * Flip the matrix by x-axis, y-axis or both. * @param a The input matrix. * @param b The output matrix (it is in-place safe). * @param btype The type of output matrix, if 0, ccv will use the sample type as the input matrix. * @param type CCV_FLIP_X - flip around x-axis, CCV_FLIP_Y - flip around y-axis. */ void ccv_flip(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int btype, int type); /** * Using [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) on a given matrix. It implements a O(n * sqrt(m)) algorithm, n is the size of input matrix, m is the size of Gaussian filtering kernel. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param sigma The sigma factor in Gaussian filtering kernel. */ void ccv_blur(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, double sigma); /** @} */ /** * @defgroup ccv_image_processing image processing utilities * The utilities in this file provides image processing methods that are widely used for image enhancements. * @{ */ enum { CCV_RGB_TO_YUV = 0x01, }; /** * Convert matrix from one color space representation to another. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will use the sample type as the input matrix. * @param flag **CCV_RGB_TO_YUV** to convert from RGB color space to YUV color space. */ void ccv_color_transform(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int flag); /** * Manipulate image's saturation. * @param a The input matrix. * @param b The output matrix (it is in-place safe). * @param type The type of output matrix, if 0, ccv will use the sample type as the input matrix. * @param ds The coefficient (0: grayscale, 1: original). */ void ccv_saturation(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, double ds); /** * Manipulate image's contrast. * @param a The input matrix. * @param b The output matrix (it is in-place safe). * @param type The type of output matrix, if 0, ccv will use the sample type as the input matrix. * @param ds The coefficient (0: mean image, 1: original). */ void ccv_contrast(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, double ds); /** @} */ /** * @defgroup ccv_resample image resampling utilities * @{ */ enum { CCV_INTER_AREA = 0x01, CCV_INTER_LINEAR = 0X02, CCV_INTER_CUBIC = 0X04, CCV_INTER_LANCZOS = 0X08, }; /** * Resample a given matrix to different size, as for now, ccv only supports either downsampling (with CCV_INTER_AREA) or upsampling (with CCV_INTER_CUBIC). * @param a The input matrix. * @param b The output matrix. * @param btype The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param rows The new row. * @param cols The new column. * @param type For now, ccv supports CCV_INTER_AREA, which is an extension to [bilinear resampling](https://en.wikipedia.org/wiki/Bilinear_filtering) for downsampling and CCV_INTER_CUBIC [bicubic resampling](https://en.wikipedia.org/wiki/Bicubic_interpolation) for upsampling. */ void ccv_resample(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int btype, int rows, int cols, int type); /** * Downsample a given matrix to exactly half size with a [Gaussian filter](https://en.wikipedia.org/wiki/Gaussian_filter). The half size is approximated by floor(rows * 0.5) x floor(cols * 0.5). * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param src_x Shift the start point by src_x. * @param src_y Shift the start point by src_y. */ void ccv_sample_down(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int src_x, int src_y); /** * Upsample a given matrix to exactly double size with a [Gaussian filter](https://en.wikipedia.org/wiki/Gaussian_filter). * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param src_x Shift the start point by src_x. * @param src_y Shift the start point by src_y. */ void ccv_sample_up(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int src_x, int src_y); /** @} */ /** * @defgroup ccv_transform image transform utilities * @{ */ /** * Similar to ccv_slice, it will slice a given matrix into required rows / cols, but it will interpolate the value with bilinear filter if x and y is non-integer. * @param a The given matrix that will be sliced * @param b The output matrix * @param type The type of output matrix * @param y The top point to slice * @param x The left point to slice * @param rows The number of rows for destination matrix * @param cols The number of cols for destination matrix */ void ccv_decimal_slice(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, float y, float x, int rows, int cols); /** * Apply a [3D transform](https://en.wikipedia.org/wiki/Perspective_transform#Perspective_projection) against the given point in a given image size, assuming field of view is 60 (in degree). * @param point The point to be transformed in decimal * @param size The image size * @param m00, m01, m02, m10, m11, m12, m20, m21, m22 The transformation matrix */ ccv_decimal_point_t ccv_perspective_transform_apply(ccv_decimal_point_t point, ccv_size_t size, float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22); /** * Apply a [3D transform](https://en.wikipedia.org/wiki/Perspective_transform#Perspective_projection) on a given matrix, assuming field of view is 60 (in degree). * @param a The given matrix to be transformed * @param b The output matrix * @param type The type of output matrix * @param m00, m01, m02, m10, m11, m12, m20, m21, m22 The transformation matrix */ void ccv_perspective_transform(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22); /** @} */ /* classic computer vision algorithms ccv_classic.c */ /** * @defgroup ccv_classic classic computer vision algorithms * @{ */ /** * [Histogram-of-Oriented-Gradients](https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients) implementation, specifically, it implements the HOG described in *Object Detection with Discriminatively Trained Part-Based Models, Pedro F. Felzenszwalb, Ross B. Girshick, David McAllester and Deva Ramanan*. * @param a The input matrix. * @param b The output matrix. * @param b_type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param sbin The number of bins for orientation (default to 9, thus, for **b**, it will have 9 * 2 + 9 + 4 = 31 channels). * @param size The window size for HOG (default to 8) */ void ccv_hog(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int b_type, int sbin, int size); /** * [Canny edge detector](https://en.wikipedia.org/wiki/Canny_edge_detector) implementation. For performance reason, this is a clean-up reimplementation of OpenCV's Canny edge detector, it has very similar performance characteristic as the OpenCV one. As of today, ccv's Canny edge detector only works with CCV_8U or CCV_32S dense matrix type. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will create a CCV_8U | CCV_C1 matrix. * @param size The underlying Sobel filter size. * @param low_thresh The low threshold that makes the point interesting. * @param high_thresh The high threshold that makes the point acceptable. */ void ccv_canny(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int size, double low_thresh, double high_thresh); void ccv_close_outline(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type); /* range: exclusive, return value: inclusive (i.e., threshold = 5, 0~5 is background, 6~range-1 is foreground */ /** * [OTSU](https://en.wikipedia.org/wiki/Otsu%27s_method) implementation. * @param a The input matrix. * @param outvar The inter-class variance. * @param range The maximum range of data in the input matrix. * @return The threshold, inclusively. e.g. 5 means 0~5 is in the background, and 6~255 is in the foreground. */ int ccv_otsu(ccv_dense_matrix_t* a, double* outvar, int range); typedef struct { ccv_decimal_point_t point; uint8_t status; } ccv_decimal_point_with_status_t; /** * [Lucas Kanade](https://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_Optical_Flow_Method) optical flow implementation with image pyramid extension. * @param a The first frame * @param b The next frame * @param point_a The points in first frame, of **ccv_decimal_point_t** type * @param point_b The output points in the next frame, of **ccv_decimal_point_with_status_t** type * @param win_size The window size to compute each optical flow, it must be a odd number * @param level How many image pyramids to be used for the computation * @param min_eigen The minimal eigen-value to pass optical flow computation */ void ccv_optical_flow_lucas_kanade(ccv_dense_matrix_t* a, ccv_dense_matrix_t* b, ccv_array_t* point_a, ccv_array_t** point_b, ccv_size_t win_size, int level, double min_eigen); /** @} */ /* modern computer vision algorithms */ /* SIFT, DAISY, SWT, MSER, DPM, BBF, SGF, SSD, FAST */ /** * @defgroup ccv_daisy DAISY * @{ */ /* daisy related methods */ typedef struct { double radius; /**< the Gaussian radius. */ int rad_q_no; int th_q_no; int hist_th_q_no; float normalize_threshold; int normalize_method; } ccv_daisy_param_t; enum { CCV_DAISY_NORMAL_PARTIAL = 0x01, CCV_DAISY_NORMAL_FULL = 0x02, CCV_DAISY_NORMAL_SIFT = 0x03, }; /** * [DAISY](http://cvlab.epfl.ch/publications/publications/2010/TolaLF10a.pdf) implementation. For more details - DAISY: An Efficient Dense Descriptor Applied to Wide-Baseline Stereo. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. * @param params A **ccv_daisy_param_t** structure that defines various aspect of the feature extractor. */ void ccv_daisy(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, ccv_daisy_param_t params); /** @} */ /* sift related methods */ /** * @defgroup ccv_sift scale invariant feature transform * @{ */ typedef struct { float x, y; int octave; int level; union { struct { double a, b; double c, d; } affine; struct { double scale; double angle; } regular; }; } ccv_keypoint_t; typedef struct { int up2x; /**< If upscale the image for better SIFT accuracy. */ int noctaves; /**< Number of octaves. */ int nlevels; /**< Number of levels for each octaves. */ float edge_threshold; /**< Above this threshold, it will be recognized as edge otherwise be ignored. */ float peak_threshold; /**< Above this threshold, it will be recognized as potential feature point. */ float norm_threshold; /**< If norm of the descriptor is smaller than threshold, it will be ignored. */ } ccv_sift_param_t; extern const ccv_sift_param_t ccv_sift_default_params; /** * Compute [SIFT](https://en.wikipedia.org/wiki/Scale-invariant_feature_transform) key-points. * @param a The input matrix. * @param keypoints The array of key-points, a ccv_keypoint_t structure. * @param desc The descriptor for each key-point. * @param type The type of the descriptor, if 0, ccv will default to CCV_32F. * @param params A **ccv_sift_param_t** structure that defines various aspect of SIFT function. */ void ccv_sift(ccv_dense_matrix_t* a, ccv_array_t** keypoints, ccv_dense_matrix_t** desc, int type, ccv_sift_param_t params); /** @} */ /* mser related method */ typedef struct { /* parameters for MSER */ int delta; int min_area; /* default: 60 */ int direction; /* default: 0, 0 for both, -1 for bright to dark, 1 for dark to bright */ int max_area; double max_variance; double min_diversity; int range; /* from 0 to range, inclusive */ /* parameters for MSCR */ double area_threshold; /* default: 1.01 */ double min_margin; /* default: 0.003 */ int max_evolution; double edge_blur_sigma; /* default: 1.0 */ } ccv_mser_param_t; typedef struct { ccv_rect_t rect; int size; long m10, m01, m11, m20, m02; ccv_point_t keypoint; } ccv_mser_keypoint_t; enum { CCV_BRIGHT_TO_DARK = -1, CCV_DARK_TO_BRIGHT = 1, }; CCV_WARN_UNUSED(ccv_array_t*) ccv_mser(ccv_dense_matrix_t* a, ccv_dense_matrix_t* h, ccv_dense_matrix_t** b, int type, ccv_mser_param_t params); /* swt related method: stroke width transform is relatively new, typically used in text detection */ /** * @defgroup ccv_swt stroke width transform * @{ */ typedef struct { int interval; /**< Intervals for scale invariant option. */ int min_neighbors; /**< Minimal neighbors to make a detection valid, this is for scale-invariant version. */ int scale_invariant; /**< Enable scale invariant swt (to scale to different sizes and then combine the results) */ int direction; /**< SWT direction. (black to white or white to black). */ double same_word_thresh[2]; /**< Overlapping more than 0.1 of the bigger one (0), and 0.9 of the smaller one (1) */ /** * @name Canny parameters * @{ */ int size; /**< Parameters for [Canny edge detector](/lib/ccv-classic). */ int low_thresh; /**< Parameters for [Canny edge detector](/lib/ccv-classic). */ int high_thresh; /**< Parameters for [Canny edge detector](/lib/ccv-classic). */ /** @} */ /** * @name Geometry filtering parameters * @{ */ int max_height; /**< The maximum height for a letter. */ int min_height; /**< The minimum height for a letter. */ int min_area; /**< The minimum occupied area for a letter. */ int letter_occlude_thresh; double aspect_ratio; /**< The maximum aspect ratio for a letter. */ double std_ratio; /**< The inner-class standard derivation when grouping letters. */ /** @} */ /** * @name Grouping parameters * @{ */ double thickness_ratio; /**< The allowable thickness variance when grouping letters. */ double height_ratio; /**< The allowable height variance when grouping letters. */ int intensity_thresh; /**< The allowable intensity variance when grouping letters. */ double distance_ratio; /**< The allowable distance variance when grouping letters. */ double intersect_ratio; /**< The allowable intersect variance when grouping letters. */ double elongate_ratio; /**< The allowable elongate variance when grouping letters. */ int letter_thresh; /**< The allowable letter threshold. */ /** @} */ /** * @name Break textline into words * @{ */ int breakdown; /**< If breakdown text line into words. */ double breakdown_ratio; /**< Apply [OSTU](/lib/ccv-classic) and if inter-class variance above the threshold, it will be break down into words. */ /** @} */ } ccv_swt_param_t; extern const ccv_swt_param_t ccv_swt_default_params; /** * Compute the Stroke-Width-Transform image. * @param a The input matrix. * @param b The output matrix. * @param type The type of the output matrix, if 0, ccv will default to CCV_32S | CCV_C1. * @param params A **ccv_swt_param_t** structure that defines various aspect of the SWT function. */ void ccv_swt(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, ccv_swt_param_t params); /** * Return array of regions that are potentially text area. * @param a The input matrix. * @param params A **ccv_swt_param_t** structure that defines various aspect of the SWT function. * @return A **ccv_array_t** of **ccv_comp_t** with detection results. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_swt_detect_words(ccv_dense_matrix_t* a, ccv_swt_param_t params); /* it makes sense now to include a simple data structure that encapsulate the common idiom of * having file name with a bounding box */ typedef struct { char* filename; union { ccv_decimal_rect_t bbox; ccv_decimal_pose_t pose; }; } ccv_file_info_t; /* I'd like to include Deformable Part Models as a general object detection method in here * The difference between BBF and DPM: * ~ BBF is for rigid object detection: banners, box, faces etc. * ~ DPM is more generalized, can detect people, car, bike (larger inner-class difference) etc. * ~ BBF is blazing fast (few milliseconds), DPM is relatively slow (around 1 seconds or so) */ /** * @defgroup ccv_dpm deformable parts model * @{ */ #define CCV_DPM_PART_MAX (10) typedef struct { int id; float confidence; } ccv_classification_t; typedef struct { ccv_rect_t rect; int neighbors; ccv_classification_t classification; } ccv_comp_t; typedef struct { ccv_rect_t rect; int neighbors; ccv_classification_t classification; int pnum; ccv_comp_t part[CCV_DPM_PART_MAX]; } ccv_root_comp_t; typedef struct { ccv_dense_matrix_t* w; double dx, dy, dxx, dyy; int x, y, z; int counterpart; float alpha[6]; } ccv_dpm_part_classifier_t; typedef struct { int count; ccv_dpm_part_classifier_t root; ccv_dpm_part_classifier_t* part; float alpha[3], beta; } ccv_dpm_root_classifier_t; typedef struct { int count; ccv_dpm_root_classifier_t* root; } ccv_dpm_mixture_model_t; typedef struct { int interval; /**< Interval images between the full size image and the half size one. e.g. 2 will generate 2 images in between full size image and half size one: image with full size, image with 5/6 size, image with 2/3 size, image with 1/2 size. */ int min_neighbors; /**< 0: no grouping afterwards. 1: group objects that intersects each other. > 1: group objects that intersects each other, and only passes these that have at least **min_neighbors** intersected objects. */ int flags; /**< CCV_DPM_NO_NESTED, if one class of object is inside another class of object, this flag will reject the first object. */ float threshold; /**< The threshold the determines the acceptance of an object. */ } ccv_dpm_param_t; typedef struct { int components; /**< The number of root filters in the mixture model. */ int parts; /**< The number of part filters for each root filter. */ int grayscale; /**< Whether to exploit color in a given image. */ int symmetric; /**< Whether to exploit symmetric property of the object. */ int min_area; /**< The minimum area that one part classifier can occupy, 3000 is a reasonable number. */ int max_area; /**< The maximum area that one part classifier can occupy. 5000 is a reasonable number. */ int iterations; /**< How many iterations needed for stochastic gradient descent. */ int data_minings; /**< How many data mining procedures are needed for discovering hard examples. */ int root_relabels; /**< How many relabel procedures for root classifier are needed. */ int relabels; /**< How many relabel procedures are needed. */ int discard_estimating_constant; // 1 int negative_cache_size; /**< The cache size for negative examples. 1000 is a reasonable number. */ double include_overlap; /**< The percentage of overlap between expected bounding box and the bounding box from detection. Beyond this threshold, it is ensured to be the same object. 0.7 is a reasonable number. */ double alpha; /**< The step size for stochastic gradient descent. */ double alpha_ratio; /**< Decrease the step size for each iteration. 0.85 is a reasonable number. */ double balance; /**< To balance the weight of positive examples and negative examples. 1.5 is a reasonable number. */ double C; /**< C in SVM. */ double percentile_breakdown; /**< The percentile use for breakdown threshold. 0.05 is the default. */ ccv_dpm_param_t detector; /**< A **ccv_dpm_params_t** structure that will be used to search positive examples and negative examples from background images. */ } ccv_dpm_new_param_t; enum { CCV_DPM_NO_NESTED = 0x10000000, }; extern const ccv_dpm_param_t ccv_dpm_default_params; /** * Create a new DPM mixture model from given positive examples and background images. This function has hard dependencies on [GSL](http://www.gnu.org/software/gsl/) and [LibLinear](http://www.csie.ntu.edu.tw/~cjlin/liblinear/). * @param posfiles An array of positive images. * @param bboxes An array of bounding boxes for positive images. * @param posnum Number of positive examples. * @param bgfiles An array of background images. * @param bgnum Number of background images. * @param negnum Number of negative examples that is harvested from background images. * @param dir The working directory to store/retrieve intermediate data. * @param params A **ccv_dpm_new_param_t** structure that defines various aspects of the training function. */ void ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params); /** * Using a DPM mixture model to detect objects in a given image. If you have several DPM mixture models, it is better to use them in one method call. In this way, ccv will try to optimize the overall performance. * @param a The input image. * @param model An array of mixture models. * @param count How many mixture models you've passed in. * @param params A **ccv_dpm_param_t** structure that defines various aspects of the detector. * @return A **ccv_array_t** of **ccv_root_comp_t** that contains the root bounding box as well as its parts. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_dpm_detect_objects(ccv_dense_matrix_t* a, ccv_dpm_mixture_model_t** model, int count, ccv_dpm_param_t params); /** * Read DPM mixture model from a model file. * @param directory The model file for DPM mixture model. * @return A DPM mixture model, 0 if no valid DPM mixture model available. */ CCV_WARN_UNUSED(ccv_dpm_mixture_model_t*) ccv_dpm_read_mixture_model(const char* directory); /** * Free up the memory of DPM mixture model. * @param model The DPM mixture model. */ void ccv_dpm_mixture_model_free(ccv_dpm_mixture_model_t* model); /** @} */ /** * @defgroup ccv_bbf binary brightness feature * this is open source implementation of object detection algorithm: brightness binary feature * it is an extension/modification of original HAAR-like feature with Adaboost, featured faster * computation and higher accuracy (current highest accuracy close-source face detector is based * on the same algorithm) * @{ */ #define CCV_BBF_POINT_MAX (8) #define CCV_BBF_POINT_MIN (3) typedef struct { int size; int px[CCV_BBF_POINT_MAX]; int py[CCV_BBF_POINT_MAX]; int pz[CCV_BBF_POINT_MAX]; int nx[CCV_BBF_POINT_MAX]; int ny[CCV_BBF_POINT_MAX]; int nz[CCV_BBF_POINT_MAX]; } ccv_bbf_feature_t; typedef struct { int count; float threshold; ccv_bbf_feature_t* feature; float* alpha; } ccv_bbf_stage_classifier_t; typedef struct { int count; ccv_size_t size; ccv_bbf_stage_classifier_t* stage_classifier; } ccv_bbf_classifier_cascade_t; enum { CCV_BBF_GENETIC_OPT = 0x01, CCV_BBF_FLOAT_OPT = 0x02, }; typedef struct { int interval; /**< Interval images between the full size image and the half size one. e.g. 2 will generate 2 images in between full size image and half size one: image with full size, image with 5/6 size, image with 2/3 size, image with 1/2 size. */ int min_neighbors; /**< 0: no grouping afterwards. 1: group objects that intersects each other. > 1: group objects that intersects each other, and only passes these that have at least **min_neighbors** intersected objects. */ int flags; /**< CCV_BBF_NO_NESTED, if one class of object is inside another class of object, this flag will reject the first object. */ int accurate; /**< BBF will generates 4 spatial scale variations for better accuracy. Set this parameter to 0 will reduce to 1 scale variation, and thus 3 times faster but lower the general accuracy of the detector. */ ccv_size_t size; /**< The smallest object size that will be interesting to us. */ } ccv_bbf_param_t; typedef struct { double pos_crit; /**< Positive criteria or the targeted recall ratio, BBF classifier tries to adjust the constant to meet this criteria. */ double neg_crit; /**< Negative criteria or the targeted reject ratio, BBF classifier tries to include more weak features until meet this criteria. */ double balance_k; /**< Weight positive examples differently from negative examples. */ int layer; /**< The maximum layer trained for the classifier cascade. */ int feature_number; /**< The maximum feature number for each classifier. */ int optimizer; /**< CCV_BBF_GENETIC_OPT, using genetic algorithm to search the best weak feature; CCV_BBF_FLOAT_OPT, using float search to improve the found best weak feature. */ ccv_bbf_param_t detector; /**< A **ccv_bbf_params_t** structure that will be used to search negative examples from background images. */ } ccv_bbf_new_param_t; enum { CCV_BBF_NO_NESTED = 0x10000000, }; extern const ccv_bbf_param_t ccv_bbf_default_params; /** * Create a new BBF classifier cascade from given positive examples and background images. This function has a hard dependency on [GSL](http://www.gnu.org/software/gsl/). * @param posimg An array of positive examples. * @param posnum Number of positive examples. * @param bgfiles An array of background images. * @param bgnum Number of background images. * @param negnum Number of negative examples that is harvested from background images. * @param size The image size of positive examples. * @param dir The working directory to store/retrieve intermediate data. * @param params A **ccv_bbf_new_param_t** structure that defines various aspects of the training function. */ void ccv_bbf_classifier_cascade_new(ccv_dense_matrix_t** posimg, int posnum, char** bgfiles, int bgnum, int negnum, ccv_size_t size, const char* dir, ccv_bbf_new_param_t params); /** * Using a BBF classifier cascade to detect objects in a given image. If you have several classifier cascades, it is better to use them in one method call. In this way, ccv will try to optimize the overall performance. * @param a The input image. * @param cascade An array of classifier cascades. * @param count How many classifier cascades you've passed in. * @param params A **ccv_bbf_param_t** structure that defines various aspects of the detector. * @return A **ccv_array_t** of **ccv_comp_t** for detection results. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_bbf_detect_objects(ccv_dense_matrix_t* a, ccv_bbf_classifier_cascade_t** cascade, int count, ccv_bbf_param_t params); /** * Read BBF classifier cascade from working directory. * @param directory The working directory that trains a BBF classifier cascade. * @return A classifier cascade, 0 if no valid classifier cascade available. */ CCV_WARN_UNUSED(ccv_bbf_classifier_cascade_t*) ccv_bbf_read_classifier_cascade(const char* directory); /** * Free up the memory of BBF classifier cascade. * @param cascade The BBF classifier cascade. */ void ccv_bbf_classifier_cascade_free(ccv_bbf_classifier_cascade_t* cascade); /** * Load BBF classifier cascade from a memory region. * @param s The memory region of binarized BBF classifier cascade. * @return A classifier cascade, 0 if no valid classifier cascade available. */ CCV_WARN_UNUSED(ccv_bbf_classifier_cascade_t*) ccv_bbf_classifier_cascade_read_binary(char* s); /** * Write BBF classifier cascade to a memory region. * @param cascade The BBF classifier cascade. * @param s The designated memory region. * @param slen The size of the designated memory region. * @return The actual size of the binarized BBF classifier cascade, if this size is larger than **slen**, please reallocate the memory region and do it again. */ int ccv_bbf_classifier_cascade_write_binary(ccv_bbf_classifier_cascade_t* cascade, char* s, int slen); /** @} */ /* Ferns classifier: this is a fern implementation that specifically used for TLD * see: http://cvlab.epfl.ch/alumni/oezuysal/ferns.html for more about ferns */ typedef struct { int structs; int features; int scales; int posteriors; float threshold; int cnum[2]; int* rnum; float* posterior; // decided to go flat organized fern so that we can profiling different memory layout impacts the performance ccv_point_t fern[1]; } ccv_ferns_t; CCV_WARN_UNUSED(ccv_ferns_t*) ccv_ferns_new(int structs, int features, int scales, ccv_size_t* sizes); void ccv_ferns_feature(ccv_ferns_t* ferns, ccv_dense_matrix_t* a, int scale, uint32_t* fern); void ccv_ferns_correct(ccv_ferns_t* ferns, uint32_t* fern, int c, int repeat); float ccv_ferns_predict(ccv_ferns_t* ferns, uint32_t* fern); void ccv_ferns_free(ccv_ferns_t* ferns); /* TLD: Track-Learn-Detection is a long-term object tracking framework, which achieved very high * tracking accuracy, this is the tracking algorithm of choice ccv implements */ /** * @defgroup ccv_tld track learn detect * @{ */ typedef struct { /** * @name Short-term lucas-kanade tracking parameters * @{ */ ccv_size_t win_size; /**< The window size to compute optical flow. */ int level; /**< Level of image pyramids */ float min_eigen; /**< The minimal eigenvalue for a valid optical flow computation */ float min_forward_backward_error; /**< The minimal forward backward error */ /** @} */ /** * @name Image pyramid generation parameters (for scale-invariant object detection) * @{ */ int interval; /**< How many intermediate images in between each image pyramid level (from width => width / 2) */ float shift; /**< How much steps sliding window should move */ /** @} */ /** * @name Samples generation parameters * @{ */ int min_win; /**< The minimal window size of patches for detection */ float include_overlap; /**< Above this threshold, a bounding box will be positively identified as overlapping with target */ float exclude_overlap; /**< Below this threshold, a bounding box will be positively identified as not overlapping with target */ /** @} */ /** * @name Ferns classifier parameters * @{ */ int structs; /**< How many ferns in the classifier */ int features; /**< How many features for each fern */ /** @} */ /** * @name Nearest neighbor classifier parameters * @{ */ float validate_set; /**< For the conservative confidence score will be only computed on a subset of all positive examples, this value gives how large that subset should be, 0.5 is a reasonable number */ float nnc_same; /**< Above this threshold, a given patch will be identified as the same */ float nnc_thres; /**< The initial threshold for positively recognize a patch */ float nnc_verify; /**< The threshold for a tracking result from short-term tracker be verified as a positive detection */ float nnc_beyond; /**< The upper bound threshold for adaptive computed threshold */ float nnc_collect; /**< The threshold that a negative patch above this will be collected as negative example */ int bad_patches; /**< How many patches should be evaluated in initialization to collect enough negative examples */ /** @} */ /** * @name Deformation parameters to apply perspective transforms on patches for robustness * @{ */ int new_deform; /**< Number of deformations should be applied at initialization */ int track_deform; /**< Number of deformations should be applied at running time */ float new_deform_angle; /**< The maximal angle for x, y and z axis rotation at initialization */ float track_deform_angle; /**< The maximal angle for x, y and z axis rotation at running time */ float new_deform_scale; /**< The maximal scale for the deformation at initialization */ float track_deform_scale; /**< The maximal scale for the deformation at running time */ float new_deform_shift; /**< The maximal shift for the deformation at initialization */ float track_deform_shift; /**< The maximal shift for the deformation at running time */ /** @} */ /** * @name Speed up parameters * @{ */ int top_n; /**< Only keep these much positive detections when applying ferns classifier */ /* speed up technique, instead of running slide window at * every frame, we will rotate them, for example, slide window 1 * only gets examined at frame % rotation == 1 */ int rotation; /**< When >= 1, using "rotation" technique, which, only evaluate a subset of sliding windows for each frame, but after rotation + 1 frames, every sliding window will be evaluated in one of these frames. */ /** @} */ } ccv_tld_param_t; extern const ccv_tld_param_t ccv_tld_default_params; typedef struct { ccv_tld_param_t params; ccv_comp_t box; // tracking comp ccv_ferns_t* ferns; // ferns classifier ccv_array_t* sv[2]; // example-based classifier ccv_size_t patch; // resized to patch for example-based classifier int found; // if the last time found a valid box int verified; // the last frame is verified, therefore, a successful tracking is verified too ccv_array_t* top; // top matches float ferns_thres; // computed dynamically from negative examples float nnc_thres; // computed dynamically from negative examples float nnc_verify_thres; // computed dynamically from negative examples double var_thres; // computed dynamically from the supplied same uint64_t frame_signature; int count; void* sfmt; void* dsfmt; uint32_t fern_buffer[1]; // fetched ferns from image, this is a buffer } ccv_tld_t; typedef struct { int perform_track; /**< Whether we performed tracking or not this time */ int perform_learn; /**< Whether we performed learning or not this time */ int track_success; /**< If we have a successful tracking (thus, short term tracker works) */ int ferns_detects; /**< How many regions passed ferns classifier */ int nnc_detects; /**< How many regions passed nearest neighbor classifier */ int clustered_detects; /**< After cluster, how many regions left */ int confident_matches; /**< How many matches we have outside of the tracking region (may cause a re-initialization of the short term tracking) */ int close_matches; /**< How many matches we have inside the tracking (may cause a new learning event) */ } ccv_tld_info_t; /** * Create a new TLD tracking instance from a given first frame image and the tracking rectangle. * @param a The first frame image. * @param box The initial tracking rectangle. * @param params A **ccv_tld_param_t** structure that defines various aspects of TLD tracker. * @return A **ccv_tld_t** object holds temporal information about tracking. */ CCV_WARN_UNUSED(ccv_tld_t*) ccv_tld_new(ccv_dense_matrix_t* a, ccv_rect_t box, ccv_tld_param_t params); /** * ccv doesn't have retain / release semantics. Thus, a TLD instance cannot retain the most recent frame it tracks for future reference, you have to pass that in by yourself. * @param tld The TLD instance for continuous tracking * @param a The last frame used for tracking (ccv_tld_track_object will check signature of this against the last frame TLD instance tracked) * @param b The new frame will be tracked * @param info A **ccv_tld_info_t** structure that will records several aspects of current tracking * @return The newly predicted bounding box for the tracking object. */ ccv_comp_t ccv_tld_track_object(ccv_tld_t* tld, ccv_dense_matrix_t* a, ccv_dense_matrix_t* b, ccv_tld_info_t* info); /** * @param tld The TLD instance to be freed. */ void ccv_tld_free(ccv_tld_t* tld); /** @} */ /* ICF: Integral Channels Features, this is a theorized framework that retrospectively incorporates the original * Viola-Jones detection method with various enhancement later. Specifically, this implementation is after: * Pedestrian detection at 100 frames per second, Rodrigo Benenson, Markus Mathias, Radu Timofte and Luc Van Gool * With WFS (width first search) tree from: * High-Performance Rotation Invariant Multiview Face Detection, Chang Huang, Haizhou Ai, Yuan Li and Shihong Lao */ /** * @defgroup ccv_icf integral channel features * @{ */ #define CCV_ICF_SAT_MAX (2) typedef struct { int count; int channel[CCV_ICF_SAT_MAX]; ccv_point_t sat[CCV_ICF_SAT_MAX * 2]; float alpha[CCV_ICF_SAT_MAX]; float beta; } ccv_icf_feature_t; typedef struct { // we use depth-2 decision tree uint32_t pass; ccv_icf_feature_t features[3]; float weigh[2]; float threshold; } ccv_icf_decision_tree_t; enum { CCV_ICF_CLASSIFIER_TYPE_A = 0x1, CCV_ICF_CLASSIFIER_TYPE_B = 0x2, }; typedef struct { int type; int count; int grayscale; ccv_margin_t margin; ccv_size_t size; // this is the size includes the margin ccv_icf_decision_tree_t* weak_classifiers; } ccv_icf_classifier_cascade_t; // Type A, scale image typedef struct { int type; int count; int octave; int grayscale; ccv_icf_classifier_cascade_t* cascade; } ccv_icf_multiscale_classifier_cascade_t; // Type B, scale the classifier typedef struct { int min_neighbors; /**< 0: no grouping afterwards. 1: group objects that intersects each other. > 1: group objects that intersects each other, and only passes these that have at least **min_neighbors** intersected objects. */ int flags; int step_through; /**< The step size for detection. */ int interval; /**< Interval images between the full size image and the half size one. e.g. 2 will generate 2 images in between full size image and half size one: image with full size, image with 5/6 size, image with 2/3 size, image with 1/2 size. */ float threshold; } ccv_icf_param_t; extern const ccv_icf_param_t ccv_icf_default_params; typedef struct { ccv_icf_param_t detector; /**< A **ccv_icf_param_t** structure that defines various aspects of the detector. */ int grayscale; /**< Whether to exploit color in a given image. */ int min_dimension; /**< The minimal size of a ICF feature region. */ ccv_margin_t margin; ccv_size_t size; /**< A **ccv_size_t** structure that defines the width and height of the classifier. */ int feature_size; /**< The number of ICF features to pool from. */ int weak_classifier; /**< The number of weak classifiers that will be used to construct the strong classifier. */ int bootstrap; /**< The number of boostrap to collect negatives. */ float deform_angle; /**< The range of rotations to add distortion, in radius. */ float deform_scale; /**< The range of scale changes to add distortion. */ float deform_shift; /**< The range of translations to add distortion, in pixel. */ double acceptance; /**< The percentage of validation examples will be accepted when soft cascading the classifiers that will be sued for bootstrap. */ } ccv_icf_new_param_t; void ccv_icf(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type); /* ICF for single scale */ /** * Create a new ICF classifier cascade from given positive examples and background images. This function has a hard dependency on [GSL](http://www.gnu.org/software/gsl/) and better be used with [libdispatch](http://libdispatch.macosforge.org/) for maximum efficiency. * @param posfiles An array of **ccv_file_info_t** that gives the positive examples and their locations. * @param posnum The number of positive examples that we want to use (with certain random distortions if so choose). * @param bgfiles An array of **ccv_file_info_t** that gives the background images. * @param negnum The number of negative examples will be collected during bootstrapping / initialization. * @param testfiles An array of **ccv_file_info_t** that gives the validation examples and their locations. * @param dir The directory that saves the progress. * @param params A **ccv_icf_new_param_t** structure that defines various aspects of the training function. * @return A trained classifier cascade. */ CCV_WARN_UNUSED(ccv_icf_classifier_cascade_t*) ccv_icf_classifier_cascade_new(ccv_array_t* posfiles, int posnum, ccv_array_t* bgfiles, int negnum, ccv_array_t* testfiles, const char* dir, ccv_icf_new_param_t params); /** * Compute soft cascade thresholds to speed up the classifier cascade performance. * @param cascade The trained classifier that we want to optimize soft cascade thresholds on. * @param posfiles An array of **ccv_array_t** that gives the positive examples and their locations. * @param acceptance The percentage of positive examples will be accepted when optimizing the soft cascade thresholds. */ void ccv_icf_classifier_cascade_soft(ccv_icf_classifier_cascade_t* cascade, ccv_array_t* posfiles, double acceptance); /** * Read a ICF classifier from a file. * @param filename The file path that contains the trained ICF classifier. * @return The classifier cascade, 0 if no valid classifier cascade available. */ CCV_WARN_UNUSED(ccv_icf_classifier_cascade_t*) ccv_icf_read_classifier_cascade(const char* filename); /** * Write a ICF classifier to a file. * @param classifier The classifier that we want to write to file. * @param filename The file path that we want to persist the ICF classifier. */ void ccv_icf_write_classifier_cascade(ccv_icf_classifier_cascade_t* classifier, const char* filename); /** * Free up the memory of ICF classifier cascade. * @param classifier The ICF classifier cascade. */ void ccv_icf_classifier_cascade_free(ccv_icf_classifier_cascade_t* classifier); /* ICF for multiple scale */ CCV_WARN_UNUSED(ccv_icf_multiscale_classifier_cascade_t*) ccv_icf_multiscale_classifier_cascade_new(ccv_icf_classifier_cascade_t* cascades, int octave, int interval); CCV_WARN_UNUSED(ccv_icf_multiscale_classifier_cascade_t*) ccv_icf_read_multiscale_classifier_cascade(const char* directory); void ccv_icf_write_multiscale_classifier_cascade(ccv_icf_multiscale_classifier_cascade_t* classifier, const char* directory); void ccv_icf_multiscale_classifier_cascade_free(ccv_icf_multiscale_classifier_cascade_t* classifier); /* polymorph function to run ICF based detector */ /** * Using a ICF classifier cascade to detect objects in a given image. If you have several classifier cascades, it is better to use them in one method call. In this way, ccv will try to optimize the overall performance. * @param a The input image. * @param cascade An array of classifier cascades. * @param count How many classifier cascades you've passed in. * @param params A **ccv_icf_param_t** structure that defines various aspects of the detector. * @return A **ccv_array_t** of **ccv_comp_t** with detection results. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_icf_detect_objects(ccv_dense_matrix_t* a, void* cascade, int count, ccv_icf_param_t params); /** @} */ /* SCD: SURF-Cascade Detector * This is a variant of VJ framework for object detection * Read: Learning SURF Cascade for Fast and Accurate Object Detection */ /** * @defgroup ccv_scd surf-cascade detection * @{ */ typedef struct { int sx[4]; int sy[4]; int dx[4]; int dy[4]; float bias; float w[32]; } ccv_scd_stump_feature_t; typedef struct { int count; ccv_scd_stump_feature_t* features; float threshold; } ccv_scd_stump_classifier_t; // this is simpler than ccv's icf feature, largely inspired // by the latest implementation of doppia, it seems more restrictive // approach can generate more robust feature due to the overfitting // nature of decision tree typedef struct { int channel; int sx; int sy; int dx; int dy; float bias; } ccv_scd_tree_feature_t; enum { CCV_SCD_STUMP_FEATURE = 0x01, CCV_SCD_TREE_FEATURE = 0x02, }; typedef struct { int type; uint32_t pass; ccv_scd_stump_feature_t feature; ccv_scd_tree_feature_t node[3]; float beta[6]; float threshold; } ccv_scd_decision_tree_t; typedef struct { int count; ccv_margin_t margin; ccv_size_t size; ccv_scd_stump_classifier_t* classifiers; // the last stage classifier is a hybrid of scd feature with icf-like feature // this is trained as soft-cascade classifier, and select between a depth-2 decision tree // or the scd feature. struct { int count; ccv_scd_decision_tree_t* tree; } decision; } ccv_scd_classifier_cascade_t; typedef struct { int min_neighbors; /**< 0: no grouping afterwards. 1: group objects that intersects each other. > 1: group objects that intersects each other, and only passes these that have at least **min_neighbors** intersected objects. */ int step_through; /**< The step size for detection. */ int interval; /**< Interval images between the full size image and the half size one. e.g. 2 will generate 2 images in between full size image and half size one: image with full size, image with 5/6 size, image with 2/3 size, image with 1/2 size. */ ccv_size_t size; /**< The smallest object size that will be interesting to us. */ } ccv_scd_param_t; typedef struct { int boosting; /**< How many stages of boosting should be performed. */ ccv_size_t size; /**< What's the window size of the final classifier. */ struct { ccv_size_t base; /**< [feature.base] A **ccv_size_t** structure defines the minimal feature dimensions. */ int range_through; /**< [feature.range_through] The step size to increase feature dimensions. */ int step_through; /**< [feature.step_through] The step size to move to cover the whole window size. */ } feature; struct { float hit_rate; /**< [stop_criteria.hit_rate] The targeted hit rate for each stage of classifier. */ float false_positive_rate; /**< [stop_criteria.false_positive_rate] The targeted false positive rate for each stage of classifier. */ float accu_false_positive_rate; /**< [stop_criteria.accu_false_positive_rate] The targeted accumulative false positive rate for classifier cascade, the training will be terminated once the accumulative false positive rate target reached. */ float auc_crit; /**< [stop_criteria.auc_crit] The epsilon to decide if auc (area under curve) can no longer be improved. Once auc can no longer be improved and the targeted false positive rate reached, this stage of training will be terminated and start the next stage training. */ int maximum_feature; /**< [stop_criteria.maximum_feature] Maximum number of features one stage can have. */ int prune_stage; /**< [stop_criteria.prune_stage] How many stages will act as "prune" stage, which means will take minimal effort to prune as much negative areas as possible. */ int prune_feature; /**< [stop_criteria.prune_feature] How many features a prune stage should have, it should be a very small number to enable efficient pruning. */ } stop_criteria; double weight_trimming; /**< Only consider examples with weights in this percentile for training, this avoid to consider examples with tiny weights. */ double C; /**< The C parameter to train the weak linear SVM classifier. */ int grayscale; /**< To train the classifier with grayscale image. */ } ccv_scd_train_param_t; extern const ccv_scd_param_t ccv_scd_default_params; /** * Create a new SCD classifier cascade from given positive examples and background images. This function has a hard dependency on [GSL](http://www.gnu.org/software/gsl/). * @param posfiles An array of **ccv_file_info_t** that gives the positive examples. * @param hard_mine An array of **ccv_file_info_t** that gives images don't contain any positive examples (for example, to train a face detector, these are images that doesn't contain any faces). * @param negative_count Number of negative examples that is harvested from background images. * @param filename The file that saves both progress and final classifier, this will be in sqlite3 database format. * @param params A **ccv_scd_train_param_t** that defines various aspects of the training function. * @return The trained SCD classifier cascade. */ CCV_WARN_UNUSED(ccv_scd_classifier_cascade_t*) ccv_scd_classifier_cascade_new(ccv_array_t* posfiles, ccv_array_t* hard_mine, int negative_count, const char* filename, ccv_scd_train_param_t params); /** * Write SCD classifier cascade to a file. * @param cascade The BBF classifier cascade. * @param filename The file that will be written to, it is in sqlite3 database format. */ void ccv_scd_classifier_cascade_write(ccv_scd_classifier_cascade_t* cascade, const char* filename); /** * Read SCD classifier cascade from file. * @param filename The file that contains a SCD classifier cascade, it is in sqlite3 database format. * @return A classifier cascade, 0 returned if no valid classifier cascade available. */ CCV_WARN_UNUSED(ccv_scd_classifier_cascade_t*) ccv_scd_classifier_cascade_read(const char* filename); /** * Free up the memory of SCD classifier cascade. * @param cascade The SCD classifier cascade. */ void ccv_scd_classifier_cascade_free(ccv_scd_classifier_cascade_t* cascade); /** * Generate 8-channel output matrix which extract SURF features (dx, dy, |dx|, |dy|, du, dv, |du|, |dv|) for input. If input is multi-channel matrix (such as RGB), will pick the strongest responses among these channels. * @param a The input matrix. * @param b The output matrix. * @param type The type of output matrix, if 0, ccv will try to match the input matrix for appropriate type. */ void ccv_scd(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type); /** * Using a SCD classifier cascade to detect objects in a given image. If you have several classifier cascades, it is better to use them in one method call. In this way, ccv will try to optimize the overall performance. * @param a The input image. * @param cascades An array of classifier cascades. * @param count How many classifier cascades you've passed in. * @param params A **ccv_scd_param_t** structure that defines various aspects of the detector. * @return A **ccv_array_t** of **ccv_comp_t** with detection results. */ CCV_WARN_UNUSED(ccv_array_t*) ccv_scd_detect_objects(ccv_dense_matrix_t* a, ccv_scd_classifier_cascade_t** cascades, int count, ccv_scd_param_t params); /** @} */ /* categorization types and methods for training */ enum { CCV_CATEGORIZED_DENSE_MATRIX = 0x01, CCV_CATEGORIZED_FILE = 0x02, }; typedef struct { int c; // class / category label int type; union { ccv_dense_matrix_t* matrix; ccv_file_info_t file; }; } ccv_categorized_t; inline static ccv_categorized_t ccv_categorized(int c, ccv_dense_matrix_t* matrix, ccv_file_info_t* file) { assert((matrix && !file) || (!matrix && file)); ccv_categorized_t categorized; categorized.c = c; if (matrix) categorized.type = CCV_CATEGORIZED_DENSE_MATRIX, categorized.matrix = matrix; else categorized.type = CCV_CATEGORIZED_FILE, categorized.file = *file; return categorized; } /** * @defgroup ccv_convnet deep convolutional networks * This is a implementation of deep convolutional networks mainly for image recognition and object detection. * @{ */ enum { CCV_CONVNET_CONVOLUTIONAL = 0x01, CCV_CONVNET_FULL_CONNECT = 0x02, CCV_CONVNET_MAX_POOL = 0x03, CCV_CONVNET_AVERAGE_POOL = 0x04, CCV_CONVNET_LOCAL_RESPONSE_NORM = 0x05, }; typedef union { struct { int count; /**< [convolutional.count] The number of filters for convolutional layer. */ int strides; /**< [convolutional.strides] The strides for convolutional filter. */ int border; /**< [convolutional.border] The padding border size for the input matrix. */ int rows; /**< [convolutional.rows] The number of rows for convolutional filter. */ int cols; /**< [convolutional.cols] The number of columns for convolutional filter. */ int channels; /**< [convolutional.channels] The number of channels for convolutional filter. */ int partition; /**< [convolutional.partition] The number of partitions for convolutional filter. */ } convolutional; struct { int strides; /**< [pool.strides] The strides for pooling layer. */ int size; /**< [pool.size] The window size for pooling layer. */ int border; /**< [pool.border] The padding border size for the input matrix. */ } pool; struct { int size; /**< [rnorm.size] The size of local response normalization layer. */ float kappa; /**< [rnorm.kappa] As of b[i] = a[i] / (rnorm.kappa + rnorm.alpha * sum(a, i - rnorm.size / 2, i + rnorm.size / 2)) ^ rnorm.beta */ float alpha; /**< [rnorm.alpha] See **rnorm.kappa**. */ float beta; /**< [rnorm.beta] See **rnorm.kappa**. */ } rnorm; struct { int relu; /**< [full_connect.relu] 0 - ReLU, 1 - no ReLU */ int count; /**< [full_connect.count] The number of output nodes for full connect layer. */ } full_connect; } ccv_convnet_type_t; typedef struct { struct { int rows; /**< [matrix.rows] The number of rows of the input matrix. */ int cols; /**< [matrix.cols] The number of columns of the input matrix. */ int channels; /**< [matrix.channels] The number of channels of the input matrix. */ int partition; /**< [matrix.partition] The number of partitions of the input matrix, it must be dividable by the number of channels (it is partitioned by channels). */ } matrix; struct { int count; /**< [node.count] The number of nodes. You should either use **node** or **matrix** to specify the input structure. */ } node; } ccv_convnet_input_t; typedef struct { int type; /**< One of following value to specify the network layer type, **CCV_CONVNET_CONVOLUTIONAL**, **CCV_CONVNET_FULL_CONNECT**, **CCV_CONVNET_MAX_POOL**, **CCV_CONVNET_AVERAGE_POOL**, **CCV_CONVNET_LOCAL_RESPONSE_NORM**. */ float bias; /**< The initialization value for bias if applicable (for convolutional layer and full connect layer). */ float glorot; /**< The truncated uniform distribution coefficients for weights if applicable (for convolutional layer and full connect layer, glorot / sqrt(in + out)). */ ccv_convnet_input_t input; /**< A **ccv_convnet_input_t** specifies the input structure. */ ccv_convnet_type_t output; /**< A **ccv_convnet_type_t** specifies the output parameters and structure. */ } ccv_convnet_layer_param_t; typedef struct { int type; float* w; // weight float* bias; // bias size_t wnum; // the number of weights ccv_convnet_input_t input; // the input requirement ccv_convnet_type_t net; // network configuration void* reserved; } ccv_convnet_layer_t; typedef struct { int use_cwc_accel; // use "ccv with cuda" acceleration // this is redundant, but good to enforcing what the input should look like ccv_size_t input; int rows; int cols; int channels; // count and layer of the convnet int count; ccv_dense_matrix_t* mean_activity; // mean activity to subtract from ccv_convnet_layer_t* layers; // the layer configuration // these can be reused and we don't need to reallocate memory ccv_dense_matrix_t** denoms; // denominators ccv_dense_matrix_t** acts; // hidden layers and output layers void* reserved; } ccv_convnet_t; typedef struct { float decay; /**< See **learn_rate**. */ float learn_rate; /**< New velocity = **momentum** * old velocity - **decay** * **learn_rate** * old value + **learn_rate** * delta, new value = old value + new velocity */ float momentum; /**< See **learn_rate**. */ } ccv_convnet_layer_sgd_param_t; typedef struct { // the dropout rate, I find that dor is better looking than dropout_rate, // and drop out is happened on the input neuron (so that when the network // is used in real-world, I simply need to multiply its weights to 1 - dor // to get the real one) float dor; /**< The dropout rate for this layer, it is only applicable for full connect layer. */ ccv_convnet_layer_sgd_param_t w; /**< A **ccv_convnet_layer_sgd_param_t** specifies the stochastic gradient descent update rule for weight, it is only applicable for full connect layer and convolutional layer. */ ccv_convnet_layer_sgd_param_t bias; /**< A **ccv_convnet_layer_sgd_param_t** specifies the stochastic gradient descent update rule for bias, it is only applicable for full connect layer and convolutional layer weight. */ } ccv_convnet_layer_train_param_t; typedef struct { int max_epoch; /**< The number of epoch (an epoch sweeps through all the examples) to go through before end the training. */ int mini_batch; /**< The number of examples for a batch in stochastic gradient descent. */ int iterations; /**< The number of iterations (an iteration is for one batch) before save the progress. */ int sgd_frequency; /**< After how many batches when we do a SGD update. */ int symmetric; /**< Whether to exploit the symmetric property of the provided examples. */ int device_count; /**< Use how many GPU devices, this is capped by available CUDA devices on your system. For now, ccv's implementation only support up to 4 GPUs */ int peer_access; /**< Enable peer access for cross device communications or not, this will enable faster multiple device training. */ float image_manipulation; /**< The value for image brightness / contrast / saturation manipulations. */ float color_gain; /**< The color variance for data augmentation (0 means no such augmentation). */ struct { int min_dim; /**< [input.min_dim] The minimum dimensions for random resize of training images. */ int max_dim; /**< [input.max_dim] The maximum dimensions for random resize of training images. */ } input; ccv_convnet_layer_train_param_t* layer_params; /**< An C-array of **ccv_convnet_layer_train_param_t** training parameters for each layer. */ } ccv_convnet_train_param_t; typedef struct { int half_precision; /**< Use half precision float point to represent network parameters. */ } ccv_convnet_write_param_t; /** * Create a new (deep) convolutional network with specified parameters. ccv only supports convolutional layer (shared weights), max pooling layer, average pooling layer, full connect layer and local response normalization layer. * @param use_cwc_accel Whether use CUDA-enabled GPU to accelerate various computations for convolutional network. * @param input Ihe input size of the image, it is not necessarily the input size of the first convolutional layer. * @param params[] The C-array of **ccv_convnet_layer_param_t** that specifies the parameters for each layer. * @param count The size of params[] C-array. * @return A new deep convolutional network structs */ CCV_WARN_UNUSED(ccv_convnet_t*) ccv_convnet_new(int use_cwc_accel, ccv_size_t input, ccv_convnet_layer_param_t params[], int count); /** * Verify the specified parameters make sense as a deep convolutional network. * @param convnet A deep convolutional network to verify. * @param output The output number of nodes (for the last full connect layer). * @return 0 if the given deep convolutional network making sense. */ int ccv_convnet_verify(ccv_convnet_t* convnet, int output); /** * Start to train a deep convolutional network with given parameters and data. * @param convnet A deep convolutional network that is initialized. * @param categorizeds An array of images with its category information for training. * @param tests An array of images with its category information for validating. * @param filename The working file to save progress and the trained convolutional network. * @param params A ccv_convnet_train_param_t that specifies the training parameters. */ void ccv_convnet_supervised_train(ccv_convnet_t* convnet, ccv_array_t* categorizeds, ccv_array_t* tests, const char* filename, ccv_convnet_train_param_t params); /** * Use a convolutional network to encode an image into a compact representation. * @param convnet The given convolutional network. * @param a A C-array of input images. * @param b A C-array of output matrix of compact representation. * @param batch The number of input images. */ void ccv_convnet_encode(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, ccv_dense_matrix_t** b, int batch); void ccv_convnet_input_formation(ccv_size_t input, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b); /** * Use a convolutional network to classify an image into categories. * @param convnet The given convolutional network. * @param a A C-array of input images. * @param symmetric Whether the input is symmetric. * @param ranks A C-array of **ccv_array_t** contains top categories by the convolutional network. * @param tops The number of top categories return for each image. * @param batch The number of input images. */ void ccv_convnet_classify(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, int symmetric, ccv_array_t** ranks, int tops, int batch); /** * Read a convolutional network that persisted on the disk. * @param use_cwc_accel Use CUDA-enabled GPU acceleration. * @param filename The file on the disk. */ CCV_WARN_UNUSED(ccv_convnet_t*) ccv_convnet_read(int use_cwc_accel, const char* filename); /** * Write a convolutional network to a disk. * @param convnet A given convolutional network. * @param filename The file on the disk. * @param params A **ccv_convnet_write_param_t** to specify the write parameters. */ void ccv_convnet_write(ccv_convnet_t* convnet, const char* filename, ccv_convnet_write_param_t params); /** * Free up temporary resources of a given convolutional network. * @param convnet A convolutional network. */ void ccv_convnet_compact(ccv_convnet_t* convnet); /** * Free up the memory of a given convolutional network. * @param convnet A convolutional network. */ void ccv_convnet_free(ccv_convnet_t* convnet); /** @} */ /* add for command-line outputs, b/c ccv's training steps has a ton of outputs, * and in the future, it can be piped into callback functions for critical information * (such as the on-going missing rate, or iterations etc.) */ enum { CCV_CLI_ERROR = 1 << 2, CCV_CLI_INFO = 1 << 1, CCV_CLI_VERBOSE = 1, CCV_CLI_NONE = 0, }; int ccv_cli_output_level_and_above(int level); void ccv_cli_set_output_levels(int level); int ccv_cli_get_output_levels(void); #define CCV_CLI_SET_OUTPUT_LEVEL_AND_ABOVE(level) ccv_cli_set_output_levels(ccv_cli_output_level_and_above(level)) #define CCV_CLI_OUTPUT_LEVEL_IS(a) (a & ccv_cli_get_output_levels()) #endif
44.102731
535
0.733657
[ "geometry", "object", "vector", "model", "transform", "3d" ]
a9ab61bc36575b9558c304af2aaeaf89118db884
125
h
C
src/day_1.h
r-ash/aoc
0a4d15fed04262e388f651cd91734c325a49afa1
[ "MIT" ]
null
null
null
src/day_1.h
r-ash/aoc
0a4d15fed04262e388f651cd91734c325a49afa1
[ "MIT" ]
7
2020-01-08T18:21:51.000Z
2020-01-10T16:39:04.000Z
src/day_1.h
r-ash/aoc
0a4d15fed04262e388f651cd91734c325a49afa1
[ "MIT" ]
null
null
null
#ifndef AOC_DAY_1_H #define AOC_DAY_1_H int fuel_required(std::vector<int> masses); int fuel(int mass); #endif AOC_DAY_1_H
15.625
43
0.784
[ "vector" ]
a9b5d9866ae6684df82518065386c8e8da2aabc7
1,278
h
C
GWEN/include/Gwen/Controls/MenuItem.h
hpidcock/gbsfml
e3aa990dff8c6b95aef92bab3e94affb978409f2
[ "Zlib" ]
null
null
null
GWEN/include/Gwen/Controls/MenuItem.h
hpidcock/gbsfml
e3aa990dff8c6b95aef92bab3e94affb978409f2
[ "Zlib" ]
null
null
null
GWEN/include/Gwen/Controls/MenuItem.h
hpidcock/gbsfml
e3aa990dff8c6b95aef92bab3e94affb978409f2
[ "Zlib" ]
null
null
null
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #pragma once #include "Base.h" #include "Gwen/BaseRender.h" #include "Gwen/Controls/Button.h" #include "Gwen/Controls/Menu.h" #include "Gwen/Controls/Symbol.h" namespace Gwen { namespace Controls { class Menu; class GWEN_EXPORT MenuItem : public Button { public: GWEN_CONTROL( MenuItem, Button ); virtual ~MenuItem(); virtual void Render( Skin::Base* skin ); virtual void Layout( Skin::Base* skin ); virtual void OnPress(); Menu* GetMenu(); bool IsMenuOpen(); void OpenMenu(); void CloseMenu(); void ToggleMenu(); void SetOnStrip( bool b ){ m_bOnStrip = b;} bool OnStrip(){ return m_bOnStrip; } virtual void SetCheckable( bool bCheck ) { m_bCheckable = bCheck; } virtual void SetCheck( bool bCheck ); virtual bool GetChecked() { return m_bChecked; } Gwen::Event::Caller onMenuItemSelected; Gwen::Event::Caller onChecked; Gwen::Event::Caller onUnChecked; Gwen::Event::Caller onCheckChange; private: Menu* m_Menu; bool m_bOnStrip; bool m_bCheckable; bool m_bChecked; Symbol::Arrow * m_SubmenuArrow; }; } }
19.363636
72
0.629108
[ "render" ]
a9bb6f0fd5c1582ce4904a478a481a545d2917c9
2,614
h
C
Minuit/Minuit/MnMigrad.h
cdeil/iminuit
8880106e8ba0df18c529c48cd193ba4411ef58b9
[ "MIT" ]
null
null
null
Minuit/Minuit/MnMigrad.h
cdeil/iminuit
8880106e8ba0df18c529c48cd193ba4411ef58b9
[ "MIT" ]
null
null
null
Minuit/Minuit/MnMigrad.h
cdeil/iminuit
8880106e8ba0df18c529c48cd193ba4411ef58b9
[ "MIT" ]
null
null
null
#ifndef MN_MnMigrad_H_ #define MN_MnMigrad_H_ #include "Minuit/MnApplication.h" #include "Minuit/VariableMetricMinimizer.h" class FCNBase; /** API class for minimization using Variable Metric technology ("MIGRAD"); allows for user interaction: set/change parameters, do minimization, change parameters, re-do minimization etc.; also used by MnMinos and MnContours; */ class MnMigrad : public MnApplication { public: /// construct from FCNBase + std::vector for parameters and errors MnMigrad(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra = 1) : MnApplication(fcn, MnUserParameterState(par,err), MnStrategy(stra)), theMinimizer(VariableMetricMinimizer()) {} /// construct from FCNBase + std::vector for parameters and covariance MnMigrad(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow, unsigned int stra = 1) : MnApplication(fcn, MnUserParameterState(par, cov, nrow), MnStrategy(stra)), theMinimizer(VariableMetricMinimizer()) {} /// construct from FCNBase + std::vector for parameters and MnUserCovariance MnMigrad(const FCNBase& fcn, const std::vector<double>& par, const MnUserCovariance& cov, unsigned int stra = 1) : MnApplication(fcn, MnUserParameterState(par, cov), MnStrategy(stra)), theMinimizer(VariableMetricMinimizer()) {} /// construct from FCNBase + MnUserParameters MnMigrad(const FCNBase& fcn, const MnUserParameters& par, unsigned int stra = 1) : MnApplication(fcn, MnUserParameterState(par), MnStrategy(stra)), theMinimizer(VariableMetricMinimizer()) {} /// construct from FCNBase + MnUserParameters + MnUserCovariance MnMigrad(const FCNBase& fcn, const MnUserParameters& par, const MnUserCovariance& cov, unsigned int stra = 1) : MnApplication(fcn, MnUserParameterState(par, cov), MnStrategy(stra)), theMinimizer(VariableMetricMinimizer()) {} /// construct from FCNBase + MnUserParameterState + MnStrategy MnMigrad(const FCNBase& fcn, const MnUserParameterState& par, const MnStrategy& str) : MnApplication(fcn, MnUserParameterState(par), str), theMinimizer(VariableMetricMinimizer()) {} MnMigrad(const MnMigrad& migr) : MnApplication(migr.fcnbase(), migr.state(), migr.strategy(), migr.numOfCalls()), theMinimizer(migr.theMinimizer) {} ~MnMigrad() {} const ModularFunctionMinimizer& minimizer() const {return theMinimizer;} private: VariableMetricMinimizer theMinimizer; private: //forbidden assignment of migrad (const FCNBase& = ) MnMigrad& operator=(const MnMigrad&) {return *this;} }; #endif //MN_MnMigrad_H_
48.407407
257
0.760903
[ "vector" ]
a9bfd7ebecf0d537ba7c1306b7a701541a05ed45
4,792
h
C
src/wire/json/read.h
serhack/monero-lws
faa51780f3f8e6c5c0c4235499b95c246e074f29
[ "BSD-3-Clause" ]
28
2020-09-05T15:50:05.000Z
2022-03-26T23:14:00.000Z
src/wire/json/read.h
serhack/monero-lws
faa51780f3f8e6c5c0c4235499b95c246e074f29
[ "BSD-3-Clause" ]
30
2020-09-23T12:36:39.000Z
2022-02-23T21:24:52.000Z
src/wire/json/read.h
serhack/monero-lws
faa51780f3f8e6c5c0c4235499b95c246e074f29
[ "BSD-3-Clause" ]
9
2020-09-23T19:53:03.000Z
2022-02-27T14:14:25.000Z
// Copyright (c) 2020, The Monero Project // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <boost/utility/string_ref.hpp> #include <cstddef> #include <rapidjson/reader.h> #include <string> #include <type_traits> #include <utility> #include <vector> #include "wire/field.h" #include "wire/json/base.h" #include "wire/read.h" #include "wire/traits.h" namespace wire { //! Reads JSON tokens one-at-a-time for DOMless parsing class json_reader : public reader { struct rapidjson_sax; std::string source_; epee::span<char> current_; rapidjson::Reader reader_; void read_next_value(rapidjson_sax& handler); char get_next_token(); boost::string_ref get_next_string(); //! Skips next value. \throw wire::exception if invalid JSON syntax. void skip_value(); public: explicit json_reader(std::string&& source); //! \throw wire::exception if JSON parsing is incomplete. void check_complete() const override final; //! \throw wire::exception if next token not a boolean. bool boolean() override final; //! \throw wire::expception if next token not an integer. std::intmax_t integer() override final; //! \throw wire::exception if next token not an unsigned integer. std::uintmax_t unsigned_integer() override final; //! \throw wire::exception if next token is not an integer encoded as string std::uintmax_t safe_unsigned_integer(); //! \throw wire::exception if next token not a valid real number double real() override final; //! \throw wire::exception if next token not a string std::string string() override final; //! \throw wire::exception if next token cannot be read as hex std::vector<std::uint8_t> binary() override final; //! \throw wire::exception if next token cannot be read as hex into `dest`. void binary(epee::span<std::uint8_t> dest) override final; //! \throw wire::exception if invalid next token invalid enum. \return Index in `enums`. std::size_t enumeration(epee::span<char const* const> enums) override final; //! \throw wire::exception if next token not `[`. std::size_t start_array() override final; //! Skips whitespace to next token. \return True if next token is eof or ']'. bool is_array_end(std::size_t count) override final; //! \throw wire::exception if next token not `{`. std::size_t start_object() override final; /*! \throw wire::exception if next token not key or `}`. \param[out] index of key match within `map`. \return True if another value to read. */ bool key(epee::span<const key_map> map, std::size_t&, std::size_t& index) override final; }; // Don't call `read` directly in this namespace, do it from `wire_read`. template<typename T> expect<T> json::from_bytes(std::string&& bytes) { json_reader source{std::move(bytes)}; return wire_read::to<T>(source); } // specialization prevents type "downgrading" to base type in cpp files template<typename T> inline void array(json_reader& source, T& dest) { wire_read::array(source, dest); } template<typename... T> inline void object(json_reader& source, T... fields) { wire_read::object(source, wire_read::tracker<T>{std::move(fields)}...); } } // wire
35.496296
93
0.713063
[ "object", "vector" ]
a9c29e075a7d499850216f8f6ac78b6275941c79
1,820
h
C
open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/GetResponseImpl.h
mrehman29/open-vm-tools
03f35e3209b3a73cf8e43a74ac764f22526723a0
[ "X11" ]
2
2020-07-23T06:01:37.000Z
2021-02-25T06:48:42.000Z
open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/GetResponseImpl.h
mrehman29/open-vm-tools
03f35e3209b3a73cf8e43a74ac764f22526723a0
[ "X11" ]
null
null
null
open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/GetResponseImpl.h
mrehman29/open-vm-tools
03f35e3209b3a73cf8e43a74ac764f22526723a0
[ "X11" ]
1
2020-11-11T12:54:06.000Z
2020-11-11T12:54:06.000Z
/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef GETRESPONSEIMPL_H_ #define GETRESPONSEIMPL_H_ #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/GetResponse.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Impelementation of the GetResponse interface * <p> * A class to bundle together the information from a received message. The content is * packaged into an Envelope, BasicProperties and the body for easier consumption as * a single unit. */ class GetResponseImpl : public GetResponse { public: GetResponseImpl(); virtual ~GetResponseImpl(); /** * @brief Object initializer * @param envelope the message envelope * @param properties the messsage properties * @param body the message body in raw bytes * @param messageCount the number of messages remaining in the queue */ void init( const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body, const uint32 messageCount); public: // GetResponse SmartPtrEnvelope getEnvelope(); AmqpContentHeaders::SmartPtrBasicProperties getProperties(); SmartPtrCDynamicByteArray getBody(); uint32 getMessageCount(); private: bool _isInitialized; SmartPtrEnvelope _envelope; AmqpContentHeaders::SmartPtrBasicProperties _properties; SmartPtrCDynamicByteArray _body; uint32 _messageCount; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(GetResponseImpl); }; CAF_DECLARE_SMART_POINTER(GetResponseImpl); }} #endif /* GETRESPONSEIMPL_H_ */
27.164179
86
0.775275
[ "object" ]
a9c2ac9adb9f215d9f5896e49b7a4dc69aeaf32a
17,787
h
C
src/rbSimLib/Joint3D.h
yck011522/modular_ik_solver
285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3
[ "MIT" ]
null
null
null
src/rbSimLib/Joint3D.h
yck011522/modular_ik_solver
285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3
[ "MIT" ]
null
null
null
src/rbSimLib/Joint3D.h
yck011522/modular_ik_solver
285020b6e549d7fb8c3acc6b54bfd90ff3a43fd3
[ "MIT" ]
null
null
null
#pragma once //TODO Refactor this file to separate Joints 2D and Joints 3D #include "RigidBody3D.h" #include <vector> using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::VectorXd; using Eigen::MatrixXd; class HingeJoint2Pt { public: const static int NumConstraints = 6; const static int NumStates = 12; //1 RigidBody is 6 states. 2 RigidBody is 12 states. HingeJoint2Pt(){ } HingeJoint2Pt(int rb0Idx, int rb1Idx, Vector3d rb0Pt0, Vector3d rb0Pt1, Vector3d rb1Pt0, Vector3d rb1Pt1) : rb0Idx(rb0Idx), rb1Idx(rb1Idx), rb0Pt0(rb0Pt0), rb0Pt1(rb0Pt1), rb1Pt0(rb1Pt0), rb1Pt1(rb1Pt1){ } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { Vector3d errorPt0 = rb1.pWorld(x, rb1Pt0) - rb0.pWorld(x, rb0Pt0); Vector3d errorPt1 = rb1.pWorld(x, rb1Pt1) - rb0.pWorld(x, rb0Pt1); Eigen::VectorXd c(6); c.segment<3>(0) = errorPt0; c.segment<3>(3) = errorPt1; return c; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { MatrixXd dCdx(NumConstraints, NumStates); //Jacobian for Pt0 Matrix<double, 3, 6> pt0_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt0); Matrix<double, 3, 6> pt0_dpWorld_dxrb1 = rb1.dpWorld_dx(x, rb1Pt0); dCdx.block<3, 6>(0, 0) = pt0_dpWorld_dxrb0 * -1.0; dCdx.block<3, 6>(0, 6) = pt0_dpWorld_dxrb1; //Jacobian for Pt1 Matrix<double, 3, 6> pt1_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt1); Matrix<double, 3, 6> pt1_dpWorld_dxrb1 = rb1.dpWorld_dx(x, rb1Pt1); dCdx.block<3, 6>(3, 0) = pt1_dpWorld_dxrb0 * -1.0; dCdx.block<3, 6>(3, 6) = pt1_dpWorld_dxrb1; return dCdx; } public: int rb0Idx, rb1Idx; Vector3d rb0Pt0, rb0Pt1, rb1Pt0, rb1Pt1; int constraintID; }; class PointOnLineJoint { public: const static int NumConstraints = 3; const static int NumStates = 12; //1 RigidBody is 6 states. 2 RigidBody is 12 states. PointOnLineJoint() { } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { Eigen::VectorXd c(3); //Point on Line Constraint by Cross Product Vector3d VectorFixed = rb0.pWorld(x, rb0Pt1) - rb0.pWorld(x, rb0Pt0); Vector3d VectorMoving = rb1.pWorld(x, rb1Pt0) - rb0.pWorld(x, rb0Pt0); c.segment<3>(0) = VectorFixed.cross(VectorMoving); return c; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { MatrixXd dCdx(NumConstraints, NumStates); Vector3d U = rb0.pWorld(x, rb0Pt1) - rb0.pWorld(x, rb0Pt0); //VectorFixed Vector3d V = rb1.pWorld(x, rb1Pt0) - rb0.pWorld(x, rb0Pt0); //VectorMoving // Deravitive of the two vectors. Matrix<double, 3, 6> du_drb0 = rb0.dpWorld_dx(x, rb0Pt1) - rb0.dpWorld_dx(x, rb0Pt0); Matrix<double, 3, 6> dv_drb0 = -1 * rb0.dpWorld_dx(x, rb0Pt0); Matrix<double, 3, 6> dv_drb1 = rb1.dpWorld_dx(x, rb1Pt0); //Partial derivative of Cross Product between the two vectors for (int s = 0; s < 6; s++) // Concerning RB0 dCdx.block<3, 1>(0, s) = du_drb0.block<3, 1>(0, s).cross(V) + U.cross(dv_drb0.block<3, 1>(0, s)); for (int s = 0; s < 6; s++) // Converning RB1 dCdx.block<3, 1>(0, s+6) = U.cross(dv_drb1.block<3, 1>(0, s)); return dCdx; } public: int rb0Idx, rb1Idx; Vector3d rb0Pt0, rb0Pt1, rb1Pt0; int constraintID; }; class FixedJoint3Pt { public: const static int NumConstraints = 9; const static int NumStates = 12; //1 RigidBody is 6 states. 2 RigidBody is 12 states. FixedJoint3Pt(int rb0Idx, int rb1Idx, Vector3d rb0Pt0, Vector3d rb0Pt1, Vector3d rb0Pt2, Vector3d rb1Pt0, Vector3d rb1Pt1, Vector3d rb1Pt2) : rb0Idx(rb0Idx), rb1Idx(rb1Idx), rb0Pts({ rb0Pt0, rb0Pt1, rb0Pt2 }), rb1Pts({ rb1Pt0, rb1Pt1, rb1Pt2 }) { } //Construct object from the relative location of rb1's coordinate frame, expressed in rb0's coordinates. FixedJoint3Pt(int rb0Idx, int rb1Idx, Vector3d rb1Origin, Vector3d rb1X, Vector3d rb1Y) : rb0Idx(rb0Idx), rb1Idx(rb1Idx), rb0Pts({ rb1Origin, rb1X, rb1Y }){ rb1Pts = { Vector3d(0,0,0), Vector3d(1,0,0), Vector3d(0,1,0) }; } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { Eigen::VectorXd c(rb0Pts.size() * 3); for (size_t i = 0; i < rb0Pts.size(); ++i) { c.segment<3>(i * 3) = rb1.pWorld(x, rb1Pts[i]) - rb0.pWorld(x, rb0Pts[i]); } return c; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx], rigidBodies[rb1Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0, const RigidBody3D &rb1) const { Matrix <double, NumConstraints, NumStates> dCdx; //Jacobian for Pt0 for (size_t i = 0; i < rb0Pts.size(); ++i) { dCdx.block<3, 6>(i*3, 0) = rb0.dpWorld_dx(x, rb0Pts[i]) * -1.0; dCdx.block<3, 6>(i*3, 6) = rb1.dpWorld_dx(x, rb1Pts[i]); } return dCdx; } public: int rb0Idx, rb1Idx; std::array<Vector3d, 3> rb0Pts; std::array<Vector3d, 3> rb1Pts; int constraintID; }; class FixedBody3Pt { public: const static int NumConstraints = 9; const static int NumStates = 6; //1 RigidBody is 6 states. 2 RigidBody is 12 states. FixedBody3Pt(int rb0Idx, Vector3d rb0Pt0, Vector3d rb0Pt1, Vector3d rb0Pt2, Vector3d worldPt0, Vector3d worldPt1, Vector3d worldPt2) : rb0Idx(rb0Idx), rb0Pt0(rb0Pt0), rb0Pt1(rb0Pt1), rb0Pt2(rb0Pt2), worldPt0(worldPt0), worldPt1(worldPt1), worldPt2(worldPt2) { } //Construct object from the relative location of rb0's coordinate frame, expressed in world coordinates. FixedBody3Pt(int rb0Idx, Vector3d rb0Origin, Vector3d rb0X, Vector3d rb0Y) : rb0Idx(rb0Idx), worldPt0(rb0Origin), worldPt1(rb0X), worldPt2(rb0Y) { rb0Pt0 = Vector3d(0, 0, 0); rb0Pt1 = Vector3d(1, 0, 0); rb0Pt2 = Vector3d(0, 1, 0); //cout << "rb0Idx: " << endl << rb0Idx << endl; //cout << "rb0Pts0: " << endl << rb0Pts[0] << endl; //cout << "rb0Pts1: " << endl << rb0Pts[1] << endl; //cout << "rb0Pts2: " << endl << rb0Pts[2] << endl; //cout << "worldPt0: " << endl << worldPts[0] << endl; //cout << "worldPt1: " << endl << worldPts[1] << endl; //cout << "worldPt2: " << endl << worldPts[2] << endl; } FixedBody3Pt(const RigidBody3D &rb, const VectorXd &x) { Vector3d rb0Origin = rb.pWorld(x, Vector3d(0, 0, 0)); Vector3d rb0X = rb.pWorld(x, Vector3d(1, 0, 0)); Vector3d rb0Y = rb.pWorld(x, Vector3d(0, 1, 0)); std::cout << "FixedBody3Pt constructor rb0Idx: " << rb.rbIdx << endl; FixedBody3Pt(rb.rbIdx, rb0Origin, rb0X, rb0Y); } FixedBody3Pt(){} public: void inline fixHere(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) { rb0Pt0 = Vector3d(0, 0, 0); rb0Pt1 = Vector3d(1, 0, 0); rb0Pt2 = Vector3d(0, 1, 0); worldPt0 = rigidBodies[rb0Idx].pWorld(x, rb0Pt0); worldPt1 = rigidBodies[rb0Idx].pWorld(x, rb0Pt1); worldPt2 = rigidBodies[rb0Idx].pWorld(x, rb0Pt2); } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0) const { Eigen::VectorXd c(NumConstraints); //for (size_t i = 0; i < rb0Pts.size(); ++i) { //std::cout << "FixedBody3Pt computeConstraints worldPts : " << worldPts[i] << endl; //std::cout << "FixedBody3Pt computeConstraints rb0.pWorld : " << rb0.pWorld(x, rb0Pts[i]) << endl; c.segment<3>(0) = worldPt0 - rb0.pWorld(x, rb0Pt0); c.segment<3>(3) = worldPt1 - rb0.pWorld(x, rb0Pt1); c.segment<3>(6) = worldPt2 - rb0.pWorld(x, rb0Pt2); return c; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const std::vector<RigidBody3D> &rigidBodies) const { //std::cout << "FixedBody3Pt computeConstraints rb0Idx: " << rb0Idx; //return computeJacobian(x, rigidBodies[rb0Idx]); //Test to see if this is the problem Matrix <double, NumConstraints, NumStates> dCdx; dCdx.block<3, 6>(0, 0) = rigidBodies[rb0Idx].dpWorld_dx(x, rb0Pt0) * -1.0; dCdx.block<3, 6>(3, 0) = rigidBodies[rb0Idx].dpWorld_dx(x, rb0Pt1) * -1.0; dCdx.block<3, 6>(6, 0) = rigidBodies[rb0Idx].dpWorld_dx(x, rb0Pt2) * -1.0; return dCdx; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0) const { Matrix <double, NumConstraints, NumStates> dCdx; dCdx.block<3, 6>(0, 0) = rb0.dpWorld_dx(x, rb0Pt0) * -1.0; dCdx.block<3, 6>(3, 0) = rb0.dpWorld_dx(x, rb0Pt1) * -1.0; dCdx.block<3, 6>(6, 0) = rb0.dpWorld_dx(x, rb0Pt2) * -1.0; return dCdx; } public: int rb0Idx; Vector3d rb0Pt0; Vector3d rb0Pt1; Vector3d rb0Pt2; Vector3d worldPt0; Vector3d worldPt1; Vector3d worldPt2; int constraintID; }; class Target1Pt { public: const static int NumConstraints = 3; // 1 Point Coincide is 3 Constraints, 2Pt = 6Constraints, 3Pt = 9Constraints const static int NumStates = 6; // 1 RigidBody is 6 states. 2 RigidBody is 12 states. Target1Pt(int rb0Idx, Vector3d rb0Pt0, Vector3d worldPt0) : rb0Idx(rb0Idx), worldPt0(worldPt0) { } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0) const { Vector3d errorPt0 = worldPt0 - rb0.pWorld(x, rb0Pt0); Eigen::VectorXd c(3); c.segment<3>(0) = errorPt0; return c; } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0) const { Matrix <double, NumConstraints, NumStates> dCdx; Matrix<double, 3, 6> pt0_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt0); dCdx.block<3, 6>(0, 0) = pt0_dpWorld_dxrb0 * -1.0; return dCdx; } public: int rb0Idx; Vector3d rb0Pt0, worldPt0; int constraintID; }; class ProgressiveTarget1Pt { public: const static int NumConstraints = 3; // 1 Point Coincide is 3 Constraints, 2Pt = 6Constraints, 3Pt = 9Constraints const static int NumStates = 6; // 1 RigidBody is 6 states. 2 RigidBody is 12 states. ProgressiveTarget1Pt(int rb0Idx, Vector3d rb0Pt0, Vector3d worldPt0, double _progressiveAlpha) : rb0Idx(rb0Idx), finalWorldPt0(worldPt0), progressiveAlpha(_progressiveAlpha) { } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0) const { Vector3d errorPt0 = worldPt0 - rb0.pWorld(x, rb0Pt0); //std::cout << "errorPt0.norm()= " << errorPt0.norm() << endl; Eigen::VectorXd c(3); c.segment<3>(0) = errorPt0; return c; } bool setProgressiveWorldPt(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) { return setProgressiveWorldPt(x, rigidBodies[rb0Idx]); } bool setProgressiveWorldPt(const VectorXd &x, const RigidBody3D &rb0) { Vector3d targetVector = finalWorldPt0 - rb0.pWorld(x, rb0Pt0); double error = targetVector.norm(); if (error > progressiveAlpha) { targetVector = targetVector.normalized() * progressiveAlpha; worldPt0 = rb0.pWorld(x, rb0Pt0) + targetVector; //std::cout << "ProgressiveWorldPt: finalWorldPt0 =" << finalWorldPt0[0] << "," << finalWorldPt0[1] << "," << finalWorldPt0[2]; //std::cout << " worldPt0 = " << worldPt0[0] << "," << worldPt0[1] << "," << worldPt0[2]; //std::cout << " errorNorm = " << error << endl; return false; } else { worldPt0 = finalWorldPt0; //std::cout << "ProgressiveWorldPt: Final Target is set" << endl; return true; //If the final target is set. } } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0) const { Matrix <double, NumConstraints, NumStates> dCdx; Matrix<double, 3, 6> pt0_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt0); dCdx.block<3, 6>(0, 0) = pt0_dpWorld_dxrb0 * -1.0; //std::cout << "computeJacobian" << endl; return dCdx; } public: int rb0Idx; Vector3d rb0Pt0, worldPt0, finalWorldPt0; double progressiveAlpha = 100; int constraintID; }; class ProgressiveTarget3Pt { public: const static int NumConstraints = 9; // 1 Point Coincide is 3 Constraints, 2Pt = 6Constraints, 3Pt = 9Constraints const static int NumStates = 6; // 1 RigidBody is 6 states. 2 RigidBody is 12 states. ProgressiveTarget3Pt() { } ProgressiveTarget3Pt(int rb0Idx) //, Vector3d rb0Pt0, Vector3d rb0Pt1, Vector3d rb0Pt2, Vector3d worldPt0, Vector3d worldPt1, Vector3d worldPt2, int _numTargetPoints, double _progressiveAlpha) : rb0Idx(rb0Idx){ //rb0Pt0(rb0Pt0), rb0Pt1(rb0Pt1), rb0Pt2(rb0Pt2), //finalWorldPt0(worldPt0), finalWorldPt1(worldPt1), finalWorldPt2(worldPt2), //numTargetPoints(_numTargetPoints), progressiveAlpha(_progressiveAlpha) { } VectorXd computeConstraints(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeConstraints(x, rigidBodies[rb0Idx]); } VectorXd computeConstraints(const VectorXd &x, const RigidBody3D &rb0) const { Vector3d errorPt0 = worldPt0 - rb0.pWorld(x, rb0Pt0); Vector3d errorPt1 = worldPt1 - rb0.pWorld(x, rb0Pt1); Vector3d errorPt2 = worldPt2 - rb0.pWorld(x, rb0Pt2); //std::cout << "errorPt0.norm()= " << errorPt0.norm() << endl; Eigen::VectorXd c(9); c.setZero(); c.segment<3>(0) = errorPt0; if (numTargetPoints > 1)c.segment<3>(3) = errorPt1; if (numTargetPoints > 2)c.segment<3>(6) = errorPt2; return c; } bool setProgressiveWorldPt(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) { return setProgressiveWorldPt(x, rigidBodies[rb0Idx]); } //This will move the WorldPoint towards the final worldPoint by the amount set by progressiveAlpha bool setProgressiveWorldPt(const VectorXd &x, const RigidBody3D &rb0) { Vector3d targetVector = finalWorldPt0 - rb0.pWorld(x, rb0Pt0); double error = targetVector.norm(); //std::cout << " Distance to Target (errorNorm) = " << error << endl; if (error > progressiveAlpha) { //Set vector length according to one Vector derived from Point 0 targetVector = targetVector.normalized() * progressiveAlpha; worldPt0 = rb0.pWorld(x, rb0Pt0) + targetVector; worldPt1 = rb0.pWorld(x, rb0Pt1) + targetVector; worldPt2 = rb0.pWorld(x, rb0Pt2) + targetVector; //std::cout << "ProgressiveWorldPt: finalWorldPt0 =" << finalWorldPt0[0] << "," << finalWorldPt0[1] << "," << finalWorldPt0[2] << "; "; //std::cout << " worldPt0 = " << worldPt0[0] << "," << worldPt0[1] << "," << worldPt0[2] << endl; return false; } else { worldPt0 = finalWorldPt0; worldPt1 = finalWorldPt1; worldPt2 = finalWorldPt2; //std::cout << "ProgressiveWorldPt: Final Target is set" << endl; //std::cout << "ProgressiveWorldPt: finalWorldPt0 =" << finalWorldPt0[0] << "," << finalWorldPt0[1] << "," << finalWorldPt0[2] << endl; return true; //If the final target is set. } } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd &x, const std::vector<RigidBody3D> &rigidBodies) const { return computeJacobian(x, rigidBodies[rb0Idx]); } Matrix <double, NumConstraints, NumStates> computeJacobian(const VectorXd x, const RigidBody3D &rb0) const { Matrix <double, NumConstraints, NumStates> dCdx; dCdx.setZero(); Matrix<double, 3, 6> pt0_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt0); Matrix<double, 3, 6> pt1_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt1); Matrix<double, 3, 6> pt2_dpWorld_dxrb0 = rb0.dpWorld_dx(x, rb0Pt2); dCdx.block<3, 6>(0, 0) = pt0_dpWorld_dxrb0 * -1.0; if (numTargetPoints > 1) dCdx.block<3, 6>(3, 0) = pt1_dpWorld_dxrb0 * -1.0; if (numTargetPoints > 2) dCdx.block<3, 6>(6, 0) = pt2_dpWorld_dxrb0 * -1.0; //std::cout << "computeJacobian" << endl; return dCdx; } public: int rb0Idx; int numTargetPoints; // This constraint can be programmed to constraint 1 or 2 or 3 points. Achieving Positional, CoAxle and Frame Targets. Vector3d rb0Pt0, rb0Pt1, rb0Pt2; // This the local coordinate on Rigidbody Vector3d worldPt0, worldPt1, worldPt2; // This is the world coordinate on the immediate target (If progressive Alpha is engaged) Vector3d finalWorldPt0, finalWorldPt1, finalWorldPt2; // This is the final World Coordinate where target should finally reach. double progressiveAlpha = 100; // This is the amount of move per progressive step for point0 to move forward. int constraintID; };
37.446316
193
0.706471
[ "object", "vector", "3d" ]
a9c72cc35f98d68ec9dbbf938053750640a3bd31
85,443
c
C
src/tests/suite/daos_dist_tx.c
fedepad/daos
ac71a320b8426b1eeb1457b0b6f5e6e115dfc9aa
[ "BSD-2-Clause-Patent" ]
1
2021-12-14T16:11:52.000Z
2021-12-14T16:11:52.000Z
src/tests/suite/daos_dist_tx.c
fedepad/daos
ac71a320b8426b1eeb1457b0b6f5e6e115dfc9aa
[ "BSD-2-Clause-Patent" ]
2
2021-05-20T16:08:50.000Z
2021-06-24T16:47:39.000Z
src/tests/suite/daos_dist_tx.c
fedepad/daos
ac71a320b8426b1eeb1457b0b6f5e6e115dfc9aa
[ "BSD-2-Clause-Patent" ]
null
null
null
/** * (C) Copyright 2020-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * This file is part of daos * * tests/suite/daos_dist_tx.c */ #define D_LOGFAC DD_FAC(tests) #include "daos_test.h" #include "daos_iotest.h" #include <daos/dtx.h> #define MUST(rc) assert_int_equal(rc, 0) #define DTX_TEST_SUB_REQS 32 #define DTX_IO_SMALL 32 #define DTX_NC_CNT 10 D_CASSERT(DTX_NC_CNT % IOREQ_SG_IOD_NR == 0); static const char *dts_dtx_dkey = "dtx_dkey"; static const char *dts_dtx_akey = "dtx_akey"; static void dtx_1(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_bufs[DTX_TEST_SUB_REQS][DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int i; print_message("DTX1: multiple SV update against the same obj\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); /* Repeatedly insert different SV for the same obj, overwrite. */ for (i = 0; i < DTX_TEST_SUB_REQS; i++) { dts_buf_render(write_bufs[i], DTX_IO_SMALL); insert_single(dkey, akey, 0, write_bufs[i], DTX_IO_SMALL, th, &req); } MUST(daos_tx_commit(th, NULL)); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); /* The last value will be fetched. */ assert_memory_equal(write_bufs[DTX_TEST_SUB_REQS - 1], fetch_buf, DTX_IO_SMALL); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_2(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_bufs[DTX_TEST_SUB_REQS][DTX_IO_SMALL * 2]; char fetch_buf[DTX_IO_SMALL * (DTX_TEST_SUB_REQS + 1)]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int i; print_message("DTX2: multiple EV update against the same obj\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); /* Repeatedly insert different SV for the same obj, some overlap. */ for (i = 0; i < DTX_TEST_SUB_REQS; i++) { dts_buf_render(write_bufs[i], DTX_IO_SMALL * 2); insert_single_with_rxnr(dkey, akey, i, write_bufs[i], DTX_IO_SMALL, 2, th, &req); } MUST(daos_tx_commit(th, NULL)); lookup_single_with_rxnr(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DTX_IO_SMALL * (DTX_TEST_SUB_REQS + 1), DAOS_TX_NONE, &req); for (i = 0; i < DTX_TEST_SUB_REQS - 1; i++) assert_memory_equal(&write_bufs[i], &fetch_buf[i * DTX_IO_SMALL], DTX_IO_SMALL); assert_memory_equal(&write_bufs[DTX_TEST_SUB_REQS - 1], &fetch_buf[DTX_IO_SMALL * (DTX_TEST_SUB_REQS - 1)], DTX_IO_SMALL * 2); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_update_multiple_objs(test_arg_t *arg, daos_iod_type_t i_type, uint32_t size, daos_oclass_id_t oclass) { const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char *write_bufs[DTX_TEST_SUB_REQS]; char *fetch_buf; daos_handle_t th = { 0 }; daos_obj_id_t oids[DTX_TEST_SUB_REQS]; struct ioreq reqs[DTX_TEST_SUB_REQS]; int i; MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; for (i = 0; i < DTX_TEST_SUB_REQS; i++) { oids[i] = daos_test_oid_gen(arg->coh, oclass, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], i_type, arg); D_ALLOC(write_bufs[i], size); assert_non_null(write_bufs[i]); dts_buf_render(write_bufs[i], size); insert_single(dkey, akey, 0, write_bufs[i], size, th, &reqs[i]); } MUST(daos_tx_commit(th, NULL)); D_ALLOC(fetch_buf, size); assert_non_null(fetch_buf); for (i = 0; i < DTX_TEST_SUB_REQS; i++) { lookup_single(dkey, akey, 0, fetch_buf, size, DAOS_TX_NONE, &reqs[i]); assert_memory_equal(write_bufs[i], fetch_buf, size); } for (i = 0; i < DTX_TEST_SUB_REQS; i++) { D_FREE(write_bufs[i]); ioreq_fini(&reqs[i]); } D_FREE(fetch_buf); MUST(daos_tx_close(th, NULL)); } static void dtx_3(void **state) { print_message("DTX3: Multiple small SV update against multiple objs\n"); dtx_update_multiple_objs(*state, DAOS_IOD_SINGLE, 1 << 6, OC_S1); } static void dtx_4(void **state) { print_message("DTX4: Multiple large EV update against multiple objs\n"); dtx_update_multiple_objs(*state, DAOS_IOD_ARRAY, 1 << 12, OC_S1); } static void dtx_5(void **state) { test_arg_t *arg = *state; print_message("DTX5: Multiple small SV update on multiple EC objs\n"); if (!test_runable(arg, 3)) skip(); dtx_update_multiple_objs(arg, DAOS_IOD_SINGLE, 1 << 8, OC_EC_2P1G1); } static void dtx_6(void **state) { test_arg_t *arg = *state; print_message("DTX6: Multiple large EV update on multiple EC objs\n"); if (!test_runable(arg, 3)) skip(); dtx_update_multiple_objs(arg, DAOS_IOD_ARRAY, 1 << 16, OC_EC_2P1G1); } static void dtx_7(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("DTX7: SV update plus punch\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); punch_akey(dkey, akey, th, &req); MUST(daos_tx_commit(th, NULL)); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); assert_int_equal(req.iod[0].iod_size, 0); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_8(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_bufs[2][DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL * 2]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("DTX8: EV update plus punch\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); dts_buf_render(write_bufs[0], DTX_IO_SMALL); insert_single(dkey, akey, 0, write_bufs[0], DTX_IO_SMALL, th, &req); punch_akey(dkey, akey, th, &req); dts_buf_render(write_bufs[1], DTX_IO_SMALL); insert_single(dkey, akey, 1, write_bufs[1], DTX_IO_SMALL, th, &req); MUST(daos_tx_commit(th, NULL)); memset(fetch_buf, 0, DTX_IO_SMALL); memset(write_bufs[0], 0, DTX_IO_SMALL); lookup_single_with_rxnr(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DTX_IO_SMALL * 2, DAOS_TX_NONE, &req); assert_memory_equal(write_bufs[0], fetch_buf, DTX_IO_SMALL); assert_memory_equal(write_bufs[1], &fetch_buf[DTX_IO_SMALL], DTX_IO_SMALL); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_9(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_bufs[2][DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL * 2]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("DTX9: conditional insert/update\n"); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); dts_buf_render(write_bufs[0], DTX_IO_SMALL); arg->expect_result = -DER_NONEXIST; insert_single_with_flags(dkey, akey, 0, write_bufs[0], DTX_IO_SMALL, th, &req, DAOS_COND_DKEY_UPDATE); arg->expect_result = 0; insert_single_with_flags(dkey, akey, 0, write_bufs[0], DTX_IO_SMALL, th, &req, DAOS_COND_DKEY_INSERT); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); dts_buf_render(write_bufs[1], DTX_IO_SMALL); arg->expect_result = -DER_EXIST; insert_single_with_flags(dkey, akey, 1, write_bufs[1], DTX_IO_SMALL, th, &req, DAOS_COND_AKEY_INSERT); arg->expect_result = 0; insert_single_with_flags(dkey, akey, 1, write_bufs[1], DTX_IO_SMALL, th, &req, DAOS_COND_AKEY_UPDATE); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); lookup_single_with_rxnr(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DTX_IO_SMALL * 2, DAOS_TX_NONE, &req); assert_memory_equal(write_bufs[0], fetch_buf, DTX_IO_SMALL); assert_memory_equal(write_bufs[1], &fetch_buf[DTX_IO_SMALL], DTX_IO_SMALL); MPI_Barrier(MPI_COMM_WORLD); ioreq_fini(&req); } static void dtx_10(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; const char *dkey2 = "tmp_dkey"; const char *akey2 = "tmp_akey"; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("DTX10: conditional punch\n"); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->expect_result = -DER_NONEXIST; punch_akey_with_flags(dkey2, akey2, th, &req, DAOS_COND_PUNCH); arg->expect_result = 0; punch_akey_with_flags(dkey, akey, th, &req, DAOS_COND_PUNCH); arg->expect_result = -DER_NONEXIST; punch_dkey_with_flags(dkey2, th, &req, DAOS_COND_PUNCH); /** Remove the test for the dkey because it can't work with client * side caching and punch propagation. The dkey will have been * removed by the akey punch above. The problem is the server * doesn't know that due to caching so there is no way to make it * work. */ MUST(daos_tx_commit(th, NULL)); arg->expect_result = 0; lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); assert_int_equal(req.iod[0].iod_size, 0); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_11(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; const char *dkey2 = "tmp_dkey"; const char *akey2 = "tmp_akey"; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("DTX11: read only transaction\n"); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); insert_single(dkey2, akey, 0, write_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); MUST(daos_tx_open(arg->coh, &th, DAOS_TF_RDONLY, NULL)); arg->expect_result = -DER_NO_PERM; insert_single(dkey, akey2, 0, write_buf, DTX_IO_SMALL, th, &req); punch_akey(dkey, akey, th, &req); arg->expect_result = 0; lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, th, &req); assert_int_equal(req.iod[0].iod_size, DTX_IO_SMALL); lookup_single(dkey, akey2, 0, fetch_buf, DTX_IO_SMALL, th, &req); assert_int_equal(req.iod[0].iod_size, 0); MUST(daos_tx_commit(th, NULL)); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_12(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; const char *akey2 = "tmp_akey"; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int i; print_message("DTX12: zero copy flag\n"); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_open(arg->coh, &th, DAOS_TF_ZERO_COPY, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); /* Reuse 'write_buf' */ for (i = 0; i < DTX_IO_SMALL; i++) write_buf[i] += 1; insert_single(dkey, akey2, 0, write_buf, DTX_IO_SMALL, th, &req); MUST(daos_tx_commit(th, NULL)); lookup_single(dkey, akey2, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); assert_memory_equal(write_buf, fetch_buf, DTX_IO_SMALL); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); /* 'write_buf' has been overwritten, so it is the same as 2nd update. * * XXX: It is just for test purpose, but not the promised hehavior to * application for the case of reuse buffer with ZERO_COPY flag. */ assert_memory_equal(write_buf, fetch_buf, DTX_IO_SMALL); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_13(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int rc; print_message("DTX13: DTX status machnie\n"); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); dts_buf_render(write_buf, DTX_IO_SMALL); print_message("Open the TX1...\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); print_message("Commit the empty TX1...\n"); MUST(daos_tx_commit(th, NULL)); print_message("Commit the committed TX1...\n"); rc = daos_tx_commit(th, NULL); assert_rc_equal(rc, -DER_ALREADY); print_message("Abort the committed TX1, expect DER_NO_PERM\n"); rc = daos_tx_abort(th, NULL); assert_rc_equal(rc, -DER_NO_PERM); print_message("Restart the committed TX1, expect DER_NO_PERM\n"); rc = daos_tx_restart(th, NULL); assert_rc_equal(rc, -DER_NO_PERM); print_message("Update against the committed TX1, expect DER_NO_PERM\n"); arg->expect_result = -DER_NO_PERM; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); print_message("Fetch against the committed TX1, expect DER_NO_PERM\n"); arg->expect_result = -DER_NO_PERM; lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, th, &req); print_message("Close the TX1...\n"); MUST(daos_tx_close(th, NULL)); print_message("Open the TX2...\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); print_message("Update via the TX2...\n"); arg->expect_result = 0; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); print_message("Restart the TX2, expect DER_NO_PERM\n"); rc = daos_tx_restart(th, NULL); assert_rc_equal(rc, -DER_NO_PERM); print_message("Abort the TX2...\n"); MUST(daos_tx_abort(th, NULL)); print_message("Abort the TX2 again...\n"); rc = daos_tx_abort(th, NULL); assert_rc_equal(rc, -DER_ALREADY); print_message("Commit the aborted TX2, expect DER_NO_PERM\n"); rc = daos_tx_commit(th, NULL); assert_rc_equal(rc, -DER_NO_PERM); print_message("Update against the aborted TX2, expect DER_NO_PERM\n"); arg->expect_result = -DER_NO_PERM; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); print_message("Fetch against the aborted TX2, expect DER_NO_PERM\n"); arg->expect_result = -DER_NO_PERM; lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, th, &req); print_message("Close the TX2...\n"); MUST(daos_tx_close(th, NULL)); ioreq_fini(&req); } static void dtx_14(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; const char *akey2 = "tmp_akey"; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int nrestarts = 13; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX14: restart because of conflict with others\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); dts_buf_render(write_buf, DTX_IO_SMALL); again: arg->expect_result = 0; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); MPI_Barrier(MPI_COMM_WORLD); /* Simulate the conflict with other DTX. */ if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_RESTART | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); rc = daos_tx_commit(th, NULL); assert_rc_equal(rc, -DER_TX_RESTART); /* Not allow new I/O before restart the TX. */ arg->expect_result = -DER_NO_PERM; insert_single(dkey, akey2, 0, write_buf, DTX_IO_SMALL, th, &req); MUST(daos_tx_restart(th, NULL)); /* Reset the fail_loc */ MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); nrestarts--; if (nrestarts > 0) { print_message("Simulate another conflict/restart...\n"); goto again; } arg->expect_result = 0; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); MUST(daos_tx_commit(th, NULL)); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); assert_memory_equal(write_buf, fetch_buf, DTX_IO_SMALL); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_15(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; FAULT_INJECTION_REQUIRED(); print_message("DTX15: restart because of stale pool map\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_STALE_PM | DAOS_FAIL_ALWAYS); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_STALE_PM | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); arg->expect_result = -DER_TX_RESTART; lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, th, &req); /* Reset the fail_loc */ MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); dts_buf_render(write_buf, DTX_IO_SMALL); /* Not allow new I/O before restart the TX. */ arg->expect_result = -DER_NO_PERM; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); MUST(daos_tx_restart(th, NULL)); arg->expect_result = 0; insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); MUST(daos_tx_commit(th, NULL)); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_handle_resent(test_arg_t *arg, uint64_t fail_loc) { const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; print_message("Resend commit because of lost CPD request\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_XSF, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_ARRAY, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, fail_loc | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_commit(th, NULL)); /* Reset the fail_loc */ MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); assert_memory_equal(write_buf, fetch_buf, DTX_IO_SMALL); ioreq_fini(&req); MUST(daos_tx_close(th, NULL)); } static void dtx_16(void **state) { print_message("DTX16: resend commit because of lost CPD request\n"); /* DAOS_DTX_LOST_RPC_REQUEST will simulate the case of CPD RPC * request lost before being executed on the leader. Then the * client will resend the CPD RPC after timeout. */ dtx_handle_resent(*state, DAOS_DTX_LOST_RPC_REQUEST); } static void dtx_17(void **state) { print_message("DTX17: resend commit because of lost CPD reply\n"); /* DAOS_DTX_LOST_RPC_REPLY will simulate the case of CPD RPC * reply lost after being executed on the leader. Then the * client will resend the CPD RPC after timeout. */ dtx_handle_resent(*state, DAOS_DTX_LOST_RPC_REPLY); } static void dtx_18(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char write_buf[DTX_IO_SMALL]; char fetch_buf[DTX_IO_SMALL]; daos_epoch_t epoch = 0; daos_handle_t th = { 0 }; daos_obj_id_t oid; struct ioreq req; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX18: Spread read time-stamp when commit\n"); if (!test_runable(arg, 3)) skip(); arg->async = 0; oid = daos_test_oid_gen(arg->coh, OC_RP_3G1, 0, 0, arg->myrank); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, DAOS_TX_NONE, &req); /* Start read only transaction. */ MUST(daos_tx_open(arg->coh, &th, DAOS_TF_RDONLY, NULL)); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) /* DAOS_DTX_NO_READ_TS will skip the initial read TS. */ daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_READ_TS | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); lookup_single(dkey, akey, 0, fetch_buf, DTX_IO_SMALL, th, &req); assert_memory_equal(write_buf, fetch_buf, DTX_IO_SMALL); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_hdl2epoch(th, &epoch)); assert_int_not_equal(epoch, 0); MUST(daos_tx_close(th, NULL)); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_SPEC_EPOCH | DAOS_FAIL_ALWAYS); daos_fail_value_set(epoch - 1); MPI_Barrier(MPI_COMM_WORLD); /* Start another RW transaction. */ MUST(daos_tx_open(arg->coh, &th, 0, NULL)); dts_buf_render(write_buf, DTX_IO_SMALL); insert_single(dkey, akey, 0, write_buf, DTX_IO_SMALL, th, &req); /* Expect to hit conflict with the read TS on other shards. */ rc = daos_tx_commit(th, NULL); assert_rc_equal(rc, -DER_TX_RESTART); MPI_Barrier(MPI_COMM_WORLD); daos_fail_value_set(0); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_close(th, NULL)); ioreq_fini(&req); } static void dtx_19(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char *write_bufs[DTX_TEST_SUB_REQS]; char *fetch_buf; daos_handle_t th = { 0 }; daos_obj_id_t oids[DTX_TEST_SUB_REQS]; struct ioreq reqs[DTX_TEST_SUB_REQS]; uint32_t nr[DTX_TEST_SUB_REQS]; size_t size[DTX_TEST_SUB_REQS]; size_t max_size = 0; daos_iod_type_t i_type; int i; daos_oclass_id_t oclass; print_message("DTX19: misc rep and EC object update in same TX.\n"); if (!test_runable(arg, 4)) skip(); MUST(daos_tx_open(arg->coh, &th, DAOS_TF_ZERO_COPY, NULL)); arg->async = 0; for (i = 0; i < DTX_TEST_SUB_REQS; i++) { switch (i % 4) { case 0: oclass = OC_EC_2P1G1; i_type = DAOS_IOD_SINGLE; nr[i] = 1; size[i] = 8 * (1 << (i % 21)); break; case 1: oclass = OC_EC_2P2G1; i_type = DAOS_IOD_ARRAY; nr[i] = 1 << (i % 21); size[i] = 8; break; case 2: oclass = OC_S1; i_type = DAOS_IOD_SINGLE; nr[i] = 1; size[i] = 8 * (1 << (i % 21)); break; default: oclass = OC_S2; i_type = DAOS_IOD_ARRAY; nr[i] = 1 << (i % 21); size[i] = 8; break; } if (max_size < size[i] * nr[i]) max_size = size[i] * nr[i]; oids[i] = daos_test_oid_gen(arg->coh, oclass, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], i_type, arg); D_ALLOC(write_bufs[i], size[i] * nr[i]); assert_non_null(write_bufs[i]); dts_buf_render(write_bufs[i], size[i] * nr[i]); insert_single_with_rxnr(dkey, akey, i, write_bufs[i], size[i], nr[i], th, &reqs[i]); } MUST(daos_tx_commit(th, NULL)); D_ALLOC(fetch_buf, max_size); assert_non_null(fetch_buf); for (i = 0; i < DTX_TEST_SUB_REQS; i++) { memset(fetch_buf, 0, max_size); lookup_single_with_rxnr(dkey, akey, i, fetch_buf, size[i], size[i] * nr[i], DAOS_TX_NONE, &reqs[i]); assert_memory_equal(write_bufs[i], fetch_buf, size[i] * nr[i]); } for (i = 0; i < DTX_TEST_SUB_REQS; i++) { D_FREE(write_bufs[i]); ioreq_fini(&reqs[i]); } D_FREE(fetch_buf); MUST(daos_tx_close(th, NULL)); } static void dtx_init_oid_req_akey(test_arg_t *arg, daos_obj_id_t *oids, struct ioreq *reqs, daos_oclass_id_t *ocs, daos_iod_type_t *types, char *akeys[], int oid_req_cnt, int akey_cnt, uint8_t ofeats) { int i; for (i = 0; i < oid_req_cnt; i++) { oids[i] = daos_test_oid_gen(arg->coh, ocs[i], daos_obj_feat2type(ofeats), 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], types[i], arg); } for (i = 0; i < akey_cnt; i++) { D_ALLOC(akeys[i], 16); assert_non_null(akeys[i]); dts_buf_render(akeys[i], 16); } } static void dtx_fini_req_akey(struct ioreq *reqs, char *akeys[], int req_cnt, int akey_cnt) { int i; for (i = 0; i < req_cnt; i++) ioreq_fini(&reqs[i]); for (i = 0; i < akey_cnt; i++) D_FREE(akeys[i]); } static void dtx_20(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; char *write_bufs[2]; char *fetch_buf; daos_handle_t th = { 0 }; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_SINGLE, DAOS_IOD_ARRAY }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G1 }; size_t size = (1 << 20) + 3; int i; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX20: atomicity - either all done or none done\n"); if (!test_runable(arg, 3)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, NULL, 2, 0, 0); print_message("Successful transactional update\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); for (i = 0; i < 2; i++) { D_ALLOC(write_bufs[i], size); assert_non_null(write_bufs[i]); dts_buf_render(write_bufs[i], size); insert_single(dkey, akey, 0, write_bufs[i], size, th, &reqs[i]); } MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); D_ALLOC(fetch_buf, size); assert_non_null(fetch_buf); print_message("Verify succeeful update result\n"); for (i = 0; i < 2; i++) { lookup_single(dkey, akey, 0, fetch_buf, size, DAOS_TX_NONE, &reqs[i]); /* Both the two object should have been updated successfully. */ assert_memory_equal(write_bufs[i], fetch_buf, size); } MPI_Barrier(MPI_COMM_WORLD); /* Simulate the case of TX IO error on the shard_1. */ if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_FAIL_IO | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Failed transactional update\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); for (i = 0; i < 2; i++) /* Exchange the buffers of the two object via new update. */ insert_single(dkey, akey, 0, write_bufs[1 - i], size, th, &reqs[i]); rc = daos_tx_commit(th, NULL); assert_rc_equal(rc, -DER_IO); MUST(daos_tx_close(th, NULL)); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Verify failed update result\n"); for (i = 0; i < 2; i++) { lookup_single(dkey, akey, 0, fetch_buf, size, DAOS_TX_NONE, &reqs[i]); /* The 2nd update failed for one object, then none of the * objects are updated, so the data should be old value. */ assert_memory_equal(write_bufs[i], fetch_buf, size); D_FREE(write_bufs[i]); ioreq_fini(&reqs[i]); } D_FREE(fetch_buf); } static void dtx_21(void **state) { test_arg_t *arg = *state; const char *akey = dts_dtx_akey; char *dkeys[DTX_TEST_SUB_REQS]; char *write_bufs[DTX_TEST_SUB_REQS]; char *fetch_buf; daos_obj_id_t oid; struct ioreq req; daos_iod_type_t type = DAOS_IOD_ARRAY; daos_oclass_id_t oc = OC_RP_2G2; size_t size = 32; int i; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX21: TX atomicity - internal transaction.\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, &oid, &req, &oc, &type, NULL, 1, 0, 0); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); for (i = 0; i < DTX_TEST_SUB_REQS; i++) { D_ALLOC(dkeys[i], 16); assert_non_null(dkeys[i]); dts_buf_render(dkeys[i], 16); D_ALLOC(write_bufs[i], size); assert_non_null(write_bufs[i]); dts_buf_render(write_bufs[i], size); insert_single(dkeys[i], akey, 0, write_bufs[i], size, DAOS_TX_NONE, &req); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); /* Simulate the case of TX IO error on the shard_1. */ if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_FAIL_IO | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Failed punch firstly\n"); rc = daos_obj_punch(req.oh, DAOS_TX_NONE, 0, NULL); assert_rc_equal(rc, -DER_IO); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); D_ALLOC(fetch_buf, size); assert_non_null(fetch_buf); print_message("Verify failed punch result\n"); for (i = 0; i < DTX_TEST_SUB_REQS; i++) { lookup_single(dkeys[i], akey, 0, fetch_buf, size, DAOS_TX_NONE, &req); /* Punch failed, all shards should be there. */ assert_memory_equal(write_bufs[i], fetch_buf, size); } print_message("Successful punch object\n"); MUST(daos_obj_punch(req.oh, DAOS_TX_NONE, 0, NULL)); print_message("Verify successful punch result\n"); arg->expect_result = -DER_NONEXIST; for (i = 0; i < DTX_TEST_SUB_REQS; i++) /* Punch succeed, all shards should have been punched. */ lookup_empty_single(dkeys[i], akey, 0, fetch_buf, size, DAOS_TX_NONE, &req); for (i = 0; i < DTX_TEST_SUB_REQS; i++) { D_FREE(dkeys[i]); D_FREE(write_bufs[i]); } D_FREE(fetch_buf); ioreq_fini(&req); } static void dtx_share_oid(daos_obj_id_t *oid) { int rc; rc = MPI_Bcast(&oid->lo, 1, MPI_UINT64_T, 0, MPI_COMM_WORLD); assert_int_equal(rc, MPI_SUCCESS); rc = MPI_Bcast(&oid->hi, 1, MPI_UINT64_T, 0, MPI_COMM_WORLD); assert_int_equal(rc, MPI_SUCCESS); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_22(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[2]; struct ioreq reqs[2]; uint64_t vals[2] = { 0 }; daos_iod_type_t types[2] = { DAOS_IOD_SINGLE, DAOS_IOD_ARRAY }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G1 }; int i, j; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX22: TX isolation - invisible partial modification\n"); if (!test_runable(arg, 3)) skip(); if (arg->myrank == 0) dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, NULL, 2, 0, 0); /* All ranks share the same two objects. */ for (i = 0; i < 2; i++) dtx_share_oid(&oids[i]); if (arg->myrank != 0) { ioreq_init(&reqs[0], arg->coh, oids[0], types[0], arg); ioreq_init(&reqs[1], arg->coh, oids[1], types[1], arg); } MPI_Barrier(MPI_COMM_WORLD); /* Generate the base objects and values via rank0. */ if (arg->myrank == 0) { daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); for (i = 0; i < 2; i++) insert_single(dkey, akey, 0, &vals[0], sizeof(vals[0]), DAOS_TX_NONE, &reqs[i]); daos_fail_loc_set(0); } MPI_Barrier(MPI_COMM_WORLD); for (j = 0; j < 200; j++) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); restart: for (i = 0; i < 2; i++) { reqs[i].arg->not_check_result = 1; lookup_empty_single(dkey, akey, 0, &vals[i], sizeof(vals[i]), th, &reqs[i]); reqs[i].arg->not_check_result = 0; if (reqs[i].result == -DER_TX_RESTART) { print_message("Handle TX restart (1) %d:%d\n", arg->myrank, j); MUST(daos_tx_restart(th, NULL)); goto restart; } assert_rc_equal(reqs[i].result, 0); } /* If "vals[0] > vals[1]", then vals[0]'s TX internal update * status is visible to current TX. * * If "vals[0] < vals[1]", then MVCC is broken because current * TX's epoch does not prevent vals[1]'s TX commit which epoch * is older than current TX's epoch (for read). */ assert_true(vals[0] == vals[1]); MUST(daos_tx_hdl2epoch(th, &vals[0])); insert_single(dkey, akey, 0, &vals[0], sizeof(vals[0]), th, &reqs[0]); insert_single(dkey, akey, 0, &vals[0], sizeof(vals[0]), th, &reqs[1]); rc = daos_tx_commit(th, NULL); if (rc == -DER_TX_RESTART) { print_message("Handle TX restart (2) %d:%d\n", arg->myrank, j); MUST(daos_tx_restart(th, NULL)); goto restart; } assert_rc_equal(rc, 0); MUST(daos_tx_close(th, NULL)); } dtx_fini_req_akey(reqs, NULL, 2, 0); } static void dtx_23(void **state) { test_arg_t *arg = *state; const char *dkey = dts_dtx_dkey; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G1 }; uint32_t vals[2]; int rc; bool once = false; FAULT_INJECTION_REQUIRED(); print_message("DTX23: server start epoch - refuse TX with old epoch\n"); if (!test_runable(arg, 3)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, NULL, 2, 0, 0); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); insert_single(dkey, akey, 0, &vals[0], sizeof(vals[0]), DAOS_TX_NONE, &reqs[0]); insert_single(dkey, akey, 0, &vals[0], sizeof(vals[0]), DAOS_TX_NONE, &reqs[1]); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_START_EPOCH | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); restart: /* It will get a stale epoch from server if set DAOS_DTX_START_EPOCH. */ lookup_single(dkey, akey, 0, &vals[1], sizeof(vals[1]), th, &reqs[0]); insert_single(dkey, akey, 0, &vals[1], sizeof(vals[1]), th, &reqs[1]); rc = daos_tx_commit(th, NULL); if (once) { assert_rc_equal(rc, 0); } else { once = true; assert_rc_equal(rc, -DER_TX_RESTART); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Handle TX restart %d\n", arg->myrank); MUST(daos_tx_restart(th, NULL)); goto restart; } MUST(daos_tx_close(th, NULL)); dtx_fini_req_akey(reqs, NULL, 2, 0); } static void dtx_24(void **state) { test_arg_t *arg = *state; const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[10]; struct ioreq reqs[10]; uint32_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX24: async batched commit\n"); if (!test_runable(arg, 4)) skip(); print_message("Transactional update something\n"); for (i = 0, val = 0; i < 10; i++, val++) { oids[i] = daos_test_oid_gen(arg->coh, OC_RP_2G2, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], DAOS_IOD_ARRAY, arg); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert_single(dkey1, akey, 0, &val, sizeof(val), th, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), th, &reqs[i]); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } print_message("Sleep %d seconds for the batched commit...\n", DTX_COMMIT_THRESHOLD_AGE + 3); /* Sleep one batched commit interval to guarantee that all async TXs * have been committed. */ sleep(DTX_COMMIT_THRESHOLD_AGE + 3); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); for (i = 0; i < 10; i++) { lookup_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i); lookup_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i); ioreq_fini(&reqs[i]); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_25(void **state) { test_arg_t *arg = *state; const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[DTX_NC_CNT]; struct ioreq reqs[DTX_NC_CNT]; uint32_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX25: uncertain status check - committable\n"); if (!test_runable(arg, 4)) skip(); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_BATCHED_CMT | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Transactional update without batched commit\n"); for (i = 0, val = 1; i < DTX_NC_CNT; i++, val++) { oids[i] = daos_test_oid_gen(arg->coh, OC_RP_2G2, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], DAOS_IOD_ARRAY, arg); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); /* Base value: i + 1 */ insert_single(dkey1, akey, 0, &val, sizeof(val), th, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), th, &reqs[i]); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } print_message("Verify update result without batched commit\n"); for (i = 0; i < DTX_NC_CNT; i++) { /* Async batched commit is disabled, so if fetch hit * 'prepared' DTX on non-leader, it needs to resolve * the uncertainty via dtx_refresh with leader. */ lookup_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i + 1); lookup_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i + 1); ioreq_fini(&reqs[i]); } MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_26(void **state) { test_arg_t *arg = *state; const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[DTX_NC_CNT]; struct ioreq reqs[DTX_NC_CNT]; uint32_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX26: uncertain status check - non-committable\n"); if (!test_runable(arg, 4)) skip(); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); for (i = 0, val = 1; i < DTX_NC_CNT; i++, val++) { oids[i] = daos_test_oid_gen(arg->coh, OC_RP_2G2, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], DAOS_IOD_ARRAY, arg); /* Base value: i + 1 */ insert_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_COMMITTABLE | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("More transactional update without mark committable\n"); for (i = 0, val = 21; i < DTX_NC_CNT; i++, val++) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); /* New value: i + 21 */ insert_single(dkey1, akey, 0, &val, sizeof(val), th, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), th, &reqs[i]); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } print_message("Verify update result without mark committable\n"); for (i = 0; i < DTX_NC_CNT; i++) { /* Inject fail_loc to simulate the case of non-committable. * So the DTX with 'prepared' status will not be committed, * and will be regarded as not ready, then become invisible * for other fetch operation. Then fetch will get old value. */ lookup_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i + 1); lookup_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); assert_int_equal(val, i + 1); ioreq_fini(&reqs[i]); } MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } static void dtx_uncertainty_miss_request(test_arg_t *arg, uint64_t loc, bool abort, bool delay) { const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; const char *akey = dts_dtx_akey; daos_handle_t th = { 0 }; daos_obj_id_t oids[DTX_NC_CNT]; struct ioreq reqs[DTX_NC_CNT]; uint32_t val; int i; int rc; if (!test_runable(arg, 4)) skip(); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); for (i = 0, val = 1; i < DTX_NC_CNT; i++, val++) { oids[i] = daos_test_oid_gen(arg->coh, OC_RP_2G2, 0, 0, arg->myrank); ioreq_init(&reqs[i], arg->coh, oids[i], DAOS_IOD_ARRAY, arg); /* Base value: i + 1 */ insert_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, loc | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Transactional update with loc %lx\n", loc); for (i = 0, val = 21; i < DTX_NC_CNT; i++, val++) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); /* New value: i + 21 */ insert_single(dkey1, akey, 0, &val, sizeof(val), th, &reqs[i]); insert_single(dkey2, akey, 0, &val, sizeof(val), th, &reqs[i]); rc = daos_tx_commit(th, NULL); if (abort) assert_rc_equal(rc, -DER_IO); else assert_rc_equal(rc, 0); MUST(daos_tx_close(th, NULL)); } MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, delay ? (DAOS_DTX_UNCERTAIN | DAOS_FAIL_ALWAYS) : 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); print_message("Verify transactional update result with loc %lx\n", loc); if (delay) { arg->not_check_result = 1; for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); rc = reqs[i].result; lookup_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); /* Either the 1st result or the 2nd one must be * -DER_TX_UNCERTAIN, and only one can be zero, * the other is -DER_TX_UNCERTAIN. */ if (rc == 0) { assert_int_equal(reqs[i].result, -DER_TX_UNCERTAIN); } else { assert_int_equal(rc, -DER_TX_UNCERTAIN); assert_int_equal(reqs[i].result, 0); } ioreq_fini(&reqs[i]); } arg->not_check_result = 0; MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } else { for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey1, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); if (abort) assert_int_equal(val, i + 1); else assert_int_equal(val, i + 21); lookup_single(dkey2, akey, 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[i]); if (abort) assert_int_equal(val, i + 1); else assert_int_equal(val, i + 21); ioreq_fini(&reqs[i]); } } } static void dtx_27(void **state) { FAULT_INJECTION_REQUIRED(); print_message("DTX27: uncertain status check - miss commit\n"); dtx_uncertainty_miss_request(*state, DAOS_DTX_MISS_COMMIT, false, false); } static void dtx_28(void **state) { FAULT_INJECTION_REQUIRED(); print_message("DTX28: uncertain status check - miss abort\n"); dtx_uncertainty_miss_request(*state, DAOS_DTX_MISS_ABORT, true, false); } static void dtx_inject_commit_fail(test_arg_t *arg, int idx) { MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { if (idx % 2 == 1) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_MISS_ABORT | DAOS_FAIL_ALWAYS, 0, NULL); else daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_MISS_COMMIT | DAOS_FAIL_ALWAYS, 0, NULL); } MPI_Barrier(MPI_COMM_WORLD); } static void dtx_generate_layout(test_arg_t *arg, const char *dkey1, const char *dkey2, char **akeys, struct ioreq *reqs, int count, bool base_only, bool inject_fail) { daos_handle_t th = { 0 }; uint64_t val; int i, j; int rc; MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Non-transactional update for base layout\n"); for (i = 0, val = 1; i < count; i++, val++) { /* Base value: i + 1 */ insert_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); insert_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); if (base_only) return; print_message("More transactional %s fail loc\n", inject_fail ? "with" : "without"); for (j = 0; j < 2; j++) { for (i = 0, val = 21; i < count; i++, val++) { if (inject_fail) dtx_inject_commit_fail(arg, i); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); /* New value: i + 21 */ insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &reqs[j]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &reqs[1 - j]); rc = daos_tx_commit(th, NULL); if (i % 2 == 1 && inject_fail) assert_rc_equal(rc, -DER_IO); else assert_rc_equal(rc, 0); MUST(daos_tx_close(th, NULL)); } } if (inject_fail) { MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } } static void dtx_29(void **state) { test_arg_t *arg = *state; const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; uint64_t data[DTX_NC_CNT] = { 0 }; daos_off_t offsets[DTX_NC_CNT]; daos_size_t rec_sizes[DTX_NC_CNT]; daos_size_t data_sizes[DTX_NC_CNT]; uint64_t *data_addrs[DTX_NC_CNT]; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX29: uncertain status check - fetch re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); for (i = 0; i < DTX_NC_CNT; i++) { offsets[i] = 0; rec_sizes[i] = sizeof(uint64_t); data_sizes[i] = sizeof(uint64_t); data_addrs[i] = &data[i]; } dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, false, true); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Triggering fetch re-entry...\n"); for (i = 0; i < DTX_NC_CNT; i += IOREQ_SG_IOD_NR) { lookup(dkey1, IOREQ_SG_IOD_NR, (const char **)(akeys + i), offsets + i, rec_sizes + i, (void **)&data_addrs[i], data_sizes + i, DAOS_TX_NONE, &reqs[0], false); lookup(dkey2, IOREQ_SG_IOD_NR, (const char **)(akeys + i), offsets + i, rec_sizes + i, (void **)&data_addrs[i], data_sizes + i, DAOS_TX_NONE, &reqs[1], false); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); print_message("Verifying fetch results...\n"); for (i = 0; i < DTX_NC_CNT; i += 2) assert_int_equal(data[i], i + 21); for (i = 1; i < DTX_NC_CNT; i += 2) assert_int_equal(data[i], i + 1); dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); } static int dtx_enum_parse_akey(char *str, int len, int base) { int val = 0; int i; for (i = 0; i < len; i++) { if (str[i] < '0' || str[i] > '9') return -1; val = val * 10 + str[i] - '0'; } return val - base; } static int dtx_enum_verify_akeys(char *buf, daos_key_desc_t *kds, int num, int base) { int trace[DTX_NC_CNT * 2]; int idx; int i; /* "trace[i] == 1" means that related akey should exist. * "trace[i] == 0" means that related akey should not exist. */ for (i = 0; i < DTX_NC_CNT; i++) trace[i] = 1; for (i = DTX_NC_CNT; i < DTX_NC_CNT * 2; i += 2) trace[i] = 1; for (i = DTX_NC_CNT + 1; i < DTX_NC_CNT * 2; i += 2) trace[i] = 0; for (i = 0; i < num; buf += kds[i++].kd_key_len) { idx = dtx_enum_parse_akey(buf, kds[i].kd_key_len, base); if (idx < 0 || idx >= DTX_NC_CNT * 2) { fprintf(stderr, "Enumeration got invalid akey %.*s\n", (int)kds[i].kd_key_len, buf); return -1; } if (trace[idx] == 0) { fprintf(stderr, "Akey %.*s should not exist\n", (int)kds[i].kd_key_len, buf); return -1; } if (trace[idx] > 1) { fprintf(stderr, "Akey %.*s is packed repeatedly\n", (int)kds[i].kd_key_len, buf); return -1; } trace[idx]++; } return 0; } static void dtx_30(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT * 2]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; int base = 10000; int akey_size = 32; daos_size_t buf_len = DTX_NC_CNT * 2 * akey_size; char buf[buf_len]; daos_key_desc_t kds[DTX_NC_CNT * 2]; daos_anchor_t anchor; daos_handle_t th = { 0 }; uint64_t val; uint32_t num; int rc; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX30: uncertain status check - enumeration re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, NULL, 2, 0, 0); for (i = 0; i < DTX_NC_CNT * 2; i++) { D_ALLOC(akeys[i], akey_size); assert_non_null(akeys[i]); snprintf(akeys[i], akey_size - 1, "%d", i + base); } dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, false, false); for (i = DTX_NC_CNT, val = 31; i < DTX_NC_CNT * 2; i++, val++) { dtx_inject_commit_fail(arg, i); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); /* New value: i + 31 */ insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &reqs[0]); insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &reqs[1]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &reqs[1]); rc = daos_tx_commit(th, NULL); if (i % 2 == 1) assert_rc_equal(rc, -DER_IO); else assert_rc_equal(rc, 0); MUST(daos_tx_close(th, NULL)); } MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Transactional enumerate to verify update result\n"); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); num = DTX_NC_CNT * 2; memset(&anchor, 0, sizeof(anchor)); memset(buf, 0, buf_len); MUST(enumerate_akey(th, dkey1, &num, kds, &anchor, buf, buf_len, &reqs[0])); assert_int_equal(num, DTX_NC_CNT + DTX_NC_CNT / 2); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); MUST(dtx_enum_verify_akeys(buf, kds, num, base)); print_message("Non-transactional enumerate to verify update result\n"); num = DTX_NC_CNT * 2; memset(&anchor, 0, sizeof(anchor)); memset(buf, 0, buf_len); MUST(enumerate_akey(DAOS_TX_NONE, dkey2, &num, kds, &anchor, buf, buf_len, &reqs[1])); assert_int_equal(num, DTX_NC_CNT + DTX_NC_CNT / 2); MUST(dtx_enum_verify_akeys(buf, kds, num, base)); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT * 2); } static void dtx_31(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_key_t api_dkey1; daos_key_t api_dkey2; daos_key_t api_akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; uint64_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX31: uncertain status check - punch re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); d_iov_set(&api_dkey1, dkey1, strlen(dkey1)); d_iov_set(&api_dkey2, dkey2, strlen(dkey2)); for (i = 0; i < DTX_NC_CNT; i++) d_iov_set(&api_akeys[i], akeys[i], strlen(akeys[i])); dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, false, true); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Triggering punch re-entry...\n"); MUST(daos_obj_punch_akeys(reqs[0].oh, DAOS_TX_NONE, 0, &api_dkey1, DTX_NC_CNT, api_akeys, NULL)); MUST(daos_obj_punch_akeys(reqs[1].oh, DAOS_TX_NONE, 0, &api_dkey2, DTX_NC_CNT, api_akeys, NULL)); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); print_message("Verifying punch re-entry results...\n"); arg->expect_result = -DER_NONEXIST; for (i = 0; i < DTX_NC_CNT; i++) { lookup_empty_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); lookup_empty_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); } dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); } static void dtx_32(void **state) { test_arg_t *arg = *state; const char *dkey1 = "a_dkey_1"; const char *dkey2 = "b_dkey_2"; char *akeys[IOREQ_SG_IOD_NR]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; uint64_t data[IOREQ_SG_IOD_NR] = { 0 }; int rx_nr[IOREQ_SG_IOD_NR]; daos_off_t offsets[IOREQ_SG_IOD_NR]; daos_size_t rec_sizes[IOREQ_SG_IOD_NR]; uint64_t *data_addrs[IOREQ_SG_IOD_NR]; uint64_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX32: uncertain status check - update re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, IOREQ_SG_IOD_NR, 0); for (i = 0; i < IOREQ_SG_IOD_NR; i++) { rx_nr[i] = 1; offsets[i] = 0; rec_sizes[i] = sizeof(uint64_t); data_addrs[i] = &data[i]; } dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, IOREQ_SG_IOD_NR, false, true); for (i = 0, val = 31; i < IOREQ_SG_IOD_NR; i++, val++) data[i] = val; MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Triggering update re-entry...\n"); arg->idx_no_jump = 1; insert(dkey1, IOREQ_SG_IOD_NR, (const char **)akeys, rec_sizes, rx_nr, offsets, (void **)data_addrs, DAOS_TX_NONE, &reqs[0], 0); insert(dkey2, IOREQ_SG_IOD_NR, (const char **)akeys, rec_sizes, rx_nr, offsets, (void **)data_addrs, DAOS_TX_NONE, &reqs[1], 0); arg->idx_no_jump = 0; MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); print_message("Verifying update re-entry results...\n"); for (i = 0; i < IOREQ_SG_IOD_NR; i++) { lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); assert_int_equal(val, i + 31); lookup_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); assert_int_equal(val, i + 31); } dtx_fini_req_akey(reqs, akeys, 2, IOREQ_SG_IOD_NR); } static void dtx_33(void **state) { test_arg_t *arg = *state; uint64_t dkeys[10]; uint64_t akeys[10]; daos_key_t api_dkeys[10]; daos_key_t api_akey; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_ARRAY }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; daos_handle_t th = { 0 }; daos_iod_t iod = { 0 }; d_sg_list_t sgl = { 0 }; daos_recx_t recx = { 0 }; d_iov_t val_iov; uint64_t val; int i, j; int rc; FAULT_INJECTION_REQUIRED(); print_message("DTX33: uncertain status check - query key re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, NULL, 2, 0, DAOS_OF_DKEY_UINT64 | DAOS_OF_AKEY_UINT64); for (i = 0; i < 10; i++) { dkeys[i] = 3 + i * 10; d_iov_set(&api_dkeys[i], &dkeys[i], sizeof(uint64_t)); } for (i = 0; i < 10; i++) akeys[i] = 5 + i * 100; d_iov_set(&val_iov, &val, sizeof(val)); recx.rx_nr = 1; sgl.sg_iovs = &val_iov; sgl.sg_nr = 1; iod.iod_size = sizeof(uint64_t); iod.iod_nr = 1; iod.iod_recxs = &recx; iod.iod_type = DAOS_IOD_ARRAY; for (j = 0; j < 10; j++) { for (i = 0, val = 100000; i < 10; i++, val++) { dtx_inject_commit_fail(arg, i); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); recx.rx_idx = 7 + i * 1000 + j * 10000; d_iov_set(&iod.iod_name, &akeys[i], sizeof(uint64_t)); MUST(daos_obj_update(reqs[j % 2].oh, th, 0, &api_dkeys[j], 1, &iod, &sgl, NULL)); MUST(daos_obj_update(reqs[1 - j % 2].oh, th, 0, &api_dkeys[10 - j - 1], 1, &iod, &sgl, NULL)); rc = daos_tx_commit(th, NULL); if (i % 2 == 1) assert_rc_equal(rc, -DER_IO); else assert_rc_equal(rc, 0); MUST(daos_tx_close(th, NULL)); } } MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); d_iov_set(&api_akey, &akeys[0], sizeof(uint64_t)); print_message("Query the max recx on obj1\n"); MUST(daos_obj_query_key(reqs[0].oh, DAOS_TX_NONE, DAOS_GET_DKEY | DAOS_GET_AKEY | DAOS_GET_RECX | DAOS_GET_MAX, &api_dkeys[0], &api_akey, &recx, NULL)); #if 0 /* MAX: obj1::dkeys[j(9)], akeys[i(8)] */ assert_int_equal(dkeys[0], 93); /* 3 + 9 * 10 */ assert_int_equal(recx.rx_idx, 98007); /* 7 + 8 * 1000 + 9 * 10000 */ assert_int_equal(recx.rx_nr, 1); #endif assert_int_equal(akeys[0], 805); /* 5 + 8 * 100 */ print_message("Query the min recx on obj2\n"); MUST(daos_obj_query_key(reqs[1].oh, DAOS_TX_NONE, DAOS_GET_DKEY | DAOS_GET_AKEY | DAOS_GET_RECX | DAOS_GET_MIN, &api_dkeys[0], &api_akey, &recx, NULL)); #if 0 /* MIX: obj2::dkeys[10 - j(0) - 1], akeys[i(0)] */ assert_int_equal(dkeys[0], 93); /* 3 + (10 - 0 - 1) * 10 */ assert_int_equal(recx.rx_idx, 7); /* 7 + 0 * 1000 + 0 * 10000 */ assert_int_equal(recx.rx_nr, 1); #endif assert_int_equal(akeys[0], 5); /* 5 + 0 * 100 */ dtx_fini_req_akey(reqs, NULL, 2, 0); } static void dtx_34(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; daos_key_t api_dkey1; daos_key_t api_dkey2; daos_key_t api_akeys[DTX_NC_CNT]; uint64_t data[DTX_NC_CNT] = { 0 }; int rx_nr[DTX_NC_CNT]; daos_off_t offsets[DTX_NC_CNT]; daos_size_t rec_sizes[DTX_NC_CNT]; uint64_t *data_addrs[DTX_NC_CNT]; daos_handle_t th = { 0 }; uint64_t val; int rc; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX34: uncertain status check - CPD RPC re-entry\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); d_iov_set(&api_dkey1, dkey1, strlen(dkey1)); d_iov_set(&api_dkey2, dkey2, strlen(dkey2)); for (i = 0; i < DTX_NC_CNT; i++) { d_iov_set(&api_akeys[i], akeys[i], strlen(akeys[i])); rx_nr[i] = 1; offsets[i] = 0; rec_sizes[i] = sizeof(uint64_t); data_addrs[i] = &data[i]; } dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, false, true); for (i = 0, val = 31; i < DTX_NC_CNT; i++, val++) data[i] = val; MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); MPI_Barrier(MPI_COMM_WORLD); print_message("Triggering CPD RPC handler re-entry...\n"); arg->idx_no_jump = 1; for (i = 0; i < DTX_NC_CNT; i += IOREQ_SG_IOD_NR) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert(dkey1, IOREQ_SG_IOD_NR, (const char **)(akeys + i), rec_sizes + i, rx_nr + i, offsets + i, (void **)&data_addrs[i], th, &reqs[0], 0); rc = daos_obj_punch_akeys(reqs[0].oh, th, 0, &api_dkey2, IOREQ_SG_IOD_NR, api_akeys + i, NULL); assert_rc_equal(rc, 0); insert(dkey1, IOREQ_SG_IOD_NR, (const char **)(akeys + i), rec_sizes + i, rx_nr + i, offsets + i, (void **)&data_addrs[i], th, &reqs[1], 0); rc = daos_obj_punch_akeys(reqs[1].oh, th, 0, &api_dkey2, IOREQ_SG_IOD_NR, api_akeys + i, NULL); assert_rc_equal(rc, 0); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); MPI_Barrier(MPI_COMM_WORLD); print_message("Verifying CPD RPC handler re-entry results...\n"); for (i = 0; i < DTX_NC_CNT; i++) { arg->expect_result = 0; lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); assert_int_equal(val, i + 31); arg->expect_result = -DER_NONEXIST; lookup_empty_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); } dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); } static void dtx_35(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_EC_2P1G1, OC_RP_2G2 }; uint64_t val; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX35: resync during reopen container\n"); if (!test_runable(arg, 4)) skip(); dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, false, false); MPI_Barrier(MPI_COMM_WORLD); print_message("closing object\n"); MUST(daos_obj_close(reqs[0].oh, NULL)); MUST(daos_obj_close(reqs[1].oh, NULL)); print_message("closing container\n"); MUST(daos_cont_close(arg->coh, NULL)); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { print_message("reopening container to trigger DTX resync\n"); MUST(daos_cont_open(arg->pool.poh, arg->co_str, DAOS_COO_RW, &arg->coh, &arg->co_info, NULL)); } MPI_Barrier(MPI_COMM_WORLD); print_message("share container\n"); handle_share(&arg->coh, HANDLE_CO, arg->myrank, arg->pool.poh, 1); print_message("reopening object\n"); MUST(daos_obj_open(arg->coh, oids[0], 0, &reqs[0].oh, NULL)); MUST(daos_obj_open(arg->coh, oids[1], 0, &reqs[1].oh, NULL)); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); /* Sleep 3 seconds, all possible DTX resync should have been done. */ sleep(3); for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); assert_int_equal(val, i + 21); lookup_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); assert_int_equal(val, i + 21); } dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); MPI_Barrier(MPI_COMM_WORLD); } static d_rank_t dtx_get_restart_rank(d_rank_t *w_ranks, d_rank_t *r_ranks, int wcnt, int rcnt) { int i, j; for (i = 0; i < rcnt; i++) { bool same = false; for (j = 0; j < wcnt; j++) { if (r_ranks[i] == w_ranks[j]) { same = true; break; } } if (!same) return r_ranks[i]; } return CRT_NO_RANK; } static void dtx_36(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; uint64_t vals[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_RP_3G2, OC_RP_3G1 }; daos_handle_t th = { 0 }; d_rank_t w_ranks[3]; d_rank_t r_ranks[6]; d_rank_t kill_rank = CRT_NO_RANK; d_rank_t restart_rank; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX36: resync - DTX entry for read only ops\n"); if (!test_runable(arg, 7)) skip(); /* Obj1 has more redundancy groups than obj2. If the TX reads * from multiple redundancy groups of obj1 and only writes to * obj2, then there must be some server(s) that only contains * read only operation. */ dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); dtx_generate_layout(arg, dkey1, dkey2, akeys, reqs, DTX_NC_CNT, true, false); /* Different MPI ranks will have different redundancy groups. * If we kill one redundancy group for each MPI rank, then it * cause too much servers to be killed as to the test can NOT * go ahead. So only check on the MPI rank_0. */ MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { daos_fail_loc_set(DAOS_DTX_SPEC_LEADER | DAOS_FAIL_ALWAYS); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_SPEC_LEADER | DAOS_FAIL_ALWAYS, 0, NULL); /* "DAOS_DTX_SPEC_LEADER" may affect the dispatch of * sub-request on the leader, set "fail_val" as very * large value can avoid such trouble. */ daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, (1 << 20), 0, NULL); print_message("Generating TXs with read only ops on server\n"); for (i = 0, vals[1] = 31; i < DTX_NC_CNT; i++, vals[1]++) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); lookup_single(dkey1, akeys[i], 0, &vals[0], sizeof(vals[0]), th, &reqs[0]); insert_single(dkey1, akeys[i], 0, &vals[1], sizeof(vals[1]), th, &reqs[1]); lookup_single(dkey2, akeys[i], 0, &vals[0], sizeof(vals[0]), th, &reqs[0]); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } for (i = 0; i < 3; i++) w_ranks[i] = get_rank_by_oid_shard(arg, oids[1], i); for (i = 0; i < 6; i++) r_ranks[i] = get_rank_by_oid_shard(arg, oids[0], i); restart_rank = dtx_get_restart_rank(w_ranks, r_ranks, 3, 6); print_message("Restart rank %d when rebuild\n", restart_rank); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_SRV_RESTART | DAOS_FAIL_ONCE, 0, NULL); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, restart_rank, 0, NULL); kill_rank = get_rank_by_oid_shard(arg, oids[1], 0); print_message("Exclude rank %d to trigger rebuild\n", kill_rank); } MPI_Barrier(MPI_COMM_WORLD); rebuild_single_pool_rank(arg, kill_rank, false); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, 0, 0, NULL); daos_fail_loc_set(0); print_message("Verifying data after rebuild...\n"); for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey2, akeys[i], 0, &vals[0], sizeof(vals[0]), DAOS_TX_NONE, &reqs[0]); assert_int_equal(vals[0], i + 1); lookup_single(dkey1, akeys[i], 0, &vals[0], sizeof(vals[0]), DAOS_TX_NONE, &reqs[1]); assert_int_equal(vals[0], i + 31); } } MPI_Barrier(MPI_COMM_WORLD); reintegrate_single_pool_rank(arg, kill_rank); dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); } static void dtx_37(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oid; struct ioreq req; uint64_t val; daos_iod_type_t type = DAOS_IOD_SINGLE; daos_oclass_id_t oc = OC_RP_3G2; daos_handle_t th = { 0 }; d_rank_t kill_rank = CRT_NO_RANK; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX37: resync - leader failed during prepare\n"); if (!test_runable(arg, 7)) skip(); dtx_init_oid_req_akey(arg, &oid, &req, &oc, &type, akeys, 1, DTX_NC_CNT, 0); MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); print_message("Non-transactional update for base layout\n"); for (i = 0, val = 1; i < DTX_NC_CNT; i++, val++) { /* Base value: i + 1 */ insert_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &req); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &req); } /* Different MPI ranks will generate different object layout. * It is not easy to control multiple MPI ranks for specified * leader and some non-leader. So only check on the MPI rank_0. */ MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) { daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_NO_BATCHED_CMT | DAOS_FAIL_ALWAYS, 0, NULL); print_message("Generating some TXs to be committed...\n"); for (i = 0, val = 31; i < DTX_NC_CNT; i += 2, val += 2) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &req); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &req); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_SKIP_PREPARE | DAOS_FAIL_ALWAYS, 0, NULL); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, 4, 0, NULL); /* Skip shard 4 */ daos_fail_loc_set(DAOS_DTX_SPEC_LEADER | DAOS_FAIL_ALWAYS); print_message("Generating some TXs to be aborted...\n"); for (i = 1, val = 101; i < DTX_NC_CNT; i += 2, val += 2) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &req); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &req); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } kill_rank = get_rank_by_oid_shard(arg, oid, 0); print_message("Exclude rank %d to trigger rebuild\n", kill_rank); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, 0, 0, NULL); daos_fail_loc_set(0); } MPI_Barrier(MPI_COMM_WORLD); rebuild_single_pool_rank(arg, kill_rank, false); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { print_message("Verifying data after rebuild...\n"); for (i = 0, val = 0; i < DTX_NC_CNT; i++, val = 0) { /* Full prepared TXs (i % 2 == 0) should has been * committed by DTX resync, then the value should * be new one. * Partially prepared TXs should has been aborted * during DTX resync, so the value should old one. */ lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &req); if (i % 2 == 0) assert_int_equal(val, i + 31); else assert_int_equal(val, i + 1); lookup_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &req); if (i % 2 == 0) assert_int_equal(val, i + 31); else assert_int_equal(val, i + 1); } } MPI_Barrier(MPI_COMM_WORLD); reintegrate_single_pool_rank(arg, kill_rank); dtx_fini_req_akey(&req, akeys, 1, DTX_NC_CNT); } static void dtx_38(void **state) { test_arg_t *arg = *state; char *dkey1 = "a_dkey_1"; char *dkey2 = "b_dkey_2"; char *akeys[DTX_NC_CNT]; daos_obj_id_t oids[2]; struct ioreq reqs[2]; daos_iod_type_t types[2] = { DAOS_IOD_ARRAY, DAOS_IOD_SINGLE }; daos_oclass_id_t ocs[2] = { OC_RP_3G2, OC_S1 }; uint64_t val; daos_handle_t th = { 0 }; d_rank_t kill_ranks[2]; int i; FAULT_INJECTION_REQUIRED(); print_message("DTX38: resync - lost whole redundancy groups\n"); if (!test_runable(arg, 7)) skip(); if (arg->myrank == 0) { oids[0] = daos_test_oid_gen(arg->coh, ocs[0], 0, 0, arg->myrank); kill_ranks[0] = get_rank_by_oid_shard(arg, oids[0], 0); do { oids[1] = daos_test_oid_gen(arg->coh, ocs[1], 0, 0, arg->myrank); kill_ranks[1] = get_rank_by_oid_shard(arg, oids[1], 0); } while (kill_ranks[0] != kill_ranks[1]); for (i = 0; i < DTX_NC_CNT; i++) { D_ALLOC(akeys[i], 16); assert_non_null(akeys[i]); dts_buf_render(akeys[i], 16); } ioreq_init(&reqs[0], arg->coh, oids[0], types[0], arg); ioreq_init(&reqs[1], arg->coh, oids[1], types[1], arg); } else { dtx_init_oid_req_akey(arg, oids, reqs, ocs, types, akeys, 2, DTX_NC_CNT, 0); kill_ranks[0] = CRT_NO_RANK; } MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(DAOS_DTX_COMMIT_SYNC | DAOS_FAIL_ALWAYS); print_message("Non-transactional update for base layout\n"); for (i = 0, val = 1; i < DTX_NC_CNT; i++, val++) { /* Base value: i + 1 */ insert_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[1]); } /* Different MPI ranks will have different redundancy groups. * If we kill one redundancy group for each MPI rank, then it * cause too much servers to be killed as to the test can NOT * go ahead. So only check on the MPI rank_0. */ MPI_Barrier(MPI_COMM_WORLD); daos_fail_loc_set(0); if (arg->myrank == 0) { daos_fail_loc_set(DAOS_DTX_SPEC_LEADER | DAOS_FAIL_ALWAYS); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, DAOS_DTX_SPEC_LEADER | DAOS_FAIL_ALWAYS, 0, NULL); /* "DAOS_DTX_SPEC_LEADER" may affect the dispatch of * sub-requests on the leader, set "fail_val" as very * large value can avoid such trouble. */ daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, (1 << 20), 0, NULL); print_message("Generating TXs with specified leader...\n"); for (i = 0, val = 31; i < DTX_NC_CNT; i++, val++) { MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert_single(dkey1, akeys[i], 0, &val, sizeof(val), th, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &reqs[1]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), th, &reqs[0]); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_close(th, NULL)); } print_message("Exclude rank %d to trigger rebuild\n", kill_ranks[0]); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_LOC, 0, 0, NULL); daos_debug_set_params(arg->group, -1, DMG_KEY_FAIL_VALUE, 0, 0, NULL); daos_fail_loc_set(DAOS_DTX_NO_RETRY | DAOS_FAIL_ALWAYS); } MPI_Barrier(MPI_COMM_WORLD); rebuild_single_pool_rank(arg, kill_ranks[0], false); MPI_Barrier(MPI_COMM_WORLD); if (arg->myrank == 0) { print_message("Verifying data after rebuild...\n"); reqs[0].arg->not_check_result = 1; for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); if (reqs[0].result == 0) { /* Fetch from the new rebuilt target, * should be the old value: i + 1 */ assert_int_equal(val, i + 1); } else { assert_rc_equal(reqs[0].result, -DER_DATA_LOSS); } lookup_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); if (reqs[0].result == 0) { /* Fetch from the new rebuilt target, * should be the old value: i + 1 */ assert_int_equal(val, i + 1); } else { assert_rc_equal(reqs[0].result, -DER_DATA_LOSS); } } reqs[0].arg->not_check_result = 0; print_message("Update against corrupted object...\n"); for (i = 0, val = 101; i < DTX_NC_CNT; i++, val++) { insert_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); insert_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); } print_message("Verify new update...\n"); for (i = 0; i < DTX_NC_CNT; i++) { lookup_single(dkey1, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); assert_int_equal(val, i + 101); lookup_single(dkey2, akeys[i], 0, &val, sizeof(val), DAOS_TX_NONE, &reqs[0]); assert_int_equal(val, i + 101); } daos_fail_loc_set(0); } MPI_Barrier(MPI_COMM_WORLD); reintegrate_single_pool_rank(arg, kill_ranks[0]); dtx_fini_req_akey(reqs, akeys, 2, DTX_NC_CNT); } static void dtx_39(void **state) { test_arg_t *arg = *state; char *akey1 = "akey_1"; char *akey2 = "akey_2"; char *akey3 = "akey_3"; struct ioreq req; uint64_t val[2]; daos_handle_t th = { 0 }; d_rank_t kill_rank = CRT_NO_RANK; print_message("DTX39: not restar the transaction with fixed epoch\n"); if (!test_runable(arg, 3)) skip(); if (arg->myrank == 0) { daos_obj_id_t oid; daos_epoch_t epoch; oid = daos_test_oid_gen(arg->coh, OC_RP_2G1, 0, 0, arg->myrank); kill_rank = get_rank_by_oid_shard(arg, oid, 0); ioreq_init(&req, arg->coh, oid, DAOS_IOD_SINGLE, arg); val[0] = 1; insert_single(dts_dtx_dkey, akey1, 0, &val[0], sizeof(val[0]), DAOS_TX_NONE, &req); insert_single(dts_dtx_dkey, akey2, 0, &val[0], sizeof(val[0]), DAOS_TX_NONE, &req); MUST(daos_tx_open(arg->coh, &th, 0, NULL)); insert_single(dts_dtx_dkey, akey3, 0, &val[0], sizeof(val[0]), th, &req); MUST(daos_tx_commit(th, NULL)); MUST(daos_tx_hdl2epoch(th, &epoch)); MUST(daos_tx_close(th, NULL)); MUST(daos_tx_open_snap(arg->coh, epoch << 1, &th, NULL)); val[1] = 0; lookup_single(dts_dtx_dkey, akey1, 0, &val[1], sizeof(val[1]), th, &req); assert_int_equal(val[0], val[1]); print_message("Exclude rank %d to trigger rebuild\n", kill_rank); } rebuild_single_pool_rank(arg, kill_rank, false); if (arg->myrank == 0) { print_message("Verifying data after rebuild...\n"); val[1] = 0; /* This fetch will refresh the client side pool map, * then the TX's pm_ver will become stale. */ lookup_single(dts_dtx_dkey, akey2, 0, &val[1], sizeof(val[1]), DAOS_TX_NONE, &req); assert_int_equal(val[0], val[1]); val[1] = 0; /* NOT restart the TX even if its pm_ver is stale. */ lookup_single(dts_dtx_dkey, akey3, 0, &val[1], sizeof(val[1]), th, &req); assert_int_equal(val[0], val[1]); MUST(daos_tx_close(th, NULL)); ioreq_fini(&req); } reintegrate_single_pool_rank(arg, kill_rank); } static void dtx_40(void **state) { FAULT_INJECTION_REQUIRED(); print_message("DTX40: uncertain check - miss commit with delay\n"); dtx_uncertainty_miss_request(*state, DAOS_DTX_MISS_COMMIT, false, true); } static void dtx_41(void **state) { FAULT_INJECTION_REQUIRED(); print_message("DTX41: uncertain check - miss abort with delay\n"); dtx_uncertainty_miss_request(*state, DAOS_DTX_MISS_ABORT, true, true); } static test_arg_t *saved_dtx_arg; static int dtx_sub_setup(void **state) { int rc; saved_dtx_arg = *state; *state = NULL; rc = test_setup(state, SETUP_CONT_CONNECT, true, SMALL_POOL_SIZE, 0, NULL); return rc; } static int dtx_sub_teardown(void **state) { int rc; rc = test_teardown(state); *state = saved_dtx_arg; saved_dtx_arg = NULL; return rc; } static const struct CMUnitTest dtx_tests[] = { {"DTX1: multiple SV update against the same obj", dtx_1, NULL, test_case_teardown}, {"DTX2: multiple EV update against the same obj", dtx_2, NULL, test_case_teardown}, {"DTX3: Multiple small SV update against multiple objs", dtx_3, NULL, test_case_teardown}, {"DTX4: Multiple large EV update against multiple objs", dtx_4, NULL, test_case_teardown}, {"DTX5: Multiple small SV update on multiple EC objs", dtx_5, NULL, test_case_teardown}, {"DTX6: Multiple large EV update on multiple EC objs", dtx_6, NULL, test_case_teardown}, {"DTX7: SV update plus punch", dtx_7, NULL, test_case_teardown}, {"DTX8: EV update plus punch", dtx_8, NULL, test_case_teardown}, {"DTX9: conditional insert/update", dtx_9, NULL, test_case_teardown}, {"DTX10: conditional punch", dtx_10, NULL, test_case_teardown}, {"DTX11: read only transaction", dtx_11, NULL, test_case_teardown}, {"DTX12: zero copy flag", dtx_12, NULL, test_case_teardown}, {"DTX13: DTX status machnie", dtx_13, NULL, test_case_teardown}, {"DTX14: restart because of conflict with others", dtx_14, NULL, test_case_teardown}, {"DTX15: restart because of stale pool map", dtx_15, NULL, test_case_teardown}, {"DTX16: resend commit because of lost CPD request", dtx_16, NULL, test_case_teardown}, {"DTX17: resend commit because of lost CPD reply", dtx_17, NULL, test_case_teardown}, {"DTX18: spread read time-stamp when commit", dtx_18, NULL, test_case_teardown}, {"DTX19: Misc rep and EC object update in same TX", dtx_19, NULL, test_case_teardown}, {"DTX20: atomicity - either all done or none done", dtx_20, NULL, test_case_teardown}, {"DTX21: atomicity - internal transaction", dtx_21, NULL, test_case_teardown}, {"DTX22: TX isolation - invisible partial modification", dtx_22, NULL, test_case_teardown}, {"DTX23: server start epoch - refuse TX with old epoch", dtx_23, NULL, test_case_teardown}, {"DTX24: async batched commit", dtx_24, NULL, test_case_teardown}, {"DTX25: uncertain status check - committable", dtx_25, NULL, test_case_teardown}, {"DTX26: uncertain status check - non-committable", dtx_26, NULL, test_case_teardown}, {"DTX27: uncertain status check - miss commit", dtx_27, NULL, test_case_teardown}, {"DTX28: uncertain status check - miss abort", dtx_28, NULL, test_case_teardown}, {"DTX29: uncertain status check - fetch re-entry", dtx_29, NULL, test_case_teardown}, {"DTX30: uncertain status check - enumeration re-entry", dtx_30, NULL, test_case_teardown}, {"DTX31: uncertain status check - punch re-entry", dtx_31, NULL, test_case_teardown}, {"DTX32: uncertain status check - update re-entry", dtx_32, NULL, test_case_teardown}, {"DTX33: uncertain status check - query key re-entry", dtx_33, NULL, test_case_teardown}, {"DTX34: uncertain status check - CPD RPC re-entry", dtx_34, NULL, test_case_teardown}, {"DTX35: resync during reopen container", dtx_35, NULL, test_case_teardown}, {"DTX36: resync - DTX entry for read only ops", dtx_36, dtx_sub_setup, dtx_sub_teardown}, {"DTX37: resync - leader failed during prepare", dtx_37, dtx_sub_setup, dtx_sub_teardown}, {"DTX38: resync - lost whole redundancy groups", dtx_38, dtx_sub_setup, dtx_sub_teardown}, {"DTX39: not restart the transaction with fixed epoch", dtx_39, dtx_sub_setup, dtx_sub_teardown}, {"DTX40: uncertain check - miss commit with delay", dtx_40, NULL, test_case_teardown}, {"DTX41: uncertain check - miss abort with delay", dtx_41, NULL, test_case_teardown}, }; static int dtx_test_setup(void **state) { int rc; rc = test_setup(state, SETUP_CONT_CONNECT, true, DEFAULT_POOL_SIZE, 0, NULL); return rc; } int run_daos_dist_tx_test(int rank, int size, int *sub_tests, int sub_tests_size) { int rc = 0; MPI_Barrier(MPI_COMM_WORLD); if (sub_tests_size == 0) { sub_tests_size = ARRAY_SIZE(dtx_tests); sub_tests = NULL; } rc = run_daos_sub_tests("DAOS_Distributed_TX", dtx_tests, ARRAY_SIZE(dtx_tests), sub_tests, sub_tests_size, dtx_test_setup, test_teardown); MPI_Barrier(MPI_COMM_WORLD); return rc; }
27.056048
79
0.67555
[ "object" ]
a9d2295e748da7429ac9e08d8fae554d5f42655b
6,627
h
C
SparkPerso/Pods/DJI-SDK-iOS/iOS_Mobile_SDK/DJISDK.framework/Headers/DJIRTK.h
BoomPowbep/Spark-Sphero-Starter
c6b3b112d3241987e2af544ff72b3dedc7f92435
[ "MIT" ]
6
2019-01-10T12:12:54.000Z
2021-11-30T10:27:28.000Z
SparkPerso/Pods/DJI-SDK-iOS/iOS_Mobile_SDK/DJISDK.framework/Headers/DJIRTK.h
BoomPowbep/Spark-Sphero-Starter
c6b3b112d3241987e2af544ff72b3dedc7f92435
[ "MIT" ]
1
2020-10-09T07:49:14.000Z
2020-10-09T07:49:14.000Z
SparkPerso/Pods/DJI-SDK-iOS/iOS_Mobile_SDK/DJISDK.framework/Headers/DJIRTK.h
BoomPowbep/Spark-Sphero-Starter
c6b3b112d3241987e2af544ff72b3dedc7f92435
[ "MIT" ]
1
2020-09-24T10:48:32.000Z
2020-09-24T10:48:32.000Z
// // DJIRTK.h // DJISDK // // Copyright © 2017, DJI. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import <DJISDK/DJIBaseProduct.h> NS_ASSUME_NONNULL_BEGIN @class DJIRTK; @class DJIRTKState; /** * This enum defines the positioning solution currently being used. */ typedef NS_ENUM (NSInteger, DJIRTKPositioningSolution){ /** * No positioning solution. This can be caused by an insufficient number of * satellites in view, insufficient time to lock onto the satellites, or a loss in * communication link between the mobile station and ground system. */ DJIRTKPositioningSolutionNone, /** * RTK point positioning. */ DJIRTKPositioningSolutionSinglePoint, /** * Float solution positioning. */ DJIRTKPositioningSolutionFloat, /** * Fixed-point solution positioning (most accurate). */ DJIRTKPositioningSolutionFixedPoint, }; /** * This protocol provides a delegate method to update the RTK state. */ @protocol DJIRTKDelegate <NSObject> @optional /** * Callback function that updates the RTK state data. * * @param rtk Instance of the RTK. * @param state Current state of the RTK. */ - (void)rtk:(DJIRTK *_Nonnull)rtk didUpdateState:(DJIRTKState *_Nonnull)state; @end /** * Single RTK receiver information. Each receiver is connected to a single antenna. */ @interface DJIRTKReceiverInfo : NSObject /** * `YES` if constellation is supported. The European and American versions of RTK * support GPS and GLONASS, while the Asia Pacific version supports GPS and BeiDou. */ @property(nonatomic, readonly) BOOL isConstellationSupported; /** * Valid satellite count for this receiver. */ @property(nonatomic, readonly) NSInteger satelliteCount; @end /** * This class holds the state of the RTK system, including position, positioning * solution, and receiver information. */ @interface DJIRTKState : NSObject /** * Gets RTK errors, if any. Returns `nil` when RTK is normal. */ @property(nonatomic, readonly) NSError *_Nullable error; /** * The positioning solution describes the method used to determine positioning. The * solutions vary in accuracy, from `DJIRTKPositioningSolutionNone` (no * positioning) to `DJIRTKPositioningSolutionFixedPoint`. */ @property(nonatomic, readonly) DJIRTKPositioningSolution positioningSolution; /** * Mobile station (aircraft) receiver 1 GPS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver1GPSInfo; /** * Mobile station (aircraft) receiver 1 BeiDou info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver1BeiDouInfo; /** * Mobile station (aircraft) receiver 1 GLONASS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver1GLONASSInfo; /** * Mobile station (aircraft) receiver 2 GPS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver2GPSInfo; /** * Mobile station (aircraft) receiver 2 BeiDou info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver2BeiDouInfo; /** * Mobile station (aircraft) receiver 2 GLONASS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull mobileStationReceiver2GLONASSInfo; /** * Base station receiver GPS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull baseStationReceiverGPSInfo; /** * Base station receiver BeiDou info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull baseStationReceiverBeiDouInfo; /** * Base station receiver GLONASS info. */ @property(nonatomic, readonly) DJIRTKReceiverInfo *_Nonnull baseStationReceiverGLONASSInfo; /** * Location information of the mobile station's receiver 1 antenna. This location * information is relative to the ground system location and is in degrees. */ @property(nonatomic, readonly) CLLocationCoordinate2D mobileStationLocation; /** * Altitude of the mobile station's receiver 1 antenna relative, to sea level. * Units are meters. */ @property(nonatomic, readonly) float mobileStationAltitude; /** * The fusion location of the mobile station (in degrees). It is the combination of * GPS and RTK. The flight controller uses this location for navigation (e.g. * waypoint mission) when RTK is available. */ @property(nonatomic, readonly) CLLocationCoordinate2D mobileStationFusionLocation; /** * The fusion altitude of the mobile station. It is the combination of GPS, RTK and * the barometer. The flight controller uses this altitude for navigation (e.g. * waypoint mission) when RTK is available. */ @property(nonatomic, readonly) float mobileStationFusionAltitude; /** * The fusion heading of the mobile station. It is the combination of RTK and the * compass. The flight controller uses this heading for navigation (e.g. waypoint * mission) when RTK is available. */ @property(nonatomic, readonly) float mobileStationFusionHeading; /** * Base station's location coordinates, in degrees. */ @property(nonatomic, readonly) CLLocationCoordinate2D baseStationLocation; /** * Altitude of the base station above sea level, in meters. */ @property(nonatomic, readonly) float baseStationAltitude; /** * Heading relative to True North as defined by the vector formed from Antenna 2 to * Antenna 1 on the mobile station. Unit is degrees. */ @property(nonatomic, readonly) float heading; /** * `YES` if heading value is valid. Heading is invalid when a satellite fix hasn't * been obtained. */ @property(nonatomic, readonly) BOOL isHeadingValid; /** * Returns state of RTK (enabled/disabled). */ @property(nonatomic, readonly) BOOL isRTKEnabled; /** * Whether the RTK is being used. */ @property(nonatomic, readonly) BOOL isRTKBeingUsed; @end /** * Real Time Kinematic */ @interface DJIRTK : NSObject /** * DJI RTK delegate. */ @property(nonatomic, weak) id<DJIRTKDelegate> delegate; /** * `YES` if RTK is connected to the aircraft. */ @property(nonatomic, readonly) BOOL isConnected; /** * Enables RTK positioning. Disable RTK when in poor signal environments, where * incorrect positioning information might make controlling the aircraft difficult. * Can only be set when the motors are off. * * @param enabled `YES` to enable RTK positioning. * @param completion Completion block that receives setter result. */ - (void)setRTKEnabled:(BOOL)enabled withCompletion:(DJICompletionBlock)completion; @end NS_ASSUME_NONNULL_END
24.098182
94
0.740305
[ "vector" ]
a9d2a4096a4d7c752f312fabf7eeeb715592ed23
535
h
C
CZOrganizerSDK/CZOrganizerSDK/UI/SchoolStar/SchoolStarShopDetail/CustomView/CZSchoolStarShopCaseCollectionView.h
RickZhaoShuCheng/StudyAbroad
9691bf33058c9cdbaa3e29f1501f3588f2e3b644
[ "MIT" ]
null
null
null
CZOrganizerSDK/CZOrganizerSDK/UI/SchoolStar/SchoolStarShopDetail/CustomView/CZSchoolStarShopCaseCollectionView.h
RickZhaoShuCheng/StudyAbroad
9691bf33058c9cdbaa3e29f1501f3588f2e3b644
[ "MIT" ]
null
null
null
CZOrganizerSDK/CZOrganizerSDK/UI/SchoolStar/SchoolStarShopDetail/CustomView/CZSchoolStarShopCaseCollectionView.h
RickZhaoShuCheng/StudyAbroad
9691bf33058c9cdbaa3e29f1501f3588f2e3b644
[ "MIT" ]
null
null
null
// // SchoolStarShopCaseCollectionView.h // CZOrganizerSDK // // Created by 谢朋远 on 2020/4/10. // Copyright © 2020 zsc. All rights reserved. // #import <UIKit/UIKit.h> #import "CZCaseModel.h" NS_ASSUME_NONNULL_BEGIN @interface CZSchoolStarShopCaseCollectionView : UICollectionView @property (nonatomic ,strong) NSMutableArray *dataArr; //点击案例 @property (nonatomic ,copy) void (^selectCaseBlock)(CZCaseModel *model); /** * 滚动值 */ @property (nonatomic,copy) void (^scrollContentSize)(CGFloat offsetY); @end NS_ASSUME_NONNULL_END
22.291667
72
0.757009
[ "model" ]
a9d3bcf3c56732279923b13df0e4e8ec570d51d1
7,240
c
C
lib/src/tests/check_types_custom.c
luzidl/Machinebeat
358e52b555a15972f47dc3543660ab7c633a12b6
[ "Apache-2.0" ]
null
null
null
lib/src/tests/check_types_custom.c
luzidl/Machinebeat
358e52b555a15972f47dc3543660ab7c633a12b6
[ "Apache-2.0" ]
null
null
null
lib/src/tests/check_types_custom.c
luzidl/Machinebeat
358e52b555a15972f47dc3543660ab7c633a12b6
[ "Apache-2.0" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ua_types.h" #include "ua_types_generated_handling.h" #include "ua_types_encoding_binary.h" #include "ua_util.h" #include "check.h" #ifdef __clang__ //required for ck_assert_ptr_eq and const casting #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wincompatible-pointer-types-discards-qualifiers" #endif /* The standard-defined datatypes are stored in the global array UA_TYPES. User * can create their own UA_CUSTOM_TYPES array (the name doesn't matter) and * provide it to the server / client. The type will be automatically decoded if * possible. */ /* The custom datatype for describing a 3d position */ typedef struct { UA_Float x; UA_Float y; UA_Float z; } Point; /* The datatype description for the Point datatype */ #define padding_y offsetof(Point,y) - offsetof(Point,x) - sizeof(UA_Float) #define padding_z offsetof(Point,z) - offsetof(Point,y) - sizeof(UA_Float) static UA_DataTypeMember members[3] = { /* x */ { UA_TYPENAME("x") /* .memberName */ UA_TYPES_FLOAT, /* .memberTypeIndex, points into UA_TYPES since .namespaceZero is true */ 0, /* .padding */ true, /* .namespaceZero, see .memberTypeIndex */ false /* .isArray */ }, /* y */ { UA_TYPENAME("y") UA_TYPES_FLOAT, padding_y, true, false }, /* z */ { UA_TYPENAME("y") UA_TYPES_FLOAT, padding_z, true, false } }; static const UA_DataType PointType = { UA_TYPENAME("Point") /* .typeName */ {1, UA_NODEIDTYPE_NUMERIC, {1}}, /* .typeId */ sizeof(Point), /* .memSize */ 0, /* .typeIndex, in the array of custom types */ 3, /* .membersSize */ false, /* .builtin */ true, /* .pointerFree */ false, /* .overlayable (depends on endianness and the absence of padding) */ 0, /* .binaryEncodingId, the numeric identifier used on the wire (the namespaceindex is from .typeId) */ members }; START_TEST(parseCustomScalar) { Point p; p.x = 1.0; p.y = 2.0; p.z = 3.0; UA_Variant var; UA_Variant_init(&var); UA_Variant_setScalar(&var, &p, &PointType); size_t buflen = UA_calcSizeBinary(&var, &UA_TYPES[UA_TYPES_VARIANT]); UA_ByteString buf; UA_StatusCode retval = UA_ByteString_allocBuffer(&buf, buflen); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_Byte *pos = buf.data; const UA_Byte *end = &buf.data[buf.length]; retval = UA_encodeBinary(&var, &UA_TYPES[UA_TYPES_VARIANT], &pos, &end, NULL, NULL); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_Variant var2; size_t offset = 0; retval = UA_decodeBinary(&buf, &offset, &var2, &UA_TYPES[UA_TYPES_VARIANT], 1, &PointType); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); ck_assert(var2.type == &PointType); Point *p2 = (Point*)var2.data; ck_assert(p.x == p2->x); UA_Variant_deleteMembers(&var2); UA_ByteString_deleteMembers(&buf); } END_TEST START_TEST(parseCustomScalarExtensionObject) { Point p; p.x = 1.0; p.y = 2.0; p.z = 3.0; UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED_NODELETE; eo.content.decoded.data = &p; eo.content.decoded.type = &PointType; size_t buflen = UA_calcSizeBinary(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); UA_ByteString buf; UA_StatusCode retval = UA_ByteString_allocBuffer(&buf, buflen); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_Byte *bufPos = buf.data; const UA_Byte *bufEnd = &buf.data[buf.length]; retval = UA_encodeBinary(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], &bufPos, &bufEnd, NULL, NULL); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_ExtensionObject eo2; size_t offset = 0; retval = UA_decodeBinary(&buf, &offset, &eo2, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], 1, &PointType); ck_assert_int_eq(offset, (uintptr_t)(bufPos - buf.data)); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); ck_assert_int_eq(eo2.encoding, UA_EXTENSIONOBJECT_DECODED); ck_assert(eo2.content.decoded.type == &PointType); Point *p2 = (Point*)eo2.content.decoded.data; ck_assert(p.x == p2->x); UA_ExtensionObject_deleteMembers(&eo2); UA_ByteString_deleteMembers(&buf); } END_TEST START_TEST(parseCustomArray) { Point ps[10]; for(size_t i = 0; i < 10; ++i) { ps[i].x = (UA_Float)(1*i); ps[i].y = (UA_Float)(2*i); ps[i].z = (UA_Float)(3*i); } UA_Variant var; UA_Variant_init(&var); UA_Variant_setArray(&var, (void*)ps, 10, &PointType); size_t buflen = UA_calcSizeBinary(&var, &UA_TYPES[UA_TYPES_VARIANT]); UA_ByteString buf; UA_StatusCode retval = UA_ByteString_allocBuffer(&buf, buflen); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_Byte *pos = buf.data; const UA_Byte *end = &buf.data[buf.length]; retval = UA_encodeBinary(&var, &UA_TYPES[UA_TYPES_VARIANT], &pos, &end, NULL, NULL); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); UA_Variant var2; size_t offset = 0; retval = UA_decodeBinary(&buf, &offset, &var2, &UA_TYPES[UA_TYPES_VARIANT], 1, &PointType); ck_assert_int_eq(retval, UA_STATUSCODE_GOOD); ck_assert(var2.type == &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ck_assert_int_eq(var2.arrayLength, 10); for (size_t i = 0; i < 10; i++) { UA_ExtensionObject *eo = &((UA_ExtensionObject*)var2.data)[i]; ck_assert_int_eq(eo->encoding, UA_EXTENSIONOBJECT_DECODED); ck_assert(eo->content.decoded.type == &PointType); Point *p2 = (Point*)eo->content.decoded.data; // we need to cast floats to int to avoid comparison of floats // which may result into false results ck_assert((int)p2->x == (int)ps[i].x); ck_assert((int)p2->y == (int)ps[i].y); ck_assert((int)p2->z == (int)ps[i].z); } UA_Variant_deleteMembers(&var2); UA_ByteString_deleteMembers(&buf); } END_TEST int main(void) { Suite *s = suite_create("Test Custom DataType Encoding"); TCase *tc = tcase_create("test cases"); tcase_add_test(tc, parseCustomScalar); tcase_add_test(tc, parseCustomScalarExtensionObject); tcase_add_test(tc, parseCustomArray); suite_add_tcase(s, tc); SRunner *sr = srunner_create(s); srunner_set_fork_status(sr, CK_NOFORK); srunner_run_all (sr, CK_NORMAL); int number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } #ifdef __clang__ #pragma clang diagnostic pop #endif
33.518519
102
0.633978
[ "3d" ]
a9d4bda90e55867601f9ca775f5f3e640612af18
3,933
h
C
Event/Recon/CalRecon/CalXtalsParams.h
fermi-lat/Event
2e9e8ee117f61c4b1abde69828a97f94ff84630a
[ "BSD-3-Clause" ]
null
null
null
Event/Recon/CalRecon/CalXtalsParams.h
fermi-lat/Event
2e9e8ee117f61c4b1abde69828a97f94ff84630a
[ "BSD-3-Clause" ]
null
null
null
Event/Recon/CalRecon/CalXtalsParams.h
fermi-lat/Event
2e9e8ee117f61c4b1abde69828a97f94ff84630a
[ "BSD-3-Clause" ]
null
null
null
#ifndef CalXtalsParams_H #define CalXtalsParams_H /** @file CalXtalsParams.h @class CalXtalsParams @brief Gaudi TDS class to store the basic quantities related to a collection of CAL xtals. These include the number of xtals in the collection, the number of saturated xtals, the number ox xtals exceeding a certainf fraction of the total energy, the moments of the xtal energy distribution etc. Whenever this class is changed, the changes should be propagated to the related files on the ROOT side: - reconRootData/reconRootData/CalXtalsParams.h - reconRootData/src/CalXtalsParams.cxx @author Luca Baldini (luca.baldini@pi.infn.it) $Revision: 1.2 $ $Date: 2011/01/19 17:34:01 $ $Header: /nfs/slac/g/glast/ground/cvs/Event/Event/Recon/CalRecon/CalXtalsParams.h,v 1.2 2011/01/19 17:34:01 lbaldini Exp $ */ #include <iostream> #include "geometry/Point.h" namespace Event { //Namespace Event class CalXtalsParams { public: /// Default (no parameter) constructor. CalXtalsParams() { clear(); } /// Constructor from all members. CalXtalsParams(int numXtals, int numTruncXtals, int numSaturatedXtals, double xtalRawEneSum, double xtalCorrEneSum, double xtalEneMax, double xtalEneRms, double xtalEneSkewness, const Point& centroid); /// Convenience constructor from the two members originally in the CalCluster class. CalXtalsParams(int numTruncXtals, int numSaturatedXtals); /// Destructor. ~CalXtalsParams() {} /// Reset method. void clear(); /// Retrieve class parameters... inline int getNumXtals() const { return m_numXtals; } inline int getNumTruncXtals() const { return m_numTruncXtals; } inline int getNumSaturatedXtals() const { return m_numSaturatedXtals; } inline double getXtalRawEneSum() const { return m_xtalRawEneSum; } inline double getXtalCorrEneSum() const { return m_xtalCorrEneSum; } inline double getXtalEneMax() const { return m_xtalEneMax; } inline double getXtalEneRms() const { return m_xtalEneRms; } inline double getXtalEneSkewness() const { return m_xtalEneSkewness; } inline const Point& getCentroid() const { return m_centroid;} /// Set class parameters. inline void setNumXtals(int val) { m_numXtals = val; } inline void setNumTruncXtals(int val) { m_numTruncXtals = val; } inline void setNumSaturatedXtals(int val) { m_numSaturatedXtals = val; } inline void setXtalRawEneSum(double val) { m_xtalRawEneSum = val; } inline void setXtalCorrEneSum(double val) { m_xtalCorrEneSum = val; } inline void setXtalEneMax(double val) { m_xtalEneMax = val; } inline void setXtalEneRms(double val) { m_xtalEneRms = val; } inline void setXtalEneSkewness(double val) { m_xtalEneSkewness = val; } inline void setCentroid(const Point& pos) { m_centroid = pos; } /// Std output facility. std::ostream& fillStream(std::ostream& s) const; friend std::ostream& operator<< (std::ostream& s, const CalXtalsParams& obj) { return obj.fillStream(s); } private: /// Number of xtals. int m_numXtals; /// Number of Xtals with > 1% (adjustable) of the total cluster energy. int m_numTruncXtals; /// Number of saturated xtals. int m_numSaturatedXtals; /// Plain sum of the xtal energies. double m_xtalRawEneSum; /// Corrected sum of the xtal energies. double m_xtalCorrEneSum; /// The energy of the xtal with the highest signal. double m_xtalEneMax; /// Rms of the xtal energy distribution. double m_xtalEneRms; /// Skewness of the xtal energy distribution. double m_xtalEneSkewness; /// Centroid of the xtal collection. Point m_centroid; }; }; //Namespace Event #endif
35.754545
125
0.683193
[ "geometry" ]
a9d4efbc410d603f54c17fc0f2928747235313ee
4,590
h
C
src/CppParser/AST.h
ChristophBender/CppSharp
59e766a394000e63bbb7fb7236b7cb9f83083e59
[ "MIT" ]
7
2015-01-09T17:59:21.000Z
2021-06-14T18:57:14.000Z
src/CppParser/AST.h
ChristophBender/CppSharp
59e766a394000e63bbb7fb7236b7cb9f83083e59
[ "MIT" ]
2
2021-02-21T01:27:25.000Z
2021-02-21T04:27:27.000Z
src/CppParser/AST.h
ChristophBender/CppSharp
59e766a394000e63bbb7fb7236b7cb9f83083e59
[ "MIT" ]
4
2021-02-15T14:00:54.000Z
2021-06-30T05:39:06.000Z
/************************************************************************ * * CppSharp * Licensed under the MIT license. * ************************************************************************/ #pragma once #include "Helpers.h" #include "Sources.h" #include "Types.h" #include "Decl.h" #include "Stmt.h" #include "Expr.h" #include <algorithm> namespace CppSharp { namespace CppParser { namespace AST { #pragma region Libraries enum class ArchType { UnknownArch, x86, x86_64 }; class CS_API NativeLibrary { public: NativeLibrary(); ~NativeLibrary(); std::string fileName; ArchType archType; VECTOR_STRING(Symbols) VECTOR_STRING(Dependencies) }; #pragma endregion #pragma region Comments enum struct CommentKind { FullComment, BlockContentComment, BlockCommandComment, ParamCommandComment, TParamCommandComment, VerbatimBlockComment, VerbatimLineComment, ParagraphComment, HTMLTagComment, HTMLStartTagComment, HTMLEndTagComment, TextComment, InlineContentComment, InlineCommandComment, VerbatimBlockLineComment }; class CS_API CS_ABSTRACT Comment { public: Comment(CommentKind kind); CommentKind kind; }; class CS_API BlockContentComment : public Comment { public: BlockContentComment(); BlockContentComment(CommentKind Kind); }; class CS_API FullComment : public Comment { public: FullComment(); ~FullComment(); VECTOR(BlockContentComment*, Blocks) }; class CS_API InlineContentComment : public Comment { public: InlineContentComment(); InlineContentComment(CommentKind Kind); bool hasTrailingNewline; }; class CS_API ParagraphComment : public BlockContentComment { public: ParagraphComment(); ~ParagraphComment(); bool isWhitespace; VECTOR(InlineContentComment*, Content) }; class CS_API BlockCommandComment : public BlockContentComment { public: class CS_API Argument { public: Argument(); Argument(const Argument&); std::string text; }; BlockCommandComment(); BlockCommandComment(CommentKind Kind); ~BlockCommandComment(); unsigned commandId; ParagraphComment* paragraphComment; VECTOR(Argument, Arguments) }; class CS_API ParamCommandComment : public BlockCommandComment { public: enum PassDirection { In, Out, InOut }; ParamCommandComment(); PassDirection direction; unsigned paramIndex; }; class CS_API TParamCommandComment : public BlockCommandComment { public: TParamCommandComment(); VECTOR(unsigned, Position) }; class CS_API VerbatimBlockLineComment : public Comment { public: VerbatimBlockLineComment(); std::string text; }; class CS_API VerbatimBlockComment : public BlockCommandComment { public: VerbatimBlockComment(); ~VerbatimBlockComment(); VECTOR(VerbatimBlockLineComment*, Lines) }; class CS_API VerbatimLineComment : public BlockCommandComment { public: VerbatimLineComment(); std::string text; }; class CS_API InlineCommandComment : public InlineContentComment { public: enum RenderKind { RenderNormal, RenderBold, RenderMonospaced, RenderEmphasized, RenderAnchor }; class CS_API Argument { public: Argument(); Argument(const Argument&); std::string text; }; InlineCommandComment(); unsigned commandId; RenderKind commentRenderKind; VECTOR(Argument, Arguments) }; class CS_API HTMLTagComment : public InlineContentComment { public: HTMLTagComment(); HTMLTagComment(CommentKind Kind); }; class CS_API HTMLStartTagComment : public HTMLTagComment { public: class CS_API Attribute { public: Attribute(); Attribute(const Attribute&); std::string name; std::string value; }; HTMLStartTagComment(); std::string tagName; VECTOR(Attribute, Attributes) }; class CS_API HTMLEndTagComment : public HTMLTagComment { public: HTMLEndTagComment(); std::string tagName; }; class CS_API TextComment : public InlineContentComment { public: TextComment(); std::string text; }; enum class RawCommentKind { Invalid, OrdinaryBCPL, OrdinaryC, BCPLSlash, BCPLExcl, JavaDoc, Qt, Merged }; class CS_API RawComment { public: RawComment(); ~RawComment(); RawCommentKind kind; std::string text; std::string briefText; FullComment* fullCommentBlock; }; #pragma region Commands #pragma endregion #pragma endregion } } }
18.142292
73
0.675163
[ "vector" ]
a9d722184f9c9527efa27b07ffe2c6bd5367b23f
1,400
h
C
Common01/Source/Common/DAG/DagNodeValue.h
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/DAG/DagNodeValue.h
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/DAG/DagNodeValue.h
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
#pragma once #include "common/dag/idagnode.h" /* combine DagValue and DagNodeValue, or would that result in too much in the resultant class DagNodeValue holds the DagValue and deals with the links/ dirty */ class iDagValue; class DagNodeValue : public iDagNode { public: /* bMarkDirtyOnSet==false is used for passing in a ref to DrawSystemFrame* (interface to set render target, draw things for the current frame) */ static std::shared_ptr< iDagNode > Factory( const std::shared_ptr< iDagValue >& pValue, const bool bMarkDirtyOnSet = true ); DagNodeValue( const std::shared_ptr< iDagValue >& pValue, const bool bMarkDirtyOnSet = true ); ~DagNodeValue(); private: virtual void SetValue( const std::shared_ptr< iDagValue >& pValue ) override; virtual std::shared_ptr< iDagValue >& GetValue( void ) override; virtual void OnMarkDirty() override; virtual void StackInputPush(iDagNode* const pNode) override; virtual void OrderedInputSet(const int index, iDagNode* const pNodeOrNullptr) override; virtual void StackInputRemove(iDagNode* const pNode) override; virtual void RemoveAllInput(void) override; virtual void SetOutput(iDagNode* const pNode) override; virtual void RemoveOutput(iDagNode* const pNode) override; private: const bool m_bMarkDirtyOnSet; std::vector< iDagNode* > m_arrayOutput; std::shared_ptr< iDagValue > m_pValue; };
35
142
0.754286
[ "render", "vector" ]
a9da864cb99a68096c83d1a3ec9b72fc12be2150
10,222
h
C
Framework/Source/Utils/OS.h
tfoleyNV/Falcor-old
2155109af2322f2aa1db2385cde44d1b7507976b
[ "BSD-3-Clause" ]
1
2020-03-24T18:16:27.000Z
2020-03-24T18:16:27.000Z
Framework/Source/Utils/OS.h
tfoleyNV/Falcor-old
2155109af2322f2aa1db2385cde44d1b7507976b
[ "BSD-3-Clause" ]
null
null
null
Framework/Source/Utils/OS.h
tfoleyNV/Falcor-old
2155109af2322f2aa1db2385cde44d1b7507976b
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** # Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************/ #pragma once #include <string> #include <vector> #include <thread> #include "API/Window.h" namespace Falcor { class Window; /*! * \addtogroup Falcor * @{ */ /** Adds an icon to the foreground window. \param[in] iconFile Icon file name \param[in] windowHandle The api handle of the window for which we need to set the icon to. nullptr will apply the icon to the foreground window */ void setWindowIcon(const std::string& iconFile, Window::ApiHandle windowHandle); /** Retrieves estimated/user-set pixel density of a display. \return integer value of number of pixels per inch. */ int getDisplayDpi(); /** Type of message box to display */ enum class MsgBoxType { Ok, ///< Single 'OK' button RetryCancel, ///< Retry/Cancel buttons OkCancel, ///< OK/Cancel buttons }; enum class MsgBoxButton { Ok, Retry, Cancel }; /** Display a message box. By default, shows a message box with a single 'OK' button. \param[in] msg The message to display. \param[in] mbType Optional. Type of message box to display \return an enum indicating which button was clicked */ MsgBoxButton msgBox(const std::string& msg, MsgBoxType mbType = MsgBoxType::Ok); /** Finds a file in one of the media directories. The arguments must not alias. \param[in] filename The file to look for \param[in] fullPath If the file was found, the full path to the file. If the file wasn't found, this is invalid. \return true if the file was found, otherwise false */ bool findFileInDataDirectories(const std::string& filename, std::string& fullPath); /** Given a filename, returns the shortest possible path to the file relative to the data directories. If the file is not relative to the data directories, return the original filename */ std::string stripDataDirectories(const std::string& filename); /** Creates a 'open file' dialog box. \param[in] pFilters A string containing pairs of null terminating strings. The first string in each pair is the name of the filter, the second string in a pair is a semicolon separated list of file extensions (for example, "*.TXT;*.DOC;*.BAK"). The last pair in the filter list has to end with a 2 null characters. \filename[in] On successful return, the name of the file selected by the user. \return true if a file was selected, otherwise false (if the user clicked 'Cancel'). */ bool openFileDialog(const char* pFilters, std::string& filename); /** Creates a 'save file' dialog box. \param[in] pFilters A string containing pairs of null terminating strings. The first string in each pair is the name of the filter, the second string in a pair is a semicolon separated list of file extensions (for example, "*.TXT;*.DOC;*.BAK"). The last pair in the filter list has to end with a 2 null characters. \filename[in] On successful return, the name of the file selected by the user. \return true if a file was selected, otherwise false (if the user clicked 'Cancel'). */ bool saveFileDialog(const char* pFilters, std::string& filename); /** Checks if a file exists in the file system. This function doesn't look in the common directories. \param[in] filename The file to look for \return true if the file was found, otherwise false */ bool doesFileExist(const std::string& filename); /** Checks if a directory exists in the file system. \param[in] filename The directory to look for \return true if the directory was found, otherwise false */ bool isDirectoryExists(const std::string& filename); /** Create a directory from path. */ bool createDirectory(const std::string& path); /** Get the current executable directory \return The full path of the application directory */ const std::string& getExecutableDirectory(); /** Get the current executable name \return The name of the executable */ const std::string& getExecutableName(); /** Get the working directory. This can be different from the executable directory (for example, by default when you launch an app from Visual Studio, the working the directory is the directory containing the project file). */ const std::string getWorkingDirectory(); /** Get the content of a system environment variable. \return The value of the environment variable. */ bool getEnvironemntVariable(const std::string& VarName, std::string& Value); /** Get the set containing all recorded data directories. */ const std::vector<std::string>& getDataDirectoriesList(); /** Read a file into a string. The function expects a full path to the file, and will not look in the common directories. \param[in] fullpath The path to the requested file \param[in] str On successful return, the content of the file \return true if the was read successfully, false if an error occurred (usually file not found) */ bool readFileToString(const std::string& fullpath, std::string& str); /** Adds a folder into the search directory. Once added, calls to FindFileInCommonDirs() will seach that directory as well \param[in] dir The new directory to add to the common directories. */ void addDataDirectory(const std::string& dir); /** Find a new filename based on the supplied parameters. This function doesn't actually create the file, just find an available file name. \param[in] prefix Requested file prefix. \param[in] directory The directory to create the file in. \param[in] extension The requested file extension. \param[out] filename On success, will hold a valid unused filename in the following format - 'Directory\\Prefix.<index>.Extension'. \return true if an available filename was found, otherwise false. */ bool findAvailableFilename(const std::string& prefix, const std::string& directory, const std::string& extension, std::string& filename); /** Check if a debugger session is attached. \return true if debugger is attached to the Falcor process. */ bool isDebuggerPresent(); /** Remove navigational elements ('.', '..) from a given path/filename and make slash direction consistent. */ std::string canonicalizeFilename(const std::string& filename); /** Breaks in debugger (int 3 functionality) */ void debugBreak(); /** Print a message into the debug window */ void printToDebugWindow(const std::string& s); /** Get directory from filename. */ std::string getDirectoryFromFile(const std::string& filename); /** Strip path from a full filename */ std::string getFilenameFromPath(const std::string& filename); /** Swap file extension (very simple implementation) */ std::string swapFileExtension(const std::string& str, const std::string& currentExtension, const std::string& newExtension); /** Enumerate Files Using search string */ void enumerateFiles(std::string searchString, std::vector<std::string>& filenames); /** Return current thread handle */ std::thread::native_handle_type getCurrentThread(); /** Sets thread affinity mask */ void setThreadAffinity(std::thread::native_handle_type thread, uint32_t affinityMask); /** Get the last time a file was modified. If the file is not found will return 0 */ time_t getFileModifiedTime(const std::string& filename); enum class ThreadPriorityType : int32_t { BackgroundBegin = -2, //< Indicates I/O-intense thread BackgroundEnd = -1, //< Indicates the end of I/O-intense operations in the thread Lowest = 0, //< Lowest priority Low = 1, Normal = 2, High = 3, Highest = 4, }; /** Sets thread priority */ void setThreadPriority(std::thread::native_handle_type thread, ThreadPriorityType priority); /** Get the Total Virtual Memory. */ uint64_t getTotalVirtualMemory(); /** Get the Used Virtual Memory. */ uint64_t getUsedVirtualMemory(); /** Get the Virtual Memory Used by this Process. */ uint64_t getProcessUsedVirtualMemory(); /*! @} */ };
43.130802
227
0.67521
[ "vector" ]
a9daf9482cfc66397fa11ee7db2100e8fab2076c
281
h
C
src/individual.h
gabrielfelipeg/TravellingSalesman-GeneticAlgo
784dd4a3b3f06633c99f040ff42231ad0377868f
[ "MIT" ]
2
2019-12-11T18:15:48.000Z
2019-12-12T18:46:54.000Z
src/individual.h
gabrielfelipeg/TravellingSalesman-GeneticAlgo
784dd4a3b3f06633c99f040ff42231ad0377868f
[ "MIT" ]
1
2019-12-12T17:52:03.000Z
2019-12-12T17:52:03.000Z
src/individual.h
gabrielfelipeg/TravellingSalesman-GeneticAlgo
784dd4a3b3f06633c99f040ff42231ad0377868f
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <cstdlib> #include <algorithm> #include <iostream> class Individual{ public: std::vector<int> chromosome; void mutate(); Individual(); bool isValid(int tam); Individual(std::vector<int> param); };
20.071429
43
0.622776
[ "vector" ]
a9e1909d1228d62892108cce6b1b67e1d04948bc
2,046
h
C
flexible_buffer.h
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
null
null
null
flexible_buffer.h
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
1
2015-08-21T06:31:32.000Z
2015-08-21T06:32:06.000Z
flexible_buffer.h
arsee11/arseeulib
528afa07d182e76ce74255a53ee01d73c2fae66f
[ "BSD-2-Clause" ]
1
2016-07-23T04:03:15.000Z
2016-07-23T04:03:15.000Z
///flexible_buffer.h #ifndef FLEXIBLE_BUFFER_H #define FLEXIBLE_BUFFER_H #include <vector> #include <tuple> #ifndef NAMESPDEF_H #include "namespdef.h" #endif using std::size_t; NAMESP_BEGIN ///a flexible buffer. ///capacity can be increase or decrease dynamically. ///not thread safety. template<typename T> class FlexibleBuffer { const static size_t factor=1; public: FlexibleBuffer(size_t n) :_begin(0) ,_end(0) ,_buf(n) {} ~FlexibleBuffer(){} typedef T value_type; typedef value_type& reference; typedef value_type* pointer; typedef const value_type* const_pointer; typedef pointer iterator; typedef const iterator const_iterator; public: void push( const_pointer data, size_t len){ if( (capacity()-size()) < len ) increase( (len-(capacity()-size()) ) *factor); std::copy(data, data+len, end()); _end += len; } ///@param len number of item need. ///@return 1st pointer to the datas, 2nd number of item obained. std::tuple<pointer, size_t> head(size_t len){ if( size() >= len ) { return std::make_tuple(begin(), len); } else { return std::make_tuple(begin(), size()); } } ///@param len the number of item to be consumed. ///@return if size() >= len return true,\n /// else return false. bool consume(size_t len){ if( size() < len ) return false; size_t s = size()-len; std::copy(begin()+len, end(), _buf.begin() ); _begin=0; _end = _begin+s; return true; } void clear(){ _begin=_end=0; } pointer operator[](size_t i){ if( size() > i) return begin()+i; return nullptr; } iterator begin(){ return &_buf[_begin]; } iterator end(){ return &_buf[_end]; } size_t size(){ return _end - _begin; } size_t capacity(){ return _buf.capacity(); } private: void increase(size_t size){ _buf.resize( capacity()+size ); } void decrease(size_t size){ _buf.resize( capacity()-size ); } private: size_t _begin, _end; std::vector<T> _buf; }; NAMESP_END/*namespace*/ #endif/*FLEXIBLE_BUFFER_H*/
16.110236
65
0.651515
[ "vector" ]
a9edfb3e1b2ee6b63d40bda30e799dc63bc124be
3,286
h
C
modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h
Tunnel-Vizion/webrtc
7c256c99a1b4a4d2cbe9078df77f42e425418a12
[ "BSD-3-Clause" ]
1
2021-03-22T22:39:45.000Z
2021-03-22T22:39:45.000Z
modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h
Tunnel-Vizion/webrtc
7c256c99a1b4a4d2cbe9078df77f42e425418a12
[ "BSD-3-Clause" ]
null
null
null
modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h
Tunnel-Vizion/webrtc
7c256c99a1b4a4d2cbe9078df77f42e425418a12
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // This class estimates the incoming available bandwidth. #ifndef MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_REMOTE_BITRATE_ESTIMATOR_H_ #define MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_REMOTE_BITRATE_ESTIMATOR_H_ #include <map> #include <memory> #include <vector> #include "modules/include/module.h" #include "modules/include/module_common_types.h" #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/rtcp_packet.h" namespace webrtc { class Clock; // RemoteBitrateObserver is used to signal changes in bitrate estimates for // the incoming streams. class RemoteBitrateObserver { public: // Called when a receive channel group has a new bitrate estimate for the // incoming streams. virtual void OnReceiveBitrateChanged(const std::vector<uint32_t>& ssrcs, uint32_t bitrate) = 0; virtual ~RemoteBitrateObserver() {} }; // TODO(bugs.webrtc.org/12693): Deprecate class TransportFeedbackSenderInterface { public: virtual ~TransportFeedbackSenderInterface() = default; virtual bool SendCombinedRtcpPacket( std::vector<std::unique_ptr<rtcp::RtcpPacket>> packets) = 0; }; // TODO(holmer): Remove when all implementations have been updated. struct ReceiveBandwidthEstimatorStats {}; class RemoteBitrateEstimator : public CallStatsObserver, public Module { public: ~RemoteBitrateEstimator() override {} // Called for each incoming packet. Updates the incoming payload bitrate // estimate and the over-use detector. If an over-use is detected the // remote bitrate estimate will be updated. Note that |payload_size| is the // packet size excluding headers. // Note that |arrival_time_ms| can be of an arbitrary time base. virtual void IncomingPacket(int64_t arrival_time_ms, size_t payload_size, const RTPHeader& header) = 0; // Removes all data for |ssrc|. virtual void RemoveStream(uint32_t ssrc) = 0; // Returns true if a valid estimate exists and sets |bitrate_bps| to the // estimated payload bitrate in bits per second. |ssrcs| is the list of ssrcs // currently being received and of which the bitrate estimate is based upon. virtual bool LatestEstimate(std::vector<uint32_t>* ssrcs, uint32_t* bitrate_bps) const = 0; // TODO(holmer): Remove when all implementations have been updated. virtual bool GetStats(ReceiveBandwidthEstimatorStats* output) const; virtual void SetMinBitrate(int min_bitrate_bps) = 0; protected: static const int64_t kProcessIntervalMs = 500; static const int64_t kStreamTimeOutMs = 2000; }; inline bool RemoteBitrateEstimator::GetStats( ReceiveBandwidthEstimatorStats* output) const { return false; } } // namespace webrtc #endif // MODULES_REMOTE_BITRATE_ESTIMATOR_INCLUDE_REMOTE_BITRATE_ESTIMATOR_H_
35.333333
79
0.744979
[ "vector" ]
a9efed027ea3aad8ccf9e115554a742268facd91
24,008
h
C
Code/Engine/Foundation/Strings/StringBuilder.h
alinoctavian/ezEngine
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
[ "MIT" ]
null
null
null
Code/Engine/Foundation/Strings/StringBuilder.h
alinoctavian/ezEngine
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
[ "MIT" ]
null
null
null
Code/Engine/Foundation/Strings/StringBuilder.h
alinoctavian/ezEngine
0312c8d777c05ac58911f3fa879e4fd7efcfcb66
[ "MIT" ]
null
null
null
#pragma once #include <Foundation/ThirdParty/utf8/utf8.h> #include <Foundation/Containers/HybridArray.h> #include <Foundation/Memory/MemoryUtils.h> #include <Foundation/Strings/FormatString.h> #include <Foundation/Strings/Implementation/StringBase.h> #include <Foundation/Strings/PathUtils.h> #include <Foundation/Strings/StringUtils.h> #include <Foundation/Strings/StringView.h> template <ezUInt16 Size> struct ezHybridStringBase; template <ezUInt16 Size, typename AllocatorWrapper> struct ezHybridString; class ezStreamReader; class ezFormatString; /// \brief ezStringBuilder is a class that is meant for creating and modifying strings. /// /// It is not meant to store strings for a longer duration. /// Each ezStringBuilder uses an ezHybridArray to allocate a large buffer on the stack, such that string manipulations /// are possible without memory allocations, unless the string is too large. /// No sharing of data happens between ezStringBuilder instances, as it is expected that they will be modified anyway. /// Instead all data is always copied, therefore instances should not be passed by copy. /// All string data is stored Utf8 encoded, just as all other string classes, too. /// That makes it difficult to modify individual characters. Instead you should prefer high-level functions /// such as 'ReplaceSubString'. If individual characters must be modified, it might make more sense to create /// a second ezStringBuilder, and iterate over the first while rebuilding the desired result in the second. /// Once a string is built and should only be stored for read access, it should be stored in an ezString instance. class EZ_FOUNDATION_DLL ezStringBuilder : public ezStringBase<ezStringBuilder> { public: /// \brief Initializes the string to be empty. No data is allocated, but the ezStringBuilder ALWAYS creates an array on the stack. ezStringBuilder(ezAllocatorBase* pAllocator = ezFoundation::GetDefaultAllocator()); // [tested] /// \brief Copies the given string into this one. ezStringBuilder(const ezStringBuilder& rhs); // [tested] /// \brief Moves the given string into this one. ezStringBuilder(ezStringBuilder&& rhs) noexcept; /// \brief Copies the given string into this one. template <ezUInt16 Size> ezStringBuilder(const ezHybridStringBase<Size>& rhs) : m_uiCharacterCount(rhs.m_uiCharacterCount) , m_Data(rhs.m_Data) { } /// \brief Copies the given string into this one. template <ezUInt16 Size, typename A> ezStringBuilder(const ezHybridString<Size, A>& rhs) : m_uiCharacterCount(rhs.m_uiCharacterCount) , m_Data(rhs.m_Data) { } /// \brief Moves the given string into this one. template <ezUInt16 Size> ezStringBuilder(ezHybridStringBase<Size>&& rhs) : m_uiCharacterCount(rhs.m_uiCharacterCount) , m_Data(std::move(rhs.m_Data)) { } /// \brief Moves the given string into this one. template <ezUInt16 Size, typename A> ezStringBuilder(ezHybridString<Size, A>&& rhs) : m_uiCharacterCount(rhs.m_uiCharacterCount) , m_Data(std::move(rhs.m_Data)) { } /// \brief Constructor that appends all the given strings. ezStringBuilder(const char* pData1, const char* pData2, const char* pData3 = nullptr, const char* pData4 = nullptr, const char* pData5 = nullptr, const char* pData6 = nullptr); // [tested] /// \brief Copies the given Utf8 string into this one. /* implicit */ ezStringBuilder(const char* szUTF8, ezAllocatorBase* pAllocator = ezFoundation::GetDefaultAllocator()); // [tested] /// \brief Copies the given wchar_t string into this one. /* implicit */ ezStringBuilder(const wchar_t* szWChar, ezAllocatorBase* pAllocator = ezFoundation::GetDefaultAllocator()); // [tested] /// \brief Copies the given substring into this one. The ezStringView might actually be a substring of this very string. /* implicit */ ezStringBuilder(const ezStringView& rhs, ezAllocatorBase* pAllocator = ezFoundation::GetDefaultAllocator()); // [tested] /// \brief Copies the given string into this one. void operator=(const ezStringBuilder& rhs); // [tested] /// \brief Moves the given string into this one. void operator=(ezStringBuilder&& rhs) noexcept; /// \brief Copies the given Utf8 string into this one. void operator=(const char* szUTF8); // [tested] /// \brief Copies the given wchar_t string into this one. void operator=(const wchar_t* szWChar); // [tested] /// \brief Copies the given substring into this one. The ezStringView might actually be a substring of this very string. void operator=(const ezStringView& rhs); // [tested] /// \brief Copies the given string into this one. template <ezUInt16 Size> void operator=(const ezHybridStringBase<Size>& rhs) { m_uiCharacterCount = rhs.m_uiCharacterCount; m_Data = rhs.m_Data; } /// \brief Copies the given string into this one. template <ezUInt16 Size, typename A> void operator=(const ezHybridString<Size, A>& rhs) { m_uiCharacterCount = rhs.m_uiCharacterCount; m_Data = rhs.m_Data; } /// \brief Moves the given string into this one. template <ezUInt16 Size> void operator=(ezHybridStringBase<Size>&& rhs) { m_uiCharacterCount = rhs.m_uiCharacterCount; m_Data = std::move(rhs.m_Data); } /// \brief Moves the given string into this one. template <ezUInt16 Size, typename A> void operator=(ezHybridString<Size, A>&& rhs) noexcept { m_uiCharacterCount = rhs.m_uiCharacterCount; m_Data = std::move(rhs.m_Data); } /// \brief Returns the allocator that is used by this object. ezAllocatorBase* GetAllocator() const; /// \brief Returns a string view to this string's data. operator ezStringView() const; // [tested] /// \brief Returns a string view to this string's data. ezStringView GetView() const; /// \brief Returns a pointer to the internal Utf8 string. EZ_ALWAYS_INLINE operator const char *() const { return GetData(); } /// \brief Resets this string to be empty. Does not deallocate any previously allocated data, as it might be reused later again. void Clear(); // [tested] /// \brief Returns a char pointer to the internal Utf8 data. const char* GetData() const; // [tested] /// \brief Returns the number of bytes that this string takes up. ezUInt32 GetElementCount() const; // [tested] /// \brief Returns the number of characters of which this string consists. Might be less than GetElementCount, if it contains Utf8 /// multi-byte characters. ezUInt32 GetCharacterCount() const; // [tested] /// \brief Returns whether this string only contains ASCII characters, which means that GetElementCount() == GetCharacterCount() bool IsPureASCII() const; // [tested] /// \brief Converts all characters to upper case. Might move the string data around, so all iterators to the data will be invalid /// afterwards. void ToUpper(); // [tested] /// \brief Converts all characters to lower case. Might move the string data around, so all iterators to the data will be invalid /// afterwards. void ToLower(); // [tested] /// \brief Changes the single character in this string, to which the iterator currently points. /// /// The string might need to be moved around, if its encoding size changes, however the given iterator will be adjusted /// so that it will always stay valid. /// \note /// This can be a very costly operation (unless this string is pure ASCII). /// It is only provided for the few rare cases where it is more convenient and performance is not of concern. /// If possible, do not use this function, at all. void ChangeCharacter(iterator& it, ezUInt32 uiCharacter); // [tested] /// \brief Sets the string by concatenating all given strings. void Set(const char* pData1, const char* pData2 = nullptr, const char* pData3 = nullptr, const char* pData4 = nullptr, const char* pData5 = nullptr, const char* pData6 = nullptr); /// \brief Copies the string starting at \a pStart up to \a pEnd (exclusive). void SetSubString_FromTo(const char* pStart, const char* pEnd); /// \brief Copies the string starting at \a pStart with a length of \a uiElementCount bytes. void SetSubString_ElementCount(const char* pStart, ezUInt32 uiElementCount); /// \brief Copies the string starting at \a pStart with a length of \a uiCharacterCount characters. void SetSubString_CharacterCount(const char* pStart, ezUInt32 uiCharacterCount); /// \brief Appends a single Utf32 character. void Append(ezUInt32 uiChar); // [tested] /// \brief Appends all the given strings at the back of this string in one operation. void Append(const wchar_t* pData1, const wchar_t* pData2 = nullptr, const wchar_t* pData3 = nullptr, const wchar_t* pData4 = nullptr, const wchar_t* pData5 = nullptr, const wchar_t* pData6 = nullptr); // [tested] /// \brief Appends all the given strings at the back of this string in one operation. void Append(const char* pData1, const char* pData2 = nullptr, const char* pData3 = nullptr, const char* pData4 = nullptr, const char* pData5 = nullptr, const char* pData6 = nullptr); // [tested] /// \brief Appends the given string at the back of this string. void Append(const ezStringView& view); /// \brief Prepends a single Utf32 character. void Prepend(ezUInt32 uiChar); // [tested] /// \brief Prepends all the given strings to the front of this string in one operation. void Prepend(const wchar_t* pData1, const wchar_t* pData2 = nullptr, const wchar_t* pData3 = nullptr, const wchar_t* pData4 = nullptr, const wchar_t* pData5 = nullptr, const wchar_t* pData6 = nullptr); // [tested] /// \brief Prepends all the given strings to the front of this string in one operation. void Prepend(const char* pData1, const char* pData2 = nullptr, const char* pData3 = nullptr, const char* pData4 = nullptr, const char* pData5 = nullptr, const char* pData6 = nullptr); // [tested] /// \brief Sets this string to the formatted string, uses printf-style formatting. void Printf(const char* szUtf8Format, ...); // [tested] /// \brief Sets this string to the formatted string, uses printf-style formatting. void PrintfArgs(const char* szUtf8Format, va_list args); // [tested] /// \brief Replaces this with a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. void Format(const ezFormatString& string); /// \brief Replaces this with a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. template <typename... ARGS> void Format(const char* szFormat, ARGS&&... args) { Format(ezFormatStringImpl<ARGS...>(szFormat, std::forward<ARGS>(args)...)); } /// \brief Appends a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. void AppendFormat(const ezFormatString& string); /// \brief Appends a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. template <typename... ARGS> void AppendFormat(const char* szFormat, ARGS&&... args) { AppendFormat(ezFormatStringImpl<ARGS...>(szFormat, std::forward<ARGS>(args)...)); } /// \brief Prepends a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. void PrependFormat(const ezFormatString& string); /// \brief Prepends a formatted string. Uses '{}' formatting placeholders, see ezFormatString for details. template <typename... ARGS> void PrependFormat(const char* szFormat, ARGS&&... args) { PrependFormat(ezFormatStringImpl<ARGS...>(szFormat, std::forward<ARGS>(args)...)); } /// \brief Removes the first n and last m characters from this string. /// /// This function will never reallocate data. /// Removing characters at the back is very cheap. /// Removing characters at the front needs to move data around, so can be quite costly. void Shrink(ezUInt32 uiShrinkCharsFront, ezUInt32 uiShrinkCharsBack); // [tested] /// \brief Reserves uiNumElements bytes. void Reserve(ezUInt32 uiNumElements); // [tested] /// \brief Replaces the string that starts at szStartPos and ends at szEndPos with the string szReplaceWith. void ReplaceSubString(const char* szStartPos, const char* szEndPos, const ezStringView& szReplaceWith); // [tested] /// \brief A wrapper around ReplaceSubString. Will insert the given string at szInsertAtPos. void Insert(const char* szInsertAtPos, const ezStringView& szTextToInsert); // [tested] /// \brief A wrapper around ReplaceSubString. Will remove the substring which starts at szRemoveFromPos and ends at szRemoveToPos. void Remove(const char* szRemoveFromPos, const char* szRemoveToPos); // [tested] /// \brief Replaces the first occurrence of szSearchFor by szReplacement. Optionally starts searching at szStartSearchAt (or the /// beginning). /// /// Returns the first position where szSearchFor was found, or nullptr if nothing was found (and replaced). const char* ReplaceFirst(const char* szSearchFor, const ezStringView& szReplacement, const char* szStartSearchAt = nullptr); // [tested] /// \brief Case-insensitive version of ReplaceFirst. const char* ReplaceFirst_NoCase(const char* szSearchFor, const ezStringView& szReplacement, const char* szStartSearchAt = nullptr); // [tested] /// \brief Replaces the last occurrence of szSearchFor by szReplacement. Optionally starts searching at szStartSearchAt (or the end). /// /// Returns the last position where szSearchFor was found, or nullptr if nothing was found (and replaced). const char* ReplaceLast(const char* szSearchFor, const ezStringView& szReplacement, const char* szStartSearchAt = nullptr); // [tested] /// \brief Case-insensitive version of ReplaceLast. const char* ReplaceLast_NoCase(const char* szSearchFor, const ezStringView& szReplacement, const char* szStartSearchAt = nullptr); // [tested] /// \brief Replaces all occurrences of szSearchFor by szReplacement. Returns the number of replacements. ezUInt32 ReplaceAll(const char* szSearchFor, const ezStringView& szReplacement); // [tested] /// \brief Case-insensitive version of ReplaceAll. ezUInt32 ReplaceAll_NoCase(const char* szSearchFor, const ezStringView& szReplacement); // [tested] /// \brief Replaces the first occurrence of szSearchFor by szReplaceWith, if szSearchFor was found to be a 'whole word', as indicated by /// the delimiter function IsDelimiterCB. const char* ReplaceWholeWord(const char* szSearchFor, const ezStringView& szReplaceWith, ezStringUtils::EZ_CHARACTER_FILTER IsDelimiterCB); // [tested] /// \brief Case-insensitive version of ReplaceWholeWord. const char* ReplaceWholeWord_NoCase(const char* szSearchFor, const ezStringView& szReplaceWith, ezStringUtils::EZ_CHARACTER_FILTER IsDelimiterCB); // [tested] /// \brief Replaces all occurrences of szSearchFor by szReplaceWith, if szSearchFor was found to be a 'whole word', as indicated by the /// delimiter function IsDelimiterCB. ezUInt32 ReplaceWholeWordAll(const char* szSearchFor, const ezStringView& szReplaceWith, ezStringUtils::EZ_CHARACTER_FILTER IsDelimiterCB); // [tested] /// \brief Case-insensitive version of ReplaceWholeWordAll. ezUInt32 ReplaceWholeWordAll_NoCase(const char* szSearchFor, const ezStringView& szReplaceWith, ezStringUtils::EZ_CHARACTER_FILTER IsDelimiterCB); // [tested] /// \brief Fills the given container with ezStringView's which represent each found substring. /// If bReturnEmptyStrings is true, even empty strings between separators are returned. /// Output must be a container that stores ezStringView's and provides the functions 'Clear' and 'Append'. /// szSeparator1 to szSeparator6 are strings which act as separators and indicate where to split the string. /// This string itself will not be modified. template <typename Container> void Split(bool bReturnEmptyStrings, Container& Output, const char* szSeparator1, const char* szSeparator2 = nullptr, const char* szSeparator3 = nullptr, const char* szSeparator4 = nullptr, const char* szSeparator5 = nullptr, const char* szSeparator6 = nullptr) const; // [tested] /// \brief Replaces the current string with the content from the stream. Reads the stream to its end. void ReadAll(ezStreamReader& Stream); // ******* Path Functions ******** /// \brief Checks whether the given path has any file extension bool HasAnyExtension() const; // [tested] /// \brief Checks whether the given path ends with the given extension. szExtension should start with a '.' for performance reasons, but /// it will work without a '.' too. bool HasExtension(const char* szExtension) const; // [tested] /// \brief Returns the file extension of the given path. Will be empty, if the path does not end with a proper extension. ezStringView GetFileExtension() const; // [tested] /// \brief Returns the file name of a path, excluding the path and extension. /// /// If the path already ends with a path separator, the result will be empty. ezStringView GetFileName() const; // [tested] /// \brief Returns the substring that represents the file name including the file extension. /// /// Returns an empty string, if sPath already ends in a path separator, or is empty itself. ezStringView GetFileNameAndExtension() const; // [tested] /// \brief Returns the directory of the given file, which is the substring up to the last path separator. /// /// If the path already ends in a path separator, and thus points to a folder, instead of a file, the unchanged path is returned. /// "path/to/file" -> "path/to/" /// "path/to/folder/" -> "path/to/folder/" /// "filename" -> "" /// "/file_at_root_level" -> "/" ezStringView GetFileDirectory() const; // [tested] /// \brief Returns true, if the given path represents an absolute path on the current OS. bool IsAbsolutePath() const; // [tested] /// \brief Returns true, if the given path represents a relative path on the current OS. bool IsRelativePath() const; // [tested] /// \brief Returns true, if the given path represents a 'rooted' path. See ezFileSystem for details. bool IsRootedPath() const; // [tested] /// \brief Extracts the root name from a rooted path /// /// ":MyRoot" -> "MyRoot" /// ":MyRoot\folder" -> "MyRoot" /// ":\MyRoot\folder" -> "MyRoot" /// ":/MyRoot\folder" -> "MyRoot" /// Returns an empty string, if the path is not rooted. ezStringView GetRootedPathRootName() const; // [tested] /// \brief Removes "../" where possible, replaces all path separators with /, removes double slashes. /// /// All paths use slashes on all platforms. If you need to convert a path to the OS specific representation, use /// 'MakePathSeparatorsNative' 'MakeCleanPath' will in rare circumstances grow the string by one character. That means it is quite safe to /// assume that it will not waste time on memory allocations. If it is repeatedly called on the same string, it has a minor overhead for /// computing the same string over and over, but no memory allocations will be done (everything is in-place). /// /// Removes all double path separators (slashes and backslashes) in a path, except if the path starts with two (back-)slashes, those are /// kept, as they might indicate a UNC path. void MakeCleanPath(); // [tested] /// \brief Modifies this string to point to the parent directory. /// /// 'uiLevelsUp' can be used to go several folders upwards. It has to be at least one. /// If there are no more folders to go up, "../" is appended as much as needed. void PathParentDirectory(ezUInt32 uiLevelsUp = 1); // [tested] /// \brief Appends several path pieces. Makes sure they are always properly separated by a slash. /// /// Will call 'MakeCleanPath' internally, so the representation of the path might change. void AppendPath(const char* szPath1, const char* szPath2 = nullptr, const char* szPath3 = nullptr, const char* szPath4 = nullptr); // [tested] /// \brief Similar to Append() but the very first argument is a separator that is only appended (once) if the existing string is not empty and does /// not already end with the separator. /// /// This is useful when one wants to append entries that require a separator like a comma in between items. E.g. calling /// AppendWithSeparator(", ", "a", "b"); /// AppendWithSeparator(", ", "c", "d"); /// results in the string "ab, cd" void AppendWithSeparator(ezStringView separator, ezStringView sText1, ezStringView sText2 = ezStringView(), ezStringView sText3 = ezStringView(), ezStringView sText4 = ezStringView(), ezStringView sText5 = ezStringView(), ezStringView sText6 = ezStringView()); /// \brief Changes the file name part of the path, keeps the extension intact (if there is any). void ChangeFileName(const char* szNewFileName); // [tested] /// \brief Changes the file name and the extension part of the path. void ChangeFileNameAndExtension(const char* szNewFileNameWithExtension); // [tested] /// \brief Only changes the file extension of the path. If there is no extension yet, one is appended. /// /// szNewExtension must not start with a dot. void ChangeFileExtension(const char* szNewExtension); // [tested] /// \brief If any extension exists, it is removed, including the dot before it. void RemoveFileExtension(); // [tested] /// \brief Converts this path into a relative path to the path with the awesome variable name 'szAbsolutePathToMakeThisRelativeTo' /// /// If the method succeeds the StringBuilder's contents are modified in place. ezResult MakeRelativeTo(const char* szAbsolutePathToMakeThisRelativeTo); // [tested] /// \brief Cleans this path up and replaces all path separators by the OS specific separator. /// /// This can be used, if you want to present paths in the OS specific form to the user in the UI. /// In all other cases the internal representation uses slashes, no matter on which operating system. void MakePathSeparatorsNative(); // [tested] /// \brief Checks whether this path is a sub-path of the given path. /// /// This function will call 'MakeCleanPath' to be able to compare both paths, thus it might modify the data of this instance. bool IsPathBelowFolder(const char* szPathToFolder); // [tested] /// \brief Returns the amount of bytes that are currently allocated on the heap. ezUInt64 GetHeapMemoryUsage() const { return m_Data.GetHeapMemoryUsage(); } /// \brief Removes all characters from the start and end that appear in the given strings. void Trim(const char* szTrimChars); // [tested] /// \brief Removes all characters from the start and/or end that appear in the given strings. void Trim(const char* szTrimCharsStart, const char* szTrimCharsEnd); // [tested] /// \brief If the string starts with one of the given words (case insensitive), it is removed and the function returns true. bool TrimWordStart( const char* szWord1, const char* szWord2 = nullptr, const char* szWord3 = nullptr, const char* szWord4 = nullptr, const char* szWord5 = nullptr); /// \brief If the string ends with one of the given words (case insensitive), it is removed and the function returns true. bool TrimWordEnd( const char* szWord1, const char* szWord2 = nullptr, const char* szWord3 = nullptr, const char* szWord4 = nullptr, const char* szWord5 = nullptr); private: /// \brief Will remove all double path separators (slashes and backslashes) in a path, except if the path starts with two (back-)slashes, /// those are kept, as they might indicate a UNC path. void RemoveDoubleSlashesInPath(); // [tested] void ChangeCharacterNonASCII(iterator& it, ezUInt32 uiCharacter); void AppendTerminator(); // needed for better copy construction template <ezUInt16 T> friend struct ezHybridStringBase; friend ezStreamReader; ezUInt32 m_uiCharacterCount; ezHybridArray<char, 128> m_Data; }; #include <Foundation/Strings/Implementation/StringBuilder_inl.h>
49.809129
150
0.734297
[ "object" ]
a9f0371333f406021cb975f129cf7a1269b36d1d
31,074
h
C
aws-cpp-sdk-ec2/include/aws/ec2/model/ImportSnapshotRequest.h
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/include/aws/ec2/model/ImportSnapshotRequest.h
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/include/aws/ec2/model/ImportSnapshotRequest.h
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2020-11-04T03:18:11.000Z
2020-11-04T03:18:11.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/ec2/EC2Request.h> #include <aws/ec2/model/ClientData.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/ec2/model/SnapshotDiskContainer.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/ec2/model/TagSpecification.h> #include <utility> namespace Aws { namespace EC2 { namespace Model { /** */ class AWS_EC2_API ImportSnapshotRequest : public EC2Request { public: ImportSnapshotRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ImportSnapshot"; } Aws::String SerializePayload() const override; protected: void DumpBodyToUrl(Aws::Http::URI& uri ) const override; public: /** * <p>The client-specific data.</p> */ inline const ClientData& GetClientData() const{ return m_clientData; } /** * <p>The client-specific data.</p> */ inline bool ClientDataHasBeenSet() const { return m_clientDataHasBeenSet; } /** * <p>The client-specific data.</p> */ inline void SetClientData(const ClientData& value) { m_clientDataHasBeenSet = true; m_clientData = value; } /** * <p>The client-specific data.</p> */ inline void SetClientData(ClientData&& value) { m_clientDataHasBeenSet = true; m_clientData = std::move(value); } /** * <p>The client-specific data.</p> */ inline ImportSnapshotRequest& WithClientData(const ClientData& value) { SetClientData(value); return *this;} /** * <p>The client-specific data.</p> */ inline ImportSnapshotRequest& WithClientData(ClientData&& value) { SetClientData(std::move(value)); return *this;} /** * <p>Token to enable idempotency for VM import requests.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>Token to enable idempotency for VM import requests.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>Token to enable idempotency for VM import requests.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>Token to enable idempotency for VM import requests.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>Token to enable idempotency for VM import requests.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>Token to enable idempotency for VM import requests.</p> */ inline ImportSnapshotRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>Token to enable idempotency for VM import requests.</p> */ inline ImportSnapshotRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>Token to enable idempotency for VM import requests.</p> */ inline ImportSnapshotRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} /** * <p>The description string for the import snapshot task.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The description string for the import snapshot task.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>The description string for the import snapshot task.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The description string for the import snapshot task.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The description string for the import snapshot task.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The description string for the import snapshot task.</p> */ inline ImportSnapshotRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The description string for the import snapshot task.</p> */ inline ImportSnapshotRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The description string for the import snapshot task.</p> */ inline ImportSnapshotRequest& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>Information about the disk container.</p> */ inline const SnapshotDiskContainer& GetDiskContainer() const{ return m_diskContainer; } /** * <p>Information about the disk container.</p> */ inline bool DiskContainerHasBeenSet() const { return m_diskContainerHasBeenSet; } /** * <p>Information about the disk container.</p> */ inline void SetDiskContainer(const SnapshotDiskContainer& value) { m_diskContainerHasBeenSet = true; m_diskContainer = value; } /** * <p>Information about the disk container.</p> */ inline void SetDiskContainer(SnapshotDiskContainer&& value) { m_diskContainerHasBeenSet = true; m_diskContainer = std::move(value); } /** * <p>Information about the disk container.</p> */ inline ImportSnapshotRequest& WithDiskContainer(const SnapshotDiskContainer& value) { SetDiskContainer(value); return *this;} /** * <p>Information about the disk container.</p> */ inline ImportSnapshotRequest& WithDiskContainer(SnapshotDiskContainer&& value) { SetDiskContainer(std::move(value)); return *this;} /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline bool GetDryRun() const{ return m_dryRun; } /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline bool DryRunHasBeenSet() const { return m_dryRunHasBeenSet; } /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; } /** * <p>Checks whether you have the required permissions for the action, without * actually making the request, and provides an error response. If you have the * required permissions, the error response is <code>DryRunOperation</code>. * Otherwise, it is <code>UnauthorizedOperation</code>.</p> */ inline ImportSnapshotRequest& WithDryRun(bool value) { SetDryRun(value); return *this;} /** * <p>Specifies whether the destination snapshot of the imported image should be * encrypted. The default CMK for EBS is used unless you specify a non-default AWS * Key Management Service (AWS KMS) CMK using <code>KmsKeyId</code>. For more * information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon * EBS Encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline bool GetEncrypted() const{ return m_encrypted; } /** * <p>Specifies whether the destination snapshot of the imported image should be * encrypted. The default CMK for EBS is used unless you specify a non-default AWS * Key Management Service (AWS KMS) CMK using <code>KmsKeyId</code>. For more * information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon * EBS Encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline bool EncryptedHasBeenSet() const { return m_encryptedHasBeenSet; } /** * <p>Specifies whether the destination snapshot of the imported image should be * encrypted. The default CMK for EBS is used unless you specify a non-default AWS * Key Management Service (AWS KMS) CMK using <code>KmsKeyId</code>. For more * information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon * EBS Encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetEncrypted(bool value) { m_encryptedHasBeenSet = true; m_encrypted = value; } /** * <p>Specifies whether the destination snapshot of the imported image should be * encrypted. The default CMK for EBS is used unless you specify a non-default AWS * Key Management Service (AWS KMS) CMK using <code>KmsKeyId</code>. For more * information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon * EBS Encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline ImportSnapshotRequest& WithEncrypted(bool value) { SetEncrypted(value); return *this;} /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; } /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline bool KmsKeyIdHasBeenSet() const { return m_kmsKeyIdHasBeenSet; } /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; } /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); } /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); } /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline ImportSnapshotRequest& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;} /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline ImportSnapshotRequest& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;} /** * <p>An identifier for the symmetric AWS Key Management Service (AWS KMS) customer * master key (CMK) to use when creating the encrypted snapshot. This parameter is * only required if you want to use a non-default CMK; if this parameter is not * specified, the default CMK for EBS is used. If a <code>KmsKeyId</code> is * specified, the <code>Encrypted</code> flag must also be set. </p> <p>The CMK * identifier may be provided in any of the following formats: </p> <ul> <li> * <p>Key ID</p> </li> <li> <p>Key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>.</p> * </li> <li> <p>ARN using key ID. The ID ARN contains the <code>arn:aws:kms</code> * namespace, followed by the Region of the CMK, the AWS account ID of the CMK * owner, the <code>key</code> namespace, and then the CMK ID. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:key/<i>abcd1234-a123-456a-a12b-a123b4cd56ef</i>.</p> * </li> <li> <p>ARN using key alias. The alias ARN contains the * <code>arn:aws:kms</code> namespace, followed by the Region of the CMK, the AWS * account ID of the CMK owner, the <code>alias</code> namespace, and then the CMK * alias. For example, * arn:aws:kms:<i>us-east-1</i>:<i>012345678910</i>:alias/<i>ExampleAlias</i>. </p> * </li> </ul> <p>AWS parses <code>KmsKeyId</code> asynchronously, meaning that the * action you call may appear to complete even though you provided an invalid * identifier. This action will eventually report failure. </p> <p>The specified * CMK must exist in the Region that the snapshot is being copied to.</p> <p>Amazon * EBS does not support asymmetric CMKs.</p> */ inline ImportSnapshotRequest& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;} /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline const Aws::String& GetRoleName() const{ return m_roleName; } /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline bool RoleNameHasBeenSet() const { return m_roleNameHasBeenSet; } /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline void SetRoleName(const Aws::String& value) { m_roleNameHasBeenSet = true; m_roleName = value; } /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline void SetRoleName(Aws::String&& value) { m_roleNameHasBeenSet = true; m_roleName = std::move(value); } /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline void SetRoleName(const char* value) { m_roleNameHasBeenSet = true; m_roleName.assign(value); } /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline ImportSnapshotRequest& WithRoleName(const Aws::String& value) { SetRoleName(value); return *this;} /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline ImportSnapshotRequest& WithRoleName(Aws::String&& value) { SetRoleName(std::move(value)); return *this;} /** * <p>The name of the role to use when not using the default role, 'vmimport'.</p> */ inline ImportSnapshotRequest& WithRoleName(const char* value) { SetRoleName(value); return *this;} /** * <p>The tags to apply to the snapshot being imported.</p> */ inline const Aws::Vector<TagSpecification>& GetTagSpecifications() const{ return m_tagSpecifications; } /** * <p>The tags to apply to the snapshot being imported.</p> */ inline bool TagSpecificationsHasBeenSet() const { return m_tagSpecificationsHasBeenSet; } /** * <p>The tags to apply to the snapshot being imported.</p> */ inline void SetTagSpecifications(const Aws::Vector<TagSpecification>& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = value; } /** * <p>The tags to apply to the snapshot being imported.</p> */ inline void SetTagSpecifications(Aws::Vector<TagSpecification>&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = std::move(value); } /** * <p>The tags to apply to the snapshot being imported.</p> */ inline ImportSnapshotRequest& WithTagSpecifications(const Aws::Vector<TagSpecification>& value) { SetTagSpecifications(value); return *this;} /** * <p>The tags to apply to the snapshot being imported.</p> */ inline ImportSnapshotRequest& WithTagSpecifications(Aws::Vector<TagSpecification>&& value) { SetTagSpecifications(std::move(value)); return *this;} /** * <p>The tags to apply to the snapshot being imported.</p> */ inline ImportSnapshotRequest& AddTagSpecifications(const TagSpecification& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(value); return *this; } /** * <p>The tags to apply to the snapshot being imported.</p> */ inline ImportSnapshotRequest& AddTagSpecifications(TagSpecification&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(std::move(value)); return *this; } private: ClientData m_clientData; bool m_clientDataHasBeenSet; Aws::String m_clientToken; bool m_clientTokenHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; SnapshotDiskContainer m_diskContainer; bool m_diskContainerHasBeenSet; bool m_dryRun; bool m_dryRunHasBeenSet; bool m_encrypted; bool m_encryptedHasBeenSet; Aws::String m_kmsKeyId; bool m_kmsKeyIdHasBeenSet; Aws::String m_roleName; bool m_roleNameHasBeenSet; Aws::Vector<TagSpecification> m_tagSpecifications; bool m_tagSpecificationsHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
51.108553
185
0.675323
[ "vector", "model" ]
a9f5f370e8dd92ce11a28d95279897e8dd04416e
3,752
h
C
src/lib/support/ObjectLifeCycle.h
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
4
2020-09-11T04:32:44.000Z
2022-03-11T09:06:07.000Z
src/lib/support/ObjectLifeCycle.h
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
8
2020-07-07T21:51:44.000Z
2021-07-26T13:43:00.000Z
src/lib/support/ObjectLifeCycle.h
mykrupp/connectedhomeip-1
c6ca8bde66f76fa95b0383e2faa6a67c74cef2c3
[ "Apache-2.0" ]
7
2021-04-26T06:22:35.000Z
2021-12-16T07:10:43.000Z
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cstdint> namespace chip { /** * Track the life cycle of an object. * * <pre> * * Construction * ↓ * Uninitialized ‹─┐ * ↓ │ * Initializing │ * ↓ │ * Initialized │ * ↓ │ * ShuttingDown │ * ↓ │ * Shutdown ───────┘ * ↓ * Destroyed * * </pre> */ class ObjectLifeCycle { public: enum class State : uint8_t { Uninitialized = 0, ///< Pre-initialized state. Initializing = 1, ///< State during intialization. Initialized = 2, ///< Initialized (active) state. ShuttingDown = 3, ///< State during shutdown. Shutdown = 4, ///< Post-shutdown state. Destroyed = 5, ///< Post-destructor state. }; ObjectLifeCycle() : mState(State::Uninitialized) {} ~ObjectLifeCycle() { mState = State::Destroyed; } /** * @returns true if and only if the object is in the Initialized state. */ bool IsInitialized() const { return mState == State::Initialized; } /* * State transitions. * * Typical use is `VerifyOrReturnError(state.SetInitializing(), CHIP_ERROR_INCORRECT_STATE)`; these functions return `bool` * rather than a `CHIP_ERROR` so that error source tracking will record the call point rather than this function itself. */ bool SetInitializing() { return Transition(State::Uninitialized, State::Initializing); } bool SetInitialized() { return Transition(State::Initializing, State::Initialized); } bool SetShuttingDown() { return Transition(State::Initialized, State::ShuttingDown); } bool SetShutdown() { return Transition(State::ShuttingDown, State::Shutdown); } bool Reset() { return Transition(State::Shutdown, State::Uninitialized); } // Skip steps when a class's shutdown code has nothing useful to do in between. bool ResetFromShuttingDown() { return Transition(State::ShuttingDown, State::Uninitialized); } bool ResetFromInitialized() { return Transition(State::Initialized, State::Uninitialized); } /** * Transition from Uninitialized or Shutdown to Destroyed. * * Typical use is `VerifyOrReturnError(state.Destroy(), CHIP_ERROR_INCORRECT_STATE)`; this function returns `bool` rather than * a `CHIP_ERROR` so that error source tracking will record the call point rather than this function itself. * * @return true if the state was Uninitialized or Shutdown and is now Destroyed. * @return false otherwise. */ bool Destroy() { if (mState == State::Uninitialized || mState == State::Shutdown) { mState = State::Destroyed; return true; } return false; } State GetState() const { return mState; } private: bool Transition(State from, State to) { if (mState == from) { mState = to; return true; } return false; } State mState; }; } // namespace chip
31.529412
130
0.61887
[ "object" ]
a9f9f920679f2af94a6842a11c054ad675b13a6c
1,888
h
C
src/Plugins/Movie1Plugin/MovieInternalObject.h
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Plugins/Movie1Plugin/MovieInternalObject.h
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Plugins/Movie1Plugin/MovieInternalObject.h
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#pragma once #include "Kernel/Node.h" #include "Kernel/BaseRender.h" #include "ResourceInternalObject.h" #include "pybind/pybind.hpp" namespace Mengine { ////////////////////////////////////////////////////////////////////////// typedef IntrusiveNodePtr<class Movie> MoviePtr; ////////////////////////////////////////////////////////////////////////// class MovieInternalObject : public Node , protected BaseRender { DECLARE_FACTORABLE( MovieInternalObject ); DECLARE_VISITABLE( Node ); DECLARE_RENDERABLE(); public: MovieInternalObject(); ~MovieInternalObject() override; public: void setMovie( Movie * _movie ); Movie * getMovie() const; void setResourceInternalObject( const ResourceInternalObjectPtr & _resource ); const ResourceInternalObjectPtr & getResourceInternalObject() const; public: const NodePtr & getInternalNode() const; protected: bool _compile() override; void _release() override; bool _activate() override; void _deactivate() override; protected: void _setPersonalColor( const Color & _color ) override; void _setPersonalAlpha( float _alpha ) override; protected: void _setLocalHide( bool _hide ) override; protected: void render( const RenderPipelineInterfacePtr & _renderPipeline, const RenderContext * _context ) const override; protected: ResourceInternalObjectPtr m_resourceInternalObject; Movie * m_movie; pybind::object m_internalObject; NodePtr m_internalNode; }; ////////////////////////////////////////////////////////////////////////// typedef IntrusiveNodePtr<MovieInternalObject> MovieInternalObjectPtr; ////////////////////////////////////////////////////////////////////////// }
29.5
121
0.567797
[ "render", "object" ]
a9fbbb0685fee61463bab758e87566b9163c9c35
739
h
C
include/mappoint.h
GentleDell/StereoSLAM
496c37b397a79e92d884f2d02620d121bd089260
[ "MIT" ]
3
2018-07-22T15:42:18.000Z
2020-04-04T20:55:21.000Z
include/mappoint.h
GentleDell/StereoSLAM
496c37b397a79e92d884f2d02620d121bd089260
[ "MIT" ]
null
null
null
include/mappoint.h
GentleDell/StereoSLAM
496c37b397a79e92d884f2d02620d121bd089260
[ "MIT" ]
1
2021-11-04T17:29:53.000Z
2021-11-04T17:29:53.000Z
#ifndef MAPPOINTS_H #define MAPPOINTS_H #include <stdio.h> #include <iostream> #include <vector> #include "opencv2/core.hpp" #include "opencv2/calib3d.hpp" using namespace std; using namespace cv; class Mappoint { public: // functions Mappoint(); Mappoint(cv::Point3f point, int queryframename, int trainframename, cv::DMatch match); public: // variances cv::Point3f position; std::vector< int > v_visibleframes_query; // vector of the name of Query frames containing this mappoint std::vector< int > v_visibleframes_train; // vector of the name of Train frames containing this mappoint std::vector< cv::DMatch > v_visiblematches; // vector of matches containing this mappoint }; #endif
21.735294
111
0.718539
[ "vector" ]
a9fcdf4b31e359316c378199aff796b3514e40d4
2,306
h
C
src/d3d11/d3d11_cuda.h
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
8,148
2017-10-29T10:51:20.000Z
2022-03-31T12:52:51.000Z
src/d3d11/d3d11_cuda.h
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
2,270
2017-12-04T12:08:13.000Z
2022-03-31T19:56:41.000Z
src/d3d11/d3d11_cuda.h
oashnic/dxvk
78ef4cfd92cb7f448292aaca83091914ab271257
[ "Zlib" ]
732
2017-11-28T13:08:15.000Z
2022-03-31T21:05:59.000Z
#pragma once #include <utility> #include <vector> #include "../dxvk/dxvk_resource.h" #include "../util/com/com_guid.h" #include "../util/com/com_object.h" #include "d3d11_buffer.h" #include "d3d11_texture.h" namespace dxvk { class CubinShaderWrapper : public ComObject<IUnknown> { public: CubinShaderWrapper(const Rc<dxvk::DxvkDevice>& dxvkDevice, VkCuModuleNVX cuModule, VkCuFunctionNVX cuFunction, VkExtent3D blockDim); ~CubinShaderWrapper(); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject); VkCuModuleNVX cuModule() const { return m_module; } VkCuFunctionNVX cuFunction() const { return m_function; } VkExtent3D blockDim() const { return m_blockDim; } private: Rc<DxvkDevice> m_dxvkDevice; VkCuModuleNVX m_module; VkCuFunctionNVX m_function; VkExtent3D m_blockDim; }; struct CubinShaderLaunchInfo { CubinShaderLaunchInfo() = default; CubinShaderLaunchInfo(CubinShaderLaunchInfo&& other) { shader = std::move(other.shader); params = std::move(other.params); paramSize = std::move(other.paramSize); nvxLaunchInfo = std::move(other.nvxLaunchInfo); cuLaunchConfig = other.cuLaunchConfig; buffers = std::move(other.buffers); images = std::move(other.images); other.cuLaunchConfig[1] = nullptr; other.cuLaunchConfig[3] = nullptr; other.nvxLaunchInfo.pExtras = nullptr; // fix-up internally-pointing pointers cuLaunchConfig[1] = params.data(); cuLaunchConfig[3] = &paramSize; nvxLaunchInfo.pExtras = cuLaunchConfig.data(); } Com<CubinShaderWrapper> shader; std::vector<uint8_t> params; size_t paramSize; VkCuLaunchInfoNVX nvxLaunchInfo = { VK_STRUCTURE_TYPE_CU_LAUNCH_INFO_NVX }; std::array<void*, 5> cuLaunchConfig; std::vector<std::pair<Rc<DxvkBuffer>, DxvkAccessFlags>> buffers; std::vector<std::pair<Rc<DxvkImage>, DxvkAccessFlags>> images; void insertResource(ID3D11Resource* pResource, DxvkAccessFlags access); template<typename T> static void insertUniqueResource(std::vector<std::pair<T, DxvkAccessFlags>>& list, const T& resource, DxvkAccessFlags access); }; }
27.452381
136
0.680833
[ "vector" ]
e70364f947f7ab360fca215db5e27964b2e1c386
5,094
h
C
Plugins/RGBZView/vtkPVRenderViewForAssembly.h
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
null
null
null
Plugins/RGBZView/vtkPVRenderViewForAssembly.h
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
null
null
null
Plugins/RGBZView/vtkPVRenderViewForAssembly.h
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Program: ParaView Module: vtkPVRenderViewWithEDL.h Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #ifndef __vtkPVRenderViewForAssembly_h #define __vtkPVRenderViewForAssembly_h #include "vtkPVRenderView.h" #include "vtkSmartPointer.h" #include <sstream> class vtkPVDataRepresentation; class vtkPVRenderViewForAssembly : public vtkPVRenderView { public: static vtkPVRenderViewForAssembly* New(); vtkTypeMacro(vtkPVRenderViewForAssembly, vtkPVRenderView); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Initialize the view with an identifier. Unless noted otherwise, this method // must be called before calling any other methods on this class. // @CallOnAllProcessess virtual void Initialize(unsigned int id); // Description: // Set the geometry bounds to use. If set to a valid value, these are the // bounds used to setup the clipping planes. void SetClippingBounds( double b1, double b2, double b3, double b4, double b5, double b6 ); void SetClippingBounds(double bds[6]) { this->ClippingBounds.SetBounds(bds); } void ResetClippingBounds(); void FreezeGeometryBounds(); // Description: // This will trigger multiple renders based on the current scene composition // and will create a single string which will encode the ordering. void ComputeZOrdering(); // Description: // Return an encoded string that represent the objects ordering for each pixel. // And NULL if no ComputeZOrdering() was done before. const char* GetZOrdering(); // Description: // Set/Get directory used when dumping the RGB buffer as image on disk vtkSetStringMacro(CompositeDirectory) vtkGetStringMacro(CompositeDirectory) // Description: // Dump RGB buffer to the disk using the CompositeDirectory (rgb.jpg) void WriteImage(); // Description: // Set image format type. Can only be 'jpg', 'png', 'tiff' where 'jpg' is // the default format. vtkGetStringMacro(ImageFormatExtension); vtkSetStringMacro(ImageFormatExtension); // Description: // Set/Get RGB image stack size vtkGetMacro(RGBStackSize,int); vtkSetMacro(RGBStackSize,int); // Description: // Reset active image stack to 0 so we can start capturing again // from the beginning the RGB buffers into our unique RGB generated image. void ResetActiveImageStack(); // Description: // Capture RGB buffer in the proper RGB stack position // and increase current active stack position. void CaptureActiveRepresentation(); // Description: // Dump composite information as JSON file into CompositeDirectory // (composite.json) void WriteComposite(); void AddRepresentationForComposite(vtkPVDataRepresentation* r); void RemoveRepresentationForComposite(vtkPVDataRepresentation* r); // Description: // Return representation encoding code inside the ZOrdering string. // Each char map a single Representation index, while 0 is reserved // for the background, hence the corresponding char is shifted by 1. const char* GetRepresentationCodes(); void SetActiveRepresentationForComposite(vtkPVDataRepresentation* r); //BTX protected: vtkPVRenderViewForAssembly(); ~vtkPVRenderViewForAssembly(); virtual void Render(bool interactive, bool skip_rendering); virtual void ResetCameraClippingRange(); private: vtkPVRenderViewForAssembly(const vtkPVRenderViewForAssembly&); // Not implemented void operator=(const vtkPVRenderViewForAssembly&); // Not implemented bool InRender; int ActiveStack; int RGBStackSize; bool InsideComputeZOrdering; bool InsideRGBDump; char* CompositeDirectory; int OrderingBufferSize; char* OrderingBuffer; int RepresentationToRender; char* ImageFormatExtension; vtkBoundingBox ClippingBounds; struct vtkInternals; vtkInternals* Internal; //ETX }; #endif
33.077922
83
0.740283
[ "geometry", "render" ]
e7057dc88b32b7d5f008da558ed3558444c8f208
26,832
c
C
libavc/encoder/ih264e_encode.c
Keneral/ae1
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
libavc/encoder/ih264e_encode.c
Keneral/ae1
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
libavc/encoder/ih264e_encode.c
Keneral/ae1
e5bbf05e3a01b449f33cca14c5ce8048df45624b
[ "Unlicense" ]
null
null
null
/****************************************************************************** * * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ /** ****************************************************************************** * @file * ih264e_encode.c * * @brief * This file contains functions for encoding the input yuv frame in synchronous * api mode * * @author * ittiam * * List of Functions * - ih264e_join_threads() * - ih264e_wait_for_thread() * - ih264e_encode() * ****************************************************************************** */ /*****************************************************************************/ /* File Includes */ /*****************************************************************************/ /* System Include files */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <limits.h> /* User Include files */ #include "ih264e_config.h" #include "ih264_typedefs.h" #include "iv2.h" #include "ive2.h" #include "ih264e.h" #include "ithread.h" #include "ih264_defs.h" #include "ih264_macros.h" #include "ih264_debug.h" #include "ih264_structs.h" #include "ih264_platform_macros.h" #include "ih264_error.h" #include "ime_distortion_metrics.h" #include "ime_defs.h" #include "ime_structs.h" #include "ih264_trans_quant_itrans_iquant.h" #include "ih264_inter_pred_filters.h" #include "ih264_mem_fns.h" #include "ih264_padding.h" #include "ih264_intra_pred_filters.h" #include "ih264_deblk_edge_filters.h" #include "ih264_cabac_tables.h" #include "ih264_list.h" #include "ih264e_error.h" #include "ih264e_defs.h" #include "ih264e_bitstream.h" #include "irc_mem_req_and_acq.h" #include "irc_cntrl_param.h" #include "irc_frame_info_collector.h" #include "ih264e_rate_control.h" #include "ih264e_time_stamp.h" #include "ih264e_cabac_structs.h" #include "ih264e_structs.h" #include "ih264e_master.h" #include "ih264e_process.h" #include "ih264_buf_mgr.h" #include "ih264_dpb_mgr.h" #include "ih264e_utils.h" #include "ih264e_fmt_conv.h" #include "ih264e_statistics.h" #include "ih264e_trace.h" #include "ih264e_debug.h" #ifdef LOGO_EN #include "ih264e_ittiam_logo.h" #endif /*****************************************************************************/ /* Function Definitions */ /*****************************************************************************/ /** ****************************************************************************** * * @brief * This function joins all the spawned threads after successful completion of * their tasks * * @par Description * * @param[in] ps_codec * pointer to codec context * * @returns none * ****************************************************************************** */ void ih264e_join_threads(codec_t *ps_codec) { /* temp var */ WORD32 i = 0; WORD32 ret = 0; /* join spawned threads */ while (i < ps_codec->i4_proc_thread_cnt) { if (ps_codec->ai4_process_thread_created[i]) { ret = ithread_join(ps_codec->apv_proc_thread_handle[i], NULL); if (ret != 0) { printf("pthread Join Failed"); assert(0); } ps_codec->ai4_process_thread_created[i] = 0; i++; } } ps_codec->i4_proc_thread_cnt = 0; } /** ****************************************************************************** * * @brief This function puts the current thread to sleep for a duration * of sleep_us * * @par Description * ithread_yield() method causes the calling thread to yield execution to another * thread that is ready to run on the current processor. The operating system * selects the thread to yield to. ithread_usleep blocks the current thread for * the specified number of milliseconds. In other words, yield just says, * end my timeslice prematurely, look around for other threads to run. If there * is nothing better than me, continue. Sleep says I don't want to run for x * milliseconds. Even if no other thread wants to run, don't make me run. * * @param[in] sleep_us * thread sleep duration * * @returns error_status * ****************************************************************************** */ IH264E_ERROR_T ih264e_wait_for_thread(UWORD32 sleep_us) { /* yield thread */ ithread_yield(); /* put thread to sleep */ ithread_usleep(sleep_us); return IH264E_SUCCESS; } /** ****************************************************************************** * * @brief * Encodes in synchronous api mode * * @par Description * This routine processes input yuv, encodes it and outputs bitstream and recon * * @param[in] ps_codec_obj * Pointer to codec object at API level * * @param[in] pv_api_ip * Pointer to input argument structure * * @param[out] pv_api_op * Pointer to output argument structure * * @returns Status * ****************************************************************************** */ WORD32 ih264e_encode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { /* error status */ IH264E_ERROR_T error_status = IH264E_SUCCESS; /* codec ctxt */ codec_t *ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; /* input frame to encode */ ih264e_video_encode_ip_t *ps_video_encode_ip = pv_api_ip; /* output buffer to write stream */ ih264e_video_encode_op_t *ps_video_encode_op = pv_api_op; /* i/o structures */ inp_buf_t s_inp_buf; out_buf_t s_out_buf; /* temp var */ WORD32 ctxt_sel = 0, i, i4_rc_pre_enc_skip; /********************************************************************/ /* BEGIN INIT */ /********************************************************************/ /* reset output structure */ ps_video_encode_op->s_ive_op.u4_error_code = IV_SUCCESS; ps_video_encode_op->s_ive_op.output_present = 0; ps_video_encode_op->s_ive_op.dump_recon = 0; ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_NA_FRAME; /* Check for output memory allocation size */ if (ps_video_encode_ip->s_ive_ip.s_out_buf.u4_bufsize < MIN_STREAM_SIZE) { error_status |= IH264E_INSUFFICIENT_OUTPUT_BUFFER; SET_ERROR_ON_RETURN(error_status, IVE_UNSUPPORTEDPARAM, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); } /* copy output info. to internal structure */ s_out_buf.s_bits_buf = ps_video_encode_ip->s_ive_ip.s_out_buf; s_out_buf.u4_is_last = 0; s_out_buf.u4_timestamp_low = ps_video_encode_ip->s_ive_ip.u4_timestamp_low; s_out_buf.u4_timestamp_high = ps_video_encode_ip->s_ive_ip.u4_timestamp_high; /* api call cnt */ ps_codec->i4_encode_api_call_cnt += 1; /* codec context selector */ ctxt_sel = ps_codec->i4_encode_api_call_cnt % MAX_CTXT_SETS; /* reset status flags */ ps_codec->ai4_pic_cnt[ctxt_sel] = -1; ps_codec->s_rate_control.post_encode_skip[ctxt_sel] = 0; ps_codec->s_rate_control.pre_encode_skip[ctxt_sel] = 0; /* pass output buffer to codec */ ps_codec->as_out_buf[ctxt_sel] = s_out_buf; /* initialize codec ctxt with default params for the first encode api call */ if (ps_codec->i4_encode_api_call_cnt == 0) { ih264e_codec_init(ps_codec); } /* parse configuration params */ for (i = 0; i < MAX_ACTIVE_CONFIG_PARAMS; i++) { cfg_params_t *ps_cfg = &ps_codec->as_cfg[i]; if (1 == ps_cfg->u4_is_valid) { if ( ((ps_cfg->u4_timestamp_high == ps_video_encode_ip->s_ive_ip.u4_timestamp_high) && (ps_cfg->u4_timestamp_low == ps_video_encode_ip->s_ive_ip.u4_timestamp_low)) || ((WORD32)ps_cfg->u4_timestamp_high == -1) || ((WORD32)ps_cfg->u4_timestamp_low == -1) ) { error_status |= ih264e_codec_update_config(ps_codec, ps_cfg); SET_ERROR_ON_RETURN(error_status, IVE_UNSUPPORTEDPARAM, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); ps_cfg->u4_is_valid = 0; } } } /****************************************************************** * INSERT LOGO *****************************************************************/ #ifdef LOGO_EN if (s_inp_buf.s_raw_buf.apv_bufs[0] != NULL && ps_codec->i4_header_mode != 1) { ih264e_insert_logo(s_inp_buf.s_raw_buf.apv_bufs[0], s_inp_buf.s_raw_buf.apv_bufs[1], s_inp_buf.s_raw_buf.apv_bufs[2], s_inp_buf.s_raw_buf.au4_strd[0], 0, 0, ps_codec->s_cfg.e_inp_color_fmt, ps_codec->s_cfg.u4_disp_wd, ps_codec->s_cfg.u4_disp_ht); } #endif /*LOGO_EN*/ /* In case of alt ref and B pics we will have non reference frame in stream */ if (ps_codec->s_cfg.u4_enable_alt_ref || ps_codec->s_cfg.u4_num_bframes) { ps_codec->i4_non_ref_frames_in_stream = 1; } if (ps_codec->i4_encode_api_call_cnt == 0) { /********************************************************************/ /* number of mv/ref bank buffers used by the codec, */ /* 1 to handle curr frame */ /* 1 to store information of ref frame */ /* 1 more additional because of the codec employs 2 ctxt sets */ /* to assist asynchronous API */ /********************************************************************/ /* initialize mv bank buffer manager */ error_status |= ih264e_mv_buf_mgr_add_bufs(ps_codec); SET_ERROR_ON_RETURN(error_status, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); /* initialize ref bank buffer manager */ error_status |= ih264e_pic_buf_mgr_add_bufs(ps_codec); SET_ERROR_ON_RETURN(error_status, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); /* for the first frame, generate header when not requested explicitly */ if (ps_codec->i4_header_mode == 0 && ps_codec->u4_header_generated == 0) { ps_codec->i4_gen_header = 1; } } /* generate header and return when encoder is operated in header mode */ if (ps_codec->i4_header_mode == 1) { /* whenever the header is generated, this implies a start of sequence * and a sequence needs to be started with IDR */ ps_codec->force_curr_frame_type = IV_IDR_FRAME; /* generate header */ error_status |= ih264e_generate_sps_pps(ps_codec); /* api call cnt */ ps_codec->i4_encode_api_call_cnt --; /* header mode tag is not sticky */ ps_codec->i4_header_mode = 0; ps_codec->i4_gen_header = 0; /* send the input to app */ ps_video_encode_op->s_ive_op.s_inp_buf = ps_video_encode_ip->s_ive_ip.s_inp_buf; ps_video_encode_op->s_ive_op.u4_timestamp_low = ps_video_encode_ip->s_ive_ip.u4_timestamp_low; ps_video_encode_op->s_ive_op.u4_timestamp_high = ps_video_encode_ip->s_ive_ip.u4_timestamp_high; ps_video_encode_op->s_ive_op.u4_is_last = ps_video_encode_ip->s_ive_ip.u4_is_last; /* send the output to app */ ps_video_encode_op->s_ive_op.output_present = 1; ps_video_encode_op->s_ive_op.dump_recon = 0; ps_video_encode_op->s_ive_op.s_out_buf = ps_codec->as_out_buf[ctxt_sel].s_bits_buf; /* error status */ SET_ERROR_ON_RETURN(error_status, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); /* indicates that header has been generated previously */ ps_codec->u4_header_generated = 1; return IV_SUCCESS; } /* curr pic cnt */ ps_codec->i4_pic_cnt += 1; i4_rc_pre_enc_skip = 0; i4_rc_pre_enc_skip = ih264e_input_queue_update( ps_codec, &ps_video_encode_ip->s_ive_ip, &s_inp_buf); s_out_buf.u4_is_last = s_inp_buf.u4_is_last; ps_video_encode_op->s_ive_op.u4_is_last = s_inp_buf.u4_is_last; /* Only encode if the current frame is not pre-encode skip */ if (!i4_rc_pre_enc_skip && s_inp_buf.s_raw_buf.apv_bufs[0]) { /* proc ctxt base idx */ WORD32 proc_ctxt_select = ctxt_sel * MAX_PROCESS_THREADS; /* proc ctxt */ process_ctxt_t *ps_proc = &ps_codec->as_process[proc_ctxt_select]; WORD32 ret = 0; /* number of addl. threads to be created */ WORD32 num_thread_cnt = ps_codec->s_cfg.u4_num_cores - 1; /* array giving pic cnt that is being processed in curr context set */ ps_codec->ai4_pic_cnt[ctxt_sel] = ps_codec->i4_pic_cnt; /* initialize all relevant process ctxts */ error_status |= ih264e_pic_init(ps_codec, &s_inp_buf); SET_ERROR_ON_RETURN(error_status, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); for (i = 0; i < num_thread_cnt; i++) { ret = ithread_create(ps_codec->apv_proc_thread_handle[i], NULL, (void *)ih264e_process_thread, &ps_codec->as_process[i + 1]); if (ret != 0) { printf("pthread Create Failed"); assert(0); } ps_codec->ai4_process_thread_created[i] = 1; ps_codec->i4_proc_thread_cnt++; } /* launch job */ ih264e_process_thread(ps_proc); /* Join threads at the end of encoding a frame */ ih264e_join_threads(ps_codec); ih264_list_reset(ps_codec->pv_proc_jobq); ih264_list_reset(ps_codec->pv_entropy_jobq); } /**************************************************************************** * RECON * Since we have forward dependent frames, we cannot return recon in encoding * order. It must be in poc order, or input pic order. To achieve this we * introduce a delay of 1 to the recon wrt encode. Now since we have that * delay, at any point minimum of pic_cnt in our ref buffer will be the * correct frame. For ex let our GOP be IBBP [1 2 3 4] . The encode order * will be [1 4 2 3] .Now since we have a delay of 1, when we are done with * encoding 4, the min in the list will be 1. After encoding 2, it will be * 2, 3 after 3 and 4 after 4. Hence we can return in sequence. Note * that the 1 delay is critical. Hence if we have post enc skip, we must * skip here too. Note that since post enc skip already frees the recon * buffer we need not do any thing here * * We need to return a recon when ever we consume an input buffer. This * comsumption include a pre or post enc skip. Thus dump recon is set for * all cases except when * 1) We are waiting -> ps_codec->i4_frame_num > 1 * 2) When the input buffer is null [ ie we are not consuming any inp] * An exception need to be made for the case when we have the last buffer * since we need to flush out the on remainig recon. ****************************************************************************/ ps_video_encode_op->s_ive_op.dump_recon = 0; if (ps_codec->s_cfg.u4_enable_recon && (ps_codec->i4_frame_num > 1 || s_inp_buf.u4_is_last) && (s_inp_buf.s_raw_buf.apv_bufs[0] || s_inp_buf.u4_is_last)) { /* error status */ IH264_ERROR_T ret = IH264_SUCCESS; pic_buf_t *ps_pic_buf = NULL; WORD32 i4_buf_status, i4_curr_poc = 32768; /* In case of skips we return recon, but indicate that buffer is zero size */ if (ps_codec->s_rate_control.post_encode_skip[ctxt_sel] || i4_rc_pre_enc_skip) { ps_video_encode_op->s_ive_op.dump_recon = 1; ps_video_encode_op->s_ive_op.s_recon_buf.au4_wd[0] = 0; ps_video_encode_op->s_ive_op.s_recon_buf.au4_wd[1] = 0; } else { for (i = 0; i < ps_codec->i4_ref_buf_cnt; i++) { if (ps_codec->as_ref_set[i].i4_pic_cnt == -1) continue; i4_buf_status = ih264_buf_mgr_get_status( ps_codec->pv_ref_buf_mgr, ps_codec->as_ref_set[i].ps_pic_buf->i4_buf_id); if ((i4_buf_status & BUF_MGR_IO) && (ps_codec->as_ref_set[i].i4_poc < i4_curr_poc)) { ps_pic_buf = ps_codec->as_ref_set[i].ps_pic_buf; i4_curr_poc = ps_codec->as_ref_set[i].i4_poc; } } ps_video_encode_op->s_ive_op.s_recon_buf = ps_video_encode_ip->s_ive_ip.s_recon_buf; /* * If we get a valid buffer. output and free recon. * * we may get an invalid buffer if num_b_frames is 0. This is because * We assume that there will be a ref frame in ref list after encoding * the last frame. With B frames this is correct since its forward ref * pic will be in the ref list. But if num_b_frames is 0, we will not * have a forward ref pic */ if (ps_pic_buf) { /* copy/convert the recon buffer and return */ ih264e_fmt_conv(ps_codec, ps_pic_buf, ps_video_encode_ip->s_ive_ip.s_recon_buf.apv_bufs[0], ps_video_encode_ip->s_ive_ip.s_recon_buf.apv_bufs[1], ps_video_encode_ip->s_ive_ip.s_recon_buf.apv_bufs[2], ps_video_encode_ip->s_ive_ip.s_recon_buf.au4_wd[0], ps_video_encode_ip->s_ive_ip.s_recon_buf.au4_wd[1], 0, ps_codec->s_cfg.u4_disp_ht); ps_video_encode_op->s_ive_op.dump_recon = 1; ret = ih264_buf_mgr_release(ps_codec->pv_ref_buf_mgr, ps_pic_buf->i4_buf_id, BUF_MGR_IO); if (IH264_SUCCESS != ret) { SET_ERROR_ON_RETURN( (IH264E_ERROR_T)ret, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); } } } } /*************************************************************************** * Free reference buffers: * In case of a post enc skip, we have to ensure that those pics will not * be used as reference anymore. In all other cases we will not even mark * the ref buffers ***************************************************************************/ if (ps_codec->s_rate_control.post_encode_skip[ctxt_sel]) { /* pic info */ pic_buf_t *ps_cur_pic; /* mv info */ mv_buf_t *ps_cur_mv_buf; /* error status */ IH264_ERROR_T ret = IH264_SUCCESS; /* Decrement coded pic count */ ps_codec->i4_poc--; /* loop through to get the min pic cnt among the list of pics stored in ref list */ /* since the skipped frame may not be on reference list, we may not have an MV bank * hence free only if we have allocated */ for (i = 0; i < ps_codec->i4_ref_buf_cnt; i++) { if (ps_codec->i4_pic_cnt == ps_codec->as_ref_set[i].i4_pic_cnt) { ps_cur_pic = ps_codec->as_ref_set[i].ps_pic_buf; ps_cur_mv_buf = ps_codec->as_ref_set[i].ps_mv_buf; /* release this frame from reference list and recon list */ ret = ih264_buf_mgr_release(ps_codec->pv_mv_buf_mgr, ps_cur_mv_buf->i4_buf_id , BUF_MGR_REF); ret |= ih264_buf_mgr_release(ps_codec->pv_mv_buf_mgr, ps_cur_mv_buf->i4_buf_id , BUF_MGR_IO); SET_ERROR_ON_RETURN((IH264E_ERROR_T)ret, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); ret = ih264_buf_mgr_release(ps_codec->pv_ref_buf_mgr, ps_cur_pic->i4_buf_id , BUF_MGR_REF); ret |= ih264_buf_mgr_release(ps_codec->pv_ref_buf_mgr, ps_cur_pic->i4_buf_id , BUF_MGR_IO); SET_ERROR_ON_RETURN((IH264E_ERROR_T)ret, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); break; } } } /* * Since recon is not in sync with output, ie there can be frame to be * given back as recon even after last output. Hence we need to mark that * the output is not the last. * Hence search through reflist and mark appropriately */ if (ps_codec->s_cfg.u4_enable_recon) { WORD32 i4_buf_status = 0; for (i = 0; i < ps_codec->i4_ref_buf_cnt; i++) { if (ps_codec->as_ref_set[i].i4_pic_cnt == -1) continue; i4_buf_status |= ih264_buf_mgr_get_status( ps_codec->pv_ref_buf_mgr, ps_codec->as_ref_set[i].ps_pic_buf->i4_buf_id); } if (i4_buf_status & BUF_MGR_IO) { s_out_buf.u4_is_last = 0; ps_video_encode_op->s_ive_op.u4_is_last = 0; } } /************************************************************************** * Signaling to APP * 1) If we valid a valid output mark it so * 2) Set the codec output ps_video_encode_op * 3) Set the error status * 4) Set the return Pic type * Note that we already has marked recon properly * 5)Send the consumed input back to app so that it can free it if possible * * We will have to return the output and input buffers unconditionally * so that app can release them **************************************************************************/ if (!i4_rc_pre_enc_skip && !ps_codec->s_rate_control.post_encode_skip[ctxt_sel] && s_inp_buf.s_raw_buf.apv_bufs[0]) { /* receive output back from codec */ s_out_buf = ps_codec->as_out_buf[ctxt_sel]; /* send the output to app */ ps_video_encode_op->s_ive_op.output_present = 1; ps_video_encode_op->s_ive_op.u4_error_code = IV_SUCCESS; /* Set the time stamps of the encodec input */ ps_video_encode_op->s_ive_op.u4_timestamp_low = s_inp_buf.u4_timestamp_low; ps_video_encode_op->s_ive_op.u4_timestamp_high = s_inp_buf.u4_timestamp_high; switch (ps_codec->pic_type) { case PIC_IDR: ps_video_encode_op->s_ive_op.u4_encoded_frame_type =IV_IDR_FRAME; break; case PIC_I: ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_I_FRAME; break; case PIC_P: ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_P_FRAME; break; case PIC_B: ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_B_FRAME; break; default: ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_NA_FRAME; break; } for (i = 0; i < (WORD32)ps_codec->s_cfg.u4_num_cores; i++) { error_status |= ps_codec->as_process[ctxt_sel + i].i4_error_code; } SET_ERROR_ON_RETURN(error_status, IVE_FATALERROR, ps_video_encode_op->s_ive_op.u4_error_code, IV_FAIL); } else { /* proc ctxt base idx */ WORD32 proc_ctxt_select = ctxt_sel * MAX_PROCESS_THREADS; /* proc ctxt */ process_ctxt_t *ps_proc = &ps_codec->as_process[proc_ctxt_select]; /* receive output back from codec */ s_out_buf = ps_codec->as_out_buf[ctxt_sel]; ps_video_encode_op->s_ive_op.output_present = 0; ps_video_encode_op->s_ive_op.u4_error_code = IV_SUCCESS; /* Set the time stamps of the encodec input */ ps_video_encode_op->s_ive_op.u4_timestamp_low = 0; ps_video_encode_op->s_ive_op.u4_timestamp_high = 0; /* receive input back from codec and send it to app */ s_inp_buf = ps_proc->s_inp_buf; ps_video_encode_op->s_ive_op.s_inp_buf = s_inp_buf.s_raw_buf; ps_video_encode_op->s_ive_op.u4_encoded_frame_type = IV_NA_FRAME; } /* Send the input to encoder so that it can free it if possible */ ps_video_encode_op->s_ive_op.s_out_buf = s_out_buf.s_bits_buf; ps_video_encode_op->s_ive_op.s_inp_buf = s_inp_buf.s_raw_buf; if (1 == s_inp_buf.u4_is_last) { ps_video_encode_op->s_ive_op.output_present = 0; ps_video_encode_op->s_ive_op.dump_recon = 0; } return IV_SUCCESS; }
36.555858
109
0.556686
[ "object" ]
e705b66cad5c5f4b264ea0f167a41d57fd38b681
819
h
C
structural/src/bridge/window.h
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
9
2016-08-03T16:15:57.000Z
2021-11-08T13:15:46.000Z
structural/src/bridge/window.h
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
null
null
null
structural/src/bridge/window.h
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
4
2016-08-03T16:16:01.000Z
2017-12-27T05:14:55.000Z
// Based on "Design Patterns: Elements of Reusable Object-Oriented Software" // book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm // // Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. #ifndef STRUCTURAL_BRIDGE_WINDOW_H_ #define STRUCTURAL_BRIDGE_WINDOW_H_ #include "window_interface.h" #include "window_imp.h" namespace structural { namespace bridge { class Window :public WindowInterface { public: explicit Window(WindowImp* imp); ~Window() override; virtual void DrawRect(const commons::Point<float>& p1, const commons::Point<float>& p2) override; virtual void DrawText(const std::string& text, const commons::Point<float>&) override = 0; protected: WindowImp *GetWindowImp() const; private: WindowImp* imp_; }; } } #endif
22.75
107
0.765568
[ "object" ]
e710ad1bed440fd555caaa841d006fedf29eb64c
1,426
h
C
3D Graphics - Final/3D Graphics - Final/VertexBufferLayout.h
ferp132/OpenGL
2d5387915f3bf80b44b7c078dd9d6bdbb1c69f6f
[ "MIT" ]
null
null
null
3D Graphics - Final/3D Graphics - Final/VertexBufferLayout.h
ferp132/OpenGL
2d5387915f3bf80b44b7c078dd9d6bdbb1c69f6f
[ "MIT" ]
null
null
null
3D Graphics - Final/3D Graphics - Final/VertexBufferLayout.h
ferp132/OpenGL
2d5387915f3bf80b44b7c078dd9d6bdbb1c69f6f
[ "MIT" ]
null
null
null
#pragma once #ifndef __VERTEXBUFFERLAYOUT_H__ #define __VERTEXBUFFERLAYOUT_H__ #include "Dependencies\glew\glew.h" #include "Renderer.h" #include <vector> struct VertexBufferElement { GLuint type; GLuint count; unsigned char normalised; static unsigned int GetSizeOfType(unsigned int type) { switch (type) { case GL_FLOAT: return 4; case GL_UNSIGNED_INT: return 4; case GL_UNSIGNED_BYTE: return 1; } ASSERT(false); return 0; } }; class VertexBufferLayout { private: std::vector<VertexBufferElement> Elements; unsigned int Stride; public: VertexBufferLayout() : Stride(0) {} template<typename T> void Push(unsigned int count) { static_assert(false); } template<> void Push<float>(unsigned int count) { Elements.push_back({ GL_FLOAT, count, GL_FALSE }); Stride += count * VertexBufferElement::GetSizeOfType(GL_FLOAT); } template<> void Push<unsigned int>(unsigned int count) { Elements.push_back({ GL_UNSIGNED_INT, count, GL_FALSE }); Stride += count * VertexBufferElement::GetSizeOfType(GL_UNSIGNED_INT); } template<> void Push<unsigned char>(unsigned int count) { Elements.push_back({ GL_UNSIGNED_BYTE, count, GL_TRUE }); Stride += count * VertexBufferElement::GetSizeOfType(GL_UNSIGNED_BYTE); } inline const std::vector<VertexBufferElement> GetElements() const& { return Elements; } inline unsigned int GetStride() const { return Stride; } }; #endif
21.283582
88
0.736325
[ "vector" ]
e711a5977c2276242cc673140ab9c832cb3255bc
8,514
h
C
src/TAO/Ledger/include/stake.h
barrystyle/LLL-TAO
d9e5b4e4db4cea3976797d8526aedb4bd94256af
[ "MIT" ]
60
2018-04-14T22:17:47.000Z
2022-03-22T14:24:46.000Z
src/TAO/Ledger/include/stake.h
barrystyle/LLL-TAO
d9e5b4e4db4cea3976797d8526aedb4bd94256af
[ "MIT" ]
60
2019-07-12T14:18:44.000Z
2022-03-30T08:03:19.000Z
src/TAO/Ledger/include/stake.h
barrystyle/LLL-TAO
d9e5b4e4db4cea3976797d8526aedb4bd94256af
[ "MIT" ]
33
2018-04-16T08:55:36.000Z
2022-03-13T10:17:06.000Z
/*__________________________________________________________________________________________ (c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ (c) Copyright The Nexus Developers 2014 - 2021 Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. "ad vocem populi" - To the Voice of the People ____________________________________________________________________________________________*/ #pragma once #ifndef NEXUS_TAO_LEDGER_INCLUDE_STAKE_H #define NEXUS_TAO_LEDGER_INCLUDE_STAKE_H #include <LLC/types/uint1024.h> #include <TAO/Ledger/types/block.h> #include <TAO/Ledger/types/genesis.h> #include <TAO/Ledger/types/transaction.h> #include <TAO/Ledger/types/tritium.h> #include <TAO/Register/types/object.h> #include <Util/include/softfloat.h> /** * The functions defined here provide a single source for settings and calculations related to Nexus Proof of Stake. * * Settings-related functions replace direct references to defined constants in the code, allowing for * activation-triggered changes to be coded in one place rather than in multiple places throughout the code. * Any other changes, such as alternative forms of definition, would also be encapsulated within * these functions and not require any change elsewhere in the code. * * Similarly, functions that perform calculations isolate the definition of these calculations into a * single location, supporting use in multiple places while only having the calculation itself * coded once. * **/ /* Global TAO namespace. */ namespace TAO { /* Ledger Layer namespace. */ namespace Ledger { /** MaxBlockAge * * Retrieve the setting for maximum block age (time since last stake block mined) * before trust decay begins. * * @return the current system setting for maximum block age * **/ uint64_t MaxBlockAge(); /** MinCoinAge * * Retrieve the setting for minimum coin age required to begin staking Genesis. * * @return the current system setting for minimum coin age * **/ uint64_t MinCoinAge(); /** MinStakeInterval * * Retrieve the minimum number of blocks required between an account's stake transactions. * * @param[in] block - Proof of Stake block to which this interval will apply * * @return the current system setting for minimum stake interval * **/ uint32_t MinStakeInterval(const Block& block); /** TrustWeightBase * * Retrieve the base time value for calculating trust weight. * * @return the current system setting for trust weight base * **/ uint64_t TrustWeightBase(); /** GetTrustScore * * Calculate new trust score from parameters. * * @param[in] nScorePrev - previous trust score of trust account * @param[in] nBlockAge - current block age (time since last stake block for trust account) * @param[in] nStake - current stake amount * @param[in] nStakeChange - amount added to or removed from stake, unstake penalty applied if this is a negative amount * @param[in] nVersion The version for checking trust score by. * * @return new value for trust score * **/ uint64_t GetTrustScore(const uint64_t nScorePrev, const uint64_t nBlockAge, const uint64_t nStake, const int64_t nStakeChange, const uint32_t nVersion); /** BlockWeight * * Calculate the proof of stake block weight for a given block age. * * @param[in] nBlockAge * * @return value for block weight * **/ cv::softdouble BlockWeight(const uint64_t nBlockAge); /** GenesisWeight * * Calculate the equivalent proof of stake trust weight for staking Genesis with a given coin age. * * @param[in] nCoinAge * * @return value for trust weight * **/ cv::softdouble GenesisWeight(const uint64_t nCoinAge); /** TrustWeight * * Calculate the proof of stake trust weight for a given trust score. * * @param[in] nTrust - Trust score * * @return value for trust weight * **/ cv::softdouble TrustWeight(const uint64_t nTrust); /** GetCurrentThreshold * * Calculate the current threshold value for Proof of Stake. * This value must exceed required threshold for staking to proceed. * * @param[in] nBlockTime - Amount of time since last block generated on the network * @param[in] nNonce - Nonce value for stake iteration * * @return value for current threshold * **/ cv::softdouble GetCurrentThreshold(const uint64_t nBlockTime, const uint64_t nNonce); /** GetRequiredThreshold * * Calculate the minimum Required Energy Efficiency Threshold. * Can only mine Proof of Stake when current threshold exceeds this value. * * @param[in] nTrustWeight - Current trust weight * @param[in] nBlockWeight - Current block weight * @param[in] nStake - Current stake balance * * @return value for minimum required threshold * **/ cv::softdouble GetRequiredThreshold(const cv::softdouble nTrustWeight, const cv::softdouble nBlockWeight, const uint64_t nStake); /** StakeRate * * Calculate the stake rate corresponding to a given trust score. * * Returned value is absolute rate. To display a percent, multiply by 100. * * @param[in] nTrust - Current trust score (ignored when fGenesis = true) * @param[in] fGenesis - Set true if staking for Genesis transaction * * @return value for stake rate * **/ cv::softdouble StakeRate(const uint64_t nTrust, const bool fGenesis = false); /** GetCoinstakeReward * * Calculate the coinstake reward for a given stake. * * @param[in] nStake - Stake balance on which reward is to be paid * @param[in] nStakeTime - Amount of time reward is for * @param[in] nTrust - Current trust score (ignored when fGenesis = true) * @param[in] fGenesis - Set true if staking for Genesis transaction * * @return amount of coinstake reward * **/ uint64_t GetCoinstakeReward(const uint64_t nStake, const uint64_t nStakeTime, const uint64_t nTrust, const bool fGenesis = false); /** CheckConsistency * * Checks a sigchain's trust for inconsistencies. * * @param[in] hashLastTrust The last trust block to search by. * @param[in] nTrustRet The trust score returned by reference. * * @return True if the consistency checks passed. * **/ bool CheckConsistency(const uint512_t& hashLastTrust, uint64_t& nTrustRet); /** FindTrustAccount * * Gets the trust account for a signature chain. * * @param[in] hashGenesis - genesis of user account signature chain that is staking * @param[out] account - trust account belonging to hashGenesis sig chain * @param[out] fIndexed - true if trust account has previously staked genesis * * @return true if the trust account was successfully retrieved * **/ bool FindTrustAccount(const uint256_t& hashGenesis, TAO::Register::Object &account, bool &fIndexed); /** FindLastStake * * Find the last stake transaction for a user signature chain. * * @param[in] hashGenesis - User genesis of signature chain to search * @param[out] tx - Last stake transaction for user * * @return True if last stake found, false otherwise * **/ bool FindLastStake(const uint256_t& hashGenesis, Transaction &tx); } } #endif
34.056
137
0.618276
[ "object" ]
e71dc0cd0e5840bd6bc65c5515757097e6e3777a
26,638
h
C
hi_sampler/sampler/ModulatorSamplerSound.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_sampler/sampler/ModulatorSamplerSound.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_sampler/sampler/ModulatorSamplerSound.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE 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. * * HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ #pragma once namespace hise { using namespace juce; struct CascadedEnvelopeLowPass { static constexpr int NumMaxOrders = 5; CascadedEnvelopeLowPass(bool isPoly); using FilterType = scriptnode::filters::one_pole<NUM_POLYPHONIC_VOICES>; FilterType** begin() { return filters.begin(); } FilterType** end() { return begin() + order; } void process(float frequency, AudioSampleBuffer& b, int startSampleInBuffer=0, int maxNumSamples=0); void setOrder(int newOrder) { order = jlimit(1, filters.size(), order); } void prepare(PrepareSpecs ps) { if (polyManager.isEnabled()) ps.voiceIndex = &polyManager; for (auto f : filters) f->prepare(ps); reset(); } void reset() { for (auto f : filters) f->reset(); } snex::PolyHandler polyManager; private: int order = 1; OwnedArray<scriptnode::filters::one_pole<NUM_POLYPHONIC_VOICES>> filters; }; typedef ReferenceCountedArray<StreamingSamplerSound> StreamingSamplerSoundArray; typedef Array<WeakReference<StreamingSamplerSound>> WeakStreamingSamplerSoundArray; #define FOR_EVERY_SOUND(x) {for (int i = 0; i < soundArray.size(); i++) if(soundArray[i].get() != nullptr) soundArray[i]->x;} // ==================================================================================================================== /** A simple POD structure for basic mapping data. This is used to convert between multimic / single samples. */ struct MappingData { MappingData(int r, int lk, int hk, int lv, int hv, int rr);; MappingData() {}; ValueTree data; /** This fills the information from the given sound. * * If the property is non-null, it will be used, so you can use sets with only one loop point * per mic position. */ void fillOtherProperties(ModulatorSamplerSound* sound); }; // ==================================================================================================================== #define DECLARE_ID(x) const juce::Identifier x(#x); namespace SampleIds { DECLARE_ID(Unused); DECLARE_ID(ID); DECLARE_ID(FileName); DECLARE_ID(Root); DECLARE_ID(HiKey); DECLARE_ID(LoKey); DECLARE_ID(LoVel); DECLARE_ID(HiVel); DECLARE_ID(RRGroup); DECLARE_ID(Volume); DECLARE_ID(Pan); DECLARE_ID(Normalized); DECLARE_ID(NormalizedPeak); DECLARE_ID(Pitch); DECLARE_ID(SampleStart); DECLARE_ID(SampleEnd); DECLARE_ID(SampleStartMod); DECLARE_ID(LoopStart); DECLARE_ID(LoopEnd); DECLARE_ID(LoopXFade); DECLARE_ID(LoopEnabled); DECLARE_ID(LowerVelocityXFade); DECLARE_ID(UpperVelocityXFade); DECLARE_ID(SampleState); DECLARE_ID(Reversed); DECLARE_ID(GainTable); DECLARE_ID(PitchTable); DECLARE_ID(LowPassTable); #undef DECLARE_ID struct Helpers { static Identifier getEnvelopeId(Modulation::Mode m) { switch (m) { case Modulation::Mode::GainMode: return SampleIds::GainTable; case Modulation::Mode::PitchMode: return SampleIds::PitchTable; case Modulation::Mode::PanMode: return SampleIds::LowPassTable; default: return {}; } return {}; } static Modulation::Mode getEnvelopeType(const Identifier& id) { if (id == GainTable) return Modulation::Mode::GainMode; if (id == PitchTable) return Modulation::Mode::PitchMode; if (id == LowPassTable) return Modulation::Mode::PanMode; return Modulation::Mode::numModes; } static const Array<Identifier>& getMapIds() { static const Array<Identifier> ids = { Root , HiKey, LoKey, HiVel, LoVel, RRGroup, LowerVelocityXFade, UpperVelocityXFade }; return ids; } static const Array<Identifier>& getAudioIds() { static const Array<Identifier> ids = { SampleStart, SampleEnd, SampleStartMod, LoopEnabled, LoopStart, LoopEnd, LoopXFade }; return ids; } static bool isMapProperty(const Identifier& id) { return id == Root || id == HiKey || id == LoKey || id == HiVel || id == LoVel || id == RRGroup || id == LowerVelocityXFade || id == UpperVelocityXFade; } static bool isAudioProperty(const Identifier& id) { return id == SampleStart || id == SampleEnd || id == SampleStartMod || id == LoopEnabled || id == LoopStart || id == LoopEnd || id == LoopXFade; } }; const int numProperties = 26; } #undef DECLARE_ID /** A ModulatorSamplerSound is a wrapper around a StreamingSamplerSound that allows modulation of parameters. * @ingroup sampler * * It also contains methods that extend the properties of a StreamingSamplerSound. */ class ModulatorSamplerSound : public ModulatorSynthSound, public ControlledObject { public: using Ptr = ReferenceCountedObjectPtr<ModulatorSamplerSound>; // ==================================================================================================================== /** The extended properties of the ModulatorSamplerSound */ enum Property { ID = 1, ///< a unique ID which corresponds to the number in the sound array FileName, ///< the complete filename of the audio file RootNote, ///< the root note HiKey, ///< the highest mapped key LoKey, ///< the lowest mapped key LoVel, ///< the lowest mapped velocity HiVel, ///< the highest mapped velocity RRGroup, ///< the group index for round robin / random group start behaviour Volume, ///< the gain in decibels. It is converted to a gain value internally Pan, Normalized, ///< enables normalization of the sample data Pitch, ///< the pitch factor in cents (+- 100). This is for fine tuning, for anything else, use RootNote. SampleStart, ///< the start sample SampleEnd, ///< the end sample, SampleStartMod, ///< the amount of samples that the sample start can be modulated. LoopStart, ///< the loop start in samples. This is independent from the sample start / end, but it checks the bounds. LoopEnd, ///< the loop end in samples. This is independent from the sample start / end, but it checks the bounds. LoopXFade, ///< the loop crossfade at the end of the loop (using a precalculated buffer) LoopEnabled, ///< true if the sample should be looped LowerVelocityXFade, ///< the length of the velocity crossfade (0 if there is no crossfade). If the crossfade starts at the bottom, it will have negative values. UpperVelocityXFade, ///< the length of the velocity crossfade (0 if there is no crossfade). If the crossfade starts at the bottom, it will have negative values. SampleState, ///< this property allows to set the state of samples between 'Normal', 'Disabled' and 'Purged' Reversed, GainTable, PitchTable, numProperties }; // ==================================================================================================================== ModulatorSamplerSound(SampleMap* parent, const ValueTree& d, HlacMonolithInfo* monolithData=nullptr); ~ModulatorSamplerSound(); // ==================================================================================================================== /** Returns the name of the Property. * * This is used to display the name in the user interface and for the tag name within the XML samplemap, * so you must return a valid tag name here. */ /** Returns true if the property should be changed asynchronously when all voices are killed. */ static bool isAsyncProperty(const Identifier& id); /** Returns the min and max values for the Property. * * This method is non-static because you can change the range dynamically eg. depending on other properties. * * It returns the following ranges: * * - MIDI Upper limits: Low limits - 127 * - MIDI Lower limits: 0 -> Upper Limit * - RRGroups: 0 -> number of RR groups * - Volume: -100dB -> +18dB * - Pitch: -100ct -> +100ct * - Sample Start: 0 -> sample end or loop start or sample end - sample start mod * - Sample End: sample start + sampleStartMod -> file end * - Sample Start Mod: 0 -> sample length * - Loop enabled: 0 -> 1 * - Loop Start: (SampleStart + Crossfade) -> (LoopEnd - Crossfade) * - Loop End: (LoopStart + Crossfade) -> SampleEnd * - Loop Xfade: 0 -> (LoopStart - SampleStart) or LoopLength */ Range<int> getPropertyRange(const Identifier& p) const;; /** Returns a string version of the Property. * * This is used for displaying a nicer value than the raw data value (eg. note names, or milliseconds). * Do not use the return value for further processing, use getProperty() instead. */ String getPropertyAsString(const Identifier& id) const;; /** Toggles the boolean properties. * * Currently supported Properties: * * - Normalized * - LoopEnabled */ void toggleBoolProperty(const Identifier& id); var operator[] (const Identifier& id) const { return getSampleProperty(id); } // ==================================================================================================================== /** Call this whenever you want to start a new series of property modifications. */ void startPropertyChange(const Identifier& id, int newValue); void startPropertyChange() { } void startPropertyChange(const String& ) { } /** Call this whenever you finish a series of property modifications. * * It will group all actions since startPropertyChange and saves it to the UndoManager list * with a description "CHANGING PROPERTY FROM X TO Y" */ void endPropertyChange(const Identifier& id, int startValue, int endValue); void endPropertyChange(const String &actionName); // ==================================================================================================================== /** Closes the file handle for all samples of this sound. */ void openFileHandle(); /** Opens the file handle for all samples of this sound. */ void closeFileHandle(); // ==================================================================================================================== /** Returns the id. * * Can also be achieved by getProperty(ID), but this is more convenient. */ int getId() const { return data.getParent().indexOf(data); }; Range<int> getNoteRange() const; Range<int> getVelocityRange() const; /** Returns the gain value of the sound. * * Unlike getProperty(Volume), it returns a value from 0.0 to 1.0, so use this for internal stuff */ float getPropertyVolume() const noexcept; /** Returns the pitch value of the sound. * * Unlike getProperty(Pitch), it returns the pitch factor (from 0.5 to 2.0) */ double getPropertyPitch() const noexcept;; /** returns the sample rate of the sound (!= the sample rate of the current audio settings) */ double getSampleRate() const { return firstSound->getSampleRate(); }; /** returns the root note. */ int getRootNote() const noexcept{ return rootNote; }; void initPreloadBuffer(int preloadSize) { checkFileReference(); if (noteRangeExceedsMaxPitch()) preloadSize = -1; FOR_EVERY_SOUND(setPreloadSize(preloadSize, true)); } bool noteRangeExceedsMaxPitch() const; double getMaxPitchRatio() const; void loadEntireSampleIfMaxPitch(); // ==================================================================================================================== void setMaxRRGroupIndex(int newGroupLimit); void setRRGroup(int newGroupIndex) noexcept{ rrGroup = jmin(newGroupIndex, maxRRGroup); }; int getRRGroup() const; // ==================================================================================================================== bool appliesToVelocity(int velocity) override { return velocityRange[velocity]; }; bool appliesToNote(int midiNoteNumber) override { return !purged && allFilesExist && midiNotes[midiNoteNumber]; }; bool appliesToChannel(int /*midiChannel*/) override { return true; }; bool appliesToRRGroup(int group) const noexcept{ return rrGroup == group; }; // ==================================================================================================================== StreamingSamplerSound::Ptr getReferenceToSound() const { return firstSound.get(); }; StreamingSamplerSound::Ptr getReferenceToSound(int multiMicIndex) const { return soundArray[multiMicIndex]; }; PoolReference createPoolReference() const { return PoolReference(getMainController(), getSampleProperty(SampleIds::FileName).toString(), ProjectHandler::SubDirectories::Samples); } PoolReference createPoolReference(int multiMicIndex) const { if (isPositiveAndBelow(multiMicIndex, getNumMultiMicSamples())) { return PoolReference(getMainController(), getReferenceToSound(multiMicIndex)->getFileName(true), ProjectHandler::SubDirectories::Samples); } return {}; } // ==================================================================================================================== /** This sets the MIDI related properties without undo / range checks. */ void setMappingData(MappingData newData); /** Calculates the gain value that must be applied to normalize the volume of the sample ( 1.0 / peakValue ). * * It should save calculated value along with the other properties, but if a new sound is added, * it will call StreamingSamplerSound::getPeakValue(), which scans the whole file. */ void calculateNormalizedPeak();; void removeNormalisationInfo(UndoManager* um); /** Returns the gain value that must be applied to normalize the volume of the sample ( 1.0 / peakValue ). */ float getNormalizedPeak() const; /** Checks if the normalization gain should be applied to the sample. */ bool isNormalizedEnabled() const noexcept{ return isNormalized; }; /** Returns the calculated (equal power) pan value for either the left or the right channel. */ float getBalance(bool getRightChannelGain) const;; void setReversed(bool shouldBeReversed); // ==================================================================================================================== void setVelocityXFade(int crossfadeLength, bool isUpperSound); float getGainValueForVelocityXFade(int velocity); // ==================================================================================================================== int getNumMultiMicSamples() const noexcept;; bool isChannelPurged(int channelIndex) const;; void setChannelPurged(int channelIndex, bool shouldBePurged); bool preloadBufferIsNonZero() const noexcept; // ==================================================================================================================== bool isPurged() const noexcept{ return purged; }; void setPurged(bool shouldBePurged); void checkFileReference(); bool isMissing() const noexcept { for (auto s : soundArray) { if (s == nullptr || s->isMissing()) return true; } return false; }; // ==================================================================================================================== static void selectSoundsBasedOnRegex(const String &regexWildcard, ModulatorSampler *sampler, SelectedItemSet<ModulatorSamplerSound::Ptr> &set); ValueTree getData() const { return data; } void updateInternalData(const Identifier& id, const var& newValue); void updateAsyncInternalData(const Identifier& id, int newValue); var getDefaultValue(const Identifier& id) const; void setSampleProperty(const Identifier& id, const var& newValue, bool useUndo=true); var getSampleProperty(const Identifier& id) const; void setDeletePending() { deletePending = true; } bool isDeletePending() const { return deletePending; } void addEnvelopeProcessor(HiseAudioThumbnail& th); AudioFormatReader* createAudioReader(int micIndex); struct EnvelopeTable : public ComplexDataUIUpdaterBase::EventListener, public Timer { static constexpr int DownsamplingFactor = 32; using Type = Modulation::Mode; void timerCallback() override; EnvelopeTable(ModulatorSamplerSound& parent_, Type type_, const String& b64); ~EnvelopeTable(); void onComplexDataEvent(ComplexDataUIUpdaterBase::EventType t, var data) override; void rebuildBuffer(); SampleLookupTable table; WeakReference<HiseAudioThumbnail> thumbnailToPreview; static void processThumbnail(EnvelopeTable& t, var left, var right); void processBuffer(AudioSampleBuffer& b, int srcOffset, int dstOffset); float getUptimeValue(double uptime) const { if (auto sl = SimpleReadWriteLock::ScopedTryReadLock(lock)) { auto s = parent.getReferenceToSound(0); auto ls = (double)s->getLoopStart(); if (s->isLoopEnabled() && uptime > (ls - (double)sampleRange.getStart())) { uptime -= ls; uptime = hmath::wrap(uptime, (double)s->getLoopLength()); uptime += ls; } else uptime += (double)sampleRange.getStart(); uptime /= (double)DownsamplingFactor; auto idx = jlimit(0, numElements - 1, roundToInt(uptime)); return lookupTable[idx]; } return 1.0f; } static float getFreqValueInverse(float input); static float getFreqValue(float input); static float getGainValue(float input) { return input * 2.0f; } static float getPitchValue(float input); private: static String getFreqencyString(float input) { input = getFreqValue(input); String s; if (input > 1000.0f) { s << String(input / 1000.0, 1); s << " kHz"; } else { s << String(roundToInt(input)); s << " Hz"; } return s; } static String getGainString(float input) { auto v = getGainValue(input); v = Decibels::gainToDecibels(v); String s; s << String(v, 1) << "dB"; return s; } static String getPitchString(float input) { auto v = getSemitones(input) * 100.0f; String s; s << String(roundToInt(v)) << " ct"; return s; } static float getSemitones(float input) { input = input * 2.0f - 1.0f; return input; } Range<int> sampleRange; HeapBlock<float> lookupTable; int numElements; Type type; ModulatorSamplerSound& parent; mutable SimpleReadWriteLock lock; JUCE_DECLARE_WEAK_REFERENCEABLE(EnvelopeTable); }; EnvelopeTable* getEnvelope(Modulation::Mode m) { if (m < Modulation::Mode::numModes) return envelopes[m]; else return nullptr; } private: void clipRangeProperties(const Identifier& id, int value, bool useUndo); void loadSampleFromValueTree(const ValueTree& sampleData, HlacMonolithInfo* hmaf); int getPropertyValueWithDefault(const Identifier& id) const; WeakReference<SampleMap> parentMap; ValueTree data; UndoManager *undoManager; ScopedPointer<EnvelopeTable> envelopes[Modulation::Mode::numModes]; // ================================================================================================================ friend class MultimicMergeDialogWindow; const CriticalSection& getLock() const { return firstSound.get()->getSampleLock(); }; CriticalSection exportLock; float normalizedPeak = 1.0f; bool isNormalized = false; bool purged = false; bool reversed = false; int upperVeloXFadeValue = 0; int lowerVeloXFadeValue = 0; int rrGroup = 1; int rootNote; int maxRRGroup; BigInteger velocityRange; BigInteger midiNotes; std::atomic<float> gain; std::atomic<double> pitchFactor; float leftBalanceGain = 1.0f; float rightBalanceGain = 1.0f; BigInteger purgeChannels; bool allFilesExist; const bool isMultiMicSound; bool deletePending = false; StreamingSamplerSoundArray soundArray; WeakReference<StreamingSamplerSound> firstSound; bool enableAsyncPropertyChange = true; // ================================================================================================================ JUCE_DECLARE_WEAK_REFERENCEABLE(ModulatorSamplerSound) JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ModulatorSamplerSound) public: using WeakPtr = WeakReference<ModulatorSamplerSound>; }; typedef Array<ModulatorSamplerSound::Ptr> SampleSelection; /** This object acts as global pool for all samples used in an instance of the plugin * @ingroup sampler * * It uses reference counting to decide if a sound is used. If a sound is added more than once, * it will not load it again, but pass a reference to the already loaded Sound. * * This is achieved by isolating the actual sample data into a StreamingSamplerSound object which will be wrapped * by a ModulatorSamplerSound object. */ class ModulatorSamplerSoundPool : public StreamingSamplerSoundPool, public SafeChangeBroadcaster, public PoolBase { public: // ================================================================================================================ ModulatorSamplerSoundPool(MainController *mc, FileHandlerBase* handler); ~ModulatorSamplerSoundPool() {} // ================================================================================================================ struct PoolEntry { PoolReference r; WeakReference<StreamingSamplerSound> sound; StreamingSamplerSound* get() const { return sound.get(); } }; /** call this with any processor to enable console output. */ void setDebugProcessor(Processor *p);; HlacMonolithInfo::Ptr loadMonolithicData(const ValueTree &sampleMap, const Array<File>& monolithicFiles); void setUpdatePool(bool shouldBeUpdated) { updatePool = shouldBeUpdated; } void setDeactivatePoolSearch(bool shouldBeDeactivated) { searchPool = !shouldBeDeactivated; } void setAllowDuplicateSamples(bool shouldAllowDuplicateSamples); int getNumLoadedFiles() const override { return getNumSoundsInPool(); } PoolReference getReference(int index) const { return pool[index].r; } void clearData() override { pool.clear(); } var getAdditionalData(PoolReference r) const override { return var(); } StringArray getTextDataForId(int index) const override { return { pool[index].r.getReferenceString() }; }; void writeItemToOutput(OutputStream& /*output*/, PoolReference /*r*/) override { jassertfalse; } Identifier getFileTypeName() const { return "Samples"; }; // ================================================================================================================ void getMissingSamples(StreamingSamplerSoundArray &missingSounds) const; void resolveMissingSamples(Component *childComponentOfMainEditor); // ================================================================================================================ /** returns the number of sounds in the pool. */ int getNumSoundsInPool() const noexcept; StringArray getFileNameList() const; /** Returns the memory usage for all sounds in the pool. * * This is not the exact amount of memory usage of the application, because every sampler has voices which have * intermediate buffers, so the total memory footprint might be a few megabytes larger. */ size_t getMemoryUsageForAllSamples() const noexcept;; String getTextForPoolTable(int columnId, int indexInPool); // ================================================================================================================ void increaseNumOpenFileHandles() override; void decreaseNumOpenFileHandles() override; bool isFileBeingUsed(int poolIndex); bool &getPreloadLockFlag() { return isCurrentlyLoading; } bool isPreloading() const { return isCurrentlyLoading; } void setForcePoolSearch(bool shouldBeForced) { forcePoolSearch = shouldBeForced; }; bool isPoolSearchForced() const; void clearUnreferencedMonoliths(); void clearUnreferencedSamples(); StreamingSamplerSound* getSampleFromPool(PoolReference r) const; void addSound(const PoolEntry& newPoolEntry); void removeFromPool(const PoolReference& ref); HlacMonolithInfo* getMonolith(const Identifier& id); private: void clearUnreferencedSamplesInternal(); struct AsyncCleaner : public Timer { AsyncCleaner(ModulatorSamplerSoundPool& parent_) : parent(parent_) { flag = false; IF_NOT_HEADLESS(startTimer(300)); }; ~AsyncCleaner() { stopTimer(); } void triggerAsyncUpdate() { flag = true; } void timerCallback() override { if (flag) { parent.clearUnreferencedSamplesInternal(); flag = false; } } ModulatorSamplerSoundPool& parent; std::atomic<bool> flag; }; // ================================================================================================================ AsyncCleaner asyncCleaner; ReferenceCountedArray<HlacMonolithInfo> loadedMonoliths; int getSoundIndexFromPool(int64 hashCode); // ================================================================================================================ AudioProcessor *mainAudioProcessor; Processor *debugProcessor; MainController *mc; Array<PoolEntry> pool; bool isCurrentlyLoading; bool forcePoolSearch; bool updatePool; bool searchPool; bool allowDuplicateSamples = true; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ModulatorSamplerSoundPool) }; struct SamplePreviewer : public ControlledObject { SamplePreviewer(ModulatorSampler* sampler_);; static void applySampleProperty(AudioSampleBuffer& b, ModulatorSamplerSound::Ptr sound, const Identifier& id, int offset); void previewSample(ModulatorSamplerSound::Ptr soundToPlay, int micIndex); void setPreviewStart(int previewStart) { previewOffset = previewStart; } int getPreviewStart() const { return previewOffset; } bool isPlaying() const; private: void previewSampleFromDisk(ModulatorSamplerSound::Ptr soundToPlay, int micIndex); void previewSampleWithMidi(ModulatorSamplerSound::Ptr soundToPlay); WeakReference<ModulatorSampler> sampler; ModulatorSamplerSound::Ptr currentlyPlayedSound; int previewOffset = 0; HiseEvent previewNote; }; } // namespace hise
28.954348
162
0.647534
[ "object" ]
e72384f63e1bfd4ed9bf0053a105d3600c5867c4
21,037
h
C
Server/MapGen/MapGenerator/include/Crossing.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/MapGen/MapGenerator/include/Crossing.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/MapGen/MapGenerator/include/Crossing.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CROSSING_H #define CROSSING_H #include "OldConnection.h" #include "GMSNode.h" #include "GMSMap.h" #include <vector> #include "ObjVector.h" #include "Vector.h" #include "OldRouteableItem.h" #include "OldStreetSegmentItem.h" #define XOR(a,b) ((bool(a) && (! bool(b))) || (bool(b) && (! bool(a)))) /* * Feature! * Use exit count (1-4)in roundabout exit/entry connection so * ExpandRouteProcessor can detect symmetries. * This will enable the use of LEFT_ROUNDABOUT, RIGHT_ROUNDABOUT and AHEAD * in some 3-way, and 5-way roundabout. * * Ex. enter rbt with exit count (1). exit rbt with exit count (3), the turn * is ahead in roundabout. * Ex enter rbt with exit count (4). exit rbt with exit count (1), the turn * is right in roundabout. * * If the exit count is at entry or exit is (0) the normal rbExitnbr should * be used -- Take the second exit in the roundabout. * * Sometimes (5-way rbt) the entry could get a number but not the exit. * Other values might be used, 11-14 might mean that only RIGHT_ROUNDABOUT * should be allowed. */ /** * Describes a connection from to a crossing and contains information * about angle, roadclass, entry restrictions and if the streetsegment * of the connection is a ramp, part of a roundabout and if it is * multi digitalized. * */ class CrossingConnectionElement : public VectorElement { public: /** * @name Operators needed for searching and sorting. * Implements the virtual methods in VectorElement * to make it possible to sort the items. */ //@{ /// Define the "equal"-operator. virtual bool operator == (const VectorElement& elm) const { return ( (dynamic_cast<const CrossingConnectionElement*> (&elm) ) ->m_angle == m_angle ); } /// Define the "not equal"-operator. virtual bool operator != (const VectorElement& elm) const { return ( (dynamic_cast<const CrossingConnectionElement*> (&elm) ) ->m_angle != m_angle ); } /// Define the "greater than"-operator. virtual bool operator > (const VectorElement& elm) const { return ( m_angle > (dynamic_cast<const CrossingConnectionElement*> (&elm) )->m_angle); } /// Define the "less than"-operator. virtual bool operator < (const VectorElement& elm) const { return ( m_angle < (dynamic_cast<const CrossingConnectionElement*> (&elm))->m_angle); } /** * Creates a new CrossingConnectionElement. * @param angle The angle of this connection. * @param endNodeAngle The angle from the node in the crossing to the * SSI's other node. Only used when merging two multiDig CCE's to one. * @param node The index of the node in the crossing to which * this connection leads. * @param roadClass The road class of the connection. * @param roundabout True if this connection is part of a roundabout. * @param ramp True if this connection is part of a ramp. * @param multiDig True if this connection is multi digitalized. * @param name A vector with the name indexes of this connection. * @param restr The restrictions for LEAVING the crossing through this * connection. * @param ctrlAcc True if this connection has controlled access. * (Default value used to ease its introduction.) * @param length the lenght of the SSI of this element. * @param junction The type of junction when leaving the crossing on this * element */ CrossingConnectionElement(float64 angle, float64 endNodeAngle, byte nodeNbr, byte roadClass, bool roundabout, bool ramp, bool multiDig, Vector name, ItemTypes::entryrestriction_t restr, bool ctrlAcc = false, uint32 length = 0, ItemTypes::junction_t junction = ItemTypes::normalCrossing, bool roundaboutish = false); /** * Destructor. (Inlined) */ virtual ~CrossingConnectionElement(){}; /// The index of the node in the crossing to which this connection leads. byte m_nodeIndex; /// The angle of this connection. float64 m_angle; /// The angle all the way to the other node of the streetsegment. float64 m_endAngle; /// The road class of the connection. byte m_roadClass; /// Tells if this connection is part of a ramp. bool m_ramp; /// Tells if this connection is part of a roundabout. bool m_roundabout; /** * Tells if this connection is part of a traffic figure, similar to * a roundabout. */ bool m_roundaboutish; /// Tells if this connection is multi digitalized. bool m_ismulti; /// Tells if this connection has controlled access. bool m_isCtrAcc; /// A vector with the name indexes of this connection. Vector m_nameIndex; /// The length of the item. uint32 m_length; /// The restrictions for LEAVING the crossing through this connection. ItemTypes::entryrestriction_t m_passNodeRestrictions; /// The type of junction when leaving the crossing through this connection. ItemTypes::junction_t m_junctionType; private: void init(float64 angle, float64 endNodeAngle, byte node, byte roadClass, bool multiDig, bool roundabout, bool roundabouish, bool ramp, bool ctrlAcc, uint32 length, Vector name, ItemTypes::entryrestriction_t restr, ItemTypes::junction_t junction); /** * Declare the default constructor private to make sure no one * uses it. */ CrossingConnectionElement(); }; // CrossingConnectionElement /** * Describes a crossing and is used to set the turn descriptions and * crossin kinds of the connections to the nodes in the crossing. * */ class Crossing { public: /** * Constructor. * @param firstNode A node in the crossing to start with. * @param theMap The map containing the node. */ Crossing(OldNode* firstNode, OldMap* theMap); /** * Destructor. */ ~Crossing(); /** * Sets turnDescriptions and crossing kind for all connections in * the crossing. Even the turns that might be illegal are described. * Crossing kind roundabout crossings are set to UNDEFINED_CROSSING * and needs to be set by setRoundaboutCrossingKind(). * (Uses getTurnDescriptions() and sets the result to member fields.) * @return False if the Crossing only contains one node. */ bool setTurnDescriptions(); /** * Struct containing the output vector of a getTurnDescriptions() * operation. * @param fromConIndex The CCE this Struct comes from. * @param toConIndex The CCE this Struct leads to. * @param description The turndescription of the connection. * @param exitCount The exit count of the connection. * @param debug Flag indicating that this turndescription should be * debuged. */ struct turndesc_t { byte fromConIndex; byte toConIndex; ItemTypes::turndirection_t description; byte exitCount; bool debug; }; /// Vector of turndesc_t structs. typedef vector<turndesc_t> turndescvector_t; /** * Retuens a vector with the turn descripton to the ObjVector with * CrossingConnectionElements that is given. * The method is {\em static} so no Crossing object is needed as no * member fields are accessed. * @param conNotices The connElements of the crossing. * @param rightSideTraffic Set true if not a leftside country. * @param result The output result as a vector. * @param kind The output crossing-kind parameter. * @param countryCode The countryCode of the map where turn descr are * set. If setting turn desc for external conns, give * NBR_COUNTRY_CODES as default. Used for deciding certain * country specific rules. * @param printOut Set to true if debug printout for this crossing is * needed. * @param mapID The id of the map used. Only used for debugs. * @param nodeID The id of one of the nodes in the crossing. * Only used for debugs. * @return True if the operation was Ok and the result is correct. */ static bool getTurnDescriptions(ObjVector* conNotices, bool rightSideTraffic, turndescvector_t& result, ItemTypes::crossingkind_t& kind, StringTable::countryCode countryCode, bool printOut = false); /* * Set the correct crossing kind and ext count in the connections that are * part of a roundabout or roundaboutish traffic figure. * Creates new crossings and uses recursive calls to find the whole figure. * All these crossings are then completed. * @return True if a roundabout crossingkind is found */ bool setRoundaboutCrossingKind(); /** * Sets the turndescriptions to a OldFerryItem node. Turn descriptions from * FItems to SSI are handled by set/getTurnDescriptions(). * @param ferryNode The ferry item to set connections to. * @param theMap The map on which the ferry item is located. */ static bool getToFerryItemTurndescriptions(OldNode* ferryNode, OldMap* theMap); bool partOfRoundabout() const { return !m_noRoundabout; } int getNbrOfConnElements() const { return m_conNotices.size(); } OldNode* getNoEntryNode(bool &leavingRoundabout) const; /** * Get the connecting angle. * This is normaly the angle from the node to the first gfxData point. * If the distance to the first point is small and the gfxData makes * a sharp turn, the angle between the first and second point is used * instead. * @param gfx The gfxData of the item. * @param isNode0 True if node 0 is in the crossing. * @param printOut Set to true if debug printout for this crossing is * needed. * @return The angle from north. */ static float64 getAdjustedAngle(GfxData* gfx, bool isNode0, bool printOut=false); protected: /** * Default constructor. Protected to avoid use. */ Crossing(); /** * Get the two first or last coordinates in one GdfData. * * @param gfx Pointer to the GfxData * @param isNode0 Shall the position be set for node0 (first * coorinate in gfx) or node1 (last coorinate). * @param lat1 Outparameter. Set to the first latitude. * @param lon1 Outparameter. Set to the first longitude. * @param lat2 Outparameter. Set to the second latitude. * @param lon2 Outparameter. Set to the second longitude. */ void getLatLon(GfxData* gfx, bool isNode0, int32& lat1, int32& lon1, int32& lat2, int32& lon2); /** * Get the angle to the other node. */ void getNodeCoords(GfxData* gfx, bool isNode0, int32& lat1, int32& lon1, int32& lat2, int32& lon2); /** * Fills the connection vector, node vector and sets the other variables * of the crossing. * @param startNode The node the crossing starts with. * @return the number of nodes in the crossing. */ byte fillConnectionNotices(OldNode* startNode); /** * Reduces the connection vector by merging multidigitalized connections. * Creates a transfer vector, m_transfV, to link nodes to the connections * in the reduced vonnection vector, * @return Number of reductions. */ byte reduceConnections(); /** * Checks if two name index vectors are the same.(The names of the * connections are the same.) Used to deside if two multidigitalized * connections are realy the same road. * @return True if same. */ static bool nameSame(Vector &name1, Vector &name2); /** * Checks if two adjacent multidigitalized crossing connections are * realy the same road. Checks names, angles and entryrestrictions. * @return True if actually the same road. */ bool sameCon(CrossingConnectionElement* con1, CrossingConnectionElement* con2); /** * Gets the crossing connection belonging to a specified node. * @param node The node to get the crossing connection from. * @return The crossing connection. */ CrossingConnectionElement* getCrossingConnection(OldNode* node); /** * Gets the crossing connection belonging to a specified connection. * @param conn The connection to get the crossing connection from. * @return The crossing connection. */ CrossingConnectionElement* getCrossingConnection(OldConnection* conn); /** * Finds the index in the connection vector of the specified * crossing connection. * @param The crossing connection. * @return The index of the crossing connection. */ byte getCrossingConnectionIndex(CrossingConnectionElement* cConn); /** * Struct with info on an exit or entry of a roundabout. * @param connection Pointer to turndesc struct repesenting this * connection. * @param multiDig true if this connection i multidig. * @param exit True if this is a exit, false if it is an entry. * @param distance The distance in meters from the first conection of * the roundabout. * @param angle The connecting angle from north. * @param index The rbt connections index in the roundabout. (Each index * can have 0-1 entry and 0-1 exit. */ struct rbtconn_t{ OldConnection* conn; bool multiDig; bool exit; int32 distance; float64 angle; int index; bool valid; }; /** * Vector of rbtconn_t structs. Used to keep track of the exit and entries * of a roundabout. */ typedef vector<rbtconn_t> rbtconnvector_t; /* * Recursive method to set crossing kind and exit count in roundabouts. * Can make more recursive calls. After this method is done this crossing * and the one created after this has crossing kind but not exitCount set. * The conns vector is used by the caller to set exit counts. * @param endNode The end node of this roundabout/figure. Indicates that a * full lap has been made. * @param exits The number of exits found so far. * @param calls The number of recursive calls. To abort endless loops * @param conns The vector with entries and exits to hav their exitCounts * set. Used to indicate symmetry. * @return The final crossing kind for the whole figure (size of Rbt) */ ItemTypes::crossingkind_t setRoundaboutCrossingKind(OldNode* endNode, int &exits, int calls, uint32 nodeLength[4], int32 &distance, rbtconnvector_t &conns, bool backward = false); /** * Checks if a four-way roundabout is symetric, which means that the * exits will be marked right, ahead, and left. * @param nodeLength A vector with the segment length to each exit. * @param maxError The maximum allowed error. * @return True if The roundabout is 4-way and symetric. */ bool isSymetricRoundAbout(uint32 nodeLength[4], float64 maxError); /** * Sets the exit count value of the roundabout connections according to * the shape of the roundabout. * @param connections Vector with the connections to/from this roundabout. * @param circumference The circumference of the roundabout in meters. * @return The number of set exits+entries. */ int setRoundAboutConnectionSymmetry(rbtconnvector_t connections, uint32 circumference); /* * Returns true if this crossing contains un merged multidig segments. */ bool isPartOfMultidigCrossing(); /** * Check neighbouring crossings to see if this multidig crossing is * 4 or 3-way. */ ItemTypes::crossingkind_t getMultidigCrossingKind(OldNode* &endNode); /** * */ bool continueOtherSide(); /** * True if the connecting OldItem is longer than 12 m. * This is just a temp. half fix of a map error */ bool rbtAngleIsValid(OldNode* connNode, OldStreetSegmentItem* connItem); /** * Puts a new rbtconn_t at the right place in the rbtconnvector_t. * @param vector The vector to insert into. * @param conn The rbtconn_t to add. * @param rbtNode The entry node of the rbtconn_t. * @param last If true the conns should be added to the end of the list. * If false in the begining.(Used when going backwards) */ void addRbtConnToVector(rbtconnvector_t &vector, rbtconn_t conn, OldNode* rbtNode, bool last); /** * The max number of nodex there can be in the crossing. */ static const uint32 m_maxNbrNodesInACrossing; /** * A vector with the nodes of the crossing. Sorted clockwise. * Keep size in sync with the m_maxNbrNodesInACrossing */ OldNode* m_nodes[15]; /** * A vector wich links the nodes of the node vector to the crossing * connections of the crossing connection vector. * Keep size in sync with the m_maxNbrNodesInACrossing */ byte m_transfV[15]; /** * The vector of crossing connections elements leading to the crossing. * Sorted clockwise. */ ObjVector m_conNotices; /// the number of nodes in the crossing. byte m_numberOfNodes; /// The map which the crossing lies on. OldMap* m_map; /// Tells if the crossing is part of a roundabout. bool m_noRoundabout; /** * Tells if this crossing is part of a traffic figure that is similar * to a roundabout. */ bool m_noRoundaboutish; /// The number of ramps in the crossing. byte m_nbrRamps; /// The number of multidigitalized connections to the crossing. byte m_nbrMulti; /// The number of road names in the crossing. byte m_nbrNames; /// Debug variable. Marks if a crossing shall be printed out. bool m_printOut; /// The largest roadclass in the crossing. byte m_majRoadClass; /// The number of connections which is of the major roadclass. byte m_majConNbr; /// The number of connections of the major roadclass with entry /// restrictions. byte m_majRestrCon; }; // Crossing #endif // CROSSING_H
36.459272
755
0.643105
[ "object", "shape", "vector" ]
e7251664efd84fab8d77bf5400f56f98339211d8
144,873
c
C
CoreFoundation/Locale.subproj/CFCalendar_Enumerate.c
mustafagunes/swift-corelibs-foundation
f17b5a25bbc604126a8c6aca8b0b75c2e0291a6c
[ "Apache-2.0" ]
1
2021-05-01T07:42:48.000Z
2021-05-01T07:42:48.000Z
CoreFoundation/Locale.subproj/CFCalendar_Enumerate.c
mustafagunes/swift-corelibs-foundation
f17b5a25bbc604126a8c6aca8b0b75c2e0291a6c
[ "Apache-2.0" ]
null
null
null
CoreFoundation/Locale.subproj/CFCalendar_Enumerate.c
mustafagunes/swift-corelibs-foundation
f17b5a25bbc604126a8c6aca8b0b75c2e0291a6c
[ "Apache-2.0" ]
1
2021-08-04T16:24:38.000Z
2021-08-04T16:24:38.000Z
/* CFCalendar_Enumerate.c Copyright (c) 2004-2018, Apple Inc. and the Swift project authors Portions Copyright (c) 2014-2018, Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors */ #include <CoreFoundation/CFCalendar.h> #include "CFCalendar_Internal.h" #include "CFDateComponents.h" #include "CFLocaleInternal.h" #include "CFInternal.h" CF_PRIVATE CFDateRef _CFDateCreateWithTimeIntervalSinceDate(CFAllocatorRef allocator, CFTimeInterval ti, CFDateRef date) { CFTimeInterval ti2 = CFDateGetAbsoluteTime(date); return CFDateCreate(allocator, ti + ti2); } #pragma mark - #define NUM_CALENDAR_UNITS (14) static CFCalendarUnit const calendarUnits[NUM_CALENDAR_UNITS] = {kCFCalendarUnitEra, kCFCalendarUnitYear, kCFCalendarUnitQuarter, kCFCalendarUnitMonth, kCFCalendarUnitDay, kCFCalendarUnitHour, kCFCalendarUnitMinute, kCFCalendarUnitSecond, kCFCalendarUnitWeekday, kCFCalendarUnitWeekdayOrdinal, kCFCalendarUnitWeekOfMonth, kCFCalendarUnitWeekOfYear, kCFCalendarUnitYearForWeekOfYear, kCFCalendarUnitNanosecond}; static CFDateRef _CFCalendarCreateDateIfEraHasYear(CFCalendarRef calendar, CFIndex era, CFIndex year) { CFDateComponentsRef tempComp = CFDateComponentsCreate(kCFAllocatorSystemDefault); CFDateComponentsSetValue(tempComp, kCFCalendarUnitEra, era); CFDateComponentsSetValue(tempComp, kCFCalendarUnitYear, year); CFDateRef date = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, tempComp); CFRelease(tempComp); CFDateComponentsRef comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, date); // This is only needed for the comparison below if (year == 1) { CFDateComponentsRef addingUnit = CFDateComponentsCreate(kCFAllocatorSystemDefault); CFDateComponentsSetValue(addingUnit, kCFCalendarUnitDay, 1); // this is needed for Japanese calendar (and maybe other calenders with more than a few eras too) while (CFDateComponentsGetValue(comp, kCFCalendarUnitEra) < era) { CFDateRef newDate = _CFCalendarCreateDateByAddingDateComponentsToDate(kCFAllocatorSystemDefault, calendar, addingUnit, date, 0); CFRelease(date); date = newDate; CFRelease(comp); comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra, date); } CFRelease(addingUnit); CFRelease(comp); comp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, date); // Because comp may have changed in the loop } CFIndex compEra = CFDateComponentsGetValue(comp, kCFCalendarUnitEra); CFIndex compYear = CFDateComponentsGetValue(comp, kCFCalendarUnitYear); CFRelease(comp); if (compEra == era && compYear == year) { // For Gregorian calendar at least, era and year should always match up so date should always be assigned to result. return date; } else { CFRelease(date); } return NULL; } static CFDateRef _CFCalendarCreateDateIfEraHasYearForWeekOfYear(CFCalendarRef calendar, CFIndex era, CFIndex yearForWeekOfYear, CFTimeInterval *resultInv) { CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYear(calendar, era, yearForWeekOfYear); if (yearBegin) { // find the beginning of the year for week of year CFDateRef result = NULL; _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitYearForWeekOfYear, &result, resultInv, yearBegin); CFRelease(yearBegin); return result; } return NULL; } static Boolean _CFCalendarCheckDateContainsMatchingComponents(CFCalendarRef calendar, CFDateRef date, CFDateComponentsRef compsToMatch, CFCalendarUnit *mismatchedUnits) { Boolean dateMatchesComps = true; CFCalendarRef cal = CFDateComponentsCopyCalendar(compsToMatch); CFTimeZoneRef tz = CFDateComponentsCopyTimeZone(compsToMatch); Boolean leapMonth = CFDateComponentsIsLeapMonth(compsToMatch); Boolean isLeapMonthSet = CFDateComponentsIsLeapMonthSet(compsToMatch); CFIndex era = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitEra); CFIndex year = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYear); CFIndex quarter = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitQuarter); CFIndex month = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMonth); CFIndex day = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitDay); CFIndex hour = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitHour); CFIndex minute = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMinute); CFIndex second = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitSecond); CFIndex weekday = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekday); CFIndex weekdayordinal = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekdayOrdinal); CFIndex weekOfMonth = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekOfMonth); CFIndex weekOfYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitWeekOfYear); CFIndex yearForWeekOfYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYearForWeekOfYear); CFIndex nanosecond = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitNanosecond); CFIndex compsToMatchValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond}; CFCalendarUnit setUnits = 0; for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) { if (compsToMatchValues[i] != CFDateComponentUndefined) { setUnits |= calendarUnits[i]; } } CFDateComponentsRef compsFromDate = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, setUnits, date); if (cal) { CFDateComponentsSetCalendar(compsFromDate, cal); CFRelease(cal); } if (tz) { CFDateComponentsSetTimeZone(compsFromDate, tz); CFRelease(tz); } if (!CFEqual(compsFromDate, compsToMatch)) { dateMatchesComps = false; // Need to make them both arrays so we can cycle through them and find the mismatched units CFIndex dateEra = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitEra); CFIndex dateYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitYear); CFIndex dateQuarter = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitQuarter); CFIndex dateMonth = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitMonth); CFIndex dateDay = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitDay); CFIndex dateHour = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitHour); CFIndex dateMinute = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitMinute); CFIndex dateSecond = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitSecond); CFIndex dateWeekday = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekday); CFIndex dateWeekdayordinal = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekdayOrdinal); CFIndex dateWeekOfMonth = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekOfMonth); CFIndex dateWeekOfYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitWeekOfYear); CFIndex dateYearForWeekOfYear = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitYearForWeekOfYear); CFIndex dateNanosecond = CFDateComponentsGetValue(compsFromDate, kCFCalendarUnitNanosecond); CFIndex compsFromDateValues[NUM_CALENDAR_UNITS] = {dateEra, dateYear, dateQuarter, dateMonth, dateDay, dateHour, dateMinute, dateSecond, dateWeekday, dateWeekdayordinal, dateWeekOfMonth, dateWeekOfYear, dateYearForWeekOfYear, dateNanosecond}; if (mismatchedUnits) { for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) { if (compsToMatchValues[i] != compsFromDateValues[i]) { *mismatchedUnits |= calendarUnits[i]; } } if (isLeapMonthSet) { if (leapMonth != CFDateComponentsIsLeapMonth(compsFromDate)) { *mismatchedUnits |= kCFCalendarUnitLeapMonth; } } } } CFRelease(compsFromDate); return dateMatchesComps; } static CFCalendarUnit _CFCalendarNextHigherUnit(CFCalendarUnit unit) { CFCalendarUnit higherUnit = kCFNotFound; switch (unit) { case kCFCalendarUnitEra: break; case kCFCalendarUnitYear: case kCFCalendarUnitYearForWeekOfYear: higherUnit = kCFCalendarUnitEra; break; case kCFCalendarUnitWeekOfYear: higherUnit = kCFCalendarUnitYearForWeekOfYear; break; case kCFCalendarUnitQuarter: case kCFCalendarUnitLeapMonth: case kCFCalendarUnitMonth: higherUnit = kCFCalendarUnitYear; break; case kCFCalendarUnitDay: case kCFCalendarUnitWeekOfMonth: case kCFCalendarUnitWeekdayOrdinal: higherUnit = kCFCalendarUnitMonth; break; case kCFCalendarUnitWeekday: higherUnit = kCFCalendarUnitWeekOfMonth; break; case kCFCalendarUnitHour: higherUnit = kCFCalendarUnitDay; break; case kCFCalendarUnitMinute: higherUnit = kCFCalendarUnitHour; break; case kCFCalendarUnitSecond: higherUnit = kCFCalendarUnitMinute; break; case kCFCalendarUnitNanosecond: higherUnit = kCFCalendarUnitSecond; default: break; } return higherUnit; } static Boolean _CFCalendarCheckIfLeapMonthHack(CFCalendarRef calendar, CFDateRef date) { // This is a hack. kCFCalendarUnitLeapMonth is SPI and components:fromDate: doesn't use it so we can't use it here (even though it's what we actually want), but whenever you create an NSDateComponents object, it sets leapMonthSet by default so we benefit. // TODO: Fact check above statement CFDateComponentsRef tempComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitMonth, date); Boolean isLeapMonth = CFDateComponentsIsLeapMonth(tempComps); Boolean isLeapMonthSet = CFDateComponentsIsLeapMonthSet(tempComps); CFRelease(tempComps); return (isLeapMonthSet && isLeapMonth); } static CFIndex _CFCalendarSetUnitCount(CFDateComponentsRef comps) { CFIndex totalSetUnits = 0; CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra); CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear); CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter); CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay); CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour); CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond); CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal); CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth); CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear); CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear); CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond); CFIndex compsValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond}; for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) { if (compsValues[i] != CFDateComponentUndefined) totalSetUnits++; } return totalSetUnits; } #pragma mark - #pragma mark Create Next Helpers static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingEra(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean *foundEra) { const CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra); if (era == CFDateComponentUndefined) return NULL; CFIndex dateEra = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitEra, startDate); if (era == dateEra) return NULL; CFDateRef result = NULL; if ((goBackwards && era <= dateEra) || (!goBackwards && era >= dateEra)) { CFDateComponentsRef datecomp = CFDateComponentsCreate(kCFAllocatorSystemDefault); CFDateComponentsSetValue(datecomp, kCFCalendarUnitEra, era); CFDateComponentsSetValue(datecomp, kCFCalendarUnitYear, 1); CFDateComponentsSetValue(datecomp, kCFCalendarUnitMonth, 1); CFDateComponentsSetValue(datecomp, kCFCalendarUnitDay, 1); CFDateComponentsSetValue(datecomp, kCFCalendarUnitHour, 0); CFDateComponentsSetValue(datecomp, kCFCalendarUnitMinute, 0); CFDateComponentsSetValue(datecomp, kCFCalendarUnitSecond, 0); CFDateComponentsSetValue(datecomp, kCFCalendarUnitNanosecond, 0); result = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, datecomp); CFRelease(datecomp); CFIndex dateCompEra = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitEra, result); if (dateCompEra != era) { *foundEra = false; // cannot find the matching era } } else { *foundEra = false; // cannot find the matching era } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear); if (year == CFDateComponentUndefined) return NULL; CFDateRef result = NULL; CFDateComponentsRef dateComp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear, startDate); if (year != CFDateComponentsGetValue(dateComp, kCFCalendarUnitYear)) { CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYear(calendar, CFDateComponentsGetValue(dateComp, kCFCalendarUnitEra), year); if (yearBegin) { // We set searchStartDate to the end of the year ONLY if we know we will be trying to match anything else beyond just the year and it'll be a backwards search; otherwise, we set searchStartDate to the start of the year. const CFIndex totalSetUnits = _CFCalendarSetUnitCount(comps); if (goBackwards && (totalSetUnits > 1)) { CFTimeInterval yearEndInv = 0.0; Boolean foundRange = CFCalendarGetTimeRangeOfUnit(calendar, kCFCalendarUnitYear, CFDateGetAbsoluteTime(yearBegin), NULL, &yearEndInv); if (foundRange) { result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearEndInv-1, yearBegin); } CFRelease(yearBegin); } else { result = yearBegin; } } } CFRelease(dateComp); return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingYearForWeekOfYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear); if (yearForWeekOfYear == CFDateComponentUndefined) return NULL; CFDateRef result = NULL; CFDateComponentsRef dateComp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYearForWeekOfYear, startDate); if (yearForWeekOfYear != CFDateComponentsGetValue(dateComp, kCFCalendarUnitYearForWeekOfYear)) { CFTimeInterval yearInv = 0.0; CFDateRef yearBegin = _CFCalendarCreateDateIfEraHasYearForWeekOfYear(calendar, CFDateComponentsGetValue(dateComp, kCFCalendarUnitEra), yearForWeekOfYear, &yearInv); if (yearBegin) { if (goBackwards) { // We need to set searchStartDate to the end of the year CFTimeInterval yearEndInv = 0.0; Boolean foundRange = CFCalendarGetTimeRangeOfUnit(calendar, kCFCalendarUnitYearForWeekOfYear, CFDateGetAbsoluteTime(yearBegin), NULL, &yearEndInv); if (foundRange) { result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearEndInv-1, yearBegin); } CFRelease(yearBegin); } else { result = yearBegin; } } } CFRelease(dateComp); return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingQuarter(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter); if (quarter == CFDateComponentUndefined) return NULL; CFDateRef result = NULL; // So this is a thing -- <rdar://problem/30229506> NSCalendar -component:fromDate: always returns 0 for kCFCalendarUnitQuarter CFDateRef yearBegin = NULL; CFTimeInterval yearInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitYear, &yearBegin, &yearInv, startDate); // Get the beginning of the year we need if (foundRange) { CFIndex count; CFDateRef quarterBegin = NULL; CFTimeInterval quarterInv = 0.0; if (goBackwards) { quarterBegin = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, yearInv-1, yearBegin); CFRelease(yearBegin); count = 4; while ((count != quarter) && (count > 0)) { CFDateRef tempDate = NULL; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitQuarter, &tempDate, &quarterInv, quarterBegin); CFRelease(quarterBegin); quarterBegin = tempDate; quarterInv *= -1; tempDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, quarterInv, quarterBegin); CFRelease(quarterBegin); quarterBegin = tempDate; count--; } } else { count = 1; quarterBegin = yearBegin; while ((count != quarter) && (count < 5)) { CFDateRef tempDate = NULL; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitQuarter, &tempDate, &quarterInv, quarterBegin); CFRelease(quarterBegin); quarterBegin = tempDate; tempDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, quarterInv, quarterBegin); CFRelease(quarterBegin); quarterBegin = tempDate; count++; } } result = quarterBegin; } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekOfYear(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear); if (weekOfYear == CFDateComponentUndefined) return NULL; CFIndex dateWeekOfYear = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfYear, startDate); if (weekOfYear == dateWeekOfYear) { // Already matches return NULL; } // After this point, the result is at least the start date CFDateRef result = CFRetain(startDate); CFDateRef woyBegin = NULL; CFTimeInterval woyInv = 0.0; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfYear, &woyBegin, &woyInv, result); if (foundRange) { if (goBackwards) { // If yearForWeekOfYear is set, at this point we'd already be at the end of the right year, so we can just iterate backward to find the week we need woyInv *= -1; // So we can go backwards in time } CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, woyInv, woyBegin); dateWeekOfYear = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfYear, tempSearchDate); CFRelease(result); result = tempSearchDate; CFRelease(woyBegin); } } while (weekOfYear != dateWeekOfYear); return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingMonth(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean isStrictMatching) { const CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); if (month == CFDateComponentUndefined) return NULL; Boolean isLeapMonthDesired = CFDateComponentsIsLeapMonth(comps); Boolean isLeapMonthSetDesired = CFDateComponentsIsLeapMonthSet(comps); const Boolean isChineseCalendar = CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierChinese); // isLeapMonth only works for Chinese calendar if (!isChineseCalendar) { isLeapMonthSetDesired = false; isLeapMonthDesired = false; } // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFIndex dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, result); if (month != dateMonth) { CFDateRef monthBegin = NULL; CFTimeInterval mInv = 0.0; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &monthBegin, &mInv, result); if (foundRange) { // If year is set, at this point we'd already be at the start of the right year, so we can just iterate forward to find the month we need if (goBackwards) { CFIndex numMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, monthBegin); if ((numMonth == 3) && CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierGregorian)) { mInv -= (86400*3); // Take it back 3 days so we land in february. That is, March has 31 days, and Feb can have 28 or 29, so to ensure we get to either Feb 1 or 2, we need to take it back 3 days. } else { mInv -= 86400; // Take it back a day } mInv *= -1; // So we can go backwards in time } CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, mInv, monthBegin); dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, tempSearchDate); CFRelease(result); result = tempSearchDate; CFRelease(monthBegin); } } while (month != dateMonth); } // As far as we know, this is only relevant for the Chinese calendar. In that calendar, the leap month has the same month number as the preceding month. // If we're searching forwards in time looking for a leap month, we need to skip the first occurrence we found of that month number because the first occurrence would not be the leap month; however, we only do this is if we are matching strictly. If we don't care about strict matching, we can skip this and let the caller handle it so it can deal with the approximations if necessary. if (isLeapMonthSetDesired && isLeapMonthDesired && isStrictMatching) { CFDateRef leapMonthBegin = NULL; CFTimeInterval leapMonthInv = 0.0; Boolean leapMonthFound = false; // We should check if we're already at a leap month! if (!_CFCalendarCheckIfLeapMonthHack(calendar, result)) { CFDateRef tempSearchDate = CFRetain(result); do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &leapMonthBegin, &leapMonthInv, tempSearchDate); if (foundRange) { if (goBackwards) { if (isChineseCalendar) { // Months in the Chinese calendar can be either 29 days ("short month") or 30 days ("long month"). We need to account for this when moving backwards in time so we don't end up accidentally skipping months. If leapMonthBegin is 30 days long, we need to subtract from that 30 so we don't potentially skip over the previous short month. // Also note that some days aren't exactly 24hrs long, so we can end up with lengthOfMonth being something like 29.958333333332, for example. This is a (albeit hacky) way of getting around that. double lengthOfMonth = leapMonthInv / 86400; if (lengthOfMonth > 30) { leapMonthInv -= 86400*2; } else if (lengthOfMonth > 28) { leapMonthInv -= 86400; } } leapMonthInv *= -1; } CFDateRef tempPossibleLeapMonth = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, leapMonthInv, leapMonthBegin); CFDateComponentsRef monthComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitMonth|kCFCalendarUnitLeapMonth, tempPossibleLeapMonth); dateMonth = CFDateComponentsGetValue(monthComps, kCFCalendarUnitMonth); Boolean tempLeapMonth = false; if (CFDateComponentsIsLeapMonthSet(monthComps)) { tempLeapMonth = CFDateComponentsIsLeapMonth(monthComps); } CFRelease(monthComps); if ((dateMonth == month) && tempLeapMonth) { CFRelease(result); result = tempPossibleLeapMonth; leapMonthFound = true; } else { CFRelease(tempSearchDate); tempSearchDate = tempPossibleLeapMonth; } CFRelease(leapMonthBegin); } } while (!leapMonthFound); CFRelease(tempSearchDate); } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekOfMonth(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth); if (weekOfMonth == CFDateComponentUndefined) return NULL; CFIndex dateWeekOfMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfMonth, startDate); if (weekOfMonth == dateWeekOfMonth) { // Already matches return NULL; } // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFDateRef womBegin = NULL; CFTimeInterval womInv = 0.0; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &womBegin, &womInv, result); if (foundRange) { // We need to advance or rewind to the next week. // This is simple when we can jump by a whole week interval, but there are complications around WoM == 1 because it can start on any day of the week. Jumping forward/backward by a whole week can miss it. // // A week 1 which starts on any day but Sunday contains days from week 5 of the previous month, e.g. // // June 2018 // Su Mo Tu We Th Fr Sa // 1 2 // 3 4 5 6 7 8 9 // 10 11 12 13 14 15 16 // 17 18 19 20 21 22 23 // 24 25 26 27 28 29 30 // // Week 1 of June 2018 starts on Friday; any day before that is week 5 of May. // We can jump by a week interval if we're not looking for WoM == 2 or we're not close. bool advanceDaily = (weekOfMonth == 1) /* we're looking for WoM == 1 */; if (goBackwards) { // Last week/earlier this week is week 1. advanceDaily &= dateWeekOfMonth <= 2; } else { // We need to be careful if it's the last week of the month. We can't assume what number week that would be, so figure it out. CFRange range = CFCalendarGetRangeOfUnit(calendar, kCFCalendarUnitWeekOfMonth, kCFCalendarUnitMonth, CFDateGetAbsoluteTime(result)); advanceDaily &= dateWeekOfMonth == range.length; } CFDateRef tempSearchDate = NULL; if (!advanceDaily) { // We can jump directly to next/last week. There's just one further wrinkle here when doing so backwards: due to DST, it's possible that this week is longer/shorter than last week. // That means that if we rewind by womInv (the length of this week), we could completely skip last week, or end up not at its first instant. // // We can avoid this by not rewinding by womInv, but by going directly to the start. if (goBackwards) { // Any instant before womBegin is last week. CFDateRef lateLastWeek = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, womBegin); if (!_CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &tempSearchDate, NULL, lateLastWeek)) { // It shouldn't be possible to hit this case, but if we somehow got here, we can fall back to searching day by day. advanceDaily = YES; } CFRelease(lateLastWeek); } else { // Skipping forward doesn't have these DST concerns, since womInv already represents the length of this week. tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, womInv, womBegin); } } // This is a separate condition because it represents a "possible" fallthrough from above. if (advanceDaily) { // The start of week 1 of any month is just day 1 of the month. CFDateRef today = CFRetain(womBegin); while (CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, today) != 1) { CFDateRef next = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, (goBackwards ? -1 : 1), kCFCalendarUnitDay, today); CFRelease(today); today = next; } tempSearchDate = today; } CFRelease(womBegin); dateWeekOfMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekOfMonth, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (weekOfMonth != dateWeekOfMonth); return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekdayOrdinal(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal); if (weekdayordinal == CFDateComponentUndefined) return NULL; CFIndex dateWeekdayOrd = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekdayOrdinal, startDate); if (weekdayordinal == dateWeekdayOrd) { // Already matches return NULL; } // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFDateRef wdBegin = NULL; CFTimeInterval wdInv = 0.0; do { // TODO: Consider jumping ahead by week here instead of day. Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekdayOrdinal, &wdBegin, &wdInv, result); if (foundRange) { if (goBackwards) { wdInv *= -1; // So we can go backwards in time } CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, wdInv, wdBegin); CFRelease(wdBegin); dateWeekdayOrd = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekdayOrdinal, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (weekdayordinal != dateWeekdayOrd); // NOTE: In order for an ordinal weekday to not be ambiguous, it needs both // - the ordinality (e.g. 1st) // - the weekday (e.g. Tuesday) // If the weekday is not set, we assume the client just wants the first time in a month where the number of occurrences of a day matches the weekdayOrdinal value (e.g. for weekdayOrdinal = 4, this means the first time a weekday is the 4th of that month. So if the start date is 2017-06-01, then the first time we hit a day that is the 4th occurrence of a weekday would be 2017-06-22. I recommend looking at the month in its entirety on a calendar to see what I'm talking about.). This is an odd request, but we will return that result to the client while silently judging them. // For a non-ambiguous ordinal weekday (i.e. the ordinality and the weekday have both been set), we need to ensure that we get the exact ordinal day that we are looking for. Hence the below weekday check. const CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); if (weekday == CFDateComponentUndefined) { // Skip weekday return result; } // Once we're here, it means we found a day with the correct ordinality, but it may not be the specific weekday we're also looking for (e.g. we found the 2nd Thursday of the month when we're looking for the 2nd Friday). CFIndex dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, result); if (weekday == dateWeekday) { // Already matches return result; } // Start result over CFRelease(result); result = NULL; if (dateWeekday > weekday) { // We're past the weekday we want. Go to the beginning of the week // We use startDate again here, not result Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekOfMonth, &result, NULL, startDate); if (foundRange) { CFDateComponentsRef startingDayWeekdayComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitWeekday|kCFCalendarUnitWeekdayOrdinal, result); dateWeekday = CFDateComponentsGetValue(startingDayWeekdayComps, kCFCalendarUnitWeekday); dateWeekdayOrd = CFDateComponentsGetValue(startingDayWeekdayComps, kCFCalendarUnitWeekdayOrdinal); CFRelease(startingDayWeekdayComps); } } if (!result) { // We need to have a value here - use the start date result = CFRetain(startDate); } while ((weekday != dateWeekday) || (weekdayordinal != dateWeekdayOrd)) { // Now iterate through each day of the week until we find the specific weekday we're looking for. CFDateRef currWeekday = NULL; CFTimeInterval currWeekdayInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &currWeekday, &currWeekdayInv, result); if (foundRange) { CFDateRef nextDay = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, currWeekdayInv, currWeekday); CFDateComponentsRef nextDayWeekdayComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitWeekday|kCFCalendarUnitWeekdayOrdinal, nextDay); dateWeekday = CFDateComponentsGetValue(nextDayWeekdayComps, kCFCalendarUnitWeekday); dateWeekdayOrd = CFDateComponentsGetValue(nextDayWeekdayComps, kCFCalendarUnitWeekdayOrdinal); CFRelease(nextDayWeekdayComps); CFRelease(result); result = nextDay; CFRelease(currWeekday); } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingWeekday(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { // NOTE: This differs from the weekday check in weekdayOrdinal because weekday is meant to be ambiguous and can be set without setting the ordinality. // e.g. inquiries like "find the next tuesday after 2017-06-01" or "find every wednesday before 2012-12-25" const CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); if (weekday == CFDateComponentUndefined) return NULL; CFIndex dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, startDate); if (weekday == dateWeekday) { // Already matches return NULL; } // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFDateRef wdBegin = NULL; CFTimeInterval wdInv = 0.0; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitWeekday, &wdBegin, &wdInv, result); if (foundRange) { // We need to either advance or rewind by a day. // * Advancing to tomorrow is relatively simple: get the start of today and get the length of that day — then, advance by that length // * Rewinding to the start of yesterday is more complicated: the length of today is not necessarily the length of yesterday if DST transitions are involved: // * Today can have 25 hours: if we rewind 25 hours from the start of today, we'll skip yesterday altogether // * Today can have 24 hours: if we rewind 24 hours from the start of today, we might skip yesterday if it had 23 hours, or end up at the wrong time if it had 25 // * Today can have 23 hours: if we rewind 23 hours from the start of today, we'll end up at the wrong time yesterday // // We need to account for DST by ensuring we rewind to exactly the time we want. CFDateRef tempSearchDate = NULL; if (goBackwards) { // Any time prior to dayBegin is yesterday. Since we want to rewind to the start of yesterday, do that directly. CFDateRef lateYesterday = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, wdBegin); CFDateRef yesterdayBegin = NULL; // Now we can get the exact moment that yesterday began on. // It shouldn't be possible to fail to find this interval, but if that somehow happens, we can try to fall back to the simple but wrong method. foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &yesterdayBegin, NULL, lateYesterday); if (foundRange) { tempSearchDate = yesterdayBegin; } else { // This fallback is only really correct when today and yesterday have the same length. // Again, it shouldn't be possible to hit this case. tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -wdInv, wdBegin); } CFRelease(lateYesterday); } else { // This is always correct to do since we are using today's length on today — there can't be a mismatch. tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, wdInv, wdBegin); } CFRelease(wdBegin); dateWeekday = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitWeekday, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (weekday != dateWeekday); return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingDay(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay); if (day == CFDateComponentUndefined) return NULL; // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFIndex dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, result); const CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); if ((month != CFDateComponentUndefined) && goBackwards) { // Are we in the right month already? If we are and goBackwards is set, we should move to the beginning of the last day of the month and work backwards. CFDateRef monthBegin = NULL; CFTimeInterval monthInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &monthBegin, &monthInv, result); if (foundRange) { CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, monthInv-1, monthBegin); // Check the order to make sure we didn't jump ahead of the start date CFComparisonResult order = CFDateCompare(tempSearchDate, originalStartDate, NULL); if (order == kCFCompareGreaterThan) { // We went too far ahead. Just go back to using the start date as our upper bound. CFRelease(result); result = CFRetain(originalStartDate); } else { CFDateRef dayBegin = NULL; CFTimeInterval dInv = 0.0; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, tempSearchDate); if (foundRange) { CFRelease(result); result = dayBegin; dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, result); } } CFRelease(tempSearchDate); CFRelease(monthBegin); } } CFDateRef dayBegin = NULL; CFTimeInterval dInv = 0.0; if (day != dateDay) { // The condition below keeps us from blowing past a month day by day to find a day which does not exist. // e.g. trying to find the 30th of February starting in January would go to March 30th if we don't stop here CFIndex const originalMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, result); Boolean advancedPastWholeMonth = false; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, result); if (foundRange) { // We need to either advance or rewind by a day. // * Advancing to tomorrow is relatively simple: get the start of today and get the length of that day — then, advance by that length // * Rewinding to the start of yesterday is more complicated: the length of today is not necessarily the length of yesterday if DST transitions are involved: // * Today can have 25 hours: if we rewind 25 hours from the start of today, we'll skip yesterday altogether // * Today can have 24 hours: if we rewind 24 hours from the start of today, we might skip yesterday if it had 23 hours, or end up at the wrong time if it had 25 // * Today can have 23 hours: if we rewind 23 hours from the start of today, we'll end up at the wrong time yesterday // // We need to account for DST by ensuring we rewind to exactly the time we want. CFDateRef tempSearchDate = NULL; if (goBackwards) { // Any time prior to dayBegin is yesterday. Since we want to rewind to the start of yesterday, do that directly. CFDateRef lateYesterday = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, dayBegin); CFDateRef yesterdayBegin = NULL; // Now we can get the exact moment that yesterday began on. // It shouldn't be possible to fail to find this interval, but if that somehow happens, we can try to fall back to the simple but wrong method. foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &yesterdayBegin, NULL, lateYesterday); if (foundRange) { tempSearchDate = yesterdayBegin; } else { // This fallback is only really correct when today and yesterday have the same length. // Again, it shouldn't be possible to hit this case. tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -dInv, dayBegin); } CFRelease(lateYesterday); } else { // This is always correct to do since we are using today's length on today -- there can't be a mismatch. tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, dInv, dayBegin); } CFRelease(dayBegin); dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, tempSearchDate); CFIndex const dateMonth = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, tempSearchDate); CFRelease(result); result = tempSearchDate; if (llabs(dateMonth - originalMonth) >= 2) { advancedPastWholeMonth = true; break; } } } while (day != dateDay); // If we blew past a month in its entirety, roll back by a day to the very end of the month. if (advancedPastWholeMonth) { CFDateRef const tempSearchDate = result; result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -dInv, tempSearchDate); CFRelease(tempSearchDate); } } else { // When the search date matches the day we're looking for, we still need to clear the lower components in case they are not part of the components we're looking for. Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, &dInv, result); if (foundRange) { CFRelease(result); result = dayBegin; } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingHour(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean findLastMatch, Boolean isStrictMatching, CFOptionFlags options) { const CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour); if (hour == CFDateComponentUndefined) return NULL; // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); Boolean adjustedSearchStartDate = false; CFIndex dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, result); // The loop below here takes care of advancing forward in the case of an hour mismatch, taking DST into account. // However, it does not take into account a unique circumstance: searching for hour 0 of a day on a day that has no hour 0 due to DST. // // America/Sao_Paulo, for instance, is a time zone which has DST at midnight -- an instant after 11:59:59 PM can become 1:00 AM, which is the start of the new day: // // 2018-11-03 2018-11-04 // ┌─────11:00 PM (GMT-3)─────┐ │ ┌ ─ ─ 12:00 AM (GMT-3)─ ─ ─┐ ┌─────1:00 AM (GMT-2) ─────┐ // │ │ │ | │ │ │ // └──────────────────────────┘ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ └▲─────────────────────────┘ // Nonexistent └── Start of Day // // The issue with this specifically is that parts of the rewinding algorithm that handle overshooting rewind to the start of the day to search again (or alternatively, adjusting higher components tends to send us to the start of the day). // This doesn't work when the day starts past the time we're looking for if we're looking for hour 0. // // If we're not matching strictly, we need to check whether we're already a non-strict match and not an overshoot. if (hour == 0 /* searching for hour 0 */ && !isStrictMatching) { CFDateRef dayBegin = NULL; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &dayBegin, NULL, result); if (foundRange) { CFIndex firstHourOfTheDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, dayBegin); if (firstHourOfTheDay != 0 && dateHour == firstHourOfTheDay) { // We're at the start of the day; it's just not hour 0. // We have a candidate match. We can modify that match based on the actual options we need to set. if (options & kCFCalendarMatchNextTime) { // We don't need to preserve the smallest components. We can wipe them out. // Note that we rewind to the start of the hour by rewinding to the start of the day -- normally we'd want to rewind to the start of _this_ hour in case there were a difference in a first/last scenario (repeated hour DST transition), but we can't both be missing hour 0 _and_ be the second hour in a repeated transition. result = CFRetain(dayBegin); } else if (options & kCFCalendarMatchNextTimePreservingSmallerUnits || options & kCFCalendarMatchPreviousTimePreservingSmallerUnits) { // We want to preserve any currently set smaller units (hour and minute), so don't do anything. // If we need to match the previous time (i.e. go back an hour), that adjustment will be made elsewhere, in the generalized isForwardDST adjustment in the main loop. } // Avoid making any further adjustments again. adjustedSearchStartDate = YES; } CFRelease(dayBegin); } } // This is a real mismatch and not due to hour 0 being missing. // NOTE: The behavior of generalized isForwardDST checking depends on the behavior of this loop! // Right now, in the general case, this loop stops iteration _before_ a forward DST transition. If that changes, please take a look at the isForwardDST code for when `beforeTransition = NO` and adjust as necessary. if (hour != dateHour && !adjustedSearchStartDate) { CFDateRef hourBegin = NULL; CFTimeInterval hInv = 0.0; do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &hourBegin, &hInv, result); if (foundRange) { CFIndex prevDateHour = dateHour; CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hInv, hourBegin); dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, tempSearchDate); // Sometimes we can get into a position where the next hour is also equal to hour (as in we hit a backwards DST change). In this case, we could be at the first time this hour occurs. If we want the next time the hour is technically the same (as in we need to go to the second time this hour occurs), we check to see if we hit a backwards DST change. CFDateRef possibleBackwardDSTDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hInv*2, hourBegin); CFIndex secondDateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, possibleBackwardDSTDate); if (((dateHour - prevDateHour) == 2) || (prevDateHour == 23 && dateHour == 1)) { // We've hit a forward DST transition. dateHour -= 1; CFRelease(possibleBackwardDSTDate); CFRelease(tempSearchDate); CFRelease(result); result = hourBegin; } else if ((secondDateHour == dateHour) && findLastMatch) { // If we're not trying to find the last match, just pass on the match we already found. // We've hit a backwards DST transition. CFRelease(tempSearchDate); CFRelease(hourBegin); CFRelease(result); result = possibleBackwardDSTDate; } else { CFRelease(possibleBackwardDSTDate); CFRelease(hourBegin); CFRelease(result); result = tempSearchDate; } adjustedSearchStartDate = true; } } while (hour != dateHour); CFComparisonResult order = CFDateCompare(originalStartDate, result, NULL); if (goBackwards && (order == kCFCompareLessThan)) { // We've gone into the future when we were supposed to go into the past. We're ahead by a day. CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitDay, result); CFRelease(result); result = tempResult; // Check hours again to see if they match (they may not because of DST change already being handled implicitly by dateByAddingUnit:) dateHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, result); if ((dateHour - hour) == 1) { // Detecting a DST transition // We have moved an hour ahead of where we want to be so we go back 1 hour to readjust. CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitHour, result); CFRelease(result); result = tempResult; } else if ((hour - dateHour) == 1) { // <rdar://problem/31051045> NSCalendar enumerateDatesStartingAfterDate: returns nil for the day before a forward DST change when searching backwards // This is a weird special edge case that only gets hit when you're searching backwards and move past a forward (skip an hour) DST transition. // We're not at a DST transition but the hour of our date got moved because the previous day had a DST transition. // So we're an hour before where we want to be. We move an hour ahead to correct and get back to where we need to be. CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, 1, kCFCalendarUnitHour, result); CFRelease(result); result = tempResult; } } } if (findLastMatch) { CFDateRef hourBegin = NULL; CFTimeInterval hInv = 0.0; // This does the same as above for detecting backwards DST changes except that it covers the case where dateHour is already equal to hour. In this case, we could be at the first time we hit an hour (if it falls in a DST transition). Note: the check here tends to be for time zones like Brazil/East where the transition happens at midnight. Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &hourBegin, &hInv, result); if (foundRange) { // Rewind forward/back hour-by-hour until we get to a different hour. A loop here is necessary because not all DST transitions are only an hour long. CFDateRef next = CFRetain(hourBegin); CFIndex nextHour = hour; while (nextHour == hour) { CFRelease(result); result = next; next = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, (goBackwards ? -1 : 1), kCFCalendarUnitHour, next); nextHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, next); } CFRelease(next); CFRelease(hourBegin); adjustedSearchStartDate = YES; } } if (!adjustedSearchStartDate) { // This applies if we didn't hit the above cases to adjust the search start date, i.e. the hour already matches the start hour and either: // 1) We're not looking to match the "last" (repeated) hour in a DST transition (regardless of whether we're in a DST transition), or // 2) We are looking to match that hour, but we're not in that DST transition. // // In either case, we need to clear the lower components in case they are not part of the components we're looking for. CFDateRef hourBegin = NULL; CFTimeInterval hInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &hourBegin, &hInv, result); if (foundRange) { CFRelease(result); result = hourBegin; adjustedSearchStartDate = true; } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingMinute(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); if (minute == CFDateComponentUndefined) return NULL; // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFIndex dateMinute = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMinute, result); CFDateRef minuteBegin = NULL; CFTimeInterval minInv = 0.0; if (minute != dateMinute) { do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMinute, &minuteBegin, &minInv, result); if (foundRange) { CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, minInv, minuteBegin); CFRelease(minuteBegin); dateMinute = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMinute, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (minute != dateMinute); } else { // When the search date matches the minute we're looking for, we need to clear the lower components in case they are not part of the components we're looking for. Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMinute, &minuteBegin, &minInv, result); if (foundRange) { CFRelease(result); result = minuteBegin; } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingSecond(CFCalendarRef calendar, CFDateRef startDate, CFDateRef originalStartDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond); if (second == CFDateComponentUndefined) return NULL; // After this point, result is at least startDate CFDateRef result = CFRetain(startDate); CFIndex dateSecond = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitSecond, result); CFDateRef secondBegin = NULL; CFTimeInterval secInv = 0.0; if (second != dateSecond) { do { Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitSecond, &secondBegin, &secInv, result); if (foundRange) { CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, secInv, secondBegin); CFRelease(secondBegin); dateSecond = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitSecond, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (second != dateSecond); CFComparisonResult order = CFDateCompare(originalStartDate, result, NULL); if (order == kCFCompareLessThan /* originalStartDate < result */) { if (goBackwards) { // We've gone into the future when we were supposed to go into the past. // There are multiple times a day where the seconds repeat. Need to take that into account. CFIndex originalStartSecond = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitSecond, originalStartDate); if (dateSecond > originalStartSecond) { CFDateRef tempResult = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitMinute, result); CFRelease(result); result = tempResult; } } else { // <rdar://problem/31098131> NSCalendar returning nil for nextDateAfterDate when I would expect it to pass -- UserNotifications unit tests are failing // See the corresponding unit test for this^^ radar to see the case in action. This handles the case where dateSecond started ahead of second, so doing the above landed us in the next minute. If minute is not set, we are fine. But if minute is set, then we are now in the wrong minute and we have to readjust. CFIndex searchStartMin = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMinute, result); const CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); if (minute != CFDateComponentUndefined) { if (searchStartMin > minute) { // We've gone ahead of where we needed to be do { // Reset to beginning of minute CFDateRef minBegin = NULL; CFTimeInterval minBeginInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMinute, &minBegin, &minBeginInv, result); if (foundRange) { CFDateRef tempSearchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, minBeginInv*-1, minBegin); CFRelease(minBegin); searchStartMin = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMinute, tempSearchDate); CFRelease(result); result = tempSearchDate; } } while (searchStartMin > minute); } } } } } else { // When the search date matches the second we're looking for, we need to clear the lower components in case they are not part of the components we're looking for. Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitSecond, &secondBegin, &secInv, result); if (foundRange) { CFRelease(result); result = secondBegin; /* Now searchStartDate <= startDate */ } } return result; } static CFDateRef _Nullable _CFCalendarCreateDateAfterDateMatchingNanosecond(CFCalendarRef calendar, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards) { const CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond); if (nanosecond == CFDateComponentUndefined) return NULL; // This taken directly from the old algorithm. We don't have great support for nanoseconds in general and trying to treat them like seconds causes a hang. :-/ // Also see <rdar://problem/30229247> NSCalendar -dateFromComponents: doesn't correctly set nanoseconds CFDateComponentsRef dateComp = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond, startDate); CFDateComponentsSetValue(dateComp, kCFCalendarUnitNanosecond, nanosecond); CFDateRef result = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, dateComp); CFRelease(dateComp); return result; } static CFDateRef _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(CFCalendarRef calendar, Boolean *success, CFDateRef startDate, CFDateComponentsRef comps, Boolean goBackwards, Boolean findLastMatch, CFOptionFlags options) { const Boolean isStrictMatching = (options & kCFCalendarMatchStrictly) == kCFCalendarMatchStrictly; // Default answer for success is yes *success = true; // This is updated as we do our search CFDateRef searchStartDate = CFRetain(startDate); CFDateRef tempDate = NULL; tempDate = _CFCalendarCreateDateAfterDateMatchingEra(calendar, searchStartDate, comps, goBackwards, success); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingYear(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingYearForWeekOfYear(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingQuarter(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingWeekOfYear(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingMonth(calendar, searchStartDate, comps, goBackwards, isStrictMatching); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingWeekOfMonth(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingWeekdayOrdinal(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingWeekday(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingDay(calendar, searchStartDate, startDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingHour(calendar, searchStartDate, startDate, comps, goBackwards, findLastMatch, isStrictMatching, options); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingMinute(calendar, searchStartDate, startDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingSecond(calendar, searchStartDate, startDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } tempDate = _CFCalendarCreateDateAfterDateMatchingNanosecond(calendar, searchStartDate, comps, goBackwards); if (tempDate) { CFRelease(searchStartDate); searchStartDate = tempDate; } *success = true; return searchStartDate; } #pragma mark - static CFCalendarUnit _CFCalendarFindHighestSetUnitInDateComponents(CFDateComponentsRef comps) { CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra); CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear); CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter); CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay); CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour); CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond); CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal); CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth); CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear); CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear); CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond); CFIndex compsValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond}; CFCalendarUnit highestMatchUnit = kCFNotFound; for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) { if (compsValues[i] != CFDateComponentUndefined) { highestMatchUnit = calendarUnits[i]; break; } } return highestMatchUnit; } static CFCalendarUnit _CFCalendarFindLowestSetUnitInDateComponents(CFDateComponentsRef comps) { CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra); CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear); CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter); CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay); CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour); CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond); CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal); CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth); CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear); CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear); CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond); CFIndex compsValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond}; CFCalendarUnit lowestMatchUnit = kCFNotFound; for (CFIndex i = NUM_CALENDAR_UNITS - 1; i >= 0; i--) { if (compsValues[i] != CFDateComponentUndefined) { lowestMatchUnit = calendarUnits[i]; break; } } return lowestMatchUnit; } static Boolean _CFCalendarVerifyCalendarOptions(CFOptionFlags options) { Boolean optionsAreValid = true; CFOptionFlags matchStrictly = options & kCFCalendarMatchStrictly; CFOptionFlags matchPrevious = options & kCFCalendarMatchPreviousTimePreservingSmallerUnits; CFOptionFlags matchNextKeepSmaller = options & kCFCalendarMatchNextTimePreservingSmallerUnits; CFOptionFlags matchNext = options & kCFCalendarMatchNextTime; CFOptionFlags matchFirst = options & kCFCalendarMatchFirst; CFOptionFlags matchLast = options & kCFCalendarMatchLast; if (matchStrictly && (matchPrevious | matchNextKeepSmaller | matchNext)) { // We can't throw here because we've never thrown on this case before, even though it is technically an invalid case. The next best thing is to return. optionsAreValid = false; } if (!matchStrictly) { if ((matchPrevious && matchNext) || (matchPrevious && matchNextKeepSmaller) || (matchNext && matchNextKeepSmaller) || (!matchPrevious && !matchNext && !matchNextKeepSmaller)) { optionsAreValid = false; } } if (matchFirst && matchLast) { optionsAreValid = false; } return optionsAreValid; } static Boolean _CFCalendarVerifyCFDateComponentsValues(CFCalendarRef calendar, CFDateComponentsRef comps) { Boolean dcValuesAreValid = true; CFIndex era = CFDateComponentsGetValue(comps, kCFCalendarUnitEra); CFIndex year = CFDateComponentsGetValue(comps, kCFCalendarUnitYear); CFIndex quarter = CFDateComponentsGetValue(comps, kCFCalendarUnitQuarter); CFIndex month = CFDateComponentsGetValue(comps, kCFCalendarUnitMonth); CFIndex day = CFDateComponentsGetValue(comps, kCFCalendarUnitDay); CFIndex hour = CFDateComponentsGetValue(comps, kCFCalendarUnitHour); CFIndex minute = CFDateComponentsGetValue(comps, kCFCalendarUnitMinute); CFIndex second = CFDateComponentsGetValue(comps, kCFCalendarUnitSecond); CFIndex weekday = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekday); CFIndex weekdayordinal = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekdayOrdinal); CFIndex weekOfMonth = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfMonth); CFIndex weekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitWeekOfYear); CFIndex yearForWeekOfYear = CFDateComponentsGetValue(comps, kCFCalendarUnitYearForWeekOfYear); CFIndex nanosecond = CFDateComponentsGetValue(comps, kCFCalendarUnitNanosecond); CFIndex compsValues[NUM_CALENDAR_UNITS] = {era, year, quarter, month, day, hour, minute, second, weekday, weekdayordinal, weekOfMonth, weekOfYear, yearForWeekOfYear, nanosecond}; // Verify the values fall in the correct range for their corresponding type CFRange max, min; Boolean compHasAtLeastOneFieldSet = false; CFStringRef calID = CFCalendarGetIdentifier(calendar); Boolean calIDIsHebrewIndianOrPersian = CFEqual(calID, kCFCalendarIdentifierHebrew) || CFEqual(calID, kCFCalendarIdentifierIndian) || CFEqual(calID, kCFCalendarIdentifierPersian); for (CFIndex i = 0; i < NUM_CALENDAR_UNITS; i++) { CFIndex currentCompVal = compsValues[i]; if (currentCompVal != CFDateComponentUndefined) { compHasAtLeastOneFieldSet = true; CFCalendarUnit currentUnit = calendarUnits[i]; if (currentUnit == kCFCalendarUnitWeekdayOrdinal) { max.length = 6; max.location = 1; min.length = 4; min.location = 1; } else if ((currentUnit == kCFCalendarUnitYear || currentUnit == kCFCalendarUnitYearForWeekOfYear) && calIDIsHebrewIndianOrPersian) { max = CFCalendarGetMaximumRangeOfUnit(calendar, kCFCalendarUnitYear); min = CFCalendarGetMinimumRangeOfUnit(calendar, kCFCalendarUnitYear); max.location = min.location = 1; } else if (currentUnit == kCFCalendarUnitYearForWeekOfYear) { max = CFCalendarGetMaximumRangeOfUnit(calendar, kCFCalendarUnitYear); min = CFCalendarGetMinimumRangeOfUnit(calendar, kCFCalendarUnitYear); } else { max = CFCalendarGetMaximumRangeOfUnit(calendar, currentUnit); min = CFCalendarGetMinimumRangeOfUnit(calendar, currentUnit); } if (currentCompVal > max.location+max.length-1 || currentCompVal < min.location) { dcValuesAreValid = false; break; } } } if ((false == compHasAtLeastOneFieldSet) && !CFDateComponentsIsLeapMonth(comps)) { dcValuesAreValid = false; } return dcValuesAreValid; } static CFDateRef _CFCalendarCreateMatchingDateAfterStartDateMatchingComponentsInNextHighestUnitRange(CFCalendarRef calendar, Boolean *foundEra, CFDateComponentsRef comps, CFCalendarUnit nextHighestUnit, CFDateRef startDate, Boolean goBackwards, Boolean findLast, CFOptionFlags options) { CFDateRef startOfCurrentRangeForUnit = NULL; CFTimeInterval invOfCurrentRangeForUnit = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, nextHighestUnit, &startOfCurrentRangeForUnit, &invOfCurrentRangeForUnit, startDate); if (foundRange) { CFDateRef nextSearchDate = NULL; if (goBackwards) { if (nextHighestUnit == kCFCalendarUnitDay) { /* If nextHighestUnit is kCFCalendarUnitDay, it's a safe assumption that the highest actual set unit is the hour. There are cases where we're looking for a minute and/or second within the first hour of the day. If we start just at the top of the day and go backwards, we could end up missing the minute/second we're looking for. E.g. We're looking for { hour: 0, minute: 30, second: 0 } in the day before the start date 2017-05-26 07:19:50 UTC. At this point, startOfCurrentRangeForUnit would be 2017-05-26 07:00:00 UTC. In this case, the algorithm would do the following: start at 2017-05-26 07:00:00 UTC, see that the hour is already set to what we want, jump to minute. when checking for minute, it will cycle forward to 2017-05-26 07:30:00 +0000 but then compare to the start and see that that date is incorrect because it's in the future. Then it will cycle the date back to 2017-05-26 06:30:00 +0000. the __findMatchingDate: call below will exit with 2017-05-26 06:30:00 UTC and the algorithm will see that date is incorrect and reset the new search date go back a day to 2017-05-25 07:19:50 UTC. Then we get back here to this method and move the start to 2017-05-25 07:00:00 UTC and the call to __findMatchingDate: below will return 2017-05-25 06:30:00 UTC, which skips what we want (2017-05-25 07:30:00 UTC) and the algorithm eventually keeps moving further and further into the past until it exhausts itself and returns nil. To adjust for this scenario, we add this line below that sets nextSearchDate to the last minute of the previous day (using the above example, 2017-05-26 06:59:59 UTC), which causes the algorithm to not skip the minutes/seconds within the first hour of the previous day. Radar that revealed this bug: // <rdar://problem/32609242> NSCalendar nextDateAfterDate:matchingHour:minute:second:options: unexpectedly returning nil when searching backwards */ nextSearchDate = CFDateCreate(kCFAllocatorSystemDefault, CFDateGetAbsoluteTime(startOfCurrentRangeForUnit) - 1); /* One caveat: if we are looking for a date within the first hour of the day (i.e. between 12 and 1 am), we want to ensure we go forwards in time to hit the exact minute and/or second we're looking for since nextSearchDate is now in the previous day. Associated radar: <rdar://problem/33944890> iOS 11 beta 5 and beta 6: Wrong backward search with -[NSCalendar nextDateAfterDate:matchingHour:minute:second:options:] */ if (0 == CFDateComponentsGetValue(comps, kCFCalendarUnitHour)) { goBackwards = false; } } else { nextSearchDate = CFRetain(startOfCurrentRangeForUnit); } } else { nextSearchDate = CFDateCreate(kCFAllocatorSystemDefault, CFDateGetAbsoluteTime(startOfCurrentRangeForUnit) + invOfCurrentRangeForUnit); } CFRelease(startOfCurrentRangeForUnit); CFDateRef result = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, foundEra, nextSearchDate, comps, goBackwards, findLast, options); CFRelease(nextSearchDate); return result; } *foundEra = true; return NULL; } static CFDateComponentsRef _CFCalendarCreateAdjustedComponents(CFCalendarRef calendar, CFDateComponentsRef comps, CFDateRef date, Boolean goBackwards) { // formerly known as "_CFCalendarEnsureThoroughEnumerationByAdjustingComponents" // This method ensures that the algorithm enumerates through each year or month if they are not explicitly set in the NSDateComponents object passed into enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock:. This only applies to cases where the highest set unit is month or day (at least for now). For full in context explanation, see where it gets called in enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock:. CFCalendarUnit highestSetUnit = _CFCalendarFindHighestSetUnitInDateComponents(comps); switch (highestSetUnit) { case kCFCalendarUnitMonth: { CFDateComponentsRef adjustedComps = CFDateComponentsCreateCopy(kCFAllocatorSystemDefault, comps); CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitYear, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitYear, date)); CFDateRef adjustedDate = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, adjustedComps); if (adjustedDate) { CFComparisonResult order = CFDateCompare(date, adjustedDate, NULL); if (!goBackwards && (order == kCFCompareGreaterThan)) { CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitYear, CFDateComponentsGetValue(adjustedComps, kCFCalendarUnitYear) + 1); } else if (goBackwards && (order == kCFCompareLessThan)) { CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitYear, CFDateComponentsGetValue(adjustedComps, kCFCalendarUnitYear) - 1); } CFRelease(adjustedDate); } return adjustedComps; } case kCFCalendarUnitDay: { CFDateComponentsRef adjustedComps = CFDateComponentsCreateCopy(kCFAllocatorSystemDefault, comps); if (goBackwards) { // We need to make sure we don't surpass the day we want CFIndex dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, date); if (CFDateComponentsGetValue(comps, kCFCalendarUnitDay) >= dateDay) { CFDateRef tempDate = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitMonth, date); CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitMonth, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, tempDate)); CFRelease(tempDate); } else { // adjustedComps here are the date components we're trying to match against; dateDay is the current day of the current search date. // See the comment in enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock: for the justification for adding the month to the components here. // // However, we can't unconditionally add the current month to these components. If the current search date is on month M and day D, and the components we're trying to match have day D' set, the resultant date components to match against are {day=D', month=M}. // This is only correct sometimes: // // * If D' > D (e.g. we're on Nov 05, and trying to find the next 15th of the month), then it's okay to try to match Nov 15. // * However, if D' <= D (e.g. we're on Nov 05, and are trying to find the next 2nd of the month), then it's not okay to try to match Nov 02. // // We can only adjust the month if it won't cause us to search "backwards" in time (causing us to elsewhere end up skipping the first [correct] match we find). // These same changes apply to the goBackwards case above. CFIndex dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, date); CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitMonth, dateDay); } } else { CFIndex dateDay = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitDay, date); if (CFDateComponentsGetValue(comps, kCFCalendarUnitDay) > dateDay) { CFDateComponentsSetValue(adjustedComps, kCFCalendarUnitMonth, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, date)); } } return adjustedComps; } default: return (CFDateComponentsRef)CFRetain(comps); } } static CFDateRef _Nullable _CFCalendarCreateBumpedDateUpToNextHigherUnitInComponents(CFCalendarRef calendar, CFDateRef searchingDate, CFDateComponentsRef comps, Boolean goBackwards, CFDateRef matchDate) { CFCalendarUnit highestSetUnit = _CFCalendarFindHighestSetUnitInDateComponents(comps); CFCalendarUnit nextUnitAboveHighestSet = _CFCalendarNextHigherUnit(highestSetUnit); if (highestSetUnit == kCFCalendarUnitEra) { nextUnitAboveHighestSet = kCFCalendarUnitYear; } else if (highestSetUnit == kCFCalendarUnitYear || highestSetUnit == kCFCalendarUnitYearForWeekOfYear) { nextUnitAboveHighestSet = highestSetUnit; } if (nextUnitAboveHighestSet == kCFNotFound) { // _CFCalendarNextHigherUnit() can return kCFNotFound if bailedUnit was somehow a deprecated unit or something return NULL; } // Advance to the start or end of the next highest unit. Old code here used to add `±1 nextUnitAboveHighestSet` to searchingDate and manually adjust afterwards, but this is incorrect in many cases. // For instance, this is wrong when searching forward looking for a specific Week of Month. Take for example, searching for WoM == 1: // // January 2018 February 2018 // Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa // W1 1 2 3 4 5 6 1 2 3 // W2 7 8 9 10 11 12 13 4 5 6 7 8 9 10 // W3 14 15 16 17 18 19 20 11 12 13 14 15 16 17 // W4 21 22 23 24 25 26 27 18 19 20 21 22 23 24 // W5 28 29 30 31 25 26 27 28 // // Consider searching for `WoM == 1` when searchingDate is *in* W1 of January. Because we're looking to advance to next month, we could simply add a month, right? // Adding a month from Monday, January 1st lands us on Thursday, February 1st; from Thursday, January 2nd we get Friday, February 2nd, etc. Note though that for January 4th, 5th, and 6th, adding a month lands us in **W2** of February! // This means that if we continue searching forward from there, we'll have completely skipped W1 of February as a candidate week, and search forward until we hit W1 of March. This is incorrect. // // What we really want is to skip to the _start_ of February and search from there -- if we undershoot, we can always keep looking. // Searching backwards is similar: we can overshoot if we were subtracting a month, so instead we want to jump back to the very end of the previous month. // In general, this translates to jumping to the very beginning of the next period of the next highest unit when searching forward, or jumping to the very end of the last period when searching backward. CFDateRef result = NULL; CFTimeInterval period = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, nextUnitAboveHighestSet, &result, &period, searchingDate); if (foundRange) { // Skip to the start of the next period (the beginning of this period + its length), or go to the end of the last one (the beginning of this period -1 instant). CFDateRef adjusted = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, (goBackwards ? -1 : period), result); CFRelease(result); result = adjusted; } if (matchDate) { CFComparisonResult ordering = CFDateCompare(matchDate, result, NULL); if (((ordering != kCFCompareLessThan) && !goBackwards) || ((ordering != kCFCompareGreaterThan) && goBackwards)) { // We need to advance searchingDate so that it starts just after matchDate CFCalendarUnit lowestSetUnit = _CFCalendarFindLowestSetUnitInDateComponents(comps); CFRelease(result); result = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, (goBackwards ? -1 : 1), lowestSetUnit, matchDate); } } return result; } static void _CFCalendarPreserveSmallerUnits(CFCalendarRef calendar, CFDateRef date, CFDateComponentsRef compsToMatch, CFDateComponentsRef compsToModify) { CFDateComponentsRef smallerUnits = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond, date); // Either preserve the units we're trying to match if they are explicitly defined or preserve the hour/min/sec in the date. CFDateComponentsSetValue(compsToModify, kCFCalendarUnitHour, CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitHour) != CFDateComponentUndefined ? CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitHour) : CFDateComponentsGetValue(smallerUnits, kCFCalendarUnitHour)); CFDateComponentsSetValue(compsToModify, kCFCalendarUnitMinute, CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMinute) != CFDateComponentUndefined ? CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMinute) : CFDateComponentsGetValue(smallerUnits, kCFCalendarUnitMinute)); CFDateComponentsSetValue(compsToModify, kCFCalendarUnitSecond, CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitSecond) != CFDateComponentUndefined ? CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitSecond) : CFDateComponentsGetValue(smallerUnits, kCFCalendarUnitSecond)); CFRelease(smallerUnits); } #pragma mark - // This function adjusts a mismatched data in the case where it is the chinese calendar and we have detected a leap month mismatch. // It will return NULL in the case where we could not find an appropriate adjustment. In that case, the algorithm should keep iterating. static CFDateRef _Nullable _CFCalendarCreateAdjustedDateForMismatchedChineseLeapMonth(CFCalendarRef calendar, CFDateRef start, CFDateRef searchingDate, CFDateRef matchDate, CFDateComponentsRef matchingComponents, CFDateComponentsRef compsToMatch, CFOptionFlags opts, Boolean *exactMatch, Boolean *isLeapDay) { const Boolean goBackwards = (opts & kCFCalendarSearchBackwards) == kCFCalendarSearchBackwards; const Boolean findLast = (opts & kCFCalendarMatchLast) == kCFCalendarMatchLast; const Boolean strictMatching = (opts & kCFCalendarMatchStrictly) == kCFCalendarMatchStrictly; const Boolean goToNextExistingWithSmallerUnits = (opts & kCFCalendarMatchNextTimePreservingSmallerUnits) == kCFCalendarMatchNextTimePreservingSmallerUnits; const Boolean goToNextExisting = (opts & kCFCalendarMatchNextTime) == kCFCalendarMatchNextTime; // We are now going to look for the month that precedes the leap month we're looking for. CFDateComponentsRef matchDateComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitEra|kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay, matchDate); const Boolean isMatchLeapMonthSet = CFDateComponentsIsLeapMonthSet(matchDateComps); const Boolean isMatchLeapMonth = CFDateComponentsIsLeapMonth(matchDateComps); CFRelease(matchDateComps); const Boolean isDesiredLeapMonthSet = CFDateComponentsIsLeapMonthSet(matchingComponents); const Boolean isDesiredLeapMonth = CFDateComponentsIsLeapMonth(matchingComponents); if (!(isMatchLeapMonthSet && !isMatchLeapMonth && isDesiredLeapMonthSet && isDesiredLeapMonth)) { // Not one of the things we adjust for return CFRetain(matchDate); } // Not an exact match after this point *exactMatch = false; CFDateRef result = CFRetain(matchDate); CFDateComponentsRef compsCopy = CFDateComponentsCreateCopy(kCFAllocatorSystemDefault, compsToMatch); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitLeapMonth, 0); // See if tempMatchDate is already the preceding non-leap month. CFCalendarUnit mismatchedUnits = 0; Boolean dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, result, compsCopy, &mismatchedUnits); if (!dateMatchesComps) { // tempMatchDate was not the preceding non-leap month so now we try to find it. Boolean success; CFDateRef nonLeapStart = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, searchingDate, compsCopy, goBackwards, findLast, opts); dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, nonLeapStart, compsCopy, &mismatchedUnits); if (!dateMatchesComps || !success) { // Bail if we can't even find the preceding month. Returning NULL allows the alg to keep iterating until we either eventually find another match and caller says stop or we hit our max number of iterations and give up. CFRelease(result); CFRelease(nonLeapStart); result = NULL; } else { CFRelease(result); result = nonLeapStart; } } if (!dateMatchesComps || !result) { CFRelease(compsCopy); return result; } // We have the non-leap month so now we check to see if the month following is a leap month. _CFReleaseDeferred CFDateRef nonLeapMonthBegin = NULL; CFTimeInterval nonLeapInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &nonLeapMonthBegin, &nonLeapInv, result); if (!foundRange) { CFRelease(compsCopy); return result; } CFDateComponentsSetValue(compsCopy, kCFCalendarUnitLeapMonth, 1); CFDateRef beginMonthAfterNonLeap = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, nonLeapInv, nonLeapMonthBegin); // Now we see if we find the date we want in what we hope is the leap month. Boolean success; CFDateRef possibleLeapDateMatch = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, beginMonthAfterNonLeap, compsCopy, goBackwards, findLast, opts); dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, possibleLeapDateMatch, compsCopy, &mismatchedUnits); if (dateMatchesComps) { // Hooray! It was a leap month and we found the date we wanted! CFRelease(result); CFRelease(compsCopy); CFRelease(beginMonthAfterNonLeap); return possibleLeapDateMatch; } // Either the month wasn't a leap month OR we couldn't find the date we wanted (e.g. the requested date is a bogus nonexistent one). CFRelease(possibleLeapDateMatch); if (strictMatching) { CFRelease(result); CFRelease(compsCopy); CFRelease(beginMonthAfterNonLeap); return NULL; // We give up, we couldn't find what we needed. } // We approximate. /* Two things we need to test for here. Either (a) beginMonthAfterNonLeap is a leap month but the date we're looking for doesn't exist (e.g. looking for the 30th day in a 29-day month) OR (b) beginMonthAfterNonLeap is not a leap month OR The reason we need to test for each separately is because they get handled differently. For (a): beginMonthAfterNonLeap IS a leap month BUT we can't find the date we want PreviousTime - Last day of this month (beginMonthAfterNonLeap) preserving smaller units NextTimePreserving - First day of following month (month after beginMonthAfterNonLeap) preserving smaller units Nextime - First day of following month (month after beginMonthAfterNonLeap) at the beginning of the day For (b): beginMonthAfterNonLeap is NOT a leap month PreviousTime - The day we want in the previous month (nonLeapMonthBegin) preserving smaller units NextTimePreserving - First day of this month (beginMonthAfterNonLeap) preserving smaller units Nextime - First day of this month (beginMonthAfterNonLeap) */ if (_CFCalendarCheckIfLeapMonthHack(calendar, beginMonthAfterNonLeap)) { // (a) if (goToNextExisting) { // We want the beginning of the next month CFDateRef begOfMonth = NULL; CFTimeInterval monthInv = 0.0; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &begOfMonth, &monthInv, beginMonthAfterNonLeap); if (foundRange) { CFRelease(result); result = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, monthInv, begOfMonth); CFRelease(begOfMonth); } } else { CFDateRef dateToUse = NULL; // Make sure we have the same hour/min/sec as the start date to preserve the smaller units _CFCalendarPreserveSmallerUnits(calendar, start, compsToMatch, compsCopy); if (goToNextExistingWithSmallerUnits) { // Make sure this is set to false CFDateComponentsSetValue(compsCopy, kCFCalendarUnitLeapMonth, 0); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, 1); // We want the first day of the next month so we need to advance the date a bit and make sure we're not on day 1 of the current month. CFDateRef throwAwayDate = NULL; CFTimeInterval dayInv = 0.0; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &throwAwayDate, &dayInv, beginMonthAfterNonLeap); if (foundRange) { CFDateRef nextDay = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, dayInv, throwAwayDate); dateToUse = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, nextDay, compsCopy, false, findLast, opts); CFRelease(nextDay); CFRelease(throwAwayDate); } } else { // MatchPreviousPreservingSmallerUnits CFDateRef begOfMonth = NULL; CFTimeInterval monthInv = 0.0; foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &begOfMonth, &monthInv, beginMonthAfterNonLeap); if (foundRange) { CFDateRef lastDayEnd = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, monthInv-1, begOfMonth); CFDateComponentsRef monthDayComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitMonth|kCFCalendarUnitDay, lastDayEnd); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitMonth, CFDateComponentsGetValue(monthDayComps, kCFCalendarUnitMonth)); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, CFDateComponentsGetValue(monthDayComps, kCFCalendarUnitDay)); CFRelease(monthDayComps); // Make sure this is set to true CFDateComponentsSetValue(compsCopy, kCFCalendarUnitLeapMonth, 1); dateToUse = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, lastDayEnd, compsCopy, true, findLast, opts); CFRelease(lastDayEnd); CFRelease(begOfMonth); } } if (dateToUse) { // We have to give a date since we can't return NULL so whatever we get back, we go with. Hopefully it's what we want. // tempMatchDate was already set to matchDate so it shouldn't be NULL here anyway. CFRelease(result); result = dateToUse; } } } else { // (b) if (goToNextExisting) { // We need first day of this month and we don't care about preserving the smaller units. CFRelease(result); result = CFRetain(beginMonthAfterNonLeap); } else { // Make sure this is set to false CFDateComponentsSetValue(compsCopy, kCFCalendarUnitLeapMonth, 0); // Make sure we have the same hour/min/sec as the start date to preserve the smaller units _CFCalendarPreserveSmallerUnits(calendar, start, compsToMatch, compsCopy); CFDateRef dateToUse = NULL; if (goToNextExistingWithSmallerUnits) { // We need first day of this month but we need to preserve the smaller units. CFDateComponentsSetValue(compsCopy, kCFCalendarUnitMonth, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, beginMonthAfterNonLeap)); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, 1); dateToUse = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, beginMonthAfterNonLeap, compsCopy, false, findLast, opts); } else { // MatchPreviousPreservingSmallerUnits // compsCopy is already set to what we're looking for, which is the date we want in the previous non-leap month. This also preserves the smaller units. dateToUse = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, nonLeapMonthBegin, compsCopy, false, findLast, opts); } if (dateToUse) { // We have to give a date since we can't return NULL so whatever we get back, we go with. Hopefully it's what we want. // tempMatchDate was already set to matchDate so it shouldn't be NULL here anyway. CFRelease(result); result = dateToUse; } } } // Even though we have an approximate date here, we still count it as a substitute for the leap date we were hoping to find. *isLeapDay = true; CFRelease(beginMonthAfterNonLeap); CFRelease(compsCopy); return result; } // For calendars other than Chinese static CFDateRef _Nullable _CFCalendarCreateAdjustedDateForMismatchedLeapMonthOrDay(CFCalendarRef calendar, CFDateRef start, CFDateRef searchingDate, CFDateRef matchDate, CFDateComponentsRef matchingComponents, CFDateComponentsRef compsToMatch, CFCalendarUnit nextHighestUnit, CFOptionFlags opts, Boolean *exactMatch, Boolean *isLeapDay) { const CFDateComponentsRef searchDateComps = CFCalendarCreateDateComponentsFromDate(kCFAllocatorSystemDefault, calendar, kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay, searchingDate); const CFIndex searchDateDay = CFDateComponentsGetValue(searchDateComps, kCFCalendarUnitDay); const CFIndex searchDateMonth = CFDateComponentsGetValue(searchDateComps, kCFCalendarUnitMonth); const CFIndex searchDateYear = CFDateComponentsGetValue(searchDateComps, kCFCalendarUnitYear); CFRelease(searchDateComps); const CFIndex desiredMonth = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMonth); const CFIndex desiredDay = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitDay); // if comps aren't equal, it means we jumped to a day that doesn't exist in that year (non-leap year) i.e. we've detected a leap year situation Boolean detectedLeapYearSituation = (((desiredDay != CFDateComponentUndefined) && (searchDateDay != desiredDay)) || ((desiredMonth != CFDateComponentUndefined) && (searchDateMonth != desiredMonth))); if (!detectedLeapYearSituation) { // Nothing to do here return NULL; } const Boolean goBackwards = (opts & kCFCalendarSearchBackwards) == kCFCalendarSearchBackwards; const Boolean findLast = (opts & kCFCalendarMatchLast) == kCFCalendarMatchLast; const Boolean strictMatching = (opts & kCFCalendarMatchStrictly) == kCFCalendarMatchStrictly; // NSCalendarMatchPreviousTimePreservingSmallerUnits is implied if neither of these two below nor NSCalendarMatchStrictly are set. const Boolean goToNextExistingWithSmallerUnits = (opts & kCFCalendarMatchNextTimePreservingSmallerUnits) == kCFCalendarMatchNextTimePreservingSmallerUnits; const Boolean goToNextExisting = (opts & kCFCalendarMatchNextTime) == kCFCalendarMatchNextTime; Boolean foundGregLeap = false, foundGregLeapMatchesComps = false; const Boolean isGregorianCalendar = CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierGregorian); CFDateRef result = CFRetain(matchDate); if (isGregorianCalendar) { // We've identified a leap year in the Gregorian calendar OR we've identified a day that doesn't exist in a different month // We check the original matchingComponents to check the caller's *intent*. If they're looking for February, then they are indeed looking for a leap year. If they didn't ask for February explicitly and we added it to compsToMatch ourselves, then don't force us to the next leap year. if (desiredMonth == 2 && CFDateComponentsGetValue(matchingComponents, kCFCalendarUnitMonth) == 2) { // Check for Gregorian leap year CFIndex amountToAdd = 0; if (goBackwards) { amountToAdd = (searchDateYear % 4) * -1; // It's possible that we're in a leap year but before 2/29. Since we're going backwards, we need to go to the previous leap year. if ((amountToAdd == 0) && (searchDateMonth >= desiredMonth)) { amountToAdd = -4; } } else { amountToAdd = 4 - (searchDateYear % 4); } CFDateRef searchDateInLeapYear = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, amountToAdd, kCFCalendarUnitYear, searchingDate); CFDateRef startOfLeapYear = NULL; CFTimeInterval startOFLeapYearInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitYear, &startOfLeapYear, &startOFLeapYearInv, searchDateInLeapYear); if (foundRange) { CFRelease(result); result = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &foundGregLeap, startOfLeapYear, compsToMatch, false, findLast, opts); CFRelease(startOfLeapYear); foundGregLeapMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, result, compsToMatch, NULL); } CFRelease(searchDateInLeapYear); } } if (!foundGregLeap || !foundGregLeapMatchesComps) { if (strictMatching) { if (isGregorianCalendar) { *exactMatch = false; // We couldn't find what we needed but we found sumthin. Step C will decide whether or not to NULL the date out. } else { // For other calendars (besides Chinese which is already being handled), go to the top of the next period for the next highest unit of the one that bailed. Boolean eraMatch = false; CFDateRef tempDate = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponentsInNextHighestUnitRange(calendar, &eraMatch, matchingComponents, nextHighestUnit, searchingDate, goBackwards, findLast, opts); if (!eraMatch) { *exactMatch = false; // We couldn't find what we needed but we found sumthin. Step C will decide whether or not to NULL the date out. CFRelease(tempDate); } else { CFRelease(result); result = tempDate; } } } else { // Figure out best approximation to give. The "correct" approximations for these cases depend on the calendar. // Note that this also works for the Hebrew calendar - since the preceding month is not numbered the same as the leap month (like in the Chinese calendar) we can treat the non-existent day in the same way that we handle Feb 29 in the Gregorian calendar. CFDateComponentsRef compsCopy = CFDateComponentsCreateCopy(kCFAllocatorSystemDefault, compsToMatch); CFDateComponentsRef tempComps = CFDateComponentsCreate(kCFAllocatorSystemDefault); CFDateComponentsSetValue(tempComps, kCFCalendarUnitYear, searchDateYear); CFDateComponentsSetValue(tempComps, kCFCalendarUnitMonth, desiredMonth); CFDateComponentsSetValue(tempComps, kCFCalendarUnitDay, 1); CFDateRef tempDate = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, tempComps); if (goToNextExisting) { // Go to the start of the next day after the desired month and day CFIndex compsToMatchYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYear); if (compsToMatchYear != CFDateComponentUndefined) { // If we explicitly set the year to match by calling __ensureThoroughEnumerationByAdjustingComponents:, we should use that year instead and not searchDateYear. CFDateComponentsSetValue(compsCopy, kCFCalendarUnitYear, compsToMatchYear > searchDateYear ? compsToMatchYear : searchDateYear); } else { CFDateComponentsSetValue(compsCopy, kCFCalendarUnitYear, searchDateYear); } CFDateRef followingMonthDate = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, 1, kCFCalendarUnitMonth, tempDate); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitMonth, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, followingMonthDate)); CFRelease(followingMonthDate); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, 1); Boolean success; CFRelease(result); result = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, start, compsCopy, goBackwards, findLast, opts); Boolean dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, result, compsCopy, NULL); if (success && dateMatchesComps) { // Need to go to the start of the day. CFDateRef startOfDay = NULL; CFTimeInterval startOfDayInv = 0.0; Boolean foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitDay, &startOfDay, &startOfDayInv, result); if (foundRange) { CFRelease(result); result = startOfDay; } else { CFRelease(startOfDay); } } else { CFRelease(result); result = NULL; } } else { // Make sure we have the same hour/min/sec as the start date to preserve the smaller units _CFCalendarPreserveSmallerUnits(calendar, start, compsToMatch, compsCopy); if (goToNextExistingWithSmallerUnits) { CFIndex compsToMatchYear = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitYear); if (compsToMatchYear != CFDateComponentUndefined) { // If we explicitly set the year to match by calling __ensureThoroughEnumerationByAdjustingComponents:, we should use that year instead and not searchDateYear. CFDateComponentsSetValue(compsCopy, kCFCalendarUnitYear, compsToMatchYear > searchDateYear ? compsToMatchYear : searchDateYear); } else { CFDateComponentsSetValue(compsCopy, kCFCalendarUnitYear, searchDateYear); } CFDateComponentsSetValue(tempComps, kCFCalendarUnitYear, CFDateComponentsGetValue(compsCopy, kCFCalendarUnitYear)); CFRelease(tempDate); tempDate = CFCalendarCreateDateFromComponents(kCFAllocatorSystemDefault, calendar, tempComps); CFDateRef followingMonthDate = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, 1, kCFCalendarUnitMonth, tempDate); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitMonth, CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, followingMonthDate)); CFRelease(followingMonthDate); CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, 1); // We want the beginning of the next month. } else { // MatchPreviousPreservingSmallerUnits CFRange foundRange = CFCalendarGetRangeOfUnit(calendar, kCFCalendarUnitDay, kCFCalendarUnitMonth, CFDateGetAbsoluteTime(tempDate)); CFIndex lastDayOfTheMonth = foundRange.length; if (desiredDay >= lastDayOfTheMonth) { CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, lastDayOfTheMonth); } else { // Go to the prior day before the desired month CFDateComponentsSetValue(compsCopy, kCFCalendarUnitDay, desiredDay - 1); } } Boolean success; CFRelease(result); result = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, searchingDate, compsCopy, goBackwards, findLast, opts); Boolean dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, result, compsCopy, NULL); if (!success || !dateMatchesComps) { // Bail if we couldn't even find an approximate match. CFRelease(result); result = NULL; } } CFRelease(tempComps); CFRelease(compsCopy); CFRelease(tempDate); *exactMatch = false; *isLeapDay = true; } } return result; } // This function checks the input (assuming we've detected a mismatch hour), for a DST transition. If we find one, then it returns a new date. Otherwise it returns NULL. static CFDateRef _Nullable _CFCalendarCreateAdjustedDateForMismatchedHour(CFCalendarRef calendar, CFDateRef matchDate /* the currently proposed match */, CFDateComponentsRef compsToMatch, CFOptionFlags opts, Boolean *exactMatch) { // It's possible this is a DST time. Let's check. CFDateRef startOfHour = NULL; CFTimeInterval hourInv = 0.0; Boolean found = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitHour, &startOfHour, &hourInv, matchDate); if (!found) { // Not DST return NULL; } // matchDate may not match because of a forward DST transition (e.g. spring forward, hour is lost). // matchDate may be before or after this lost hour, so look in both directions. CFIndex currentHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, startOfHour); Boolean isForwardDST = false; Boolean beforeTransition = true; CFDateRef next = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hourInv, startOfHour); CFIndex nextHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, next); if ((nextHour - currentHour) > 1 || (currentHour == 23 && nextHour > 0)) { // We're just before a forward DST transition, e.g., for America/Sao_Paulo: // // 2018-11-03 2018-11-04 // ┌─────11:00 PM (GMT-3)─────┐ │ ┌ ─ ─ 12:00 AM (GMT-3)─ ─ ─┐ ┌─────1:00 AM (GMT-2) ─────┐ // │ │ │ | │ │ │ // └──────▲───────────────────┘ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ └──────────────────────────┘ // └── Here Nonexistent // isForwardDST = true; } else { // We might be just after such a transition. CFDateRef previous = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, -1, startOfHour); CFIndex previousHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, previous); if ((currentHour - previousHour) > 1 || (previousHour == 23 && currentHour > 0)) { // We're just after a forward DST transition, e.g., for America/Sao_Paulo: // // 2018-11-03 2018-11-04 // ┌─────11:00 PM (GMT-3)─────┐ │ ┌ ─ ─ 12:00 AM (GMT-3)─ ─ ─┐ ┌─────1:00 AM (GMT-2) ─────┐ // │ │ │ | │ │ │ // └──────────────────────────┘ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ └──▲───────────────────────┘ // Nonexistent └── Here // isForwardDST = YES; beforeTransition = NO; } CFRelease(previous); } CFDateRef result = NULL; if (isForwardDST && !(opts & kCFCalendarMatchStrictly) /* we can only adjust when matches need not be strict */) { // We can adjust the time as necessary to make this match close enough. // Since we aren't trying to strictly match and are now going to make a best guess approximation, we set exactMatch to NO. *exactMatch = false; if (beforeTransition) { if (opts & kCFCalendarMatchNextTimePreservingSmallerUnits) { // Adding an hour this way gives us the right candidate while preserving the minute and second (as opposed to `next` which has those wiped out) result = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, 1, kCFCalendarUnitHour, matchDate); } else if (opts & kCFCalendarMatchNextTime) { // `next` is the start of the next hour past `matchDate` (i.e. round `matchDate` up to the next hour) result = CFRetain(next); } else { // No need to check `NSCalendarMatchPreviousTimePreservingSmallerUnits` or `NSCalendarMatchStrictly`: // * If we're matching the previous time, `matchDate` is already correct because we're pre-transition // * If we're matching strictly, we shouldn't be here (should be guarded by the if-statement condition): we can't adjust a strict match result = CFRetain(matchDate); } } else { if (opts & kCFCalendarMatchNextTime) { // `startOfHour` is the start of the hour containing `matchDate` (i.e. take `matchDate` but wipe the minute and second) result = CFRetain(startOfHour); } else if (opts & kCFCalendarMatchPreviousTimePreservingSmallerUnits) { // We've arrived here after a mismatch due to a forward DST transition, and specifically, one which produced a candidate matchDate which was _after_ the transition. // At the time of writing this (2018-07-11), the only way to hit this case is under the following circumstances: // // * DST transition in a time zone which transitions at `hour = 0` (i.e. 11:59:59 -> 01:00:00) // * Components request `hour = 0` // * Components contain a date component higher than hour which advanced us to the start of the day from a prior day // // If the DST transition is not at midnight, the components request any other hour, or there is no higher date component, we will have fallen into the usual hour-rolling loop. // That loop right now takes care to stop looping _before_ the transition. // // This means that right now, if we attempt to match the previous time while preserving smaller components (i.e. rewinding by an hour), we will no longer match the higher date component which had been requested. // For instance, if searching for `weekday = 1` (Sunday) got us here, rewinding by an hour brings us back to Saturday. Similarly, if asking for `month = x` got us here, rewinding by an hour would bring us to `month = x - 1`. // These mismatches are not proper candidates and should not be accepted. // // However, if the conditions of the hour-rolling loop ever change, I am including the code which would be correct to use here: attempt to roll back by an hour, and check whether we've introduced a new mismatch. // Right now, candidateMatches is always false, so the check is redundant. // We don't actually have a match. Claim it's not DST too, to avoid accepting matchDate as-is anyway further on (which is what isForwardDST = YES allows for). result = NULL; // NOTE: The following is intentionally if-def'd out. Please see the comment above for rationale. #if 0 // Subtract an hour to keep smaller units the same. // The issue here is that this may cause a different component mismatch (e.g. rewinding across a day where the DST transition is at midnight). CFDateRef candidate = _CFCalendarCreateDateByAddingValueOfUnitToDate(calendar, -1, kCFCalendarUnitHour, matchDate); // We know the hour mismatched, and that's fine. Check all other components though. CFDateComponentsRef candidateComponents = CFDateComponentsCreateCopy(kCFAllocatorSystemDefault, compsToMatch); CFDateComponentsSetValue(candidateComponents, kCFCalendarUnitHour, CFDateComponentUndefined); Boolean candidateMatches = _CFCalendarCheckDateContainsMatchingComponents(calendar, candidate, candidateComponents, NULL); if (candidateMatches) { *exactMatch = true; result = candidate; } else { // The new candidate is no better (e.g. we introduced a different mismatch elsewhere). // We'll have to skip ahead. CFRelease(candidate); } CFRelease(candidateComponents); #endif } else { // No need to check `NSCalendarMatchNextTimePreservingSmallerUnits` or `NSCalendarMatchStrictly`: // * If we're matching the next time, `matchDate` is already correct because we're post-transition // * If we're matching strictly, we shouldn't be here (should be guarded by the if-statement condition): we can't adjust a strict match result = CFRetain(matchDate); } } } CFRelease(next); CFRelease(startOfHour); return result; } static CFDateRef _Nullable _CFCalendarCreateAdjustedDateForMismatches(CFCalendarRef calendar, CFDateRef start /* the original search date */, CFDateRef searchingDate /* the date that is adjusted as we loop */, CFDateRef matchDate /* the currently proposed match */, Boolean success /* output of the match function */, CFDateComponentsRef matchingComponents /* aka searchingComponents */, CFDateComponentsRef compsToMatch, CFOptionFlags opts, Boolean *isForwardDST, Boolean *exactMatch, Boolean *isLeapDay) { // Set up some default answers for the out args *isForwardDST = false; *exactMatch = true; *isLeapDay = false; // use this to find the units that don't match and then those units become the bailedUnit CFCalendarUnit mismatchedUnits = 0; Boolean dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, matchDate, compsToMatch, &mismatchedUnits); // Skip trying to correct nanoseconds or quarters. See <rdar://problem/30229247> NSCalendar -dateFromComponents: doesn't correctly set nanoseconds and <rdar://problem/30229506> NSCalendar -component:fromDate: always returns 0 for NSCalendarUnitQuarter Boolean nanoSecondsMismatch = ((mismatchedUnits & kCFCalendarUnitNanosecond) == kCFCalendarUnitNanosecond); Boolean quarterMismatch = ((mismatchedUnits & kCFCalendarUnitQuarter) == kCFCalendarUnitQuarter); if (!(!nanoSecondsMismatch && !quarterMismatch)) { // Everything else is fine. Just return this date. return CFRetain(matchDate); } if (mismatchedUnits == kCFCalendarUnitHour) { CFDateRef resultAdjustedForDST = _CFCalendarCreateAdjustedDateForMismatchedHour(calendar, matchDate, compsToMatch, opts, exactMatch); if (resultAdjustedForDST) { *isForwardDST = true; // Skip the next set of adjustments too return resultAdjustedForDST; } } if (success && dateMatchesComps) { // Everything is already fine. Just return the value. return CFRetain(matchDate); } const Boolean goBackwards = (opts & kCFCalendarSearchBackwards) == kCFCalendarSearchBackwards; const Boolean findLast = (opts & kCFCalendarMatchLast) == kCFCalendarMatchLast; const Boolean isChineseCalendar = CFEqual(CFCalendarGetIdentifier(calendar), kCFCalendarIdentifierChinese); CFCalendarUnit bailedUnit = 0; // We want to get the highest mismatched unit for (CFIndex i = NUM_CALENDAR_UNITS - 1; i > -1; i--) { CFCalendarUnit highestSoFar = mismatchedUnits & calendarUnits[i]; if (highestSoFar == calendarUnits[i]) { bailedUnit = highestSoFar; } } const Boolean leapMonthMismatch = ((mismatchedUnits & kCFCalendarUnitLeapMonth) == kCFCalendarUnitLeapMonth); CFCalendarUnit nextHighestUnit =_CFCalendarNextHigherUnit(bailedUnit); if (nextHighestUnit == kCFNotFound && !leapMonthMismatch) { // _CFCalendarNextHigherUnit() can return kCFNotFound if bailedUnit was somehow a deprecated unit or something // Just return the original date in this case return CFRetain(matchDate); } // corrective measures if (bailedUnit == kCFCalendarUnitEra) { nextHighestUnit = kCFCalendarUnitYear; } else if (bailedUnit == kCFCalendarUnitYear || bailedUnit == kCFCalendarUnitYearForWeekOfYear) { nextHighestUnit = bailedUnit; } // We need to check for leap* situations Boolean const isGregorianCalendar = CFEqual(CFCalendarGetIdentifier(calendar), kCFGregorianCalendar); if (nextHighestUnit == kCFCalendarUnitYear || leapMonthMismatch) { const CFIndex desiredMonth = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitMonth); const CFIndex desiredDay = CFDateComponentsGetValue(compsToMatch, kCFCalendarUnitDay); if (!((desiredMonth != CFDateComponentUndefined) && (desiredDay != CFDateComponentUndefined))) { // Just return the original date in this case return CFRetain(matchDate); } if (isChineseCalendar) { if (leapMonthMismatch) { return _CFCalendarCreateAdjustedDateForMismatchedChineseLeapMonth(calendar, start, searchingDate, matchDate, matchingComponents, compsToMatch, opts, exactMatch, isLeapDay); } else { // Just return the original date in this case return CFRetain(matchDate); } } // Here is where we handle the other leap* situations (e.g. leap years in Gregorian calendar, leap months in Hebrew calendar) const Boolean monthMismatched = (mismatchedUnits & kCFCalendarUnitMonth) == kCFCalendarUnitMonth; const Boolean dayMismatched = (mismatchedUnits & kCFCalendarUnitDay) == kCFCalendarUnitDay; if (monthMismatched || dayMismatched) { CFDateRef result = _CFCalendarCreateAdjustedDateForMismatchedLeapMonthOrDay(calendar, start, searchingDate, matchDate, matchingComponents, compsToMatch, nextHighestUnit, opts, exactMatch, isLeapDay); // result may be NULL, which indicates a need to keep iterating return result; } // Last opportunity here is just to return the original match date return CFRetain(matchDate); } else if (nextHighestUnit == kCFCalendarUnitMonth && isGregorianCalendar && CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitMonth, matchDate) == 2) { // We've landed here because we couldn't find the date we wanted in February, because it doesn't exist (e.g. Feb 31st or 30th, or 29th on a non-leap-year). // matchDate is the end of February, so we need to advance to the beginning of March. CFDateRef startOfFebruary = NULL; CFTimeInterval monthInv = 0.0; Boolean const foundRange = _CFCalendarGetTimeRangeOfUnitForDate(calendar, kCFCalendarUnitMonth, &startOfFebruary, &monthInv, matchDate); if (foundRange) { CFDateRef adjustedDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorDefault, monthInv, startOfFebruary); if (opts & kCFCalendarMatchNextTimePreservingSmallerUnits) { // Advancing has caused us to lose all smaller units, so if we're looking to preserve them we need to add them back. CFDateComponentsRef const smallerUnits = CFCalendarCreateDateComponentsFromDate(kCFAllocatorDefault, calendar, kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond, start); CFDateRef const tempSearchDate = adjustedDate; adjustedDate = _CFCalendarCreateDateByAddingDateComponentsToDate(kCFAllocatorDefault, calendar, smallerUnits, tempSearchDate, opts); CFRelease(tempSearchDate); CFRelease(smallerUnits); } // This isn't strictly a leap day, just a day that doesn't exist. *isLeapDay = true; *exactMatch = false; CFRelease(startOfFebruary); return adjustedDate; } return CFRetain(matchDate); } else { // Go to the top of the next period for the next highest unit of the one that bailed. Boolean s = false; CFDateRef result = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponentsInNextHighestUnitRange(calendar, &s, matchingComponents, nextHighestUnit, searchingDate, goBackwards, findLast, opts); if (!s) { *exactMatch = false; } return result; } } #pragma mark - #pragma mark Enumerate Entry Point CF_CROSS_PLATFORM_EXPORT void _CFCalendarEnumerateDates(CFCalendarRef calendar, CFDateRef start, CFDateComponentsRef matchingComponents, CFOptionFlags opts, void (^block)(CFDateRef _Nullable, Boolean, Boolean*)) { if (!start || !_CFCalendarVerifyCalendarOptions(opts) || !_CFCalendarVerifyCFDateComponentsValues(calendar, matchingComponents)) { return; } // Set up all of the options we need const Boolean goBackwards = (opts & kCFCalendarSearchBackwards) == kCFCalendarSearchBackwards; const Boolean findLast = (opts & kCFCalendarMatchLast) == kCFCalendarMatchLast; const Boolean strictMatching = (opts & kCFCalendarMatchStrictly) == kCFCalendarMatchStrictly; CFDateRef searchingDate = CFRetain(start); Boolean stop = false; // We keep track of the previous match date passed to the given block to ensure that we return exclusively increasing or decreasing results. // This should only be updated with non-nil values actually passed to the block. CFDateRef previouslyReturnedMatchDate = NULL; /* An important note: There are 2 distinct ways in which the enumeration is controlled. 1) The caller sets *stop in the block to let us know when to stop. 2) We keep trying for a certain number of iterations and give up if we don't find an answer within that span. Without either of these methods (esp #2), we potentially run into the halting problem. */ CFIndex iterations = -1; #define STOP_EXHAUSTIVE_SEARCH_AFTER_MAX_ITERATIONS 100 /* This is the loop that controls the iterating. */ while (stop == false) { iterations++; Boolean passToBlock = false; Boolean exactMatch = true; _CFReleaseDeferred CFDateRef resultDate = NULL; Boolean isLeapDay = false; // NOTE: Several comments reference "isForwardDST" as a way to relate areas in forward DST handling. // If you rename this variable, make sure to find all references in comments as well and update accordingly. Boolean isForwardDST = false; /* Step A: Call helper method that does the searching */ /* Note: The reasoning behind this is a bit difficult to immediately grok because it's not obvious but what it does is ensure that the algorithm enumerates through each year or month if they are not explicitly set in the NSDateComponents object passed in by the caller. This only applies to cases where the highest set unit is month or day (at least for now). For ex, let's say comps is set the following way: { Day: 31 } We want to enumerate through all of the months that have a 31st day. If NSCalendarMatchStrictly is set, the algorithm automagically skips over the months that don't have a 31st day and we pass the desired results to the block. However, if any of the approximation options are set, we can't skip the months that don't have a 31st day - we need to provide the appropriate approximate date for them. Calling this method allows us to see that day is the highest unit set in comps, and sets the month value in compsToMatch (previously unset in comps) to whatever the month is of the date we're using to search. Ex: searchingDate is '2016-06-10 07:00:00 +0000' so { Day: 31 } becomes { Month: 6, Day: 31 } in compsToMatch This way, the algorithm from here on out sees that month is now the highest set unit and we ensure that we search for the day we want in each month and provide an approximation when we can't find it, thus getting the results the caller expects. Ex: { Month: 6, Day: 31 } does not exist so if NSCalendarMatchNextTime is set, we pass '2016-07-01 07:00:00 +0000' to the block. */ _CFReleaseDeferred CFDateComponentsRef compsToMatch = _CFCalendarCreateAdjustedComponents(calendar, matchingComponents, searchingDate, goBackwards); Boolean success = true; _CFReleaseDeferred CFDateRef matchDate = _CFCalendarCreateMatchingDateAfterStartDateMatchingComponents(calendar, &success, searchingDate, compsToMatch, goBackwards, findLast, opts); /* Step B: Couldn't find matching date with a quick and dirty search in the current era, year, etc. Now try in the near future/past and make adjustments for leap situations and non-existent dates */ _CFReleaseDeferred CFDateRef tempDate = _CFCalendarCreateAdjustedDateForMismatches(calendar, start, searchingDate, matchDate, success, matchingComponents, compsToMatch, opts, &isForwardDST, &exactMatch, &isLeapDay); // tempDate may be NULL, which indicates a need to keep iterating /* Step C: Validate what we found and then run block. Then prepare the search date for the next round of the loop */ if (tempDate) { CFRelease(matchDate); matchDate = CFRetain(tempDate); // Check the components to see if they match what was desired CFCalendarUnit mismatchedUnits = 0; Boolean dateMatchesComps = _CFCalendarCheckDateContainsMatchingComponents(calendar, matchDate, matchingComponents, &mismatchedUnits); Boolean nanoSecondsMismatch = ((mismatchedUnits & kCFCalendarUnitNanosecond) == kCFCalendarUnitNanosecond); Boolean quarterMismatch = ((mismatchedUnits & kCFCalendarUnitQuarter) == kCFCalendarUnitQuarter); // Since we adjusted the matching components at the start of this loop, we'll check to see if what we found matches the components that were originally passed in. if (dateMatchesComps && !exactMatch) { exactMatch = true; } // Bump up the next highest unit CFDateRef newSearchingDate = _CFCalendarCreateBumpedDateUpToNextHigherUnitInComponents(calendar, searchingDate, matchingComponents, goBackwards, matchDate); if (newSearchingDate) { CFRelease(searchingDate); searchingDate = newSearchingDate; } // Nanosecond and quarter mismatches are not considered inexact. Boolean notAnExactMatch = (!dateMatchesComps && !nanoSecondsMismatch && !quarterMismatch); if (notAnExactMatch) { exactMatch = false; } CFComparisonResult order = previouslyReturnedMatchDate ? CFDateCompare(previouslyReturnedMatchDate, matchDate, NULL) : CFDateCompare(start, matchDate, NULL); if (((goBackwards && (order == kCFCompareLessThan)) || (!goBackwards && (order == kCFCompareGreaterThan))) && !nanoSecondsMismatch) { // We've gone ahead when we should have gone backwards or we went in the past when we were supposed to move forwards. // Normally, it's sufficient to set matchDate to nil and move on with the existing searching date. However, the searching date has been bumped forward by the next highest date component, which isn't always correct. // Specifically, if we're in a type of transition when the highest date component can repeat between now and the next highest date component, then we need to move forward by less. // // This can happen during a "fall back" DST transition in which an hour is repeated: // // ┌─────1:00 PDT─────┐ ┌─────1:00 PST─────┐ // │ │ │ │ // └───────────▲───▲──┘ └───────────▲──────┘ // │ │ │ // | | valid // │ last match/start // │ // matchDate // // Instead of jumping ahead by a whole day, we can jump ahead by an hour to the next appropriate match. `valid` here would be the result found by searching with NSCalendarMatchLast. // In this case, before giving up on the current match date, we need to adjust newSearchingDate with this information. // // Currently, the case we care most about is adjusting for DST, but we might need to expand this to handle repeated months in some calendars. if (_CFCalendarFindHighestSetUnitInDateComponents(compsToMatch) == kCFCalendarUnitHour) { CFIndex const matchHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, matchDate); CFTimeInterval const hourAdjustment = (goBackwards ? -1 : 1) * 60 * 60; CFDateRef const potentialNextMatchDate = _CFDateCreateWithTimeIntervalSinceDate(kCFAllocatorSystemDefault, hourAdjustment, matchDate); CFIndex const potentialMatchHour = CFCalendarGetComponentFromDate(calendar, kCFCalendarUnitHour, potentialNextMatchDate); if (matchHour == potentialMatchHour) { // We're in a DST transition where the hour repeats. Use this date as the next search date. CFRelease(searchingDate); searchingDate = potentialNextMatchDate; } else { CFRelease(potentialNextMatchDate); } } // In any case, return nil. // <rdar://problem/30681375> NSCalendar enumerateDatesAfterStartDate: should return nil or start date if search criteria is inconsistent? // TODO - Determine if we want to return the starting boundary if the approximation options are set. CFRelease(matchDate); matchDate = NULL; // Returning NULL is fine if we've exhausted our search. if (iterations < STOP_EXHAUSTIVE_SEARCH_AFTER_MAX_ITERATIONS) { continue; } else { passToBlock = true; } } // At this point, the date we matched is allowable unless: // 1) It's not an exact match AND // 2) We require an exact match (strict) OR // 3) It's not an exact match but not because we found a DST hour or day that doesn't exist in the month (i.e. it's truly the wrong result) Boolean const allowInexactMatchingDueToTimeSkips = isForwardDST || isLeapDay; if (matchDate && !exactMatch && (strictMatching || !allowInexactMatchingDueToTimeSkips)) { CFRelease(matchDate); matchDate = NULL; } if (order != kCFCompareEqualTo || !matchDate) { // If we get a result that is exactly the same as the start date, skip. if (matchDate) { resultDate = CFRetain(matchDate); passToBlock = true; } else { if (iterations < STOP_EXHAUSTIVE_SEARCH_AFTER_MAX_ITERATIONS) { continue; } else { passToBlock = true; } } } else { // Returning NULL is fine if we've exhausted our search. if (iterations < STOP_EXHAUSTIVE_SEARCH_AFTER_MAX_ITERATIONS) { continue; } else { passToBlock = true; } } } else { // Bump up the next highest unit CFDateRef newSearchingDate = _CFCalendarCreateBumpedDateUpToNextHigherUnitInComponents(calendar, searchingDate, matchingComponents, goBackwards, NULL); if (newSearchingDate) { CFRelease(searchingDate); searchingDate = newSearchingDate; } // Returning NULL is fine if we've exhausted our search. if (iterations < STOP_EXHAUSTIVE_SEARCH_AFTER_MAX_ITERATIONS) { continue; } else { passToBlock = true; } } if (passToBlock) { // Execute the block if (resultDate) { if (previouslyReturnedMatchDate) CFRelease(previouslyReturnedMatchDate); previouslyReturnedMatchDate = CFRetain(resultDate); } block(resultDate, exactMatch, &stop); } } // End while loop if (previouslyReturnedMatchDate) CFRelease(previouslyReturnedMatchDate); CFRelease(searchingDate); }
62.257413
617
0.679119
[ "object" ]
e728e25583267f5e3c3a0679047a3a7885e9eaad
2,850
h
C
ur_robot_driver/include/ur_robot_driver/primary/robot_message.h
urmahp/Universal_Robots_Isaac_Driver
5ae8c52127ec64b9572cd08e35895ce7527c57a1
[ "Apache-2.0" ]
null
null
null
ur_robot_driver/include/ur_robot_driver/primary/robot_message.h
urmahp/Universal_Robots_Isaac_Driver
5ae8c52127ec64b9572cd08e35895ce7527c57a1
[ "Apache-2.0" ]
null
null
null
ur_robot_driver/include/ur_robot_driver/primary/robot_message.h
urmahp/Universal_Robots_Isaac_Driver
5ae8c52127ec64b9572cd08e35895ce7527c57a1
[ "Apache-2.0" ]
null
null
null
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright 2019 FZI Forschungszentrum Informatik // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Lea Steffen steffen@fzi.de * \date 2019-04-01 * */ //---------------------------------------------------------------------- #ifndef UR_RTDE_DRIVER_ROBOT_MESSAGE_H_INCLUDED #define UR_RTDE_DRIVER_ROBOT_MESSAGE_H_INCLUDED #include "ur_robot_driver/primary/primary_package.h" namespace ur_driver { namespace primary_interface { /*! * \brief Possible RobotMessage types */ enum class RobotMessagePackageType : uint8_t { ROBOT_MESSAGE_TEXT = 0, ROBOT_MESSAGE_PROGRAM_LABEL = 1, PROGRAM_STATE_MESSAGE_VARIABLE_UPDATE = 2, ROBOT_MESSAGE_VERSION = 3, ROBOT_MESSAGE_SAFETY_MODE = 5, ROBOT_MESSAGE_ERROR_CODE = 6, ROBOT_MESSAGE_KEY = 7, ROBOT_MESSAGE_REQUEST_VALUE = 9, ROBOT_MESSAGE_RUNTIME_EXCEPTION = 10 }; /*! * \brief The RobotMessage class is a parent class for the different received robot messages. */ class RobotMessage : public PrimaryPackage { public: /*! * \brief Creates a new RobotMessage object to be filled from a package. * * \param timestamp Timestamp of the package * \param source The package's source */ RobotMessage(const uint64_t timestamp, const uint8_t source) : timestamp_(timestamp), source_(source) { } virtual ~RobotMessage() = default; /*! * \brief Sets the attributes of the package by parsing a serialized representation of the * package. * * \param bp A parser containing a serialized version of the package * * \returns True, if the package was parsed successfully, false otherwise */ virtual bool parseWith(comm::BinParser& bp); /*! * \brief Produces a human readable representation of the package object. * * \returns A string representing the object */ virtual std::string toString() const; uint64_t timestamp_; uint8_t source_; RobotMessagePackageType message_type_; }; } // namespace primary_interface } // namespace ur_driver #endif /* UR_RTDE_DRIVER_ROBOT_MESSAGE_H_INCLUDED */
29.6875
103
0.674035
[ "object" ]
e72f7e55491dd87d6b4fd2e0d797abbbc9548817
6,255
h
C
VTK/Filtering/vtkCompositeDataSet.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
VTK/Filtering/vtkCompositeDataSet.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
VTK/Filtering/vtkCompositeDataSet.h
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile$ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkCompositeDataSet - abstract superclass for composite // (multi-block or AMR) datasets // .SECTION Description // vtkCompositeDataSet is an abstract class that represents a collection // of datasets (including other composite datasets). It // provides an interface to access the datasets through iterators. // vtkCompositeDataSet provides methods that are used by subclasses to store the // datasets. // vtkCompositeDataSet provides the datastructure for a full tree // representation. Subclasses provide the semantics for it and control how // this tree is built. // .SECTION See Also // vtkCompositeDataIterator #ifndef __vtkCompositeDataSet_h #define __vtkCompositeDataSet_h #include "vtkDataObject.h" class vtkCompositeDataIterator; class vtkCompositeDataSetInternals; class vtkInformation; class vtkInformationStringKey; class VTK_FILTERING_EXPORT vtkCompositeDataSet : public vtkDataObject { public: vtkTypeRevisionMacro(vtkCompositeDataSet, vtkDataObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Return a new iterator (the iterator has to be deleted by user). virtual vtkCompositeDataIterator* NewIterator(); // Description: // Return class name of data type (see vtkType.h for // definitions). virtual int GetDataObjectType() {return VTK_COMPOSITE_DATA_SET;} // Description: // Get the port currently producing this object. virtual vtkAlgorithmOutput* GetProducerPort(); // Description: // Copies the tree structure from the input. All pointers to non-composite // data objects are intialized to NULL. This also shallow copies the meta data // associated with all the nodes. virtual void CopyStructure(vtkCompositeDataSet* input); // Description: // Sets the data set at the location pointed by the iterator. // The iterator does not need to be iterating over this dataset itself. It can // be any composite datasite with similar structure (achieved by using // CopyStructure). virtual void SetDataSet(vtkCompositeDataIterator* iter, vtkDataObject* dataObj); // Description: // Returns the dataset located at the positiong pointed by the iterator. // The iterator does not need to be iterating over this dataset itself. It can // be an iterator for composite dataset with similar structure (achieved by // using CopyStructure). virtual vtkDataObject* GetDataSet(vtkCompositeDataIterator* iter); // Description: // Returns the meta-data associated with the position pointed by the iterator. // This will create a new vtkInformation object if none already exists. Use // HasMetaData to avoid creating the vtkInformation object unnecessarily. // The iterator does not need to be iterating over this dataset itself. It can // be an iterator for composite dataset with similar structure (achieved by // using CopyStructure). virtual vtkInformation* GetMetaData(vtkCompositeDataIterator* iter); // Description: // Returns if any meta-data associated with the position pointed by the iterator. // The iterator does not need to be iterating over this dataset itself. It can // be an iterator for composite dataset with similar structure (achieved by // using CopyStructure). virtual int HasMetaData(vtkCompositeDataIterator* iter); //BTX // Description: // Retrieve an instance of this class from an information object. static vtkCompositeDataSet* GetData(vtkInformation* info); static vtkCompositeDataSet* GetData(vtkInformationVector* v, int i=0); //ETX // Description: // Restore data object to initial state, virtual void Initialize(); // Description: // Shallow and Deep copy. virtual void ShallowCopy(vtkDataObject *src); virtual void DeepCopy(vtkDataObject *src); // Description: // Returns the total number of points of all blocks. This will // iterate over all blocks and call GetNumberOfPoints() so it // might be expansive. virtual vtkIdType GetNumberOfPoints(); // Description: // Key used to put node name in the meta-data associated with a node. static vtkInformationStringKey* NAME(); //BTX protected: vtkCompositeDataSet(); ~vtkCompositeDataSet(); // Description: // Set the number of children. void SetNumberOfChildren(unsigned int num); // Description: // Get the number of children. unsigned int GetNumberOfChildren(); // Description: // Set child dataset at a given index. The number of children is adjusted to // to be greater than the index specified. void SetChild(unsigned int index, vtkDataObject*); // Description: // Remove the child at a given index. void RemoveChild(unsigned int index); // Description: // Returns a child dataset at a given index. vtkDataObject* GetChild(unsigned int num); // Description: // Returns the meta-data at a given index. If the index is valid, however, no // information object is set, then a new one will created and returned. // To avoid unnecessary creation, use HasMetaData(). vtkInformation* GetChildMetaData(unsigned int index); // Description: // Sets the meta-data at a given index. void SetChildMetaData(unsigned int index, vtkInformation* info); // Description: // Returns if meta-data information is available for the given child index. // Returns 1 is present, 0 otherwise. int HasChildMetaData(unsigned int index); // The internal datastructure. Subclasses need not access this directly. vtkCompositeDataSetInternals* Internals; friend class vtkCompositeDataIterator; private: vtkCompositeDataSet(const vtkCompositeDataSet&); // Not implemented. void operator=(const vtkCompositeDataSet&); // Not implemented. //ETX }; #endif
35.742857
83
0.73797
[ "object" ]
30ad6fb2fbb095397981924e3f90e2b91b69a697
3,771
h
C
aws-cpp-sdk-inspector/include/aws/inspector/model/GetAssessmentReportResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-inspector/include/aws/inspector/model/GetAssessmentReportResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-inspector/include/aws/inspector/model/GetAssessmentReportResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/inspector/Inspector_EXPORTS.h> #include <aws/inspector/model/ReportStatus.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Inspector { namespace Model { class AWS_INSPECTOR_API GetAssessmentReportResult { public: GetAssessmentReportResult(); GetAssessmentReportResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); GetAssessmentReportResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Specifies the status of the request to generate an assessment report. </p> */ inline const ReportStatus& GetStatus() const{ return m_status; } /** * <p>Specifies the status of the request to generate an assessment report. </p> */ inline void SetStatus(const ReportStatus& value) { m_status = value; } /** * <p>Specifies the status of the request to generate an assessment report. </p> */ inline void SetStatus(ReportStatus&& value) { m_status = std::move(value); } /** * <p>Specifies the status of the request to generate an assessment report. </p> */ inline GetAssessmentReportResult& WithStatus(const ReportStatus& value) { SetStatus(value); return *this;} /** * <p>Specifies the status of the request to generate an assessment report. </p> */ inline GetAssessmentReportResult& WithStatus(ReportStatus&& value) { SetStatus(std::move(value)); return *this;} /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline const Aws::String& GetUrl() const{ return m_url; } /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline void SetUrl(const Aws::String& value) { m_url = value; } /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline void SetUrl(Aws::String&& value) { m_url = std::move(value); } /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline void SetUrl(const char* value) { m_url.assign(value); } /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline GetAssessmentReportResult& WithUrl(const Aws::String& value) { SetUrl(value); return *this;} /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline GetAssessmentReportResult& WithUrl(Aws::String&& value) { SetUrl(std::move(value)); return *this;} /** * <p>Specifies the URL where you can find the generated assessment report. This * parameter is only returned if the report is successfully generated.</p> */ inline GetAssessmentReportResult& WithUrl(const char* value) { SetUrl(value); return *this;} private: ReportStatus m_status; Aws::String m_url; }; } // namespace Model } // namespace Inspector } // namespace Aws
33.078947
116
0.693185
[ "model" ]
30aedafccc1e94384420d542670e30c23446ce9b
39,167
c
C
source/dao_scene.c
sanyaade-teachings/DaoGraphics
604952cd8c5b9e59e416f98b1ea08488cdc61bf1
[ "BSD-2-Clause" ]
1
2017-04-30T04:48:42.000Z
2017-04-30T04:48:42.000Z
source/dao_scene.c
sanyaade-teachings/DaoGraphics
604952cd8c5b9e59e416f98b1ea08488cdc61bf1
[ "BSD-2-Clause" ]
null
null
null
source/dao_scene.c
sanyaade-teachings/DaoGraphics
604952cd8c5b9e59e416f98b1ea08488cdc61bf1
[ "BSD-2-Clause" ]
null
null
null
/* // Dao Graphics Engine // http://www.daovm.net // // Copyright (c) 2012, Limin Fu // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include "dao_scene.h" #if defined(__APPLE__) //# include <OpenGL/gl.h> # include <OpenGL/gl3.h> # include <GLUT/glut.h> #else //# include <GL/gl.h> # include <GL/gl3.h> # include <GL/glut.h> #endif void DaoxTexture_glFreeTexture( DaoxTexture *self ); DaoxTexture* DaoxTexture_New() { DaoxTexture *self = (DaoxTexture*) dao_malloc( sizeof(DaoxTexture) ); DaoCstruct_Init( (DaoCstruct*) self, daox_type_texture ); self->tid = 0; self->image = NULL; self->file = DString_New(1); return self; } void DaoxTexture_Delete( DaoxTexture *self ) { if( self->tid ) DaoxTexture_glFreeTexture( self ); DaoCstruct_Free( (DaoCstruct*) self ); DaoGC_DecRC( (DaoValue*) self->image ); DString_Delete( self->file ); dao_free( self ); } void DaoxTexture_SetImage( DaoxTexture *self, DaoxImage *image ) { if( self->tid ) DaoxTexture_glFreeTexture( self ); DaoGC_ShiftRC( (DaoValue*) image, (DaoValue*) self->image ); self->image = image; } void DaoxTexture_LoadImage( DaoxTexture *self, const char *file ) { DaoxImage *image = self->image; if( image == NULL || image->refCount > 1 ){ image = DaoxImage_New(); DaoxTexture_SetImage( self, image ); } DaoxImage_LoadBMP( self->image, file ); } void DaoxTexture_glFreeTexture( DaoxTexture *self ) { GLuint tid = self->tid; if( tid == 0 ) return; glDeleteTextures( 1, & tid ); self->tid = 0; } void DaoxTexture_glInitTexture( DaoxTexture *self ) { uchar_t *data; int W, H; GLuint tid = 0; if( self->tid ) return; if( self->file->size ){ if( self->image == NULL || self->image->imageData == NULL ){ DString_ToMBS( self->file ); DaoxTexture_LoadImage( self, self->file->mbs ); } } if( self->image == NULL ) return; data = self->image->imageData; W = self->image->width; H = self->image->height; if( W == 0 || H == 0 ) return; glGenTextures( 1, & tid ); self->tid = tid; glBindTexture(GL_TEXTURE_2D, self->tid); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if( self->image->depth == DAOX_IMAGE_BIT24 ){ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, W, H, 0, GL_RGB, GL_UNSIGNED_BYTE, data); }else if( self->image->depth == DAOX_IMAGE_BIT32 ){ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, W, H, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } glBindTexture(GL_TEXTURE_2D, 0); } DaoxMaterial* DaoxMaterial_New() { DaoxMaterial *self = (DaoxMaterial*) dao_calloc( 1, sizeof(DaoxMaterial) ); DaoCstruct_Init( (DaoCstruct*) self, daox_type_material ); self->name = DString_New(1); return self; } void DaoxMaterial_Delete( DaoxMaterial *self ) { DString_Delete( self->name ); DaoGC_DecRC( (DaoValue*) self->texture1 ); DaoGC_DecRC( (DaoValue*) self->texture2 ); DaoCstruct_Free( (DaoCstruct*) self ); dao_free( self ); } void DaoxMaterial_CopyFrom( DaoxMaterial *self, DaoxMaterial *other ) { /* Do not copy name! */ memcpy( & self->ambient, & other->ambient, 4*sizeof(DaoxColor) ); memcpy( & self->lighting, & other->lighting, 6*sizeof(uint_t) ); DaoGC_ShiftRC( (DaoValue*) other->texture1, (DaoValue*) self->texture1 ); DaoGC_ShiftRC( (DaoValue*) other->texture2, (DaoValue*) self->texture2 ); self->texture1 = other->texture1; self->texture2 = other->texture2; } void DaoxMaterial_SetTexture( DaoxMaterial *self, DaoxTexture *texture ) { DaoGC_ShiftRC( (DaoValue*) texture, (DaoValue*) self->texture1 ); self->texture1 = texture; } /* // View direction: -z; // Up direction: y; // Right direction: x; */ void DaoxViewFrustum_Init( DaoxViewFrustum *self, DaoxCamera *camera ) { DaoxVector3D cameraPosition = {0.0, 0.0, 0.0}; DaoxVector3D viewDirection = {0.0, 0.0, -1.0}; DaoxVector3D nearViewCenter = {0.0, 0.0, 0.0}; DaoxVector3D farViewCenter = {0.0, 0.0, 0.0}; DaoxVector3D topLeft = cameraPosition; DaoxVector3D topRight = cameraPosition; DaoxVector3D bottomLeft = cameraPosition; DaoxVector3D bottomRight = cameraPosition; DaoxVector3D leftPlaneNorm; DaoxVector3D rightPlaneNorm; DaoxVector3D topPlaneNorm; DaoxVector3D bottomPlaneNorm; DaoxMatrix4D objectToWorld = DaoxSceneNode_GetWorldTransform( & camera->base ); float xtan = tan( 0.5 * camera->fovAngle * M_PI / 180.0 ); float scale, scale2; self->right = camera->nearPlane * xtan; self->left = - self->right; self->top = self->right / camera->aspectRatio; self->bottom = - self->top; self->near = camera->nearPlane; self->far = camera->farPlane; topLeft.x = self->left; topLeft.y = self->top; topLeft.z = - camera->nearPlane; topRight.x = self->right; topRight.y = self->top; topRight.z = - camera->nearPlane; bottomLeft.x = self->left; bottomLeft.y = self->bottom; bottomLeft.z = - camera->nearPlane; bottomRight.x = self->right; bottomRight.y = self->bottom; bottomRight.z = - camera->nearPlane; nearViewCenter.z = - camera->nearPlane; farViewCenter.z = - camera->farPlane; leftPlaneNorm = DaoxVector3D_Cross( & topLeft, & bottomLeft ); rightPlaneNorm = DaoxVector3D_Cross( & bottomRight, & topRight ); topPlaneNorm = DaoxVector3D_Cross( & topRight, & topLeft ); bottomPlaneNorm = DaoxVector3D_Cross( & bottomLeft, & bottomRight ); scale = 1.0 / sqrt( DaoxVector3D_Norm2( & leftPlaneNorm ) ); scale2 = 1.0 / sqrt( DaoxVector3D_Norm2( & topPlaneNorm ) ); leftPlaneNorm = DaoxVector3D_Scale( & leftPlaneNorm, scale ); rightPlaneNorm = DaoxVector3D_Scale( & rightPlaneNorm, scale ); topPlaneNorm = DaoxVector3D_Scale( & topPlaneNorm, scale2 ); bottomPlaneNorm = DaoxVector3D_Scale( & bottomPlaneNorm, scale2 ); self->cameraPosition = DaoxMatrix4D_MulVector( & objectToWorld, & cameraPosition, 1.0 ); self->nearViewCenter = DaoxMatrix4D_MulVector( & objectToWorld, & nearViewCenter, 1.0 ); self->farViewCenter = DaoxMatrix4D_MulVector( & objectToWorld, & farViewCenter, 1.0 ); self->viewDirection = DaoxMatrix4D_MulVector( & objectToWorld, & viewDirection, 0.0 ); self->topLeftEdge = DaoxMatrix4D_MulVector( & objectToWorld, & topLeft, 0.0 ); self->topRightEdge = DaoxMatrix4D_MulVector( & objectToWorld, & topRight, 0.0 ); self->bottomLeftEdge = DaoxMatrix4D_MulVector( & objectToWorld, & bottomLeft, 0.0 ); self->bottomRightEdge = DaoxMatrix4D_MulVector( & objectToWorld, & bottomRight, 0.0 ); self->leftPlaneNorm = DaoxMatrix4D_MulVector( & objectToWorld, & leftPlaneNorm, 0.0 ); self->rightPlaneNorm = DaoxMatrix4D_MulVector( & objectToWorld, & rightPlaneNorm, 0.0 ); self->topPlaneNorm = DaoxMatrix4D_MulVector( & objectToWorld, & topPlaneNorm, 0.0 ); self->bottomPlaneNorm = DaoxMatrix4D_MulVector( & objectToWorld, & bottomPlaneNorm, 0.0 ); } DaoxViewFrustum DaoxViewFrustum_Transform( DaoxViewFrustum *self, DaoxMatrix4D *matrix ) { DaoxViewFrustum frustum = *self; frustum.cameraPosition = DaoxMatrix4D_MulVector( matrix, & self->cameraPosition, 1.0 ); frustum.nearViewCenter = DaoxMatrix4D_MulVector( matrix, & self->nearViewCenter, 1.0 ); frustum.farViewCenter = DaoxMatrix4D_MulVector( matrix, & self->farViewCenter, 1.0 ); frustum.viewDirection = DaoxMatrix4D_MulVector( matrix, & self->viewDirection, 0.0 ); frustum.topLeftEdge = DaoxMatrix4D_MulVector( matrix, & self->topLeftEdge, 0.0 ); frustum.topRightEdge = DaoxMatrix4D_MulVector( matrix, & self->topRightEdge, 0.0 ); frustum.bottomLeftEdge = DaoxMatrix4D_MulVector( matrix, & self->bottomLeftEdge, 0.0 ); frustum.bottomRightEdge = DaoxMatrix4D_MulVector( matrix, & self->bottomRightEdge, 0.0 ); frustum.leftPlaneNorm = DaoxMatrix4D_MulVector( matrix, & self->leftPlaneNorm, 0.0 ); frustum.rightPlaneNorm = DaoxMatrix4D_MulVector( matrix, & self->rightPlaneNorm, 0.0 ); frustum.topPlaneNorm = DaoxMatrix4D_MulVector( matrix, & self->topPlaneNorm, 0.0 ); frustum.bottomPlaneNorm = DaoxMatrix4D_MulVector( matrix, & self->bottomPlaneNorm, 0.0 ); return frustum; } double DaoxViewFrustum_Difference( DaoxViewFrustum *self, DaoxViewFrustum *other ) { double d1, d2, d3, d4, d5, max = 0.0; d1 = DaoxVector3D_Difference( & self->cameraPosition, & other->cameraPosition); d2 = DaoxVector3D_Difference( & self->leftPlaneNorm, & other->leftPlaneNorm); d3 = DaoxVector3D_Difference( & self->rightPlaneNorm, & other->rightPlaneNorm); d4 = DaoxVector3D_Difference( & self->topPlaneNorm, & other->topPlaneNorm); d5 = DaoxVector3D_Difference( & self->bottomPlaneNorm, & other->bottomPlaneNorm); if( d1 > max ) max = d1; if( d2 > max ) max = d2; if( d3 > max ) max = d3; if( d4 > max ) max = d4; if( d5 > max ) max = d5; return max; } void DaoxViewFrustum_Print( DaoxViewFrustum *self ) { printf( "DaoxViewFrustum:\n" ); DaoxVector3D_Print( & self->cameraPosition ); DaoxVector3D_Print( & self->leftPlaneNorm ); DaoxVector3D_Print( & self->rightPlaneNorm ); DaoxVector3D_Print( & self->topPlaneNorm ); DaoxVector3D_Print( & self->bottomPlaneNorm ); } /* // This function take a plane (passing "point" with normal "norm"), // and a line segment (connecting P1 and P2) as parameter. It returns: // -1, if the line segment P1P2 lies in the negative side of the plane; // 0, if the line segment cross the plane; // 1, if the line segment lies in the positive side of the plane; */ static int CheckLine( DaoxVector3D point, DaoxVector3D norm, DaoxVector3D P1, DaoxVector3D P2 ) { double dot1, dot2; P1 = DaoxVector3D_Sub( & P1, & point ); P2 = DaoxVector3D_Sub( & P2, & point ); dot1 = DaoxVector3D_Dot( & P1, & norm ); dot2 = DaoxVector3D_Dot( & P2, & norm ); if( dot1 * dot2 <= 0.0 ) return 0; if( dot1 < 0.0 ) return -1; return 1; } static int CheckBox( DaoxVector3D point, DaoxVector3D norm, DaoxOBBox3D *box ) { DaoxVector3D dX, dY, dZ, XY, YZ, ZX, XYZ; int ch, check; dX = DaoxVector3D_Sub( & box->X, & box->O ); dY = DaoxVector3D_Sub( & box->Y, & box->O ); dZ = DaoxVector3D_Sub( & box->Z, & box->O ); XY = DaoxVector3D_Add( & box->X, & dY ); check = CheckLine( point, norm, box->Z, XY ); if( check == 0 ) return 0; YZ = DaoxVector3D_Add( & box->Y, & dZ ); ch = CheckLine( point, norm, box->X, YZ ); if( (check * ch) <= 0 ) return 0; ZX = DaoxVector3D_Add( & box->Z, & dX ); ch = CheckLine( point, norm, box->Y, ZX ); if( (check * ch) <= 0 ) return 0; XYZ = DaoxVector3D_Add( & ZX, & dY ); ch = CheckLine( point, norm, box->O, XYZ ); if( (check * ch) <= 0 ) return 0; return check; } int DaoxViewFrustum_SphereCheck( DaoxViewFrustum *self, DaoxOBBox3D *box ) { DaoxVector3D C = DaoxVector3D_Sub( & box->C, & self->cameraPosition ); double D0 = DaoxVector3D_Dot( & C, & self->viewDirection ); double D1, D2, D3, D4, margin = box->R + EPSILON; if( D0 > (self->far + margin) ) return -1; if( D0 < (self->near - margin) ) return -1; if( (D1 = DaoxVector3D_Dot( & C, & self->leftPlaneNorm )) > margin ) return -1; if( (D2 = DaoxVector3D_Dot( & C, & self->rightPlaneNorm )) > margin ) return -1; if( (D3 = DaoxVector3D_Dot( & C, & self->topPlaneNorm )) > margin ) return -1; if( (D4 = DaoxVector3D_Dot( & C, & self->bottomPlaneNorm )) > margin ) return -1; if( D0 > (self->near + margin) && D0 < (self->far - margin) && D1 < -margin && D2 < -margin && D3 < -margin && D4 < -margin ) return 1; return 0; } int DaoxViewFrustum_Visible( DaoxViewFrustum *self, DaoxOBBox3D *box ) { int C1, C2, C3, C4, C5, C6; int C0 = DaoxViewFrustum_SphereCheck( self, box ); if( C0 != 0 ) return C0; C1 = C2 = C3 = C4 = C5 = C6 = 0; if( (C1 = CheckBox( self->nearViewCenter, self->viewDirection, box )) < 0 ) return -1; if( (C2 = CheckBox( self->farViewCenter, self->viewDirection, box )) > 0 ) return -1; if( (C3 = CheckBox( self->cameraPosition, self->leftPlaneNorm, box )) > 0 ) return -1; if( (C4 = CheckBox( self->cameraPosition, self->rightPlaneNorm, box )) > 0 ) return -1; if( (C5 = CheckBox( self->cameraPosition, self->topPlaneNorm, box )) > 0 ) return -1; if( (C6 = CheckBox( self->cameraPosition, self->bottomPlaneNorm, box )) > 0 ) return -1; if( C1 > 0 && C2 < 0 && C3 < 0 && C4 < 0 && C5 < 0 && C6 < 0 ) return 1; return 0; } typedef struct DaoxPointable DaoxPointable; struct DaoxPointable { DaoxSceneNode base; DaoxVector3D targetPosition; }; void DaoxSceneNode_Init( DaoxSceneNode *self, DaoType *type ) { DaoCstruct_Init( (DaoCstruct*) self, type ); self->renderable = 0; self->parent = NULL; self->children = DArray_New(D_VALUE); self->transform = DaoxMatrix4D_Identity(); } void DaoxSceneNode_Free( DaoxSceneNode *self ) { DaoCstruct_Free( (DaoCstruct*) self ); DaoGC_DecRC( (DaoValue*) self->parent ); DArray_Delete( self->children ); } DaoxSceneNode* DaoxSceneNode_New() { DaoxSceneNode *self = (DaoxSceneNode*) dao_calloc( 1, sizeof(DaoxSceneNode) ); DaoxSceneNode_Init( self, daox_type_scene_node ); return self; } void DaoxSceneNode_Delete( DaoxSceneNode *self ) { DaoxSceneNode_Free( self ); dao_free( self ); } void DaoxSceneNode_ApplyTransform( DaoxSceneNode *self, DaoxMatrix4D mat ) { if( self->ctype == daox_type_model ){ DaoxModel *model = (DaoxModel*) self; daoint i; for(i=0; i<model->points->size; ++i){ DaoxPlainArray *points = (DaoxPlainArray*) model->points->items.pVoid[i]; DaoxPlainArray_ResetSize( points, 0 ); } } self->transform = DaoxMatrix4D_MulMatrix( & mat, & self->transform ); } void DaoxSceneNode_MoveByXYZ( DaoxSceneNode *self, float dx, float dy, float dz ) { DaoxMatrix4D M = DaoxMatrix4D_Translation( dx, dy, dz ); DaoxSceneNode_ApplyTransform( self, M ); } void DaoxSceneNode_MoveXYZ( DaoxSceneNode *self, float x, float y, float z ) { DaoxMatrix4D M = self->transform; DaoxSceneNode_MoveByXYZ( self, x - M.B1, y - M.B2, z - M.B3 ); } void DaoxSceneNode_MoveBy( DaoxSceneNode *self, DaoxVector3D delta ) { DaoxSceneNode_MoveByXYZ( self, delta.x, delta.y, delta.z ); } void DaoxSceneNode_Move( DaoxSceneNode *self, DaoxVector3D pos ) { DaoxSceneNode_MoveXYZ( self, pos.x, pos.y, pos.z ); } DaoxMatrix4D DaoxSceneNode_GetWorldTransform( DaoxSceneNode *self ) { DaoxMatrix4D transform = self->transform; DaoxSceneNode *node = self; while( node->parent ){ node = node->parent; transform = DaoxMatrix4D_MulMatrix( & node->transform, & transform ); } return transform; } DaoxVector3D DaoxSceneNode_GetWorldPosition( DaoxSceneNode *self ) { DaoxMatrix4D transform = DaoxSceneNode_GetWorldTransform( self ); DaoxVector3D vec = {0.0, 0.0, 0.0}; return DaoxMatrix4D_MulVector( & transform, & vec, 1.0 ); } void DaoxSceneNode_AddChild( DaoxSceneNode *self, DaoxSceneNode *child ) { DaoGC_ShiftRC( (DaoValue*) self, (DaoValue*) child->parent ); child->parent = self; DArray_Append( self->children, child ); } void DaoxPointable_PointAt( DaoxPointable *self, DaoxVector3D pos ) { double dot, angle, angle2; DaoxVector3D axis, newPointDirection; DaoxVector3D xaxis = {1.0,0.0,0.0}; DaoxVector3D yaxis = {0.0,1.0,0.0}; DaoxVector3D sourcePosition = {0.0,0.0,0.0}; DaoxVector3D pointDirection = {0.0,0.0,-1.0}; DaoxVector3D rightDirection = {1.0,0.0,0.0}; DaoxMatrix4D rotation = DaoxMatrix4D_RotationOnly( & self->base.transform ); DaoxMatrix4D translation = DaoxMatrix4D_TranslationOnly( & self->base.transform ); DaoxMatrix4D rot, rot2; self->targetPosition = pos; sourcePosition = DaoxMatrix4D_MulVector( & self->base.transform, & sourcePosition, 1.0 ); pointDirection = DaoxMatrix4D_MulVector( & rotation, & pointDirection, 1.0 ); rightDirection = DaoxMatrix4D_MulVector( & rotation, & rightDirection, 1.0 ); newPointDirection = DaoxVector3D_Sub( & pos, & sourcePosition ); pointDirection = DaoxVector3D_Normalize( & pointDirection ); newPointDirection = DaoxVector3D_Normalize( & newPointDirection ); dot = DaoxVector3D_Dot( & newPointDirection, & yaxis ); angle = DaoxVector3D_Angle( & newPointDirection, & yaxis ); angle -= DaoxVector3D_Angle( & pointDirection, & yaxis ); rot = DaoxMatrix4D_AxisRotation( rightDirection, - angle ); if( fabs( fabs(dot) - 1.0 ) < EPSILON ) goto Final; pointDirection.y = newPointDirection.y = 0; angle2 = DaoxVector3D_Angle( & newPointDirection, & xaxis ); angle2 -= DaoxVector3D_Angle( & pointDirection, & xaxis ); rot2 = DaoxMatrix4D_AxisRotation( yaxis, angle2 ); rot = DaoxMatrix4D_MulMatrix( & rot, & rot2 ); rot = DaoxMatrix4D_MulMatrix( & rot, & rotation ); Final: self->base.transform = DaoxMatrix4D_MulMatrix( & translation, & rot ); } void DaoxPointable_PointAtXYZ( DaoxPointable *self, float x, float y, float z ) { DaoxVector3D pos; pos.x = x; pos.y = y; pos.z = z; DaoxPointable_PointAt( self, pos ); } void DaoxPointable_Move( DaoxPointable *self, DaoxVector3D pos ) { DaoxSceneNode_Move( (DaoxSceneNode*) self, pos ); DaoxPointable_PointAt( self, self->targetPosition ); } void DaoxPointable_MoveXYZ( DaoxPointable *self, float x, float y, float z ) { DaoxSceneNode_MoveXYZ( (DaoxSceneNode*) self, x, y, z ); DaoxPointable_PointAt( self, self->targetPosition ); } void DaoxPointable_MoveBy( DaoxPointable *self, DaoxVector3D delta ) { DaoxSceneNode_MoveBy( (DaoxSceneNode*) self, delta ); DaoxPointable_PointAt( self, self->targetPosition ); } void DaoxPointable_MoveByXYZ( DaoxPointable *self, float dx, float dy, float dz ) { DaoxSceneNode_MoveByXYZ( (DaoxSceneNode*) self, dx, dy, dz ); DaoxPointable_PointAt( self, self->targetPosition ); } DaoxCamera* DaoxCamera_New() { DaoxCamera *self = (DaoxCamera*) dao_calloc( 1, sizeof(DaoxCamera) ); DaoxSceneNode_Init( (DaoxSceneNode*) self, daox_type_camera ); self->viewTarget.x = 0; self->viewTarget.y = 0; self->viewTarget.z = -1; self->fovAngle = 90.0; self->aspectRatio = 1.2; self->nearPlane = 0.5; self->farPlane = 100.0; return self; } void DaoxCamera_Delete( DaoxCamera *self ) { DaoxSceneNode_Free( (DaoxSceneNode*) self ); dao_free( self ); } void DaoxCamera_CopyFrom( DaoxCamera *self, DaoxCamera *other ) { self->viewTarget = other->viewTarget; self->fovAngle = other->fovAngle; self->aspectRatio = other->aspectRatio; self->nearPlane = other->nearPlane; self->farPlane = other->farPlane; } void DaoxCamera_Move( DaoxCamera *self, DaoxVector3D pos ) { DaoxPointable_Move( (DaoxPointable*) self, pos ); } void DaoxCamera_MoveBy( DaoxCamera *self, DaoxVector3D delta ) { DaoxPointable_MoveBy( (DaoxPointable*) self, delta ); } void DaoxCamera_LookAt( DaoxCamera *self, DaoxVector3D pos ) { DaoxPointable_PointAt( (DaoxPointable*) self, pos ); } void DaoxCamera_MoveXYZ( DaoxCamera *self, float x, float y, float z ) { DaoxPointable_MoveXYZ( (DaoxPointable*) self, x, y, z ); } void DaoxCamera_MoveByXYZ( DaoxCamera *self, float dx, float dy, float dz ) { DaoxPointable_MoveByXYZ( (DaoxPointable*) self, dx, dy, dz ); } void DaoxCamera_LookAtXYZ( DaoxCamera *self, float x, float y, float z ) { DaoxPointable_PointAtXYZ( (DaoxPointable*) self, x, y, z ); } DaoxLight* DaoxLight_New() { DaoxLight *self = (DaoxLight*) dao_calloc( 1, sizeof(DaoxLight) ); DaoxSceneNode_Init( (DaoxSceneNode*) self, daox_type_light ); self->targetPosition.x = 0; self->targetPosition.y = -1E16; self->targetPosition.z = 0; self->intensity.alpha = 1.0; return self; } void DaoxLight_Delete( DaoxLight *self ) { DaoxSceneNode_Free( (DaoxSceneNode*) self ); dao_free( self ); } void DaoxLight_CopyFrom( DaoxLight *self, DaoxLight *other ) { self->targetPosition = other->targetPosition; self->intensity = other->intensity; } void DaoxLight_Move( DaoxLight *self, DaoxVector3D pos ) { DaoxPointable_Move( (DaoxPointable*) self, pos ); } void DaoxLight_PointAt( DaoxLight *self, DaoxVector3D pos ) { DaoxPointable_PointAt( (DaoxPointable*) self, pos ); } void DaoxLight_MoveXYZ( DaoxLight *self, float x, float y, float z ) { DaoxPointable_MoveXYZ( (DaoxPointable*) self, x, y, z ); } void DaoxLight_PointAtXYZ( DaoxLight *self, float x, float y, float z ) { DaoxPointable_PointAtXYZ( (DaoxPointable*) self, x, y, z ); } DaoxModel* DaoxModel_New() { DaoxModel *self = (DaoxModel*) dao_calloc( 1, sizeof(DaoxModel) ); DaoxSceneNode_Init( (DaoxSceneNode*) self, daox_type_model ); self->points = DArray_New(0); self->vnorms = DArray_New(0); self->tnorms = DArray_New(0); self->offsets = DaoxPlainArray_New( sizeof(int) ); return self; } static void DArray_DeleteVector3DArrays( DArray *self ) { daoint i; for(i=0; i<self->size; ++i) DaoxPlainArray_Delete( (DaoxPlainArray*) self->items.pVoid[i] ); DArray_Delete( self ); } void DaoxModel_Delete( DaoxModel *self ) { DaoxPlainArray_Delete( self->offsets ); DArray_DeleteVector3DArrays( self->points ); DArray_DeleteVector3DArrays( self->vnorms ); DArray_DeleteVector3DArrays( self->tnorms ); DaoxSceneNode_Free( (DaoxSceneNode*) self ); dao_free( self ); } void DaoxModel_SetMesh( DaoxModel *self, DaoxMesh *mesh ) { DaoGC_ShiftRC( (DaoValue*) mesh, (DaoValue*) self->mesh ); self->mesh = mesh; self->base.obbox = mesh->obbox; } void DaoxModel_TransformMesh( DaoxModel *self ) { DaoxMatrix4D transform = DaoxSceneNode_GetWorldTransform( & self->base ); daoint i, j; if( self->mesh == NULL ) return; while( self->points->size < self->mesh->units->size ){ DArray_Append( self->points, DaoxPlainArray_New( sizeof(DaoxVector3D) ) ); DArray_Append( self->vnorms, DaoxPlainArray_New( sizeof(DaoxVector3D) ) ); DArray_Append( self->tnorms, DaoxPlainArray_New( sizeof(DaoxVector3D) ) ); } for(i=0; i<self->mesh->units->size; ++i){ DaoxMeshUnit *unit = (DaoxMeshUnit*) self->mesh->units->items.pVoid[i]; DaoxPlainArray *points = (DaoxPlainArray*) self->points->items.pVoid[i]; DaoxPlainArray *vnorms = (DaoxPlainArray*) self->vnorms->items.pVoid[i]; DaoxPlainArray *tnorms = (DaoxPlainArray*) self->tnorms->items.pVoid[i]; if( points->size == unit->vertices->size && vnorms->size == unit->vertices->size && tnorms->size == unit->triangles->size ) continue; DaoxPlainArray_ResetSize( points, unit->vertices->size ); DaoxPlainArray_ResetSize( vnorms, unit->vertices->size ); DaoxPlainArray_ResetSize( tnorms, unit->triangles->size ); for(j=0; j<unit->vertices->size; ++j){ DaoxVertex *vertex = & unit->vertices->pod.vertices[j]; points->pod.vectors3d[j] = DaoxMatrix4D_MulVector( & transform, & vertex->point, 1.0 ); vnorms->pod.vectors3d[j] = DaoxMatrix4D_MulVector( & transform, & vertex->norm, 0.0 ); } for(j=0; j<unit->triangles->size; ++j){ DaoxTriangle *triangle = & unit->triangles->pod.triangles[j]; DaoxVector3D *A = points->pod.vectors3d + triangle->index[0]; DaoxVector3D *B = points->pod.vectors3d + triangle->index[1]; DaoxVector3D *C = points->pod.vectors3d + triangle->index[2]; tnorms->pod.vectors3d[j] = DaoxTriangle_Normal( A, B, C ); } } } DaoxScene* DaoxScene_New() { int i; DaoxColor colors[6]; DaoxMaterial *material; DaoxScene *self = (DaoxScene*) dao_malloc( sizeof(DaoxScene) ); DaoCstruct_Init( (DaoCstruct*) self, daox_type_scene ); self->nodes = DArray_New( D_VALUE ); self->lights = DArray_New(0); self->materialNames = DMap_New(D_STRING,0); self->textureNames = DMap_New(D_STRING,0); self->materials = DArray_New(D_VALUE); self->textures = DArray_New(D_VALUE); colors[0] = daox_black_color; colors[1] = daox_white_color; colors[2] = daox_red_color; colors[3] = daox_green_color; colors[4] = daox_blue_color; colors[5] = daox_gray_color; for(i=0; i<6; ++i){ material = DaoxMaterial_New(); material->ambient = material->diffuse = material->specular = colors[i]; DArray_Append( self->materials, material ); } return self; } void DaoxScene_Delete( DaoxScene *self ) { printf( "DaoxScene_Delete: %p\n", self ); DaoCstruct_Free( (DaoCstruct*) self ); DArray_Delete( self->nodes ); DArray_Delete( self->lights ); DArray_Delete( self->materials ); DArray_Delete( self->textures ); DMap_Delete( self->materialNames ); DMap_Delete( self->textureNames ); dao_free( self ); } void DaoxScene_AddNode( DaoxScene *self, DaoxSceneNode *node ) { DArray_Append( self->nodes, node ); if( node->ctype == daox_type_light ) DArray_Append( self->lights, node ); } void DaoxScene_AddMaterial( DaoxScene *self, DString *name, DaoxMaterial *material ) { MAP_Insert( self->materialNames, name, self->materials->size ); DArray_Append( self->materials, material ); } typedef struct DaoxBinaryParser DaoxBinaryParser; struct DaoxBinaryParser { uchar_t *source; uchar_t *end; uchar_t *error; }; uint_t DaoxBinaryParser_DecodeUInt16LE( DaoxBinaryParser *self ) { uint_t res; if( (self->source + 2) > self->end ){ self->source = self->error; return 0; } res = (self->source[1]<<8)|(self->source[0]); self->source += 2; return res; } uint_t DaoxBinaryParser_DecodeUInt32LE( DaoxBinaryParser *self ) { uint_t res; if( (self->source + 4) > self->end ){ self->source = self->error; return 0; } res = (self->source[3]<<24)|(self->source[2]<<16)|(self->source[1]<<8)|(self->source[0]); self->source += 4; return res; } uint_t DaoxBinaryParser_DecodeUInt32BE( DaoxBinaryParser *self ) { uint_t res; if( (self->source + 4) > self->end ){ self->source = self->error; return 0; } res = (self->source[0]<<24)|(self->source[1]<<16)|(self->source[2]<<8)|(self->source[3]); self->source += 4; return res; } /* // IEEE 754 single-precision binary floating-point format: // sign(1)--exponent(8)--fraction(23)-- // S EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF // 31 22 0 // // value = (-1)^S * ( 1 + \sigma_0^22 (b_i * 2^{-(23-i)}) ) * 2^{E-127} */ double DaoxBinaryParser_DecodeFloatLE( DaoxBinaryParser *self ) { double value = 1.0; uint_t bits = DaoxBinaryParser_DecodeUInt32LE( self ); uint_t negative = bits & (1<<31); int i, expon; if( (self->source + 4) > self->end ){ self->source = self->error; return 0; } if( bits == 0 ) return 0; if( bits == (0x7FF<<20) ) return INFINITY; if( bits == ((0x7FF<<20)|1) ) return NAN; bits = (bits<<1)>>1; expon = (bits>>23) - 127; for(i=0; i<23; ++i){ if( (bits>>i)&0x1 ){ int e = -(23-i); if( e >= 0 ) value += pow( 2, e ); else value += 1.0 / pow( 2, -e ); } } if( expon >= 0 ) value *= pow( 2, expon ); else value /= pow( 2, -expon ); if( negative ) value = -value; return value; } char* DaoxBinaryParser_DecodeString( DaoxBinaryParser *self ) { char *s = (char*) self->source; while( *self->source ) self->source += 1; self->source += 1; return s; } enum ColorType { AMBIENT, DIFFUSE, SPECULAR }; void DaoxScene_Parse3DS( DaoxScene *self, DString *source ) { DaoxColor tmpColor; DaoxVector3D vector; DaoxVector3D vector2; DaoxMatrix4D matrix; DaoxColor *color = NULL; DaoxImage *image = NULL; DaoxTexture *texture = NULL; DaoxMeshUnit *unit = NULL; DaoxMesh *mesh = NULL; DaoxModel *model = NULL; DaoxLight *light = NULL; DaoxCamera *camera = NULL; DaoxMaterial *material = NULL; DaoxBinaryParser parser0; DaoxBinaryParser *parser = & parser0; DaoxPlainArray *vertices = DaoxPlainArray_New( sizeof(DaoxVertex) ); DaoxPlainArray *triangles = DaoxPlainArray_New( sizeof(DaoxTriangle) ); DArray *integers = DArray_New(0); DArray *chunkids = DArray_New(0); DArray *chunkends = DArray_New(0); DArray *faceCounts = DArray_New(0); DString *string = DString_New(1); DNode *it = NULL; int colortype = AMBIENT; int i, j, k, m, n; float x, y, z, floats[16]; float amount; parser->source = (uchar_t*) source->mbs; parser->end = parser->source + source->size; parser->error = parser->end + 1; while( parser->source < parser->end ){ uint_t chunkid = DaoxBinaryParser_DecodeUInt16LE( parser ); uint_t chunklen = DaoxBinaryParser_DecodeUInt32LE( parser ); uint_t parentid = (daoint) DArray_Back( chunkids ); if( parser->source >= parser->end ) break; while( chunkends->size && ((uchar_t*)DArray_Back( chunkends )) < parser->source ){ DArray_PopBack( chunkends ); DArray_PopBack( chunkids ); } DArray_PushBack( chunkends, parser->source + (chunklen - 6) ); DArray_PushBack( chunkids, (void*)(size_t)chunkid ); printf( "chunk: %6X -> %6X %6i\n", parentid, chunkid, chunklen ); switch( chunkid ){ case 0x4D4D : /* Main Chunk */ case 0x3D3D : /* 3D Editor Chunk */ break; case 0x4000 : /* Object Block */ DaoxBinaryParser_DecodeString( parser ); break; case 0x4100 : /* Triangular Mesh */ if( model ){ DaoxMesh_UpdateTree( mesh, 0 ); DaoxMesh_ResetBoundingBox( mesh ); DaoxModel_SetMesh( model, mesh ); DaoxScene_AddNode( self, (DaoxSceneNode*) model ); } printf( "mesh\n" ); model = DaoxModel_New(); mesh = DaoxMesh_New(); break; case 0x4110 : /* Vertices List */ m = DaoxBinaryParser_DecodeUInt16LE( parser ); printf( "vertices: %i %p\n", m, unit ); DArray_Resize( faceCounts, m, 0 ); DaoxPlainArray_ResetSize( vertices, 0 ); for(i=0; i<m; ++i){ DaoxVertex *vertex = DaoxPlainArray_PushVertex( vertices ); vertex->point.x = DaoxBinaryParser_DecodeFloatLE( parser ); vertex->point.y = DaoxBinaryParser_DecodeFloatLE( parser ); vertex->point.z = DaoxBinaryParser_DecodeFloatLE( parser ); vertex->norm.x = vertex->norm.y = vertex->norm.z = 0.0; vertex->texUV.x = vertex->texUV.y = 0.0; faceCounts->items.pInt[i] = 0; //printf( "%9.3f %9.3f %9.3f\n", vertex->point.x, vertex->point.y, vertex->point.z ); } break; case 0x4120 : /* Faces Description */ m = DaoxBinaryParser_DecodeUInt16LE( parser ); DaoxPlainArray_ResetSize( triangles, 0 ); printf( "triangles: %i %p\n", m, unit ); for(i=0; i<m; ++i){ DaoxTriangle *triangle = DaoxPlainArray_PushTriangle( triangles ); DaoxVertex *A, *B, *C; DaoxVector3D AB, BC, N; float norm; triangle->index[0] = DaoxBinaryParser_DecodeUInt16LE( parser ); triangle->index[1] = DaoxBinaryParser_DecodeUInt16LE( parser ); triangle->index[2] = DaoxBinaryParser_DecodeUInt16LE( parser ); DaoxBinaryParser_DecodeUInt16LE( parser ); A = & vertices->pod.vertices[ triangle->index[0] ]; B = & vertices->pod.vertices[ triangle->index[1] ]; C = & vertices->pod.vertices[ triangle->index[2] ]; AB = DaoxVector3D_Sub( & B->point, & A->point ); BC = DaoxVector3D_Sub( & C->point, & B->point ); N = DaoxVector3D_Cross( & AB, & BC ); norm = DaoxVector3D_Norm2( & N ); N = DaoxVector3D_Scale( & N, 1.0 / sqrt( norm ) ); A->norm = DaoxVector3D_Add( & A->norm, & N ); B->norm = DaoxVector3D_Add( & B->norm, & N ); C->norm = DaoxVector3D_Add( & C->norm, & N ); faceCounts->items.pInt[ triangle->index[0] ] += 1; faceCounts->items.pInt[ triangle->index[1] ] += 1; faceCounts->items.pInt[ triangle->index[2] ] += 1; //printf( "%6i%6i%6i\n", triangle->index[0], triangle->index[1], triangle->index[2] ); } for(i=0; i<vertices->size; ++i){ DaoxVertex *V = & vertices->pod.vertices[i]; int count = faceCounts->items.pInt[i]; V->norm = DaoxVector3D_Scale( & V->norm, 1.0 / count ); } break; case 0x4130 : /* Faces Material */ DString_SetMBS( string, DaoxBinaryParser_DecodeString( parser ) ); it = DMap_Find( self->materialNames, string ); m = DaoxBinaryParser_DecodeUInt16LE( parser ); k = it ? it->value.pInt : 0; unit = DaoxMesh_AddUnit( mesh ); material = (DaoxMaterial*) self->materials->items.pVoid[k]; DaoxMeshUnit_SetMaterial( unit, material ); if( integers->size < vertices->size ) DArray_Resize( integers, vertices->size, 0 ); memset( integers->items.pInt, 0, vertices->size*sizeof(daoint) ); for(i=0; i<m; ++i){ int id = DaoxBinaryParser_DecodeUInt16LE( parser ); DaoxTriangle *triangle = DaoxPlainArray_PushTriangle( unit->triangles ); DaoxTriangle *triangle2 = triangles->pod.triangles + id; for(j=0; j<3; ++j){ if( integers->items.pInt[ triangle2->index[j] ] == 0 ){ DaoxVertex *vertex = DaoxPlainArray_PushVertex( unit->vertices ); DaoxVertex *vertex2 = vertices->pod.vertices + triangle2->index[j]; integers->items.pInt[ triangle2->index[j] ] = unit->vertices->size; *vertex = *vertex2; } triangle->index[j] = integers->items.pInt[ triangle2->index[j] ] - 1; } } break; case 0x4140 : /* Mapping Coordinates List */ m = DaoxBinaryParser_DecodeUInt16LE( parser ); for(i=0; i<m; ++i){ DaoxVertex *vertex = & vertices->pod.vertices[i]; x = DaoxBinaryParser_DecodeFloatLE( parser ); y = DaoxBinaryParser_DecodeFloatLE( parser ); if( i >= vertices->size ) continue; vertex->texUV.x = x; vertex->texUV.y = y; } break; case 0x4160 : /* Local Coordinates System */ matrix = DaoxMatrix4D_Identity(); matrix.A11 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A21 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A31 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A12 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A22 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A32 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A13 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A23 = DaoxBinaryParser_DecodeFloatLE( parser ); matrix.A33 = DaoxBinaryParser_DecodeFloatLE( parser ); vector.x = DaoxBinaryParser_DecodeFloatLE( parser ); vector.y = DaoxBinaryParser_DecodeFloatLE( parser ); vector.z = DaoxBinaryParser_DecodeFloatLE( parser ); DaoxMatrix4D_Print( & matrix ); DaoxVector3D_Print( & vector ); #warning "=========================================== transform" for(i=0; i<vertices->size; ++i){ DaoxVertex *vertex = & vertices->pod.vertices[i]; DaoxVector3D point = DaoxVector3D_Sub( & vertex->point, & vector ); vertex->point = DaoxMatrix4D_MulVector( & matrix, & point, 1.0 ); } matrix.B1 = vector.x; matrix.B2 = vector.y; matrix.B3 = vector.z; model->base.transform = matrix; break; case 0x4600 : /* Light */ light = DaoxLight_New(); DaoxScene_AddNode( self, (DaoxSceneNode*) light ); vector.x = DaoxBinaryParser_DecodeFloatLE( parser ); vector.y = DaoxBinaryParser_DecodeFloatLE( parser ); vector.z = DaoxBinaryParser_DecodeFloatLE( parser ); DaoxLight_Move( light, vector ); printf( "light: " ); DaoxVector3D_Print( & vector ); break; case 0x4700 : camera = DaoxCamera_New(); DaoxScene_AddNode( self, (DaoxSceneNode*) camera ); vector.x = DaoxBinaryParser_DecodeFloatLE( parser ); vector.y = DaoxBinaryParser_DecodeFloatLE( parser ); vector.z = DaoxBinaryParser_DecodeFloatLE( parser ); DaoxCamera_Move( camera, vector ); vector2.x = DaoxBinaryParser_DecodeFloatLE( parser ); vector2.y = DaoxBinaryParser_DecodeFloatLE( parser ); vector2.z = DaoxBinaryParser_DecodeFloatLE( parser ); DaoxCamera_LookAt( camera, vector2 ); x = DaoxBinaryParser_DecodeFloatLE( parser ); /* rotation angle; */ y = DaoxBinaryParser_DecodeFloatLE( parser ); /* camera lens; */ camera->farPlane = 10.0 * sqrt( DaoxVector3D_Dist2( & vector, & vector2 ) ); printf( "camera: " ); DaoxVector3D_Print( & vector ); break; case 0xAFFF : /* Material Block */ material = DaoxMaterial_New(); DArray_Append( self->materials, material ); break; case 0xA000 : /* Material name */ DString_SetMBS( string, DaoxBinaryParser_DecodeString( parser ) ); MAP_Insert( self->materialNames, string, self->materials->size - 1 ); break; case 0xA010 : /* ambient color */ colortype = AMBIENT; break; case 0xA020 : /* diffuse color */ colortype = DIFFUSE; break; case 0xA030 : /* specular color */ colortype = SPECULAR; break; case 0x0010 : /* RGB color (float format) */ case 0x0011 : /* RGB color (24bits) */ switch( parentid ){ case 0x4600 : color = & light->intensity; break; case 0xA010 : color = & material->ambient; break; case 0xA020 : color = & material->diffuse; break; case 0xA030 : color = & material->specular; break; default : color = & tmpColor; break; } color->alpha = 1.0; if( chunkid == 0x0010 ){ color->red = DaoxBinaryParser_DecodeFloatLE( parser ); color->green = DaoxBinaryParser_DecodeFloatLE( parser ); color->blue = DaoxBinaryParser_DecodeFloatLE( parser ); }else{ color->red = parser->source[0] / 255.0; color->green = parser->source[1] / 255.0; color->blue = parser->source[2] / 255.0; parser->source += chunklen - 6; } break; case 0xA040 : /* shininess */ case 0xA041 : /* shin. strength */ case 0xA050 : /* transparency */ case 0xA052 : /* trans. falloff */ case 0xA053 : /* reflect blur */ case 0xA100 : /* material type */ case 0xA084 : /* self illum */ case 0xB000 : /* Keyframer Chunk */ parser->source += chunklen - 6; break; case 0xA200 : texture = DaoxTexture_New(); MAP_Insert( self->textureNames, string, self->textures->size ); DArray_Append( self->textures, texture ); DaoxMaterial_SetTexture( material, texture ); break; case 0xA300 : DString_SetMBS( string, DaoxBinaryParser_DecodeString( parser ) ); DaoxTexture_LoadImage( texture, string->mbs ); printf( "texture: %s %i %i\n", string->mbs, texture->image->width, texture->image->height ); break; case 0x0030 : amount = DaoxBinaryParser_DecodeUInt16LE( parser ) / 100.0; printf( "%f\n", amount ); //if( parentid == 0xA200 ) break; default : parser->source += chunklen - 6; break; } } if( model ){ DaoxMesh_UpdateTree( mesh, 0 ); DaoxMesh_ResetBoundingBox( mesh ); DaoxModel_SetMesh( model, mesh ); DaoxScene_AddNode( self, (DaoxSceneNode*) model ); } DaoxPlainArray_Delete( vertices ); DaoxPlainArray_Delete( triangles ); DArray_Delete( integers ); DArray_Delete( chunkids ); DArray_Delete( chunkends ); DArray_Delete( faceCounts ); DString_Delete( string ); } void DaoxScene_Load3DS( DaoxScene *self, const char *file ) { DString *source = DString_New(1); FILE *fin = fopen( file, "r" ); if( fin == NULL ) return; // TODO: Error; DaoFile_ReadAll( fin, source, 1 ); DaoxScene_Parse3DS( self, source ); DString_Delete( source ); }
34.147341
136
0.695917
[ "mesh", "object", "vector", "model", "transform", "3d" ]
30b21cfb9becf78290de56240170627a5aee9c13
4,052
h
C
3rdparty/webkit/Source/WebCore/loader/ThreadableLoader.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
3rdparty/webkit/Source/WebCore/loader/ThreadableLoader.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
3rdparty/webkit/Source/WebCore/loader/ThreadableLoader.h
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "ResourceLoaderOptions.h" #include <wtf/Noncopyable.h> #include <wtf/RefPtr.h> #include <wtf/text/AtomicString.h> namespace WebCore { class ResourceError; class ResourceRequest; class ResourceResponse; class ScriptExecutionContext; class ThreadableLoaderClient; enum PreflightPolicy { ConsiderPreflight, ForcePreflight, PreventPreflight }; enum class ContentSecurityPolicyEnforcement { DoNotEnforce, EnforceChildSrcDirective, EnforceConnectSrcDirective, EnforceScriptSrcDirective, }; enum class ResponseFilteringPolicy { Enable, Disable, }; struct ThreadableLoaderOptions : ResourceLoaderOptions { ThreadableLoaderOptions(); ThreadableLoaderOptions(const ResourceLoaderOptions&, PreflightPolicy, ContentSecurityPolicyEnforcement, String&& initiator, ResponseFilteringPolicy); ~ThreadableLoaderOptions(); ThreadableLoaderOptions isolatedCopy() const; PreflightPolicy preflightPolicy { ConsiderPreflight }; ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement { ContentSecurityPolicyEnforcement::EnforceConnectSrcDirective }; String initiator; // This cannot be an AtomicString, as isolatedCopy() wouldn't create an object that's safe for passing to another thread. ResponseFilteringPolicy filteringPolicy { ResponseFilteringPolicy::Disable }; }; // Useful for doing loader operations from any thread (not threadsafe, // just able to run on threads other than the main thread). class ThreadableLoader { WTF_MAKE_NONCOPYABLE(ThreadableLoader); public: static void loadResourceSynchronously(ScriptExecutionContext&, ResourceRequest&&, ThreadableLoaderClient&, const ThreadableLoaderOptions&); static RefPtr<ThreadableLoader> create(ScriptExecutionContext&, ThreadableLoaderClient&, ResourceRequest&&, const ThreadableLoaderOptions&, String&& referrer = String()); virtual void cancel() = 0; void ref() { refThreadableLoader(); } void deref() { derefThreadableLoader(); } static void logError(ScriptExecutionContext&, const ResourceError&, const String&); protected: ThreadableLoader() = default; virtual ~ThreadableLoader() = default; virtual void refThreadableLoader() = 0; virtual void derefThreadableLoader() = 0; }; } // namespace WebCore
40.929293
178
0.739882
[ "object" ]
30b62867ac397e4729b9516021ead64613fa447e
63,984
h
C
printscan/faxsrv/print/faxprint/faxdrv/win9x/ddk/printer/inc/minidriv.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/faxsrv/print/faxprint/faxdrv/win9x/ddk/printer/inc/minidriv.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/faxsrv/print/faxprint/faxdrv/win9x/ddk/printer/inc/minidriv.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**************************************************************************** * * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * * PURPOSE. * * * * Copyright (C) 1993-95 Microsoft Corporation. All Rights Reserved. * * * ****************************************************************************/ //----------------------------------------------------------------------------- // Filename: minidriv.h // // This file contains definitions for tables contained in the resource file // of the Mini Drivers. It should be shared by both UNITOOL and UNIDRV. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Mindrvrc.h contains resource type values for minidrivers //----------------------------------------------------------------------------- #include <mindrvrc.h> //***************************************************************************** // DATAHDR is at the beginning of each Mini Driver, describes where the rest // of the strcutures are, their size, count, etc. //***************************************************************************** typedef struct { short sOffset; // offset from the beginning of this resource // to obtain a table entry short sLength; // length of each element in the table short sCount; // number of elements in the table. } HEADERENTRY; //----------------------------------------------------------------------------- // index into array of header entry in DATAHDR //----------------------------------------------------------------------------- #define HE_MODELDATA 0 #define HE_RESOLUTION 1 #define HE_PAPERSIZE 2 #define HE_PAPERQUALITY 3 #define HE_PAPERSOURCE 4 #define HE_PAPERDEST 5 #define HE_TEXTQUAL 6 #define HE_COMPRESSION 7 #define HE_FONTCART 8 #define HE_PAGECONTROL 9 #define HE_CURSORMOVE 10 #define HE_FONTSIM 11 #define HE_DEVCOLOR 12 #define HE_RECTFILL 13 #define HE_DOWNLOADINFO 14 #define HE_VECTPAGE 15 #define HE_CAROUSEL 16 #define HE_PENINFO 17 #define HE_LINEINFO 18 #define HE_BRUSHINFO 19 #define HE_VECTOUTPUT 20 #define HE_POLYVECTOUTPUT 21 #define HE_VECTSUPPORT 22 #define HE_IMAGECONTROL 23 #define HE_PRINTDENSITY 24 #define HE_COLORTRC 25 #define HE_RESERVED1 26 #define HE_RESERVED2 27 #define HE_RESERVED3 28 #define HE_RESERVED4 29 #define MAXHE 30 #define MAXHE_GPC2 15 typedef struct // size is 180 bytes { short sMagic; // reserved, must be 0x7F00 WORD wVersion; // GPC file version # POINT ptMaster; // Horizontal & Vertical Master Units DWORD loHeap; // offset from beginning of file to HEAP data DWORD dwFileSize; // size of file in bytes WORD fTechnology; // flags for special technologies WORD fGeneral; // misc flags char rgchRes[10]; // 10 bytes reserved short sMaxHE; // header entry count HEADERENTRY rghe[MAXHE]; } DATAHDR, *PDH, far *LPDH; #define GPC_VERSION3 0x0300 // GPC file version 3 #define GPC_VERSION2 0x0200 // GPC file version 2 #define GPC_VERSION 0x0300 // current GPC file version # //------------------------------------------- // fTechnology--used as an ID, not a bitfield //------------------------------------------- #define GPC_TECH_DEFAULT 0 // Default technology #define GPC_TECH_PCL4 1 // Uses PCL level 4 or above #define GPC_TECH_CAPSL 2 // Uses CaPSL level 3 or above #define GPC_TECH_PPDS 3 // Uses PPDS #define GPC_TECH_TTY 4 // TTY printer--user configurable #define GPC_TECH_DBCS 5 // Uses DBCS PDL printer //-------------------- // fGeneral //-------------------- #define GPC_GEN_PRIVATE_HELP 0x0001 // this driver has a private help // file named <driver>.hlp #define GPC_GEN_DRAFT_SINGLE 0x0002 // Only 1 font in draft mode //----------------------------------------------------------------------------- // OCD are offsets into the heap to obtain a CD structure //----------------------------------------------------------------------------- typedef WORD OCD; typedef OCD far * LPOCD; // far ptr to OCD typedef DWORD LOCD; // double word offset to a CD typedef WORD OOCD; // offset to table of OCD's. //***************************************************************************** // // MODELDATA contains information describing the attributes and capabilities // of a single printer model. // //***************************************************************************** //----------------------------------------------------------------------------- // MODELDATA.rgoi[] index values //----------------------------------------------------------------------------- #define MD_OI_FIRST MD_OI_PORT_FONTS #define MD_OI_PORT_FONTS 0 #define MD_OI_LAND_FONTS 1 #define MD_OI_RESOLUTION 2 #define MD_OI_PAPERSIZE 3 #define MD_OI_PAPERQUALITY 4 #define MD_OI_PAPERSOURCE 5 #define MD_OI_PAPERDEST 6 #define MD_OI_TEXTQUAL 7 #define MD_OI_COMPRESSION 8 #define MD_OI_FONTCART 9 #define MD_OI_COLOR 10 #define MD_OI_MEMCONFIG 11 #define MD_OI_MAX 12 // // MODELDATA.rgoi2[] index values // #define MD_OI2_PENINFO 0 #define MD_OI2_IMAGECONTROL 1 #define MD_OI2_PRINTDENSITY 2 #define MD_OI2_COLORTRC 3 #define MD_OI2_RESERVED1 4 #define MD_OI2_MAX 5 //----------------------------------------------------------------------------- // MODELDATA.rgi[] index values //----------------------------------------------------------------------------- #define MD_I_PAGECONTROL 0 #define MD_I_CURSORMOVE 1 #define MD_I_FONTSIM 2 #define MD_I_RECTFILL 3 #define MD_I_DOWNLOADINFO 4 #define MD_I_VECTPAGE 5 #define MD_I_CAROUSEL 6 #define MD_I_LINEINFO 7 #define MD_I_BRUSHINFO 8 #define MD_I_VECTOUTPUT 9 #define MD_I_POLYVECTOUTPUT 10 #define MD_I_VECTSUPPORT 11 #define MD_I_RESERVED1 12 #define MD_I_RESERVED2 13 #define MD_I_RESERVED3 14 #define MD_I_RESERVED4 15 #define MD_I_MAX 16 // 9/20/93 ZhanW // define some constants help uniform access of rgoi and rgoi2 arrays. // When more indices are used in rgoi2 array, make sure to add new define's. #define MD_OI_OI2 (MD_OI_MAX + MD_I_MAX) #define MD_OI_PENINFO (MD_OI_OI2 + MD_OI2_PENINFO) #define MD_OI_IMAGECONTROL (MD_OI_OI2 + MD_OI2_IMAGECONTROL) #define MD_OI_PRINTDENSITY (MD_OI_OI2 + MD_OI2_PRINTDENSITY) #define MD_OI_COLORTRC (MD_OI_OI2 + MD_OI2_COLORTRC) #define MD_OI_RESERVED (MD_OI_OI2 + MD_OI2_RESERVED) #define MD_OI_TOTALMAX (MD_OI_OI2 + MD_OI2_MAX) typedef struct { short cbSize; // size of MODELDATA, 152 bytes short sIDS; // stringtable ID for model name WORD fGeneral; // General printer capabilities WORD fCurves; // Curve Capabilities WORD fLines; // Line Capabilities WORD fPolygonals; // Polygonal Capabilities WORD fText; // Text Capabilities WORD fClip; // Clipping Capabilities WORD fRaster; // Raster Capabilities WORD fLText; // Text Capabilities in landscape mode short sLeftMargin; // Unprintable minimum left margin. short sMaxPhysWidth; // Maximum physical page width POINT ptMax; // Maximum X & Y printable dimensions in master units POINT ptMin; // Minimum X & Y page dimensions in master units short sDefaultFontID; // Default font resource ID short sLookAhead; // Size of Lookahead region short sMaxFontsPage; // Max number of fonts printer can place on single page // -1 if no limit short sCartSlots; // Number of cartridge slots on printer short sDefaultCTT; short rgoi[MD_OI_MAX]; // list of offsets to index lists short rgi[MD_I_MAX]; // list of indices. // The following fields are added in GPC 3.0 short rgoi2[MD_OI2_MAX];// Orphans from rgoi (here due to compatibility) short orgoiDefaults; // Offset to list of defaults for RGOI & RGOI2 WORD wReserved; // Needed for alignment DWORD dwICMManufacturer; // id to match ICC profiles against DWORD dwICMModel; // id to match ICC profiles against DWORD rgdwReserved[8]; // 32 bytes reserved for future use } MODELDATA, *PMODELDATA, FAR * LPMODELDATA; //----------------------------------------------------------------------------- // MODELDATA.fGeneral flag values //----------------------------------------------------------------------------- #define MD_SERIAL 0x0001 // must output text serially such // as dotmatrix printers //#define MD_PARAMETERIZE 0x0002 // supports parameterized escape codes #define MD_RESERVED 0x0002 // MD_PARAMETERIZE is Never used 1/4/93 #define MD_ROTATE_FONT_ABLE 0x0004 // can rotate hardware fonts #define MD_COPIES 0x0008 // supports multiple copies #define MD_DUPLEX 0x0010 // supports duplexing #define MD_NO_ADJACENT 0x0020 // old model, cannot print adjacent pins #define MD_LANDSCAPE_GRX_ABLE 0x0040 // can rotate raster graphics #define MD_ALIGN_BASELINE 0x0080 // text output are algned on the // baseline, not top of char #define MD_FONT_MEMCFG 0x0100 // Mem ref'd @ rgoi[MD_OI_MEMCONFIG] // used for download fonts only. #define MD_LANDSCAPE_RT90 0x0200 // landscape is portrait rotated // 90 degress counter-clockwise, i.e. the end of a page is printed // first. The default is 270 degrees, i.e. the beginning of a // page is printed first. !!!For printers which do not have the // set-orientation command (i.e. only have portrait mode), this // bit should NOT be set. UNIDRV will rotate the graphics and // the beginning of a page will come out first. #define MD_USE_CURSOR_ORIG 0x0400 // use cursor origins in // PAPERSIZE to calculate the print origin. The default // cursor origin is the upper left corner of the printable area. #define MD_WHITE_TEXT 0x0800 // can print white text on black // bkgrd. Cmds from DEVCOLOR struct. #define MD_PCL_PAGEPROTECT 0x1000 // provide PCL5-style page protection #define MD_MARGINS 0x2000 // allow the user to set paper // unprintable area. On some printers (such // as Epson, the user could manipulate the // printer to have different margins than // the default. Add this bit for Win3.0 // driver compatibility. #define MD_CMD_CALLBACK 0x4000 // Model requires fnOEMGetCmd callback #define MD_MEMRES 0x8000 // User may reserve printer memory //***************************************************************************** // // RESOLUTION contains information needed to compose bitmap images on the printer. // There is one RESOLUTION structure defined for each supported printer resolution. // RESOLUTION array should be arranged from the highest resolution to the lowest // resolution. It is also the order that will be displayed in the dialog box. // This strucuture becomes part of the physical device block. // //***************************************************************************** //----------------------------------------------------------------------------- // RESOLUTION.rgocd[] index values //----------------------------------------------------------------------------- #define RES_OCD_SELECTRES 0 #define RES_OCD_BEGINGRAPHICS 1 #define RES_OCD_ENDGRAPHICS 2 #define RES_OCD_SENDBLOCK 3 #define RES_OCD_ENDBLOCK 4 #define RES_OCD_MAX 5 typedef struct { short cbSize; // size of RESOLUTION, 40 bytes short sIDS; // String ID for displaying resolution WORD fDump; // Dump method flags. WORD fBlockOut; // Block out method flags. WORD fCursor; // Cursor position flags. short iDitherBrush; // selected brush for dithering POINT ptTextScale; // relationship between master units and text units. POINT ptScaleFac; // relationship between graphics and text // scale factors. expressed in powers of 2. short sNPins; // Minimum height of the image to be rendered // together. short sPinsPerPass; // Physical number of pins fired in one pass. short sTextYOffset; // offset from top of graphics output that of text // output short sMinBlankSkip; // Min. # of bytes of null data that must occur before // compression (strip null data only) will occur short sSpotDiameter; // size of dot at this resolution OCD rgocd[RES_OCD_MAX]; } RESOLUTION, *PRESOLUTION, FAR * LPRESOLUTION; //----------------------------------------------------------------------------- // RESOLUTION.fDump values (low byte: graphics-specific; high byte: general) //----------------------------------------------------------------------------- #define RES_DM_GDI 0x0040 // GDI bitmap format #define RES_DM_LEFT_BOUND 0x0080 // Optimize by bounding rect #define RES_DM_COLOR 0x0100 // Color support available this resolution #define RES_DM_DOWNLOAD_OUTLINE 0x0200 // outline support avail in this resolution //----------------------------------------------------------------------------- // RESOLUTION.fBlockOut values //----------------------------------------------------------------------------- #define RES_BO_LEADING_BLNKS 0x0001 // Strip leading blanks if sMinBlankSkip // or more bytes of null data occur #define RES_BO_TRAILING_BLNKS 0x0002 // Strip trailing blanks if sMinBlankSkip // or more bytes of null data occur #define RES_BO_ENCLOSED_BLNKS 0x0004 // Strip enclosed blanks if sMinBlankSkip // or more bytes of null data occur #define RES_BO_RESET_FONT 0x0008 // Must reselect font after // blockout command // Removed ... LinS 3/08/91 // #define RES_BO_3BYTESIN4 0x0010 // each pixel is expressed in 4 bytes #define RES_BO_UNIDIR 0x0020 // send unidir #define RES_BO_NO_ADJACENT 0x0040 // no adjacent pins can be fired // block out command #define RES_BO_RESET_CMP 0x0080 // must reset compression when entering // graphics mode #define RES_BO_OEMGRXFILTER 0x4000 // use oem supplied graphics filter #define RES_BO_MULTIPLE_ROWS 0x8000 // Multiple lines of data can be sent // with the RES_OCD_SENDBLOCK command. //----------------------------------------------------------------------------- // RESOLUTION.fCursor values //----------------------------------------------------------------------------- #define RES_CUR_X_POS_ORG 0x0001 // X Position is at X start point // of graphic data after rendering data #define RES_CUR_X_POS_AT_0 0x0002 // X position at leftmost place // on page after rendering data #define RES_CUR_Y_POS_AUTO 0x0004 // Y position automatically moves // to next Y row #define RES_CUR_CR_GRX_ORG 0x0008 // CR moves X pos to X start point of // of graphic data //----------------------------------------------------------------------------- // RESOLUTION.iDitherBrush flag values //----------------------------------------------------------------------------- #define RES_DB_NONE 0 #define RES_DB_COARSE 1 #define RES_DB_FINE 2 #define RES_DB_LINEART 3 #define RES_DB_ERRORDIFFUSION 4 #define RES_DB_MAX RES_DB_ERRORDIFFUSION // last defined ditherbrush //***************************************************************************** // // PAPERSIZE contains physical paper sizes and unprintable margins // //***************************************************************************** //----------------------------------------------------------------------------- // PAPERSIZE.rgocd[] index values //----------------------------------------------------------------------------- #define PSZ_OCD_SELECTPORTRAIT 0 #define PSZ_OCD_SELECTLANDSCAPE 1 #define PSZ_OCD_PAGEPROTECT_ON 2 #define PSZ_OCD_PAGEPROTECT_OFF 3 #define PSZ_OCD_RESERVED1 4 #define PSZ_OCD_RESERVED2 5 #define PSZ_OCD_MAX 6 typedef struct { short cbSize; // size of PAPERSIZE, 60 bytes. short sPaperSizeID; // If sPaperSizeID is < 256 then it's predefined. // If it's = 256, allow user defined sizes. // If it's >= 257, it's driver-defined & is the // string ID to name this driver-defined PAPERSIZE WORD fGeneral; // General flag to describe info about this size WORD fPaperType; // Bit field to describe this size, used by PAPERSRC POINT ptSize; // X & Y paper size dimension in master units. RECT rcMargins; // Specifies the unprintable margins in master units. // (Portrait mode in new spec) POINT ptCursorOrig; // Cursor origin relative to physical page origin. POINT ptLCursorOrig; // Cursor origin relative to physical page origin // in landscape. OCD rgocd[PSZ_OCD_MAX]; // Command Descriptors RECT rcLMargins; // Specifies the unprintable margins in master units // when printing in landscape mode. POINT ptVectOffset; // Offset (in master units) from vector 0,0 to // UL corner of page in portrait mode POINT ptLVectOffset; // Offset (in master units) from vector 0,0 to // UL corner of page in landscape mode WORD wYSizeUnit; // Base unit for custom paper size dimensions WORD wPageProtMem; // Amount of mem (in KBs) PAGEPROTECT_ON uses } PAPERSIZE, * PPAPERSIZE, FAR * LPPAPERSIZE; //----------------------------------------------------------------------------- // PAPERSIZE.fGeneral flag values //----------------------------------------------------------------------------- #define PS_CENTER 0x0001 // center the printable area along the paper path #define PS_ROTATE 0x0002 // rotate X & Y dimensions #define PS_SUGGEST_LNDSCP 0x0004 // suggest landscape mode #define PS_EJECTFF 0x0008 // eject page via CURSORMOVE.rgocd[CM_OCD_FF] //----------------------------------------------------------------------------- // PAPERSIZE.fPaperType flag values //----------------------------------------------------------------------------- #define PS_T_STD 0x0001 #define PS_T_LARGE 0x0002 #define PS_T_ENV 0x0004 #define PS_T_LRGENV 0x0008 #define PS_T_ROLL 0x0010 #define PS_T_OEM1 0x0400 #define PS_T_OEM2 0x0800 #define PS_T_OEM3 0x1000 #define PS_T_OEM4 0x2000 #define PS_T_OEM5 0x4000 #define PS_T_OEM6 0x8000 //***************************************************************************** // // PAPERQUALITY contains an ID & OCD // //***************************************************************************** typedef struct { short cbSize; // size of PAPERQUALITY, 12 bytes. short sPaperQualID; // DWORD dwReserved; // reserved for future use WORD wReserved; // " " OCD ocdSelect; // Command Descriptor to select this Paper Quality. } PAPERQUALITY, * PPAPERQUALITY, FAR * LPPAPERQUALITY; //***************************************************************************** // // PAPERSOURCE contains information needed to select a feed methods and // the margin that might be introduced by the feed method. // //***************************************************************************** typedef struct { short cbSize; // size of PAPERSOURCE, 16 bytes short sPaperSourceID; // If sPaperSourceID <= 256 then it's predefined // by genlib, otherwise, it is the string ID. WORD fGeneral; WORD fPaperType; // Bit field to describe this size, used by PAPERSRC short sTopMargin; // Top margin introduced by the feed method. short sBottomMargin; // Bottom margin introduced by the feed method. short sBinAdjust; // Describes adjustments supported by bin OCD ocdSelect; // Command Descriptor to select this Paper source. } PAPERSOURCE, * PPAPERSOURCE, FAR * LPPAPERSOURCE; //----------------------------------------------------------------------------- // PAPERSOURCE.fGeneral flag values //----------------------------------------------------------------------------- #define PSRC_EJECTFF 0x0001 #define PSRC_MAN_PROMPT 0x0002 //***************************************************************************** // // PAPERDEST contains information needed to select a paper out bin/tray // //***************************************************************************** typedef struct { short cbSize; // size of PAPERDEST, 8 bytes short sID; // If sID <= 256 then it's predefined // otherwise, it is the stringtable ID. short fGeneral; // General purpose Bit field OCD ocdSelect; // Command Descriptor to select this attribute. } PAPERDEST, * PPAPERDEST, FAR * LPPAPERDEST; //----------------------------------------------------------------------------- // PAPERDEST.fGeneral flag values //----------------------------------------------------------------------------- #define PDST_JOBSEPARATION 0x0001 //***************************************************************************** // // TEXTQUALITY contains information needed to select a text quality attribute // //***************************************************************************** typedef struct { short cbSize; // size of TEXTQUALITY, 8 bytes short sID; // If sID <= 256 then it's predefined // otherwise, it is the string ID. short fGeneral; // General purpose Bit field OCD ocdSelect; // Command Descriptor to select this text quality. } TEXTQUALITY, * PTEXTQUALITY, FAR * LPTEXTQUALITY; //***************************************************************************** // // COMPRESSMODE // //***************************************************************************** //----------------------------------------------------------------------------- // COMPRESSMODE.rgocd[] index values //----------------------------------------------------------------------------- #define CMP_OCD_BEGIN 0 #define CMP_OCD_END 1 #define CMP_OCD_MAX 2 typedef struct { short cbSize; // size of COMPRESSMODE, 8 bytes WORD iMode; // ID for type of commpression mode OCD rgocd[CMP_OCD_MAX]; // Offset to commands } COMPRESSMODE, *PCOMPRESSMODE, FAR * LPCOMPRESSMODE; //----------------------------------------------------------------------------- // COMPRESSMODE.wModeID flags //----------------------------------------------------------------------------- #define CMP_ID_FIRST CMP_ID_RLE #define CMP_ID_RLE 1 #define CMP_ID_TIFF40 2 #define CMP_ID_DELTAROW 3 #define CMP_ID_BITREPEAT 4 #define CMP_ID_FE_RLE 5 #define CMP_ID_LAST CMP_ID_FE_RLE //***************************************************************************** // // FONTCART // //***************************************************************************** #define FC_ORGW_PORT 0 #define FC_ORGW_LAND 1 #define FC_ORGW_MAX 2 typedef struct { short cbSize; // size of FONTCART, 12 bytes WORD sCartNameID; // stringtable ID for cartridge name WORD orgwPFM[FC_ORGW_MAX];// array of offsets to array of indices // of PFM resources WORD fGeneral; // General bit flags WORD wReserved; // for DWORD alignment } FONTCART, * PFONTCART, FAR * LPFONTCART; //#define FC_GEN_RESIDENT 0x0001 // resident font cart //***************************************************************************** // // PAGECONTROL // //***************************************************************************** //----------------------------------------------------------------------------- // PAGECONTROL.rgocd[] index values //----------------------------------------------------------------------------- #define PC_OCD_BEGIN_DOC 0 #define PC_OCD_BEGIN_PAGE 1 #define PC_OCD_DUPLEX_ON 2 #define PC_OCD_ENDDOC 3 #define PC_OCD_ENDPAGE 4 #define PC_OCD_DUPLEX_OFF 5 #define PC_OCD_ABORT 6 #define PC_OCD_PORTRAIT 7 #define PC_OCD_LANDSCAPE 8 #define PC_OCD_MULT_COPIES 9 #define PC_OCD_DUPLEX_VERT 10 #define PC_OCD_DUPLEX_HORZ 11 #define PC_OCD_PRN_DIRECTION 12 #define PC_OCD_JOB_SEPARATION 13 #define PC_OCD_MAX 14 typedef struct { short cbSize; // size of PAGECONTROL, 36 bytes short sMaxCopyCount; // max # of copies w/ PC_OCD_MULT_COPIES WORD fGeneral; // General bit flags WORD orgwOrder; OCD rgocd[PC_OCD_MAX]; } PAGECONTROL, * PPAGECONTROL, FAR * LPPAGECONTROL; //----------------------------------------------------------------------------- // PAGECONTROL.owOrder index values //----------------------------------------------------------------------------- #define PC_ORD_BEGINDOC 1 #define PC_ORD_ORIENTATION 2 #define PC_ORD_MULT_COPIES 3 #define PC_ORD_DUPLEX 4 #define PC_ORD_DUPLEX_TYPE 5 #define PC_ORD_TEXTQUALITY 6 #define PC_ORD_PAPER_SOURCE 7 #define PC_ORD_PAPER_SIZE 8 #define PC_ORD_PAPER_DEST 9 #define PC_ORD_RESOLUTION 10 #define PC_ORD_BEGINPAGE 11 #define PC_ORD_SETCOLORMODE 12 #define PC_ORD_PAPER_QUALITY 13 #define PC_ORD_PAGEPROTECT 14 #define PC_ORD_IMAGECONTROL 15 #define PC_ORD_PRINTDENSITY 16 #define PC_ORD_MAX PC_ORD_PRINTDENSITY #define PC_ORD_LAST PC_ORD_PRINTDENSITY //***************************************************************************** // // CURSORMOVE // //***************************************************************************** //----------------------------------------------------------------------------- // CURSORMOVE.rgocd[] index values //----------------------------------------------------------------------------- #define CM_OCD_XM_ABS 0 #define CM_OCD_XM_REL 1 #define CM_OCD_XM_RELLEFT 2 #define CM_OCD_YM_ABS 3 #define CM_OCD_YM_REL 4 #define CM_OCD_YM_RELUP 5 #define CM_OCD_YM_LINESPACING 6 #define CM_OCD_XY_REL 7 #define CM_OCD_XY_ABS 8 #define CM_OCD_CR 9 #define CM_OCD_LF 10 #define CM_OCD_FF 11 #define CM_OCD_BS 12 #define CM_OCD_UNI_DIR 13 #define CM_OCD_UNI_DIR_OFF 14 #define CM_OCD_PUSH_POS 15 #define CM_OCD_POP_POS 16 #define CM_OCD_MAX 17 typedef struct { short cbSize; // size of CURSORMOVE, 44 bytes WORD wReserved; WORD fGeneral; WORD fXMove; WORD fYMove; OCD rgocd[CM_OCD_MAX]; // Array of offsets to commands } CURSORMOVE, *PCURSORMOVE, FAR * LPCURSORMOVE; //----------------------------------------------------------------------------- // CURSORMOVE.fGeneral flag values //----------------------------------------------------------------------------- #define CM_GEN_FAV_XY 0x0002 // CM_OCD_XY_ABS and CM_OCD_XY_REL // move vector CAP to new position //----------------------------------------------------------------------------- // CURSORMOVE.fXmove flag values //----------------------------------------------------------------------------- #define CM_XM_NO_POR_GRX 0x0004 // no x movemnt while in graphics mode, portrait #define CM_XM_NO_LAN_GRX 0x0008 // no x movemnt while in graphics mode, landscape #define CM_XM_RESET_FONT 0x0010 // Font is reset after x movement command #define CM_XM_FAVOR_ABS 0x0080 // favor absolute x command #define CM_XM_REL_LEFT 0x0200 // has relative x to the left #define CM_XM_ABS_NO_LEFT 0x0400 // No left X movement command #define CM_XM_RES_DEPENDENT 0x0800 // X movement in resolution unit, not mu //----------------------------------------------------------------------------- // CURSORMOVE.fYmove flag values //----------------------------------------------------------------------------- #define CM_YM_FAV_ABS 0x0001 #define CM_YM_REL_UP 0x0002 #define CM_YM_NO_POR_GRX 0x0004 // no y movemnt while in graphics mode, portrait #define CM_YM_NO_LAN_GRX 0x0008 // no y movemnt while in graphics mode, landscape #define CM_YM_CR 0x0040 #define CM_YM_LINESPACING 0x0080 #define CM_YM_TRUNCATE 0x0100 // don't compensate for ymovement error #define CM_YM_RES_DEPENDENT 0x0200 // X movement in resolution unit, not mu //***************************************************************************** // // FONTSIMULATION describes various printer commands to enable and disable // various character attributes such as bold, italic, etc. // //***************************************************************************** //----------------------------------------------------------------------------- // FONTSIMULATION.rgocStd[] index values //----------------------------------------------------------------------------- #define FS_OCD_BOLD_ON 0 #define FS_OCD_BOLD_OFF 1 #define FS_OCD_ITALIC_ON 2 #define FS_OCD_ITALIC_OFF 3 #define FS_OCD_UNDERLINE_ON 4 #define FS_OCD_UNDERLINE_OFF 5 #define FS_OCD_DOUBLEUNDERLINE_ON 6 #define FS_OCD_DOUBLEUNDERLINE_OFF 7 #define FS_OCD_STRIKETHRU_ON 8 #define FS_OCD_STRIKETHRU_OFF 9 #define FS_OCD_WHITE_TEXT_ON 10 #define FS_OCD_WHITE_TEXT_OFF 11 #define FS_OCD_SINGLE_BYTE 12 #define FS_OCD_DOUBLE_BYTE 13 #define FS_OCD_VERT_ON 14 #define FS_OCD_VERT_OFF 15 #define FS_OCD_MAX 16 typedef struct { short cbSize; // size of FONTSIMULATION, 44 bytes WORD wReserved; // so DW aligned WORD fGeneral; short sBoldExtra; short sItalicExtra; short sBoldItalicExtra; OCD rgocd[FS_OCD_MAX]; } FONTSIMULATION, * PFONTSIMULATION, FAR * LPFONTSIMULATION; //***************************************************************************** // // DEVCOLOR is the physical color info which describes the device color // capabilities and how to compose colors based on available device colors. // //***************************************************************************** //----------------------------------------------------------------------------- // DEVCOLOR.fGeneral bit flags: //----------------------------------------------------------------------------- #define DC_PRIMARY_RGB 0x0001 // use RGB as 3 primary colors. // Default: use CMY instead. #define DC_EXTRACT_BLK 0x0002 // Separate black ink/ribbon is available. // Default: compose black using CMY. // It is ignored if DC_PRIMARY_RGB is set #define DC_CF_SEND_CR 0x0004 // send CR before selecting graphics // color. Due to limited printer buffer #define DC_SEND_ALL_PLANES 0x0008 // All color plane data must be sent #define DC_SEND_PAGE_PLANE 0x0010 // Color separation required #define DC_EXPLICIT_COLOR 0x0020 // Color must be set before sending // the RES_OCD_SENDBLOCK command. #define DC_SEND_PALETTE 0x0040 // Color palette must be downloaded //----------------------------------------------------------------------------- // One and only one of DEVCOLOR.sPlanes or DEVCOLOR.sBitsPixel must be 1. // // Example: // // DEVCOLOR.sPlanes: // Valid values are: // 1: use the pixel color model. // n (n > 1): use the plane color model. // Ex. for Brother M-1924, n = 4; for PaintJet, n = 3. // // DEVCOLOR.sBitsPixel: // Valid values are: // 1: use the plane color model. // 4, 8, 16, 24: use the pixel color model. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // DEVCOLOR.rgocd array values //----------------------------------------------------------------------------- #define DC_OCD_TC_BLACK 0 #define DC_OCD_TC_RED 1 #define DC_OCD_TC_GREEN 2 #define DC_OCD_TC_YELLOW 3 #define DC_OCD_TC_BLUE 4 #define DC_OCD_TC_MAGENTA 5 #define DC_OCD_TC_CYAN 6 #define DC_OCD_TC_WHITE 7 #define DC_OCD_SETCOLORMODE 8 #define DC_OCD_PC_START 9 #define DC_OCD_PC_ENTRY 10 #define DC_OCD_PC_END 11 #define DC_OCD_PC_SELECTINDEX 12 #define DC_OCD_RESERVED 13 #define DC_OCD_MAX 14 //----------------------------------------------------------------------------- // DEVCOLOR.rgbOrder array values //----------------------------------------------------------------------------- #define DC_PLANE_NONE 0 #define DC_PLANE_RED 1 #define DC_PLANE_GREEN 2 #define DC_PLANE_BLUE 3 #define DC_PLANE_CYAN 4 #define DC_PLANE_MAGENTA 5 #define DC_PLANE_YELLOW 6 #define DC_PLANE_BLACK 7 #define DC_MAX_PLANES 4 typedef struct { short cbSize; // size of DEVCOLOR, 44 bytes WORD fGeneral; // general flag bit field short sPlanes; // # of color planes required short sBitsPixel; // # of bits per pixel (per plane). At least // one of 'sPlanes' and 'sBitsPixel' is 1. WORD orgocdPlanes; // offset to a list of OCD's for sending data // planes. The # of OCD's is equal to 'sPlanes'. // This field is not used in case of pixel // color models. The first command will be // used to send data of the first plane, // and so on. OCD rgocd[DC_OCD_MAX]; // array of Offsets to commands. BYTE rgbOrder[DC_MAX_PLANES]; // order in which color planes are sent WORD wReserved; // For alignment } DEVCOLOR, * PDEVCOLOR, FAR * LPDEVCOLOR; //***************************************************************************** // // RECTFILL // //***************************************************************************** //----------------------------------------------------------------------------- // RECTFILL.rgocd[] index values //----------------------------------------------------------------------------- #define RF_OCD_X_SIZE 0 #define RF_OCD_Y_SIZE 1 #define RF_OCD_GRAY_FILL 2 #define RF_OCD_WHITE_FILL 3 #define RF_OCD_HATCH_FILL 4 #define RF_OCD_MAX 5 typedef struct { short cbSize; // size of RECTFILL, 20 bytes WORD fGeneral; WORD wMinGray; WORD wMaxGray; OCD rgocd[RF_OCD_MAX]; // Offset to Command Descriptor WORD wReserved; } RECTFILL, *PRECTFILL, FAR * LPRECTFILL; //----------------------------------------------------------------------------- // RECTFILL.fGeneral flag values //----------------------------------------------------------------------------- #define RF_WHITE_ABLE 0x0001 // White rule exists #define RF_MIN_IS_WHITE 0x0002 // min. graylevel = white rule #define RF_CUR_X_END 0x0100 // X Position is at X end point // of fill area after rendering #define RF_CUR_Y_END 0x0200 // Y position is at Y end point // of fill area after rendering // default is no chg of position //***************************************************************************** // // DOWNLOADINFO describes that way in which unidrv should instruct the font // installer to handle downloading soft fonts. It contains OCDs for all // appropriate codes. // //***************************************************************************** //----------------------------------------------------------------------------- // DOWNLOADINFO.rgocd[] index values //----------------------------------------------------------------------------- #define DLI_OCD_RESERVED 0 #define DLI_OCD_BEGIN_DL_JOB 1 #define DLI_OCD_BEGIN_FONT_DL 2 #define DLI_OCD_SET_FONT_ID 3 #define DLI_OCD_SEND_FONT_DESCRIPTOR 4 #define DLI_OCD_SELECT_FONT_ID 5 #define DLI_OCD_SET_CHAR_CODE 6 #define DLI_OCD_SEND_CHAR_DESCRIPTOR 7 #define DLI_OCD_END_FONT_DL 8 #define DLI_OCD_MAKE_PERM 9 #define DLI_OCD_MAKE_TEMP 10 #define DLI_OCD_END_DL_JOB 11 #define DLI_OCD_DEL_FONT 12 #define DLI_OCD_DEL_ALL_FONTS 13 #define DLI_OCD_SET_SECOND_FONT_ID 14 #define DLI_OCD_SELECT_SECOND_FONT_ID 15 #define DLI_OCD_MAX 16 typedef struct { short cbSize; // size of DOWNLOADINFO, 56 bytes WORD wReserved; // for DWORD alignment WORD fGeneral; // general bit flags WORD fFormat; // describes download font format WORD wIDMin; WORD wIDMax; short cbBitmapFontDsc; WORD wReserved1; // Formerly: short cbScaleFontDsc; short cbBitmapCharDsc; WORD wReserved2; // Formerly: short cbScaleCharDsc; short sMaxFontCount; WORD wReserved3; OCD rgocd[DLI_OCD_MAX]; } DOWNLOADINFO, * PDOWNLOADINFO, FAR * LPDOWNLOADINFO; //----------------------------------------------------------------------------- // DOWNLOADINFO.fGeneral flag values //----------------------------------------------------------------------------- #define DLI_GEN_RESERVED1 0x0001 // No longer used--reserved #define DLI_GEN_MEMORY 0x0002 // printer limits # DL fonts by memory #define DLI_GEN_DLJOB 0x0004 // printer can only DL fonts on per // job basis #define DLI_GEN_DLPAGE 0x0008 // printer can DL fonts on per page // basis // NOTE: if neither of the above 2 flags // are ste, assume DL can happen any time #define DLI_GEN_PT_IDS 0x0010 // use OCD_SET_FONT_ID for specifiy // perm/temp #define DLI_GEN_RESERVED2 0x0020 // No longer used--reserved #define DLI_GEN_RESERVED3 0x0040 // No longer used--reserved #define DLI_GEN_FNTDEL_ANYWHERE 0x0080 // if set, fonts can be deleted at // any point. Default is at page // boundary only #define DLI_GEN_7BIT_CHARSET 0x0100 // printer supports only 7-bit charset //----------------------------------------------------------------------------- // DOWNLOADINFO.fFormat flag values //----------------------------------------------------------------------------- #define DLI_FMT_PCL 0x0001 // PCL printer #define DLI_FMT_INCREMENT 0x0002 // incremental download recommended #define DLI_FMT_PCL_RESSPEC 0x0004 // allow resolution specified bitmap // font download. The X & Y resolutions // are attached to the end of the // regular PCL bitmap font descriptor. #define DLI_FMT_OUTLINE 0x0008 // printer supports outline downloading #define DLI_FMT_PCLETTO 0x0008 // alias for outline downloading (remove later) #define DLI_FMT_CAPSL 0x0010 // Use CaPSL download header #define DLI_FMT_PPDS 0x0020 // Use PPDS download header #define DLI_FMT_CALLBACK 0x0040 // minidriver provide callbacks for // for downloading bitmap fonts. //***************************************************************************** // // VECTPAGE describes information about the vector page and miscellaneous // vector capabilities and commands // //***************************************************************************** //----------------------------------------------------------------------------- // VECTPAGE.rgocd[] index values //----------------------------------------------------------------------------- #define VP_OCD_INIT_VECT 0 #define VP_OCD_ENTER_VECT 1 #define VP_OCD_EXIT_VECT 2 #define VP_OCD_TRANSPARENT 3 #define VP_OCD_OPAQUE 4 #define VP_OCD_ANCHOR 5 #define VP_OCD_SET_CLIPRECT 6 #define VP_OCD_CLEAR_CLIPRECT 7 #define VP_OCD_ENDCAP_FLAT 8 #define VP_OCD_ENDCAP_ROUND 9 #define VP_OCD_ENDCAP_SQUARE 10 #define VP_OCD_JOIN_BEVEL 11 #define VP_OCD_JOIN_MITER 12 #define VP_OCD_JOIN_ROUND 13 #define VP_OCD_RESERVED1 14 #define VP_OCD_RESERVED2 15 #define VP_OCD_RESERVED3 16 #define VP_OCD_RESERVED4 17 #define VP_OCD_MAX 18 typedef struct { WORD cbSize; // Size of VECTPAGE, 44 bytes WORD fGeneral; // General use bitfield POINT ptVectDPI; // Vector units per inch OCD rgocd[VP_OCD_MAX]; // Offsets to commands } VECTPAGE, *PVECTPAGE, FAR *LPVECTPAGE; //----------------------------------------------------------------------------- // VECTPAGE.fGeneral flags //----------------------------------------------------------------------------- #define VP_GEN_X_AXIS_LEFT 0x0001 // Set if plotter's X axis (horizontal) // extends left. Default is to the right #define VP_GEN_Y_AXIS_UP 0x0002 // Sef if plotter's Y axis (vertical) // extends upward. Default is downward. //****************************************************************************** // // CAROUSEL describes carousel characteristics. If the pens are fixed, // this also specifies the colors of each pen. // //****************************************************************************** //------------------------------------------------------------------------------ // CAROUSEL.rgocd[] index values //------------------------------------------------------------------------------ #define CAR_OCD_SELECT_PEN_COLOR 0 #define CAR_OCD_SET_PEN_WIDTH 1 #define CAR_OCD_RETURN_PEN 2 #define CAR_OCD_RESERVED 3 #define CAR_OCD_MAX 4 typedef struct { WORD cbSize; // Size of CAROUSEL, 16 bytes WORD fGeneral; // General purpose bitfield WORD wNumPens; // # of pens in carousel short oiRGBColors; // colors of pens in carousel OCD rgocd[CAR_OCD_MAX]; // commands associated with carousel } CAROUSEL, *PCAROUSEL, FAR *LPCAROUSEL; //------------------------------------------------------------------------------ // CAROUSEL.fGeneral flags //------------------------------------------------------------------------------ #define CAR_GEN_CAROUSEL_LEFT 0x0001 // Set if pen moves to the left of // page when returned to carousel #define CAR_GEN_CAROUSEL_RIGHT 0x0002 // Set if pen moves to the right of // page when returned to carousel #define CAR_GEN_CAROUSEL_TOP 0x0004 // Set if pen moves to the top of // page when returned to carousel #define CAR_GEN_CAROUSEL_BOTTOM 0x0008 // Set if pen moves to the bottom of // page when returned to carousel #define CAR_GEN_CAROUSEL_FIXED 0x0010 // Carousel has fixed set of pens #define CAR_GEN_RETURN_PEN 0x0020 // Pen must be explicitly returned // to the carousel before selecting // a new pen. #define CAR_GEN_VARIABLE_PEN_WIDTH 0x0040 // Set if SET_PEN_WIDTH changes // the width of the (logical) pen // as opposed to informing the // plotter of the physical width. //****************************************************************************** // // PENINFO describes the characteristics of an available pen // //****************************************************************************** //------------------------------------------------------------------------------ // PENINFO.rgocd[] index values //------------------------------------------------------------------------------ typedef struct { WORD cbSize; // Size of PENINFO, 16 bytes WORD fGeneral; // General purpose bitfield DWORD fType; // Surfaces on which pen can draw DWORD dwColor; // RGB color of the pen WORD fThick; // Thickness in which pen is available WORD wIDS; // Stringtable resource for this color's name } PENINFO, *PPENINFO, FAR *LPPENINFO; //------------------------------------------------------------------------------ // PENINFO.fThick values //------------------------------------------------------------------------------ #define PI_FTHICK_18 0x0001 // Pen comes in 0.18mm #define PI_FTHICK_25 0x0002 // Pen comes in 0.25mm #define PI_FTHICK_30 0x0004 // Pen comes in 0.30mm #define PI_FTHICK_35 0x0008 // Pen comes in 0.35mm #define PI_FTHICK_50 0x0010 // Pen comes in 0.50mm #define PI_FTHICK_70 0x0020 // Pen comes in 0.70mm #define PI_FTHICK_100 0x0040 // Pen comes in 1.00mm //------------------------------------------------------------------------------ // PENINFO.fType values depend on the defined paper sources, but reserve // the high bit to indicate that any paper source is valid. //------------------------------------------------------------------------------ #define PI_FTYPE_ANY 0x80000000 //****************************************************************************** // // LINEINFO describes the line style creation and selection commands // //****************************************************************************** //------------------------------------------------------------------------------ // LINEINFO.rgocd[] index values //------------------------------------------------------------------------------ #define LI_OCD_DELETE_LINESTYLE 0 #define LI_OCD_SELECT_NULL 1 #define LI_OCD_SELECT_SOLID 2 #define LI_OCD_CREATE_DASH 3 #define LI_OCD_SELECT_DASH 4 #define LI_OCD_CREATE_DOT 5 #define LI_OCD_SELECT_DOT 6 #define LI_OCD_CREATE_DASHDOT 7 #define LI_OCD_SELECT_DASHDOT 8 #define LI_OCD_CREATE_DASHDOTDOT 9 #define LI_OCD_SELECT_DASHDOTDOT 10 #define LI_OCD_RESERVED1 11 #define LI_OCD_RESERVED2 12 #define LI_OCD_RESERVED3 13 #define LI_OCD_RESERVED4 14 #define LI_OCD_RESERVED5 15 #define LI_OCD_MAX 16 typedef struct { WORD cbSize; // Size of LINEINFO, 40 bytes WORD fGeneral; // General purpose bitfield short sMaxUserDefined; // Max # of line styles that can be defined at once WORD wReserved; // Maintain DWORD alignment OCD rgocd[LI_OCD_MAX]; // Offsets to commands } LINEINFO, *PLINEINFO, FAR *LPLINEINFO; //****************************************************************************** // // BRUSHINFO describes the brush style creation and selection commands // //****************************************************************************** //------------------------------------------------------------------------------ // BRUSHINFO.rgocd[] index values //------------------------------------------------------------------------------ #define BI_OCD_SELECT_NULL 0 #define BI_OCD_SELECT_SOLID 1 #define BI_OCD_SELECT_HS_HORIZONTAL 2 #define BI_OCD_SELECT_HS_VERTICAL 3 #define BI_OCD_SELECT_HS_FDIAGONAL 4 #define BI_OCD_SELECT_HS_BDIAGONAL 5 #define BI_OCD_SELECT_HS_CROSS 6 #define BI_OCD_SELECT_HS_DIAGCROSS 7 #define BI_OCD_CREATE_BRUSHSTYLE_1 8 #define BI_OCD_CREATE_BIT_1 9 #define BI_OCD_CREATE_SEPARATOR_1 10 #define BI_OCD_CREATE_BRUSHSTYLE_2 11 #define BI_OCD_CREATE_BYTE_2 12 #define BI_OCD_SELECT_BRUSHSTYLE 13 #define BI_OCD_DELETE_BRUSHSTYLE 14 #define BI_OCD_CREATE_END_1 15 #define BI_OCD_RESERVED2 16 #define BI_OCD_RESERVED3 17 #define BI_OCD_MAX 18 typedef struct { WORD cbSize; // Size of BRUSHINFO, 40 bytes WORD fGeneral; // General purpose bitfield short sMaxUserDefined; // Max # of user-defined brushes allowed at once WORD wReserved; // Maintain DWORD alignment OCD rgocd[BI_OCD_MAX]; // Offsets to commands } BRUSHINFO, *PBRUSHINFO, FAR *LPBRUSHINFO; //------------------------------------------------------------------------------ // BRUSHINFO.fGeneral flags //------------------------------------------------------------------------------ #define BI_GEN_BRUSHSTYLE1 0x0001 // BRUSHSTYLE1 supported #define BI_GEN_BRUSHSTYLE2 0x0002 // BRUSHSTYLE2 supported #define BI_GEN_BRUSH32x32 0x0004 // Brush size of 32x32 pixels ONLY //****************************************************************************** // // VECTOUTPUT describes the graphic output drawing commands & ordering // //****************************************************************************** //------------------------------------------------------------------------------ // VECTOUTPUT.rgocd[] index values //------------------------------------------------------------------------------ #define VO_OCD_RECTANGLE 0 #define VO_OCD_CIRCLE 1 #define VO_OCD_ELLIPSE 2 #define VO_OCD_C_PIE 3 #define VO_OCD_E_PIE 4 #define VO_OCD_C_ARC 5 #define VO_OCD_E_ARC 6 #define VO_OCD_C_CHORD 7 #define VO_OCD_E_CHORD 8 #define VO_OCD_RESERVED1 9 #define VO_OCD_RESERVED2 10 #define VO_OCD_RESERVED3 11 #define VO_OCD_RESERVED4 12 #define VO_OCD_RESERVED5 13 #define VO_OCD_RESERVED6 14 #define VO_OCD_RESERVED7 15 #define VO_OCD_MAX 16 #define VO_OCD_NUM 9 // # non-reserved VOs typedef struct { WORD cbSize; // Size of VECTOUTPUT, 40 bytes WORD fGeneral; // General purpose bitfield WORD wReserved; // Maintain DWORD alignment short rgoi[VO_OCD_MAX]; // Offsets to arrays of VECTSUPPORT OCD rgocd[VO_OCD_MAX]; // Offsets to commands } VECTOUTPUT, *PVECTOUTPUT, FAR *LPVECTOUTPUT; //****************************************************************************** // // POLYVECTOUTPUT describes the polygon/polyline drawing commands & ordering // //****************************************************************************** //------------------------------------------------------------------------------ // POLYVECTOUTPUT.rgocd[] index values //------------------------------------------------------------------------------ #define PVO_OCD_POLYLINE 0 #define PVO_OCD_ALTPOLYGON 1 #define PVO_OCD_WINDPOLYGON 2 #define PVO_OCD_POLYBEZIER 3 #define PVO_OCD_RESERVED1 4 #define PVO_OCD_RESERVED2 5 #define PVO_OCD_RESERVED3 6 #define PVO_OCD_RESERVED4 7 #define PVO_OCD_MAX 8 #define PVO_OCD_NUM 4 // # non-reserved PVOs //----------------------------------------------------------------------------- // Indices into 2-dimensional array rgocd //----------------------------------------------------------------------------- #define OCD_BEGIN 0 #define OCD_CONTINUE 1 #define OCD_SEPARATOR 2 #define OCD_END 3 #define OCD_MAX 4 typedef struct { WORD cbSize; // sizeof POLYVECTOUTPUT, 88 bytes WORD fGeneral; // General purpose bitfield WORD wPointLimit; // Polygon Point Number Limit WORD wReserved; // Reserved for future use short rgoi[PVO_OCD_MAX]; // Describes which VECTSUPPORTs are used OCD rgocd[PVO_OCD_MAX][OCD_MAX]; // offsets to commands } POLYVECTOUTPUT, *PPOLYVECTOUTPUT, FAR *LPPOLYVECTOUTPUT; //****************************************************************************** // // VECTSUPPORT describes methods used by VECTOUTPUT and POLYVECTOUTPUT // //****************************************************************************** //------------------------------------------------------------------------------ // VECTSUPPORT.rgocd[] index values //------------------------------------------------------------------------------ #define VS_OCD_BEGIN_POLYDEF 0 #define VS_OCD_END_POLYDEF 1 #define VS_OCD_WIND_FILL 2 #define VS_OCD_ALT_FILL 3 #define VS_OCD_STROKE 4 #define VS_OCD_PEN_UP 5 #define VS_OCD_PEN_DOWN 6 #define VS_OCD_RESERVED1 7 #define VS_OCD_RESERVED2 8 #define VS_OCD_RESERVED3 9 #define VS_OCD_MAX 10 // These are used by VECTOUTPUT and POLYVECTOUTPUT to represent their ordering // of pen and brush selection, as well as their OCD or Begin OCD, Continue // OCD, and End OCD combination #define VS_SELECT_PEN -1 #define VS_SELECT_BRUSH -2 #define VS_OCD -3 #define VS_OCD_BEGIN -4 #define VS_OCD_CONTINUE -5 #define VS_OCD_END -6 typedef struct { WORD cbSize; // Size of VECTSUPPORT, 24 bytes WORD fGeneral; // General purpose bitfield short rgocd[VS_OCD_MAX]; // Offsets to commands } VECTSUPPORT, *PVECTSUPPORT, FAR *LPVECTSUPPORT; //***************************************************************************** // // IMAGECONTROL contains information needed to select an image control // //***************************************************************************** typedef struct { short cbSize; // size of IMAGECONTROL, 8 bytes short sID; // If sID <= 256 then it's predefined // otherwise, it is the stringtable ID. short fGeneral; // General purpose Bit field OCD ocdSelect; // Command Descriptor to select this attribute. } IMAGECONTROL, * PIMAGECONTROL, FAR * LPIMAGECONTROL; //----------------------------------------------------------------------------- // IMAGECONTROL.fGeneral flag values //----------------------------------------------------------------------------- // None defined //***************************************************************************** // // PRINTDENSITY contains information needed to select an image control // //***************************************************************************** typedef struct { short cbSize; // size of PRINTDENSITY, 8 bytes short sID; // If sID <= 256 then it's predefined // otherwise, it is the stringtable ID. OCD ocdSelect; // Command Descriptor to select this attribute. WORD wReserved; // make the structure DWORD aligned. } PRINTDENSITY, * PPRINTDENSITY, FAR * LPPRINTDENSITY; //***************************************************************************** // // COLORTRC contains rgb transfer curves on PAPERQUALITY and RESOLUTION basis // //***************************************************************************** typedef struct tagColorTRC { short cbSize; // size of COLORTRC, 116 bytes WORD wReserved; // keep everything DWORD aligned WORD fGeneral; WORD wIndexPaperQuality; WORD wIndexResolution; WORD wDitherType; // reserved for dither, set to zero WORD wReserved1; // always a good idea WORD wReserved2; BYTE RGBOrdinates[3][17]; BYTE padding0; // keep everything DWORD aligned BYTE DarkRGBOrdinates[3][17]; BYTE padding1; // keep everything DWORD aligned } COLORTRC, * PCOLORTRC, FAR * LPCOLORTRC; // flags for COLORTRC #define CTRC_NO_CHECKER_BOARD 0x0001 #define CTRC_NO_BLACK_PEN 0x0002 // Offsets into arrays of ORDINATELIST #define TRC_RED 0 #define TRC_GREEN 1 #define TRC_BLUE 2 //***************************************************************************** //***************************************************************************** // // CD - Command Descriptor is used in many of the following structures to // reference a particular set of printer command/escape codes // used to select paper sizes, graphics resolutions, character attributes, // etc. The actual command string (cd.wLength bytes) follows immediately // after the CD. which is immediately followed by cd.wCount EXTCD // structures. In earliser versions of this specification, the EXTCD // structures were not WORD aligned if the command string was an odd // number of bytes. Beginning with GPC version 3, the EXTCD structures // will be WORD-aligned. This is done by adding an additional NULL after // the end of an odd-length command string. cd.wCount does not include // this additional NULL. // //***************************************************************************** //***************************************************************************** typedef struct { BYTE fGeneral; // General purpose bitfield BYTE bCmdCbId; // Callback ID; 0 iff no callback WORD wCount; // # of EXTCD structures following WORD wLength; // length of the command } CD, *PCD, FAR * LPCD; //------------------------------------------------------------------------------ // CD.fGeneral flags //------------------------------------------------------------------------------ #define CMD_GEN_MAY_REPEAT 0x0001 // Command may be sent multiple times if // the parameter exceeds sMax #define CMD_MARKER '%' //----------------------------------------------------------------------------- // EXTCD - Extended portion of the Command Descriptor. cd.sCount of these // structures follow any CD. // // valueOut=(((valueIn+sPreAdd)*sUnitMult) $ sUnitDiv)+sUnitAdd // // where $ is either division or modulo, depending on XCD_GEN_MODULO // // Values that are 0 are ignored. //----------------------------------------------------------------------------- typedef struct { WORD fGeneral; // General purpose flags short sUnitDiv; short sUnitMult; short sUnitAdd; short sPreAdd; short sMax; short sMin; WORD wParam; // Parameter ordinal for multiple parameters } EXTCD, *PEXTCD, FAR * LPEXTCD; #define XCD_GEN_RESERVED 0x0001 // Previously defined, now unused #define XCD_GEN_NO_MAX 0x0002 // Set iff there is no max (sMax ignored) #define XCD_GEN_NO_MIN 0x0004 // Set iff there is no min (sMin ignored) #define XCD_GEN_MODULO 0x0008 // Set if divide should be modulo //----------------------------------------------------------------------------- // pre-defined text qualities //----------------------------------------------------------------------------- #define DMTEXT_FIRST DMTEXT_LQ #define DMTEXT_LQ 1 #define DMTEXT_NLQ 2 #define DMTEXT_MEMO 3 #define DMTEXT_DRAFT 4 #define DMTEXT_TEXT 5 #define DMTEXT_LAST DMTEXT_TEXT #define DMTEXT_USER 256 // lower bound for user-defined text // quality id //----------------------------------------------------------------------------- // misc //----------------------------------------------------------------------------- // someday make NOOCD ((OCD)NOT_USED) #define NOT_USED -1 // the value should not be used. #define NOOCD NOT_USED // command does not exist
44.464211
86
0.487497
[ "vector", "model" ]
30ba12ce6cf89257ab7068f44d533c69770d3bd1
1,966
h
C
src/util-lib/zobrist.h
LieuweVinkhuijzen/ltsmin
b318b366a26f7aa1126198b17e8e0844ce0d8750
[ "BSD-3-Clause" ]
40
2015-03-27T12:55:56.000Z
2022-03-17T10:47:11.000Z
src/util-lib/zobrist.h
LieuweVinkhuijzen/ltsmin
b318b366a26f7aa1126198b17e8e0844ce0d8750
[ "BSD-3-Clause" ]
160
2015-01-29T13:45:32.000Z
2022-03-29T11:43:50.000Z
src/util-lib/zobrist.h
LieuweVinkhuijzen/ltsmin
b318b366a26f7aa1126198b17e8e0844ce0d8750
[ "BSD-3-Clause" ]
27
2015-02-02T10:46:51.000Z
2022-03-24T14:39:55.000Z
#ifndef ZOBRIST_H #define ZOBRIST_H /** * Implementation of zobrist incremental hashing on fixed-length state vectors. * Successor states in model checking often exhibit similarity to their * predecessors: only a few variables are updated (the state space explosion * is caused by combinatorial values of the variables in the states). * This zobrist implementation exploits this, by hashing in and out random * values for the variables that a state differs from its predecessor. The set * of random values is small so it can be precalculated and stored. It is * indexed by the variable's value. * * @incollection {springerlink:10.1007/978-3-642-20398-5_40, author = {Laarman, Alfons and van de Pol, Jaco and Weber, Michael}, affiliation = {Formal Methods and Tools, University of Twente, The Netherlands}, title = {Multi-Core LTS&lt;span style="font-variant:small-caps"&gt;&lt;small&gt;min&lt;/small&gt;&lt;/span&gt;: Marrying Modularity and Scalability}, booktitle = {NASA Formal Methods}, series = {Lecture Notes in Computer Science}, editor = {Bobaru, Mihaela and Havelund, Klaus and Holzmann, Gerard and Joshi, Rajeev}, publisher = {Springer Berlin / Heidelberg}, isbn = {978-3-642-20397-8}, keyword = {Computer Science}, pages = {506-511}, volume = {6617}, url = {http://dx.doi.org/10.1007/978-3-642-20398-5_40}, note = {10.1007/978-3-642-20398-5_40}, year = {2011} } * */ #include <stdint.h> #include <dm/dm.h> #include <util-lib/fast_hash.h> typedef struct zobrist_s *zobrist_t; extern hash64_t zobrist_hash (const zobrist_t z, int *v, int *prev, hash64_t h); extern hash64_t zobrist_hash_dm (const zobrist_t z, int *v, int *prev, hash64_t h, int g); extern hash64_t zobrist_rehash (zobrist_t z, hash64_t seed); extern zobrist_t zobrist_create (size_t length, size_t z, matrix_t * m); extern void zobrist_free (zobrist_t z); #endif
36.407407
154
0.706511
[ "model" ]
30bac81d4a7868c614c496ef698ea537eeab7fed
3,896
h
C
aws-cpp-sdk-lex/include/aws/lex/model/ActiveContextTimeToLive.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lex/include/aws/lex/model/ActiveContextTimeToLive.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lex/include/aws/lex/model/ActiveContextTimeToLive.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lex/LexRuntimeService_EXPORTS.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace LexRuntimeService { namespace Model { /** * <p>The length of time or number of turns that a context remains * active.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/ActiveContextTimeToLive">AWS * API Reference</a></p> */ class AWS_LEXRUNTIMESERVICE_API ActiveContextTimeToLive { public: ActiveContextTimeToLive(); ActiveContextTimeToLive(Aws::Utils::Json::JsonView jsonValue); ActiveContextTimeToLive& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The number of seconds that the context should be active after it is first * sent in a <code>PostContent</code> or <code>PostText</code> response. You can * set the value between 5 and 86,400 seconds (24 hours).</p> */ inline int GetTimeToLiveInSeconds() const{ return m_timeToLiveInSeconds; } /** * <p>The number of seconds that the context should be active after it is first * sent in a <code>PostContent</code> or <code>PostText</code> response. You can * set the value between 5 and 86,400 seconds (24 hours).</p> */ inline bool TimeToLiveInSecondsHasBeenSet() const { return m_timeToLiveInSecondsHasBeenSet; } /** * <p>The number of seconds that the context should be active after it is first * sent in a <code>PostContent</code> or <code>PostText</code> response. You can * set the value between 5 and 86,400 seconds (24 hours).</p> */ inline void SetTimeToLiveInSeconds(int value) { m_timeToLiveInSecondsHasBeenSet = true; m_timeToLiveInSeconds = value; } /** * <p>The number of seconds that the context should be active after it is first * sent in a <code>PostContent</code> or <code>PostText</code> response. You can * set the value between 5 and 86,400 seconds (24 hours).</p> */ inline ActiveContextTimeToLive& WithTimeToLiveInSeconds(int value) { SetTimeToLiveInSeconds(value); return *this;} /** * <p>The number of conversation turns that the context should be active. A * conversation turn is one <code>PostContent</code> or <code>PostText</code> * request and the corresponding response from Amazon Lex.</p> */ inline int GetTurnsToLive() const{ return m_turnsToLive; } /** * <p>The number of conversation turns that the context should be active. A * conversation turn is one <code>PostContent</code> or <code>PostText</code> * request and the corresponding response from Amazon Lex.</p> */ inline bool TurnsToLiveHasBeenSet() const { return m_turnsToLiveHasBeenSet; } /** * <p>The number of conversation turns that the context should be active. A * conversation turn is one <code>PostContent</code> or <code>PostText</code> * request and the corresponding response from Amazon Lex.</p> */ inline void SetTurnsToLive(int value) { m_turnsToLiveHasBeenSet = true; m_turnsToLive = value; } /** * <p>The number of conversation turns that the context should be active. A * conversation turn is one <code>PostContent</code> or <code>PostText</code> * request and the corresponding response from Amazon Lex.</p> */ inline ActiveContextTimeToLive& WithTurnsToLive(int value) { SetTurnsToLive(value); return *this;} private: int m_timeToLiveInSeconds; bool m_timeToLiveInSecondsHasBeenSet; int m_turnsToLive; bool m_turnsToLiveHasBeenSet; }; } // namespace Model } // namespace LexRuntimeService } // namespace Aws
36.074074
124
0.699692
[ "model" ]
30bacf5005d4f350bbbaba8b9fda80ca1b935567
7,683
h
C
CLI/FK_CLI/include/DList_CLI.h
rita0222/FK
bc5786a5da0dd732e2f411c1a953b331323ee432
[ "BSD-3-Clause" ]
4
2020-05-15T03:43:53.000Z
2021-06-05T16:21:31.000Z
CLI/FK_CLI/include/DList_CLI.h
rita0222/FK
bc5786a5da0dd732e2f411c1a953b331323ee432
[ "BSD-3-Clause" ]
1
2020-05-19T09:27:16.000Z
2020-05-21T02:12:54.000Z
CLI/FK_CLI/include/DList_CLI.h
rita0222/FK
bc5786a5da0dd732e2f411c1a953b331323ee432
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <FK/DList.h> #include "Base_CLI.h" #include "Model_CLI.h" #include "Projection_CLI.h" #using <System.dll> namespace FK_CLI { using namespace System::Collections::Generic; //! 立体視出力を制御する際に用いる列挙型 public enum class fk_StereoChannel { STEREO_LEFT, //!< 右目側 STEREO_RIGHT //!< 左目側 }; //! ディスプレイリストを制御するクラス /*! * このクラスは、ディスプレイリストを制御する機能を提供します。 * ディスプレイリストとは、シーン中に表示するためのモデルを管理する仕組みです。 * 実際の利用時には、インスタンスは本クラスのものではなく * 派生クラスの fk_Scene によるものを利用することになります。 * * ディスプレイリストに登録する要素は、以下のようなものがあります。 * - 通常モデル: * 3次元空間に表示するためのモデルです。 * - オーバーレイモデル: * オーバーレイモデルとして登録したモデルは、 * カメラからの前後に関係なく常に全体が表示されます。 * オーバーレイモデルが複数登録されている場合は、 * 後に登録されたものほど前面に表示されます。 * - カメラ: * シーンのカメラに当たるモデルです。 * 同時に登録できるモデルは1つだけですが、 * どの時点でもモデルを変更することができます。 * - 投影設定: * シーンを表示する際の投影設定です。 * 詳細は fk_Perspective, fk_Frustum, fk_Ortho の * 各マニュアルを参照して下さい。 * * \sa fk_Scene, fk_Fog, fk_Model, fk_Perspective, , fk_Frustum, fk_Ortho */ public ref class fk_DisplayLink : fk_BaseObject { internal: LinkedList<fk_Model^>^ modelList; LinkedList<fk_Model^>^ overlayList; fk_Model^ _camera; fk_Model^ _lCamera; fk_Model^ _rCamera; fk_ProjectBase^ _proj; fk_ProjectBase^ _lProj; fk_ProjectBase^ _rProj; ::FK::fk_DisplayLink * GetP(void); void CameraUpdate(void); ::FK::fk_StereoChannel GetStereo(fk_StereoChannel); public: #ifndef FK_DOXYGEN_USER_PROCESS fk_DisplayLink(bool argNewFlg); ~fk_DisplayLink(); #endif //! カメラモデルプロパティ /*! * ディスプレイリストでのカメラモデルの設定・参照を行います。 * * \sa fk_Model */ property fk_Model^ Camera { fk_Model^ get(); void set(fk_Model^ argM); } //! 立体視用左眼カメラプロパティ /*! * 立体視における左眼を表すカメラモデルの設定・参照を行います。 * * \sa fk_Model */ property fk_Model^ LeftCamera { fk_Model^ get(); void set(fk_Model^ argM); } //! 立体視用右眼カメラプロパティ /*! * 立体視における右眼を表すカメラモデルの設定・参照を行います。 * * \sa fk_Model */ property fk_Model^ RightCamera { fk_Model^ get(); void set(fk_Model^ argM); } //! 投影設定プロパティ /*! * シーンにおける投影状態の設定・参照を行います。 * * \sa fk_Perspective, fk_Ortho, fk_Frustum */ property fk_ProjectBase^ Projection { fk_ProjectBase^ get(); void set(fk_ProjectBase^ argP); } //! 立体視用左眼投影プロパティ /*! * 立体視における、左眼を表すカメラ投影状態の設定・参照を行います。 * * \sa fk_Perspective, fk_Ortho, fk_Frustum */ property fk_ProjectBase^ LeftProjection { fk_ProjectBase^ get(); void set(fk_ProjectBase^ argP); } //! 立体視用右眼投影プロパティ /*! * 立体視における、右眼を表すカメラ投影状態の設定・参照を行います。 * * \sa fk_Perspective, fk_Ortho, fk_Frustum */ property fk_ProjectBase^ RightProjection { fk_ProjectBase^ get(); void set(fk_ProjectBase^ argP); } //! 立体視モード時のオーバーレイ描画モードプロパティ /*! * 立体視モード時のオーバーレイ描画モデルに対する動作の設定・参照を行います。 * 一般的なゲームアプリケーションでは、3DCG をレンダリングした画面上に * 2D の画像や文字などを情報として表示(いわゆる HUD 表示)しますが、 * 立体視を有効にした場合はそれらの表示にも視差が適用されます。 * この動作は状況によっては望ましくない場合もあります。 * このプロパティによって、オーバーレイ描画を行うモデルに対して視差を適用するか、 * しないかを選択することができます。 * HUD 表示はオーバーレイ描画によって実現することが多いため、 * 多くの場合はこのプロパティによる設定で十分制御が可能となるはずです。 * デフォルトではオーバーレイ描画モデルにも視差を適用する設定(true)になっています。 * true だった場合、オーバーレイ描画モデルの視差を有効にします。 * false だった場合、オーバーレイ描画モデルの視差を無効にします。 */ property bool StereoOverlayMode { bool get(); void set(bool argMode); } //! 初期化メソッド /*! * ディスプレイリストに登録されていた全ての情報を解除します。 * 解除する対象は通常表示モデル、モデルオーバーレイモデル、 * カメラ、投影設定です。 */ void ClearDisplay(void); //! 立体視用設定情報初期化メソッド /*! * 立体視モードで使用する設定情報を初期化します。 */ void ClearStereo(void); //! 通常モデル登録メソッド /*! * 通常モデルをディスプレイリストに登録します。 * * \param[in] model 登録モデルのアドレス */ void EntryModel(fk_Model ^model); //! 通常モデル解除メソッド /*! * ディスプレイリストに登録されている通常モデルに対し、 * 登録を解除します。 * もし登録されていないモデルが指定された場合は、 * 特に何も起こりません。 * * \param[in] model 解除モデルのアドレス */ void RemoveModel(fk_Model ^model); //! 通常モデル全解除メソッド /*! * ディスプレイリストに登録されている全ての通常モデルに対し、 * 登録を解除します。 */ void ClearModel(void); //! オーバーレイモデル登録メソッド /*! * オーバーレイモデルをディスプレイリストに登録します。 * オーバーレイモデルは、後に登録したものほど前面に表示されるようになります。 * もし既に登録されているモデルを再度登録した場合は、 * 一度解除したのちに改めて登録しなおすことと同義となります。 * * \param[in] model 登録モデルのアドレス */ void EntryOverlayModel(fk_Model ^model); //! オーバーレイモデル解除メソッド /*! * ディスプレイリストに登録されているオーバーレイモデルに対し、 * 登録を解除します。 * もし登録されていないモデルが指定された場合は、 * 特に何も起こりません。 * * \param[in] model 解除モデルのアドレス */ void RemoveOverlayModel(fk_Model^ model); //! オーバーレイモデル全解除メソッド /*! * ディスプレイリストに登録されている全てのオーバーレイモデルに対し、 * 登録を解除します。 */ void ClearOverlayModel(void); }; } /**************************************************************************** * * Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or * other materials provided with the distribution. * * - Neither the name of the copyright holders nor the names * of its contributors may be used to endorse or promote * products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * * Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved. * * 本ソフトウェアおよびソースコードのライセンスは、基本的に * 「修正 BSD ライセンス」に従います。以下にその詳細を記します。 * * ソースコード形式かバイナリ形式か、変更するかしないかを問わず、 * 以下の条件を満たす場合に限り、再頒布および使用が許可されます。 * * - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、 * および下記免責条項を含めること。 * * - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の * 資料に、上記の著作権表示、本条件一覧、および下記免責条項を * 含めること。 * * - 書面による特別の許可なしに、本ソフトウェアから派生した製品の * 宣伝または販売促進に、本ソフトウェアの著作権者の名前または * コントリビューターの名前を使用してはならない。 * * 本ソフトウェアは、著作権者およびコントリビューターによって「現 * 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、 * および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ * に限定されない、いかなる保証もないものとします。著作権者もコン * トリビューターも、事由のいかんを問わず、損害発生の原因いかんを * 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その * 他の)不法行為であるかを問わず、仮にそのような損害が発生する可 * 能性を知らされていたとしても、本ソフトウェアの使用によって発生 * した(代替品または代用サービスの調達、使用の喪失、データの喪失、 * 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、 * 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に * ついて、一切責任を負わないものとします。 * ****************************************************************************/
26.044068
79
0.651959
[ "model" ]
30c0d7da7ae63bd9ae097c2c4d100f37764c9250
13,435
c
C
src/plugins/gitresolver/gitresolver.c
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
src/plugins/gitresolver/gitresolver.c
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
src/plugins/gitresolver/gitresolver.c
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
/** * @file * * @brief Source for gitresolver plugin * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) * */ #include "gitresolver.h" #include <fcntl.h> #include <git2.h> #include <kdberrors.h> #include <kdbhelper.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #define TV_MAX_DIGITS 26 #define DEFAULT_CHECKOUT_LOCATION "/tmp/" #define REFSTRING "refs/heads/" typedef enum { OBJECT, HEAD, } Tracking; typedef struct { char * tmpFile; // temporary filename for checkout char * repo; // path to repo (currently only local) char * branch; // branchname char * file; // filename char * refName; // git reference name e.g. refs/heads/master char * headID; // id of the most recent commit char * objID; // most recent id of the file Tracking tracking; // track commit ids or object ids int setPhase; // Set phase counter, 0 setresolver, 1 commit time_t mtime; // creation timestamp of tmp file } GitData; int elektraGitresolverCheckFile (const char * filename) { if (filename[0] == '/') return 0; return 1; } static void genCheckoutFileName (GitData * data) { // generate temp filename: /tmp/branch_filename_tv_sec:tv_usec struct timeval tv; gettimeofday (&tv, 0); const char * fileName = strrchr (data->file, '/'); if (!fileName) fileName = data->file; else fileName += 1; size_t len = strlen (DEFAULT_CHECKOUT_LOCATION) + strlen (data->branch) + strlen (fileName) + TV_MAX_DIGITS + 1; data->tmpFile = elektraCalloc (len); snprintf (data->tmpFile, len, "%s%s_%s_%lu:%lu", DEFAULT_CHECKOUT_LOCATION, data->branch, fileName, tv.tv_sec, tv.tv_usec); } int elektraGitresolverOpen (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED) { // plugin initialization logic // this function is optional return 1; // success } int elektraGitresolverClose (Plugin * handle ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED) { // free all plugin resources and shut it down // this function is optional GitData * data = elektraPluginGetData (handle); if (!data) return 0; if (data->headID) elektraFree (data->headID); if (data->tmpFile) { unlink (data->tmpFile); // remove temporary checked out file when closing elektraFree (data->tmpFile); } if (data->refName) elektraFree (data->refName); elektraFree (data); elektraPluginSetData (handle, NULL); return 1; // success } static int initData (Plugin * handle, Key * parentKey) { GitData * data = elektraPluginGetData (handle); if (!data) { KeySet * config = elektraPluginGetConfig (handle); data = elektraCalloc (sizeof (GitData)); Key * key = ksLookupByName (config, "/path", KDB_O_NONE); data->repo = (char *)keyString (key); if (!key) { ELEKTRA_SET_ERROR (34, parentKey, "no repository specified"); return -1; } // default to master branch when no branchname is supplied const char * defaultBranch = "master"; key = ksLookupByName (config, "/branch", KDB_O_NONE); if (!key) data->branch = (char *)defaultBranch; else data->branch = (char *)keyString (key); key = ksLookupByName (config, "/tracking", KDB_O_NONE); if (!key) data->tracking = HEAD; else { if (!strcmp (keyString (key), "object")) data->tracking = OBJECT; else data->tracking = HEAD; } size_t refLen = strlen (REFSTRING) + strlen (data->branch) + 1; data->refName = elektraCalloc (refLen); snprintf (data->refName, refLen, "%s%s", REFSTRING, data->branch); elektraPluginSetData (handle, data); } return 0; } static git_repository * connectToLocalRepo (GitData * data) { git_libgit2_init (); git_repository * repo; int rc; rc = git_repository_open_ext (&(repo), data->repo, 0, NULL); if (rc) { return NULL; } const char * repoPath = git_repository_workdir (repo); data->file = data->repo + strlen (repoPath); return repo; } static const git_oid * getHeadRef (GitData * data, git_repository * repo) { git_reference * headRef; int rc = git_reference_lookup (&headRef, repo, data->refName); if (rc) { git_reference_free (headRef); return NULL; } // compare newest commit id to last saved commit id // only update if there's a newer commit const git_oid * headObj = git_reference_target (headRef); git_reference_free (headRef); return headObj; } static char * hasNewCommit (GitData * data, const git_oid * headObj) { size_t IDSize = GIT_OID_HEXSZ + 1; char * commitID = elektraCalloc (IDSize); git_oid_tostr (commitID, IDSize, headObj); if (!data->headID) { return commitID; } else { if (!strcmp (data->headID, commitID)) { elektraFree (commitID); return NULL; } else { return commitID; } } } static char * hasNewObjectCommit (GitData * data, git_object * blob) { size_t IDSize = GIT_OID_HEXSZ + 1; char * objID = elektraCalloc (IDSize); git_oid_tostr (objID, IDSize, git_object_id (blob)); if (!data->objID) { return objID; } else { if (!strcmp (data->objID, objID)) { elektraFree (objID); return NULL; } else { return objID; } } } static git_object * getBlob (GitData * data, git_repository * repo) { git_object * blob; char spec[strlen (data->refName) + strlen (data->file) + 2]; snprintf (spec, sizeof (spec), "%s:%s", data->refName, data->file); int rc = git_revparse_single (&blob, repo, spec); if (rc) { // file doesn't exist in repo return NULL; } return blob; } int elektraGitresolverGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED) { if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/gitresolver")) { KeySet * contract = ksNew ( 30, keyNew ("system/elektra/modules/gitresolver", KEY_VALUE, "gitresolver plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/gitresolver/exports", KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/open", KEY_FUNC, elektraGitresolverOpen, KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/close", KEY_FUNC, elektraGitresolverClose, KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/get", KEY_FUNC, elektraGitresolverGet, KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/set", KEY_FUNC, elektraGitresolverSet, KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/error", KEY_FUNC, elektraGitresolverError, KEY_END), keyNew ("system/elektra/modules/gitresolver/exports/checkfile", KEY_FUNC, elektraGitresolverCheckFile, KEY_END), #include ELEKTRA_README (gitresolver) keyNew ("system/elektra/modules/gitresolver/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); ksAppend (returned, contract); ksDel (contract); return 1; // success } // get all keys if (initData (handle, parentKey)) return -1; GitData * data = elektraPluginGetData (handle); git_repository * repo = connectToLocalRepo (data); if (!repo) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to open Repository %s\n", data->repo); git_libgit2_shutdown (); return -1; } genCheckoutFileName (data); keySetString (parentKey, data->tmpFile); // TODO: check for empty repo and initialize repo const git_oid * headObj = getHeadRef (data, repo); if (!headObj) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName); git_repository_free (repo); git_libgit2_shutdown (); return -1; } if (data->tracking == HEAD) { char * newCommit = hasNewCommit (data, headObj); if (data->headID && !newCommit) { // still newest commit, no need to update git_repository_free (repo); git_libgit2_shutdown (); return 0; } else if (data->headID && newCommit) { elektraFree (data->headID); data->headID = newCommit; } else { data->headID = newCommit; } elektraPluginSetData (handle, data); data = elektraPluginGetData (handle); } git_object * blob = getBlob (data, repo); if (!blob) { ELEKTRA_ADD_WARNINGF (83, parentKey, "File %s not found in repository %s\n", data->file, data->repo); git_repository_free (repo); git_libgit2_shutdown (); return 0; } if (data->tracking == OBJECT) { char * newObj = hasNewObjectCommit (data, blob); if (!newObj) { git_object_free (blob); git_repository_free (repo); git_libgit2_shutdown (); return 0; } else { if (data->objID) { elektraFree (data->objID); data->objID = newObj; } else { data->objID = newObj; } } elektraPluginSetData (handle, data); data = elektraPluginGetData (handle); } FILE * outFile; outFile = fopen (data->tmpFile, "w+"); if (!outFile) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parentKey, "Failed to check out file %s to %s\n", data->file, data->tmpFile); git_object_free (blob); git_repository_free (repo); git_libgit2_shutdown (); return -1; } fwrite (git_blob_rawcontent ((git_blob *)blob), (size_t)git_blob_rawsize ((git_blob *)blob), 1, outFile); struct stat buf; int fd; fd = fileno (outFile); if (fstat (fd, &buf) == -1) { // this shouldn't happen anyway } data->mtime = buf.st_mtime; fclose (outFile); git_object_free (blob); git_repository_free (repo); git_libgit2_shutdown (); return 1; // success } static void addFileToIndex (git_repository * repo, GitData * data, git_index * index) { git_blob * blob; git_oid blobID; git_index_entry ie; ie.path = data->file; ie.mode = GIT_FILEMODE_BLOB; git_blob_create_fromdisk (&blobID, repo, data->tmpFile); git_blob_lookup (&blob, repo, &blobID); git_index_add_frombuffer (index, &ie, git_blob_rawcontent (blob), git_blob_rawsize (blob)); } int elektraGitresolverSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED) { // get all keys // this function is optional GitData * data = elektraPluginGetData (handle); if (!data) return -1; keySetString (parentKey, data->tmpFile); git_repository * repo = connectToLocalRepo (data); if (!repo) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to open Repository %s\n", data->repo); git_libgit2_shutdown (); return -1; } const git_oid * headObj = getHeadRef (data, repo); if (!headObj) { ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_GITRESOLVER_RESOLVING_ISSUE, parentKey, "Failed to get reference %s\n", data->refName); git_repository_free (repo); git_libgit2_shutdown (); return -1; } if (data->tracking == HEAD) { char * newCommit = hasNewCommit (data, headObj); if (newCommit) { // newer commit in repo - abort ELEKTRA_SET_ERROR (ELEKTRA_ERROR_GITRESOLVER_CONFLICT, parentKey, "The repository has been updated and is ahead of you"); elektraFree (newCommit); git_repository_free (repo); git_libgit2_shutdown (); return -1; } elektraFree (newCommit); } if (data->tracking == OBJECT) { git_object * blob = getBlob (data, repo); if (blob) { char * newObj = hasNewObjectCommit (data, blob); if (newObj) { ELEKTRA_SET_ERROR (ELEKTRA_ERROR_GITRESOLVER_CONFLICT, parentKey, "The repository has been updated and is ahead of you"); elektraFree (newObj); git_object_free (blob); git_repository_free (repo); git_libgit2_shutdown (); return -1; } git_object_free (blob); } } if (!data->setPhase) { ++(data->setPhase); } else if (data->setPhase == 1) { // commit phase int fd = open (data->tmpFile, O_RDONLY); struct stat buf; fstat (fd, &buf); close (fd); if (data->mtime == buf.st_mtime) { // file hasn't changed, nothing to do here git_repository_free (repo); git_libgit2_shutdown (); return 0; } // get repo index git_index * index; git_repository_index (&index, repo); // add file addFileToIndex (repo, data, index); git_index_write (index); // get tree id git_oid treeID; git_index_write_tree (&treeID, index); // get parent commit git_oid parentID; git_commit * parent; git_reference_name_to_id (&parentID, repo, "HEAD"); git_commit_lookup (&parent, repo, &parentID); // extract default git user git_signature * sig; int rc = git_signature_default (&sig, repo); if (rc == GIT_ENOTFOUND) { git_signature_now (&sig, "Elektra", "@libelektra.org"); } // get git tree git_tree * tree; git_tree_lookup (&tree, repo, &treeID); // create default commit git_oid commitID; git_commit_create (&commitID, repo, "HEAD", sig, sig, NULL, "kdb git autocommit", tree, 1, (const git_commit **)&parent); git_signature_free (sig); git_commit_free (parent); } elektraPluginSetData (handle, data); git_repository_free (repo); git_libgit2_shutdown (); return 1; // success } int elektraGitresolverError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED) { // set all keys // this function is optional return 1; // success } Plugin * ELEKTRA_PLUGIN_EXPORT (gitresolver) { // clang-format off return elektraPluginExport ("gitresolver", ELEKTRA_PLUGIN_OPEN, &elektraGitresolverOpen, ELEKTRA_PLUGIN_CLOSE, &elektraGitresolverClose, ELEKTRA_PLUGIN_GET, &elektraGitresolverGet, ELEKTRA_PLUGIN_SET, &elektraGitresolverSet, ELEKTRA_PLUGIN_ERROR, &elektraGitresolverError, ELEKTRA_PLUGIN_END); }
26.291585
126
0.694827
[ "object" ]
30c1e9d3f40c60f98b178d6ef1de6d62c5686e28
2,615
h
C
src/render_support/SpriteMgr.h
lachlanorr/gaen
325b4604ac8a8a366aa93cca9d8393ccdbc682fa
[ "Zlib" ]
2
2015-05-07T21:03:25.000Z
2017-10-11T11:17:28.000Z
src/render_support/SpriteMgr.h
lachlanorr/gaen
325b4604ac8a8a366aa93cca9d8393ccdbc682fa
[ "Zlib" ]
4
2016-06-25T21:41:50.000Z
2016-12-26T19:35:19.000Z
src/render_support/SpriteMgr.h
lachlanorr/gaen
325b4604ac8a8a366aa93cca9d8393ccdbc682fa
[ "Zlib" ]
1
2016-08-27T18:05:49.000Z
2016-08-27T18:05:49.000Z
//------------------------------------------------------------------------------ // SpriteMgr.h - Management of Sprite lifetimes, animations and collisions // // Gaen Concurrency Engine - http://gaen.org // Copyright (c) 2014-2021 Lachlan Orr // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. //------------------------------------------------------------------------------ #ifndef GAEN_RENDER_SUPPORT_SPRITEMGR_H #define GAEN_RENDER_SUPPORT_SPRITEMGR_H #include "core/HashMap.h" #include "core/List.h" #include "math/mat43.h" #include "engine/Handle.h" #include "render_support/Sprite.h" #include "render_support/SpritePhysics.h" namespace gaen { class SpriteMgr { public: typedef HashMap<kMEM_Engine, u32, SpriteInstanceUP> SpriteMap; typedef HashMap<kMEM_Engine, task_id, List<kMEM_Engine, u32>> SpriteOwners; ~SpriteMgr(); void update(f32 delta); template <typename T> MessageResult message(const T& msgAcc); private: SpriteMap mSpriteMap; SpriteOwners mSpriteOwners; SpritePhysics mPhysics; }; // Compose API class Entity; namespace system_api { i32 sprite_create(AssetHandleP pAssetHandle, i32 stageHash, i32 passHash, const mat43 & transform, Entity * pCaller); void sprite_play_anim(i32 spriteUid, i32 animHash, f32 duration, bool loop, i32 doneMessage, Entity * pCaller); void sprite_set_velocity(i32 spriteUid, const vec2 & velocity, Entity * pCaller); void sprite_init_body(i32 spriteUid, f32 mass, i32 group, ivec4 mask03, ivec4 mask47, Entity * pCaller); void sprite_stage_show(i32 stageHash, Entity * pCaller); void sprite_stage_hide(i32 stageHash, Entity * pCaller); void sprite_stage_remove(i32 stageHash, Entity * pCaller); } // namespace system_api } // namespace gaen #endif // #ifndef GAEN_RENDER_SUPPORT_SPRITEMGR_H
33.101266
117
0.712046
[ "transform" ]
30c503fd3982e5fba5864d6e5605962680cb7c81
2,594
h
C
src/tools/gui/stlink-gui.h
Sensoteq/stlink
bcee11a4af59b6aed15a6b9a2cdd689ce6483522
[ "BSD-3-Clause" ]
1
2020-03-02T09:41:52.000Z
2020-03-02T09:41:52.000Z
src/tools/gui/stlink-gui.h
Sensoteq/stlink
bcee11a4af59b6aed15a6b9a2cdd689ce6483522
[ "BSD-3-Clause" ]
1
2018-12-10T16:39:46.000Z
2018-12-10T16:39:46.000Z
src/tools/gui/stlink-gui.h
Sensoteq/stlink
bcee11a4af59b6aed15a6b9a2cdd689ce6483522
[ "BSD-3-Clause" ]
1
2020-08-27T18:58:12.000Z
2020-08-27T18:58:12.000Z
#ifndef __STLINK_GUI_H__ #define __STLINK_GUI_H__ #include <glib-object.h> #define STLINK_TYPE_GUI (stlink_gui_get_type ()) #define STLINK_GUI(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), STLINK_TYPE_GUI, STlinkGUI)) #define STLINK_IS_GUI(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), STLINK_TYPE_GUI)) #define STLINK_GUI_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), STLINK_TYPE_GUI, STlinkGUIClass)) #define STLINK_IS_GUI_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), STLINK_TYPE_GUI)) #define STLINK_GUI_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), STLINK_TYPE_GUI, STlinkGUIlass)) #define STLINK_GUI_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), STLINK_TYPE_GUI, STlinkGUIPrivate)) typedef struct _STlinkGUI STlinkGUI; typedef struct _STlinkGUIClass STlinkGUIClass; typedef struct _STlinkGUIPrivate STlinkGUIPrivate; enum stlink_gui_pages_t { PAGE_DEVMEM, PAGE_FILEMEM }; enum stlink_gui_dnd_targets_t { TARGET_FILENAME, TARGET_ROOTWIN }; struct progress_t { GtkProgressBar *bar; guint timer; gboolean activity_mode; gdouble fraction; }; struct mem_t { guchar *memory; gsize size; guint32 base; }; struct _STlinkGUI { GObject parent_instance; /*< private >*/ GtkWindow *window; GtkTreeView *devmem_treeview; GtkTreeView *filemem_treeview; GtkSpinner *spinner; GtkStatusbar *statusbar; GtkInfoBar *infobar; GtkLabel *infolabel; GtkNotebook *notebook; GtkFrame *device_frame; GtkLabel *chip_id_label; GtkLabel *core_id_label; GtkLabel *flash_size_label; GtkLabel *ram_size_label; GtkBox *devmem_box; GtkEntry *devmem_jmp_entry; GtkBox *filemem_box; GtkEntry *filemem_jmp_entry; GtkToolButton *connect_button; GtkToolButton *disconnect_button; GtkToolButton *flash_button; GtkToolButton *export_button; GtkToolButton *open_button; /* flash dialog */ GtkDialog *flash_dialog; GtkButton *flash_dialog_ok; GtkButton *flash_dialog_cancel; GtkEntry *flash_dialog_entry; struct progress_t progress; struct mem_t flash_mem; struct mem_t file_mem; gchar *error_message; gchar *filename; stlink_t *sl; }; struct _STlinkGUIClass { GObjectClass parent_class; /* class members */ }; GType stlink_gui_get_type (void); int export_to_file(const char*filename, const struct mem_t flash_mem); #endif
27.020833
108
0.696608
[ "object" ]
30c5489c70cd44d949e4d9852275ccea0609b1d5
1,357
h
C
utils/TestDisplay.h
nullpo24/ArOgre
f4c229663f5f3b2761191e20b78863a3efe1c071
[ "MIT" ]
3
2016-05-29T01:13:11.000Z
2020-01-03T03:06:22.000Z
utils/TestDisplay.h
nullpo24/ArOgre
f4c229663f5f3b2761191e20b78863a3efe1c071
[ "MIT" ]
null
null
null
utils/TestDisplay.h
nullpo24/ArOgre
f4c229663f5f3b2761191e20b78863a3efe1c071
[ "MIT" ]
4
2018-08-03T14:36:07.000Z
2020-11-07T06:54:08.000Z
#ifndef _TESTDISPLAY_H__ #define _TESTDISPLAY_H__ #include "PCH.h" #include "ArBaseApplication.h" enum eAction{DCOLOR, DROTATE, DSCALE, DSELECT}; class TestDisplay : public ArBaseApplication { public: TestDisplay(); virtual ~TestDisplay(); protected: // Frame Listener virtual void createScene(); virtual void createFrameListener(); virtual bool frameRenderingQueued(const Ogre::FrameEvent &evt); // Key Listener virtual bool keyPressed( const OIS::KeyEvent &arg ); virtual bool keyReleased( const OIS::KeyEvent &arg ); // Mouse Listener virtual bool mouseMoved(const OIS::MouseEvent &arg); virtual bool mousePressed(const OIS::MouseEvent &arg,OIS::MouseButtonID id); virtual bool mouseReleased(const OIS::MouseEvent &arg,OIS::MouseButtonID id); // Sdktray Listener virtual void buttonHit(OgreBites::Button* button); // sdktray menu void createInfoMenu(); void createMainMenu(); void createDisplay(); void performAction(bool next); private: ArOgre::ArModel* mLight, * mModel, * mNextAction, * mPreviousAction; Ogre::Real mTimeActionNext, mTimeActionPrev, mTimeChange; std::vector<unsigned int> vIdChange; std::vector<Ogre::ColourValue> vColors; std::vector<Ogre::String> vNameModels; unsigned int mCurrentAcion, mCurrentColor, mCurrentModel; }; #endif // #ifndef _TESTDISPLAY_H__
26.096154
79
0.743552
[ "vector" ]
30c97994591e07fc520c443d43130bb376cbf3f2
781
h
C
kinect_sim/include/kinect_sim/scene.h
Tacha-S/perception
aefbb5612c84b46a745c7db4fe860a2456d6e7ef
[ "BSD-3-Clause" ]
17
2020-07-08T06:38:22.000Z
2021-09-20T01:18:12.000Z
kinect_sim/include/kinect_sim/scene.h
Tacha-S/perception
aefbb5612c84b46a745c7db4fe860a2456d6e7ef
[ "BSD-3-Clause" ]
116
2019-03-10T23:02:44.000Z
2021-07-22T15:28:14.000Z
kinect_sim/include/kinect_sim/scene.h
Tacha-S/perception
aefbb5612c84b46a745c7db4fe860a2456d6e7ef
[ "BSD-3-Clause" ]
4
2019-12-08T23:20:36.000Z
2021-06-02T09:32:30.000Z
/* * scene.hpp * * Created on: Aug 16, 2011 * Author: Hordur Johannsson */ #ifndef PCL_SIMULATION_SCENE_HPP_ #define PCL_SIMULATION_SCENE_HPP_ #include <boost/shared_ptr.hpp> #include <pcl/pcl_macros.h> //#include <pcl/win32_macros.h> #include <kinect_sim/camera.h> #include <kinect_sim/model.h> namespace pcl { namespace simulation { class PCL_EXPORTS Scene { public: typedef boost::shared_ptr<Scene> Ptr; typedef boost::shared_ptr<Scene> ConstPtr; void draw (); void add (Model::Ptr model); void addCompleteModel (std::vector<Model::Ptr> model); void clear (); private: std::vector<Model::Ptr> models_; }; } // namespace - simulation } // namespace - pcl #endif
15.938776
55
0.633803
[ "vector", "model" ]
30c99f24f4e57b36e96078048363f42f1dd6ac5b
6,586
h
C
src/shm_logger.h
YoheiKakiuchi/elmo_shm
e7b9e2d55100485f3dc6212ed82dc1324df4cce1
[ "MIT" ]
null
null
null
src/shm_logger.h
YoheiKakiuchi/elmo_shm
e7b9e2d55100485f3dc6212ed82dc1324df4cce1
[ "MIT" ]
null
null
null
src/shm_logger.h
YoheiKakiuchi/elmo_shm
e7b9e2d55100485f3dc6212ed82dc1324df4cce1
[ "MIT" ]
null
null
null
#include <deque> #include "servo_shm.h" #include <string> #include <vector> #include <iostream> #include <fstream> template <typename T> class shm_port { std::string suffix; //std::ostream *os; std::ofstream *os; int size; int offset; int step; public: shm_port(std::string suf, int in_size, int in_offset, int in_step) : suffix(suf), size(in_size), offset(in_offset), step(in_step) { } public: shm_port(std::string suf, int in_size, int in_offset) : shm_port(suf, in_size, in_offset, 1) { } public: void open(std::string &fname) { std::string name = fname; name.append("."); name.append(suffix); std::cerr << "open : " << name << std::endl; os = new std::ofstream (name.c_str()); if (!os->is_open()) { std::cerr << "failed to open " << name << std::endl; } } void close() { os->close(); } void print(servo_shm &shm) { T* pt = (T *)(((long)(void *)&shm) + offset); *os << (shm.frame) * 0.001 << " "; for(int i = 0; i < size; i++) { *os << *pt << " "; pt += step; } *os << std::endl; } }; std::vector<shm_port <float> > log_f_ports; std::vector<shm_port <int> > log_i_ports; std::vector<shm_port <char> > log_c_ports; class shm_logger { public: shm_logger () { _m_maxLength = 1000 * 300; } public: void clear () { //std::cerr << "clear log" << std::endl; _m_log.clear(); } void log(servo_shm *shm) { //std::cerr << "log0 " << _m_log.size() << std::endl; _m_log.push_back(*shm); //std::cerr << "log1 " << _m_log.size() << std::endl; while (_m_log.size() > _m_maxLength) { _m_log.pop_front(); } } void open (std::string &fname) { for(unsigned int i = 0; i < log_f_ports.size(); i++) { log_f_ports[i].open(fname); } for(unsigned int i = 0; i < log_i_ports.size(); i++) { log_i_ports[i].open(fname); } for(unsigned int i = 0; i < log_c_ports.size(); i++) { log_c_ports[i].open(fname); } } void close (std::string &fname) { for(unsigned int i = 0; i < log_f_ports.size(); i++) { log_f_ports[i].close(); } for(unsigned int i = 0; i < log_i_ports.size(); i++) { log_i_ports[i].close(); } for(unsigned int i = 0; i < log_c_ports.size(); i++) { log_c_ports[i].close(); } } void save (std::string &fname) { std::cerr << "save : " << fname << ", size = " << _m_log.size() << std::endl; if (_m_log.size() == 0) { std::cerr << "do not save log" << std::endl; return; } open(fname); for(unsigned int j = 0; j < _m_log.size(); j++) { servo_shm &shm = _m_log[j]; for(unsigned int i = 0; i < log_f_ports.size(); i++) { log_f_ports[i].print(shm); } for(unsigned int i = 0; i < log_i_ports.size(); i++) { log_i_ports[i].print(shm); } for(unsigned int i = 0; i < log_c_ports.size(); i++) { log_c_ports[i].print(shm); } } close(fname); } public: std::deque<servo_shm> _m_log; long _m_maxLength; }; void create_logger () { { shm_port<float> p("ref_angle", 28, 0); log_f_ports.push_back(p); } { shm_port<float> p("cur_angle", 28, 256); log_f_ports.push_back(p); } { shm_port<float> p("abs_angle", 28, 512); log_f_ports.push_back(p); } { shm_port<float> p("ref_vel", 28, 768); log_f_ports.push_back(p); } { shm_port<float> p("cur_vel", 28, 1024); log_f_ports.push_back(p); } { shm_port<float> p("ref_torque", 28, 1280); log_f_ports.push_back(p); } { shm_port<float> p("cur_torque", 28, 1536); log_f_ports.push_back(p); } { shm_port<float> p("pgain", 28, 1792); log_f_ports.push_back(p); } { shm_port<float> p("dgain", 28, 2048); log_f_ports.push_back(p); } { shm_port<float> p("torque_pgain", 28, 2304); log_f_ports.push_back(p); } { shm_port<float> p("torque_dgain", 28, 2560); log_f_ports.push_back(p); } { shm_port<float> p("prev_angle", 28, 12040); log_f_ports.push_back(p); } { shm_port<float> p("abs_vel", 28, 12552); log_f_ports.push_back(p); } { shm_port<float> p("motor_temp_0", 28, 4096); log_f_ports.push_back(p); } { shm_port<float> p("motor_temp_1", 28, 4352); log_f_ports.push_back(p); } { shm_port<float> p("motor_outer_temp_0", 28, 4608); log_f_ports.push_back(p); } { shm_port<float> p("motor_outer_temp_1", 28, 4864); log_f_ports.push_back(p); } { shm_port<float> p("motor_current_0", 28, 5120); log_f_ports.push_back(p); } { shm_port<float> p("motor_current_1", 28, 5376); log_f_ports.push_back(p); } { shm_port<float> p("motor_output_0", 28, 5632); log_f_ports.push_back(p); } { shm_port<float> p("motor_output_1", 28, 5888); log_f_ports.push_back(p); } { shm_port<float> p("board_vin_0", 28, 6144); log_f_ports.push_back(p); } { shm_port<float> p("board_vin_1", 28, 6400); log_f_ports.push_back(p); } { shm_port<float> p("board_vdd_0", 28, 6656); log_f_ports.push_back(p); } { shm_port<float> p("board_vdd_1", 28, 6912); log_f_ports.push_back(p); } { shm_port<float> p("h817_rx_error0_0", 28, 7680); log_f_ports.push_back(p); } { shm_port<float> p("h817_rx_error0_1", 28, 7936); log_f_ports.push_back(p); } { shm_port<float> p("h817_rx_error1_0", 28, 8192); log_f_ports.push_back(p); } { shm_port<float> p("h817_rx_error1_1", 28, 8448); log_f_ports.push_back(p); } { shm_port<int> p("motor_num", 28, 3840); log_i_ports.push_back(p); } { shm_port<int> p("controlmode", 28, 9576); log_i_ports.push_back(p); } { shm_port<int> p("joint_offset", 28, 11264); log_i_ports.push_back(p); } { shm_port<int> p("interpolation_counter", 28, 12296); log_i_ports.push_back(p); } { shm_port<int> p("comm_normal_0", 28, 7168); log_i_ports.push_back(p); } { shm_port<int> p("comm_normal_1", 28, 7424); log_i_ports.push_back(p); } { shm_port<int> p("servo_state_0", 28, 10088); log_i_ports.push_back(p); } { shm_port<int> p("servo_state_1", 28, 10344); log_i_ports.push_back(p); } { shm_port<int> p("hole_status_0", 28, 10684); log_i_ports.push_back(p); } { shm_port<int> p("hole_status_1", 28, 10940); log_i_ports.push_back(p); } { shm_port<char> p("is_servo_on", 28, 9832); log_c_ports.push_back(p); } { shm_port<char> p("servo_on", 28, 9896); log_c_ports.push_back(p); } { shm_port<char> p("servo_off", 28, 9960); log_c_ports.push_back(p); } { shm_port<char> p("torque0", 28, 10024); log_c_ports.push_back(p); } { shm_port<char> p("loopback", 28, 10620); log_c_ports.push_back(p); } { shm_port<char> p("joint_enable", 28, 11198); log_c_ports.push_back(p); } }
21.452769
137
0.614485
[ "vector" ]
30c9b3beeef94111652d5151829d2da3a9b7a58f
13,170
c
C
source/kernel/drivers/gpu/drm/amd/amdgpu/cik_ih.c
mikedlowis-prototypes/albase
e441be370dce14b4c9210510d7e7a9b69c5eef20
[ "BSD-2-Clause" ]
null
null
null
source/kernel/drivers/gpu/drm/amd/amdgpu/cik_ih.c
mikedlowis-prototypes/albase
e441be370dce14b4c9210510d7e7a9b69c5eef20
[ "BSD-2-Clause" ]
null
null
null
source/kernel/drivers/gpu/drm/amd/amdgpu/cik_ih.c
mikedlowis-prototypes/albase
e441be370dce14b4c9210510d7e7a9b69c5eef20
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2012 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include "drmP.h" #include "amdgpu.h" #include "amdgpu_ih.h" #include "cikd.h" #include "bif/bif_4_1_d.h" #include "bif/bif_4_1_sh_mask.h" #include "oss/oss_2_0_d.h" #include "oss/oss_2_0_sh_mask.h" /* * Interrupts * Starting with r6xx, interrupts are handled via a ring buffer. * Ring buffers are areas of GPU accessible memory that the GPU * writes interrupt vectors into and the host reads vectors out of. * There is a rptr (read pointer) that determines where the * host is currently reading, and a wptr (write pointer) * which determines where the GPU has written. When the * pointers are equal, the ring is idle. When the GPU * writes vectors to the ring buffer, it increments the * wptr. When there is an interrupt, the host then starts * fetching commands and processing them until the pointers are * equal again at which point it updates the rptr. */ static void cik_ih_set_interrupt_funcs(struct amdgpu_device *adev); /** * cik_ih_enable_interrupts - Enable the interrupt ring buffer * * @adev: amdgpu_device pointer * * Enable the interrupt ring buffer (CIK). */ static void cik_ih_enable_interrupts(struct amdgpu_device *adev) { u32 ih_cntl = RREG32(mmIH_CNTL); u32 ih_rb_cntl = RREG32(mmIH_RB_CNTL); ih_cntl |= IH_CNTL__ENABLE_INTR_MASK; ih_rb_cntl |= IH_RB_CNTL__RB_ENABLE_MASK; WREG32(mmIH_CNTL, ih_cntl); WREG32(mmIH_RB_CNTL, ih_rb_cntl); adev->irq.ih.enabled = true; } /** * cik_ih_disable_interrupts - Disable the interrupt ring buffer * * @adev: amdgpu_device pointer * * Disable the interrupt ring buffer (CIK). */ static void cik_ih_disable_interrupts(struct amdgpu_device *adev) { u32 ih_rb_cntl = RREG32(mmIH_RB_CNTL); u32 ih_cntl = RREG32(mmIH_CNTL); ih_rb_cntl &= ~IH_RB_CNTL__RB_ENABLE_MASK; ih_cntl &= ~IH_CNTL__ENABLE_INTR_MASK; WREG32(mmIH_RB_CNTL, ih_rb_cntl); WREG32(mmIH_CNTL, ih_cntl); /* set rptr, wptr to 0 */ WREG32(mmIH_RB_RPTR, 0); WREG32(mmIH_RB_WPTR, 0); adev->irq.ih.enabled = false; adev->irq.ih.rptr = 0; } /** * cik_ih_irq_init - init and enable the interrupt ring * * @adev: amdgpu_device pointer * * Allocate a ring buffer for the interrupt controller, * enable the RLC, disable interrupts, enable the IH * ring buffer and enable it (CIK). * Called at device load and reume. * Returns 0 for success, errors for failure. */ static int cik_ih_irq_init(struct amdgpu_device *adev) { int ret = 0; int rb_bufsz; u32 interrupt_cntl, ih_cntl, ih_rb_cntl; u64 wptr_off; /* disable irqs */ cik_ih_disable_interrupts(adev); /* setup interrupt control */ WREG32(mmINTERRUPT_CNTL2, adev->dummy_page.addr >> 8); interrupt_cntl = RREG32(mmINTERRUPT_CNTL); /* INTERRUPT_CNTL__IH_DUMMY_RD_OVERRIDE_MASK=0 - dummy read disabled with msi, enabled without msi * INTERRUPT_CNTL__IH_DUMMY_RD_OVERRIDE_MASK=1 - dummy read controlled by IH_DUMMY_RD_EN */ interrupt_cntl &= ~INTERRUPT_CNTL__IH_DUMMY_RD_OVERRIDE_MASK; /* INTERRUPT_CNTL__IH_REQ_NONSNOOP_EN_MASK=1 if ring is in non-cacheable memory, e.g., vram */ interrupt_cntl &= ~INTERRUPT_CNTL__IH_REQ_NONSNOOP_EN_MASK; WREG32(mmINTERRUPT_CNTL, interrupt_cntl); WREG32(mmIH_RB_BASE, adev->irq.ih.gpu_addr >> 8); rb_bufsz = order_base_2(adev->irq.ih.ring_size / 4); ih_rb_cntl = (IH_RB_CNTL__WPTR_OVERFLOW_ENABLE_MASK | IH_RB_CNTL__WPTR_OVERFLOW_CLEAR_MASK | (rb_bufsz << 1)); ih_rb_cntl |= IH_RB_CNTL__WPTR_WRITEBACK_ENABLE_MASK; /* set the writeback address whether it's enabled or not */ wptr_off = adev->wb.gpu_addr + (adev->irq.ih.wptr_offs * 4); WREG32(mmIH_RB_WPTR_ADDR_LO, lower_32_bits(wptr_off)); WREG32(mmIH_RB_WPTR_ADDR_HI, upper_32_bits(wptr_off) & 0xFF); WREG32(mmIH_RB_CNTL, ih_rb_cntl); /* set rptr, wptr to 0 */ WREG32(mmIH_RB_RPTR, 0); WREG32(mmIH_RB_WPTR, 0); /* Default settings for IH_CNTL (disabled at first) */ ih_cntl = (0x10 << IH_CNTL__MC_WRREQ_CREDIT__SHIFT) | (0x10 << IH_CNTL__MC_WR_CLEAN_CNT__SHIFT) | (0 << IH_CNTL__MC_VMID__SHIFT); /* IH_CNTL__RPTR_REARM_MASK only works if msi's are enabled */ if (adev->irq.msi_enabled) ih_cntl |= IH_CNTL__RPTR_REARM_MASK; WREG32(mmIH_CNTL, ih_cntl); pci_set_master(adev->pdev); /* enable irqs */ cik_ih_enable_interrupts(adev); return ret; } /** * cik_ih_irq_disable - disable interrupts * * @adev: amdgpu_device pointer * * Disable interrupts on the hw (CIK). */ static void cik_ih_irq_disable(struct amdgpu_device *adev) { cik_ih_disable_interrupts(adev); /* Wait and acknowledge irq */ mdelay(1); } /** * cik_ih_get_wptr - get the IH ring buffer wptr * * @adev: amdgpu_device pointer * * Get the IH ring buffer wptr from either the register * or the writeback memory buffer (CIK). Also check for * ring buffer overflow and deal with it. * Used by cik_irq_process(). * Returns the value of the wptr. */ static u32 cik_ih_get_wptr(struct amdgpu_device *adev) { u32 wptr, tmp; wptr = le32_to_cpu(adev->wb.wb[adev->irq.ih.wptr_offs]); if (wptr & IH_RB_WPTR__RB_OVERFLOW_MASK) { wptr &= ~IH_RB_WPTR__RB_OVERFLOW_MASK; /* When a ring buffer overflow happen start parsing interrupt * from the last not overwritten vector (wptr + 16). Hopefully * this should allow us to catchup. */ dev_warn(adev->dev, "IH ring buffer overflow (0x%08X, 0x%08X, 0x%08X)\n", wptr, adev->irq.ih.rptr, (wptr + 16) & adev->irq.ih.ptr_mask); adev->irq.ih.rptr = (wptr + 16) & adev->irq.ih.ptr_mask; tmp = RREG32(mmIH_RB_CNTL); tmp |= IH_RB_CNTL__WPTR_OVERFLOW_CLEAR_MASK; WREG32(mmIH_RB_CNTL, tmp); } return (wptr & adev->irq.ih.ptr_mask); } /* CIK IV Ring * Each IV ring entry is 128 bits: * [7:0] - interrupt source id * [31:8] - reserved * [59:32] - interrupt source data * [63:60] - reserved * [71:64] - RINGID * CP: * ME_ID [1:0], PIPE_ID[1:0], QUEUE_ID[2:0] * QUEUE_ID - for compute, which of the 8 queues owned by the dispatcher * - for gfx, hw shader state (0=PS...5=LS, 6=CS) * ME_ID - 0 = gfx, 1 = first 4 CS pipes, 2 = second 4 CS pipes * PIPE_ID - ME0 0=3D * - ME1&2 compute dispatcher (4 pipes each) * SDMA: * INSTANCE_ID [1:0], QUEUE_ID[1:0] * INSTANCE_ID - 0 = sdma0, 1 = sdma1 * QUEUE_ID - 0 = gfx, 1 = rlc0, 2 = rlc1 * [79:72] - VMID * [95:80] - PASID * [127:96] - reserved */ /** * cik_ih_decode_iv - decode an interrupt vector * * @adev: amdgpu_device pointer * * Decodes the interrupt vector at the current rptr * position and also advance the position. */ static void cik_ih_decode_iv(struct amdgpu_device *adev, struct amdgpu_iv_entry *entry) { /* wptr/rptr are in bytes! */ u32 ring_index = adev->irq.ih.rptr >> 2; uint32_t dw[4]; dw[0] = le32_to_cpu(adev->irq.ih.ring[ring_index + 0]); dw[1] = le32_to_cpu(adev->irq.ih.ring[ring_index + 1]); dw[2] = le32_to_cpu(adev->irq.ih.ring[ring_index + 2]); dw[3] = le32_to_cpu(adev->irq.ih.ring[ring_index + 3]); entry->src_id = dw[0] & 0xff; entry->src_data = dw[1] & 0xfffffff; entry->ring_id = dw[2] & 0xff; entry->vm_id = (dw[2] >> 8) & 0xff; entry->pas_id = (dw[2] >> 16) & 0xffff; /* wptr/rptr are in bytes! */ adev->irq.ih.rptr += 16; } /** * cik_ih_set_rptr - set the IH ring buffer rptr * * @adev: amdgpu_device pointer * * Set the IH ring buffer rptr. */ static void cik_ih_set_rptr(struct amdgpu_device *adev) { WREG32(mmIH_RB_RPTR, adev->irq.ih.rptr); } static int cik_ih_early_init(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; int ret; ret = amdgpu_irq_add_domain(adev); if (ret) return ret; cik_ih_set_interrupt_funcs(adev); return 0; } static int cik_ih_sw_init(void *handle) { int r; struct amdgpu_device *adev = (struct amdgpu_device *)handle; r = amdgpu_ih_ring_init(adev, 64 * 1024, false); if (r) return r; r = amdgpu_irq_init(adev); return r; } static int cik_ih_sw_fini(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; amdgpu_irq_fini(adev); amdgpu_ih_ring_fini(adev); amdgpu_irq_remove_domain(adev); return 0; } static int cik_ih_hw_init(void *handle) { int r; struct amdgpu_device *adev = (struct amdgpu_device *)handle; r = cik_ih_irq_init(adev); if (r) return r; return 0; } static int cik_ih_hw_fini(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; cik_ih_irq_disable(adev); return 0; } static int cik_ih_suspend(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; return cik_ih_hw_fini(adev); } static int cik_ih_resume(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; return cik_ih_hw_init(adev); } static bool cik_ih_is_idle(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; u32 tmp = RREG32(mmSRBM_STATUS); if (tmp & SRBM_STATUS__IH_BUSY_MASK) return false; return true; } static int cik_ih_wait_for_idle(void *handle) { unsigned i; u32 tmp; struct amdgpu_device *adev = (struct amdgpu_device *)handle; for (i = 0; i < adev->usec_timeout; i++) { /* read MC_STATUS */ tmp = RREG32(mmSRBM_STATUS) & SRBM_STATUS__IH_BUSY_MASK; if (!tmp) return 0; udelay(1); } return -ETIMEDOUT; } static void cik_ih_print_status(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; dev_info(adev->dev, "CIK IH registers\n"); dev_info(adev->dev, " SRBM_STATUS=0x%08X\n", RREG32(mmSRBM_STATUS)); dev_info(adev->dev, " SRBM_STATUS2=0x%08X\n", RREG32(mmSRBM_STATUS2)); dev_info(adev->dev, " INTERRUPT_CNTL=0x%08X\n", RREG32(mmINTERRUPT_CNTL)); dev_info(adev->dev, " INTERRUPT_CNTL2=0x%08X\n", RREG32(mmINTERRUPT_CNTL2)); dev_info(adev->dev, " IH_CNTL=0x%08X\n", RREG32(mmIH_CNTL)); dev_info(adev->dev, " IH_RB_CNTL=0x%08X\n", RREG32(mmIH_RB_CNTL)); dev_info(adev->dev, " IH_RB_BASE=0x%08X\n", RREG32(mmIH_RB_BASE)); dev_info(adev->dev, " IH_RB_WPTR_ADDR_LO=0x%08X\n", RREG32(mmIH_RB_WPTR_ADDR_LO)); dev_info(adev->dev, " IH_RB_WPTR_ADDR_HI=0x%08X\n", RREG32(mmIH_RB_WPTR_ADDR_HI)); dev_info(adev->dev, " IH_RB_RPTR=0x%08X\n", RREG32(mmIH_RB_RPTR)); dev_info(adev->dev, " IH_RB_WPTR=0x%08X\n", RREG32(mmIH_RB_WPTR)); } static int cik_ih_soft_reset(void *handle) { struct amdgpu_device *adev = (struct amdgpu_device *)handle; u32 srbm_soft_reset = 0; u32 tmp = RREG32(mmSRBM_STATUS); if (tmp & SRBM_STATUS__IH_BUSY_MASK) srbm_soft_reset |= SRBM_SOFT_RESET__SOFT_RESET_IH_MASK; if (srbm_soft_reset) { cik_ih_print_status((void *)adev); tmp = RREG32(mmSRBM_SOFT_RESET); tmp |= srbm_soft_reset; dev_info(adev->dev, "SRBM_SOFT_RESET=0x%08X\n", tmp); WREG32(mmSRBM_SOFT_RESET, tmp); tmp = RREG32(mmSRBM_SOFT_RESET); udelay(50); tmp &= ~srbm_soft_reset; WREG32(mmSRBM_SOFT_RESET, tmp); tmp = RREG32(mmSRBM_SOFT_RESET); /* Wait a little for things to settle down */ udelay(50); cik_ih_print_status((void *)adev); } return 0; } static int cik_ih_set_clockgating_state(void *handle, enum amd_clockgating_state state) { return 0; } static int cik_ih_set_powergating_state(void *handle, enum amd_powergating_state state) { return 0; } const struct amd_ip_funcs cik_ih_ip_funcs = { .early_init = cik_ih_early_init, .late_init = NULL, .sw_init = cik_ih_sw_init, .sw_fini = cik_ih_sw_fini, .hw_init = cik_ih_hw_init, .hw_fini = cik_ih_hw_fini, .suspend = cik_ih_suspend, .resume = cik_ih_resume, .is_idle = cik_ih_is_idle, .wait_for_idle = cik_ih_wait_for_idle, .soft_reset = cik_ih_soft_reset, .print_status = cik_ih_print_status, .set_clockgating_state = cik_ih_set_clockgating_state, .set_powergating_state = cik_ih_set_powergating_state, }; static const struct amdgpu_ih_funcs cik_ih_funcs = { .get_wptr = cik_ih_get_wptr, .decode_iv = cik_ih_decode_iv, .set_rptr = cik_ih_set_rptr }; static void cik_ih_set_interrupt_funcs(struct amdgpu_device *adev) { if (adev->irq.ih_funcs == NULL) adev->irq.ih_funcs = &cik_ih_funcs; }
27.552301
99
0.716856
[ "vector", "3d" ]
30cb7db24fc8e914e7c7916419cf79ee6c72eba5
6,311
h
C
extensions/renderer/native_renderer_messaging_service.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
extensions/renderer/native_renderer_messaging_service.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
extensions/renderer/native_renderer_messaging_service.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EXTENSIONS_RENDERER_NATIVE_RENDERER_MESSAGING_SERVICE_H_ #define EXTENSIONS_RENDERER_NATIVE_RENDERER_MESSAGING_SERVICE_H_ #include <string> #include "base/macros.h" #include "extensions/common/extension_id.h" #include "extensions/renderer/gin_port.h" #include "extensions/renderer/one_time_message_handler.h" #include "extensions/renderer/renderer_messaging_service.h" #include "gin/handle.h" struct ExtensionMsg_ExternalConnectionInfo; struct ExtensionMsg_TabConnectionInfo; namespace extensions { class NativeExtensionBindingsSystem; struct Message; struct MessageTarget; struct PortId; // The messaging service to handle dispatching extension messages and connection // events to different contexts. // This primarily handles long-lived port-based communications (like // runtime.connect). A basic flow will create an "opener" port and one ore more // "receiver" ports in different contexts (and possibly processes). This class // manages the communication with the browser to forward these messages along. // From JavaScript, a basic flow would be: // // page1.js // var port = chrome.runtime.connect(); // port.onMessage.addListener(function() { <handle message> }); // port.postMessage('hi!'); // <eventually> port.disconnect(); // // page2.js // chrome.runtime.onConnect.addListener(function(port) { // port.onMessage.addListener(function() { <handle message> }); // port.postMessage('hey!'); // }); // This causes the following steps in the messaging service: // Connection: // * connect() triggers OpenChannelToExtension, which notifies the browser of // a new connection. // * The browser dispatches OnConnect messages to different renderers. If a // renderer has a listener, it will respond with an OpenMessagePort message. // If no renderer has a listener, the browser will close the port. // Message Posting // * Calls to postMessage() trigger a PostMessageToPort messge to the browser. // * The browser sends a DeliverMessage message to listening renderers. These // then dispatch the onMessage event to listeners. // Disconnecting // * disconnect() calls result in sending a CloseMessagePort message to the // browser. // * The browser then sends a DispatchOnDisconnect message to other renderers, // which triggers the onDisconnect() event. // TODO(devlin): This is a pretty large comment for a class, and it documents // browser/renderer interaction. I wonder if this would be better in a // messaging.md document? class NativeRendererMessagingService : public RendererMessagingService, public GinPort::Delegate { public: explicit NativeRendererMessagingService( NativeExtensionBindingsSystem* bindings_system); ~NativeRendererMessagingService() override; // Creates and opens a new message port in the specified context. gin::Handle<GinPort> Connect(ScriptContext* script_context, const MessageTarget& target, const std::string& name, bool include_tls_channel_id); // Sends a one-time message, as is used by runtime.sendMessage. void SendOneTimeMessage(ScriptContext* script_context, const MessageTarget& target, const std::string& channel_name, bool include_tls_channel_id, const Message& message, v8::Local<v8::Function> response_callback); // GinPort::Delegate: void PostMessageToPort(v8::Local<v8::Context> context, const PortId& port_id, int routing_id, std::unique_ptr<Message> message) override; void ClosePort(v8::Local<v8::Context> context, const PortId& port_id, int routing_id) override; gin::Handle<GinPort> CreatePortForTesting(ScriptContext* script_context, const std::string& channel_name, const PortId& port_id); gin::Handle<GinPort> GetPortForTesting(ScriptContext* script_context, const PortId& port_id); bool HasPortForTesting(ScriptContext* script_context, const PortId& port_id); private: // RendererMessagingService: bool ContextHasMessagePort(ScriptContext* script_context, const PortId& port_id) override; void DispatchOnConnectToListeners( ScriptContext* script_context, const PortId& target_port_id, const ExtensionId& target_extension_id, const std::string& channel_name, const ExtensionMsg_TabConnectionInfo* source, const ExtensionMsg_ExternalConnectionInfo& info, const std::string& tls_channel_id, const std::string& event_name) override; void DispatchOnMessageToListeners(ScriptContext* script_context, const Message& message, const PortId& target_port_id) override; void DispatchOnDisconnectToListeners(ScriptContext* script_context, const PortId& port_id, const std::string& error) override; // Creates a new port in the given context, with the specified |channel_name| // and |port_id|. Assumes no such port exists. gin::Handle<GinPort> CreatePort(ScriptContext* script_context, const std::string& channel_name, const PortId& port_id); // Returns the port with the given |port_id| in the given |script_context|; // requires that such a port exists. gin::Handle<GinPort> GetPort(ScriptContext* script_context, const PortId& port_id); // The associated bindings system; guaranteed to outlive this object. NativeExtensionBindingsSystem* const bindings_system_; OneTimeMessageHandler one_time_message_handler_; DISALLOW_COPY_AND_ASSIGN(NativeRendererMessagingService); }; } // namespace extensions #endif // EXTENSIONS_RENDERER_NATIVE_RENDERER_MESSAGING_SERVICE_H_
44.758865
80
0.686737
[ "object" ]
30cd99d00d8b9bf85c231b799f9404223394d3dd
6,577
h
C
Engine/PhysX/Include/geometry/PxGeometryHelpers.h
elliotjb/CulverinEngine-Project3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
4
2017-10-23T18:05:48.000Z
2017-11-29T06:57:26.000Z
Engine/PhysX/Include/geometry/PxGeometryHelpers.h
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
null
null
null
Engine/PhysX/Include/geometry/PxGeometryHelpers.h
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
1
2018-06-16T16:12:11.000Z
2018-06-16T16:12:11.000Z
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_GEOMETRYHELPERS #define PX_PHYSICS_GEOMETRYHELPERS /** \addtogroup geomutils @{ */ #include "../common/PxPhysXCommonConfig.h" #include "PxGeometry.h" #include "PxBoxGeometry.h" #include "PxSphereGeometry.h" #include "PxCapsuleGeometry.h" #include "PxPlaneGeometry.h" #include "PxConvexMeshGeometry.h" #include "PxTriangleMeshGeometry.h" #include "PxHeightFieldGeometry.h" #include "../foundation/PxPlane.h" #include "../foundation/PxTransform.h" #include "../foundation/PxUnionCast.h" #if !PX_DOXYGEN namespace physx { #endif /** \brief Geometry holder class This class contains enough space to hold a value of any PxGeometry subtype. Its principal use is as a convenience class to allow geometries to be returned polymorphically from functions. See PxShape::getGeometry(); */ PX_ALIGN_PREFIX(4) class PxGeometryHolder { public: PX_FORCE_INLINE PxGeometryType::Enum getType() const { return any().getType(); } PX_FORCE_INLINE PxGeometry& any() { return *PxUnionCast<PxGeometry*>(&bytes.geometry); } PX_FORCE_INLINE const PxGeometry& any() const { return *PxUnionCast<const PxGeometry*>(&bytes.geometry); } PX_FORCE_INLINE PxSphereGeometry& sphere() { return get<PxSphereGeometry, PxGeometryType::eSPHERE>(); } PX_FORCE_INLINE const PxSphereGeometry& sphere() const { return get<const PxSphereGeometry, PxGeometryType::eSPHERE>(); } PX_FORCE_INLINE PxPlaneGeometry& plane() { return get<PxPlaneGeometry, PxGeometryType::ePLANE>(); } PX_FORCE_INLINE const PxPlaneGeometry& plane() const { return get<const PxPlaneGeometry, PxGeometryType::ePLANE>(); } PX_FORCE_INLINE PxCapsuleGeometry& capsule() { return get<PxCapsuleGeometry, PxGeometryType::eCAPSULE>(); } PX_FORCE_INLINE const PxCapsuleGeometry& capsule() const { return get<const PxCapsuleGeometry, PxGeometryType::eCAPSULE>(); } PX_FORCE_INLINE PxBoxGeometry& box() { return get<PxBoxGeometry, PxGeometryType::eBOX>(); } PX_FORCE_INLINE const PxBoxGeometry& box() const { return get<const PxBoxGeometry, PxGeometryType::eBOX>(); } PX_FORCE_INLINE PxConvexMeshGeometry& convexMesh() { return get<PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>(); } PX_FORCE_INLINE const PxConvexMeshGeometry& convexMesh() const { return get<const PxConvexMeshGeometry, PxGeometryType::eCONVEXMESH>(); } PX_FORCE_INLINE PxTriangleMeshGeometry& triangleMesh() { return get<PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>(); } PX_FORCE_INLINE const PxTriangleMeshGeometry& triangleMesh() const { return get<const PxTriangleMeshGeometry, PxGeometryType::eTRIANGLEMESH>(); } PX_FORCE_INLINE PxHeightFieldGeometry& heightField() { return get<PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>(); } PX_FORCE_INLINE const PxHeightFieldGeometry& heightField() const { return get<const PxHeightFieldGeometry, PxGeometryType::eHEIGHTFIELD>(); } PX_FORCE_INLINE void storeAny(const PxGeometry& geometry) { PX_ASSERT_WITH_MESSAGE( (geometry.getType() >= PxGeometryType::eSPHERE) && (geometry.getType() < PxGeometryType::eGEOMETRY_COUNT), "Unexpected GeometryType in PxGeometryHolder::storeAny"); switch(geometry.getType()) { case PxGeometryType::eSPHERE: put<PxSphereGeometry>(geometry); break; case PxGeometryType::ePLANE: put<PxPlaneGeometry>(geometry); break; case PxGeometryType::eCAPSULE: put<PxCapsuleGeometry>(geometry); break; case PxGeometryType::eBOX: put<PxBoxGeometry>(geometry); break; case PxGeometryType::eCONVEXMESH: put<PxConvexMeshGeometry>(geometry); break; case PxGeometryType::eTRIANGLEMESH: put<PxTriangleMeshGeometry>(geometry); break; case PxGeometryType::eHEIGHTFIELD: put<PxHeightFieldGeometry>(geometry); break; case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: break; } } PX_FORCE_INLINE PxGeometryHolder() {} PX_FORCE_INLINE PxGeometryHolder(const PxGeometry& geometry){ storeAny(geometry); } private: template<typename T> void put(const PxGeometry& geometry) { static_cast<T&>(any()) = static_cast<const T&>(geometry); } template<typename T, PxGeometryType::Enum type> T& get() { PX_ASSERT(getType() == type); return static_cast<T&>(any()); } template<typename T, PxGeometryType::Enum type> T& get() const { PX_ASSERT(getType() == type); return static_cast<T&>(any()); } union { PxU8 geometry[sizeof(PxGeometry)]; PxU8 box[sizeof(PxBoxGeometry)]; PxU8 sphere[sizeof(PxSphereGeometry)]; PxU8 capsule[sizeof(PxCapsuleGeometry)]; PxU8 plane[sizeof(PxPlaneGeometry)]; PxU8 convex[sizeof(PxConvexMeshGeometry)]; PxU8 mesh[sizeof(PxTriangleMeshGeometry)]; PxU8 heightfield[sizeof(PxHeightFieldGeometry)]; } bytes; } PX_ALIGN_SUFFIX(4); #if !PX_DOXYGEN } // namespace physx #endif /** @} */ #endif
30.449074
95
0.764634
[ "mesh", "geometry" ]
30d3e95a4bfebae5dd6fff6c8ca2430bd2ca8e55
27,292
h
C
modules/platforms/cpp/odbc/include/ignite/odbc/message.h
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/platforms/cpp/odbc/include/ignite/odbc/message.h
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/platforms/cpp/odbc/include/ignite/odbc/message.h
tsdb-io/gridgain
6726ed9cc34a7d2671a3625600c375939d40bc35
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _IGNITE_ODBC_MESSAGE #define _IGNITE_ODBC_MESSAGE #include <stdint.h> #include <string> #include "ignite/impl/binary/binary_writer_impl.h" #include "ignite/impl/binary/binary_reader_impl.h" #include "ignite/odbc/result_page.h" #include "ignite/odbc/protocol_version.h" #include "ignite/odbc/meta/column_meta.h" #include "ignite/odbc/meta/table_meta.h" #include "ignite/odbc/app/parameter_set.h" #include "config/configuration.h" namespace ignite { namespace odbc { namespace streaming { // Forward declaration. class StreamingBatch; } struct ClientType { enum Type { ODBC = 0 }; }; struct RequestType { enum Type { HANDSHAKE = 1, EXECUTE_SQL_QUERY = 2, FETCH_SQL_QUERY = 3, CLOSE_SQL_QUERY = 4, GET_COLUMNS_METADATA = 5, GET_TABLES_METADATA = 6, GET_PARAMS_METADATA = 7, EXECUTE_SQL_QUERY_BATCH = 8, QUERY_MORE_RESULTS = 9, STREAMING_BATCH = 10, META_RESULTSET = 11 }; }; /** * Handshake request. */ class HandshakeRequest { public: /** * Constructor. * * @param config Configuration. */ HandshakeRequest(const config::Configuration& config); /** * Destructor. */ ~HandshakeRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Configuration. */ const config::Configuration& config; }; /** * Query execute request. */ class QueryExecuteRequest { public: /** * Constructor. * * @param schema Schema. * @param sql SQL query. * @param params Query arguments. * @param timeout Timeout. * @param autoCommit Auto commit flag. */ QueryExecuteRequest(const std::string& schema, const std::string& sql, const app::ParameterSet& params, int32_t timeout, bool autoCommit); /** * Destructor. */ ~QueryExecuteRequest(); /** * Write request using provided writer. * @param writer Writer. * @param ver Version. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion& ver) const; private: /** Schema name. */ std::string schema; /** SQL query. */ std::string sql; /** Parameters bindings. */ const app::ParameterSet& params; /** Timeout. */ int32_t timeout; /** Auto commit. */ bool autoCommit; }; /** * Query execute batch request. */ class QueryExecuteBatchRequest { public: /** * Constructor. * * @param schema Schema. * @param sql SQL query. * @param params Query arguments. * @param begin Beginning of the interval. * @param end End of the interval. * @param timeout Timeout. * @param autoCommit Auto commit flag. */ QueryExecuteBatchRequest(const std::string& schema, const std::string& sql, const app::ParameterSet& params, SqlUlen begin, SqlUlen end, bool last, int32_t timeout, bool autoCommit); /** * Destructor. */ ~QueryExecuteBatchRequest(); /** * Write request using provided writer. * @param writer Writer. * @param ver Version. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion& ver) const; private: /** Schema name. */ std::string schema; /** SQL query. */ std::string sql; /** Parameters bindings. */ const app::ParameterSet& params; /** Beginning of the interval. */ SqlUlen begin; /** End of the interval. */ SqlUlen end; /** Last page flag. */ bool last; /** Timeout. */ int32_t timeout; /** Auto commit. */ bool autoCommit; }; /** * Query close request. */ class QueryCloseRequest { public: /** * Constructor. * * @param queryId Query ID. */ QueryCloseRequest(int64_t queryId); /** * Destructor. */ ~QueryCloseRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Query ID. */ int64_t queryId; }; /** * Query fetch request. */ class QueryFetchRequest { public: /** * Constructor. * * @param queryId Query ID. * @param pageSize Required page size. */ QueryFetchRequest(int64_t queryId, int32_t pageSize); /** * Destructor. */ ~QueryFetchRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Query ID. */ int64_t queryId; /** SQL query. */ int32_t pageSize; }; /** * Query get columns metadata request. */ class QueryGetColumnsMetaRequest { public: /** * Constructor. * * @param schema Schema name. * @param table Table name. * @param column Column name. */ QueryGetColumnsMetaRequest(const std::string& schema, const std::string& table, const std::string& column); /** * Destructor. */ ~QueryGetColumnsMetaRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Schema search pattern. */ std::string schema; /** Table search pattern. */ std::string table; /** Column search pattern. */ std::string column; }; /** * Query get result set metadata request. */ class QueryGetResultsetMetaRequest { public: /** * Constructor. * * @param schema Schema. * @param sqlQuery SQL query itself. */ QueryGetResultsetMetaRequest(const std::string& schema, const std::string& sqlQuery); /** * Destructor. */ ~QueryGetResultsetMetaRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Schema. */ std::string schema; /** SQL query. */ std::string sqlQuery; }; /** * Query get tables metadata request. */ class QueryGetTablesMetaRequest { public: /** * Constructor. * * @param catalog Catalog search pattern. * @param schema Schema search pattern. * @param table Table search pattern. * @param tableTypes Table types search pattern. */ QueryGetTablesMetaRequest(const std::string& catalog, const std::string& schema, const std::string& table, const std::string& tableTypes); /** * Destructor. */ ~QueryGetTablesMetaRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Column search pattern. */ std::string catalog; /** Schema search pattern. */ std::string schema; /** Table search pattern. */ std::string table; /** Column search pattern. */ std::string tableTypes; }; /** * Get parameter metadata request. */ class QueryGetParamsMetaRequest { public: /** * Constructor. * * @param schema Schema. * @param sqlQuery SQL query itself. */ QueryGetParamsMetaRequest(const std::string& schema, const std::string& sqlQuery) : schema(schema), sqlQuery(sqlQuery) { // No-op. } /** * Destructor. */ ~QueryGetParamsMetaRequest() { // No-op. } /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Schema. */ std::string schema; /** SQL query. */ std::string sqlQuery; }; /** * Query fetch request. */ class QueryMoreResultsRequest { public: /** * Constructor. * * @param queryId Query ID. * @param pageSize Required page size. */ QueryMoreResultsRequest(int64_t queryId, int32_t pageSize) : queryId(queryId), pageSize(pageSize) { // No-op. } /** * Destructor. */ ~QueryMoreResultsRequest() { // No-op. } /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Query ID. */ int64_t queryId; /** SQL query. */ int32_t pageSize; }; /** * Streaming batch request. */ class StreamingBatchRequest { public: /** * Constructor. * * @param schema Schema. * @param batch Batch. * @param last Last batch indicator. * @param order Order. */ StreamingBatchRequest(const std::string& schema, const streaming::StreamingBatch& batch, bool last, int64_t order); /** * Destructor. */ ~StreamingBatchRequest(); /** * Write request using provided writer. * @param writer Writer. */ void Write(impl::binary::BinaryWriterImpl& writer, const ProtocolVersion&) const; private: /** Schema name. */ std::string schema; /** Batch. */ const streaming::StreamingBatch& batch; /** Last page flag. */ bool last; /** Order. */ int64_t order; }; /** * General response. */ class Response { public: /** * Constructor. */ Response(); /** * Destructor. */ virtual ~Response(); /** * Read response using provided reader. * @param reader Reader. * @param ver Protocol version. */ void Read(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion& ver); /** * Get request processing status. * @return Status. */ int32_t GetStatus() const { return status; } /** * Get resulting error. * @return Error. */ const std::string& GetError() const { return error; } protected: /** * Read data if response status is ResponseStatus::SUCCESS. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl&, const ProtocolVersion&); private: /** Request processing status. */ int32_t status; /** Error message. */ std::string error; }; /** * Handshake response. */ class HandshakeResponse { public: /** * Constructor. */ HandshakeResponse(); /** * Destructor. */ ~HandshakeResponse(); /** * Check if the handshake has been accepted. * @return True if the handshake has been accepted. */ bool IsAccepted() const { return accepted; } /** * Get optional error. * @return Optional error message. */ const std::string& GetError() const { return error; } /** * Current host Apache Ignite version. * @return Current host Apache Ignite version. */ const ProtocolVersion& GetCurrentVer() const { return currentVer; } /** * Read response using provided reader. * @param reader Reader. */ void Read(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); private: /** Handshake accepted. */ bool accepted; /** Node's protocol version. */ ProtocolVersion currentVer; /** Optional error message. */ std::string error; }; /** * Query close response. */ class QueryCloseResponse : public Response { public: /** * Constructor. */ QueryCloseResponse(); /** * Destructor. */ virtual ~QueryCloseResponse(); /** * Get query ID. * @return Query ID. */ int64_t GetQueryId() const { return queryId; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Query ID. */ int64_t queryId; }; /** * Query execute response. */ class QueryExecuteResponse : public Response { public: /** * Constructor. */ QueryExecuteResponse(); /** * Destructor. */ virtual ~QueryExecuteResponse(); /** * Get query ID. * @return Query ID. */ int64_t GetQueryId() const { return queryId; } /** * Get column metadata. * @return Column metadata. */ const meta::ColumnMetaVector& GetMeta() const { return meta; } /** * Get affected rows number. * @return Number of rows affected by the query. */ const std::vector<int64_t>& GetAffectedRows() { return affectedRows; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion& ver); /** Query ID. */ int64_t queryId; /** Columns metadata. */ meta::ColumnMetaVector meta; /** Number of affected rows. */ std::vector<int64_t> affectedRows; }; /** * Query execute batch start response. */ class QueryExecuteBatchResponse : public Response { public: /** * Constructor. */ QueryExecuteBatchResponse(); /** * Destructor. */ virtual ~QueryExecuteBatchResponse(); /** * Affected rows. * @return Affected rows. */ const std::vector<int64_t>& GetAffectedRows() const { return affectedRows; } /** * Get error message. * @return Error message. */ const std::string& GetErrorMessage() const { return errorMessage; } /** * Get error code. * @return Error code. */ int32_t GetErrorCode() const { return errorCode; } private: /** * Read response using provided reader. * @param reader Reader. * @param ver Protocol version. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion& ver); /** Affected rows. */ std::vector<int64_t> affectedRows; /** Error message. */ std::string errorMessage; /** Error code. */ int32_t errorCode; }; /** * Streaming batch response. */ class StreamingBatchResponse : public Response { public: /** * Constructor. */ StreamingBatchResponse(); /** * Destructor. */ virtual ~StreamingBatchResponse(); /** * Get error message. * @return Error message. */ const std::string& GetErrorMessage() const { return errorMessage; } /** * Get error code. * @return Error code. */ int32_t GetErrorCode() const { return errorCode; } /** * Get order. * @return Order. */ int64_t GetOrder() const { return order; } private: /** * Read response using provided reader. * @param reader Reader. * @param ver Protocol version. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion& ver); /** Error message. */ std::string errorMessage; /** Error code. */ int32_t errorCode; /** Order. */ int64_t order; }; /** * Query fetch response. */ class QueryFetchResponse : public Response { public: /** * Constructor. * @param resultPage Result page. */ QueryFetchResponse(ResultPage& resultPage); /** * Destructor. */ virtual ~QueryFetchResponse(); /** * Get query ID. * @return Query ID. */ int64_t GetQueryId() const { return queryId; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Query ID. */ int64_t queryId; /** Result page. */ ResultPage& resultPage; }; /** * Query get column metadata response. */ class QueryGetColumnsMetaResponse : public Response { public: /** * Constructor. */ QueryGetColumnsMetaResponse(); /** * Destructor. */ virtual ~QueryGetColumnsMetaResponse(); /** * Get column metadata. * @return Column metadata. */ const meta::ColumnMetaVector& GetMeta() const { return meta; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Columns metadata. */ meta::ColumnMetaVector meta; }; /** * Query get resultset metadata response. */ class QueryGetResultsetMetaResponse : public Response { public: /** * Constructor. */ QueryGetResultsetMetaResponse(); /** * Destructor. */ virtual ~QueryGetResultsetMetaResponse(); /** * Get column metadata. * @return Column metadata. */ const meta::ColumnMetaVector& GetMeta() const { return meta; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Columns metadata. */ meta::ColumnMetaVector meta; }; /** * Query get table metadata response. */ class QueryGetTablesMetaResponse : public Response { public: /** * Constructor. */ QueryGetTablesMetaResponse(); /** * Destructor. */ virtual ~QueryGetTablesMetaResponse(); /** * Get column metadata. * @return Column metadata. */ const meta::TableMetaVector& GetMeta() const { return meta; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Columns metadata. */ meta::TableMetaVector meta; }; /** * Get params metadata response. */ class QueryGetParamsMetaResponse : public Response { public: /** * Constructor. */ QueryGetParamsMetaResponse(); /** * Destructor. */ virtual ~QueryGetParamsMetaResponse(); /** * Get parameter type IDs. * @return Type IDs. */ const std::vector<int8_t>& GetTypeIds() const { return typeIds; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Columns metadata. */ std::vector<int8_t> typeIds; }; /** * Query fetch response. */ class QueryMoreResultsResponse : public Response { public: /** * Constructor. * @param resultPage Result page. */ QueryMoreResultsResponse(ResultPage& resultPage); /** * Destructor. */ virtual ~QueryMoreResultsResponse(); /** * Get query ID. * @return Query ID. */ int64_t GetQueryId() const { return queryId; } private: /** * Read response using provided reader. * @param reader Reader. */ virtual void ReadOnSuccess(impl::binary::BinaryReaderImpl& reader, const ProtocolVersion&); /** Query ID. */ int64_t queryId; /** Result page. */ ResultPage& resultPage; }; } } #endif //_IGNITE_ODBC_MESSAGE
25.435228
119
0.445588
[ "vector" ]
30d65cd803102639ecdcd24ba2427ca62f5d57f4
10,418
c
C
proctable.c
mvermeulen/wspy
f1c42747600687bc3ec8fae772e837a60ccb0380
[ "MIT" ]
2
2019-06-03T17:11:07.000Z
2021-07-02T11:37:30.000Z
proctable.c
mvermeulen/wspy
f1c42747600687bc3ec8fae772e837a60ccb0380
[ "MIT" ]
null
null
null
proctable.c
mvermeulen/wspy
f1c42747600687bc3ec8fae772e837a60ccb0380
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include "wspy.h" #include "error.h" void finalize_syscall_open(procinfo *pinfo); #define HASHBUCKETS 127 struct proctable_hash_entry { procinfo *pinfo; struct proctable_hash_entry *next; }; struct proctable_hash_entry *process_table[HASHBUCKETS] = { 0 }; procinfo *lookup_process_info(pid_t pid,int insert){ struct proctable_hash_entry *hentry; procinfo *pinfo,*ppinfo,*pinfo_sibling; for (hentry = process_table[pid%HASHBUCKETS];hentry != NULL;hentry = hentry->next){ // pid's can wrap around, so skip processes if they've exited if ((!flag_require_ptrace || hentry->pinfo->p_exited) && (!flag_require_ftrace || hentry->pinfo->f_exited)) continue; // if (hentry->pinfo->exited) continue; if (hentry->pinfo->pid == pid){ return hentry->pinfo; } } // not found if (insert == 0){ return NULL; } // splice in a new entry pinfo = calloc(1,sizeof(procinfo)); hentry = calloc(1,sizeof(struct proctable_hash_entry)); hentry->pinfo = pinfo; hentry->next = process_table[pid%HASHBUCKETS]; process_table[pid%HASHBUCKETS] = hentry; pinfo->pid = pid; return pinfo; } procinfo *reverse_siblings(procinfo *p){ procinfo *new_p = NULL; procinfo *next; while (p){ next = p->sibling; p->sibling = new_p; new_p = p; p = next; } return new_p; } void print_open_info(FILE *output,struct open_file_info *oinfo,int level){ int i; for (i=0;i<level;i++){ fprintf(output," "); } fprintf(output," >open: %3d %s\n",oinfo->result,oinfo->filename); } static int clocks_per_second = 0; void print_process_tree(FILE *output,procinfo *pinfo,int level,double basetime){ int i; double elapsed = pinfo->time_finish - pinfo->time_start; procinfo *child; double on_cpu,on_core; unsigned long total_time; unsigned long fetch_bubbles,total_slots,slots_issued,slots_retired,recovery_bubbles; unsigned long cpu_cycles; double frontend_bound,retiring,speculation,backend_bound; char *vendor; struct open_file_info *oinfo; vendor = lookup_vendor(); if (pinfo == NULL) return; if (level > 100) return; if (clocks_per_second == 0) clocks_per_second = sysconf(_SC_CLK_TCK); for (i=0;i<level;i++){ fprintf(output," "); } if (pinfo->cloned) fprintf(output,"(%d)",pinfo->pid); else fprintf(output,"[%d]",pinfo->pid); if (pinfo->filename) fprintf(output," %-12s",pinfo->filename); else fprintf(output," %-12s",pinfo->comm); fprintf(output," cpu=%d",pinfo->cpu); if (perf_counters_same == NULL){ // counters were not reset, so we can print the defaults if (flag_require_perftree && flag_require_ptrace){ if (pinfo->total_counter[1]){ fprintf(output," ipc=%4.2f", (double) pinfo->total_counter[0] / pinfo->total_counter[1]); } total_time = pinfo->total_utime + pinfo->total_stime; if (total_time){ on_core = (double) total_time/clocks_per_second/elapsed; on_cpu = on_core / num_procs; fprintf(output," on_cpu=%3.2f on_core=%3.2f",on_cpu,on_core); } // Intel topdown metrics, note scaling wasn't done yet so do it here if (vendor && !strcmp(vendor,"GenuineIntel")){ total_slots = pinfo->total_counter[1]*2; fetch_bubbles = pinfo->total_counter[2]; recovery_bubbles = pinfo->total_counter[3]*2; slots_issued = pinfo->total_counter[4]; slots_retired = pinfo->total_counter[5]; frontend_bound = (double) fetch_bubbles / total_slots; retiring = (double) slots_retired / total_slots; speculation = (double) (slots_issued - slots_retired + recovery_bubbles) / total_slots; backend_bound = 1 - (frontend_bound + retiring + speculation); if (total_slots){ fprintf(output," retire=%4.3f",retiring); fprintf(output," frontend=%4.3f",frontend_bound); fprintf(output," spec=%4.3f",speculation); fprintf(output," backend=%4.3f",backend_bound); } } else if (vendor && !strcmp(vendor,"AuthenticAMD")){ cpu_cycles = pinfo->total_counter[1]; frontend_bound = pinfo->total_counter[2]; backend_bound = pinfo->total_counter[3]; if (cpu_cycles){ fprintf(output," frontend=%4.3f",frontend_bound / cpu_cycles); fprintf(output," backend=%4.3f",backend_bound / cpu_cycles); } } } if (get_error_level() >= ERROR_LEVEL_DEBUG){ fprintf(output," inst=%lu cycles=%lu", pinfo->total_counter[0],pinfo->total_counter[1]); } fprintf(output," elapsed=%5.2f",elapsed); } else { for (i=0;i<NUM_COUNTERS_PER_PROCESS;i++){ if (perf_counters_by_process[i]){ fprintf(output," %s=%lu",perf_counters_by_process[i]->name,pinfo->pci.perf_counter[i]); } } } if (pinfo->f_exited){ fprintf(output," start=%5.2f finish=%5.2f",pinfo->time_start-basetime,pinfo->time_finish-basetime); } else if (pinfo->p_exited){ fprintf(output," user=%4.2f system=%4.2f", pinfo->utime / (double) clocks_per_second, pinfo->stime / (double) clocks_per_second); } fprintf(output," pcount=%d",pinfo->pcount); fprintf(output,"\n"); pinfo->printed = 1; for (oinfo = pinfo->syscall_open;oinfo;oinfo = oinfo->next){ print_open_info(output,oinfo,level); } for (child = pinfo->child;child;child = child->sibling){ print_process_tree(output,child,level+1,basetime); } } // print all the rooted trees // if "name" != NULL, then print roots starting at name // otherwise print general roots void print_all_process_trees(FILE *output,double basetime,char *name){ int i; struct proctable_hash_entry *hash; for (i=0;i<HASHBUCKETS;i++){ for (hash = process_table[i];hash;hash = hash->next){ if (hash->pinfo->printed) continue; if (name != NULL){ if (!hash->pinfo->filename && !hash->pinfo->comm) continue; if (hash->pinfo->filename){ if (!strcmp(hash->pinfo->filename,name) && !hash->pinfo->printed){ print_process_tree(output,hash->pinfo,0,basetime); } } else if (hash->pinfo->comm){ if (!strcmp(hash->pinfo->comm,name) && ((hash->pinfo->parent == NULL) || (hash->pinfo->parent->comm == NULL) || (strcmp(hash->pinfo->parent->comm,name) != 0))){ print_process_tree(output,hash->pinfo,0,basetime); } } } else { // only print top level trees if (hash->pinfo->parent) continue; print_process_tree(output,hash->pinfo,0,basetime); } } } } // dump process csv // - dump all process info; return count of # of records int print_all_processes_csv(FILE *output){ int count = 0; int i,j; procinfo *pinfo; struct counterlist *cl; struct proctable_hash_entry *hash; fprintf(output,"#version 10\n"); fprintf(output,"#pid,ppid,filename,starttime,start,finish,cpu,utime,stime,cutime,cstime,vsize,rss,minflt,majflt,num_counters,"); for (j=0;j<NUM_COUNTERS_PER_PROCESS;j++){ fprintf(output,"counter%d,",j); } fprintf(output,"\n"); for (i=0;i<HASHBUCKETS;i++){ for (hash = process_table[i];hash;hash = hash->next){ pinfo = hash->pinfo; fprintf(output,"%d,%d,",pinfo->pid,pinfo->ppid); if (pinfo->filename) fprintf(output,"%s,",pinfo->filename); else if (pinfo->comm) fprintf(output,"%s,",pinfo->comm); else fprintf(output,"?,"); fprintf(output,"%llu,%6.5f,%6.5f,",pinfo->starttime,pinfo->time_start,pinfo->time_finish); fprintf(output,"%d,",pinfo->cpu); fprintf(output,"%lu,%lu,%lu,%lu,",pinfo->utime,pinfo->stime,pinfo->cutime,pinfo->cstime); fprintf(output,"%lu,%lu,",pinfo->vsize,pinfo->rss); fprintf(output,"%lu,%lu,",pinfo->minflt,pinfo->majflt); fprintf(output,"%d,",NUM_COUNTERS_PER_PROCESS); for (j=0;j<NUM_COUNTERS_PER_PROCESS;j++){ if ((cl = perf_counters_by_process[j]) && cl->ci->scale){ fprintf(output,"%lu,",pinfo->pci.perf_counter[j]*cl->ci->scale); } else { fprintf(output,"%lu,",pinfo->pci.perf_counter[j]); } } fprintf(output,"\n"); count++; } } return count; } void sum_counts_processes(procinfo *pinfo); // make remaining tweaks before printing, e.g. reverse sibling order void finalize_process_tree(void){ int i; struct proctable_hash_entry *hash; // fix the sibling orders for (i=0;i<HASHBUCKETS;i++){ for (hash = process_table[i];hash;hash = hash->next){ // update the counts sum_counts_processes(hash->pinfo); // fix up any children if (hash->pinfo->child && !hash->pinfo->sibling_order){ hash->pinfo->child = reverse_siblings(hash->pinfo->child); hash->pinfo->sibling_order = 1; } // fix up open counts finalize_syscall_open(hash->pinfo); } } } // count # of children of a process (including self) // total the utime and stime // total the performance counter times void sum_counts_processes(procinfo *pinfo){ int i; int pcount; unsigned long total_utime; unsigned long total_stime; unsigned long total_counter[NUM_COUNTERS_PER_PROCESS]; procinfo *child; if (pinfo->pcount == 0){ // not yet counted pcount = 1; total_utime = pinfo->utime; total_stime = pinfo->stime; for (i=0;i<NUM_COUNTERS_PER_PROCESS;i++) total_counter[i] = pinfo->pci.perf_counter[i]; for (child = pinfo->child;child;child = child->sibling){ sum_counts_processes(child); pcount += child->pcount; total_utime += child->total_utime; total_stime += child->total_stime; for (i=0;i<NUM_COUNTERS_PER_PROCESS;i++) total_counter[i] += child->total_counter[i]; } pinfo->pcount = pcount; pinfo->total_utime = total_utime; pinfo->total_stime = total_stime; for (i=0;i<NUM_COUNTERS_PER_PROCESS;i++) pinfo->total_counter[i] = total_counter[i]; } } // builds a linked list where "syscall_open" always points to the last void add_process_syscall_open(procinfo *pinfo,char *filename,int result){ struct open_file_info *fi = calloc(1,sizeof(struct open_file_info)); fi->filename = strdup(filename); fi->result = result; fi->prev = pinfo->syscall_open; if (pinfo->syscall_open){ pinfo->syscall_open->next = fi; } pinfo->syscall_open = fi; } // update the linked list so "syscall_open" now points to the first void finalize_syscall_open(procinfo *pinfo){ struct open_file_info *fi = pinfo->syscall_open; if (fi == NULL) return; // run until we have no previous entries while (fi->prev) fi = fi->prev; pinfo->syscall_open = fi; }
32.658307
130
0.671626
[ "3d" ]
30d81fb84548130a576111427d4be6e90e26e6cb
235,390
c
C
src/vnmr/recon_all.c
DanIverson/OpenVnmrJ
0db324603dbd8f618a6a9526b9477a999c5a4cc3
[ "Apache-2.0" ]
32
2016-06-17T05:04:26.000Z
2022-03-28T17:54:44.000Z
src/vnmr/recon_all.c
timburrow/openvnmrj-source
f5e65eb2db4bded3437701f0fa91abd41928579c
[ "Apache-2.0" ]
128
2016-07-13T17:09:02.000Z
2022-03-28T17:53:52.000Z
src/vnmr/recon_all.c
timburrow/openvnmrj-source
f5e65eb2db4bded3437701f0fa91abd41928579c
[ "Apache-2.0" ]
102
2016-01-23T15:27:16.000Z
2022-03-20T05:41:54.000Z
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /***************************************************************************** * File recon_all.c: * * main reconstruction for all sequences (fid data --> images)* note: no conversion of fid file to standard or compressed format is performed * * made into generalized recon including multi-channel 3-28-2002 M. Kritzer * ******************************************************************************/ #include <math.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/file.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/statvfs.h> #include <fcntl.h> #include <stdlib.h> #include <arpa/inet.h> #include <inttypes.h> #include "data.h" #include "group.h" #include "mfileObj.h" #include "symtab.h" #include "vnmrsys.h" #include "variables.h" #include "fft.h" #include "ftpar.h" #include "process.h" #include "epi_recon.h" #include "phase_correct.h" #include "mfileObj.h" #include "vfilesys.h" #include "allocate.h" #include "pvars.h" #include "wjunk.h" #include "graphics.h" #include "init2d.h" #include "buttons.h" #ifdef VNMRJ #include "aipCInterface.h" #endif extern int interuption; extern void Vperror(char *); extern int specIndex; extern double getfpmult(int fdimname, int ddr); extern int unlinkFilesWithSuffix(char *dirpath, char *suffix); static float *slicedata, *pc, *magnitude, *mag2; static float *slicedata_neg, *pc_neg; static float *imdata, *imdata2, *imdata_neg, *imdata2_neg; static float *rawmag, *rawphs, *imgphs, *imgphs2; static float *navdata; static double *nav_refphase; static int *view_order, *nav_list; static int *skview_order; static int *sskview_order; static int *sview_order; static int *slice_order; static int *blockreps; static int *blockrepeat; static int *repeat; static int *nts; static short *pc_done, *pcneg_done, *pcd; static reconInfo rInfo; static int reconInfoSet = 0; static int realtime_block; static int recon_aborted; static double *ro_frqP, *pe_frqP; int nmice; float *pss; float *upss; /* prototypes */ void recon_abort(); char *recon_allocate(int, char *); int write_fdf(int, float *, fdfInfo *, int *, int, char *, int, int); int write_3Dfdf(float *, fdfInfo *, char *, int); int svcalc(int, int, svInfo *, int *, int *, int *, int *, int *); int psscompare(const void *, const void *); int upsscompare(const void *, const void *); int pcompare(const void *, const void *); void threeD_ft(float *, int, int, int, float *, float *, int, int, int, int, float *, double *, double *); static int recon_space_check(); static int generate_images(char *arstr); static int generate_images3D(char *arstr); static void phase_ft(float *xkydata, int nx, int ny, float *win, float *absdata, int phase_rev, int zeropad_ro, int zeropad_ph, float ro_frq, float ph_frq, float *phsdata, int output_type); static void filter_window(int window_type, float *window, int npts); static void fftshift(float *data, int npts); static void nav_correct(int method, float *data, double *ref_phase, int nro, int npe, float *navdata, svInfo *svI); int arraycheck(char *param, char *arraystr); int arrayparse(char *arraystring, int *nparams, arrayElement **arrayelsPP, int phasesize, int sviewsize); int smartphsfit(float *input, double *inphs, int npts, double *outphs); int pc_pick(char *pc_str); int arrayfdf(int block, int np, arrayElement *arrayels, char *fdfstring); extern void rotate_fid(float *fptr,double p0, double p1,int np, int dt); extern int pc_calc(float *d, float *r, int es, int etl, int m, int tr); extern int getphase(int ie, int el, int nv, double *ph, float *data, int tr); extern int phaseunwrap(double *i, int n, double *o); extern int polyfit(double *i, int n, double *o, int or); extern int svprocpar(int ff, char *fp); /*******************************************************************************/ /*******************************************************************************/ /* RECON_ALL */ /*******************************************************************************/ /*******************************************************************************/ /* Purpose: ------- Routine recon_all is the program for epi reconstruction. Arguments: --------- argc : ( ) Argument count. argv : ( ) Command line arguments. retc : ( ) Return argument count. Not used here. retv : ( ) Return arguments. Not used here */ int recon_all(int argc, char *argv[], int retc, char *retv[]) { /* Local Variables: */ FILE *f1; FILE *table_ptr; char filepath[MAXPATHL]; char tablefile[MAXPATHL]; char tempdir[MAXPATHL]; char petable[MAXSTR]; char sequence[MAXSTR]; char studyid[MAXSTR]; char pos1[MAXSTR]; char pos2[MAXSTR]; char tnstring[MAXSTR]; char dnstring[MAXSTR]; char apptype[MAXSTR]; char msintlv[MAXSTR]; char fdfstr[MAXSTR]; char rcvrs_str[MAXSTR]; char rscfilename[MAXPATHL]; char epi_pc[MAXSTR]; char nav_type[MAXSTR]; char recon_windowstr[MAXSTR]; char aname[SHORTSTR]; char nav_str[SHORTSTR]; char tmp_str[SHORTSTR]; char dcrmv[SHORTSTR]; char profstr[SHORTSTR]; char arraystr[MAXSTR]; char *ptr; char *imptr; char str[MAXSTR]; short *sdataptr; char *serr; vInfo info; double fpointmult; double rnseg, rfc, retl, rnv, rnv2; double recon_force; double rimflag; double a1, b1; double dt2; double rechoes, repi_rev; double rslices, rnf; double dtemp; double m1, m2; double acqtime; dpointers inblock; dblockhead *bhp; dfilehead *fid_file_head; #ifdef LINUX dfilehead tmpFileHead; dblockhead tmpBhp; #endif float pss0; float *pss2; float *fptr, *nrptr; float *datptr=NULL; float *wptr; float *read_window=NULL; float *phase_window=NULL; float *phase2_window=NULL; float *nav_window=NULL; float *fdataptr; float *pc_temp; float real_dc = 0.0, imag_dc = 0.0; double ro_frq, pe_frq; double ro_ph, pe_ph; float a, b, c, d; float t1, t2, *pt1, *pt2, *pt3, *pt4, *pt5, *pt6; float ftemp; float *fdptr; float nt_scale=1.0; int ierr; int floatstatus; int status=0; int echoes=1; int tstch; int slab; int *idataptr; int imglen=0; int dimfirst, imfound; int dimafter =1; int imzero, imneg1, imneg2; int icnt; int nv=1; int uslice; int ispb, itrc, it; int ip; int iecho; int blockctr; int pc_offset; int soffset; int tablen, itablen; int skiplen = 0; int skipilen; int skipitlen; int magoffset; int roffset; int iro; int ipc; int ibr; int ntlen=0; int phase_correct; int nt; int nshifts; int within_nt=1; int dsize=1; int nsize=0; int views=1; int nro=1; int nro2=1; int ro_size=1; int pe_size=1; int pe2_size=1; int ro2; int slices=1; int etl=1; int nblocks=1; int ntraces=1; int slice_reps=1; int slab_reps=1; int slicesperblock=1; int viewsperblock=1; int sviewsperblock=1; int slabsperblock=1; int uslicesperblock=1; int error, error1; int ipt; int npts=1; int npts3d=1; int im_slice=0; int pc_slice; int itab; int ichan; int view, slice, echo; int oview; int coilfactor; int nchannels=1; int slabs=1; int within_slabs=1; int within_sviews=1; int within_views=1; int within_slices=1; int rep=0; int urep; int i, min_view, min_view2, iview; int pcslice; int min_sview=0; int j; int narg; int zeropad=0; int zeropad2=0; int n_ft; int irep; int ctcount; int pwr, level; int fnt; int nshots=1; int nsize_ref=0; int nnav=0; int nav_pts=0; int nav; int fn, fn1, fn2; int wtflag; int itemp; int ch0=0; int in1, in2; int temp1, temp2, temp3, temp4; int d2array, d3array; int *skiptab; int inum; unsigned *skipint; unsigned skipd, iskip, ione; short s1; int l1; /* useconds_t snoozetime; */ struct wtparams wtp; /* flags */ int threeD=FALSE; int sview_zf=FALSE; int options=FALSE; int pc_option=OFF; int epi_dualref=FALSE; int nav_option=OFF; int recon_window=NOFILTER; int done=FALSE; int imflag=TRUE; int imflag_neg=FALSE; int pcflag_neg=FALSE; int pcflag=FALSE; int multi_shot=FALSE; int transposed=FALSE; int epi_seq=FALSE; int multi_slice=FALSE; int epi_rev=TRUE; int reverse=TRUE; int acq_done=FALSE; int sliceenc_compressed=TRUE; int slice_compressed=TRUE; int slab_compressed=TRUE; int phase_compressed=TRUE; /* a good assumption */ int flash_converted=FALSE; int tab_converted=FALSE; int epi_me=FALSE; int phase_reverse=FALSE; int navflag=FALSE; int rawflag=FALSE; int sense=FALSE; int smash=FALSE; int phsflag=FALSE; int halfF_ro=FALSE; int display=TRUE; int image_jnt=FALSE; int lastchan=FALSE; int reallybig=FALSE; int variableNT=FALSE; int look_locker=FALSE; symbol **root; /*********************/ /* executable code */ /*********************/ /* default : do complete setup and mallocs */ rInfo.do_setup=TRUE; rInfo.narray=0; // init this /* look for command line arguments */ narg=1; if (argc>narg) /* first argument is acq or a dummy string*/ { if (strcmp(argv[narg], "acq")==0) /* not first time through!!! */ { rInfo.do_setup=FALSE; } narg++; } if (rInfo.do_setup) { if (reconInfoSet) { (void)releaseAllWithId("recon_all"); if(rInfo.fidMd) { mClose(rInfo.fidMd); } } reconInfoSet = 1; rInfo.fidMd=NULL; sview_order=NULL; view_order=NULL; skview_order=NULL; sskview_order=NULL; recon_aborted=FALSE; } if (interuption || recon_aborted) { error=P_setstring(CURRENT, "wnt", "", 0); error=P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: ABORTING "); (void)recon_abort(); ABORT; } /* what sequence is this ? */ error=P_getstring(PROCESSED, "seqfil", sequence, 1, MAXSTR); if (error) { Werrprintf("recon_all: Error getting seqfil"); (void)recon_abort(); ABORT; } /* get studyid */ error=P_getstring(PROCESSED, "studyid_", studyid, 1, MAXSTR); if (error) (void)strcpy(studyid, "unknown"); /* get patient positions */ error=P_getstring(PROCESSED, "position1", pos1, 1, MAXSTR); if (error) (void)strcpy(pos1, ""); error=P_getstring(PROCESSED, "position2", pos2, 1, MAXSTR); if (error) (void)strcpy(pos2, ""); /* get transmit and decouple nucleii */ error=P_getstring(PROCESSED, "tn", tnstring, 1, MAXSTR); if (error) (void)strcpy(tnstring, "H1"); error=P_getstring(PROCESSED, "dn", dnstring, 1, MAXSTR); if (error) (void)strcpy(dnstring, "H1"); /* get apptype */ error=P_getstring(PROCESSED, "apptype", apptype, 1, MAXSTR); /* if(error) { Werrprintf("recon_all: Error getting apptype"); (void)recon_abort(); ABORT; } if(!strlen(apptype)) { Winfoprintf("recon_all: WARNING:apptype unknown!"); Winfoprintf("recon_all: Set apptype in processed tree"); } */ if (!error) { if (strstr(apptype, "imEPI")) epi_seq=TRUE; } error=P_getstring(CURRENT,"epi_pc", epi_pc, 1, MAXSTR); if (!error) { epi_seq=TRUE; epi_rev=TRUE; pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in epi_pc"); (void)recon_abort(); ABORT; } } if (epi_seq) pc_option=POINTWISE; /* further arguments for phase correction & image directory */ if (argc>narg) { options=TRUE; pc_option=pc_pick(argv[narg]); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { (void)strcpy(rInfo.picInfo.imdir, argv[narg++]); rInfo.picInfo.fullpath=TRUE; if (argc>narg) { if (epi_seq) { (void)strcpy(epi_pc, argv[narg]); pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in command line"); (void)recon_abort(); ABORT; } } } } else { if (epi_seq) { (void)strcpy(epi_pc, argv[narg]); pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in command line"); (void)recon_abort(); ABORT; } } } } if (!options) /* try vnmr parameters */ { error=P_getstring(CURRENT,"epi_pc", epi_pc, 1, MAXSTR); if (!error && epi_seq) { options=TRUE; pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in epi_pc"); (void)recon_abort(); ABORT; } error=P_getreal(CURRENT,"epi_rev", &repi_rev, 1); if (!error) { if (repi_rev>0.0) epi_rev=TRUE; else epi_rev=FALSE; } } } if (!options) /* try the resource file to get recon particulars */ { (void)strcpy(rscfilename, curexpdir); (void)strcat(rscfilename, "/recon_all.rsc"); f1=fopen(rscfilename, "r"); if (f1) { options=TRUE; serr=fgets(str, MAXSTR, f1); if (strstr(str, "image directory")) { (void)sscanf(str, "image directory=%s", rInfo.picInfo.imdir); rInfo.picInfo.fullpath=FALSE; if (epi_seq) { serr=fgets(epi_pc, MAXSTR, f1); pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in recon_all.rsc file"); (void)recon_abort(); ABORT; } serr=fgets(str, MAXSTR, f1); (void)sscanf(str, "reverse=%d", &epi_rev); } } else /* no image directory specifed */ { if (epi_seq) { (void)strcpy(epi_pc, str); pc_option=pc_pick(epi_pc); if ((pc_option>MAX_OPTION)||(pc_option<OFF)) { Werrprintf("recon_all: Invalid phase correction option in recon_all.rsc file"); (void)recon_abort(); ABORT; } serr=fgets(str, MAXSTR, f1); (void)sscanf(str, "reverse=%d", &epi_rev); } } (void)fclose(f1); } } if (epi_seq) { if ((pc_option>MAX_OPTION)||(pc_option<OFF)) pc_option=POINTWISE; } /* always write to recon */ (void)strcpy(rInfo.picInfo.imdir, "recon"); rInfo.picInfo.fullpath=FALSE; /******************************/ /* setup */ /******************************/ if (rInfo.do_setup) { #ifdef VNMRJ if (!aipOwnsScreen()) { setdisplay(); Wturnoff_buttons(); sunGraphClear(); aipDeleteFrames(); } else aipSetReconDisplay(-1); #else setdisplay(); Wturnoff_buttons(); sunGraphClear(); #endif (void)init2d_getfidparms(FALSE); if (!epi_seq) { epi_rev=FALSE; pc_option=OFF; } // get rid of 3D cursors if they are there (void)execString("aipShow3Planes(0)\n"); /* get choice of filter, if any */ error=P_getstring(PROCESSED,"recon_window", recon_windowstr, 1, MAXSTR); if (error) (void)strcpy(recon_windowstr, "NOFILTER"); if (strstr(recon_windowstr, "OFF")||strstr(recon_windowstr, "off")) recon_window=NOFILTER; else if (strstr(recon_windowstr, "NOFILTER")||strstr(recon_windowstr, "nofilter")) recon_window=NOFILTER; else if (strstr(recon_windowstr, "BLACKMANN")||strstr(recon_windowstr, "blackmann")) recon_window=BLACKMANN; else if (strstr(recon_windowstr, "HANN")||strstr(recon_windowstr, "hann")) recon_window=HANN; else if (strstr(recon_windowstr, "HAMMING")||strstr(recon_windowstr, "hamming")) recon_window=HAMMING; else if (strstr(recon_windowstr, "GAUSSIAN")||strstr(recon_windowstr, "gaussian")) recon_window=GAUSSIAN; /* open the fid file */ (void)strcpy (filepath, curexpdir ); (void)strcat (filepath, "/acqfil/fid"); (void)strcpy(rInfo.picInfo.fidname, filepath); rInfo.fidMd=mOpen(filepath, 0, O_RDONLY); if ( ! rInfo.fidMd ) { Werrprintf("recon_all: Failed to access data at %s",filepath); (void)recon_abort(); ABORT; } (void)mAdvise(rInfo.fidMd, MF_SEQUENTIAL); /* start out fresh */ /* D_close(D_USERFILE); fid_file_head=&tmpFileHead; error = D_gethead(D_USERFILE, fid_file_head); if (error) { error = D_open(D_USERFILE, filepath, fid_file_head); if (error) { Werrprintf("recon_all: Error opening FID file"); (void)recon_abort(); ABORT; } } */ /* how many receivers? */ error=P_getstring(PROCESSED, "rcvrs", rcvrs_str, 1, MAXSTR); if (!error) { nchannels=strlen(rcvrs_str); for (i=0; i<strlen(rcvrs_str); i++) if (*(rcvrs_str+i)!='y') nchannels--; } rInfo.nchannels=nchannels; /* figure out if compressed in slice dimension */ error=P_getstring(PROCESSED, "seqcon", str, 1, MAXSTR); if (error) { Werrprintf("recon_all: Error getting seqcon"); (void)recon_abort(); ABORT; } if (str[3] != 'n') threeD=TRUE; if (str[1] != 'c') slice_compressed=FALSE; if (str[2] != 'c') phase_compressed=FALSE; if (threeD) if (str[3] != 'c') sliceenc_compressed=FALSE; /* display images or not? */ rInfo.dispint=1; if (threeD) rInfo.dispint=0; error=P_getreal(CURRENT,"recondisplay",&dtemp,1); if (!error) rInfo.dispint=(int)dtemp; error=P_getreal(PROCESSED,"ns",&rslices,1); if (error) { Werrprintf("recon_all: Error getting ns"); (void)recon_abort(); ABORT; } slices=(int)rslices; error=P_getreal(PROCESSED,"nf",&rnf,1); if (error) { Werrprintf("recon_all: Error getting nf"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"nv",&rnv,1); if (error) { Werrprintf("recon_all: Error getting nv"); (void)recon_abort(); ABORT; } nv=(int)rnv; views=nv; if (nv<MINPE) { Werrprintf("recon_all: nv too small"); (void)recon_abort(); ABORT; } #ifdef LINUX memcpy( &tmpFileHead, (dfilehead *)(rInfo.fidMd->offsetAddr), sizeof(dfilehead)); fid_file_head = &tmpFileHead; #else fid_file_head = (dfilehead *)(rInfo.fidMd->offsetAddr); #endif /* byte swap if necessary */ DATAFILEHEADER_CONVERT_NTOH(fid_file_head); ntraces=fid_file_head->ntraces; nblocks=fid_file_head->nblocks; nro=fid_file_head->np/2; rInfo.fidMd->offsetAddr+= sizeof(dfilehead); rInfo.tbytes=fid_file_head->tbytes; rInfo.ebytes=fid_file_head->ebytes; rInfo.bbytes=fid_file_head->bbytes; if (nro<MINRO) { Werrprintf("recon_all: np too small"); (void)recon_abort(); ABORT; } /* check for power of 2 in readout */ zeropad=0; fn=0; error=P_getVarInfo(CURRENT,"fn",&info); if (info.active) { error=P_getreal(CURRENT,"fn",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting fn"); (void)recon_abort(); ABORT; } fn=(int)(dtemp/2); ro_size=fn; } else { n_ft=1; while (n_ft<nro) n_ft*=2; ro_size=n_ft; } error=P_getreal(PROCESSED, "fract_kx", &dtemp, 1); if (!error) { ro_size=2*(nro-(int)dtemp); zeropad=ro_size-nro; n_ft=1; while (n_ft<ro_size) n_ft*=2; ro_size=n_ft; if (n_ft<fn) ro_size=fn; if ((zeropad > HALFF*nro)&&(pc_option<=MAX_OPTION)&&(pc_option>OFF)) { Werrprintf("recon_all: phase correction and fract_kx are incompatible"); (void)recon_abort(); ABORT; } } if (nro<ro_size) { itemp=ro_size-nro; nro=ro_size; ro_size-=itemp; } else ro_size=nro; /* are there mousies? */ nmice=0; error=P_getreal(PROCESSED,"nmice",&dtemp,1); if (!error) nmice=(int)dtemp; /* get pro and ppe for image shifting */ ro_frq=0.0; ro_ph=0.0; /* (void)ls_ph_fid("lsfid", &itemp, "phfid", &ro_ph, "lsfrq", &ro_frq); */ error=P_getreal(CURRENT,"pro",&ro_frq,1); if (!error) { error=P_getreal(PROCESSED,"lro",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lro"); (void)recon_abort(); ABORT; } ro_frq *= (180/dtemp); } ro_frq=0.0; /* disable this -recon has no business doing readout shifts! */ pe_frq=0.0; pe_ph=0.0; /* (void)ls_ph_fid("lsfid1", &itemp, "phfid1", &pe_ph, "lsfrq1", &pe_frq); */ error=P_getreal(CURRENT,"ppe",&pe_frq,1); if (!error) { error=P_getreal(PROCESSED,"lpe",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lpe"); (void)recon_abort(); ABORT; } pe_frq *= (-180/dtemp); } ro_frqP=NULL; pe_frqP=NULL; /* for multi-mouse 2D */ if (nmice) { error=P_getVarInfo(CURRENT,"lsfrq1",&info); if (!error && info.active) { nshifts=info.size; if (((nshifts > 1) &&nshifts != nmice)) { Werrprintf("recon_all: length of lsfrq does not equal nmice "); (void)recon_abort(); ABORT; } pe_frqP=(double *)recon_allocate(nmice*sizeof(double), "recon_all"); error=P_getreal(PROCESSED,"sw1",&dt2,1); if (error) { Werrprintf("recon_all: Error getting sw1 "); (void)recon_abort(); ABORT; } if (nshifts==1) { error=P_getreal(CURRENT,"lsfrq1",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lsfrq1 "); (void)recon_abort(); ABORT; } for (i=0; i<nmice; i++) pe_frqP[i]=180.0*dtemp/dt2; } else { for (i=0; i<nmice; i++) { error=P_getreal(CURRENT,"lsfrq1",&dtemp,(i+1)); if (error) { Werrprintf("recon_all: Error getting lsfrq1 element"); (void)recon_abort(); ABORT; } pe_frqP[i]=180.0*dtemp/dt2; } } } error=P_getVarInfo(CURRENT,"lsfrq",&info); if (!error && info.active) { nshifts=info.size; if (((nshifts > 1) &&nshifts != nmice)) { Werrprintf("recon_all: length of lsfrq does not equal nmice "); (void)recon_abort(); ABORT; } ro_frqP=(double *)recon_allocate(nmice*sizeof(double), "recon_all"); error=P_getreal(PROCESSED,"sw",&dt2,1); if (error) { Werrprintf("recon_all: Error getting sw "); (void)recon_abort(); ABORT; } if (nshifts==1) { error=P_getreal(CURRENT,"lsfrq",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lsfrq "); (void)recon_abort(); ABORT; } for (i=0; i<nmice; i++) ro_frqP[i]=180.0*dtemp/dt2; } else { for (i=0; i<nmice; i++) { error=P_getreal(CURRENT,"lsfrq",&dtemp,(i+1)); if (error) { Werrprintf("recon_all: Error getting lsfrq element"); (void)recon_abort(); ABORT; } ro_frqP[i]=180.0*dtemp/dt2; } } } } error=P_getreal(PROCESSED,"nseg",&rnseg,1); if (error) rnseg=1.0; error=P_getreal(PROCESSED,"ne",&rechoes,1); if (error) rechoes=1.0; echoes=(int)rechoes; if (echoes>1&&epi_seq) epi_me=echoes; look_locker=0; error=P_getstring(PROCESSED, "recontype", str, 1, MAXSTR); if(!error && (strstr(str,"ook"))) { error=P_getreal(PROCESSED,"nti",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting nti for Look-Locker"); (void)recon_abort(); ABORT; } else{ look_locker=1; if(strstr(str,"2")) look_locker=2; echoes = (int)dtemp; } } error=P_getreal(PROCESSED,"etl",&retl,1); if (error) retl=1.0; /* get some epi related parameters */ error1=P_getreal(PROCESSED,"flash_converted",&rfc,1); if (!error1) flash_converted=TRUE; /* sanity checks */ if (flash_converted) { if (ntraces==nv*slices) { phase_compressed=TRUE; slice_compressed=TRUE; } else if (ntraces==nv) { phase_compressed=TRUE; slice_compressed=FALSE; } else if (ntraces==slices) { phase_compressed=FALSE; slice_compressed=TRUE; } else if (ntraces==1) { phase_compressed=FALSE; slice_compressed=FALSE; } } if (slice_compressed&&!epi_seq&&!threeD) multi_slice=TRUE; else if(threeD && slab_compressed) multi_slice=TRUE; error=P_getstring(PROCESSED, "ms_intlv", msintlv, 1, MAXSTR); if (!error) { if (msintlv[0]=='y') multi_slice=TRUE; } imglen=1; error=P_getVarInfo(PROCESSED,"image",&info); if (!error) imglen=info.size; error=P_getstring(PROCESSED,"array", arraystr, 1, MAXSTR); if (error) { Werrprintf("recon_all: Error getting array"); (void)recon_abort(); ABORT; } /* locate image within array to see if reference scan was acquired */ imzero=0; imneg1=0; imneg2=0; imptr=strstr(arraystr, "image"); if (!imptr) imglen=1; /* image was not arrayed */ else if (imglen>1) { /* how many when image=1? */ /* also check for image = -2 or -1 */ for (i=0; i<imglen; i++) { error=P_getreal(PROCESSED,"image",&rimflag,(i+1)); if (error) { Werrprintf("recon_all: Error getting image element"); (void)recon_abort(); ABORT; } if (rimflag==0.0) imzero++; else if (rimflag==-1) imneg1++; else if (rimflag==-2) imneg2++; } if ((imneg1>0) && (imneg2>0)) epi_dualref=TRUE; } if ((!imzero)&&(!epi_dualref)) pc_option=OFF; /* get nt array */ error=P_getVarInfo(PROCESSED,"nt",&info); if (error) { Werrprintf("recon_all: Error getting nt info"); (void)recon_abort(); ABORT; } ntlen=info.size; /* read nt values*/ nts=(int *)recon_allocate(ntlen*sizeof(int), "recon_all"); for (i=0; i<ntlen; i++) { error=P_getreal(PROCESSED,"nt",&dtemp,(i+1)); if (error) { Werrprintf("recon_all: Error getting nt element"); (void)recon_abort(); ABORT; } nts[i]=(int)dtemp; } /* dc correct or not? */ rInfo.dc_flag=FALSE; error=P_getstring(CURRENT, "dcrmv", dcrmv, 1, SHORTSTR); if (!error) { if ((dcrmv[0] == 'y') &&(nts[0]==1)) rInfo.dc_flag = TRUE; } views=nv; etl=1; nshots=views; multi_shot=FALSE; if (epi_seq) { /* default for EPI is single shot */ etl=views; nshots=1; if (rnseg>1.0) { nshots=(int)rnseg; multi_shot=TRUE; if (rnseg) etl=(int)views/nshots; else { Werrprintf("recon_all: nseg equal to zero"); (void)recon_abort(); ABORT; } } } else { if (retl > 1.0) { multi_shot=TRUE; etl=(int)retl; nshots=views/etl; } } if (slice_compressed) { slices=(int)rslices; slicesperblock=slices; } else { P_getVarInfo(PROCESSED, "pss", &info); slices = info.size; slicesperblock=1; if (slices>nblocks) { Werrprintf("recon_all: slices greater than fids for standard mode"); (void)recon_abort(); ABORT; } if (slices>1) { viewsperblock=1; if(etl < views) viewsperblock=etl; if (phase_compressed) viewsperblock=views; within_slices=(nblocks/nchannels); /* get array info */ rInfo.narray=0; if (strlen(arraystr)) { (void)arrayparse(arraystr, &(rInfo.narray), &(rInfo.arrayelsP), (views/viewsperblock),slices); /* find pss and determine number of blocks within each slice */ ip=0; while ((!strstr((char *) rInfo.arrayelsP[ip].names, "pss")) &&(ip<rInfo.narray)) ip++; within_slices=rInfo.arrayelsP[ip].denom; } within_slices *= nchannels; } else within_slices=(nblocks/nchannels); if (!slices) { Werrprintf("recon_all: slices equal to zero"); (void)recon_abort(); ABORT; } } if (phase_compressed) { if (slices) slice_reps=nblocks*slicesperblock/slices; else { Werrprintf("recon_all: slices equal to zero"); (void)recon_abort(); ABORT; } slice_reps -= (imzero+imneg1+imneg2); if (slicesperblock) views=ntraces/slicesperblock; else { Werrprintf("recon_all: slicesperblock equal to zero"); (void)recon_abort(); ABORT; } views=nv; viewsperblock=views; } else { // standard in phase dimension views=nv; d2array=FALSE; if (rInfo.narray == 0) // evaluation array string if not done yet { if (strlen(arraystr)) { (void) arrayparse(arraystr, &(rInfo.narray), &(rInfo.arrayelsP), (views / viewsperblock), slices); } } /* look for d2 and determine number of blocks within each view */ ip = 0; if (strlen(arraystr)) { while ((!strstr((char *) rInfo.arrayelsP[ip].names, "d2")) && (ip < rInfo.narray)) ip++; if (ip < rInfo.narray) { within_views = rInfo.arrayelsP[ip].denom; within_views *= nchannels; d2array = TRUE; } } if (slices) slice_reps=nblocks*slicesperblock/slices; else { Werrprintf("recon_all: slices equal to zero"); (void)recon_abort(); ABORT; } if (nshots) slice_reps/=nshots; else { Werrprintf("recon_all: nshots equal to zero"); (void)recon_abort(); ABORT; } slice_reps -= (imzero+imneg1+imneg2); viewsperblock=1; if (nshots) { if(!d2array) within_views=(nblocks)/nshots; /* views are outermost */ // if (!slice_compressed&&!flash_converted) // within_slices/=nshots; } else { Werrprintf("recon_all: nshots equal to zero"); (void)recon_abort(); ABORT; } } if (threeD) { d2array=d3array=FALSE; // phase encoding explicitly arrayed error = P_getreal(PROCESSED, "nv2", &rnv2, 1); if (error) { Werrprintf("recon3D: Error getting nv2"); (void) recon_abort(); ABORT; } slices = (int) rnv2; if (phase_compressed) { slab_reps=nblocks*slabsperblock/slabs; slab_reps -= (imzero+imneg1+imneg2); viewsperblock=views; } else { slab_reps=nblocks*slabsperblock/slabs; slab_reps/=views; slab_reps -= (imzero+imneg1+imneg2); viewsperblock=1; /* look for d2 and determine number of blocks within each view */ // evaluation array string with correct value of slices ip=0; if (strlen(arraystr)) { (void) arrayparse(arraystr, &(rInfo.narray), &(rInfo.arrayelsP), (views / viewsperblock), slices); while ((!strstr((char *) rInfo.arrayelsP[ip].names, "d2")) && (ip < rInfo.narray)) ip++; } if((strlen(arraystr)) && (ip < rInfo.narray)){ within_views=rInfo.arrayelsP[ip].denom; within_views *= nchannels; d2array=TRUE; } else{ within_views=nblocks/views; /* views are outermost */ if(!sliceenc_compressed) within_views /= slices; } if (!slab_compressed&&!flash_converted) within_slabs/=views; } if (sliceenc_compressed) { sviewsperblock=slices; } else { slab_reps/=slices; sviewsperblock = 1; within_sviews = nblocks / slices; // implicit arrays if(strlen(arraystr)) { /* look for d3 and determine number of blocks within each sview */ if (rInfo.narray == 0) // evaluation array string if not done yet { (void) arrayparse(arraystr, &(rInfo.narray), &(rInfo.arrayelsP), (views / viewsperblock), slices); } ip = 0; while ((!strstr((char *) rInfo.arrayelsP[ip].names, "d3")) && (ip < rInfo.narray)) ip++; if (ip < rInfo.narray) { within_sviews = rInfo.arrayelsP[ip].denom; within_sviews *= nchannels; d3array = TRUE; if (!phase_compressed && !d2array) within_views *= slices; } } } /* check profile flag and fake a 2D if need be */ error=P_getstring(PROCESSED, "profile", profstr, 1, SHORTSTR); if (!error) { if ((profstr[0] == 'y') && (profstr[1] == 'n')) { threeD=FALSE; slices=1; slice_reps=nchannels; slicesperblock=1; within_slices=1; views=(int)rnv2; rInfo.dispint=1; /* phase encode inherits properties of slice encode */ phase_compressed=sliceenc_compressed; viewsperblock=sviewsperblock; within_views=within_sviews; } else if ((profstr[0] == 'n') && (profstr[1] == 'y')) { threeD=FALSE; rInfo.dispint=1; slices=1; views=(int)rnv; } } /* slice encode direction zero fill or not? */ fn2=0; error=P_getVarInfo(CURRENT,"fn2",&info); if (info.active) { error=P_getreal(CURRENT,"fn2",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting fn2"); (void)recon_abort(); ABORT; } fn2=(int)(dtemp/2); pe2_size=fn2; } else { n_ft=1; while (n_ft<slices) n_ft*=2; pe2_size=n_ft; } } /* end if 3D */ /* get array info */ if (strlen(arraystr)) { (void) arrayparse(arraystr, &(rInfo.narray), &(rInfo.arrayelsP), (views / viewsperblock), slices); } /* figure out if nt and d2 are jointly arrayed */ variableNT=FALSE; i=0; while(i<rInfo.narray){ if(rInfo.arrayelsP[i].nparams > 1) { for(in1=0;in1<rInfo.arrayelsP[i].nparams;in1++) if(!strcmp(rInfo.arrayelsP[i].names[in1],"d2")) { for(in2=++in1;in2<rInfo.arrayelsP[i].nparams;in2++) if(!strcmp(rInfo.arrayelsP[i].names[in2],"nt")) variableNT=TRUE; } else if(!strcmp(rInfo.arrayelsP[i].names[in1],"nt")) { for(in2=++in1;in2<rInfo.arrayelsP[i].nparams;in2++) if(!strcmp(rInfo.arrayelsP[i].names[in2],"d2")) variableNT=TRUE; } } i++; } zeropad2=0; fn1=0; error=P_getVarInfo(CURRENT,"fn1",&info); if (info.active) { error=P_getreal(CURRENT,"fn1",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting fn1"); (void)recon_abort(); ABORT; } fn1=(int)(dtemp/2); pe_size=fn1; } else { n_ft=1; while (n_ft<views) n_ft*=2; pe_size=n_ft; } error=P_getreal(PROCESSED, "fract_ky", &dtemp, 1); if (!error) { pe_size=views; views=views/2+ (int)dtemp; zeropad2=pe_size-views; n_ft=1; while (n_ft<pe_size) n_ft*=2; pe_size=n_ft; if (n_ft<fn1) pe_size=fn1; /* adjust etl OR nshots, depending on VJ parameter */ if (epi_seq) { if (nshots) etl=(int)views/nshots; } else { if (etl) nshots=views/etl; } if (phase_compressed) viewsperblock=views; if ((zeropad > HALFF*nro)&&(zeropad2 > HALFF*views)) { Werrprintf("recon_all: fract_kx and fract_ky are incompatible"); (void)recon_abort(); ABORT; } } /* initialize phase & read reversal flags */ rInfo.phsrev_flag=FALSE; rInfo.alt_phaserev_flag=FALSE; rInfo.alt_readrev_flag=FALSE; if (echoes>1) { error=P_getstring(CURRENT,"altecho_reverse", tmp_str, 1, SHORTSTR); if (!error) { if (tmp_str[0]=='y') rInfo.alt_readrev_flag=TRUE; if (strlen(tmp_str)>1) if (tmp_str[1]=='y') rInfo.alt_phaserev_flag=TRUE; } } /* navigator stuff */ nnav=0; error=P_getstring(PROCESSED, "navigator", nav_str, 1, SHORTSTR); if (!error) { if (nav_str[0]=='y') { error=P_getVarInfo(PROCESSED,"nav_echo",&info); if (!error) { nnav=info.size; nav_list = (int *)recon_allocate(nnav*sizeof(int), "recon_all"); for (i=0; i<nnav; i++) { error=P_getreal(PROCESSED,"nav_echo",&dtemp,i+1); nav_list[i]=(int)dtemp - 1; if ((nav_list[i]<0)||(nav_list[i]>=(etl+nnav))) { Werrprintf("recon_all: navigator value out of range"); (void)recon_abort(); ABORT; } } } if (!nnav) { /* figure out navigators per echo train */ nnav=((ntraces/slicesperblock)-views)/nshots; if (nnav>0) { nav_list = (int *)recon_allocate(nnav*sizeof(int), "recon_all"); for (i=0; i<nnav; i++) nav_list[i]=i; nav_pts=ro_size; } else nnav=0; } error=P_getreal(PROCESSED,"navnp",&dtemp,1); if (!error) { nav_pts=(int)dtemp; nav_pts/=2; } else nav_pts=ro_size; } } nav_option=OFF; if (nnav) { nav_option=POINTWISE; if (nnav>1) nav_option=PAIRWISE; error=P_getstring(CURRENT,"nav_type", nav_type, 1, MAXSTR); if (!error) { if (strstr(nav_type, "OFF")||strstr(nav_type, "off")) nav_option=OFF; else if (strstr(nav_type, "POINTWISE")||strstr(nav_type, "pointwise")) nav_option=POINTWISE; else if (strstr(nav_type, "LINEAR")||strstr(nav_type, "linear")) nav_option=LINEAR; else if (strstr(nav_type, "PAIRWISE")||strstr(nav_type, "pairwise")) nav_option=PAIRWISE; else { Werrprintf("recon_all: Invalid navigator option in nav_type parameter!"); (void)recon_abort(); ABORT; } } if ((nav_option==PAIRWISE)&&(nnav<2)) { Werrprintf("recon_all: 2 navigators required for PAIRWISE nav_type"); (void)recon_abort(); ABORT; } /* adjust etl and views if necessary */ if (views == (ntraces/slicesperblock)) { views-=nshots*nnav; etl=views/nshots; if (phase_compressed) viewsperblock=views; } } /* end of navigator setup */ if (threeD) slice_reps=slab_reps; if (slice_reps<1) { Werrprintf("recon_all: slice reps less than 1"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"tab_converted",&rfc,1); if (!error) tab_converted=TRUE; tablen=views; if (threeD) tablen*=slices; multi_shot=FALSE; min_view=min_view2=0; skipint = NULL; skiptab = NULL; error =P_getstring(PROCESSED, "skiptab", str, 1, MAXSTR); if (strstr(str, "y")) { // read skipint error = P_getVarInfo(CURRENT, "skipint", &info); if (!error && (info.size > 1)) { skipilen = info.size; skipint = (unsigned *) recon_allocate(skipilen * sizeof(unsigned), "recon_all"); for (itab = 0; itab < skipilen; itab++) { error = P_getreal(CURRENT, "skipint", &dtemp, itab + 1); if (error) { Werrprintf("recon_all: Error getting skipint element"); (void) recon_abort(); ABORT; } skipint[itab] = (unsigned)dtemp; } } // read skiptabvals skiplen = 0; error = P_getVarInfo(CURRENT, "skiptabvals", &info); if (!error && (info.size > 1)) { itablen = info.size; if ((itablen = tablen) && (itablen != views) && (itablen != slices * views)) { Werrprintf("recon_all: skiptabvals is wrong size"); (void) recon_abort(); ABORT; } tablen = itablen; skiptab = (int *) recon_allocate(itablen * sizeof(int), "recon_all"); for (itab = 0; itab < itablen; itab++) { error = P_getreal(CURRENT, "skiptabvals", &dtemp, itab + 1); if (error) { Werrprintf( "recon_all: Error getting skiptabvals element"); (void) recon_abort(); ABORT; } if (dtemp > 0.0) { skiplen++; } skiptab[itab] = dtemp; } } } error=P_getVarInfo(CURRENT,"pelist",&info); if (!error && (info.size>1)) { itablen=info.size; if ((itablen != tablen)&&(itablen != views)) { Werrprintf("recon_all: pelist is wrong size"); (void)recon_abort(); ABORT; } tablen=itablen; view_order = (int *)recon_allocate(itablen*sizeof(int), "recon_all"); for (itab=0; itab<itablen; itab++) { error=P_getreal(CURRENT,"pelist",&dtemp,itab+1); if (error) { Werrprintf("recon_all: Error getting pelist element"); (void)recon_abort(); ABORT; } view_order[itab]=dtemp; if (dtemp<min_view) min_view=dtemp; if (-1*dtemp<min_view2) min_view2=-1*dtemp; } multi_shot=TRUE; } else { error=P_getstring(PROCESSED, "petable", petable, 1, MAXSTR); /* open table for sorting */ if ((!error)&&strlen(petable)&&strcmp(petable, "n")&&strcmp( petable, "N")&&(!tab_converted)) { multi_shot=TRUE; /* try user's directory*/ error=P_getstring(PROCESSED, "petable", petable, 1, MAXSTR); if (error) { Werrprintf("recon_all: Error getting petable"); (void)recon_abort(); ABORT; } table_ptr = NULL; if (appdirFind(petable, "tablib", tablefile, NULL, R_OK)) table_ptr = fopen(tablefile, "r"); if (!table_ptr) { Werrprintf("recon_all: Error opening petable file %s", petable); (void)recon_abort(); ABORT; } /* first figure out size of sorting table(s) */ while ((tstch=fgetc(table_ptr) != '=') && (tstch != EOF)) ; itablen = 0; done=FALSE; while ((itablen<tablen) && !done) { if (fscanf(table_ptr, "%d", &iview) == 1) itablen++; else done = TRUE; } /* reposition to start of file */ error=fseek(table_ptr, 0, SEEK_SET); if (error) { Werrprintf("recon_all: Error with fseek, petable"); (void)recon_abort(); ABORT; } if ((itablen!=views)&&(itablen!=tablen)) { Werrprintf("recon_all: Error wrong phase sorting table size"); (void)recon_abort(); ABORT; } /* read in table for view sorting */ view_order = (int *)recon_allocate(tablen*sizeof(int), "recon_all"); while ((tstch=fgetc(table_ptr) != '=') && (tstch != EOF)) ; if (tstch == EOF) { Werrprintf("recon_all: EOF while reading petable file"); (void)recon_abort(); ABORT; } itab = 0; min_view=0; min_view2=0; done=FALSE; while ((itab<tablen) && !done) { if (fscanf(table_ptr, "%d", &iview)==1) { view_order[itab]=iview; if (iview<min_view) min_view=iview; if (-1*iview<min_view2) min_view2=-1*iview; itab++; } else done = TRUE; } /* check for t2 table describing slice encode ordering */ tstch=fgetc(table_ptr); while ((tstch != 't') && (tstch != EOF)) tstch=fgetc(table_ptr); sview_order=NULL; if ((tstch != EOF)&&threeD) { sview_order = (int *)recon_allocate(tablen*sizeof(int), "recon_all"); while ((tstch=fgetc(table_ptr) != '=') && (tstch != EOF)) ; if (tstch == EOF) { Werrprintf("recon_all: EOF while reading petable file for t2"); (void)recon_abort(); ABORT; } itab = 0; min_sview=0; done=FALSE; while ((itab<tablen) && !done) { if (fscanf(table_ptr, "%d", &iview) == 1) { sview_order[itab]=iview; if (iview<min_sview) min_sview=iview; itab++; } else done = TRUE; } } (void)fclose(table_ptr); } } if (multi_shot) { /* make it start from zero */ if (FALSE && (min_view<min_view2)) { if (sview_order) { for (i=0; i<tablen; i++) { view_order[i]=-1*view_order[i]-min_view2; sview_order[i]-=min_sview; } } else { for (i=0; i<tablen; i++) view_order[i]=-1*view_order[i]-min_view2; } rInfo.phsrev_flag=TRUE; } else { if (sview_order) { for (i=0; i<tablen; i++) { view_order[i]-=min_view; sview_order[i]-=min_sview; } } else { for (i=0; i<tablen; i++) view_order[i]-=min_view; } } } /* end if multishot*/ if (skipint) { // this is the compressed version of skiptab multi_shot = TRUE; ione=1; if (threeD) { // these may be oversized but that's ok skipitlen=slices*views; sskview_order = (int *) recon_allocate(skipitlen * sizeof(int), "recon_all"); skview_order = (int *) recon_allocate(skipitlen * sizeof(int), "recon_all"); } else { skipitlen=views; skview_order = (int *) recon_allocate(skipitlen * sizeof(int), "recon_all"); } if (view_order) { j = 0; for (i = 0; i < skipitlen; i++) { inum=i/32; // which skipint to read skipd = (int)skipint[inum]; // get the double iskip = ione & (skipd >> (i%32)); if (iskip > 0) skview_order[j++] = view_order[i]; } } if (sview_order) { j = 0; for (i = 0; i < skipitlen; i++) { inum=i/32; // which skipint to read skipd = (int)skipint[inum]; // get the double iskip = ione & (skipd >> (i%32)); if (iskip > 0) sskview_order[j++] = sview_order[i]; } } else // no sort table so assume linear { j = 0; for (i = 0; i < skipitlen; i++) { inum=i/32; // which skipint to read skipd = (int)skipint[inum]; // get the double iskip = ione & (skipd >> (i%32)); if (iskip > 0) { skview_order[j] = i % views; if(threeD) sskview_order[j] = (i / views) % slices; j++; } } } if (j < ntraces) { Werrprintf("recon_all: Error - mismatch between traces and elliptical table values"); (void) recon_abort(); ABORT; } } else if (skiptab) { multi_shot = TRUE; skview_order = (int *) recon_allocate(skiplen * sizeof(int), "recon_all"); if (threeD) sskview_order = (int *) recon_allocate(skiplen * sizeof(int), "recon_all"); if (view_order) { j = 0; for (i = 0; i < tablen; i++) { if (skiptab[i] > 0) skview_order[j++] = view_order[i]; } } if (sview_order) { j = 0; for (i = 0; i < tablen; i++) { if (skiptab[i] > 0) sskview_order[j++] = sview_order[i]; } } else // no sort table so assume linear { j = 0; for (i = 0; i < tablen; i++) { if (skiptab[i] > 0) { skview_order[j] = i % views; j++; } } if (threeD) { j = 0; for (i = 0; i < tablen; i++) { if (skiptab[i] > 0) { sskview_order[j] = (i / views) % slices; j++; } } } } } if (flash_converted) multi_shot=FALSE; blockreps = NULL; blockrepeat = NULL; if (!threeD) { /* get pss array and make slice order array */ pss=(float*)recon_allocate(slices*sizeof(float), "recon_all"); slice_order=(int*)recon_allocate(slices*sizeof(int), "recon_all"); for (i=0; i<slices; i++) { error=P_getreal(PROCESSED,"pss",&dtemp,i+1); if (error) { Werrprintf("recon_all: Error getting slice offset"); (void)recon_abort(); ABORT; } pss[i]=(float)dtemp; slice_order[i]=i+1; } uslicesperblock=slicesperblock; if (slice_compressed) { /* count repetitions of slice positions */ blockreps=(int *)recon_allocate(slicesperblock*sizeof(int), "recon_all"); blockrepeat=(int *)recon_allocate(slicesperblock*sizeof(int), "recon_all"); pss2=(float *)recon_allocate(slicesperblock*sizeof(float), "recon_all"); for (i=0; i<slicesperblock; i++) { blockreps[i]=0; blockrepeat[i]=-1; pss2[i]=pss[i]; } (void)qsort(pss2, slices, sizeof(float), pcompare); pss0=pss2[0]; i=0; j=0; while (i<slicesperblock) { if (pss2[i]!=pss0) { pss0=pss2[i]; j++; } blockreps[j]++; i++; } uslicesperblock=j+1; } /* sort the slice order based on pss */ if (uslicesperblock==slicesperblock) (void)qsort(slice_order, slices, sizeof(int), psscompare); else { upss=(float *)recon_allocate(uslicesperblock*sizeof(float), "recon_all"); j=0; for (i=0; i<uslicesperblock; i++) { upss[i]=pss[j]; j+=blockreps[i]; } (void)qsort(slice_order, uslicesperblock, sizeof(int), upsscompare); /* undo all this and report repeat slices as unique */ uslicesperblock=slicesperblock; } } /***********************************************************************************/ /* get array to see how reference scan data was interleaved with acquisition */ /***********************************************************************************/ dimfirst=1; dimafter=1; if (imptr != NULL) /* don't bother if no image */ { /* interrogate array to find position of 'image' */ imfound=FALSE; ptr=strtok(arraystr, ","); while (ptr != NULL) { if (ptr == imptr) imfound=TRUE; /* is this a jointly arrayed thing? */ if (strstr(ptr, "(")) { while (strstr(ptr, ")")==NULL) /* move to end of jointly arrayed list */ { if (strstr(ptr, "image")) image_jnt=TRUE; ptr=strtok(NULL,","); } *(ptr+strlen(ptr)-1)='\0'; } strcpy(aname, ptr); error=P_getVarInfo(PROCESSED,aname,&info); if (error) { Werrprintf("recon_all: Error getting something"); (void)recon_abort(); ABORT; } if (imfound) { if (ptr != imptr) dimafter *= info.size; /* get dimension of this variable */ } else dimfirst *= info.size; ptr = strtok(NULL, ","); } dimafter *= nchannels; } else { if (nchannels > 0) dimfirst = nblocks / nchannels; else dimfirst = nblocks; } if (flash_converted) dimafter*=slices; // dimafter *= nchannels; /* set up fdf header structure */ error=P_getreal(PROCESSED,"lro",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lro"); (void)recon_abort(); ABORT; } rInfo.picInfo.fovro=dtemp; error=P_getreal(PROCESSED,"lpe",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lpe"); (void)recon_abort(); ABORT; } rInfo.picInfo.fovpe=dtemp; error=P_getreal(PROCESSED,"thk",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting thk"); (void)recon_abort(); ABORT; } rInfo.picInfo.thickness=MM_TO_CM*dtemp; error=P_getreal(PROCESSED,"gap",&dtemp,1); if (error && !threeD) { Werrprintf("recon_all: Error getting gap"); (void)recon_abort(); ABORT; } rInfo.picInfo.gap=dtemp; if (threeD) { error=P_getreal(PROCESSED,"lpe2",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting lpe2"); (void)recon_abort(); ABORT; } rInfo.picInfo.thickness=dtemp; } rInfo.picInfo.slices=slices; rInfo.picInfo.echo=1; rInfo.picInfo.echoes=echoes; error=P_getVarInfo(PROCESSED,"psi",&info); if (error) { Werrprintf("recon_all: Error getting psi info"); (void)recon_abort(); ABORT; } rInfo.picInfo.npsi=info.size; error=P_getVarInfo(PROCESSED,"phi",&info); if (error) { Werrprintf("recon_all: Error getting phi info"); (void)recon_abort(); ABORT; } rInfo.picInfo.nphi=info.size; error=P_getVarInfo(PROCESSED,"theta",&info); if (error) { Werrprintf("recon_all: Error getting theta info"); (void)recon_abort(); ABORT; } rInfo.picInfo.ntheta=info.size; error=P_getreal(PROCESSED,"te",&dtemp,1); if (error) { Werrprintf("recon_all: recon_all: Error getting te"); (void)recon_abort(); ABORT; } rInfo.picInfo.te=(float)SEC_TO_MSEC*dtemp; error=P_getreal(PROCESSED,"tr",&dtemp,1); if (error) { Werrprintf("recon_all: recon_all: Error getting tr"); (void)recon_abort(); ABORT; } rInfo.picInfo.tr=(float)SEC_TO_MSEC*dtemp; (void)strcpy(rInfo.picInfo.seqname, sequence); (void)strcpy(rInfo.picInfo.studyid, studyid); (void)strcpy(rInfo.picInfo.position1, pos1); (void)strcpy(rInfo.picInfo.position2, pos2); (void)strcpy(rInfo.picInfo.tn, tnstring); (void)strcpy(rInfo.picInfo.dn, dnstring); error=P_getreal(PROCESSED,"ti",&dtemp,1); if (error) { Werrprintf("recon_all: recon_all: Error getting ti"); (void)recon_abort(); ABORT; } rInfo.picInfo.ti=(float)SEC_TO_MSEC*dtemp; rInfo.picInfo.image=dimafter*dimfirst; if (image_jnt) rInfo.picInfo.image/=imglen; rInfo.picInfo.image*=(imglen-imzero-imneg1-imneg2); if (!phase_compressed) { if (multi_shot) rInfo.picInfo.image /= nshots; else rInfo.picInfo.image /= views; } if (!slice_compressed) rInfo.picInfo.image/=slices; rInfo.picInfo.array_index=1; error=P_getreal(PROCESSED,"sfrq",&dtemp,1); if (error) { Werrprintf("recon_all: recon_all: Error getting sfrq"); (void)recon_abort(); ABORT; } rInfo.picInfo.sfrq=dtemp; error=P_getreal(PROCESSED,"dfrq",&dtemp,1); if (error) { Werrprintf("recon_all: recon_all: Error getting dfrq"); (void)recon_abort(); ABORT; } rInfo.picInfo.dfrq=dtemp; /* estimate time for block acquisition */ error = P_getreal(PROCESSED,"at",&acqtime,1); if (error) { Werrprintf("recon_all: Error getting at"); (void)recon_abort(); ABORT; } /* snoozetime=(useconds_t)(acqtime*ntraces*nt*SEC_TO_USEC);*/ /* snoozetime=(useconds_t)(0.25*rInfo.picInfo.tr*MSEC_TO_USEC); */ if (views<pe_size) { itemp=pe_size-views; views=pe_size; pe_size-=itemp; } else pe_size=views; if (threeD) { if (slices<pe2_size) { itemp=pe2_size-slices; slices=pe2_size; pe2_size-=itemp; } else pe2_size=slices; rInfo.picInfo.slices=slices; } /* set up filter window if necessary */ read_window=NULL; phase_window=NULL; phase2_window=NULL; nav_window=NULL; recon_window=NOFILTER; /* turn mine off */ if (nnav) /* make a window for navigator echoes */ { nav_window=(float*)recon_allocate(ro_size*sizeof(float), "recon_all"); (void)filter_window(GAUSS_NAV,nav_window, ro_size); } error=P_getreal(CURRENT,"ftproc",&dtemp,1); if (error) { Werrprintf("recon_all: Error getting ftproc"); (void)recon_abort(); ABORT; } wtflag=(int)dtemp; if (wtflag) { recon_window=MAX_FILTER; if (init_wt1(&wtp, S_NP)) { Werrprintf("recon_all: Error from init_wt1"); (void)recon_abort(); ABORT; } wtp.wtflag=TRUE; // fpointmult = getfpmult(S_NP, fid_file_head->status & S_DDR); fpointmult = getfpmult(S_NP, 0); read_window=(float*)recon_allocate(ro_size*sizeof(float), "recon_all"); if (init_wt2(&wtp, read_window, ro_size, FALSE, S_NP, fpointmult, FALSE)) { Werrprintf("recon_all: Error from init_wt2"); (void)recon_abort(); ABORT; } phase_window=(float*)recon_allocate(views*sizeof(float), "recon_all"); if (phase_compressed) { if (init_wt1(&wtp, S_NF)) { Werrprintf("recon_all: Error from init_wt1"); (void)recon_abort(); ABORT; } wtp.wtflag=TRUE; fpointmult = getfpmult(S_NF,0); if (init_wt2(&wtp, phase_window, views, FALSE, S_NF, fpointmult, FALSE)) { Werrprintf("recon_all: Error from init_wt2"); (void)recon_abort(); ABORT; } } else { if (init_wt1(&wtp, S_NI)) { Werrprintf("recon_all: Error from init_wt1"); (void)recon_abort(); ABORT; } wtp.wtflag=TRUE; fpointmult = getfpmult(S_NI,0); if (init_wt2(&wtp, phase_window, views, FALSE, S_NI, fpointmult, FALSE)) { Werrprintf("recon_all: Error from init_wt2"); (void)recon_abort(); ABORT; } } if(threeD) { phase2_window=(float*)recon_allocate(slices*sizeof(float), "recon_all"); if (init_wt1(&wtp, S_NI2)) { Werrprintf("recon_all: Error from init_wt1"); (void)recon_abort(); ABORT; } wtp.wtflag=TRUE; fpointmult = getfpmult(S_NI2,0); if (init_wt2(&wtp, phase2_window, slices, FALSE, S_NI2, fpointmult, FALSE)) { Werrprintf("recon_all: Error from init_wt2"); (void)recon_abort(); ABORT; } } } error=P_getstring(CURRENT, "rcvrout",tmp_str, 1, SHORTSTR); if ((!error)&& (tmp_str[0]=='i')) { smash=TRUE; sense=TRUE; } error=P_getstring(CURRENT, "raw", tmp_str, 1, SHORTSTR); if (!error) { if (tmp_str[0]=='m') rawflag=RAW_MAG; if (tmp_str[0]=='p') rawflag=RAW_PHS; if (tmp_str[0]=='b') rawflag=RAW_MP; } error=P_getstring(CURRENT, "dmg", tmp_str, 1, SHORTSTR); if (!error) { if (strstr(tmp_str, "pa")) phsflag=TRUE; } if (nmice) { sense=TRUE; phsflag=FALSE; rawflag=FALSE; } /* get scaling for images if available */ error=P_getreal(CURRENT,"aipScale",&dtemp,1); if (!error) rInfo.image_scale=dtemp; else rInfo.image_scale=IMAGE_SCALE; if(rInfo.image_scale == 0.0) rInfo.image_scale=1.0; /* turn off recon force */ root = getTreeRoot ("current"); (void)RcreateVar ("recon_force", root, T_REAL); error=P_getreal(CURRENT,"recon_force",&recon_force,1); if (!error) error=P_setreal(CURRENT,"recon_force",0.0,1); realtime_block=0; rInfo.image_order=0; rInfo.phase_order=0; rInfo.rawmag_order=0; rInfo.rawphs_order=0; rInfo.pc_slicecnt=0; rInfo.slicecnt=0; rInfo.dispcnt=0; coilfactor=1; if (smash||sense||threeD) coilfactor=nchannels; npts=views*nro; /* number of pixels per slice */ npts3d=npts*slices; /* number of pixels per slab */ if (threeD) { double chkSize; chkSize = (double) (slabsperblock*slab_reps*echoes*2*coilfactor); chkSize *= (double) npts3d * (double) sizeof(float); if (chkSize > 65536.0*32768.0) { Werrprintf("recon_all: Data too large (> 2 Gbytes)"); (void)recon_abort(); ABORT; } dsize=slabsperblock*slab_reps*echoes*2*npts3d; dsize*=coilfactor; // magnitude=(float *)recon_allocate(dsize/2*sizeof(float), // "recon_all"); // mag2=(float *)recon_allocate(npts3d*sizeof(float), "recon_all"); if (nnav) { nsize=nshots*nnav*echoes*nro*slices*slice_reps; nsize_ref=echoes*nro*slices; navdata=(float *)recon_allocate(nsize*sizeof(float), "recon_all"); nav_refphase=(double *)recon_allocate(nsize_ref*sizeof(double), "recon_all"); } } /* 2D cases below */ else if (phase_compressed) { dsize=slicesperblock*echoes*2*npts; if (threeD) dsize=slabsperblock*echoes*2*npts3d; magnitude=(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); mag2=(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); if (nnav) { nsize=nshots*nnav*echoes*nro*2*slicesperblock; nsize_ref=echoes*nro*slicesperblock; navdata=(float *)recon_allocate(nsize*sizeof(float), "recon_all"); nav_refphase=(double *)recon_allocate(nsize_ref*sizeof(double), "recon_all"); } } else { dsize=slices*slice_reps*echoes*2*npts; dsize*=coilfactor; magnitude=(float *)recon_allocate(npts*sizeof(float), "recon_all"); mag2=(float *)recon_allocate(npts*sizeof(float), "recon_all"); if (nnav) { nsize=nshots*nnav*echoes*2*nro*slices*slice_reps; nsize_ref=echoes*2*nro*slices; navdata=(float *)recon_allocate(nsize*sizeof(float), "recon_all"); nav_refphase=(double *)recon_allocate(nsize_ref*sizeof(double), "recon_all"); } } slicedata=(float *)recon_allocate(dsize*sizeof(float), "recon_all"); if (slicedata == NULL) { (void)recon_abort(); ABORT; } if ((rawflag==RAW_MAG)||(rawflag==RAW_MP)) rawmag =(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); if ((rawflag==RAW_PHS)||(rawflag==RAW_MP)) rawphs =(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); if (sense||phsflag) imgphs =(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); if (phsflag) imgphs2=(float *)recon_allocate((dsize/2)*sizeof(float), "recon_all"); if (pc_option!=OFF) { pc=(float *)recon_allocate(slices*echoes*nchannels*2*npts*sizeof(float), "recon_all"); pc_done=(short *)recon_allocate(slices*nchannels*echoes*sizeof(int), "recon_all"); for (ipc=0; ipc<slices*nchannels*echoes; ipc++) *(pc_done+ipc)=FALSE; if (epi_dualref && (pc_option==TRIPLE_REF)) { pc_neg=(float *)recon_allocate(slices*nchannels*echoes*2*npts *sizeof(float), "recon_all"); slicedata_neg=(float *)recon_allocate(dsize*sizeof(float), "recon_all"); imdata =(float *)recon_allocate(dsize*sizeof(float), "recon_all"); imdata_neg=(float *)recon_allocate(dsize*sizeof(float), "recon_all"); if (nchannels) { imdata2=(float *)recon_allocate(dsize*sizeof(float), "recon_all"); imdata2_neg=(float *)recon_allocate(dsize*sizeof(float), "recon_all"); } } if (epi_dualref) { pcneg_done=(short *)recon_allocate(slices*nchannels*echoes*sizeof(int), "recon_all"); for (ipc=0; ipc<slices*nchannels*echoes; ipc++) *(pcneg_done+ipc)=FALSE; } } if (ntlen) { if (strstr(arraystr,"nt")) { ip = 0; while ((ip < rInfo.narray) && (!strstr((char *) rInfo.arrayelsP[ip].names, "nt"))) ip++; within_nt = rInfo.arrayelsP[ip].denom; within_nt *= nchannels; } else { if (phase_compressed) within_nt = nblocks / ntlen; else if (variableNT) within_nt = etl * nblocks / (nv); else within_nt = etl * nblocks / (nv * ntlen); } } else { Werrprintf("recon_all: ntlen equal to zero"); (void)recon_abort(); ABORT; } /* bundle these for convenience */ rInfo.picInfo.ro_size=ro_size; rInfo.picInfo.pe_size=pe_size; rInfo.picInfo.nro=nro; rInfo.picInfo.npe=views; rInfo.svinfo.ro_size=ro_size; rInfo.svinfo.pe_size=pe_size; rInfo.svinfo.pe2_size=pe2_size; rInfo.svinfo.slice_reps=slice_reps; rInfo.svinfo.nblocks=nblocks; rInfo.svinfo.ntraces=ntraces; rInfo.svinfo.dimafter=dimafter; rInfo.svinfo.dimfirst=dimfirst; rInfo.svinfo.multi_shot=multi_shot; rInfo.svinfo.multi_slice=multi_slice; rInfo.svinfo.etl=etl; rInfo.svinfo.uslicesperblock=uslicesperblock; rInfo.svinfo.slabsperblock=slabsperblock; rInfo.svinfo.slicesperblock=slicesperblock; rInfo.svinfo.viewsperblock=viewsperblock; rInfo.svinfo.within_slices = within_slices; rInfo.svinfo.within_views = within_views; rInfo.svinfo.within_sviews = within_sviews; rInfo.svinfo.slabs=slabs; rInfo.svinfo.within_slabs=within_slabs; rInfo.svinfo.phase_compressed=phase_compressed; rInfo.svinfo.slab_compressed=slab_compressed; rInfo.svinfo.slice_compressed=slice_compressed; rInfo.svinfo.sliceenc_compressed=sliceenc_compressed; rInfo.svinfo.slices=slices; rInfo.svinfo.echoes=echoes; rInfo.svinfo.epi_seq=epi_seq; rInfo.svinfo.threeD=threeD; rInfo.svinfo.flash_converted=flash_converted; rInfo.svinfo.pc_option=pc_option; rInfo.svinfo.epi_dualref=epi_dualref; rInfo.svinfo.nnav=nnav; rInfo.svinfo.nav_option=nav_option; rInfo.svinfo.nav_pts=nav_pts; rInfo.imglen=imglen; rInfo.ntlen=ntlen; rInfo.within_nt=within_nt; rInfo.epi_rev=epi_rev; rInfo.rwindow=read_window; rInfo.pwindow=phase_window; rInfo.swindow=phase2_window; rInfo.nwindow=nav_window; rInfo.zeropad = zeropad; rInfo.zeropad2 = zeropad2; rInfo.ro_frq = ro_frq; rInfo.pe_frq = pe_frq; rInfo.dsize = dsize; rInfo.nsize = nsize; rInfo.rawflag = rawflag; rInfo.sense = sense; rInfo.smash = smash; rInfo.phsflag = phsflag; rInfo.variableNT = variableNT; rInfo.svinfo.look_locker=look_locker; if (recon_space_check()) { Werrprintf("recon_all: space check failed "); (void)recon_abort(); ABORT; } /* zero everything important */ (void)memset(slicedata, 0, dsize * sizeof(*slicedata)); if(pc_option!=OFF) { (void)memset(pc, 0, slices * nchannels * echoes * 2 * npts * sizeof(*pc)); } if(epi_dualref && (pc_option==TRIPLE_REF)) { (void)memset(slicedata_neg, 0, dsize * sizeof(*slicedata_neg)); (void)memset(imdata, 0, dsize * sizeof(*imdata)); (void)memset(imdata_neg, 0, dsize * sizeof(*imdata_neg)); if(nchannels) { (void)memset(imdata2, 0, dsize * sizeof(*imdata2)); (void)memset(imdata2_neg, 0, dsize * sizeof(*imdata2_neg)); } (void)memset(pc_neg, 0, slices * nchannels * echoes * 2 * npts * sizeof(*pc_neg)); } if(nnav) { (void)memset(navdata, 0, nsize * sizeof(*navdata)); (void)memset(nav_refphase, 0, nsize_ref * sizeof(*nav_refphase)); } if((rawflag==RAW_MAG)||(rawflag==RAW_MP)) { (void)memset(rawmag, 0, (dsize/2) * sizeof(*rawmag)); } if((rawflag==RAW_PHS)||(rawflag==RAW_MP)) { (void)memset(rawphs, 0, (dsize/2) * sizeof(*rawphs)); } if(sense||phsflag) { (void)memset(imgphs, 0, (dsize/2) * sizeof(*imgphs)); } if(threeD) { repeat=(int *)recon_allocate(slabsperblock*slices*views*echoes*sizeof(int),"recon_all"); for(i=0;i<slabsperblock*slices*echoes*views;i++) *(repeat+i)=-1; } else { repeat=(int *)recon_allocate(slices*views*echoes*sizeof(int),"recon_all"); for(i=0;i<slices*echoes*views;i++) *(repeat+i)=-1; } /* remove extra directories */ (void)strcpy(tempdir,curexpdir); (void)strcat(tempdir,"/reconphs"); (void)sprintf(str,"rm -rf %s \n",tempdir); ierr=system(str); (void)strcpy(tempdir,curexpdir); (void)strcat(tempdir,"/rawphs"); (void)sprintf(str,"rm -rf %s \n",tempdir); ierr=system(str); (void)strcpy(tempdir,curexpdir); (void)strcat(tempdir,"/rawmag"); (void)sprintf(str,"rm -rf %s \n",tempdir); ierr=system(str); (void)strcpy(tempdir,curexpdir); (void)strcat(tempdir,"/recon"); (void)sprintf(str,"rm -rf %s \n",tempdir); ierr=system(str); } /******************************/ /* end setup */ /******************************/ if(!rInfo.do_setup) { /* unpack the structure for convenience */ nav_option=rInfo.svinfo.nav_option; nnav=rInfo.svinfo.nnav; nav_pts=rInfo.svinfo.nav_pts; pc_option=rInfo.svinfo.pc_option; epi_dualref=rInfo.svinfo.epi_dualref; slice_reps=rInfo.svinfo.slice_reps; nblocks=rInfo.svinfo.nblocks; ntraces=rInfo.svinfo.ntraces; dimafter=rInfo.svinfo.dimafter; dimfirst=rInfo.svinfo.dimfirst; multi_shot=rInfo.svinfo.multi_shot; multi_slice=rInfo.svinfo.multi_slice; etl=rInfo.svinfo.etl; slicesperblock=rInfo.svinfo.slicesperblock; slabs=rInfo.svinfo.slabs; slabsperblock=rInfo.svinfo.slabsperblock; uslicesperblock=rInfo.svinfo.uslicesperblock; viewsperblock=rInfo.svinfo.viewsperblock; within_slices=rInfo.svinfo.within_slices; within_views=rInfo.svinfo.within_views; within_sviews=rInfo.svinfo.within_sviews; within_slabs=rInfo.svinfo.within_slabs; phase_compressed=rInfo.svinfo.phase_compressed; slice_compressed=rInfo.svinfo.slice_compressed; slab_compressed=rInfo.svinfo.slab_compressed; sliceenc_compressed=rInfo.svinfo.sliceenc_compressed; views=rInfo.picInfo.npe; nro=rInfo.picInfo.nro; ro_size=rInfo.svinfo.ro_size; pe_size=rInfo.svinfo.pe_size; pe2_size=rInfo.svinfo.pe2_size; slices=rInfo.svinfo.slices; echoes=rInfo.svinfo.echoes; epi_seq=rInfo.svinfo.epi_seq; threeD=rInfo.svinfo.threeD; flash_converted=rInfo.svinfo.flash_converted; imglen=rInfo.imglen; ntlen=rInfo.ntlen; within_nt=rInfo.within_nt; epi_rev=rInfo.epi_rev; read_window=rInfo.rwindow; phase_window=rInfo.pwindow; phase2_window=rInfo.swindow; nav_window=rInfo.nwindow; zeropad=rInfo.zeropad; zeropad2=rInfo.zeropad2; ro_frq=rInfo.ro_frq; pe_frq=rInfo.pe_frq; dsize=rInfo.dsize; nsize=rInfo.nsize; rawflag=rInfo.rawflag; sense=rInfo.sense; smash=rInfo.smash; phsflag=rInfo.phsflag; variableNT=rInfo.variableNT; look_locker=rInfo.svinfo.look_locker; } reallybig=FALSE; if(threeD) if(slices*ro_size*pe_size >= BIG3D) reallybig=TRUE; if(realtime_block>=nblocks) { (void)recon_abort(); ABORT; } slice=0; view=0; echo=0; nshots=views/etl; nshots=pe_size/etl; if(threeD &&(pe2_size<slices)) sview_zf=TRUE; if(mFidSeek(rInfo.fidMd, (realtime_block+1), sizeof(dfilehead), rInfo.bbytes)) { (void)sprintf(str,"recon_all: mFidSeek error for block %d\n",realtime_block); Werrprintf(str); (void)recon_abort(); ABORT; } #ifdef LINUX memcpy( & tmpBhp, (dblockhead *)(rInfo.fidMd->offsetAddr), sizeof(dblockhead) ); bhp = &tmpBhp; #else bhp = (dblockhead *)(rInfo.fidMd->offsetAddr); #endif /* byte swap if necessary */ DATABLOCKHEADER_CONVERT_NTOH(bhp); /* if(error = D_getbuf(D_USERFILE, nblocks, realtime_block, &inblock)) { Werrprintf("recon_all: error reading block 0"); (void)recon_abort(); ABORT; } bhp = inblock.head; cblockdata=inblock.data; */ ctcount = (int) (bhp->ctcount); if(within_nt){ nt=nts[(realtime_block/within_nt)%ntlen]; } else { Werrprintf("recon_all: within_nt equal to zero"); (void)recon_abort(); ABORT; } /*********************/ /* loop on blocks */ /*********************/ while((!acq_done)&&(ctcount==nt)) { if(interuption) { error=P_setstring(CURRENT, "wnt", "", 0); error=P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: aborting by request"); (void)recon_abort(); ABORT; } // cblockdata=inblock.data; /* copy pointer to data */ blockctr=realtime_block++; if(realtime_block>=nblocks) acq_done=TRUE; if(reallybig) { sprintf(str,"reading block %d\n",blockctr); Winfoprintf(str); } nt_scale=rInfo.image_scale; if(variableNT) nt_scale /= (ctcount); else nt_scale=rInfo.image_scale/nt; /* what channel is this? */ ichan= blockctr%rInfo.nchannels; if(ichan==(rInfo.nchannels-1)) lastchan=TRUE; else lastchan=FALSE; /* reset nt */ if(within_nt) { nt=nts[(realtime_block/within_nt)%ntlen]; } else { Werrprintf("recon_all: within_nt equal to zero"); (void)recon_abort(); ABORT; } /* point to data for this block */ inblock.head = bhp; floatstatus = bhp->status & S_FLOAT; rInfo.fidMd->offsetAddr += sizeof(dblockhead); inblock.data = (float *)(rInfo.fidMd->offsetAddr); /* get dc offsets if necessary */ if(rInfo.dc_flag) { real_dc=nt_scale*(bhp->lvl); imag_dc=nt_scale*(bhp->tlt); } if(epi_seq) { if(dimafter) icnt=(blockctr/dimafter)%(imglen)+1; else { Werrprintf("recon_all:dimafter equal to zero"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"image",&rimflag,icnt); if(error) { Werrprintf("recon_all: Error getting image element"); (void)recon_abort(); ABORT; } /* set flag to describe data block */ imflag=imflag_neg=pcflag=pcflag_neg=FALSE; if(rimflag==1.0) imflag=TRUE; else imflag=FALSE; if(rimflag==-1.0) imflag_neg=TRUE; else imflag_neg=FALSE; if(rimflag==-2.0) pcflag_neg=TRUE; else pcflag_neg=FALSE; if(rimflag==0.0) pcflag=TRUE; else pcflag=FALSE; } else imflag=TRUE; /* point to phase & image indicator */ if(pc_option!=OFF) { pcd=pc_done; if(epi_dualref && (imflag_neg || pcflag_neg)) pcd=pcneg_done; } if((imflag)||(pc_option!=OFF)) { /* start of raw data */ sdataptr=NULL; idataptr=NULL; fdataptr=NULL; if (rInfo.ebytes==2) sdataptr=(short *)inblock.data; else if (floatstatus == 0) idataptr=(int *)inblock.data; else fdataptr=(float *)inblock.data; if(((ro_size<nro)||(pe_size<views)||sview_zf)&&(phase_compressed)&&(!threeD)) { (void)memset(slicedata, 0, (dsize) * sizeof(*slicedata)); if(epi_dualref && (pc_option==TRIPLE_REF)) (void)memset(slicedata_neg, 0, (dsize) * sizeof(*slicedata_neg)); if(nnav) (void)memset(navdata, 0, (nsize) * sizeof(*navdata)); if((rawflag==RAW_MAG)||(rawflag==RAW_MP)) (void)memset(rawmag, 0, (dsize/2) * sizeof(*rawmag)); if((rawflag==RAW_PHS)||(rawflag==RAW_MP)) (void)memset(rawphs, 0, (dsize/2) * sizeof(*rawphs)); if(sense||phsflag) (void)memset(imgphs, 0, (dsize/2) * sizeof(*imgphs)); } if(imflag) { *fdfstr='\0'; if(rInfo.narray) { if(rInfo.nchannels >0) (void)arrayfdf((blockctr/rInfo.nchannels), rInfo.narray, rInfo.arrayelsP, fdfstr); else (void)arrayfdf(blockctr, rInfo.narray, rInfo.arrayelsP, fdfstr); } } for(itrc=0;itrc<ntraces;itrc++) { if (interuption) { error = P_setstring(CURRENT, "wnt", "", 0); error = P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: aborting by request"); (void) recon_abort(); ABORT; } /* figure out where to put this echo */ navflag=FALSE; status=svcalc(itrc,blockctr,&(rInfo.svinfo),&view,&slice,&echo,&nav,&slab); if(status) { (void)recon_abort(); ABORT; } oview=view; slab=0; if(nav>-1) navflag=TRUE; if((imflag_neg||imflag)&&multi_shot&&!navflag) { if(skview_order) view=skview_order[itrc]; else view=view_order[view]; if(threeD) { if(sskview_order) slice=sskview_order[itrc]; else if(sview_order) slice=sview_order[oview]; } } if(navflag&&!imflag&&!imflag_neg) { /* skip this echo and advance data pointer */ if (sdataptr) sdataptr+=2*nav_pts; else if(idataptr) idataptr+=2*nav_pts; else fdataptr+=2*nav_pts; } else if((imflag_neg || pcflag_neg)&& (pc_option != TRIPLE_REF)) { /* skip this echo and advance data pointer */ if (sdataptr) sdataptr+=2*nro; else if(idataptr) idataptr+=2*nro; else fdataptr+=2*nro; } else { if(!threeD) { /* which unique slice is this? */ uslice=slice; if(uslicesperblock != slicesperblock) { i=-1; j=-1; while((j<slice)&&(i<uslicesperblock)) { i++; j+=blockreps[i]; uslice=i; } } } /* evaluate repetition number */ if(imflag&&!navflag) { if(threeD) { rep= *(repeat+slab*slices*views*echoes+slice*views*echoes+view*echoes+echo); rep++; rep=rep%(slab_reps); *(repeat+slab*slices*views*echoes+slice*views*echoes+view*echoes+echo)=rep; } else { rep= *(repeat+slice*views*echoes+view*echoes+echo); rep++; rep=rep%(slice_reps); *(repeat+slice*views*echoes+view*echoes+echo)=rep; } } if(imflag||imflag_neg) { im_slice=slice; if(!navflag&&lastchan&&(pc_option!=OFF)) *(pcd+slice)=(*(pcd+ichan+ nchannels*slice)) | IMG_DONE; } else pc_slice=slice; if(threeD) { if(imflag||imflag_neg) im_slice=slab; else pc_slice=slab; } /* set up pointers & offsets */ if(!navflag) { nro2=nro; ro2=ro_size; npts=views*nro2; npts3d=npts*slices; datptr=slicedata; if(imflag_neg) datptr=slicedata_neg; if(threeD) { soffset=rep; soffset*=echoes; soffset+=echo; soffset*=slices; soffset+=slice; soffset*=views; soffset+=view; soffset*=(2*nro); /* soffset = rep*echoes*2*npts3d + echo*2*npts3d + slice*2*npts + view*2*nro; soffset=view*2*nro+echo*npts*2+rep*echoes*npts*2+slice*slice_reps*echoes*2*npts; */ } else { if(phase_compressed) soffset=view*2*nro+echo*npts*2+(slice%slicesperblock)*echoes*npts*2; else soffset=view*2*nro+echo*npts*2+rep*echoes*npts*2+slice*slice_reps*echoes*2*npts; } } else { nro2=nro; ro2=nav_pts; datptr=navdata; if(phase_compressed) soffset=nav*2*nro2+echo*nro2*nshots*nnav*2+ (slice%slicesperblock)*echoes*nro2*nshots*nnav*2; else soffset=nav*2*nro2+echo*nshots*nnav*nro2*2+rep*echoes*nnav*nshots*nro2*2+ slice*slice_reps*echoes*nnav*nshots*2*nro2; } /* scale and convert to float */ soffset+=(nro2-ro2); if (sdataptr) for(iro=0;iro<2*ro2;iro++) { s1=ntohs(*sdataptr++); *(datptr+soffset+iro)=nt_scale*s1; } else if(idataptr) for(iro=0;iro<2*ro2;iro++) { l1=ntohl(*idataptr++); *(datptr+soffset+iro)=nt_scale*l1; } else /* data is float */ for(iro=0;iro<2*ro2;iro++) { memcpy(&l1, fdataptr, sizeof(int)); fdataptr++; l1=ntohl(l1); memcpy(&ftemp,&l1, sizeof(int)); *(datptr+soffset+iro)=nt_scale*ftemp; } if(rInfo.dc_flag) { for(iro=0;iro<2*ro2;iro++) { if(iro%2) *(datptr+soffset+iro) -= imag_dc; else *(datptr+soffset+iro) -= real_dc; } } soffset-=(nro2-ro2); /* time reverse data */ if(epi_rev || rInfo.alt_readrev_flag) { reverse=FALSE; if((rInfo.alt_readrev_flag)&&(echo%2)) reverse=TRUE; else if(epi_rev) { if((imflag||pcflag)&&(oview%2)) reverse=TRUE; if((imflag_neg||pcflag_neg)&&((oview%2)==0)) reverse=TRUE; } /* reverse if even and positive readout OR if odd and negative readout */ if(reverse) { pt1=datptr+soffset; pt2=pt1+1; pt3=pt1+2*(nro2-1); pt4=pt3+1; for(iro=0;iro<nro2/2;iro++) { t1=*pt1; t2=*pt2; *pt1=*pt3; *pt2=*pt4; *pt3=t1; *pt4=t2; pt1+=2; pt2+=2; pt3-=2; pt4-=2; } } } if(rawflag&&imflag&&(!navflag)) { /* raw data must be written transposed */ roffset=soffset/2-view*nro2+view; switch(rawflag) { case RAW_MAG: for(iro=0;iro<nro2;iro++) { m1=(double)*(datptr+soffset+2*iro); m2=(double)*(datptr+soffset+2*iro+1); dtemp=sqrt(m1*m1+m2*m2); rawmag[roffset+iro*views]=(float)dtemp; } break; case RAW_PHS: for(iro=0;iro<nro2;iro++) { m1=(double)*(datptr+soffset+2*iro); m2=(double)*(datptr+soffset+2*iro+1); dtemp=atan2(m2,m1); rawphs[roffset+iro*views]=(float)dtemp; } break; case RAW_MP: for(iro=0;iro<nro2;iro++) { m1=(double)*(datptr+soffset+2*iro); m2=(double)*(datptr+soffset+2*iro+1); dtemp=sqrt(m1*m1+m2*m2); rawmag[roffset+iro*views]=(float)dtemp; dtemp=atan2(m2,m1); rawphs[roffset+iro*views]=(float)dtemp; } break; default: break; } } /* if((recon_window>NOFILTER)&&(recon_window<=MAX_FILTER)) */ if(read_window) { pt1=datptr+soffset+(nro2-ro2); wptr=read_window; for(iro=0;iro<ro2;iro++) { *pt1 *= *wptr; pt1++; *pt1 *= *wptr; pt1++; wptr++; } } if(navflag&&nav_window) { pt1=datptr+soffset+(nro2-ro2); wptr=nav_window; for(iro=0;iro<ro2;iro++) { *pt1 *= *wptr; pt1++; *pt1 *= *wptr; pt1++; wptr++; } } halfF_ro=FALSE; if(zeropad > HALFF*nro2) halfF_ro=TRUE; if(!halfF_ro) { /* read direction ft */ nrptr=datptr+soffset; /* apply frequency shift */ if(ro_frqP&&nmice) { ichan= blockctr%nmice; if((rInfo.alt_readrev_flag)&&echo%2) (void)rotate_fid(nrptr, 0.0, -1*ro_frqP[ichan], 2*nro2, COMPLEX); else (void)rotate_fid(nrptr, 0.0, ro_frqP[ichan], 2*nro2, COMPLEX); } /* else if(ro_frq!=0.0) { if((rInfo.alt_readrev_flag)&&echo%2) (void)rotate_fid(nrptr, 0.0, -1*ro_frq, 2*nro2, COMPLEX); else (void)rotate_fid(nrptr, 0.0, ro_frq, 2*nro2, COMPLEX); } */ level = nro2/(2*nro2); if (level > 0) { i = 2; while (i <= level) i *= 2; level= i/2; } else level = 0; level=0; pwr = 4; fnt = 32; while (fnt < 2*nro2) { fnt *= 2; pwr++; } (void)fftshift(nrptr,nro2); (void)fft(nrptr, nro2,pwr, level, COMPLEX,COMPLEX,-1.0,1.0,nro2); } /* phase correction application */ if(!navflag&&(imflag||imflag_neg)&&(pc_option!=OFF)) { pc_temp=pc; if(imflag_neg) pc_temp=pc_neg; if((pc_option!=OFF)&&(*(pcd+im_slice*nchannels + ichan) & PHS_DONE)) { /* pc_offset=im_slice*echoes*npts*2+echo*npts*2+view*nro*2; */ pc_offset=im_slice*nchannels*echoes*npts*2+ echo*nchannels*npts*2+ichan*npts*2 + oview*nro*2; if(threeD) pc_offset=im_slice*echoes*nchannels*npts3d*2+ echo*nchannels*npts3d*2+ichan*npts3d*2+oview*nro*2; pt1=datptr+soffset; pt2=pt1+1; pt3=pc_temp+pc_offset; pt4=pt3+1; pt5=pt1; pt6=pt5+1; for(iro=0;iro<nro;iro++) { a=*pt1; b=*pt2; c=*pt3; d=*pt4; *pt5=a*c-b*d; *pt6=a*d+b*c; pt1+=2; pt2+=2; pt3+=2; pt4+=2; pt5+=2; pt6+=2; } } } } /* end if image or not navigator */ } /* end of loop on traces */ // D_release(D_USERFILE,(realtime_block-1)); pcslice=rInfo.pc_slicecnt; /* compute phase correction */ if((pcflag||(pcflag_neg&&(pc_option==TRIPLE_REF)))&&(pc_option!=OFF)) { phase_correct=pc_option; if(pc_option==TRIPLE_REF) phase_correct=POINTWISE; pc_temp=pc; if(pcflag_neg) pc_temp=pc_neg; if(phase_compressed) { fptr=slicedata; if(multi_shot&&((pc_option==CENTER_PAIR)||(pc_option==FIRST_PAIR))) { for (ispb=0;ispb<slicesperblock*echoes;ispb++) { *(pcd+nchannels*(rInfo.pc_slicecnt)+ichan)=(*(pcd+nchannels*(rInfo.pc_slicecnt)+ichan)) | PHS_DONE; pc_offset=rInfo.pc_slicecnt*nchannels*npts*2 + ichan*npts*2; /* pc_offset+=(views-pe_size)*nro2; */ for(it=0;it<(pe_size/etl);it++) { (void)pc_calc(fptr, (pc_temp+pc_offset), nro2, etl, phase_correct, transposed); pc_offset += 2*nro2*etl; } rInfo.pc_slicecnt++; rInfo.pc_slicecnt=rInfo.pc_slicecnt%(slices*echoes); fptr+=2*npts; } } else { for (ispb=0;ispb<slicesperblock*echoes;ispb++) { *(pcd+nchannels*(rInfo.pc_slicecnt)+ichan)=(*(pcd+nchannels*(rInfo.pc_slicecnt)+ichan)) | PHS_DONE; pc_offset=rInfo.pc_slicecnt*nchannels*npts*2 + ichan*npts*2; /* pc_offset+=(views-pe_size)*nro2; */ (void)pc_calc(fptr, (pc_temp+pc_offset), nro2, pe_size, phase_correct, transposed); rInfo.pc_slicecnt++; rInfo.pc_slicecnt=rInfo.pc_slicecnt%(slices*echoes); fptr+=2*npts; } } } } /* if triple reference negative phase data and already have corresponding image data, do phase correction and continue */ if(pcflag_neg && (pc_option==TRIPLE_REF) && ( *(pcneg_done+nchannels*pcslice+ichan) & IMG_DONE)) { pcflag_neg=FALSE; imflag_neg=TRUE; pc_temp=pc_neg; /* location of phase correction data */ pt1=slicedata_neg; /* location of phase encoded negative readout reference data */ pt2=pt1+1; pt5=pt1; /* where to put result */ pt6=pt5+1; for (ispb=0;ispb<slicesperblock*echoes;ispb++) { for (iview=0;iview<pe_size;iview++) { oview=iview; /* figure out which unsorted view it is */ if(multi_shot && view_order) { oview=0; while(iview != view_order[oview]) oview++; } pc_offset=(pcslice+ispb)*nchannels*echoes*npts*2+ echo*nchannels*npts*2+ichan*2*npts+oview*nro*2; pt3=pc_temp+pc_offset; pt4=pt3+1; for(iro=0;iro<nro;iro++) { a=*pt1; b=*pt2; c=*pt3; d=*pt4; *pt5=a*c-b*d; *pt6=a*d+b*c; pt1+=2; pt2+=2; pt3+=2; pt4+=2; pt5+=2; pt6+=2; } } } } /* do 2nd transform if possible */ if(phase_compressed&&(imflag||(imflag_neg&&(pc_option==TRIPLE_REF)))&&(!threeD)) { magoffset=0; roffset=0; fptr=slicedata; if(imflag_neg) fptr=slicedata_neg; if(nnav) datptr=navdata; if(slice_compressed) for(ispb=0;ispb<slicesperblock;ispb++) blockrepeat[ispb]=-1; for(ispb=0;ispb<slicesperblock;ispb++) { /* which unique slice is this? */ uslice=slice; if(slice_compressed) uslice=ispb; urep=0; ibr=1; if(uslicesperblock != slicesperblock) { i=-1; j=-1; while((j<ispb)&&(i<uslicesperblock)) { i++; j+=blockreps[i]; uslice=i; } urep= blockrepeat[uslice]; urep++; blockrepeat[uslice]=urep; ibr=blockreps[uslice]; } /* bail out if haven't done phase correction for triple reference */ if(!((imflag_neg)&&!(*(pcd+ispb*nchannels+ichan) & PHS_DONE))) { for(iecho=0;iecho<echoes;iecho++) { if(nnav&&(nav_option!=OFF)) { if(rep==0) (void)getphase(0,nro,nshots*nnav,nav_refphase+roffset,datptr,FALSE); nav_correct(nav_option,fptr,nav_refphase+roffset,nro,pe_size,datptr, &(rInfo.svinfo)); roffset+=nro; } phase_reverse=FALSE; if(rInfo.phsrev_flag) phase_reverse=TRUE; if((rInfo.alt_phaserev_flag)&&iecho%2) { if(phase_reverse) phase_reverse=FALSE; else phase_reverse=TRUE; } if(nmice&&pe_frqP) pe_frq=pe_frqP[ichan]; if(ichan&&(!sense)) { if(phsflag) { (void)phase_ft(fptr,nro,views,phase_window,mag2+magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, imgphs2+magoffset,MAGNITUDE); for(ipt=0;ipt<npts;ipt++) { magnitude[magoffset+ipt]+=mag2[magoffset+ipt]; imgphs[magoffset+ipt]+=imgphs2[magoffset+ipt]; } } else { if(epi_dualref && (pc_option==TRIPLE_REF)) { if(imflag) { (void)phase_ft(fptr,nro,views,phase_window,imdata2+2*magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, NULL, COMPLEX); for(ipt=0;ipt<2*npts;ipt++) imdata[2*magoffset+ipt]+=imdata2[2*magoffset+ipt]; } if(imflag_neg) { (void)phase_ft(fptr,nro,views,phase_window,imdata2_neg+2*magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, NULL, COMPLEX); for(ipt=0;ipt<2*npts;ipt++) imdata_neg[2*magoffset+ipt]+=imdata2_neg[2*magoffset+ipt]; } } else /* this is the usual case */ { (void)phase_ft(fptr,nro,views,phase_window,mag2+magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, NULL, MAGNITUDE); for(ipt=0;ipt<npts;ipt++) magnitude[magoffset+ipt]+=mag2[magoffset+ipt]; } } } else if(sense) (void)phase_ft(fptr,nro,views,phase_window,magnitude+magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq,imgphs+magoffset, MAGNITUDE); else { if(phsflag) (void)phase_ft(fptr,nro,views,phase_window,magnitude+magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq,imgphs+magoffset, MAGNITUDE); else { if(epi_dualref && (pc_option==TRIPLE_REF)) { if(imflag) (void)phase_ft(fptr,nro,views,phase_window,imdata+2*magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, NULL, COMPLEX); if(imflag_neg) (void)phase_ft(fptr,nro,views,phase_window,imdata_neg+2*magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq, NULL, COMPLEX); } else /* this is the usual case */ (void)phase_ft(fptr,nro,views,phase_window,magnitude+magoffset,phase_reverse, zeropad,zeropad2,ro_frq,pe_frq,NULL, MAGNITUDE); } } /* write out images and/or raw data */ if(lastchan||sense||smash) { if(rInfo.nchannels) irep=(rep/(rInfo.nchannels)); else { Werrprintf("recon_all: nchannels equal to zero"); (void)recon_abort(); ABORT; } irep=irep*ibr + urep +1; if((rInfo.nchannels>1)&&(lastchan)&&(!sense)) { for(ipt=0;ipt<npts;ipt++) magnitude[magoffset+ipt]/=(rInfo.nchannels); } if(epi_dualref&&(pc_option==TRIPLE_REF)&&imflag&&lastchan&&(!sense)) { /* scale the complex sum of channels and pos & neg readout images */ for(ipt=0;ipt<2*npts;ipt++) { imdata[2*magoffset+ipt] += imdata_neg[2*magoffset+ipt]; imdata[2*magoffset+ipt]/=(2*(rInfo.nchannels)); } /* compute the magnitude */ fdptr=imdata+2*magoffset; for(ipt=0;ipt<npts;ipt++) { a1=*fdptr++; b1=*fdptr++; magnitude[magoffset+ipt] = (float)sqrt(a1*a1 + b1*b1); } } rInfo.picInfo.echo=iecho+1; rInfo.picInfo.slice=rInfo.slicecnt+1; rInfo.picInfo.slice=uslice+1; if(rawflag) { (void)strcpy(tempdir,rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; if((rawflag==RAW_MAG)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir,"rawmag"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if(smash) status=write_fdf(irep,rawmag+magoffset, &(rInfo.picInfo), &(rInfo.rawmag_order),display,fdfstr,threeD, (ichan+1)); else if(lastchan) status=write_fdf(irep,rawmag+magoffset, &(rInfo.picInfo), &(rInfo.rawmag_order),display,fdfstr,threeD, ch0); if(status) { (void)recon_abort(); ABORT; } } if((rawflag==RAW_PHS)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir,"rawphs"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if(smash) status=write_fdf(irep,rawphs+magoffset, &(rInfo.picInfo), &(rInfo.rawphs_order),display,fdfstr,threeD, (ichan+1)); else if(lastchan) status=write_fdf(irep,rawphs+magoffset, &(rInfo.picInfo), &(rInfo.rawphs_order),display,fdfstr,threeD, ch0); if(status) { (void)recon_abort(); ABORT; } } (void)strcpy(rInfo.picInfo.imdir,tempdir); rInfo.picInfo.fullpath=itemp; } display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if(sense) { /* write phase of image data */ (void)strcpy(tempdir,rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir,"reconphs"); display=FALSE; status=write_fdf(irep,imgphs+magoffset, &(rInfo.picInfo), &(rInfo.phase_order),display,fdfstr,threeD,(ichan+1)); (void)strcpy(rInfo.picInfo.imdir,tempdir); rInfo.picInfo.fullpath=itemp; /* write magnitude image data */ display=TRUE; status=write_fdf(irep,magnitude+magoffset, &(rInfo.picInfo), &(rInfo.phase_order),display,fdfstr,threeD,(ichan+1)); if(status) { (void)recon_abort(); ABORT; } } else if(lastchan&&imflag) { if(phsflag) { (void)strcpy(tempdir,rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir,"reconphs"); status=write_fdf(irep,imgphs+magoffset, &(rInfo.picInfo), &(rInfo.phase_order),display,fdfstr,threeD,ch0); if(status) { (void)recon_abort(); ABORT; } (void)strcpy(rInfo.picInfo.imdir,tempdir); rInfo.picInfo.fullpath=itemp; } if(look_locker){ temp1=irep; temp2=rInfo.picInfo.echo; irep=(temp1-1)*rInfo.picInfo.echoes+temp2; rInfo.picInfo.echo=1; temp3=rInfo.picInfo.echoes; rInfo.picInfo.echoes=1; temp4=rInfo.picInfo.image; rInfo.picInfo.image=temp3*temp4; // get corresponding inversion time error=P_getreal(PROCESSED,"ti",&dtemp,temp2); if (error) { Werrprintf("recon_all: recon_all: Error getting ti"); (void)recon_abort(); ABORT; } rInfo.picInfo.ti=(float)SEC_TO_MSEC*dtemp; status=write_fdf(irep,magnitude+magoffset, &(rInfo.picInfo), &(rInfo.image_order),display,fdfstr,threeD,ch0); irep=temp1; rInfo.picInfo.echo=temp2; rInfo.picInfo.echoes=temp3;rInfo.picInfo.image=temp4; } else status=write_fdf(irep,magnitude+magoffset, &(rInfo.picInfo), &(rInfo.image_order),display,fdfstr,threeD,ch0); if(status) { (void)recon_abort(); ABORT; } } } fptr+=2*npts; magoffset+=npts; datptr+=2*nshots*nnav*nro; } /* end of echo loop */ rInfo.slicecnt++; rInfo.slicecnt=rInfo.slicecnt%slices; } /* end of if bail out due to image_neg and no phase correction */ } /* end of slice loop */ } } /* end if imflag or doing phase correction */ /* see if recon has been forced */ error=P_getreal(CURRENT,"recon_force",&recon_force,1); if(!error) { if(recon_force>0.0) { error=P_setreal(CURRENT,"recon_force",0.0,1); /* turn it back off */ if(!phase_compressed) (void)generate_images(fdfstr); } } /* point to header of next block and get new ctcount */ if(!acq_done) { if(mFidSeek(rInfo.fidMd, (realtime_block+1), sizeof(dfilehead), rInfo.bbytes)) { (void)sprintf(str,"recon_all: mFidSeek error for block %d\n",realtime_block); Werrprintf(str); (void)recon_abort(); ABORT; } #ifdef LINUX memcpy( & tmpBhp, (dblockhead *)(rInfo.fidMd->offsetAddr), sizeof(dblockhead) ); bhp = &tmpBhp; #else bhp = (dblockhead *)(rInfo.fidMd->offsetAddr); #endif /* byte swap if necessary */ DATABLOCKHEADER_CONVERT_NTOH(bhp); ctcount = (int) (bhp->ctcount); /* if(error = D_getbuf(D_USERFILE, nblocks, realtime_block, &inblock)) { (void)sprintf(str,"recon_all: D_getbuf error for block %d\n",realtime_block); Werrprintf(str); (void)recon_abort(); ABORT; } bhp = inblock.head; */ } } /**************************/ /* end loop on blocks */ /**************************/ if(acq_done) { // D_close(D_USERFILE); *fdfstr='\0'; if((!phase_compressed) && (!threeD)) /* process data for each slice now */ (void)generate_images(fdfstr); if(threeD) /* process all 3D data */ (void)generate_images3D(fdfstr); #ifdef VNMRJ // (void)aipUpdateRQ(); /* sort by slices */ // (void)execString("rqsort2=1 aipRQcommand('display','',1,1)\n"); #endif (void)releaseAllWithId("recon_all"); if(rInfo.fidMd) { mClose(rInfo.fidMd); rInfo.fidMd=NULL; } } return(0); } /******************************************************************************/ /******************************************************************************/ static int generate_images(char *arrstr) { float ro_frq, pe_frq; float *fptr; float *window; double dtemp; int slices, views, nro, slice_reps, nchannels; int multi_shot, *dispcntptr, dispint, zeropad, zeropad2; int phsflag; int threeD=FALSE; int itemp; int rawflag, smash, sense; int i, j; int blkreps; int ibr; int uslices; int uslice; int echoes; int urep; int slice, rep, ipt; int ichan, irep; int npts; int echo; int phase_reverse; int display; int status; int lastchan; int ch0=0; int temp1, temp2, temp3, temp4; char tempdir[MAXPATHL]; char arstr[MAXSTR]; fptr=slicedata; blkreps=FALSE; /* get relevant parameters from struct */ slices=rInfo.svinfo.slices; views=rInfo.picInfo.npe; nro=rInfo.picInfo.nro; slice_reps=rInfo.svinfo.slice_reps; nchannels=rInfo.nchannels; window=rInfo.pwindow; multi_shot=rInfo.svinfo.multi_shot; dispcntptr=&(rInfo.dispcnt); dispint=rInfo.dispint; zeropad=rInfo.zeropad; zeropad2=rInfo.zeropad2; ro_frq=rInfo.ro_frq; pe_frq=rInfo.pe_frq; rawflag=rInfo.rawflag; sense=rInfo.sense; smash=rInfo.smash; phsflag=rInfo.phsflag; echoes=rInfo.svinfo.echoes; uslices=slices; npts=views*nro; if (blockreps) { for (i=0; i<slices; i++) { if (blockreps[i]>0) { blkreps=TRUE; uslices=i; } } } if (blockrepeat) for (slice=0; slice<slices; slice++) blockrepeat[slice]=-1; for (slice=0; slice<slices; slice++) { /* which unique slice is this? */ uslice=slice; urep=0; ibr=1; if (blkreps) { i=-1; j=-1; while ((j<slice)&&(i<uslices)) { urep=slice-j-1; i++; j+=blockreps[i]; uslice=i; } urep= blockrepeat[uslice]; urep++; blockrepeat[uslice]=urep; ibr=blockreps[uslice]; } for (rep=0; rep<(slice_reps/nchannels); rep++) { for (echo=0; echo<echoes; echo++) { phase_reverse=FALSE; if (rInfo.phsrev_flag) phase_reverse=TRUE; if ((rInfo.alt_phaserev_flag)&&echo%2) { if (phase_reverse) phase_reverse=FALSE; else phase_reverse=TRUE; } for (ichan=0; ichan<nchannels; ichan++) { if (ichan==(rInfo.nchannels-1)) lastchan=TRUE; else lastchan=FALSE; fptr=slicedata + slice*slice_reps*echoes*2*npts + rep*nchannels*echoes*2*npts + ichan*echoes*2*npts + echo*2*npts; if (nmice&&pe_frqP) pe_frq=pe_frqP[ichan]; if (ichan) { if (sense) (void)phase_ft(fptr, nro, views, window, magnitude, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, imgphs, MAGNITUDE); else if (phsflag) { (void)phase_ft(fptr, nro, views, window, mag2, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, imgphs2, MAGNITUDE); for (ipt=0; ipt<npts; ipt++) { magnitude[ipt]+=mag2[ipt]; imgphs[ipt]+=imgphs2[ipt]; } } else { (void)phase_ft(fptr, nro, views, window, mag2, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, NULL, MAGNITUDE); for (ipt=0; ipt<npts; ipt++) magnitude[ipt]+=mag2[ipt]; } } else { if (sense) (void)phase_ft(fptr, nro, views, window, magnitude, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, imgphs, MAGNITUDE); else if (phsflag) (void)phase_ft(fptr, nro, views, window, magnitude, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, imgphs, MAGNITUDE); else (void)phase_ft(fptr, nro, views, window, magnitude, phase_reverse, zeropad, zeropad2, ro_frq, pe_frq, NULL, MAGNITUDE); } // fptr+=2*npts; rInfo.picInfo.echo=echo+1; rInfo.picInfo.slice=slice+1; rInfo.picInfo.slice=uslice+1; irep=rep*ibr + urep +1; arstr[0]='\0'; if(rInfo.narray) { (void)arrayfdf(irep-1, rInfo.narray, rInfo.arrayelsP, arstr); } if (rawflag) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; status=0; if ((rawflag==RAW_MAG)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir, "rawmag"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if (smash) status=write_fdf(irep, rawmag, &(rInfo.picInfo), &(rInfo.rawmag_order), display, arstr, threeD, (ichan+1)); else if (lastchan) status=write_fdf(irep, rawmag, &(rInfo.picInfo), &(rInfo.rawmag_order), display, arstr, threeD, ch0); if (status) { (void)recon_abort(); ABORT; } } if ((rawflag==RAW_PHS)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir, "rawphs"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if (smash) status=write_fdf(irep, rawphs, &(rInfo.picInfo), &(rInfo.rawphs_order), display, arstr, threeD, (ichan+1)); else if (lastchan) status=write_fdf(irep, rawphs, &(rInfo.picInfo), &(rInfo.rawphs_order), display, arstr, threeD, ch0); if (status) { (void)recon_abort(); ABORT; } } /* restore imgdir */ (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } if (sense) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir, "reconphs"); display=FALSE; status=write_fdf(irep, imgphs, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeD, (ichan+1)); (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; /* write magnitude image data */ display=TRUE; status=write_fdf(irep, magnitude, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeD, (ichan+1)); if (status) { (void)recon_abort(); ABORT; } /* restore imgdir */ (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } else if (lastchan) { if (nchannels>1) { for (ipt=0; ipt<npts; ipt++) magnitude[ipt]/=nchannels; } display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if(rInfo.svinfo.look_locker){ temp1=irep; temp2=rInfo.picInfo.echo; irep=(temp1-1)*rInfo.picInfo.echoes+temp2; rInfo.picInfo.echo=1; temp3=rInfo.picInfo.echoes; rInfo.picInfo.echoes=1; temp4=rInfo.picInfo.image; rInfo.picInfo.image=temp3*temp4; // get corresponding inversion time status=P_getreal(PROCESSED,"ti",&dtemp,temp2); if (status) { Werrprintf("recon_all: recon_all: Error getting ti"); (void)recon_abort(); ABORT; } rInfo.picInfo.ti=(float)SEC_TO_MSEC*dtemp; status=write_fdf(irep,magnitude, &(rInfo.picInfo), &(rInfo.image_order),display,arstr,FALSE,ch0); irep=temp1; rInfo.picInfo.echo=temp2; rInfo.picInfo.echoes=temp3;rInfo.picInfo.image=temp4; } else { // this is the standard case status = write_fdf(irep, magnitude, &(rInfo.picInfo), &(rInfo.image_order), display, arstr, FALSE, ch0); } if (status) { (void)recon_abort(); ABORT; } if (phsflag) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir, "reconphs"); status=write_fdf(irep, imgphs, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeD, ch0); (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; if (status) { (void)recon_abort(); ABORT; } /* restore imgdir */ (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } } } /* end of channel loop */ } } } RETURN; } /******************************************************************************/ /* this is the 3D version */ /******************************************************************************/ static int generate_images3D(char *arstr) { vInfo info; float ro_frq, pe_frq; float *fptr; float *window; float *window2; int slices, views, nro, slice_reps, nchannels; int multi_shot, *dispcntptr, dispint, zeropad, zeropad2; int phsflag; int threeDslab; int itemp; int rawflag, smash, sense; int i, j; int blkreps; int ibr; int uslices; int uslice; int echoes; int urep; int nshifts; int slice, rep, ipt; int ichan, irep; int fnchan; int echo; int phase_reverse; int display; int slabs; int status; int npts2d, npts3d; int islab, islice; int error; int choffset; int offset; int lastchan; int ch0=0; int nomouse=0; char tempdir[MAXPATHL]; char str[200]; double *pe2_frq; double dtemp; double dfov; double pefrq; fptr=slicedata; blkreps=FALSE; slice = 0; /* get relevant parameters from struct */ slices=rInfo.svinfo.slices; views=rInfo.picInfo.npe; nro=rInfo.picInfo.nro; slice_reps=rInfo.svinfo.slice_reps; nchannels=rInfo.nchannels; window=rInfo.pwindow; window2=rInfo.swindow; multi_shot=rInfo.svinfo.multi_shot; dispcntptr=&(rInfo.dispcnt); dispint=rInfo.dispint; zeropad=rInfo.zeropad; zeropad2=rInfo.zeropad2; ro_frq=rInfo.ro_frq; pe_frq=rInfo.pe_frq; rawflag=rInfo.rawflag; sense=rInfo.sense; smash=rInfo.smash; phsflag=rInfo.phsflag; echoes=rInfo.svinfo.echoes; slabs=rInfo.svinfo.slabs; pefrq=pe_frq; uslices=slices; npts2d=views*nro; npts3d=npts2d*slices; fnchan=(smash|sense) ? nchannels:1; choffset=(smash|sense) ? 1:nchannels; if (blockreps) { for (i=0; i<slices; i++) { if (blockreps[i]>0) { blkreps=TRUE; uslices=i; } } } if (blockrepeat) for (slice=0; slice<slices; slice++) blockrepeat[slice]=-1; pe2_frq=NULL; error=P_getVarInfo(CURRENT,"ppe2",&info); if (!error && info.active) { nshifts=info.size; if (nshifts != slabs) { Werrprintf("recon_all: length of ppe2 less than slabs "); (void)recon_abort(); ABORT; } pe2_frq=(double *)allocateWithId(slabs*sizeof(double), "recon_all"); error=P_getreal(PROCESSED,"lpe2",&dfov,1); if (error) { Werrprintf("recon_all: Error getting lpe2"); (void)recon_abort(); ABORT; } for (islab=0; islab<slabs; islab++) { error=P_getreal(CURRENT,"ppe2",&dtemp,islab+1); if (error) { Werrprintf("recon_all: Error getting ppe2 "); (void)recon_abort(); ABORT; } pe2_frq[islab]=-180.0*dtemp/dfov; } } offset=0; for (islab=0; islab<slabs; islab++) { /* which unique slice is this? */ uslice=slice; urep=0; ibr=1; if (blkreps) { i=-1; j=-1; while ((j<slice)&&(i<uslices)) { urep=slice-j-1; i++; j+=blockreps[i]; uslice=i; } urep= blockrepeat[uslice]; urep++; blockrepeat[uslice]=urep; ibr=blockreps[uslice]; } for (rep=0; rep<(slice_reps/nchannels); rep++) { for (echo=0; echo<echoes; echo++) { phase_reverse=FALSE; if (rInfo.phsrev_flag) phase_reverse=TRUE; if ((rInfo.alt_phaserev_flag)&&echo%2) { if (phase_reverse) phase_reverse=FALSE; else phase_reverse=TRUE; } for (ichan=0; ichan<nchannels; ichan++) { if (ichan==(rInfo.nchannels-1)) lastchan=TRUE; else lastchan=FALSE; if (ichan) { if (phsflag) { (void)threeD_ft(fptr, nro, views, slices, window, window2, phase_reverse, zeropad, zeropad2, nomouse, imgphs2, &pefrq, pe2_frq); for (ipt=0; ipt<npts3d; ipt++) imgphs[ipt]+=imgphs2[ipt]; } else (void)threeD_ft(fptr, nro, views, slices, window, window2, phase_reverse, zeropad, zeropad2, nomouse, NULL, &pefrq, pe2_frq); } else { if (phsflag) (void)threeD_ft(fptr, nro, views, slices, window, window2, phase_reverse, zeropad, zeropad2, nomouse, imgphs+offset, &pefrq, pe2_frq); else (void)threeD_ft(fptr, nro, views, slices, window,window2, phase_reverse, zeropad, zeropad2, nomouse, NULL, &pefrq, pe2_frq); } fptr+=2*npts3d; offset += npts3d; } /* end ichan loop */ /* never output any 2D fdf files for 3D */ if (FALSE&&(dispint||sense||rawflag||phsflag)) { for (islice=0; islice<slices; islice++) { /* slice loop */ rInfo.picInfo.echo=echo+1; threeDslab=islab + 1; rInfo.picInfo.slice=islab*slices + islice + 1; /* rInfo.picInfo.slice=uslice+1;*/ irep=rep*ibr + urep +1; if (rawflag) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; if ((rawflag==RAW_MAG)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir, "rawmag"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if (smash) status=write_fdf(irep, rawmag+offset, &(rInfo.picInfo), &(rInfo.rawmag_order), display, arstr, threeDslab, (ichan+1)); else if (lastchan) status=write_fdf(irep, rawmag+offset, &(rInfo.picInfo), &(rInfo.rawmag_order), display, arstr, threeDslab, ch0); if (status) { (void)recon_abort(); ABORT; } } if ((rawflag==RAW_PHS)||(rawflag==RAW_MP)) { (void)strcpy(rInfo.picInfo.imdir, "rawphs"); display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; if (smash) status=write_fdf(irep, rawphs+offset, &(rInfo.picInfo), &(rInfo.rawphs_order), display, arstr, threeDslab, (ichan+1)); else if (lastchan) status=write_fdf(irep, rawphs+offset, &(rInfo.picInfo), &(rInfo.rawphs_order), display, arstr, threeDslab, ch0); if (status) { (void)recon_abort(); ABORT; } } (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } /* end if raw flag */ if (sense) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir, "reconphs"); status=write_fdf(irep, imgphs+offset, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeDslab, (ichan+1)); (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; /* write magnitude image data */ status=write_fdf(irep, magnitude+offset, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeDslab, (ichan+1)); if (status) { (void)recon_abort(); ABORT; } /* restore imgdir */ (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } if (phsflag && lastchan) { (void)strcpy(tempdir, rInfo.picInfo.imdir); itemp=rInfo.picInfo.fullpath; rInfo.picInfo.fullpath=FALSE; (void)strcpy(rInfo.picInfo.imdir, "reconphs"); status=write_fdf(irep, imgphs+offset, &(rInfo.picInfo), &(rInfo.phase_order), display, arstr, threeDslab, ch0); (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; if (status) { (void)recon_abort(); ABORT; } /* restore imgdir */ (void)strcpy(rInfo.picInfo.imdir, tempdir); rInfo.picInfo.fullpath=itemp; } if (nchannels>1) { for (ipt=0; ipt<npts2d; ipt++) magnitude[offset+ipt]/=nchannels; } display=DISPFLAG(rInfo.dispcnt, rInfo.dispint); rInfo.dispcnt++; status=write_fdf(irep, magnitude+offset, &(rInfo.picInfo), &(rInfo.image_order), display, arstr, threeDslab, ch0); if (status) { (void)recon_abort(); ABORT; } offset+=npts2d; } /* end slice loop */ }/* end if dispint */ } /* end of echo loop */ } /* end of rep loop */ }/* end of slab loop */ /* get rid of any fdf files first */ (void)sprintf(str, "%s/datadir3d/data/",curexpdir); (void)unlinkFilesWithSuffix(str, ".fdf"); /* create a big fdf containing all data for aipExtract */ /* need to reverse readout and phase directions for this */ rInfo.picInfo.echoes=echoes; rInfo.picInfo.datatype=MAGNITUDE; fptr=slicedata; for (islab=0; islab<slabs; islab++) { rInfo.picInfo.slice=islab+1; for (rep=0; rep<(slice_reps/nchannels); rep++) { arstr[0]='\0'; if (rInfo.narray) { (void)arrayfdf(rep, rInfo.narray, rInfo.arrayelsP, arstr); } rInfo.picInfo.image=(float)(rep+1.0); for (echo=0; echo<echoes; echo++) { rInfo.picInfo.echo=echo+1; for (ichan=0; ichan<fnchan; ichan++) { status=write_3Dfdf(fptr, &(rInfo.picInfo), arstr,ichan); if (status) { (void)recon_abort(); ABORT; } fptr+=2*npts3d*choffset; } } } } /* copy first image 3D fdf to data.fdf in case someone needs it there */ /* (void)sprintf(str, "cp %s/datadir3d/data/img_slab001image001echo001.fdf %s/datadir3d/data/data.fdf \n", curexpdir, curexpdir); ierr=system(str); */ /* do all that for raw magnitude if needed */ if ((rawflag==RAW_MAG) || (rawflag==RAW_MP)) { rInfo.picInfo.datatype=RAW_MAG; fptr=rawmag; for (islab=0; islab<slabs; islab++) { rInfo.picInfo.slice=islab+1; for (rep=0; rep<(slice_reps/nchannels); rep++) { arstr[0]='\0'; if(rInfo.narray) (void)arrayfdf(rep, rInfo.narray, rInfo.arrayelsP, arstr); rInfo.picInfo.image=(float)(rep+1.0); for (echo=0; echo<echoes; echo++) { rInfo.picInfo.echo=echo+1; for (ichan=0; ichan<fnchan; ichan++) { status=write_3Dfdf(fptr, &(rInfo.picInfo), arstr, ichan); if (status) { (void)recon_abort(); ABORT; } fptr+=2*npts3d*choffset; } } } } } /* do all that for raw phase if needed */ if ((rawflag==RAW_PHS) || (rawflag==RAW_MP)) { rInfo.picInfo.datatype=RAW_PHS; fptr=rawphs; for (islab=0; islab<slabs; islab++) { rInfo.picInfo.slice=islab+1; for (rep=0; rep<(slice_reps/nchannels); rep++) { arstr[0]='\0'; if(rInfo.narray) (void)arrayfdf(rep, rInfo.narray, rInfo.arrayelsP, arstr); rInfo.picInfo.image=(float)(rep+1.0); for (echo=0; echo<echoes; echo++) { rInfo.picInfo.echo=echo+1; for (ichan=0; ichan<fnchan; ichan++) { status=write_3Dfdf(fptr, &(rInfo.picInfo), arstr, ichan); if (status) { (void)recon_abort(); ABORT; } fptr+=2*npts3d*choffset; } } } } } /* do all that for phase if needed */ if (phsflag) { rInfo.picInfo.datatype=PHS_IMG; fptr=slicedata; for (islab=0; islab<slabs; islab++) { rInfo.picInfo.slice=islab+1; for (rep=0; rep<(slice_reps/nchannels); rep++) { rInfo.picInfo.image=(float)(rep+1.0); arstr[0]='\0'; if(rInfo.narray) (void)arrayfdf(rep, rInfo.narray, rInfo.arrayelsP, arstr); for (echo=0; echo<echoes; echo++) { rInfo.picInfo.echo=echo+1; for (ichan=0; ichan<fnchan; ichan++) { status=write_3Dfdf(fptr, &(rInfo.picInfo), arstr, ichan); if (status) { (void)recon_abort(); ABORT; } fptr+=2*npts3d*choffset; } } } } } RETURN; } /********************************************************************************/ /* halfFourier */ /********************************************************************************/ void halfFourier(data, nsamp, nfinal, method) float *data;int nsamp, nfinal, method; { int i; int offset; int nsmall; int nfill; int nf2; int pwr, fnt; float *fptr; float *fptr2; float *cdata; float *tdata; float t1, t2; double a, b; double d1, d2; double *phstmp; double *dptr; nf2=nfinal/2; nsmall=nsamp-nf2; nsmall*=2; offset=nfinal-nsamp; offset*=2; /* complex data */ pwr = 4; fnt = 32; while (fnt < 2*nfinal) { fnt *= 2; pwr++; } cdata=(float *)recon_allocate(2*nfinal*sizeof(float), "halfFourier"); tdata=(float *)recon_allocate(2*nfinal*sizeof(float), "halfFourier"); phstmp=(double *)recon_allocate(nfinal*sizeof(double), "halfFourier"); /* zero these buffers */ for (i=0; i<2*nfinal; i++) { cdata[i]=0.0; tdata[i]=0.0; } /* copy data into tdata and perform shift as data is zerofilled at back*/ fptr=tdata+offset; fptr2=data; for (i=0; i<2*nsamp; i++) *fptr++=*fptr2++; /* get FT of center data and find phase */ fptr=tdata+offset; for (i=0; i<2*nsmall; i++) cdata[i+offset]=*fptr++; (void)fft(cdata, nfinal, pwr, 0, COMPLEX, COMPLEX, -1.0, 1.0, nfinal); (void)getphase(0, nfinal, 1, phstmp, cdata, FALSE); if (method==LINEAR) { (void)phaseunwrap(phstmp, nfinal, phstmp); (void)polyfit(phstmp, nfinal, phstmp, LINEAR); } /* FT data, phase correct, then IFT */ (void)fft(tdata, nfinal, pwr, 0, COMPLEX, COMPLEX, -1.0, 1.0, nfinal); fptr=tdata; dptr=phstmp; for (i=0; i<nfinal; i++) { d1=*fptr; d2=*(fptr+1); a=cos(*dptr); b=-sin(*dptr++); *fptr++=(float) (d1*a-d2*b); *fptr++=(float)(a*d2+b*d1); } fftshift(tdata, nfinal); (void)fft(tdata, nfinal, pwr, 0, COMPLEX, COMPLEX, 1.0, -1.0, nfinal); fftshift(tdata, nfinal); /* copy data back to original location*/ /* data is shifted for some reason */ /* fptr=data+2; fptr2=tdata+2*nfinal-1; for(i=0;i<2*(nfinal-1);i++) *fptr++=*fptr2--; *data=*tdata; *(data+1)=*(tdata+1); */ fptr=data; fptr2=tdata; for (i=0; i<2*nfinal; i++) *fptr++=*fptr2++; /* now synthesize missing data */ nfill=nfinal-nsamp; fptr=data; fptr2=data+2*nfinal-1; for (i=0; i<nfill; i++) { t1=*fptr++; t2=-1.0*(*fptr++); *fptr2--=t2; *fptr2--=t1; } releaseAllWithId("halfFourier"); return; } /********************************************************************************************************/ /* fftshift routine */ /********************************************************************************************************/ static void fftshift(float *data, int npts) { float *fptr; float t1, t2; int i; int n2; n2=npts/2; /*perform the shift */ fptr=data; for (i=0; i<n2; i++) { t1=*(fptr+npts); t2=*(fptr+1+npts); *(fptr+npts)=*fptr; *(fptr+1+npts)=*(fptr+1); *fptr++=t1; *fptr++=t2; } return; } /********************************************************************************************************/ /* nav_correct performs phase correction for raw data based on phase of navigators */ /********************************************************************************************************/ static void nav_correct(int method, float *data, double *ref_phase, int nro, int npe, float *navdata, svInfo *svI) { int i; int tnav; int nsegs; int ipt; int iseg; int iv; int npts; int offset; int netl; int nmod; float *fptr; double *dptr; double *dptr2; double a, b, c; double d1, d2; double *uphs; double *nav_phase; double phi; netl=svI->nnav+svI->etl; npts=nro; nsegs=(svI->pe_size)/(svI->etl); tnav=(svI->nnav)*nsegs; nmod=svI->nnav; nav_phase=(double *)recon_allocate(tnav*npts*sizeof(double), "nav_correct"); uphs = (double *)recon_allocate(npts*sizeof(double), "nav_correct"); /* get phase of each navigator */ offset=0; for (i=0; i<tnav; i++) { (void)getphase(i, npts, tnav, nav_phase+offset, navdata, FALSE); offset+=npts; } dptr=nav_phase; if (method==PAIRWISE) { nmod=2; /* for picking out correction echo */ /* compute even/odd phase differences */ for (i=0; i<nsegs; i++) { dptr=nav_phase+i*npts*(svI->nnav); dptr2=dptr+npts; for (ipt=0; ipt<npts; ipt++) { a=*dptr; b=*dptr2; /* c=0.5*(a-b); *dptr++ = c; *dptr2++ = -c; *dptr++ = a; *dptr2++ = b; */ c=(b-a); *dptr++ = 0.; *dptr2++ = c; } } } /* correct with reference navigator */ dptr=nav_phase; for (i=0; i<tnav; i++) for (ipt=0; ipt<npts; ipt++) *dptr++ -= ref_phase[ipt]; /* perform least squares fit if needed */ if (method==LINEAR) { dptr=nav_phase; fptr=navdata; for (i=0; i<tnav; i++) { (void)phaseunwrap(dptr, npts, uphs); /* fit to polynomial and return polynomial evaluation */ (void)smartphsfit(fptr, uphs, npts, dptr); dptr+=npts; fptr+=2*npts; } } /* now correct imaging data */ fptr=data; for (i=0; i<npe; i++) { if (svI->multi_shot) { /* find unsorted view */ iv=0; while (view_order[iv] != i) iv++; } else iv=i; iseg=iv/(svI->etl); if (nav_list[0]==0) iv+=svI->nnav; offset=iseg*(svI->nnav)+ iv%nmod; offset=offset%tnav; offset*=npts; for (ipt=0; ipt<nro; ipt++) { phi=nav_phase[offset+ipt]; a=cos(phi); b=-sin(phi); d1=*fptr; d2=*(fptr+1); *fptr++=(float)(d1*a-d2*b); *fptr++=(float)(a*d2+b*d1); } } releaseAllWithId("nav_correct"); return; } /********************************************************************************************************/ /* phase_ft is also responsible for reversing magnitude data in read & phase directions (new fft) */ /* int output_type MAGNITUDE or COMPLEX */ /********************************************************************************************************/ static void phase_ft(float *xkydata, int nx, int ny, float *win, float *absdata, int phase_rev, int zeropad_ro, int zeropad_ph, float ro_frq, float ph_frq, float *phsdata, int output_type) { float a, b; float *fptr, *pptr, *pt1, *pt2; int ix, iy; int np; int pwr, fnt; int offset; int halfR=FALSE; int halfP=FALSE; float *nrptr; float templine[2*MAXPE]; float *tempdat = NULL; fptr=absdata; pptr=phsdata; np=nx*ny; if (zeropad_ph > HALFF*ny) halfP=TRUE; if (zeropad_ro > HALFF*nx) { halfR=TRUE; tempdat=(float *)recon_allocate(2*np*sizeof(float), "phase_ft"); } /* do phase direction ft */ for (ix=nx-1; ix>-1; ix--) { if (interuption) { (void)P_setstring(CURRENT, "wnt", "", 0); (void)P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: aborting by request"); //(void) recon_abort(); return; } /* get the ky line */ nrptr=templine; if (phase_rev && (!halfP)) { pt1=xkydata+2*ix; pt1+=(ny-1)*2*nx; pt2=pt1+1; for (iy=0; iy<ny; iy++) { *nrptr++=*pt1; *nrptr++=*pt2; pt1-=2*nx; pt2=pt1+1; } } else { pt1=xkydata+2*ix; pt2=pt1+1; nrptr=templine; for (iy=0; iy<ny; iy++) { *nrptr++=*pt1; *nrptr++=*pt2; pt1+=2*nx; pt2=pt1+1; } } if (win) { for (iy=0; iy<ny; iy++) { templine[2*iy]*= *(win+iy); templine[2*iy+1]*= *(win+iy); } } if (halfP) { /* perform half Fourier data estimation */ (void)halfFourier(templine, (ny-zeropad_ph), ny, POINTWISE); if (phase_rev) { offset=2*(ny-1); /* reverse after doing the processing */ for (iy=0; iy<ny; iy++) { a=templine[2*iy]; b=templine[2*iy+1]; templine[2*iy]=templine[offset-2*iy]; templine[2*iy+1]=templine[offset-2*iy+1]; templine[offset-2*iy]=a; templine[offset-2*iy+1]=b; } } } /* apply frequency shift */ if (ph_frq!=0.0) { if (phase_rev) (void)rotate_fid(templine, 0.0, -1*ph_frq, 2*ny, COMPLEX); else (void)rotate_fid(templine, 0.0, ph_frq, 2*ny, COMPLEX); } nrptr=templine; pwr = 4; fnt = 32; while (fnt < 2*ny) { fnt *= 2; pwr++; } (void)fftshift(nrptr,ny); (void)fft(nrptr, ny, pwr, 0, COMPLEX, COMPLEX, -1.0, 1.0, ny); /* write it back */ if (halfR) { pt1=tempdat+2*ix; pt2=pt1+1; nrptr=templine; for (iy=0; iy<ny; iy++) { *pt1=*nrptr++; *pt2=*nrptr++; pt1+=2*nx; pt2=pt1+1; } } else /* write result */ { if (output_type==MAGNITUDE) { nrptr=templine+2*ny-1; for (iy=0; iy<ny; iy++) { a=*nrptr--; b=*nrptr--; *fptr++=(float)sqrt((double)(a*a+b*b)); if (phsdata) *pptr++=(float)atan2(b, a); } } else if (output_type==COMPLEX) { nrptr=templine+2*ny-1; for (iy=0; iy<ny; iy++) { a=*nrptr--; b=*nrptr--; *fptr++=(float)a; *fptr++=(float)b; if (phsdata) *pptr++=(float)atan2(b, a); } } } } if (halfR) { /* perform half Fourier in readout */ nrptr=tempdat; for (iy=0; iy<ny; iy++) { (void)halfFourier(nrptr, (nx-zeropad_ro), nx, POINTWISE); pwr = 4; fnt = 32; while (fnt < 2*ny) { fnt *= 2; pwr++; } /* apply frequency shift */ if (ro_frq!=0.0) (void)rotate_fid(nrptr, 0.0, ro_frq, 2*nx, COMPLEX); (void)fft(nrptr, nx, pwr, 0, COMPLEX, COMPLEX, -1.0, 1.0, nx); nrptr+=2*nx; } /* write out result */ if (output_type==MAGNITUDE) { for (ix=nx-1; ix>-1; ix--) { for (iy=ny-1; iy>-1; iy--) { nrptr=tempdat+2*ix+iy*2*nx; a=*nrptr++; b=*nrptr++; *fptr++=(float)sqrt((double)(a*a+b*b)); if (phsdata) *pptr++=(float)atan2(b, a); } } } else if (output_type==COMPLEX) { for (ix=nx-1; ix>-1; ix--) { for (iy=ny-1; iy>-1; iy--) { nrptr=tempdat+2*ix+iy*2*nx; a=*nrptr++; b=*nrptr++; *fptr++=(float)a; *fptr++=(float)b; if (phsdata) *pptr++=(float)atan2(b, a); } } } } (void)releaseAllWithId("phase_ft"); return; } /******************************************************************************/ /******************************************************************************/ static void filter_window(int window_type, float *window, int npts) { double f, alpha; int i; switch (window_type) { case NOFILTER: return; case BLACKMANN: { for (i=0; i<npts; i++) window[i]=0.42-0.5*cos(2*M_PI*(i-1)/(npts-1))+0.08*cos(4*M_PI*(i-1) /(npts-1)); return; } case HANN: { for (i=0; i<npts; i++) window[i]=0.5*(1-cos(2*M_PI*(i-1)/(npts-1))); return; } case HAMMING: { for (i=0; i<npts; i++) window[i]=0.54-0.46*cos(2*M_PI*(i-1)/(npts-1)); return; } case GAUSSIAN: { alpha=2.5; f=(-2*alpha*alpha)/(npts*npts); for (i=0; i<npts; i++) window[i]=exp(f*(i-1-npts/2)*(i-1-npts/2)); return; } case GAUSS_NAV: { alpha=20; f=(-2*alpha*alpha)/(npts*npts); for (i=0; i<npts; i++) window[i]=exp(f*(i-1-npts/2)*(i-1-npts/2)); return; } default: return; } } /******************************************************************************/ /******************************************************************************/ int pc_pick(char *pc_str) { int pc_opt; /* decipher phase correction option */ if (strstr(pc_str, "OFF")||strstr(pc_str, "off")) pc_opt=OFF; else if (strstr(pc_str, "POINTWISE")||strstr(pc_str, "pointwise")) pc_opt=POINTWISE; else if (strstr(pc_str, "LINEAR")||strstr(pc_str, "linear")) pc_opt=LINEAR; else if (strstr(pc_str, "QUADRATIC")||strstr(pc_str, "quadratic")) pc_opt=QUADRATIC; else if (strstr(pc_str, "CENTER_PAIR")||strstr(pc_str, "center_pair")) pc_opt=CENTER_PAIR; else if (strstr(pc_str, "PAIRWISE")||strstr(pc_str, "pairwise")) pc_opt=PAIRWISE; else if (strstr(pc_str, "FIRST_PAIR")||strstr(pc_str, "first_pair")) pc_opt=FIRST_PAIR; else if (strstr(pc_str, "TRIPLE_REF")||strstr(pc_str, "triple_ref")) pc_opt=TRIPLE_REF; else pc_opt=10000; return (pc_opt); } /******************************************************************************/ /******************************************************************************/ /* returns slice and view number given trace and block number */ int svcalc(trace, block, svI, view, slice, echo, nav, slab) int trace, block;svInfo *svI;int *view;int *slice;int *echo;int *nav;int *slab; { int v, s, sl, sv; int d; int i; int nav1 = 0; int nec, ec; int netl; int n; int seg; int nnavs; int navflag; int viewsize, slabsize, sviewsize, segsize; netl=svI->etl; nnavs=(svI->pe_size)/(netl); nnavs*=(svI->nnav); nec=0; *nav=-1; *slab=0; navflag=FALSE; if (svI->threeD) { if (svI->phase_compressed) viewsize=svI->etl; else viewsize=1; if (svI->multi_shot) segsize=svI->pe_size/(svI->etl); else segsize=1; if(svI->phase_compressed) segsize=svI->pe_size/(svI->etl); if (svI->slab_compressed) slabsize=svI->slabs; else slabsize=1; if (svI->sliceenc_compressed) sviewsize=svI->pe2_size; else sviewsize=1; ec=trace%((svI->etl)*(svI->echoes)); if (svI->multi_slice) { sl=trace/(viewsize*svI->echoes); /* slab number */ seg=trace/(viewsize*slabsize*svI->echoes); /* segment number */ sv=trace/(viewsize*slabsize*segsize*svI->echoes); /* slice encode view */ /* sv=trace/(viewsize); *//* slice encode number */ /* sl=trace/(viewsize*sviewsize); *//* slab number */ /* seg=trace/(viewsize*sviewsize*slabsize); *//* segments are outermost */ } else { seg=trace/(viewsize*svI->echoes); /* segment number */ sl=trace/(viewsize*segsize*svI->echoes); /* slab number */ sv=trace/(viewsize*slabsize*segsize*svI->echoes); /* slice encode view */ sv=trace/(viewsize*svI->echoes); /* slice encode number */ sl=trace/(viewsize*sviewsize*svI->echoes); /* slab number */ seg=trace/(viewsize*sviewsize*slabsize*svI->echoes); /* segments are outermost */ } v=seg*viewsize+ec; if (!svI->slab_compressed) sl=(block/svI->within_slabs); if (!svI->phase_compressed) v=(block/svI->within_views); if (!svI->sliceenc_compressed) sv=(block/svI->within_sviews); *view=v%(svI->pe_size); *slab=sl%(svI->slabs); *slice=sv%(svI->pe2_size); } else /* ***************** 2D case below this point ****** */ { if (svI->nnav) { netl+=svI->nnav; /* figure out how many navigators preceed this */ d=(netl); if (d) ec=(trace%d); else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } i=0; while ((i<svI->nnav)&&(!navflag)) { if (nav_list[i]<ec) nec++; else if (nav_list[i]==ec) { nav1=i; navflag=TRUE; } i++; } if (navflag) { /* kludge to make view even or odd for echo reversal in epi */ if ((nav_list[0]==0)&&((svI->nnav)%2)) nec=-1; else nec=0; if (svI->multi_slice) { d=(netl)*(svI->slicesperblock)*(svI->echoes); if (d) n=trace/d; /* segment */ else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } n*=svI->nnav; /* times navigators per segment */ /* n+=ec; *//* plus echo */ n+=nav1; /* plus echo */ *nav=n; } else *nav=trace; *nav=(*nav)%(nnavs); } } /* end if navigators */ if (svI->look_locker||svI->multi_shot||svI->epi_seq||svI->nnav) { if (svI->phase_compressed) { if (svI->multi_slice) d=(netl)*(svI->slicesperblock)*(svI->echoes); else d=(netl)*(svI->echoes); if (d) v=trace/d; /* segment */ else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } v*=svI->etl; /* times etl */ if (svI->look_locker==1) d = 1.0; // views change fastest else if (svI->look_locker==2) d = (svI->echoes) * (svI->slicesperblock); else // d=(svI->slicesperblock)*(svI->echoes); d = (svI->echoes); if (d) v+=((trace/d)%(netl)); /* plus echo */ else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } v=v-nec; } else /* not phase compressed but still multi-shot (like FSE) */ { d=svI->within_views; if (d) v=(block/d); else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } v*=svI->etl; /* times etl */ if ((svI->multi_slice) && (svI->etl==1)) d=(svI->slicesperblock)*(svI->echoes); else if(svI->look_locker) d=1; // views change innermost for look locker else if (svI->look_locker==2) d = (svI->echoes) * (svI->slicesperblock); else d=(svI->echoes); if (d) v+=((trace/d)%(netl)); /* plus echo */ else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } v=v-nec; } if (svI->slice_compressed) { if (svI->multi_slice) { d=netl; if(svI->look_locker)d *= (svI->echoes); if(svI->look_locker == 2)d =1; // slices innermost if (d) s=trace/d; else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } else { d=svI->viewsperblock; if (d) s=trace/d; else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } } else /* not slice compressed */ { d=(svI->within_slices); if (d) s=(block/d); else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } } else /* not multi_shot */ { if (svI->phase_compressed) { if (svI->multi_slice) d=(svI->slicesperblock)*(svI->echoes); else d=(svI->echoes); if (d) v=trace/d; else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } else { d=(svI->within_views); if (d) v=(block/d); else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } if (svI->slice_compressed) { if (svI->multi_slice) d=(svI->echoes); else d=(svI->viewsperblock)*(svI->echoes); if (d) s=trace/d; else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } else { d=(svI->within_slices); if (d) s=(block/d); else { Werrprintf("recon_all:svcalc: divide by zero"); (void)recon_abort(); ABORT; } } } *view=v%(svI->pe_size); *slice=s%(svI->slices); } /* end if not threeD */ if (svI->epi_seq) { d = (netl) * (svI->slicesperblock); if (d) *echo = trace / d; else { Werrprintf("recon_all:svcalc: divide by zero"); (void) recon_abort(); ABORT; } *echo = (*echo) % (svI->echoes); } else if (svI->look_locker == 1) { d = netl; *echo = (trace / d) % (svI->echoes); // echoes outside etl loop } else if (svI->look_locker == 2) { d = (svI->slicesperblock); *echo = (trace / d) % (svI->echoes); // echoes outside etl loop } else *echo = trace % (svI->echoes); return (0); } /******************************************************************************/ /******************************************************************************/ char *recon_allocate(nsize, caller_id) int nsize;char *caller_id; { char *ptr; char str[MAXSTR]; ptr=NULL; ptr=allocateWithId(nsize, caller_id); if (!ptr) { (void)sprintf(str, "recon_all: Error mallocing size of %d \n", nsize); Werrprintf(str); (void)recon_abort(); return (NULL); } return (ptr); } /******************************************************************************/ /******************************************************************************/ void recon_abort() { // D_close(D_USERFILE); if (rInfo.fidMd) { mClose(rInfo.fidMd); rInfo.fidMd=NULL; } recon_aborted=TRUE; (void)releaseAllWithId("recon_all"); return; } /******************************************************************************/ /******************************************************************************/ int svib_image(pname, image) char *pname;int image; { char arraystr[MAXSTR]; char errstr[MAXSTR]; char *imptr=NULL; char *lp=NULL; char *rp=NULL; char *nmptr=NULL; int i=0; int error; int imcnt=0; double rimflag; error=P_getstring(PROCESSED,"array", arraystr, 1, MAXSTR); if (error) { Werrprintf("recon_all: svib_image: Error getting array"); (void)recon_abort(); ABORT; } lp=strstr(arraystr, "("); imptr=strstr(arraystr, "image"); nmptr=strstr(arraystr, pname); rp=strstr(arraystr, ")"); if (((imptr>lp)&&(nmptr>lp)&&(imptr<rp)&&(nmptr<rp)) || ( rInfo.svinfo.epi_seq)){ /* how many when image=1? */ i=0; while(imcnt<image) { error=P_getreal(PROCESSED,"image",&rimflag,(i+1)); if (error) { sprintf(errstr,"recon_all: svib_image: Error getting image element %d \n",i+1); Werrprintf(errstr); (void)recon_abort(); return(-1); } if (rimflag==1.0) imcnt++; i++; } } else i=image; return (i); } /******************************************************************************/ /******************************************************************************/ int write_fdf(imageno, datap, fI, image_orderP, display, arstr, threeD, channel) int imageno;fdfInfo *fI;float *datap;int *image_orderP;int display;char *arstr;int threeD;int channel; { MFILE_ID fdfMd; vInfo info; char *ptr; char *ptr2; char sviblist[MAXSTR]; char filename[MAXPATHL]; char dirname[MAXPATHL]; char svbname[SHORTSTR]; char ctemp[SHORTSTR]; char str[100]; char hdr[2000]; int i, error; int ierr; int pad_cnt, align; int hdrlen; int filesize; int ior; int slice_acq, slice_pos; int nimage; int id; int w1, w2, w3; double rppe, rpro, rpss; double orppe, orpro, orpss; double psi, phi, theta; double cospsi, cosphi, costheta; double sinpsi, sinphi, sintheta; double or0, or1, or2, or3, or4, or5, or6, or7, or8; double te; double dtemp; if (fI->fullpath) (void)strcpy(dirname, fI->imdir); else { (void)strcpy(dirname, curexpdir); (void)strcat(dirname, "/"); (void)strcat(dirname, fI->imdir); } (void)strcpy(filename, dirname); if ((*image_orderP==0)&&!channel) { (void)unlinkFilesWithSuffix(dirname, ".fdf"); } slice_acq=fI->slice; if (!threeD) { i=0; while (slice_acq != slice_order[i]) i++; slice_pos=i+1; } else { slice_pos=fI->slice; slice_acq=threeD; } w1= (fI->slices)> 999 ? 1 + (int)log10(fI->slices) : 3; w2= (fI->image)> 999 ? 1 + (int)log10(fI->image) : 3; w3= (fI->echoes)> 999 ? 1 + (int)log10(fI->echoes) : 3; (void)sprintf(str, "/slice%0*dimage%0*decho%0*d", w1,slice_pos, w2, imageno, w3, fI->echo); (void)strcat(filename, str); if (channel) { (void)sprintf(str, "coil%03d", channel); (void)strcat(filename, str); } (void)strcat(filename, ".fdf"); /* get some slice or image specific information */ rpss=0.0; if (nmice) { rpss=0.0; error=P_getreal(PROCESSED,"mpss",&rpss,channel); if (threeD) rpss += (slice_pos- (fI->slices/2))*fI->thickness; else { error=P_getreal(PROCESSED,"pss",&dtemp,slice_acq); if (error) { Werrprintf("recon_all: write_fdf: Error getting slice offset pss"); (void)recon_abort(); ABORT; } rpss+=dtemp; } rppe=0.0; error=P_getreal(PROCESSED,"mppe",&rppe,channel); /* account for pe direction shift in recon */ rppe += (fI->fovpe)*(rInfo.pe_frq/180.); rpro=0.0; error=P_getreal(PROCESSED,"mpro",&rpro,channel); orppe=rppe; orpro=rpro; orpss=rpss; error=P_getreal(GLOBAL,"moriginx",&orpro,channel); error=P_getreal(GLOBAL,"moriginy",&orppe,channel); error=P_getreal(GLOBAL,"moriginz",&orpss,channel); } else { if (threeD) rpss += (slice_pos- (fI->slices/2))*fI->thickness; else { error=P_getreal(PROCESSED,"pss",&rpss,slice_acq); if (error) { Werrprintf("recon_all: write_fdf: Error getting slice offset"); (void)recon_abort(); ABORT; } } error=P_getreal(PROCESSED,"ppe",&rppe,1); if (error) { Werrprintf("recon_all: write_fdf: Error getting phase encode offset"); (void)recon_abort(); ABORT; } /* account for pe direction shift in recon */ rppe = (fI->fovpe)*(rInfo.pe_frq/180.); error=P_getreal(PROCESSED,"pro",&rpro,1); if (error) { Werrprintf("recon_all: write_fdf: Error getting readout offset"); (void)recon_abort(); ABORT; } orppe=rppe; orpro=rpro; } /* get orientation for this image */ ior=(imageno-1)%(fI->npsi)+1; error=P_getreal(PROCESSED,"psi",&psi,ior); if (error) { Werrprintf("recon_all: write_fdf: Error getting psi"); (void)recon_abort(); ABORT; } ior=(imageno-1)%(fI->nphi)+1; error=P_getreal(PROCESSED,"phi",&phi,ior); if (error) { Werrprintf("recon_all: write_fdf: Error getting phi"); (void)recon_abort(); ABORT; } ior=(imageno-1)%(fI->ntheta)+1; error=P_getreal(PROCESSED,"theta",&theta,ior); if (error) { Werrprintf("recon_all: write_fdf: Error getting theta"); (void)recon_abort(); ABORT; } cospsi=cos(DEG_TO_RAD*psi); sinpsi=sin(DEG_TO_RAD*psi); cosphi=cos(DEG_TO_RAD*phi); sinphi=sin(DEG_TO_RAD*phi); costheta=cos(DEG_TO_RAD*theta); sintheta=sin(DEG_TO_RAD*theta); or0=-1*cosphi*cospsi - sinphi*costheta*sinpsi; or1=-1*cosphi*sinpsi + sinphi*costheta*cospsi; or2=-1*sinphi*sintheta; or3=-1*sinphi*cospsi + cosphi*costheta*sinpsi; or4=-1*sinphi*sinpsi - cosphi*costheta*cospsi; or5=cosphi*sintheta; or6=-1*sintheta*sinpsi; or7=sintheta*cospsi; or8=costheta; /* get te if necessary */ te=fI->te; te*=fI->echo; if (fI->echoes > 1) { error=P_getVarInfo(PROCESSED,"TE",&info); if (!error) { if (info.size > 1) { error=P_getreal(PROCESSED,"TE",&te,(fI->echo -1)%info.size + 1); if (error) { Werrprintf("recon_all: write_fdf: Error getting particular TE"); (void)recon_abort(); ABORT; } } } } (void)sprintf(hdr, "#!/usr/local/fdf/startup\n"); (void)strcat(hdr, "float rank = 2;\n"); (void)strcat(hdr, "char *spatial_rank = \"2dfov\";\n"); (void)strcat(hdr, "char *storage = \"float\";\n"); (void)strcat(hdr, "float bits = 32;\n"); if(rInfo.phsflag) (void)strcat(hdr, "char *type = \"phase\";\n"); else (void)strcat(hdr, "char *type = \"absval\";\n"); (void)sprintf(str, "float matrix[] = {%d, %d};\n", fI->npe, fI->nro); (void)strcat(hdr, str); (void)strcat(hdr, "char *abscissa[] = {\"cm\", \"cm\"};\n"); (void)strcat(hdr, "char *ordinate[] = { \"intensity\" };\n"); (void)sprintf(str, "float span[] = {%.6f, %.6f};\n", fI->fovpe, fI->fovro); (void)strcat(hdr, str); (void)sprintf(str, "float origin[] = {%.6f,%.6f};\n", orppe, orpro); (void)strcat(hdr, str); if (nmice) { /* (void)sprintf(str,"int coils = %d;\n",rInfo.nchannels); */ (void)sprintf(str, "int coils = %d;\n", nmice); (void)strcat(hdr, str); (void)sprintf(str, "int coil = %d;\n", channel); (void)strcat(hdr, str); (void)sprintf(str, "float morigin = {%.6f,%.6f,%.6f};\n", orpro, orppe, orpss); /* (void)sprintf(str,"float morigin = {%.6f,%.6f,%.6f};\n",orppe,orpro,orpss); */ (void)strcat(hdr, str); rppe *= (-1); } (void)sprintf(str, "char *nucleus[] = {\"%s\",\"%s\"};\n",fI->tn,fI->dn); (void)strcat(hdr, str); (void)sprintf(str, "float nucfreq[] = {%.6f,%.6f};\n", fI->sfrq, fI->dfrq); (void)strcat(hdr, str); (void)sprintf(str, "float location[] = {%.6f,%.6f,%.6f};\n", rppe, rpro, rpss); (void)strcat(hdr, str); (void)sprintf(str, "float roi[] = {%.6f,%.6f,%.6f};\n", fI->fovpe, fI->fovro, fI->thickness); (void)strcat(hdr, str); (void)sprintf(str, "float gap = %.6f;\n", fI->gap); (void)strcat(hdr, str); (void)sprintf(str, "char *file = \"%s\";\n", fI->fidname); (void)strcat(hdr, str); /* (void)sprintf(str,"int slice_no = %d;\n",slice_acq); */ (void)sprintf(str, "int slice_no = %d;\n", slice_pos); (void)strcat(hdr, str); (void)sprintf(str, "int slices = %d;\n", fI->slices); (void)strcat(hdr, str); (void)sprintf(str, "int echo_no = %d;\n", fI->echo); (void)strcat(hdr, str); (void)sprintf(str, "int echoes = %d;\n", fI->echoes); (void)strcat(hdr, str); if (!arraycheck("te", arstr)) { (void)sprintf(str, "float TE = %.3f;\n", te); (void)strcat(hdr, str); (void)sprintf(str, "float te = %.6f;\n", MSEC_TO_SEC*te); (void)strcat(hdr, str); } if (!arraycheck("tr", arstr)) { (void)sprintf(str, "float TR = %.3f;\n", fI->tr); (void)strcat(hdr, str); (void)sprintf(str, "float tr = %.6f;\n", MSEC_TO_SEC*fI->tr); (void)strcat(hdr, str); } (void)sprintf(str, "int ro_size = %d;\n", fI->ro_size); (void)strcat(hdr, str); (void)sprintf(str, "int pe_size = %d;\n", fI->pe_size); (void)strcat(hdr, str); (void)sprintf(str, "char *sequence = \"%s\";\n", fI->seqname); (void)strcat(hdr, str); (void)sprintf(str, "char *studyid = \"%s\";\n", fI->studyid); (void)strcat(hdr, str); (void)sprintf(str, "char *position1 = \"%s\";\n", fI->position1); (void)strcat(hdr, str); (void)sprintf(str, "char *position2 = \"%s\";\n", fI->position2); (void)strcat(hdr, str); if (!arraycheck("ti", arstr)) { (void)sprintf(str, "float TI = %.3f;\n", fI->ti); (void)strcat(hdr, str); (void)sprintf(str, "float ti = %.6f;\n", MSEC_TO_SEC*fI->ti); (void)strcat(hdr, str); } /* (void)sprintf(str,"int array_index = %d;\n",fI->array_index); */ (void)sprintf(str, "int array_index = %d;\n", imageno); (void)strcat(hdr, str); (void)sprintf(str, "float array_dim = %.4f;\n", fI->image); (void)strcat(hdr, str); /* (void)sprintf(str,"float image = %.4f;\n",fI->image); */ (void)sprintf(str, "float image = 1.0;\n"); (void)strcat(hdr, str); /* id = (slice_pos-1)*fI->image*fI->echoes + (imageno-1)*fI->echoes + (fI->echo-1); */ id = (imageno-1)*fI->slices*fI->echoes+ (slice_pos-1)*fI->echoes+ (fI->echo-1); //if(rInfo.svinfo.look_locker) // id=(slice_pos-1)*fI->image+ (imageno-1); (void)sprintf(str, "int display_order = %d;\n", id); (void)strcat(hdr, str); #ifdef LINUX (void)sprintf(str, "int bigendian = 0;\n"); (void)strcat(hdr, str); #endif (void)sprintf(str, "float imagescale = %.9f;\n",rInfo.image_scale); (void)strcat(hdr, str); if (!arraycheck("psi", arstr)) { (void)sprintf(str, "float psi = %.4f;\n", psi); (void)strcat(hdr, str); } if (!arraycheck("phi", arstr)) { (void)sprintf(str, "float phi = %.4f;\n", phi); (void)strcat(hdr, str); } if (!arraycheck("theta", arstr)) { (void)sprintf(str, "float theta = %.4f;\n", theta); (void)strcat(hdr, str); } /* check for sviblist stuff */ error=P_getstring(PROCESSED,"sviblist", sviblist, 1, MAXSTR); if (!error) { ptr=strtok(sviblist, ","); while (ptr != NULL) { strcpy(svbname, ptr); /* strip off any blanks */ ptr2=ptr; while ((*ptr2==' ')&&(ptr2<(ptr+strlen(svbname)))) ptr2++; strcpy(svbname, ptr2); if (!strstr(svbname, "TE")) /* TE handled separately */ { error=P_getVarInfo(PROCESSED,svbname,&info); if (error) { (void)sprintf(str, "recon_all: write_fdf: Error getting %s", svbname); /* Werrprintf("recon_all: write_fdf: Error getting something"); */ Winfoprintf(str); } else { nimage=svib_image(svbname, imageno); if (nimage<0) { Werrprintf("recon_all: write_fdf: Problem with sviblist"); (void)recon_abort(); ABORT; } nimage=(nimage-1)%info.size+1; switch (info.basicType) { case T_REAL: { error=P_getreal(PROCESSED,svbname,&dtemp,nimage); if (error) { Werrprintf("recon_all: write_fdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } (void)sprintf(str, "float %s = %.6f;\n", svbname, dtemp); (void)strcat(hdr, str); } break; case T_STRING: { error =P_getstring(PROCESSED,svbname,ctemp,nimage, SHORTSTR); if (error) { Werrprintf("recon_all: write_fdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } (void)sprintf(str, "char *%s = \"%s\";\n", svbname, ctemp); (void)strcat(hdr, str); } break; default: { Werrprintf("recon_all: write_fdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } break; } /* end switch */ } } ptr=strtok(NULL,","); } } (void)sprintf(str, "float orientation[] = {%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f};\n", or0, or1, or2, or3, or4, or5, or6, or7, or8); (void)strcat(hdr, str); (void)strcat(hdr, arstr); /* add array based parameters */ (void)strcat(hdr, "int checksum = 1291708713;\n"); (void)strcat(hdr, "\f\n"); align = sizeof(float); hdrlen=strlen(hdr); hdrlen++; /* include NULL terminator */ pad_cnt = hdrlen % align; pad_cnt = (align - pad_cnt) % align; pad_cnt = pad_cnt + align -1; /* Put in padding */ (void)sprintf(str, " "); for (i=0; i<pad_cnt-1; i++) (void)strcat(str, " "); (void)strcat(str, "\n"); (void)strcat(hdr, str); hdrlen+=strlen(str); *(hdr + hdrlen) = '\0'; /* open the fdf file */ filesize=hdrlen*sizeof(char)+ fI->nro*fI->npe*sizeof(float); if (!access(filename, W_OK)) { fdfMd=mOpen(filename, filesize, O_RDWR | O_CREAT); (void)mAdvise(fdfMd, MF_SEQUENTIAL); } else { /* create the output directory and try again */ if (access(dirname, F_OK)) { (void)sprintf(str, "mkdir %s \n", dirname); ierr=system(str); } fdfMd=mOpen(filename, filesize, O_RDWR | O_CREAT); (void)mAdvise(fdfMd, MF_SEQUENTIAL); if (!fdfMd) { Werrprintf("recon_all: write_fdf: Error opening image file"); (void)recon_abort(); ABORT; } } if ((*image_orderP==0)&&!channel) { if (svprocpar(TRUE, dirname)) { Werrprintf("recon_all: write_fdf: Error creating procpar"); (void)recon_abort(); ABORT; } } if (!channel) *image_orderP=*image_orderP + 1; (void)memcpy(fdfMd->offsetAddr, hdr, hdrlen*sizeof(char)); fdfMd->newByteLen += hdrlen*sizeof(char); fdfMd->offsetAddr += hdrlen*sizeof(char); (void)memcpy(fdfMd->offsetAddr, datap, fI->nro*fI->npe*sizeof(float)); fdfMd->newByteLen += fI->nro*fI->npe*sizeof(float); (void)mClose(fdfMd); #ifdef VNMRJ if (display) { (void)aipDisplayFile(filename, -1); //aipAutoScale(); } #endif return (0); } /******************************************************************************/ /******************************************************************************/ int write_3Dfdf(datap, fI, arstr, channel) fdfInfo *fI;float *datap;char *arstr;int channel; { MFILE_ID fdfMd; vInfo info; char *ptr; char *ptr2; char sviblist[MAXSTR]; char filestr[MAXSTR]; char filename[MAXPATHL]; char dirname[MAXPATHL]; char svbname[SHORTSTR]; char ctemp[SHORTSTR]; char str[100]; char hdr[2000]; int ierr; int i, error; int pad_cnt, align; int hdrlen; int filesize; int ior; int slice_acq, slice_pos; int nimage; int npts2d; int npts3d; int reallybig=FALSE; int id; int nch, ich; int iro, iview, islice; double rppe, rpro, rpss; double orro, orpe, orpe2; double psi, phi, theta; double cospsi, cosphi, costheta; double sinpsi, sinphi, sintheta; double or0, or1, or2, or3, or4, or5, or6, or7, or8; double te; double dtemp; float *aptr, *bptr; float a, b; float *fp2; float *mag2D; (void)strcpy(dirname, curexpdir); (void)strcat(dirname, "/datadir3d/data"); (void)strcpy(filename, dirname); switch (fI->datatype) { case RAW_MAG: (void)strcat(filename, "/rawmag"); break; case RAW_PHS: (void)strcat(filename, "/rawphs"); break; case PHS_IMG: (void)strcat(filename, "/imgphs"); break; case MAGNITUDE: default: (void)strcat(filename, "/img"); break; } if ((rInfo.smash)||(rInfo.sense)) (void)sprintf(str, "_slab%03dimage%03decho%03dchan%02d.fdf", fI->slice, (int)(fI->image), fI->echo, (channel+1)); else (void)sprintf(str, "_slab%03dimage%03decho%03d.fdf", fI->slice, (int)(fI->image), fI->echo); (void)strcat(filename, str); slice_acq=0; slice_pos=0; /* get some slice or image specific information */ error=P_getreal(PROCESSED,"pss",&rpss,1); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting slab offset"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"ppe",&rppe,1); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting phase encode offset"); (void)recon_abort(); ABORT; } /* account for pe direction shift in recon */ rppe = (fI->fovpe)*(rInfo.pe_frq/180.); rppe *= -1.0; /* make compatible with ft3d output */ error=P_getreal(PROCESSED,"pro",&rpro,1); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting readout offset"); (void)recon_abort(); ABORT; } rpro *= -1.0; /* make compatible with planning */ if (nmice) { if (pe_frqP) rppe += (fI->fovpe)*(*(pe_frqP+channel-1)/180.); if (ro_frqP) rpro += (fI->fovro)*(*(ro_frqP+channel-1)/180.); } /* get orientation for this image */ ior=1; error=P_getreal(PROCESSED,"psi",&psi,ior); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting psi"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"phi",&phi,ior); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting phi"); (void)recon_abort(); ABORT; } error=P_getreal(PROCESSED,"theta",&theta,ior); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting theta"); (void)recon_abort(); ABORT; } cospsi=cos(DEG_TO_RAD*psi); sinpsi=sin(DEG_TO_RAD*psi); cosphi=cos(DEG_TO_RAD*phi); sinphi=sin(DEG_TO_RAD*phi); costheta=cos(DEG_TO_RAD*theta); sintheta=sin(DEG_TO_RAD*theta); /* or0=-1*cosphi*cospsi - sinphi*costheta*sinpsi; or1=-1*cosphi*sinpsi + sinphi*costheta*cospsi; or2=-1*sinphi*sintheta; or3=-1*sinphi*cospsi + cosphi*costheta*sinpsi; or4=-1*sinphi*sinpsi - cosphi*costheta*cospsi; or5=cosphi*sintheta; or6=-1*sintheta*sinpsi; or7=sintheta*cospsi; or8=costheta; */ or0=-1*sinphi*sinpsi - cosphi*costheta*cospsi; or1=sinphi*cospsi - cosphi*costheta*sinpsi; or2=sintheta*cosphi; or3=cosphi*sinpsi - sinphi*costheta*cospsi; or4=-1*cosphi*cospsi - sinphi*costheta*sinpsi; or5=sintheta*sinphi; or6=cospsi*sintheta; or7=sinpsi*sintheta; or8=costheta; /* get te if necessary */ te=fI->te; te*=fI->echo; if (fI->echoes > 1) { error=P_getVarInfo(PROCESSED,"TE",&info); if (!error) { if (info.size > 1) { error=P_getreal(PROCESSED,"TE",&te,(fI->echo -1)%info.size + 1); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting particular TE"); (void)recon_abort(); ABORT; } } } } error=P_getstring(CURRENT, "file", filestr, 1, MAXSTR); if (error) { Werrprintf("recon_all: write_3Dfdf Error getting file"); (void)recon_abort(); ABORT; } orro=rpro; orpe=rppe; orpe2=rpss; if (!nmice) { orro -= .5*(fI->fovro); orpe -= .5*(fI->fovpe); orpe2 -= .5*(fI->thickness); } (void)sprintf(hdr, "#!/usr/local/fdf/startup\n"); (void)strcat(hdr, "float rank = 3;\n"); (void)strcat(hdr, "char *spatial_rank = \"3dfov\";\n"); (void)strcat(hdr, "char *storage = \"float\";\n"); (void)strcat(hdr, "float bits = 32;\n"); if(rInfo.phsflag) (void)strcat(hdr, "char *type = \"phase\";\n"); else (void)strcat(hdr, "char *type = \"absval\";\n"); (void)sprintf(str, "float matrix[] = {%d, %d, %d};\n", fI->nro, fI->npe, fI->slices); (void)strcat(hdr, str); (void)strcat(hdr, "char *abscissa[] = {\"cm\", \"cm\", \"cm\"};\n"); (void)strcat(hdr, "char *ordinate[] = { \"intensity\" };\n"); (void)sprintf(str, "float span[] = {%.6f, %.6f, %.6f};\n", fI->fovro, fI->fovpe, fI->thickness); (void)strcat(hdr, str); (void)sprintf(str, "float origin[] = {%.6f,%.6f,%.6f};\n", orro, orpe, orpe2); (void)strcat(hdr, str); (void)sprintf(str, "char *nucleus[] = {\"%s\",\"%s\"};\n",fI->tn,fI->dn); (void)strcat(hdr, str); (void)sprintf(str, "float nucfreq[] = {%.6f,%.6f};\n", fI->sfrq, fI->dfrq); (void)strcat(hdr, str); (void)sprintf(str, "float location[] = {%.6f,%.6f,%.6f};\n", rpro, rppe, rpss); (void)strcat(hdr, str); (void)sprintf(str, "float roi[] = {%.6f,%.6f,%.6f};\n", fI->fovro, fI->fovpe, fI->thickness); (void)strcat(hdr, str); (void)sprintf( str, "float orientation[] = {%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f};\n", or0, or1, or2, or3, or4, or5, or6, or7, or8); (void)strcat(hdr, str); (void)sprintf(str, "char *array_name = \"%s\"; \n", "none"); (void)strcat(hdr, str); (void)sprintf(str, "char *file = \"%s\";\n", fI->fidname); (void)strcat(hdr, str); /* THIS STUFF IS NOw APPRECIATED!! */ // (void)sprintf(str,"int slice_no = %d;\n",slice_pos); // (void)sprintf(str,"int slice_no = 1;\n"); // (void)strcat(hdr,str); // (void)sprintf(str,"int slices = %d;\n",fI->slices); // (void)strcat(hdr,str); (void)sprintf(str,"int slab_no = 1;\n"); (void)strcat(hdr,str); (void)sprintf(str,"int slabs = %d;\n",rInfo.svinfo.slabs); (void)strcat(hdr,str); (void)sprintf(str,"int echo_no = %d;\n",fI->echo); (void)strcat(hdr,str); (void)sprintf(str,"int echoes = %d;\n",fI->echoes); (void)strcat(hdr,str); if(!arraycheck("te",arstr)) { (void)sprintf(str,"float TE = %.3f;\n",te); (void)strcat(hdr,str); (void)sprintf(str,"float te = %.6f;\n",MSEC_TO_SEC*te); (void)strcat(hdr,str); } if(!arraycheck("tr",arstr)) { (void)sprintf(str,"float TR = %.3f;\n",fI->tr); (void)strcat(hdr,str); (void)sprintf(str,"float tr = %.6f;\n",MSEC_TO_SEC*fI->tr); (void)strcat(hdr,str); } (void)sprintf(str,"int ro_size = %d;\n",fI->ro_size); (void)strcat(hdr,str); (void)sprintf(str,"int pe_size = %d;\n",fI->pe_size); (void)strcat(hdr,str); (void)sprintf(str,"char *sequence = \"%s\";\n",fI->seqname); (void)strcat(hdr,str); (void)sprintf(str,"char *studyid = \"%s\";\n",fI->studyid); (void)strcat(hdr,str); (void)sprintf(str,"char *file = \"%s\";\n",filestr); (void)strcat(hdr,str); (void)sprintf(str,"char *position1 = \"%s\";\n",fI->position1); (void)strcat(hdr,str); (void)sprintf(str,"char *position2 = \"%s\";\n",fI->position2); (void)strcat(hdr,str); if(!arraycheck("ti",arstr)) { (void)sprintf(str,"float TI = %.3f;\n",fI->ti); (void)strcat(hdr,str); (void)sprintf(str,"float ti = %.6f;\n",MSEC_TO_SEC*fI->ti); (void)strcat(hdr,str); } // (void)sprintf(str,"int array_index = 1;\n"); // (void)strcat(hdr,str); (void)sprintf(str,"int array_index = %d;\n",(int)(fI->image)); (void)strcat(hdr,str); (void)sprintf(str,"float image = 1.0;\n"); (void)strcat(hdr,str); id=1; (void)sprintf(str,"int display_order = %d;\n",id); (void)strcat(hdr,str); #ifdef LINUX (void)sprintf(str,"int bigendian = 0;\n"); (void)strcat(hdr,str); #endif (void)sprintf(str, "float imagescale = %.9f;\n",rInfo.image_scale); (void)strcat(hdr, str); if (!arraycheck("psi", arstr)) { (void)sprintf(str, "float psi = %.4f;\n", psi); (void)strcat(hdr, str); } if (!arraycheck("phi", arstr)) { (void)sprintf(str, "float phi = %.4f;\n", phi); (void)strcat(hdr, str); } if (!arraycheck("theta", arstr)) { (void)sprintf(str, "float theta = %.4f;\n", theta); (void)strcat(hdr, str); } /* check for sviblist stuff */ error=P_getstring(PROCESSED, "sviblist", sviblist, 1, MAXSTR); if (!error) { ptr=strtok(sviblist, ","); while (ptr != NULL) { strcpy(svbname, ptr); ptr2=ptr; while ((*ptr2==' ')&&(ptr2<(ptr+strlen(svbname)))) ptr2++; strcpy(svbname, ptr2); if (!strstr(svbname, "TE")) { error=P_getVarInfo(PROCESSED, svbname, &info); if (error) { (void)sprintf(str, "recon_all: write_3Dfdf: Error getting %s", svbname); Winfoprintf(str); } else { nimage=svib_image(svbname, 0); if (nimage<0) { (void)recon_abort(); ABORT; } // nimage=(nimage-1)%info.size+1; nimage=(nimage)%info.size+1; switch (info.basicType) { case T_REAL: { error=P_getreal(PROCESSED, svbname, &dtemp, nimage); if (error) { sprintf(str,"recon_all: write_3Dfdf: Error getting sviblist variable %s for nimage %d",svbname,nimage); Werrprintf(str); // Werrprintf("recon_all: write_3Dfdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } (void)sprintf(str, "float %s = %.6f;\n", svbname, dtemp); (void)strcat(hdr, str); } break; case T_STRING: { error=P_getstring(PROCESSED, svbname, ctemp, nimage, SHORTSTR); if (error) { Werrprintf("recon_all: write_3Dfdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } (void)sprintf(str, "char *%s = %s;\n", svbname, ctemp); (void)strcat(hdr, str); } break; default: { Werrprintf("recon_all: write_3Dfdf: Error getting sviblist variable"); (void)recon_abort(); ABORT; } break; } } } ptr=strtok(NULL, ","); } } (void)strcat(hdr, arstr); (void)strcat(hdr, "int checksum = 0;\n"); (void)strcat(hdr, "\f\n"); align = sizeof(float); hdrlen=strlen(hdr); hdrlen++; /* include NULL terminator */ pad_cnt = hdrlen % align; pad_cnt = (align - pad_cnt) % align; /* Put in padding */ for (i=0; i<pad_cnt; i++) { (void)strcat(hdr, "\n"); hdrlen++; } *(hdr + hdrlen) = '\0'; /* open the fdf file */ filesize=hdrlen*sizeof(char)+ fI->nro*fI->npe*fI->slices*sizeof(float); if (!access(filename, W_OK)) { fdfMd=mOpen(filename,filesize,O_RDWR | O_CREAT); (void)mAdvise(fdfMd, MF_SEQUENTIAL); // fptr=fopen(filename, "w"); } else { /* create the output directory and try again */ if (access(dirname, F_OK)) { (void)strcpy(dirname, curexpdir); (void)strcat(dirname, "/datadir3d"); (void)sprintf(str, "mkdir %s \n", dirname); ierr=system(str); (void)strcpy(dirname, curexpdir); (void)strcat(dirname, "/datadir3d/data"); (void)sprintf(str, "mkdir %s \n", dirname); ierr=system(str); } fdfMd=mOpen(filename,filesize,O_RDWR | O_CREAT); (void)mAdvise(fdfMd, MF_SEQUENTIAL); if (!fdfMd) { Werrprintf("recon_all: write_3Dfdf: Error opening image file"); (void)recon_abort(); ABORT; } } (void)memcpy(fdfMd->offsetAddr, hdr, hdrlen*sizeof(char)); fdfMd->newByteLen += hdrlen*sizeof(char); fdfMd->offsetAddr += hdrlen*sizeof(char); npts2d=(fI->nro)*(fI->npe); npts3d=npts2d*(fI->slices); nch=(rInfo.sense || rInfo.smash) ? 1: rInfo.nchannels; if (npts3d >= BIG3D) reallybig=TRUE; reallybig=FALSE; if ((fI->datatype == MAGNITUDE)||(fI->datatype == PHS_IMG)) { mag2D=(float *)malloc(npts2d*sizeof(float)); /* this will combine channels if necessary */ for (islice=0; islice<fI->slices; islice++) { if (reallybig) { (void)sprintf(str, "writing slice %d \n", islice); Winfoprintf(str); } (void)memset(mag2D, 0, npts2d*sizeof(*mag2D)); for (ich=0; ich<nch; ich++) { fp2=mag2D; aptr=datap + ich*2*npts3d + islice*2*npts2d; bptr=aptr+1; for (iview=0; iview<fI->npe; iview++) { for (iro=0; iro<fI->nro; iro++) { a=*aptr; b=*bptr; aptr+=2; bptr+=2; if(fI->datatype == MAGNITUDE) *fp2++ += (float)sqrt((double)(a*a+b*b)); else if(fI->datatype == PHS_IMG) *fp2++ += (float)atan2(b,a); } } } (void)memcpy(fdfMd->offsetAddr, mag2D, npts2d*sizeof(float)); fdfMd->newByteLen += npts2d*sizeof(float); fdfMd->offsetAddr += npts2d*sizeof(float); } (void)free(mag2D); } else { /* just dump the data */ (void)memcpy(fdfMd->offsetAddr, datap, npts3d*sizeof(float)); fdfMd->newByteLen += npts3d*sizeof(float); fdfMd->offsetAddr += npts3d*sizeof(float); } (void)mClose(fdfMd); if (svprocpar(TRUE, dirname)) { Werrprintf("recon_all: write_3Dfdf: Error creating procpar"); (void)recon_abort(); ABORT; } return (0); } /*****************************************************************/ int psscompare(p1, p2) const void *p1;const void *p2; { int i= *((int *)p1); int j= *((int *)p2); i=i-1; j=j-1; if (pss[i]>pss[j]) return (1); else if (pss[i]<pss[j]) return (-1); else return (0); } /*****************************************************************/ int pcompare(p1, p2) const void *p1;const void *p2; { float f1= *((float *)p1); float f2= *((float *)p2); if (f1>f2) return (1); else if (f1<f2) return (-1); else return (0); } /*****************************************************************/ int upsscompare(p1, p2) const void *p1;const void *p2; { int i= *((int *)p1); int j= *((int *)p2); i=i-1; j=j-1; if (upss[i]>upss[j]) return (1); else if (upss[i]<upss[j]) return (-1); else return (0); } /******************************************************************************/ /* arraycheck */ /******************************************************************************/ /* returns TRUE if param is a member of the arrayed elements */ int arraycheck(char *param, char *arraystr) { int match; char str[MAXSTR]; match=FALSE; (void)sprintf(str, " %s =", param); if (strstr(arraystr, str)) match=TRUE; return (match); } /******************************************************************************/ /* arrayparse */ /******************************************************************************/ /* returns names and sizes from array string*/ int arrayparse(char *arraystring, int *nparams, arrayElement **arrayelsPP, int phasesize, int p2size) { arrayElement *ap; char *ptr; char arraystr[MAXSTR]; char aname[MAXSTR]; int np=0; int i, ipar, denom; vInfo info; (void)strcpy(arraystr, arraystring); /* count the array elements */ ptr=strtok(arraystr, ","); while (ptr != NULL) { /* is this a jointly arrayed thing? */ if (strstr(ptr, "(")) { while (strstr(ptr, ")")==NULL) /* move to end of jointly arrayed list */ { ptr=strtok(NULL,","); } } np++; ptr=strtok(NULL,","); } (void)strcpy(arraystr, arraystring); /* restore this */ ap = (arrayElement *)recon_allocate(np*sizeof(arrayElement), "recon_all"); /* find info about each array element */ ptr=strtok(arraystr, ","); ipar=0; while (ptr != NULL) { /* is this a jointly arrayed thing? */ if (strstr(ptr, "(")) { i=0; ptr++; /* move past the ( */ while (strstr(ptr, ")")==NULL) /* move to end of jointly arrayed list */ { strcpy(ap[ipar].names[i], ptr); i++; ptr=strtok(NULL,","); } *(ptr+strlen(ptr)-1)='\0'; /* overwrite the ) */ strcpy(ap[ipar].names[i], ptr); i++; strcpy(aname, ptr); (void)P_getVarInfo(PROCESSED,aname,&info); ap[ipar].size=info.size; ap[ipar].nparams=i; } else { ap[ipar].nparams=1; strcpy(ap[ipar].names[0], ptr); strcpy(aname, ptr); (void)P_getVarInfo(PROCESSED,aname,&info); ap[ipar].size=info.size; } ptr=strtok(NULL,","); ipar++; } /* compute denominator for block to element conversion */ denom=phasesize; /* account for phase loop being outermost if not compressed */ denom=1; for (ipar=np-1; ipar>=0; ipar--) { ap[ipar].denom=denom; if(!strcmp(ap[ipar].names[0], "d2")) denom *= phasesize; else if(!strcmp(ap[ipar].names[0], "d3")) denom *= p2size; else denom *= ap[ipar].size; } denom=1; for (ipar=np-1; ipar>=0; ipar--) { ap[ipar].idenom=denom; if(!strcmp(ap[ipar].names[0], "d2")) denom *= 1; else if(!strcmp(ap[ipar].names[0], "d3")) denom *= 1; else if(!strcmp(ap[ipar].names[0], "pss")) denom *= 1; else denom *= ap[ipar].size; } *nparams=np; *arrayelsPP=ap; return (0); } /******************************************************************************/ /* arrayfdf */ /******************************************************************************/ int arrayfdf(int block, int np, arrayElement *arrayels, char *fdfstring) { char str[MAXSTR]; char name[MAXSTR]; int ip, ij; int error; int image; int arrayno; vInfo info; double dtemp; char ctemp[MAXSTR]; /* construct string for fdf header */ (void)strcpy(fdfstring, ""); for (ip=0; ip<np; ip++) { for (ij=0; ij<arrayels[ip].nparams; ij++) { image=FALSE; strcpy(name, arrayels[ip].names[ij]); if (strstr(name, "image")) image=TRUE; arrayno=block/(arrayels[ip].idenom); arrayno=arrayno%(arrayels[ip].size); arrayno=arrayno+1; error=P_getVarInfo(PROCESSED,name,&info); if (strstr(name, "d2")) break; if (strstr(name, "d3")) break; if (strstr(name, "pss")) break; if (error) { Werrprintf("recon_all: arrayfdf: Error getting arrayed parameter info"); (void)recon_abort(); ABORT; } switch (info.basicType) { case T_REAL: { error=P_getreal(PROCESSED,name,&dtemp,arrayno); if (error) { Werrprintf("recon_all: arrayfdf: Error getting arrayed variable"); (void)recon_abort(); ABORT; } if (image&&(dtemp<1.0)) { (void)sprintf(fdfstring, "\n"); return (0); /* nothing to do */ } (void)sprintf(str, "float %s = %.6f;\n", name, dtemp); (void)strcat(fdfstring, str); } break; case T_STRING: { error=P_getstring(PROCESSED,name,ctemp,arrayno, SHORTSTR); if (error) { Werrprintf("recon_all: arrayfdf: Error getting arrayed variable"); (void)recon_abort(); ABORT; } (void)sprintf(str, "char *%s = %s;\n", name, ctemp); (void)strcat(fdfstring, str); } break; default: { Werrprintf("recon_all: arrayfdf: Error getting arrayed variable"); (void)recon_abort(); ABORT; } break; } /* end switch */ } } return (0); } /*******************************************************/ /* fits phase over region of reasonable amplitude */ /* input is complex data, output is fitted phase */ /* inphs is input phase data, unwrapped */ /* fit is linear only */ /********************************************************/ int smartphsfit(float *input, double *inphs, int npts, double *outphs) { int i; int width; int nfit; int nogood=FALSE; int maxloc; int startpt, endpt; float *dp1, *dp2; double a, b; double maxfactor; double sx=0.0; double sy=0.0; double ssx=0.0; double sxy=0.0; double x, y; double b0, b1; double maxamp; double *amp; amp=(double *)recon_allocate(npts*sizeof(double), "smartphsfit"); width=PC_FIT_WIDTH*npts/100; nfit=2*width; /* find max amplitude and its location */ dp1=input; dp2=dp1+1; maxloc=0; a=*dp1; b=*dp2; maxamp=sqrt(a*a+b*b); for (i=0; i<npts; i++) { a=*dp1; b=*dp2; *(amp+i)=sqrt(a*a+b*b); if (*(amp+i) > maxamp) { maxamp=*(amp+i); maxloc=i; } dp1+=2; dp2=dp1+1; } /* find a region of good amplitude */ maxfactor=.8; startpt=maxloc; startpt=npts/2; while ((*(amp+startpt)>maxfactor*maxamp) && (startpt>=0)) startpt--; endpt=maxloc; endpt=npts/2; while ((*(amp+endpt)>maxfactor*maxamp) && (endpt<npts)) endpt++; if (endpt-startpt<10) { /* startpt=npts/2-5; endpt=npts/2+5; */ nogood=TRUE; } /* fit the phase from startpt to endpt */ nfit=0; for (i=startpt; i<endpt; i++) { x=(double)i; y=inphs[i]; sx += x; sy += y; ssx += x*x; sxy += x*y; nfit++; } b1=(nfit*sxy-sx*sy)/(nfit*ssx-sx*sx); b0=(sy-b1*sx)/nfit; if (nogood) { b0=0; b1=0; } /* generate evaluation */ for (i=0; i<npts; i++) outphs[i]=b0+b1*i; return (0); } /********************************************************************************************************/ /* threeD_ft is also responsible for reversing magnitude data in read & phase directions (new fft) */ /********************************************************************************************************/ void threeD_ft(xkydata,nx,ny,nz,win,win2, phase_rev, zeropad_ro, zeropad_ph, imouse, phsdata,pe_frq, frq_pe2) float *xkydata; float *win; float *win2; int nx,ny,nz,phase_rev,zeropad_ro,zeropad_ph; int imouse; float *phsdata; double *pe_frq; double *frq_pe2; { float a,b; float *fptr,*pt1,*pt2; int ix,iy,iz; int np; int pwr,fnt; int reallybig=FALSE; int halfR=FALSE; float *nrptr; float *pptr; float templine[2*MAXPE]; float *tempdat; double frq; char str[100]; // fptr=absdata; pptr=phsdata; np=nx*ny; if(np*nz>=BIG3D) reallybig=TRUE; reallybig=FALSE; if(zeropad_ro > HALFF*nx) { halfR=TRUE; tempdat=(float *)allocateWithId(2*np*sizeof(float),"threeD_ft"); } /* do slice direction ft */ pwr = 4; fnt = 32; while (fnt < 2*nz) { fnt *= 2; pwr++; } for(iy=0;iy<ny;iy++) { if (reallybig) { sprintf(str, "slice ft for y=%d\n", iy); Winfoprintf(str); } for (ix = 0; ix < nx; ix++) { if (interuption) { (void)P_setstring(CURRENT, "wnt", "", 0); (void)P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: aborting by request"); //(void) recon_abort(); return; } /* get the kz line */ pt1=xkydata+2*ix + 2*nx*iy; pt2=pt1+1; nrptr=templine; for(iz=0;iz<nz;iz++) { *nrptr++=*pt1; *nrptr++=*pt2; pt1+=2*np; pt2=pt1+1; } if(win2) { for(iz=0;iz<nz;iz++) { templine[2*iz]*= *(win2+iz); templine[2*iz+1]*= *(win2+iz); } } /* apply frequency shift */ if(frq_pe2!=NULL) { frq=*(frq_pe2+imouse); (void)rotate_fid(templine, 0.0, frq, 2*nz, COMPLEX); } nrptr=templine; (void)fftshift(nrptr,nz); (void)fft(nrptr, nz,pwr, 0, COMPLEX,COMPLEX,-1.0,1.0,nz); /* write it back */ pt1=xkydata+2*ix + 2*nx*iy; pt2=pt1+1; nrptr=templine; for(iz=0;iz<nz;iz++) { *pt1=*nrptr++; *pt2=*nrptr++; pt1+=2*np; pt2=pt1+1; } } } /* do phase direction ft */ pwr = 4; fnt = 32; while (fnt < 2*ny) { fnt *= 2; pwr++; } for(iz=0;iz<nz;iz++) { if(reallybig){ sprintf(str,"phase ft for z=%d\n",iz); Winfoprintf(str); } for (ix = nx - 1; ix > -1; ix--) { if (interuption) { (void)P_setstring(CURRENT, "wnt", "", 0); (void)P_setstring(PROCESSED, "wnt", "", 0); Werrprintf("recon_all: aborting by request"); //(void) recon_abort(); return; } /* get the ky line */ pt1=xkydata+2*ix; pt1=xkydata+2*ix + 2*np*iz; pt2=pt1+1; nrptr=templine; for(iy=0;iy<ny;iy++) { *nrptr++=*pt1; *nrptr++=*pt2; pt1+=2*nx; pt2=pt1+1; } if(win) { for(iy=0;iy<ny;iy++) { templine[2*iy]*= *(win+iy); templine[2*iy+1]*= *(win+iy); } } #ifdef HALFF /* perform half Fourier data estimation */ if(zeropad_ph > HALFF*ny) (void)halfFourier(templine, (ny-zeropad_ph), ny, POINTWISE); #endif /* apply frequency shift */ if(pe_frq!=NULL) { frq=*(pe_frq+imouse); if(phase_rev) (void)rotate_fid(templine, 0.0, -1*frq, 2*ny, COMPLEX); else (void)rotate_fid(templine, 0.0, frq, 2*ny, COMPLEX); } nrptr = templine; (void) fftshift(nrptr, ny); (void) fft(nrptr, ny, pwr, 0, COMPLEX, COMPLEX, -1.0, 1.0, ny); /* write it back */ pt1=xkydata+2*ix + 2*np*iz; pt2=pt1+1; nrptr=templine; for(iy=0;iy<ny;iy++) { *pt1=*nrptr++; *pt2=*nrptr++; pt1+=2*nx; pt2=pt1+1; } /* write magnitude */ /* NOT!! */ if(!halfR && FALSE) { if(!phase_rev) { nrptr=templine+2*ny-1; for(iy=0;iy<ny;iy++) { a=*nrptr--; b=*nrptr--; *fptr++=(float)sqrt((double)(a*a+b*b)); if(phsdata) *pptr++=(float)atan2(b,a); } } else { nrptr=templine; for(iy=0;iy<ny;iy++) { a=*nrptr++; b=*nrptr++; *fptr++=(float)sqrt((double)(a*a+b*b)); if(phsdata) *pptr++=(float)atan2(b,a); } } } } } #ifdef HALFF if(halfR && FALSE) { /* perform half Fourier in readout */ nrptr=tempdat; for(iy=0;iy<ny;iy++) { (void)halfFourier(nrptr,(nx-zeropad_ro), nx, POINTWISE); pwr = 4; fnt = 32; while (fnt < 2*ny) { fnt *= 2; pwr++; } /* apply frequency shift */ /* if(ro_frq!=NULL) (void)rotate_fid(nrptr, 0.0, ro_frq, 2*nx, COMPLEX); (void)fft(nrptr, nx,pwr, 0, COMPLEX,COMPLEX,-1.0,1.0,nx); */ nrptr+=2*nx; } /* write out magnitude */ if(!phase_rev) { for(ix=nx-1;ix>-1;ix--) { for(iy=ny-1;iy>-1;iy--) { nrptr=tempdat+2*ix+iy*2*nx; a=*nrptr++; b=*nrptr++; *fptr++=(float)sqrt((double)(a*a+b*b)); if(phsdata) *pptr++=(float)atan2(b,a); } } } else { for(ix=nx-1;ix>-1;ix--) { for(iy=0;iy<ny;iy++) { nrptr=tempdat+2*ix+iy*2*nx; a=*nrptr++; b=*nrptr++; *fptr++=(float)sqrt((double)(a*a+b*b)); if(phsdata) *pptr++=(float)atan2(b,a); } } } } #endif (void)releaseAllWithId("threeD_ft"); return; } static int recon_space_check() { struct statvfs freeblocks_buf; double free_kbytes; /* number of free kbytes available */ double req_kbytes; /* kbytes required for images */ char tmpdir[MAXSTR]; double req_bytes; int headerlen = 2048; // a generous estimate of fdf header size int narray; /* For a VnmrS or 400-MR the check is done in PSG * (to cover multiple receivers, etc */ if ( P_getstring(SYSTEMGLOBAL, "Console", tmpdir, 1, MAXPATHL) < 0) { Werrprintf("Cannot find the 'Console' parameter"); return(-1); } if (strcmp(tmpdir,"vnmrs") == 0) return(0); sprintf(tmpdir,"%s/.",curexpdir); statvfs( tmpdir, &freeblocks_buf); free_kbytes = (double) freeblocks_buf.f_bavail; req_bytes = 4 * rInfo.svinfo.ro_size * rInfo.svinfo.pe_size; if(rInfo.svinfo.threeD){ req_bytes *= rInfo.svinfo.pe2_size; req_bytes += headerlen; req_bytes *= rInfo.svinfo.echoes; } else { req_bytes += headerlen; req_bytes *= rInfo.svinfo.echoes; req_bytes *= rInfo.svinfo.slices; } // arrayed elements narray = rInfo.narray; if (!rInfo.svinfo.phase_compressed) narray /= rInfo.picInfo.npe; if (rInfo.svinfo.threeD) { if (!rInfo.svinfo.sliceenc_compressed) narray /= rInfo.svinfo.pe2_size; } else { if (!rInfo.svinfo.slice_compressed) narray /= rInfo.svinfo.slices; } if(narray > 1) req_bytes *= narray; req_kbytes = req_bytes / 1024; if(req_kbytes > free_kbytes) { Werrprintf("recon_all : Insufficient disk space available to save images!!"); return(1); } return(0); }
33.459844
166
0.442219
[ "transform", "3d" ]
30dba9cc1aafc82aa21b6b0b62cb115c8510f574
3,453
h
C
include/eZmaxApi/model/Ezsignfoldersignerassociation_ResponseCompound_User.h
ezmaxinc/eZmax-SDK-cpp-restsdk
3928a9bdad37448d87bbeafa51308927f8338764
[ "MIT" ]
null
null
null
include/eZmaxApi/model/Ezsignfoldersignerassociation_ResponseCompound_User.h
ezmaxinc/eZmax-SDK-cpp-restsdk
3928a9bdad37448d87bbeafa51308927f8338764
[ "MIT" ]
null
null
null
include/eZmaxApi/model/Ezsignfoldersignerassociation_ResponseCompound_User.h
ezmaxinc/eZmax-SDK-cpp-restsdk
3928a9bdad37448d87bbeafa51308927f8338764
[ "MIT" ]
null
null
null
/** * eZmax API Definition * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.6 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * Ezsignfoldersignerassociation_ResponseCompound_User.h * * A Ezsignfoldersignerassociation-&gt;User Object and children to create a complete structure */ #ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_Ezsignfoldersignerassociation_ResponseCompound_User_H_ #define ORG_OPENAPITOOLS_CLIENT_MODEL_Ezsignfoldersignerassociation_ResponseCompound_User_H_ #include "eZmaxApi/ModelBase.h" #include <cpprest/details/basic_types.h> namespace org { namespace openapitools { namespace client { namespace model { /// <summary> /// A Ezsignfoldersignerassociation-&gt;User Object and children to create a complete structure /// </summary> class Ezsignfoldersignerassociation_ResponseCompound_User : public ModelBase { public: Ezsignfoldersignerassociation_ResponseCompound_User(); virtual ~Ezsignfoldersignerassociation_ResponseCompound_User(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; bool fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// Ezsignfoldersignerassociation_ResponseCompound_User members /// <summary> /// The unique ID of the User /// </summary> int32_t getPkiUserID() const; bool pkiUserIDIsSet() const; void unsetPkiUserID(); void setPkiUserID(int32_t value); /// <summary> /// The unique ID of the Language. Valid values: |Value|Description| |-|-| |1|French| |2|English| /// </summary> int32_t getFkiLanguageID() const; bool fkiLanguageIDIsSet() const; void unsetFkiLanguageID(); void setFkiLanguageID(int32_t value); /// <summary> /// The First name of the user /// </summary> utility::string_t getSUserFirstname() const; bool sUserFirstnameIsSet() const; void unsetSUserFirstname(); void setSUserFirstname(const utility::string_t& value); /// <summary> /// The Last name of the user /// </summary> utility::string_t getSUserLastname() const; bool sUserLastnameIsSet() const; void unsetSUserLastname(); void setSUserLastname(const utility::string_t& value); /// <summary> /// The email address. /// </summary> utility::string_t getSEmailAddress() const; bool sEmailAddressIsSet() const; void unsetSEmailAddress(); void setSEmailAddress(const utility::string_t& value); protected: int32_t m_PkiUserID; bool m_PkiUserIDIsSet; int32_t m_FkiLanguageID; bool m_FkiLanguageIDIsSet; utility::string_t m_SUserFirstname; bool m_SUserFirstnameIsSet; utility::string_t m_SUserLastname; bool m_SUserLastnameIsSet; utility::string_t m_SEmailAddress; bool m_SEmailAddressIsSet; }; } } } } #endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_Ezsignfoldersignerassociation_ResponseCompound_User_H_ */
28.073171
119
0.715899
[ "object", "model" ]
30dda85eb25bc5184f6f6d86910f8bb289807c64
5,991
h
C
Ko-Fi Engine/Source/PieShape.h
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-26T23:35:53.000Z
2022-03-04T16:25:18.000Z
Ko-Fi Engine/Source/PieShape.h
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
2
2022-02-23T09:41:09.000Z
2022-03-08T08:46:21.000Z
Ko-Fi Engine/Source/PieShape.h
Chamfer-Studios/Ko-Fi-Engine
cdc7fd9fd8c30803ac2e3fe0ecaf1923bbd7532e
[ "MIT" ]
1
2022-03-03T18:41:32.000Z
2022-03-03T18:41:32.000Z
/////////////////////////////////////////////////////////////////////////////// // CylinderShape.h // ========== // CylinderShape for OpenGL with (base radius, top radius, height, sectors, stacks) // The min number of sectors (slices) is 3 and the min number of stacks are 1. // - base radius: the radius of the cylinder at z = -height/2 // - top radius : the radiusof the cylinder at z = height/2 // - height : the height of the cylinder along z-axis // - sectors : the number of slices of the base and top caps // - stacks : the number of subdivisions along z-axis // // AUTHOR: Song Ho Ahn (song.ahn@gmail.com) // CREATED: 2018-03-27 // UPDATED: 2019-12-02 /////////////////////////////////////////////////////////////////////////////// #ifndef GEOMETRY_CYLINDER_H #define GEOMETRY_CYLINDER_H #include <vector> #include "MathGeoLib/Math/float4x4.h" class PieShape { public: // ctor/dtor PieShape(float baseRadius = 1.0f, float topRadius = 1.0f, float height = 1.0f, int sectorCount = 36, int stackCount = 1, bool smooth = true); ~PieShape() {} // getters/setters float getBaseRadius() const { return baseRadius; } float getTopRadius() const { return topRadius; } float getHeight() const { return height; } int getSectorCount() const { return sectorCount; } int getStackCount() const { return stackCount; } void set(float baseRadius, float topRadius, float height, int sectorCount, int stackCount, bool smooth = true); void setBaseRadius(float radius); void setTopRadius(float radius); void setHeight(float radius); void setSectorCount(int sectorCount); void setStackCount(int stackCount); void setSmooth(bool smooth); // for vertex data unsigned int getVertexCount() const { return (unsigned int)vertices.size() / 3; } unsigned int getNormalCount() const { return (unsigned int)normals.size() / 3; } unsigned int getTexCoordCount() const { return (unsigned int)texCoords.size() / 2; } unsigned int getIndexCount() const { return (unsigned int)indices.size(); } unsigned int getLineIndexCount() const { return (unsigned int)lineIndices.size(); } unsigned int getTriangleCount() const { return getIndexCount() / 3; } unsigned int getVertexSize() const { return (unsigned int)vertices.size() * sizeof(float); } unsigned int getNormalSize() const { return (unsigned int)normals.size() * sizeof(float); } unsigned int getTexCoordSize() const { return (unsigned int)texCoords.size() * sizeof(float); } unsigned int getIndexSize() const { return (unsigned int)indices.size() * sizeof(unsigned int); } unsigned int getLineIndexSize() const { return (unsigned int)lineIndices.size() * sizeof(unsigned int); } const float* getVertices() const { return vertices.data(); } const float* getNormals() const { return normals.data(); } const float* getTexCoords() const { return texCoords.data(); } const unsigned int* getIndices() const { return indices.data(); } const unsigned int* getLineIndices() const { return lineIndices.data(); } // for interleaved vertices: V/N/T unsigned int getInterleavedVertexCount() const { return getVertexCount(); } // # of vertices unsigned int getInterleavedVertexSize() const { return (unsigned int)interleavedVertices.size() * sizeof(unsigned int); } // # of bytes int getInterleavedStride() const { return interleavedStride; } // should be 32 bytes const float* getInterleavedVertices() const { return &interleavedVertices[0]; } // for indices of base/top/side parts unsigned int getBaseIndexCount() const { return ((unsigned int)indices.size() - baseIndex) / 2; } unsigned int getTopIndexCount() const { return ((unsigned int)indices.size() - baseIndex) / 2; } unsigned int getSideIndexCount() const { return baseIndex; } unsigned int getBaseStartIndex() const { return baseIndex; } unsigned int getTopStartIndex() const { return topIndex; } unsigned int getSideStartIndex() const { return 0; } // side starts from the begining // draw in VertexArray mode void draw(float4x4 transform = float4x4::identity, float red = 1.0f, float green = 1.0f, float blue = 1.0f, float alpha = 1.0f) const; // draw all void drawBase() const; // draw base cap only void drawTop() const; // draw top cap only void drawSide() const; // draw side only void drawLines(const float lineColor[4]) const; // draw lines only void drawWithLines(const float lineColor[4]) const; // draw surface and lines // debug void printSelf() const; protected: private: // member functions void clearArrays(); void buildVerticesSmooth(); void buildVerticesFlat(); void buildInterleavedVertices(); void buildUnitCircleVertices(); void addVertex(float x, float y, float z); void addNormal(float x, float y, float z); void addTexCoord(float s, float t); void addIndices(unsigned int i1, unsigned int i2, unsigned int i3); std::vector<float> getSideNormals(); std::vector<float> computeFaceNormal(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3); // memeber vars float baseRadius; float topRadius; float height; int sectorCount; // # of slices int stackCount; // # of stacks unsigned int baseIndex; // starting index of base unsigned int topIndex; // starting index of top bool smooth; std::vector<float> unitCircleVertices; std::vector<float> vertices; std::vector<float> normals; std::vector<float> texCoords; std::vector<unsigned int> indices; std::vector<unsigned int> lineIndices; // interleaved std::vector<float> interleavedVertices; int interleavedStride; // # of bytes to hop to the next vertex (should be 32 bytes) }; #endif
45.732824
159
0.65999
[ "vector", "transform" ]
30df9b59c76bd3ee0a7d3123ec5a13c47a9754b5
6,233
h
C
aws-cpp-sdk-location/include/aws/location/model/BatchDeleteDevicePositionHistoryRequest.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-location/include/aws/location/model/BatchDeleteDevicePositionHistoryRequest.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-location/include/aws/location/model/BatchDeleteDevicePositionHistoryRequest.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/location/LocationService_EXPORTS.h> #include <aws/location/LocationServiceRequest.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace LocationService { namespace Model { /** */ class AWS_LOCATIONSERVICE_API BatchDeleteDevicePositionHistoryRequest : public LocationServiceRequest { public: BatchDeleteDevicePositionHistoryRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "BatchDeleteDevicePositionHistory"; } Aws::String SerializePayload() const override; /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline const Aws::Vector<Aws::String>& GetDeviceIds() const{ return m_deviceIds; } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline bool DeviceIdsHasBeenSet() const { return m_deviceIdsHasBeenSet; } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline void SetDeviceIds(const Aws::Vector<Aws::String>& value) { m_deviceIdsHasBeenSet = true; m_deviceIds = value; } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline void SetDeviceIds(Aws::Vector<Aws::String>&& value) { m_deviceIdsHasBeenSet = true; m_deviceIds = std::move(value); } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline BatchDeleteDevicePositionHistoryRequest& WithDeviceIds(const Aws::Vector<Aws::String>& value) { SetDeviceIds(value); return *this;} /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline BatchDeleteDevicePositionHistoryRequest& WithDeviceIds(Aws::Vector<Aws::String>&& value) { SetDeviceIds(std::move(value)); return *this;} /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline BatchDeleteDevicePositionHistoryRequest& AddDeviceIds(const Aws::String& value) { m_deviceIdsHasBeenSet = true; m_deviceIds.push_back(value); return *this; } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline BatchDeleteDevicePositionHistoryRequest& AddDeviceIds(Aws::String&& value) { m_deviceIdsHasBeenSet = true; m_deviceIds.push_back(std::move(value)); return *this; } /** * <p>Devices whose position history you want to delete.</p> <ul> <li> <p>For * example, for two devices: <code>“DeviceIds” : [DeviceId1,DeviceId2]</code> </p> * </li> </ul> */ inline BatchDeleteDevicePositionHistoryRequest& AddDeviceIds(const char* value) { m_deviceIdsHasBeenSet = true; m_deviceIds.push_back(value); return *this; } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline const Aws::String& GetTrackerName() const{ return m_trackerName; } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline bool TrackerNameHasBeenSet() const { return m_trackerNameHasBeenSet; } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline void SetTrackerName(const Aws::String& value) { m_trackerNameHasBeenSet = true; m_trackerName = value; } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline void SetTrackerName(Aws::String&& value) { m_trackerNameHasBeenSet = true; m_trackerName = std::move(value); } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline void SetTrackerName(const char* value) { m_trackerNameHasBeenSet = true; m_trackerName.assign(value); } /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline BatchDeleteDevicePositionHistoryRequest& WithTrackerName(const Aws::String& value) { SetTrackerName(value); return *this;} /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline BatchDeleteDevicePositionHistoryRequest& WithTrackerName(Aws::String&& value) { SetTrackerName(std::move(value)); return *this;} /** * <p>The name of the tracker resource to delete the device position history * from.</p> */ inline BatchDeleteDevicePositionHistoryRequest& WithTrackerName(const char* value) { SetTrackerName(value); return *this;} private: Aws::Vector<Aws::String> m_deviceIds; bool m_deviceIdsHasBeenSet; Aws::String m_trackerName; bool m_trackerNameHasBeenSet; }; } // namespace Model } // namespace LocationService } // namespace Aws
38.95625
174
0.671105
[ "vector", "model" ]
30e39d22cc9e34d9c1bdedbb47e3326bc818cfd1
1,639
h
C
src/dag/cclient/request/get_trytes.h
bcashclassic/bcashclassic
2a31ac8b617226c8e99a47512013530ba4899f66
[ "MIT" ]
null
null
null
src/dag/cclient/request/get_trytes.h
bcashclassic/bcashclassic
2a31ac8b617226c8e99a47512013530ba4899f66
[ "MIT" ]
null
null
null
src/dag/cclient/request/get_trytes.h
bcashclassic/bcashclassic
2a31ac8b617226c8e99a47512013530ba4899f66
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 IOTA Stiftung * https://github.com/iotaledger/entangled * * Refer to the LICENSE file for licensing information */ /** * @ingroup request * * @{ * * @file * @brief * */ #ifndef CCLIENT_REQUEST_GET_TRYTES_H #define CCLIENT_REQUEST_GET_TRYTES_H #include "common/errors.h" #include "utils/containers/hash/hash243_queue.h" #ifdef __cplusplus extern "C" { #endif /** * @brief The data structure of the get trytes request. * */ typedef struct get_trytes_req_s { /* List of transaction hashes for which request should get */ hash243_queue_t hashes; } get_trytes_req_t; /** * @brief Allocates a get trytes request object. * * @return A pointer to the request object. */ get_trytes_req_t* get_trytes_req_new(); /** * @brief Free a get trytes request object. * * @param[in] req The request object. */ void get_trytes_req_free(get_trytes_req_t** const req); /** * @brief Add a transaction hash to the request. * * @param[in] req The request object. * @param[in] hash A transaction hash. * @return #retcode_t */ static inline retcode_t get_trytes_req_hash_add(get_trytes_req_t* const req, flex_trit_t const* const hash) { return hash243_queue_push(&req->hashes, hash); } /** * @brief Get a transaction hash by index. * * @param[in] req The request object. * @param[in] index An index of transaction list. * @return A pointer to a transaction hash. */ static inline flex_trit_t* get_trytes_req_hash_get(get_trytes_req_t* const req, size_t index) { return hash243_queue_at(&req->hashes, index); } #ifdef __cplusplus } #endif #endif // CCLIENT_REQUEST_GET_TRYTES_H /** @} */
21.012821
109
0.716901
[ "object" ]
30e50fe81bc21c20915651ce12abbd0935df952f
667
h
C
include/RCubeViewer/Colormap.h
pradeep-pyro/RCube
df0e13eadbd70aadd721629bc77f48c31f9c0f4d
[ "BSD-3-Clause" ]
4
2019-03-13T00:43:16.000Z
2021-12-02T00:27:52.000Z
include/RCubeViewer/Colormap.h
pradeep-pyro/RCube
df0e13eadbd70aadd721629bc77f48c31f9c0f4d
[ "BSD-3-Clause" ]
14
2019-11-12T17:32:29.000Z
2021-03-18T07:22:24.000Z
include/RCubeViewer/Colormap.h
pradeep-pyro/RCube
df0e13eadbd70aadd721629bc77f48c31f9c0f4d
[ "BSD-3-Clause" ]
1
2019-11-10T22:20:27.000Z
2019-11-10T22:20:27.000Z
#pragma once #include "glm/glm.hpp" #include <vector> namespace rcube { namespace viewer { enum class Colormap { None, Viridis, Magma, }; void colormap(Colormap cm, float value, float vmin, float vmax, glm::vec3 &rgb); void colormap(Colormap cm, const float *value, size_t size, float vmin, float vmax, std::vector<glm::vec3> &rgb); void colormap(Colormap cm, const std::vector<float> values, float vmin, float vmax, std::vector<float> &colors); void colormap(Colormap cm, const std::vector<float> &value, float vmin, float vmax, std::vector<glm::vec3> &colors); } // namespace viewer } // namespace rcube
22.233333
83
0.667166
[ "vector" ]
30e646cb22fccb7f085f17f0b793c8983b5375ca
5,630
c
C
libexec/ld.so/boot.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2019-02-16T13:29:23.000Z
2019-02-16T13:29:23.000Z
libexec/ld.so/boot.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2018-08-21T03:56:33.000Z
2018-08-21T03:56:33.000Z
libexec/ld.so/boot.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
null
null
null
/* $OpenBSD: boot.c,v 1.6 2015/12/06 23:36:12 guenther Exp $ */ /* * Copyright (c) 1998 Per Fogelstrom, Opsycon AB * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * IMPORTANT: any functions below are NOT protected by SSP. Please * do not add anything except what is required to reach GOT with * an adjustment. */ #define _DYN_LOADER #include <sys/types.h> #include <sys/mman.h> #include <sys/exec.h> #include <sys/sysctl.h> #include <nlist.h> #include <link.h> #include <dlfcn.h> #include "syscall.h" #include "archdep.h" #include "stdlib.h" #include "../../lib/csu/os-note-elf.h" #if RELOC_TAG == DT_RELA typedef Elf_RelA RELOC_TYPE; #elif RELOC_TAG == DT_REL typedef Elf_Rel RELOC_TYPE; #else # error "unknown RELOC_TAG" #endif /* The set of dynamic tags that we're interested in for bootstrapping */ struct boot_dyn { RELOC_TYPE *dt_reloc; /* DT_RELA or DT_REL */ Elf_Addr dt_relocsz; /* DT_RELASZ or DT_RELSZ */ Elf_Addr *dt_pltgot; Elf_Addr dt_pltrelsz; const Elf_Sym *dt_symtab; #ifdef HAVE_JMPREL RELOC_TYPE *dt_jmprel; #endif #if DT_PROCNUM > 0 u_long dt_proc[DT_PROCNUM]; #endif }; /* * Local decls. */ void _dl_boot_bind(const long, long *, Elf_Dyn *); void _dl_boot_bind(const long sp, long *dl_data, Elf_Dyn *dynamicp) { struct boot_dyn dynld; /* Resolver data for the loader */ AuxInfo *auxstack; long *stack; Elf_Dyn *dynp; int n, argc; char **argv, **envp; long loff; Elf_Addr i; RELOC_TYPE *rp; /* * Scan argument and environment vectors. Find dynamic * data vector put after them. */ stack = (long *)sp; argc = *stack++; argv = (char **)stack; envp = &argv[argc + 1]; stack = (long *)envp; while (*stack++ != 0L) ; /* * Zero out dl_data. */ for (n = 0; n <= AUX_entry; n++) dl_data[n] = 0; /* * Dig out auxiliary data set up by exec call. Move all known * tags to an indexed local table for easy access. */ for (auxstack = (AuxInfo *)stack; auxstack->au_id != AUX_null; auxstack++) { if (auxstack->au_id > AUX_entry) continue; dl_data[auxstack->au_id] = auxstack->au_v; } loff = dl_data[AUX_base]; /* XXX assumes ld.so is linked at 0x0 */ /* * We need to do 'selfreloc' in case the code weren't * loaded at the address it was linked to. * * Scan the DYNAMIC section for the loader. * Cache the data for easier access. */ #if defined(__alpha__) dynp = (Elf_Dyn *)((long)_DYNAMIC); #elif defined(__sparc__) || defined(__sparc64__) || defined(__powerpc__) || \ defined(__hppa__) || defined(__sh__) dynp = dynamicp; #else dynp = (Elf_Dyn *)((long)_DYNAMIC + loff); #endif _dl_memset(&dynld, 0, sizeof(dynld)); while (dynp->d_tag != DT_NULL) { /* first the tags that are pointers to be relocated */ if (dynp->d_tag == DT_PLTGOT) dynld.dt_pltgot = (void *)(dynp->d_un.d_ptr + loff); else if (dynp->d_tag == DT_SYMTAB) dynld.dt_symtab = (void *)(dynp->d_un.d_ptr + loff); else if (dynp->d_tag == RELOC_TAG) /* DT_{RELA,REL} */ dynld.dt_reloc = (void *)(dynp->d_un.d_ptr + loff); #ifdef HAVE_JMPREL else if (dynp->d_tag == DT_JMPREL) dynld.dt_jmprel = (void *)(dynp->d_un.d_ptr + loff); #endif /* Now for the tags that are just sizes or counts */ else if (dynp->d_tag == DT_PLTRELSZ) dynld.dt_pltrelsz = dynp->d_un.d_val; else if (dynp->d_tag == RELOC_TAG+1) /* DT_{RELA,REL}SZ */ dynld.dt_relocsz = dynp->d_un.d_val; #if DT_PROCNUM > 0 else if (dynp->d_tag >= DT_LOPROC && dynp->d_tag < DT_LOPROC + DT_PROCNUM) dynld.dt_proc[dynp->d_tag - DT_LOPROC] = dynp->d_un.d_val; #endif /* DT_PROCNUM */ dynp++; } #ifdef HAVE_JMPREL rp = dynld.dt_jmprel; for (i = 0; i < dynld.dt_pltrelsz; i += sizeof *rp) { Elf_Addr *ra; const Elf_Sym *sp; sp = dynld.dt_symtab + ELF_R_SYM(rp->r_info); if (ELF_R_SYM(rp->r_info) && sp->st_value == 0) _dl_exit(5); ra = (Elf_Addr *)(rp->r_offset + loff); RELOC_JMPREL(rp, sp, ra, loff, dynld.dt_pltgot); rp++; } #endif /* HAVE_JMPREL */ rp = dynld.dt_reloc; for (i = 0; i < dynld.dt_relocsz; i += sizeof *rp) { Elf_Addr *ra; const Elf_Sym *sp; sp = dynld.dt_symtab + ELF_R_SYM(rp->r_info); if (ELF_R_SYM(rp->r_info) && sp->st_value == 0) _dl_exit(6); ra = (Elf_Addr *)(rp->r_offset + loff); RELOC_DYN(rp, sp, ra, loff); rp++; } RELOC_GOT(&dynld, loff); /* * we have been fully relocated here, so most things no longer * need the loff adjustment */ }
27.598039
77
0.679929
[ "vector" ]
30fe45e8e6bbc246f59e218408e8f1450edb00f1
41,805
h
C
flash-graph/vertex.h
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
140
2015-01-02T21:28:55.000Z
2015-12-22T01:25:03.000Z
flash-graph/vertex.h
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
160
2016-11-07T18:37:33.000Z
2020-03-10T22:57:07.000Z
flash-graph/vertex.h
kjhyun824/uncertain-graph-engine
17aa1b8b5d03b03200583797ab0cfb4a42ff8845
[ "Apache-2.0" ]
25
2016-11-14T04:31:29.000Z
2020-07-28T04:58:44.000Z
#ifndef __EXT_VERTEX_H__ #define __EXT_VERTEX_H__ /* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <memory> #include <vector> #include <algorithm> #include <unordered_map> #include "comm_exception.h" #include "container.h" #include "cache.h" #include "FG_basic_types.h" namespace fg { /** \brief Edge type of an edge in the graph. */ enum edge_type { NONE, /**No edge*/ IN_EDGE, /**In edges*/ OUT_EDGE, /**Out edges*/ BOTH_EDGES, /**Both in and out edges*/ NUM_TYPES, }; class vertex_index; /* * \brief This class contains the basic information about a vertex on the disk. * */ class ext_mem_vertex_info { vertex_id_t id; vsize_t size; off_t off; public: ext_mem_vertex_info() { id = INVALID_VERTEX_ID; off = 0; size = 0; } ext_mem_vertex_info(vertex_id_t id, off_t off, size_t size) { this->id = id; this->off = off; this->size = size; } vertex_id_t get_id() const { return id; } off_t get_off() const { return off; } vsize_t get_size() const { return size; } bool has_edges() const; bool is_valid() const { return id != INVALID_VERTEX_ID; } }; /* * The information of vertex header. * It contains the vertex ID and the number of edges. */ class vertex_header { vertex_id_t id; vsize_t num_edges; public: vertex_header(vertex_id_t id, vsize_t num_edges) { this->id = id; this->num_edges = num_edges; } vertex_id_t get_id() const { return id; } vsize_t get_num_edges() const { return num_edges; } }; /* * The information of directed vertex header. * In addition to the vertex header, it has the number of in-edges * and out-edges. */ class directed_vertex_header: public vertex_header { vsize_t num_in_edges; vsize_t num_out_edges; public: directed_vertex_header(vertex_id_t id, vsize_t num_in_edges, vsize_t num_out_edges): vertex_header(id, num_in_edges + num_out_edges) { this->num_in_edges = num_in_edges; this->num_out_edges = num_out_edges; } vsize_t get_num_in_edges() const { return num_in_edges; } vsize_t get_num_out_edges() const { return num_out_edges; } }; class empty_data { public: bool operator==(const empty_data &data) const { return true; } }; static inline std::ostream& operator<<(std::ostream& cout, empty_data obj) { return cout; } template<class data_type = empty_data> class edge { bool has_data; vertex_id_t from; vertex_id_t to; data_type data; public: edge() { this->from = -1; this->to = -1; has_data = false; } edge(vertex_id_t from, vertex_id_t to) { this->from = from; this->to = to; has_data = false; } edge(vertex_id_t from, vertex_id_t to, const data_type &data) { this->from = from; this->to = to; this->data = data; has_data = true; } vertex_id_t get_from() const { return from; } vertex_id_t get_to() const { return to; } bool has_edge_data() const { return has_data; } const data_type &get_data() const { assert(has_data); return data; } void reverse_dir() { vertex_id_t tmp = from; from = to; to = tmp; } }; template<> class edge<empty_data> { static empty_data data; vertex_id_t from; vertex_id_t to; public: edge() { this->from = -1; this->to = -1; } edge(vertex_id_t from, vertex_id_t to) { this->from = from; this->to = to; } edge(vertex_id_t from, vertex_id_t to, const empty_data &data) { this->from = from; this->to = to; } vertex_id_t get_from() const { return from; } vertex_id_t get_to() const { return to; } bool has_edge_data() const { return false; } const empty_data &get_data() const { return data; } void reverse_dir() { vertex_id_t tmp = from; from = to; to = tmp; } }; /** * The timestamp of an edge. */ class ts_edge_data { time_t timestamp; public: ts_edge_data() { timestamp = 0; } ts_edge_data(time_t timestamp) { this->timestamp = timestamp; } time_t get_timestamp() const { return timestamp; } bool operator==(const ts_edge_data &data) const { return this->timestamp == data.timestamp; } bool operator<(const ts_edge_data &data) const { return this->timestamp < data.timestamp; } }; static inline std::ostream& operator<<(std::ostream& cout, const ts_edge_data &obj) { return cout << obj.get_timestamp(); } template<> class edge<ts_edge_data> { vertex_id_t from; vertex_id_t to; ts_edge_data data; public: edge() { this->from = -1; this->to = -1; } edge(vertex_id_t from, vertex_id_t to) { this->from = from; this->to = to; } edge(vertex_id_t from, vertex_id_t to, const ts_edge_data &data) { this->from = from; this->to = to; this->data = data; } vertex_id_t get_from() const { return from; } vertex_id_t get_to() const { return to; } bool has_edge_data() const { return true; } const ts_edge_data &get_data() const { return data; } void reverse_dir() { vertex_id_t tmp = from; from = to; to = tmp; } }; /** * The number of duplicated edges. * It is used as edge data type. */ class edge_count { uint32_t num; public: edge_count() { num = 1; } edge_count(uint32_t n) { num = n; } uint32_t get_count() const { return num; } bool operator==(const edge_count &count) const { return this->num == count.num; } edge_count& operator+=(const edge_count& rhs) { this->num += rhs.get_count(); return *this; } }; static inline std::ostream& operator<<(std::ostream& cout, const edge_count &obj) { return cout << obj.get_count(); } template<class edge_data_type> class in_mem_directed_vertex; template<class edge_data_type> class in_mem_undirected_vertex; template<class edge_data_type> class edge_const_iterator { bool is_in_edge; vertex_id_t id; const vertex_id_t *ptr; const edge_data_type *data_ptr; public: edge_const_iterator(vertex_id_t id, const vertex_id_t *edge_ptr, const edge_data_type *data_ptr, bool is_in_edge) { this->is_in_edge = is_in_edge; this->id = id; this->ptr = edge_ptr; this->data_ptr = data_ptr; } edge<edge_data_type> operator*() const { if (data_ptr) { if (is_in_edge) return edge<edge_data_type>(*ptr, id, *data_ptr); else return edge<edge_data_type>(id, *ptr, *data_ptr); } else { if (is_in_edge) return edge<edge_data_type>(*ptr, id); else return edge<edge_data_type>(id, *ptr); } } edge_const_iterator &operator++() { ptr++; if (data_ptr) data_ptr++; return *this; } bool operator==(const edge_const_iterator &it) const { return this->ptr == it.ptr; } bool operator!=(const edge_const_iterator &it) const { return this->ptr != it.ptr; } edge_const_iterator &operator+=(int num) { ptr += num; if (data_ptr) data_ptr += num; return *this; } }; template<class T> struct delete_as_chararr { public: void operator()(T *obj) const { char *char_p = (char *) obj; delete [] char_p; } }; class in_mem_vertex; /* * This vertex represents an undirected vertex in the external memory. */ class ext_mem_undirected_vertex { vertex_id_t id; uint32_t edge_data_size; vsize_t num_edges; vertex_id_t neighbors[0]; void set_id(vertex_id_t id) { this->id = id; } /* * The size of the vertex without counting the edge data list. */ size_t get_size0() const { return get_header_size() + sizeof(neighbors[0]) * num_edges; } char *get_edge_data_addr() const { return ((char *) this) + ROUNDUP(get_size0(), edge_data_size); } template<class edge_data_type = empty_data> const edge_data_type *get_edge_data_begin() const { assert(sizeof(edge_data_type) == edge_data_size); return (edge_data_type *) get_edge_data_addr(); } template<class edge_data_type = empty_data> edge_data_type *get_edge_data_begin() { assert(sizeof(edge_data_type) == edge_data_size); return (edge_data_type *) get_edge_data_addr(); } public: static size_t get_header_size() { return offsetof(ext_mem_undirected_vertex, neighbors); } static size_t get_edge_data_offset(vsize_t num_edges, uint32_t edge_data_size) { ext_mem_undirected_vertex v(0, num_edges, edge_data_size); return v.get_edge_data_addr() - (char *) &v; } static ext_mem_undirected_vertex *deserialize(char *buf, size_t size) { assert(size >= ext_mem_undirected_vertex::get_header_size()); ext_mem_undirected_vertex *v = (ext_mem_undirected_vertex *) buf; assert(size >= v->get_size()); return v; } static size_t serialize(const in_mem_vertex &v, char *buf, size_t size, edge_type type); static vsize_t vsize2num_edges(size_t vertex_size, size_t edge_data_size) { return (vertex_size - get_header_size()) / (sizeof(vertex_id_t) + edge_data_size); } static size_t num_edges2vsize(vsize_t num_edges, size_t edge_data_size) { ext_mem_undirected_vertex v(0, num_edges, edge_data_size); return v.get_size(); } ext_mem_undirected_vertex() { this->id = 0; this->num_edges = 0; this->edge_data_size = 0; } ext_mem_undirected_vertex(vertex_id_t id, vsize_t num_edges, uint32_t edge_data_size) { this->id = id; this->num_edges = num_edges; this->edge_data_size = edge_data_size; } size_t get_size() const { if (has_edge_data()) return ROUNDUP(((size_t) get_edge_data_addr()) - ((size_t) this) + (num_edges) * edge_data_size, sizeof(vertex_id_t)); else return ext_mem_undirected_vertex::get_header_size() + (num_edges) * sizeof(neighbors[0]); } bool has_edge_data() const { return edge_data_size > 0; } size_t get_edge_data_size() const { return edge_data_size; } size_t get_num_edges() const { return num_edges; } vertex_id_t get_neighbor(size_t idx) const { return neighbors[idx]; } void set_neighbor(size_t idx, vertex_id_t id) { neighbors[idx] = id; } char *get_raw_edge_data(size_t idx) const { return this->get_edge_data_addr() + idx * edge_data_size; } template<class edge_data_type = empty_data> const edge_data_type &get_edge_data(size_t idx) const { return ((edge_data_type *) this->get_edge_data_addr())[idx]; } vertex_id_t get_id() const { return id; } }; inline bool ext_mem_vertex_info::has_edges() const { return size > ext_mem_undirected_vertex::get_header_size(); } typedef safs::page_byte_array::const_iterator<vertex_id_t> edge_iterator; typedef safs::page_byte_array::seq_const_iterator<vertex_id_t> edge_seq_iterator; /** * \brief Vertex representation when in the page cache. */ class page_vertex { bool directed; public: page_vertex(bool directed) { this->directed = directed; } /** * \brief Get the number of edges connecting the vertex to othe vertices. * \return The number of edges conning the vertex. * \param type The type of edges a user wishes to iterate over e.g `IN_EDGE`, `OUT_EDGE`. */ virtual size_t get_num_edges(edge_type type) const = 0; /** * \brief Get an STL-style const iterator pointing to the *first* neighbor in a vertex's neighbor list. * \return A const iterator pointing to the *first* neighbor in a vertex's neighbor list. * \param type The type of edges a user wishes to iterate over e.g `IN_EDGE`, `OUT_EDGE`. */ virtual edge_iterator get_neigh_begin(edge_type type) const = 0; /** * \brief Get an STL-style const iterator pointing to the *end* of a vertex's neighbor list. * \return A const iterator pointing to the *end* of a vertex's neighbor list. * \param type The type of edges a user wishes to iterate over e.g `IN_EDGE`, `OUT_EDGE`. */ virtual edge_iterator get_neigh_end(edge_type type) const = 0; /** * \brief Get a java-style sequential const iterator that iterates * the neighbors in the specified range. * \return A sequential const iterator. * \param type The type of edges a user wishes to iterate over e.g `IN_EDGE`, * `OUT_EDGE`. * \param start The starting offset in the neighbor list iterated by * the sequential iterator. * \param end The end offset in the neighbor list iterated by the sequential * iterator. */ virtual edge_seq_iterator get_neigh_seq_it(edge_type type, size_t start = 0, size_t end = -1) const = 0; /** * \brief Get the vertex unique ID. * \return The vertex unique ID. */ virtual vertex_id_t get_id() const = 0; /** * \brief Read the edges of the specified type. * \param type The type of edges a user wishes to read * e.g `IN_EDGE`, `OUT_EDGE`. * \param edges The array of edges returned to a user. * \param num The maximal number of edges read by a user. */ virtual size_t read_edges(edge_type type, vertex_id_t edges[], size_t num) const { throw unsupported_exception("read_edges"); } /** * \brief Whether the vertex is directed. * \return true if it's a directed vertex. */ virtual bool is_directed() const { return directed; } /** * \internal */ virtual void print() const { } }; /* * These two ranges are defined as [first, second), * i.e., inclusive in the beginning and exclusive in the end. */ typedef std::pair<int, int> timestamp_pair; typedef std::pair<off_t, off_t> offset_pair; /** * Time-series page vertex utilized when doing time series graph analysis * */ class TS_page_vertex: public page_vertex { public: TS_page_vertex(bool directed): page_vertex(directed) { } using page_vertex::get_num_edges; /** * \brief Get the global number of edges associated with a vertex. * \return The number of edges associated with a vertex. */ virtual size_t get_num_edges() const = 0; /** * \brief Get the number of edges associated with a vertex at a specific time point. * \param timestamp The specific time stamp where you want the vertex metadata evaluated. * \param type The type of edges a user wishes to evaluate e.g `IN_EDGE`. * \return The number of edges associated with a vertex. */ virtual size_t get_num_edges(int timestamp, edge_type type) const = 0; /** * \brief Get the number of time stamps the vertex has in the graph. * \return The number of time stamps the vertex has in the graph. */ virtual int get_num_timestamps() const = 0; using page_vertex::get_neigh_begin; using page_vertex::get_neigh_end; /** * \brief Get an STL-style const iterator pointing to the *first* element in the * neighbor list of a vertex at a specific time point. * \param timpstamp The time stamp of interest. * \param type The type of edges a user wishes to evaluate e.g `IN_EDGE`. * \return A const iterator pointing to the *first* element in the * neighbor list of a vertex. */ virtual edge_iterator get_neigh_begin(int timestamp, edge_type type) const = 0; /** * \brief Get an STL-style const iterator pointing to the *end* of the * neighbor list of a vertex at a specific time point. * \param timpstamp The time stamp of interest. * \param type The type of edges a user wishes to evaluate e.g `IN_EDGE`. * \return A const iterator pointing to the *end* of the * neighbor list of a vertex. */ virtual edge_iterator get_neigh_end(int timestamp, edge_type type) const = 0; /** \brief This method should translate the timestamp range to the absolute * location of the adjacency list in the timestamp range. * * \param range The timestamp range. * \return The location range of the adjacency list within the time range. */ virtual offset_pair get_edge_list_offset( const timestamp_pair &range) const = 0; }; /** * This vertex represents a directed vertex stored in the page cache. */ class page_directed_vertex: public page_vertex { vertex_id_t id; vsize_t num_in_edges; vsize_t num_out_edges; size_t in_size; size_t out_size; const safs::page_byte_array *in_array; const safs::page_byte_array *out_array; public: static vertex_id_t get_id(const safs::page_byte_array &arr) { BOOST_VERIFY(arr.get_size() >= ext_mem_undirected_vertex::get_header_size()); ext_mem_undirected_vertex v = arr.get<ext_mem_undirected_vertex>(0); return v.get_id(); } /** * \internal * The constructor for a directed vertex in the page cache. * \param arr The byte array containing the directed vertex * in the page cache. */ page_directed_vertex(const safs::page_byte_array &arr, bool in_part): page_vertex(true) { size_t size = arr.get_size(); BOOST_VERIFY(size >= ext_mem_undirected_vertex::get_header_size()); ext_mem_undirected_vertex v = arr.get<ext_mem_undirected_vertex>(0); if (in_part) { in_size = v.get_size(); assert(size >= in_size); out_size = 0; this->in_array = &arr; this->out_array = NULL; num_in_edges = v.get_num_edges(); num_out_edges = 0; } else { out_size = v.get_size(); in_size = 0; assert(size >= out_size); this->out_array = &arr; this->in_array = NULL; num_out_edges = v.get_num_edges(); num_in_edges = 0; } id = v.get_id(); } page_directed_vertex(const safs::page_byte_array &in_arr, const safs::page_byte_array &out_arr): page_vertex(true) { this->in_array = &in_arr; this->out_array = &out_arr; size_t size = in_arr.get_size(); BOOST_VERIFY(size >= ext_mem_undirected_vertex::get_header_size()); ext_mem_undirected_vertex v = in_arr.get<ext_mem_undirected_vertex>(0); in_size = v.get_size(); assert(size >= in_size); id = v.get_id(); num_in_edges = v.get_num_edges(); size = out_arr.get_size(); assert(size >= ext_mem_undirected_vertex::get_header_size()); v = out_arr.get<ext_mem_undirected_vertex>(0); out_size = v.get_size(); assert(size >= out_size); assert(id == v.get_id()); num_out_edges = v.get_num_edges(); } size_t get_in_size() const { return in_size; } size_t get_out_size() const { return out_size; } /** * \brief Get the number of edges associated with a vertex. * \param type The type of edges a user wishes to evaluate e.g `IN_EDGE`, `OUT_EDGE`. * \return The number of edges associated with a vertex. */ size_t get_num_edges(edge_type type) const { switch(type) { case IN_EDGE: return num_in_edges; case OUT_EDGE: return num_out_edges; case BOTH_EDGES: return num_in_edges + num_out_edges; default: throw invalid_arg_exception("invalid edge type"); } } /** * \brief Get an STL-style const iterator pointing to the *first* element in the * neighbor list of a vertex. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \return A const iterator pointing to the *first* element in the * neighbor list of a vertex. */ edge_iterator get_neigh_begin(edge_type type) const { switch(type) { case IN_EDGE: assert(in_array); return in_array->begin<vertex_id_t>( ext_mem_undirected_vertex::get_header_size()); case OUT_EDGE: assert(out_array); return out_array->begin<vertex_id_t>( ext_mem_undirected_vertex::get_header_size()); default: throw invalid_arg_exception("invalid edge type"); } } /* * \brief Get an STL-style const iterator pointing to the *end* of the * neighbor list of a vertex. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \return A const iterator pointing to the *end* of the * neighbor list of a vertex. */ edge_iterator get_neigh_end(edge_type type) const { edge_iterator it = get_neigh_begin(type); it += get_num_edges(type); return it; } /* * \brief Get a java-style sequential const iterator that iterates * the neighbors in the specified range. * \return A sequential const iterator. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \param start The starting offset in the neighbor list iterated by * the sequential iterator. * \param end The end offset in the neighbor list iterated by the sequential * iterator. */ edge_seq_iterator get_neigh_seq_it(edge_type type, size_t start = 0, size_t end = -1) const { end = std::min(end, get_num_edges(type)); assert(start <= end); switch(type) { case IN_EDGE: assert(in_array); return in_array->get_seq_iterator<vertex_id_t>( ext_mem_undirected_vertex::get_header_size() + start * sizeof(vertex_id_t), ext_mem_undirected_vertex::get_header_size() + end * sizeof(vertex_id_t)); case OUT_EDGE: assert(out_array); return out_array->get_seq_iterator<vertex_id_t>( ext_mem_undirected_vertex::get_header_size() + start * sizeof(vertex_id_t), ext_mem_undirected_vertex::get_header_size() + end * sizeof(vertex_id_t)); default: throw invalid_arg_exception("invalid edge type"); } } /** * \brief Get an STL-style const iterator pointing to the *first* element in the * edge data list of a vertex. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \return A const iterator pointing to the *first* element in the * edge data list of a vertex. */ template<class edge_data_type> safs::page_byte_array::const_iterator<edge_data_type> get_data_begin( edge_type type) const { switch(type) { case IN_EDGE: assert(in_array); return in_array->begin<edge_data_type>( ext_mem_undirected_vertex::get_edge_data_offset( num_in_edges, sizeof(edge_data_type))); case OUT_EDGE: assert(out_array); return out_array->begin<edge_data_type>( ext_mem_undirected_vertex::get_edge_data_offset( num_out_edges, sizeof(edge_data_type))); default: throw invalid_arg_exception("invalid edge type"); } } /** * \brief Get an STL-style const iterator pointing to the *end* of the * edge data list of a vertex. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \return A const iterator pointing to the *first* element in the * edge data list of a vertex. */ template<class edge_data_type> safs::page_byte_array::const_iterator<edge_data_type> get_data_end( edge_type type) const { auto it = get_data_begin<edge_data_type>(type); it += get_num_edges(type); return it; } /** * \brief Get a java-style sequential const iterator for edge data * with additional parameters to define the range to iterate. * \return A sequential const iterator. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \param start The starting offset in the edge list. * \param end The end offset in the edge list. */ template<class edge_data_type> safs::page_byte_array::seq_const_iterator<edge_data_type> get_data_seq_it( edge_type type, size_t start, size_t end) const { off_t edge_end; switch(type) { case IN_EDGE: assert(in_array); edge_end = ext_mem_undirected_vertex::get_edge_data_offset( num_in_edges, sizeof(edge_data_type)); return in_array->get_seq_iterator<edge_data_type>( edge_end + start * sizeof(edge_data_type), edge_end + end * sizeof(edge_data_type)); case OUT_EDGE: assert(out_array); edge_end = ext_mem_undirected_vertex::get_edge_data_offset( num_out_edges, sizeof(edge_data_type)); return out_array->get_seq_iterator<edge_data_type>( edge_end + start * sizeof(edge_data_type), edge_end + end * sizeof(edge_data_type)); default: throw invalid_arg_exception("invalid edge type"); } } /** * \brief Get a java-style sequential const iterator that iterates * the edge data list. * \param type The type of edges a user wishes to iterate over. A user * can iterate over `IN_EDGE` or `OUT_EDGE`. * \return A sequential const iterator. */ template<class edge_data_type> safs::page_byte_array::seq_const_iterator<edge_data_type> get_data_seq_it( edge_type type) const { size_t start = 0; size_t end = get_num_edges(type); return get_data_seq_it<edge_data_type>(type, start, end); } virtual size_t read_edges(edge_type type, vertex_id_t edges[], size_t num) const { size_t num_edges; switch(type) { case IN_EDGE: assert(num_in_edges <= num); assert(in_array); num_edges = num_in_edges; in_array->memcpy(ext_mem_undirected_vertex::get_header_size(), (char *) edges, sizeof(vertex_id_t) * num_edges); break; case OUT_EDGE: assert(num_out_edges <= num); assert(out_array); num_edges = num_out_edges; out_array->memcpy(ext_mem_undirected_vertex::get_header_size(), (char *) edges, sizeof(vertex_id_t) * num_edges); break; default: return 0; } return num_edges; } /** \brief Get the id of the vertex * \return The vertex id */ vertex_id_t get_id() const { return id; } /** \brief Determine whether the page vertex contains in-edges. * \return True if it contains in-edges. */ bool has_in_part() const { return in_array; } /** \brief Determine whether the page vertex contains out-edges. * \return True if it contains out-edges. */ bool has_out_part() const { return out_array; } }; /** * \brief This vertex class represents an undirected vertex in the page cache. */ class page_undirected_vertex: public page_vertex { vertex_id_t id; vsize_t vertex_size; vsize_t num_edges; const safs::page_byte_array &array; public: page_undirected_vertex(const safs::page_byte_array &arr): page_vertex( false), array(arr) { size_t size = arr.get_size(); BOOST_VERIFY(size >= ext_mem_undirected_vertex::get_header_size()); // We only want to know the header of the vertex, so we don't need to // know what data type an edge has. ext_mem_undirected_vertex v = arr.get<ext_mem_undirected_vertex>(0); BOOST_VERIFY((unsigned) size >= v.get_size()); vertex_size = v.get_size(); id = v.get_id(); num_edges = v.get_num_edges(); } size_t get_size() const { return vertex_size; } /** * \brief Get the number of edges of a specific `edge_type` associated with the vertex. * \param type The type of edge i.e `IN_EDGE`, `OUT_EDGE` are equivalent, * since it's an undirected vertex. * return The number of edges associated with the vertex. */ size_t get_num_edges(edge_type type = edge_type::IN_EDGE) const { return num_edges; } /** * \brief Get an STL-style const iterator pointing to the *first* element in the * neighbor list of a vertex. * \param type The type of edge i.e `IN_EDGE`, `OUT_EDGE` are equivalent, * since it's an undirected vertex. * \return A const iterator pointing to the *first* element in the * neighbor list of a vertex. */ edge_iterator get_neigh_begin(edge_type type) const { return array.begin<vertex_id_t>( ext_mem_undirected_vertex::get_header_size()); } /** * \brief Get an STL-style const iterator pointing to the *end* of the * neighbor list of a vertex. * \param type The type of edge i.e `IN_EDGE`, `OUT_EDGE` are equivalent, * since it's an undirected vertex. * \return A const iterator pointing to the *end* of the * neighbor list of a vertex. */ edge_iterator get_neigh_end(edge_type type) const { auto it = get_neigh_begin(type); it += num_edges; return it; } /** * \brief Get a java-style sequential const iterator for the specified range * in a vertex's neighbor list. * \param type The type of edge i.e `IN_EDGE`, `OUT_EDGE` are equivalent, * since it's an undirected vertex. * \param start The starting offset in the neighbor list iterated by * the sequential iterator. * \param end The end offset in the neighbor list iterated by the sequential * iterator. * \return A sequential const iterator for the specified range * in a vertex's neighbor list. */ edge_seq_iterator get_neigh_seq_it(edge_type type, size_t start = 0, size_t end = -1) const { end = std::min(end, get_num_edges(type)); assert(start <= end); assert(end <= get_num_edges(type)); return array.get_seq_iterator<vertex_id_t>( ext_mem_undirected_vertex::get_header_size() + start * sizeof(vertex_id_t), ext_mem_undirected_vertex::get_header_size() + end * sizeof(vertex_id_t)); } /** * \brief Read the edges of the specified type. * \param type The type of edge i.e `IN_EDGE`, `OUT_EDGE` are equivalent, * since it's an undirected vertex. * \param edges The array of edges returned to a user. * \param num The maximal number of edges read by a user. */ virtual size_t read_edges(edge_type type, vertex_id_t edges[], size_t num) const { vsize_t num_edges = get_num_edges(type); assert(num_edges <= num); array.memcpy(ext_mem_undirected_vertex::get_header_size(), (char *) edges, sizeof(vertex_id_t) * num_edges); return num_edges; } /** * \brief Get a java-style sequential const iterator for edge data * with additional parameters to define the range to iterate. * \return A sequential const iterator. * \param start The starting offset in the edge list. * \param end The end offset in the edge list. */ template<class edge_data_type> safs::page_byte_array::seq_const_iterator<edge_data_type> get_data_seq_it( size_t start, size_t end) const { off_t edge_end = ext_mem_undirected_vertex::get_edge_data_offset( num_edges, sizeof(edge_data_type)); return array.get_seq_iterator<edge_data_type>( edge_end + start * sizeof(edge_data_type), edge_end + end * sizeof(edge_data_type)); } /** * \brief Get a java-style sequential const iterator that iterates * the edge data list. * \return A sequential const iterator. */ template<class edge_data_type> safs::page_byte_array::seq_const_iterator<edge_data_type> get_data_seq_it( ) const { size_t start = 0; size_t end = get_num_edges(); return get_data_seq_it<edge_data_type>(start, end); } /** * \brief Get the vertex ID. * \return The vertex ID. */ vertex_id_t get_id() const { return id; } }; /* * The offset of in- and out-edges in the edge list of a time-series vertex. */ struct edge_off { // TODO vsize_t may not be enough. A graph with many timestamps may have // many edges. vsize_t in_off; vsize_t out_off; }; class in_mem_vertex { public: typedef std::shared_ptr<in_mem_vertex> ptr; virtual vertex_id_t get_id() const = 0; virtual bool has_edge_data() const = 0; virtual size_t get_edge_data_size() const = 0; virtual void serialize_edges(vertex_id_t ids[], edge_type type) const = 0; virtual void serialize_edge_data(char *data, edge_type type) const = 0; virtual size_t get_serialize_size(edge_type type) const = 0; virtual size_t get_num_edges(edge_type type) const = 0; virtual ptr create_remapped_vertex( const std::unordered_map<vertex_id_t, vertex_id_t> &map) const = 0; virtual void remap( const std::unordered_map<vertex_id_t, vertex_id_t> &map) = 0; }; /* * This is the size of a page vertex (either directed or undirected). * It's mainly used for allocating a buffer from the stack for a page vertex. */ const size_t STACK_PAGE_VERTEX_SIZE = sizeof(page_directed_vertex); template<class edge_data_type = empty_data> class in_mem_directed_vertex: public in_mem_vertex { vertex_id_t id; bool has_data; std::vector<vertex_id_t> out_edges; std::vector<vertex_id_t> in_edges; std::vector<edge_data_type> out_data; std::vector<edge_data_type> in_data; public: in_mem_directed_vertex(vertex_id_t id, bool has_data) { this->id = id; this->has_data = has_data; } in_mem_directed_vertex(const page_directed_vertex &vertex, bool has_data) { this->id = vertex.get_id(); this->has_data = has_data; in_edges.resize(vertex.get_num_edges(edge_type::IN_EDGE)); vertex.read_edges(edge_type::IN_EDGE, in_edges.data(), vertex.get_num_edges(edge_type::IN_EDGE)); out_edges.resize(vertex.get_num_edges(edge_type::OUT_EDGE)); vertex.read_edges(edge_type::OUT_EDGE, out_edges.data(), vertex.get_num_edges(edge_type::OUT_EDGE)); assert(!has_data); } vertex_id_t get_id() const { return id; } bool has_edge_data() const { return has_data; } size_t get_edge_data_size() const { return has_data ? sizeof(edge_data_type) : 0; } virtual void serialize_edges(vertex_id_t ids[], edge_type type) const { switch (type) { case edge_type::IN_EDGE: memcpy(ids, in_edges.data(), in_edges.size() * sizeof(ids[0])); break; case edge_type::OUT_EDGE: memcpy(ids, out_edges.data(), out_edges.size() * sizeof(ids[0])); break; default: BOOST_LOG_TRIVIAL(error) << "can't serialize other edge types"; } } virtual void serialize_edge_data(char *data, edge_type type) const { assert(has_data); switch (type) { case edge_type::IN_EDGE: memcpy(data, in_data.data(), in_data.size() * sizeof(edge_data_type)); break; case edge_type::OUT_EDGE: memcpy(data, out_data.data(), out_data.size() * sizeof(edge_data_type)); break; default: BOOST_LOG_TRIVIAL(error) << "can't serialize other edge types"; } } /* * Add an in-edge to the vertex. * We allow to have multiple same edges, but all edges must be added * in a sorted order. */ void add_in_edge(const edge<edge_data_type> &e) { assert(e.get_to() == id); in_edges.push_back(e.get_from()); if (has_edge_data()) in_data.push_back(e.get_data()); } /* * Add an out-edge to the vertex. * We allow to have multiple same edges, but all edges must be added * in a sorted order. */ void add_out_edge(const edge<edge_data_type> &e) { assert(e.get_from() == id); out_edges.push_back(e.get_to()); if (has_edge_data()) out_data.push_back(e.get_data()); } size_t get_num_edges(edge_type type) const { switch(type) { case edge_type::IN_EDGE: return get_num_in_edges(); case edge_type::OUT_EDGE: return get_num_out_edges(); case edge_type::BOTH_EDGES: return get_num_in_edges() + get_num_out_edges(); default: throw invalid_arg_exception("invalid edge type"); } } size_t get_num_in_edges() const { return in_edges.size(); } size_t get_num_out_edges() const { return out_edges.size(); } edge_const_iterator<edge_data_type> get_in_edge_begin() const { return edge_const_iterator<edge_data_type>(id, in_edges.data(), in_data.data(), true); } edge_const_iterator<edge_data_type> get_in_edge_end() const { edge_const_iterator<edge_data_type> it = get_in_edge_begin(); it += get_num_in_edges(); return it; } edge_const_iterator<edge_data_type> get_out_edge_begin() const { return edge_const_iterator<edge_data_type>(id, out_edges.data(), out_data.data(), false); } edge_const_iterator<edge_data_type> get_out_edge_end() const { edge_const_iterator<edge_data_type> it = get_out_edge_begin(); it += get_num_out_edges(); return it; } const edge<edge_data_type> get_in_edge(int idx) const { if (has_edge_data()) return edge<edge_data_type>(in_edges[idx], id, in_data[idx]); else return edge<edge_data_type>(in_edges[idx], id); } const edge<edge_data_type> get_out_edge(int idx) const { if (has_edge_data()) return edge<edge_data_type>(id, out_edges[idx], out_data[idx]); else return edge<edge_data_type>(id, out_edges[idx]); } size_t get_serialize_size(edge_type type) const { assert(type == edge_type::IN_EDGE || type == edge_type::OUT_EDGE); if (type == edge_type::IN_EDGE) { ext_mem_undirected_vertex v(0, in_edges.size(), has_data ? sizeof(edge_data_type) : 0); return v.get_size(); } else { ext_mem_undirected_vertex v(0, out_edges.size(), has_data ? sizeof(edge_data_type) : 0); return v.get_size(); } } in_mem_vertex::ptr create_remapped_vertex( const std::unordered_map<vertex_id_t, vertex_id_t> &map) const { in_mem_directed_vertex<edge_data_type> *new_v = new in_mem_directed_vertex<edge_data_type>(*this); std::unordered_map<vertex_id_t, vertex_id_t>::const_iterator it = map.find(new_v->id); assert(it != map.end()); new_v->id = it->second; for (size_t i = 0; i < new_v->out_edges.size(); i++) { it = map.find(new_v->out_edges[i]); assert(it != map.end()); new_v->out_edges[i] = it->second; } for (size_t i = 0; i < new_v->in_edges.size(); i++) { it = map.find(new_v->in_edges[i]); assert(it != map.end()); new_v->in_edges[i] = it->second; } return in_mem_vertex::ptr(new_v); } virtual void remap( const std::unordered_map<vertex_id_t, vertex_id_t> &map) { std::unordered_map<vertex_id_t, vertex_id_t>::const_iterator it = map.find(this->id); assert(it != map.end()); this->id = it->second; for (size_t i = 0; i < this->out_edges.size(); i++) { it = map.find(this->out_edges[i]); assert(it != map.end()); this->out_edges[i] = it->second; } for (size_t i = 0; i < this->in_edges.size(); i++) { it = map.find(this->in_edges[i]); assert(it != map.end()); this->in_edges[i] = it->second; } } void print() const { printf("v%ld has edge data: %d\n", (unsigned long) get_id(), has_edge_data()); printf("There are %ld in-edges: ", in_edges.size()); for (size_t i = 0; i < in_edges.size(); i++) printf("%ld, ", (unsigned long) in_edges[i]); printf("\n"); printf("There are %ld out-edges: ", out_edges.size()); for (size_t i = 0; i < out_edges.size(); i++) printf("%ld, ", (unsigned long) out_edges[i]); printf("\n"); } }; template<class edge_data_type = empty_data> class in_mem_undirected_vertex: public in_mem_vertex { bool has_data; vertex_id_t id; std::vector<vertex_id_t> edges; std::vector<edge_data_type> data_arr; public: in_mem_undirected_vertex(vertex_id_t id, bool has_data) { this->id = id; this->has_data = has_data; } in_mem_undirected_vertex(const page_undirected_vertex &vertex, bool has_data) { this->id = vertex.get_id(); this->has_data = has_data; edges.resize(vertex.get_num_edges()); vertex.read_edges(edge_type::IN_EDGE, edges.data(), vertex.get_num_edges()); assert(!has_data); } vertex_id_t get_id() const { return id; } bool has_edge_data() const { return has_data; } size_t get_edge_data_size() const { return has_data ? sizeof(edge_data_type) : 0; } virtual void serialize_edges(vertex_id_t ids[], edge_type type) const { memcpy(ids, edges.data(), edges.size() * sizeof(ids[0])); } virtual void serialize_edge_data(char *data, edge_type type) const { memcpy(data, data_arr.data(), data_arr.size() * sizeof(edge_data_type)); } /* * Add an edge to the vertex. * We allow to have multiple same edges, but all edges must be added * in a sorted order. */ void add_edge(const edge<edge_data_type> &e) { assert(e.get_from() == id); if (!edges.empty()) assert(e.get_to() >= edges.back()); edges.push_back(e.get_to()); if (has_edge_data()) data_arr.push_back(e.get_data()); } size_t get_num_edges(edge_type type = edge_type::IN_EDGE) const { return edges.size(); } bool has_edge(vertex_id_t id) const { for (size_t i = 0; i < edges.size(); i++) if (edges[i] == id) return true; return false; } const edge<edge_data_type> get_edge(int idx) const { if (has_edge_data()) return edge<edge_data_type>(id, edges[idx], data_arr[idx]); else return edge<edge_data_type>(id, edges[idx]); } size_t get_serialize_size(edge_type type) const { ext_mem_undirected_vertex v(0, edges.size(), has_data ? sizeof(edge_data_type) : 0); return v.get_size(); } in_mem_vertex::ptr create_remapped_vertex( const std::unordered_map<vertex_id_t, vertex_id_t> &map) const { in_mem_undirected_vertex<edge_data_type> *new_v = new in_mem_undirected_vertex<edge_data_type>(*this); std::unordered_map<vertex_id_t, vertex_id_t>::const_iterator it = map.find(new_v->id); assert(it != map.end()); new_v->id = it->second; for (size_t i = 0; i < new_v->edges.size(); i++) { it = map.find(new_v->edges[i]); assert(it != map.end()); new_v->edges[i] = it->second; } return in_mem_vertex::ptr(new_v); } virtual void remap( const std::unordered_map<vertex_id_t, vertex_id_t> &map) { std::unordered_map<vertex_id_t, vertex_id_t>::const_iterator it = map.find(this->id); assert(it != map.end()); this->id = it->second; for (size_t i = 0; i < this->edges.size(); i++) { it = map.find(this->edges[i]); assert(it != map.end()); this->edges[i] = it->second; } } }; } #endif
27.04075
93
0.687191
[ "vector" ]
30fe8f60c1b0de39a45f83ed865d144b18982dfd
1,687
h
C
multimedia/command.h
metaplus/Gallery
d1b4b078e205c1145c0aac9b96c99f6d69470c3d
[ "MIT" ]
1
2019-09-19T11:07:42.000Z
2019-09-19T11:07:42.000Z
multimedia/command.h
metaplus/Gallery
d1b4b078e205c1145c0aac9b96c99f6d69470c3d
[ "MIT" ]
null
null
null
multimedia/command.h
metaplus/Gallery
d1b4b078e205c1145c0aac9b96c99f6d69470c3d
[ "MIT" ]
3
2019-02-28T07:32:18.000Z
2022-03-23T20:14:12.000Z
#pragma once #include <filesystem> namespace media { struct filter_param final { const int wcrop = 0; const int hcrop = 0; const int wscale = 1; const int hscale = 1; }; struct size_param final { const int width = 0; const int height = 0; }; struct rate_control final { const int bit_rate = 5000; const int frame_rate = 30; }; class command final { public: struct pace_control final { const int stride = 4; const int offset = 0; }; static inline std::filesystem::path input_directory; static inline std::filesystem::path output_directory; static inline auto wcrop = 0; static inline auto hcrop = 0; static inline auto wscale = 1; static inline auto hscale = 1; static void resize(std::string_view input, size_param size); static void crop_scale_transcode(std::filesystem::path input, rate_control rate = {}, pace_control pace = {}); static void crop_scale_package(std::filesystem::path input, int qp); static void package_container(rate_control rate); static void dash_segment(std::chrono::milliseconds duration); static void dash_segment(std::filesystem::path input, std::chrono::milliseconds duration); static std::filesystem::path merge_dash_mpd(); static std::vector<std::filesystem::path> tile_path_list(); }; }
26.359375
69
0.550089
[ "vector" ]
30fedb6157748f7119e555fd15d6ea547a21230a
3,431
h
C
Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasAssetHolder.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasAssetHolder.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/ScriptCanvas/Code/Editor/Assets/ScriptCanvasAssetHolder.h
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Component/EntityId.h> #include <AzCore/Asset/AssetCommon.h> #include <Editor/Assets/ScriptCanvasAssetTrackerBus.h> #include <ScriptCanvas/Bus/RequestBus.h> #include <ScriptCanvas/Core/Core.h> namespace ScriptCanvasEditor { class ScriptCanvasAsset; /*! ScriptCanvasAssetHolder Wraps a ScriptCanvasAsset reference and registers for the individual AssetBus events for saving, loading and unloading the asset. The ScriptCanvasAsset Holder contains functionality for activating the ScriptCanvasEntity stored on the reference asset as well as attempting to open the ScriptCanvasAsset within the ScriptCanvas Editor. It also provides the EditContext reflection for opening the asset in the ScriptCanvas Editor via a button */ class ScriptCanvasAssetHolder : AssetTrackerNotificationBus::Handler , AZ::Data::AssetBus::Handler { public: AZ_RTTI(ScriptCanvasAssetHolder, "{3E80CEE3-2932-4DC1-AADF-398FDDC6DEFE}"); AZ_CLASS_ALLOCATOR(ScriptCanvasAssetHolder, AZ::SystemAllocator, 0); using ScriptChangedCB = AZStd::function<void(AZ::Data::AssetId)>; ScriptCanvasAssetHolder() = default; ~ScriptCanvasAssetHolder() override; static void Reflect(AZ::ReflectContext* context); void Init(AZ::EntityId ownerId = AZ::EntityId(), AZ::ComponentId componentId = AZ::ComponentId()); const AZ::Data::AssetType& GetAssetType() const; void ClearAsset(); void SetAsset(AZ::Data::AssetId fileAssetId); AZ::Data::AssetId GetAssetId() const; ScriptCanvas::ScriptCanvasId GetScriptCanvasId() const; void LaunchScriptCanvasEditor(const AZ::Data::AssetId&, const AZ::Data::AssetType&) const; void OpenEditor() const; void SetScriptChangedCB(const ScriptChangedCB&); void Load(AZ::Data::AssetId fileAssetId); void LoadMemoryAsset(AZ::Data::AssetId fileAssetId); //! AZ::Data::AssetBus void OnAssetReady(AZ::Data::Asset<AZ::Data::AssetData> asset) override; //// const AZStd::string_view GetAssetHint() const { if (m_scriptCanvasAsset) { return m_scriptCanvasAsset.GetHint().c_str(); } if (m_memoryScriptCanvasAsset) { return m_memoryScriptCanvasAsset.GetHint().c_str(); } return ""; } protected: //===================================================================== // AssetTrackerNotificationBus void OnAssetReady(const ScriptCanvasMemoryAsset::pointer asset) override; //===================================================================== //! Reloads the Script From the AssetData if it has changed AZ::u32 OnScriptChanged(); AZ::Data::Asset<ScriptCanvasAsset> m_scriptCanvasAsset; AZ::Data::Asset<ScriptCanvasAsset> m_memoryScriptCanvasAsset; TypeDefs::EntityComponentId m_ownerId; // Id of Entity which stores this AssetHolder object ScriptChangedCB m_scriptNotifyCallback; bool m_triggeredLoad = false; }; }
34.656566
158
0.651414
[ "object", "3d" ]
a5084d7790910c356ee2854b50e7fafee1c231ad
3,189
c
C
ds/security/ntmarta/newsrc/event.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/ntmarta/newsrc/event.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/ntmarta/newsrc/event.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997 - 1997. // // File: EVENT.C // // Contents: Routines used by the event viewer to map GUIDs to names // // History: 25-Oct-97 CliffV Created // //---------------------------------------------------------------------------- #include <nt.h> #include <ntrtl.h> #include <nturtl.h> #include <windows.h> #include <rpc.h> #include <rpcdce.h> #include <lucache.h> DWORD EventGuidToName( IN LPCWSTR Source, IN LPCWSTR GuidString, OUT LPWSTR *NameString ) /*++ Routine Description: General purpose routine used by the event viewer to translate from a GUID in an event log message to a name of the GUID. This instance of the routine translates the following GUID types: Object Class Guids (e.g., user) Property set Guids (e.g., ATT_USER_PRINCIPLE_NAME) Property Guids (e.g., adminDisplayName) Object Guids (e.g., <DnsDomainName>/Users/<UserName>) Arguments: Source - Specifies the source of the GUID. The routine will use this field to differentiate between multiple sources potentially implemented by the routine. This instance of the routine requires the Source to be ACCESS_DS_SOURCE_W. GuidString - A string-ized version of the GUID to translate. The GUID should be in the form 33ff431c-4d78-11d1-b61a-00c04fd8ebaa. NameString - Returns the name that corresponds to the GUID. If the name cannot be found, a stringized version of the GUID is returned. The name should be freed by calling EventNameFree. Return Value: NO_ERROR - The Name was successfully translated. ERROR_NOT_ENOUGH_MEMORY - There was not enough memory to complete the operation. ERROR_INVALID_PARAMETER - Source is not supported. RPC_S_INVALID_STRING_UUID - Syntax of GuidString is invalid --*/ { DWORD dwErr; GUID Guid; // // Ensure the source is one we recognize. // if ( _wcsicmp( Source, ACCESS_DS_SOURCE_W) != 0 ) { return ERROR_INVALID_PARAMETER; } // // Convert the specified GUID to binary. // dwErr = UuidFromString((LPWSTR)GuidString, &Guid); if ( dwErr != NO_ERROR ) { return dwErr; } // // Convert the GUID to a name. // dwErr = AccctrlLookupIdName( NULL, // No existing LDAP handle L"", // Only the root path &Guid, TRUE, // Allocate the return buffer TRUE, // Handle individual object GUIDs NameString ); return dwErr; } VOID EventNameFree( IN LPCWSTR NameString ) /*++ Routine Description: Routine to free strings returned by EventNameFree. Arguments: NameString - Returns the name that corresponds to the GUID. Return Value: None. --*/ { LocalFree((PVOID)NameString); }
23.448529
85
0.580119
[ "object" ]
aa1b46d2d4b771fc30e903cce4f30096feb25e1d
1,578
h
C
public/r_efx.h
vxsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
14
2021-02-16T14:13:50.000Z
2022-03-17T18:29:19.000Z
public/r_efx.h
undbsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
7
2021-08-06T18:40:37.000Z
2022-03-09T18:05:08.000Z
public/r_efx.h
undbsd/refraction
bb6def1feb6c2e5c94b2604ad55607ed380a2d7e
[ "MIT" ]
2
2021-08-05T16:03:03.000Z
2021-11-26T00:11:27.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //===========================================================================// #if !defined ( EFXH ) #define EFXH #ifdef _WIN32 #pragma once #endif #include "iefx.h" class IMaterial; struct dlight_t; class CVEfx : public IVEfx { public: virtual ~CVEfx() {} virtual int Draw_DecalIndexFromName ( char *name ); virtual void DecalShoot ( int textureIndex, int entity, const model_t *model, const Vector& model_origin, const QAngle& model_angles, const Vector& position, const Vector *saxis, int flags); virtual void DecalColorShoot ( int textureIndex, int entity, const model_t *model, const Vector& model_origin, const QAngle& model_angles, const Vector& position, const Vector *saxis, int flags, const color32 &rgbaColor); virtual void PlayerDecalShoot ( IMaterial *material, void *userdata, int entity, const model_t *model, const Vector& model_origin, const QAngle& model_angles, const Vector& position, const Vector *saxis, int flags, const color32 &rgbaColor ); virtual dlight_t *CL_AllocDlight ( int key ); virtual dlight_t *CL_AllocElight ( int key ); virtual int CL_GetActiveDLights ( dlight_t *pList[MAX_DLIGHTS] ); virtual const char *Draw_DecalNameFromIndex ( int nIndex ); virtual dlight_t *GetElightByKey ( int key ); }; extern CVEfx *g_pEfx; #endif
40.461538
240
0.618504
[ "vector", "model" ]
aa1d8f1c03e48efc3816b22f2b36c41c4fa56092
7,009
h
C
lib/include/xnetwork/algorithms/assortativity/mixing.h
luk036/xnetwork
462c25da3aead6b834e6027f4d679dc47965b134
[ "MIT" ]
1
2020-03-31T06:10:58.000Z
2020-03-31T06:10:58.000Z
lib/include/xnetwork/algorithms/assortativity/mixing.h
luk036/xnetwork
462c25da3aead6b834e6027f4d679dc47965b134
[ "MIT" ]
null
null
null
lib/include/xnetwork/algorithms/assortativity/mixing.h
luk036/xnetwork
462c25da3aead6b834e6027f4d679dc47965b134
[ "MIT" ]
1
2020-04-08T05:56:26.000Z
2020-04-08T05:56:26.000Z
// -*- coding: utf-8 -*- /** Mixing matrices for node attributes && degree. */ #include <xnetwork.hpp> // as xn #include <xnetwork/utils.hpp> // import dict_to_numpy_array from xnetwork.algorithms.assortativity.pairs import node_degree_xy, \ node_attribute_xy __author__ = " ".join(["Wai-Shing Luk <luk036@gmail.com>"]); static const auto __all__ = ["attribute_mixing_matrix", "attribute_mixing_dict", "degree_mixing_matrix", "degree_mixing_dict", "numeric_mixing_matrix", "mixing_dict"]; auto attribute_mixing_dict(G, attribute, nodes=None, normalized=false) { /** Return dictionary representation of mixing matrix for attribute. Parameters ---------- G : graph XNetwork graph object. attribute : string Node attribute key. nodes: list || iterable (optional); Unse nodes : container to build the dict. The default is all nodes. normalized : bool (default=false); Return counts if (false || probabilities if (true. Examples -------- >>> G=xn::Graph(); >>> G.add_nodes_from([0,1],color="red"); >>> G.add_nodes_from([2,3],color="blue"); >>> G.add_edge(1,3); >>> d=xn::attribute_mixing_dict(G,"color"); >>> print(d["red"]["blue"]); 1 >>> print(d["blue"]["red"]) // d symmetric for undirected graphs 1 Returns ------- d : dictionary Counts || joint probability of occurrence of attribute pairs. */ xy_iter = node_attribute_xy(G, attribute, nodes); return mixing_dict(xy_iter, normalized=normalized); auto attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=true) { /** Return mixing matrix for attribute. Parameters ---------- G : graph XNetwork graph object. attribute : string Node attribute key. nodes: list || iterable (optional); Use only nodes : container to build the matrix. The default is all nodes. mapping : dictionary, optional Mapping from node attribute to integer index : matrix. If not specified, an arbitrary ordering will be used. normalized : bool (default=false); Return counts if (false || probabilities if (true. Returns ------- m: numpy array Counts || joint probability of occurrence of attribute pairs. */ d = attribute_mixing_dict(G, attribute, nodes); a = dict_to_numpy_array(d, mapping=mapping); if (normalized) { a = a / a.sum(); return a auto degree_mixing_dict(G, x="out", y="in", weight=None, nodes=None, normalized=false) { /** Return dictionary representation of mixing matrix for degree. Parameters ---------- G : graph XNetwork graph object. x: string ("in","out"); The degree type for source node (directed graphs only). y: string ("in","out"); The degree type for target node (directed graphs only). weight: string || None, optional (default=None); The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. normalized : bool (default=false); Return counts if (false || probabilities if (true. Returns ------- d: dictionary Counts || joint probability of occurrence of degree pairs. */ xy_iter = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight); return mixing_dict(xy_iter, normalized=normalized); auto degree_mixing_matrix(G, x="out", y="in", weight=None, nodes=None, normalized=true) { /** Return mixing matrix for attribute. Parameters ---------- G : graph XNetwork graph object. x: string ("in","out"); The degree type for source node (directed graphs only). y: string ("in","out"); The degree type for target node (directed graphs only). nodes: list || iterable (optional); Build the matrix using only nodes : container. The default is all nodes. weight: string || None, optional (default=None); The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. normalized : bool (default=false); Return counts if (false || probabilities if (true. Returns ------- m: numpy array Counts, || joint probability, of occurrence of node degree. */ d = degree_mixing_dict(G, x=x, y=y, nodes=nodes, weight=weight); s = set(d.keys()); for (auto k, v : d.items() { s.update(v.keys()); m = max(s); mapping = {x: x for x : range(m + 1)} a = dict_to_numpy_array(d, mapping=mapping); if (normalized) { a = a / a.sum(); return a auto numeric_mixing_matrix(G, attribute, nodes=None, normalized=true) { /** Return numeric mixing matrix for attribute. The attribute must be an integer. Parameters ---------- G : graph XNetwork graph object. attribute : string Node attribute key. The corresponding attribute must be an integer. nodes: list || iterable (optional); Build the matrix only with nodes : container. The default is all nodes. normalized : bool (default=false); Return counts if (false || probabilities if (true. Returns ------- m: numpy array Counts, || joint, probability of occurrence of node attribute pairs. */ d = attribute_mixing_dict(G, attribute, nodes); s = set(d.keys()); for (auto k, v : d.items() { s.update(v.keys()); m = max(s); mapping = {x: x for x : range(m + 1)} a = dict_to_numpy_array(d, mapping=mapping); if (normalized) { a = a / a.sum(); return a auto mixing_dict(xy, normalized=false) { /** Return a dictionary representation of mixing matrix. Parameters ---------- xy : list || container of two-tuples Pairs of (x,y) items. attribute : string Node attribute key normalized : bool (default=false); Return counts if (false || probabilities if (true. Returns ------- d: dictionary Counts || Joint probability of occurrence of values : xy. */ d = {}; psum = 0.0 for (auto x, y : xy) { if (x not : d) { d[x] = {}; if (y not : d) { d[y] = {}; v = d[x].get(y, 0); d[x][y] = v + 1 psum += 1; if (normalized) { for (auto k, jdict : d.items() { for (auto j : jdict) { jdict[j] /= psum return d // fixture for nose tests auto setup_module(module) { from nose import SkipTest try { import numpy except) { throw SkipTest("NumPy not available"); try { import scipy except) { throw SkipTest("SciPy not available");
27.924303
79
0.599515
[ "object" ]
aa1da59fe2b7d62f0d1ebc2092f9bf34eaf77993
752
h
C
oxygine/src/core/Restorable.h
sanyaade-teachings/oxygine-framework_back
6bbc9ba40e2bfb6c27c2ac008a434244c57b6df6
[ "MIT" ]
null
null
null
oxygine/src/core/Restorable.h
sanyaade-teachings/oxygine-framework_back
6bbc9ba40e2bfb6c27c2ac008a434244c57b6df6
[ "MIT" ]
null
null
null
oxygine/src/core/Restorable.h
sanyaade-teachings/oxygine-framework_back
6bbc9ba40e2bfb6c27c2ac008a434244c57b6df6
[ "MIT" ]
null
null
null
#pragma once #include "oxygine_include.h" #include "closure/closure.h" #include <vector> namespace oxygine { class Restorable { public: Restorable(); virtual ~Restorable(); typedef std::vector<Restorable*> restorable; static const restorable &getObjects(); static void restoreAll(); static void releaseAll(); virtual void *_getRestorableObject() = 0; virtual void release() = 0; void restore(); typedef Closure<void (Restorable *, void *userData)> RestoreCallback; void reg(RestoreCallback cb, void *user); void unreg(); protected: private: //non copyable Restorable(const Restorable&); const Restorable& operator=(const Restorable&); RestoreCallback _cb; void *_userData; bool _registered; }; }
19.282051
71
0.708777
[ "vector" ]