hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ee4d9f0b7691083c31bb579d2302827c41934c55
231
cpp
C++
src/lib/Target/Target.cpp
cgsdfc/Optimize
f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3
[ "MIT" ]
1
2019-07-13T16:40:47.000Z
2019-07-13T16:40:47.000Z
src/lib/Target/Target.cpp
cgsdfc/simplecc
f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3
[ "MIT" ]
null
null
null
src/lib/Target/Target.cpp
cgsdfc/simplecc
f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3
[ "MIT" ]
null
null
null
#include "simplecc/Target/Target.h" #include "simplecc/Target/MipsAssemblyWriter.h" namespace simplecc { void AssembleMips(const ByteCodeModule &M, std::ostream &O) { MipsAssemblyWriter().Write(M, O); } } // namespace simplecc
23.1
61
0.753247
cgsdfc
ee4e95dae0f7382b4b69d466655d7eade51f829a
12,371
cxx
C++
private/inet/mshtml/src/site/text/lsm2.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/site/text/lsm2.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/site/text/lsm2.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/* * LSM2.CXX -- CLSMeasurer class * * Authors: * Sujal Parikh * Chris Thrasher * Paul Parker * * History: * 2/27/98 sujalp created * * Copyright (c) 1997-1998 Microsoft Corporation. All rights reserved. */ #include "headers.hxx" #ifndef X_LSM_HXX_ #define X_LSM_HXX_ #include "lsm.hxx" #endif #ifndef X__FONT_H_ #define X__FONT_H_ #include "_font.h" #endif #ifndef X__DISP_H_ #define X__DISP_H_ #include "_disp.h" #endif #ifndef X_TREEPOS_HXX_ #define X_TREEPOS_HXX_ #include "treepos.hxx" #endif #ifndef X_NUMCONV_HXX_ #define X_NUMCONV_HXX_ #include "numconv.hxx" #endif #ifndef X_DOWNLOAD_HXX_ #define X_DOWNLOAD_HXX_ #include "download.hxx" #endif #ifndef X__FONTLNK_H_ #define X__FONTLNK_H_ #include "_fontlnk.h" #endif #ifndef X_OBJDIM_H_ #define X_OBJDIM_H_ #include <objdim.h> #endif #ifndef X_POBJDIM_H_ #define X_POBJDIM_H_ #include <pobjdim.h> #endif #ifndef X_HEIGHTS_H_ #define X_HEIGHTS_H_ #include <heights.h> #endif #ifndef X_FLOWLYT_HXX_ #define X_FLOWLYT_HXX_ #include <flowlyt.hxx> #endif #ifndef X_LINESRV_HXX_ #define X_LINESRV_HXX_ #include "linesrv.hxx" #endif ExternTag(tagDontReuseLinkFonts); #if DBG!=1 #pragma optimize(SPEED_OPTIMIZE_FLAGS, on) #endif //+---------------------------------------------------------------------------- // // Member: CLSMeasurer::Resync() // // Synopsis: This is temporary fn till we are using the CLSMeasurer and // CMeasurer. Essentiall does me = lsme // //----------------------------------------------------------------------------- void CLSMeasurer::Resync() { _cAlignedSites = _pLS->_cAlignedSites; _cAlignedSitesAtBeginningOfLine = _pLS->_cAlignedSitesAtBOL; _cchWhiteAtBeginningOfLine = _pLS->_cWhiteAtBOL; _fLastWasBreak = _pLS->_li._fHasBreak; } // Wrapper to tell if an element is a list item or not. inline BOOL IsListItem (CElement *pElement) { return !!pElement->HasFlag(TAGDESC_LISTITEM); } //+---------------------------------------------------------------------------- // Member: CLSMeasurer::MeasureListIndent() // // Synopsis: Compute and indent of line due to list properties (bullets and // numbering) in device units // //----------------------------------------------------------------------------- void CLSMeasurer::MeasureListIndent() { const CParaFormat *pPF; BOOL fInner = FALSE; // Keep retail compiler happy LONG dxOffset = 0; LONG dxPFOffset; pPF = MeasureGetPF(&fInner); dxPFOffset = pPF->GetBulletOffset(GetCalcInfo(), fInner); // Adjust the line height if the current line has a bullet or number if(_li._fHasBulletOrNum) { SIZE sizeImg; if (pPF->GetImgCookie(fInner) && MeasureImage(pPF->GetImgCookie(fInner), &sizeImg)) { // If we have an image cookie, try measuring the image. // If it has not come in yet or does not exist, fall through // to either bullet or number measuring. dxOffset = sizeImg.cx; // Adjust line height if necessary if(sizeImg.cy > _li._yHeight - _li._yDescent) _li._yHeight = sizeImg.cy + _li._yDescent; _li._yBulletHeight = sizeImg.cy; } else { switch (pPF->GetListing(fInner).GetType()) { case CListing::BULLET: MeasureSymbol(chDisc, &dxOffset); break; case CListing::NUMBERING: MeasureNumber(pPF, &dxOffset); break; } } dxOffset = max(dxOffset, LXTODX(LIST_FIRST_REDUCTION_TWIPS)); } if(dxOffset > dxPFOffset) { if (!pPF->HasRTL(fInner)) { _li._xLeft += dxOffset - dxPFOffset; } else { _li._xRight += dxOffset - dxPFOffset; } } } //+---------------------------------------------------------------------------- // // Member: CLSMeasurer::MeasureNumber(pxWidth, pyHeight) // // Synopsis: Computes number width and height (if any) // // Returns: number width and height // //----------------------------------------------------------------------------- void CLSMeasurer::MeasureNumber(const CParaFormat *ppf, LONG *pxWidth) { CCcs * pccs; CTreeNode * pNodeLI; pNodeLI = GetMarkup()->SearchBranchForTagInStory(GetPtp()->GetBranch(), ETAG_LI); Assert(pNodeLI && pNodeLI->Element()->IsTagAndBlock(ETAG_LI)); pccs = GetCcsNumber(pNodeLI->GetCharFormat()); AssertSz(pxWidth, "CLSMeasurer::MeasureNumber: invalid arg(s)"); Assert(pccs); // BUGBUG (cthrash) Currently we employ Netscape-sytle numbering. // This means we don't adjust for the size of the index value, // keeping the offset constant regardless of the size of the index value // string. *pxWidth = 0; if (pccs) { SHORT yAscent, yDescent; pccs->GetBaseCcs()->GetAscentDescent(&yAscent, &yDescent); _li._yBulletHeight = yAscent + yDescent; _pLS->RecalcLineHeight(pccs, &_li); pccs->Release(); } } //+---------------------------------------------------------------------------- // // Member: CLSMeasurer::GetCcsSymbol() (used for symbols & bullets) // // Synopsis: Get CCcs for symbol font // // Returns: ptr to symbol font CCcs // //----------------------------------------------------------------------------- // Default character format for a bullet static CCharFormat s_cfBullet; CCcs * CLSMeasurer::GetCcsSymbol( TCHAR chSymbol, const CCharFormat * pcf, CCharFormat * pcfRet) { CCcs * pccs = NULL; CCharFormat cf; CCharFormat * pcfUsed = (pcfRet != NULL) ? pcfRet : &cf; static BOOL s_fBullet = FALSE; if (!s_fBullet) { // N.B. (johnv) For some reason, Win95 does not render the Windings font properly // for certain characters at less than 7 points. Do not go below that size! s_cfBullet.SetHeightInTwips( TWIPS_FROM_POINTS ( 7 ) ); s_cfBullet._bCharSet = SYMBOL_CHARSET; s_cfBullet._fNarrow = FALSE; s_cfBullet._bPitchAndFamily = (BYTE) FF_DONTCARE; s_cfBullet._latmFaceName= fc().GetAtomWingdings(); s_cfBullet._bCrcFont = s_cfBullet.ComputeFontCrc(); s_fBullet = TRUE; } // Use bullet char format *pcfUsed = s_cfBullet; pcfUsed->_ccvTextColor = pcf->_ccvTextColor; // Since we always cook up the bullet character format, we don't need // to cache it. pccs = fc().GetCcs(_pci->_hdc, _pci, pcfUsed); // Important - CM_SYMBOL is a special mode where out WC chars are actually // zero-extended MB chars. This allows us to have a codepage-independent // call to ExTextOutA. (cthrash) pccs->GetBaseCcs()->_bConvertMode = CM_SYMBOL; #if DBG==1 if(!pccs) { TraceTag((tagError, "CRchMeasurer::GetCcsBullet(): no CCcs")); } #endif return pccs; } //+---------------------------------------------------------------------------- // // Member: CLSMeasurer::GetCcsNumber() // // Synopsis: Get CCcs for numbering font // // Returns: ptr to numbering CCcs // // Comment: The font for the number could change with every instance of a // number, because it is subject to the implied formatting of the // LI. // //----------------------------------------------------------------------------- CCcs * CLSMeasurer::GetCcsNumber ( const CCharFormat * pCF, CCharFormat * pCFRet) { CCharFormat cf = *pCF; cf._fSubscript = cf._fSuperscript = FALSE; cf._bCrcFont = cf.ComputeFontCrc(); if(pCFRet) *pCFRet = cf; return fc().GetCcs( _pci->_hdc, _pci, &cf ); } //+---------------------------------------------------------------------------- // // Member: CLSMeasurer::MeasureSymbol() // // Synopsis: Measures the special character in WingDings // // Returns: Nothing // // Note: that this function returns ascent of the font // rather than the entire height. This means that the // selected symbol (bullet) character should NOT have a descender. // //----------------------------------------------------------------------------- void CLSMeasurer::MeasureSymbol (TCHAR chSymbol, LONG *pxWidth) { const CCharFormat *pCF; LONG xWidthTemp; CTreeNode *pNode; CCcs *pccs; AssertSz(pxWidth, "CLSMeasurer::MeasureSymbol: invalid arg(s)"); pNode = GetMarkup()->SearchBranchForTagInStory(GetPtp()->GetBranch(), ETAG_LI); Assert(pNode && pNode->Element()->IsTagAndBlock(ETAG_LI)); pCF = pNode->GetCharFormat(); pccs = GetCcsSymbol(chSymbol, pCF); xWidthTemp = 0; if(pccs) { if(!pccs->Include(chSymbol, xWidthTemp)) { TraceTag((tagError, "CLSMeasurer::MeasureSymbol(): Error filling CCcs")); } xWidthTemp += pccs->GetBaseCcs()->_xUnderhang + pccs->GetBaseCcs()->_xOverhangAdjust; } *pxWidth = xWidthTemp; if (pccs) { SHORT yAscent, yDescent; CTreePos *ptpStart; _pFlowLayout->GetContentTreeExtent(&ptpStart, NULL); pccs->GetBaseCcs()->GetAscentDescent(&yAscent, &yDescent); _li._yBulletHeight = yAscent + yDescent; pccs->Release(); // Get the height of normal text in the site. // I had originally used the height of the LI, // but Netscape doesn't seem to do that. It's // possible that they actually have a fixed // height for the bullets. pCF = ptpStart->Branch()->GetCharFormat(); pccs = fc().GetCcs(_pci->_hdc, _pci, pCF); _pLS->RecalcLineHeight(pccs, &_li); pccs->Release(); } } BOOL CLSMeasurer::MeasureImage(long lImgCookie, SIZE * psizeImg) { CDoc * pDoc = _pFlowLayout->Doc(); CImgCtx * pImgCtx = pDoc->GetUrlImgCtx(lImgCookie); if (!pImgCtx || !(pImgCtx->GetState(FALSE, psizeImg) & IMGLOAD_COMPLETE)) { psizeImg->cx = psizeImg->cy = 0; return FALSE; } else if (pDoc->IsPrintDoc()) { CDoc * pRootDoc = pDoc->GetRootDoc(); psizeImg->cx = pRootDoc->_dci.DocPixelsFromWindowX(psizeImg->cx); psizeImg->cy = pRootDoc->_dci.DocPixelsFromWindowY(psizeImg->cy); } return TRUE; } //----------------------------------------------------------------------------- // // Member: TestForClear // // Synopsis: Tests if the clear bit is to be set and returns the result // //----------------------------------------------------------------------------- BOOL CLSMeasurer::TestForClear(const CMarginInfo *pMarginInfo, LONG cp, BOOL fShouldMarginsExist, const CFancyFormat *pFF) { // // If margins are not necessary for clear to be turned on, then lets ignore it // and just check the flags inside the char format. Bug 47575 shows us that // if clear has been applied to BR's and that line contains a aligned image, then // the margins have not been setup yet (since the image will be measure // *after* the line is measured. However, if we do not turn on clear left/right // here then we will never clear the margins! // BOOL fClearLeft = (!fShouldMarginsExist || pMarginInfo->HasLeftMargin()) && pFF->_fClearLeft; BOOL fClearRight = (!fShouldMarginsExist || pMarginInfo->HasRightMargin()) && pFF->_fClearRight; if (cp >= 0) { Assert(_pLS); if (fClearLeft) _pLS->_lineFlags.AddLineFlag(cp, FLAG_HAS_CLEARLEFT); if (fClearRight) _pLS->_lineFlags.AddLineFlag(cp, FLAG_HAS_CLEARRIGHT); } return fClearLeft || fClearRight; } #pragma optimize("", on)
28.504608
118
0.551451
King0987654
ee4f9451e5c2fe79d28325d67392fbca9a4a82f1
640
cpp
C++
src/arithmetic/extractor/field.cpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
2
2016-06-01T14:44:21.000Z
2018-05-04T11:55:02.000Z
src/arithmetic/extractor/field.cpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
1
2021-03-21T11:36:18.000Z
2021-03-21T14:49:17.000Z
src/arithmetic/extractor/field.cpp
r3c/tesca
e5ea2f4f2c4a35c47f38468a89f2f05038fb18d8
[ "MIT" ]
null
null
null
#include "field.hpp" using namespace Glay; using namespace Tesca::Provision; using namespace Tesca::Storage; using namespace std; namespace Tesca { namespace Arithmetic { FieldExtractor::FieldExtractor (Int32u field, const string& name) : field (field), name (name) { } string FieldExtractor::createName (Int32u) const { return this->name; } Int32u FieldExtractor::getFlags () const { return SCALAR; } Variant FieldExtractor::collect (Aggregator const* const*) const { return Variant::empty; } Variant FieldExtractor::extract (Row const& row) const { return row[this->field]; } } }
16
69
0.690625
r3c
ee52087b5f15639c23b8b0853e576457605c9c47
4,953
cpp
C++
src/EDAF80/assignment1.cpp
4onen/CG_Labs
ad6feb1aa0a301b8d2bf5a6e2dee0ca2d8948b89
[ "MIT" ]
null
null
null
src/EDAF80/assignment1.cpp
4onen/CG_Labs
ad6feb1aa0a301b8d2bf5a6e2dee0ca2d8948b89
[ "MIT" ]
null
null
null
src/EDAF80/assignment1.cpp
4onen/CG_Labs
ad6feb1aa0a301b8d2bf5a6e2dee0ca2d8948b89
[ "MIT" ]
null
null
null
#include "config.hpp" #include "core/FPSCamera.h" #include "core/helpers.hpp" #include "core/Log.h" #include "core/LogView.h" #include "core/Misc.h" #include "core/node.hpp" #include "core/ShaderProgramManager.hpp" #include "core/WindowManager.hpp" #include <imgui.h> #include <external/imgui_impl_glfw_gl3.h> #include <stack> #include <cstdlib> int main() { // // Set up the logging system // Log::Init(); Log::View::Init(); // // Set up the camera // InputHandler input_handler; FPSCameraf camera(0.5f * glm::half_pi<float>(), static_cast<float>(config::resolution_x) / static_cast<float>(config::resolution_y), 0.01f, 1000.0f); camera.mWorld.SetTranslate(glm::vec3(0.0f, 0.0f, 6.0f)); camera.mMouseSensitivity = 0.003f; camera.mMovementSpeed = 0.25f * 12.0f; // // Set up the windowing system and create the window // WindowManager window_manager; WindowManager::WindowDatum window_datum{ input_handler, camera, config::resolution_x, config::resolution_y, 0, 0, 0, 0}; GLFWwindow* window = window_manager.CreateWindow("EDAF80: Assignment 1", window_datum, config::msaa_rate); if (window == nullptr) { LogError("Failed to get a window: exiting."); Log::View::Destroy(); Log::Destroy(); return EXIT_FAILURE; } // // Load the sphere geometry // std::vector<bonobo::mesh_data> const objects = bonobo::loadObjects("sphere.obj"); if (objects.empty()) { LogError("Failed to load the sphere geometry: exiting."); Log::View::Destroy(); Log::Destroy(); return EXIT_FAILURE; } bonobo::mesh_data const& sphere = objects.front(); // // Create the shader program // ShaderProgramManager program_manager; GLuint shader = 0u; program_manager.CreateAndRegisterProgram({ { ShaderType::vertex, "EDAF80/default.vert" }, { ShaderType::fragment, "EDAF80/default.frag" } }, shader); if (shader == 0u) { LogError("Failed to generate the shader program: exiting."); Log::View::Destroy(); Log::Destroy(); return EXIT_FAILURE; } // // Set up the sun node and other related attributes // Node sun_node; sun_node.set_geometry(sphere); GLuint const sun_texture = bonobo::loadTexture2D("sunmap.png"); sun_node.add_texture("diffuse_texture", sun_texture, GL_TEXTURE_2D); float const sun_spin_speed = glm::two_pi<float>() / 6.0f; // Full rotation in six seconds Node solar_system_node; solar_system_node.add_child(&sun_node); // // TODO: Create nodes for the remaining of the solar system // // Retrieve the actual framebuffer size: for HiDPI monitors, you might // end up with a framebuffer larger than what you actually asked for. // For example, if you ask for a 1920x1080 framebuffer, you might get a // 3840x2160 one instead. int framebuffer_width, framebuffer_height; glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height); glViewport(0, 0, framebuffer_width, framebuffer_height); glClearDepthf(1.0f); glClearColor(0.2f, 0.2f, 0.2f, 1.0f); glEnable(GL_DEPTH_TEST); size_t fpsSamples = 0; double lastTime = GetTimeSeconds(); double fpsNextTick = lastTime + 1.0; bool show_logs = true; bool show_gui = true; while (!glfwWindowShouldClose(window)) { // // Compute timings information // double const nowTime = GetTimeSeconds(); double const delta_time = nowTime - lastTime; lastTime = nowTime; if (nowTime > fpsNextTick) { fpsNextTick += 1.0; fpsSamples = 0; } ++fpsSamples; // // Process inputs // glfwPollEvents(); ImGuiIO const& io = ImGui::GetIO(); input_handler.SetUICapture(io.WantCaptureMouse, io.WantCaptureKeyboard); input_handler.Advance(); camera.Update(delta_time, input_handler); if (input_handler.GetKeycodeState(GLFW_KEY_F3) & JUST_RELEASED) show_logs = !show_logs; if (input_handler.GetKeycodeState(GLFW_KEY_F2) & JUST_RELEASED) show_gui = !show_gui; // // Start a new frame for Dear ImGui // ImGui_ImplGlfwGL3_NewFrame(); // // Clear the screen // glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); // // Update the transforms // sun_node.rotate_y(sun_spin_speed * delta_time); // // Traverse the scene graph and render all nodes // std::stack<Node const*> node_stack({ &solar_system_node }); std::stack<glm::mat4> matrix_stack({ glm::mat4(1.0f) }); // TODO: Replace this explicit rendering of the Sun with a // traversal of the scene graph and rendering of all its nodes. sun_node.render(camera.GetWorldToClipMatrix(), sun_node.get_transform(), shader, [](GLuint /*program*/){}); // // Display Dear ImGui windows // if (show_logs) Log::View::Render(); if (show_gui) ImGui::Render(); // // Queue the computed frame for display on screen // glfwSwapBuffers(window); } glDeleteTextures(1, &sun_texture); Log::View::Destroy(); Log::Destroy(); return EXIT_SUCCESS; }
23.927536
121
0.689077
4onen
ee55801fc43b3bf8df2fab55ee9f5b95846d4c04
27,701
cpp
C++
SOURCES/graphics/renderer/render3d.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/graphics/renderer/render3d.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/graphics/renderer/render3d.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
/***************************************************************************\ Render3D.cpp Scott Randolph December 29, 1995 //JAM 08Jan04 - Begin Major Rewrite \***************************************************************************/ #include <math.h> #include "falclib/include/debuggr.h" #include "StateStack.h" #include "ObjectInstance.h" #include "Matrix.h" #include "Render3D.h" extern float g_fDefaultFOV; //Wombat778 10-31-2003 #include "Graphics/DXEngine/DXEngine.h" #include "Graphics/DXEngine/DXTools.h" extern bool g_bUse_DX_Engine; /***************************************************************************\ Setup the rendering context for thiw view \***************************************************************************/ void Render3D::Setup( ImageBuffer *imageBuffer ) { Tpoint pos; horizontal_half_angle = PI/180.0f; // this is used in the 2d setup call detailScaler = 1.0f; SetFar( 10000.0f ); // Call our parents Setup code (win is available only after this call) Render2D::Setup( imageBuffer ); SetFOV( 60.0f * PI / 180.0f ); // Intialize our camera parameters to something reasonable pos.x = pos.y = pos.z = 0.0f; SetCamera( &pos, &IMatrix ); // Put a default light source into the 3D object drawing context //JAM 08Jan04 lightAmbient = 0.4f; lightDiffuse = 0.6f; lightSpecular = 0.6f; //JAM Tpoint dir = { 0.0f, 0.0f, -1.0f }; SetLightDirection(&dir); objTextureState = TRUE; } /***************************************************************************\ Do start of frame housekeeping \***************************************************************************/ void Render3D::StartDraw( void ) { // DX - YELLOW BUG FIX - RED Render2D::StartDraw(); TheStateStack.SetContext( &context ); TheStateStack.SetCameraProperties( oneOVERtanHFOV, oneOVERtanVFOV, scaleX, scaleY, shiftX, shiftY ); TheStateStack.SetLight(lightAmbient,lightDiffuse,lightSpecular,&lightVector); //JAM 08Jan04 TheStateStack.SetLODBias( resRelativeScaler ); TheStateStack.SetTextureState( TRUE );//objTextureState ); TheColorBank.SetColorMode( ColorBankClass::NormalMode ); } /***************************************************************************\ Set the dimensions and location of the viewport. \***************************************************************************/ void Render3D::SetViewport( float l, float t, float r, float b ) { // First call the base class's version of this function Render2D::SetViewport( l, t, r, b ); // Redo our FOV dependent setup SetFOV(GetFOV()); } /***************************************************************************\ Set the field of view of this camera. \***************************************************************************/ void Render3D::SetFOV( float horizontal_fov, float NearZ) { const float maxHalfFOV = 70 * PI/180.0f; // JB 010120 Allow narrower field of views for Mavs and GBUs //const float minHalfFOV = 2 * PI/180.0f; //const float minHalfFOV = PI/180.0f; //MI need to be able to go higher for the TGP const float minHalfFOV = (PI/180.0f) / 4; // JB 010120 // Set the field of view horizontal_half_angle = horizontal_fov / 2.0f; // Keep the field of view values within a reasonable range if (horizontal_half_angle > maxHalfFOV) { horizontal_half_angle = maxHalfFOV; } else if (horizontal_half_angle < minHalfFOV) { horizontal_half_angle = minHalfFOV; } // Recompute the vertical and diangonal field of views to retain consistency // NOTE: (Computation of vertical and diagonal ASSUMES SQUARE PIXELS) if (scaleX) { vertical_half_angle = (float)atan2( scaleY * tan(horizontal_half_angle), scaleX ); diagonal_half_angle = (float)atan2( sqrt(scaleX*scaleX+scaleY*scaleY) * tan(horizontal_half_angle), scaleX ); } else { vertical_half_angle = (float)atan2( 3.0f * tan(horizontal_half_angle), 4.0f ); diagonal_half_angle = (float)atan2( 5.0f * tan(horizontal_half_angle), 4.0f ); } oneOVERtanHFOV = 1.0f / (float)tan(horizontal_half_angle); oneOVERtanVFOV = 1.0f / (float)tan(vertical_half_angle); SetObjectDetail( detailScaler ); // Send relevant stuff to the BSP object library TheStateStack.SetCameraProperties( oneOVERtanHFOV, oneOVERtanVFOV, scaleX, scaleY, shiftX, shiftY ); // COBRA - DX - Setu up Projection here if(g_bUse_DX_Engine){ // Default FOV D3DXMATRIX matProj; D3DXMatrixPerspectiveFov(&matProj, PI/2, (float)(xRes/yRes), NearZ, context.ZFAR); // Original Falcon FOV transformation matProj.m10*=oneOVERtanVFOV; matProj.m11*=oneOVERtanVFOV; matProj.m12*=oneOVERtanVFOV; matProj.m00*=oneOVERtanHFOV; matProj.m01*=oneOVERtanHFOV; matProj.m02*=oneOVERtanHFOV; D3DXMATRIX Flip; ZeroMemory(&Flip,sizeof(Flip)); Flip.m02=-1.0f; Flip.m21=-1.0f; Flip.m10=1.0f; Flip.m33=1.0f; D3DXMatrixMultiply(&matProj,&Flip,&matProj); TheDXEngine.SetProjection(&matProj); } } /***************************************************************************\ Set the position and orientation of the camera in world space. (Note: we're storing the inverse of the camera rotation) \***************************************************************************/ void Render3D::SetCamera( const Tpoint* pos, const Trotation* rot ) { float sinRoll, cosRoll; float sinPitch, cosPitch; // Store the provided position and orientation if (rot){ memcpy( &cameraPos, pos, sizeof( cameraPos ) ); MatrixTranspose( rot, &cameraRot ); } // Back compute the roll, pitch, and yaw of the viewer pitch = (float)-asin( cameraRot.M13 ); roll = (float)atan2( cameraRot.M23, cameraRot.M33 ); yaw = (float)atan2( cameraRot.M12, cameraRot.M11 ); if (yaw < 0.0f){ yaw += 2.0f * PI; // Convert from +/-180 to 0-360 degrees } // The result of multiplying a point by this matrix will be permuted into // screen space by renaming the components of the output vector // (after this, plus X will be to the right and plus Y will be down the screen) // Output x axis corresponds to row 2 // Output y axis corresponds to row 3 // Output z axis corresponds to row 1 // In this matrix, we also scale output x and y to account for the field of view. // Now |X| > Z or |Y| > Z are out T.M11 = cameraRot.M11; T.M12 = cameraRot.M12; T.M13 = cameraRot.M13; T.M21 = cameraRot.M21 * oneOVERtanHFOV; T.M22 = cameraRot.M22 * oneOVERtanHFOV; T.M23 = cameraRot.M23 * oneOVERtanHFOV; T.M31 = cameraRot.M31 * oneOVERtanVFOV; T.M32 = cameraRot.M32 * oneOVERtanVFOV; T.M33 = cameraRot.M33 * oneOVERtanVFOV; // Compute the vector from the camera to the origin rotated into camera space move.x = - cameraPos.x * T.M11 - cameraPos.y * T.M12 - cameraPos.z * T.M13; move.y = - cameraPos.x * T.M21 - cameraPos.y * T.M22 - cameraPos.z * T.M23; move.z = - cameraPos.x * T.M31 - cameraPos.y * T.M32 - cameraPos.z * T.M33; // Build the billboard matrix (appropriate for Erick's row vector object library) sinRoll = (float)sin( roll ); cosRoll = (float)cos( roll ); Tbb.M11 = 1.0f; Tbb.M21 = 0.0f; Tbb.M31 = 0.0f; Tbb.M12 = 0.0f; Tbb.M22 = cosRoll*oneOVERtanHFOV; Tbb.M32 = -sinRoll*oneOVERtanVFOV; Tbb.M13 = 0.0f; Tbb.M23 = sinRoll*oneOVERtanHFOV; Tbb.M33 = cosRoll*oneOVERtanVFOV; // Build the tree matrix sinPitch = (float)sin( pitch ); cosPitch = (float)cos( pitch ); Tt.M11 = cosPitch; Tt.M21 = sinPitch*Tbb.M23; Tt.M31 = sinPitch*Tbb.M33; Tt.M12 = 0.0f; Tt.M22 = Tbb.M22; Tt.M32 = Tbb.M32; Tt.M13 = -sinPitch; Tt.M23 = cosPitch*Tbb.M23; Tt.M33 = cosPitch*Tbb.M33; // Send relevant stuff to the BSP object library if(g_bUse_DX_Engine){ D3DXMATRIX a,c; Pmatrix b; D3DXMatrixRotationY(&a, pitch); D3DXMatrixRotationZ(&c, yaw); D3DXMatrixMultiply(&a, &a, &c); AssignD3DXMATRIXToPmatrix(&b, &a ); TheStateStack.SetCamera(pos,(Pmatrix*)&cameraRot,(Pmatrix*)&b,&Tt); } else { TheStateStack.SetCamera(pos,&T,&Tbb,&Tt); } //JAM 02Jan04 TheStateStack.SetView(pos,&cameraRot); TheStateStack.SetProjection(horizontal_half_angle*2.f,(float)(xRes/yRes)); } /***************************************************************************\ Set the detail adjustment scaler for objects \***************************************************************************/ void Render3D::SetObjectDetail( float scaler ) { // This constant is set based on the design resolution for the visual objects // art work. Specificly, 60 degree field of view // on a display 640 pixels across. This is our reference display // precision, or LOD scale 1.0. static const float RadiansPerPixel = (60.0f * PI / 180.0f) / 640; // Ignor invalid parameters if (scaler <= 0.0f) { return; } detailScaler = scaler; resRelativeScaler = detailScaler * RadiansPerPixel * scaleX * oneOVERtanHFOV; TheStateStack.SetLODBias( resRelativeScaler ); } /***************************************************************************\ Set the lighting direction (based on a Falcon 4 X north, Y east, Z down coordinate system) \***************************************************************************/ void Render3D::SetLightDirection( const Tpoint* dir ) { lightVector = *dir; TheStateStack.SetLight(lightAmbient,lightDiffuse,lightSpecular,&lightVector); //JAM 08Jan04 } /***************************************************************************\ Get the lighting direction (based on a Falcon 4 X north, Y east, Z down coordinate system) \***************************************************************************/ void Render3D::GetLightDirection( Tpoint* dir ) { *dir = lightVector; } /***************************************************************************\ Select the amount of textureing employed \***************************************************************************/ void Render3D::SetObjectTextureState( BOOL state ) { if (state != objTextureState) { // Record the choice objTextureState = state; // Update the object library // NOTE: If any other renderer is inside a StartFrame, this will clobber their settings TheStateStack.SetTextureState( objTextureState ); } } /***************************************************************************\ Transform the given point (from World space to Screen space) \***************************************************************************/ void Render3D::TransformPoint( Tpoint* p, ThreeDVertex* result ) { register float scratch_x; register float scratch_y; register float scratch_z; register DWORD clipFlag; // This part does rotation, translation, and scaling // Note, we're swapping the x and z axes here to get from z up/down to z far/near // then we're swapping the x and y axes to get into conventional screen pixel coordinates scratch_z = T.M11 * p->x + T.M12 * p->y + T.M13 * p->z + move.x; scratch_x = T.M21 * p->x + T.M22 * p->y + T.M23 * p->z + move.y; scratch_y = T.M31 * p->x + T.M32 * p->y + T.M33 * p->z + move.z; // Now determine if the point is out behind us or to the sides clipFlag = GetRangeClipFlags( scratch_z, far_clip ); clipFlag |= GetHorizontalClipFlags( scratch_x, scratch_z ); clipFlag |= GetVerticalClipFlags( scratch_y, scratch_z ); // Finally, do the perspective divide and scale and shift into screen space register float OneOverZ = 1.0f/scratch_z; result->csX = scratch_x; result->csY = scratch_y; result->csZ = scratch_z; result->x = viewportXtoPixel( scratch_x * OneOverZ ); result->y = viewportYtoPixel( scratch_y * OneOverZ ); result->clipFlag = clipFlag; } /***************************************************************************\ Transform the given point (from World space to Screen space) The point should be camera-centric: ie has the camera XYZ subtracted out of its world space XYZ. Why have this function? Because of floating point roundoff error. We may want a high-precision transform of a world space point that would otherwise get rounded off if the world space point had high-range XYZ values. \***************************************************************************/ void Render3D::TransformCameraCentricPoint( Tpoint* p, ThreeDVertex* result ) { register float scratch_x; register float scratch_y; register float scratch_z; register DWORD clipFlag; // This part does rotation, translation, and scaling // Note, we're swapping the x and z axes here to get from z up/down to z far/near // then we're swapping the x and y axes to get into conventional screen pixel coordinates scratch_z = T.M11 * p->x + T.M12 * p->y + T.M13 * p->z; scratch_x = T.M21 * p->x + T.M22 * p->y + T.M23 * p->z; scratch_y = T.M31 * p->x + T.M32 * p->y + T.M33 * p->z; // Now determine if the point is out behind us or to the sides clipFlag = GetRangeClipFlags( scratch_z, far_clip ); clipFlag |= GetHorizontalClipFlags( scratch_x, scratch_z ); clipFlag |= GetVerticalClipFlags( scratch_y, scratch_z ); // Finally, do the perspective divide and scale and shift into screen space register float OneOverZ = 1.0f/scratch_z; result->csX = scratch_x; result->csY = scratch_y; result->csZ = scratch_z; result->x = viewportXtoPixel( scratch_x * OneOverZ ); result->y = viewportYtoPixel( scratch_y * OneOverZ ); result->clipFlag = clipFlag; } /***************************************************************************\ Transform the given point (from World space to View space) \***************************************************************************/ void Render3D::TransformPointToView( Tpoint * p, Tpoint * result ) { // This part does rotation, translation, and scaling // no swapping... result->x = T.M11 * p->x + T.M12 * p->y + T.M13 * p->z + move.x; result->y = T.M21 * p->x + T.M22 * p->y + T.M23 * p->z + move.y; result->z = T.M31 * p->x + T.M32 * p->y + T.M33 * p->z + move.z; } //JAM 03Dec03 void Render3D::TransformPointToViewSwapped(Tpoint *p, Tpoint *result) { result->z = T.M11 * p->x + T.M12 * p->y + T.M13 * p->z + move.x; result->x = T.M21 * p->x + T.M22 * p->y + T.M23 * p->z + move.y; result->y = T.M31 * p->x + T.M32 * p->y + T.M33 * p->z + move.z; } /***************************************************************************\ Transform the given point (from World space to Screen space) Uses billboard matrix. Most of this is just duplicatcion of TransformPoint and perhaps should be condensed into 1 function \***************************************************************************/ void Render3D::TransformBillboardPoint( Tpoint* p, Tpoint *viewOffset, ThreeDVertex* result ) { register float scratch_x; register float scratch_y; register float scratch_z; register DWORD clipFlag; // This part does rotation, translation, and scaling // Note, we're swapping the x and z axes here to get from z up/down to z far/near // then we're swapping the x and y axes to get into conventional screen pixel coordinates // Note: since this is a billboard we don't have to do the full: // scratch_z = T.M11 * p->x + T.M12 * p->y + T.M13 * p->z + move.x; // scratch_x = T.M21 * p->x + T.M22 * p->y + T.M23 * p->z + move.y; // scratch_y = T.M31 * p->x + T.M32 * p->y + T.M33 * p->z + move.z; // since we know where some 1's and 0's are scratch_z = p->x + viewOffset->x; scratch_x = Tbb.M22 * p->y + Tbb.M23 * p->z + viewOffset->y; scratch_y = Tbb.M32 * p->y + Tbb.M33 * p->z + viewOffset->z; // Now determine if the point is out behind us or to the sides clipFlag = GetRangeClipFlags( scratch_z, far_clip ); clipFlag |= GetHorizontalClipFlags( scratch_x, scratch_z ); clipFlag |= GetVerticalClipFlags( scratch_y, scratch_z ); // Finally, do the perspective divide and scale and shift into screen space register float OneOverZ = 1.0f/scratch_z; result->csX = scratch_x; result->csY = scratch_y; result->csZ = scratch_z; result->x = viewportXtoPixel( scratch_x * OneOverZ ); result->y = viewportYtoPixel( scratch_y * OneOverZ ); result->clipFlag = clipFlag; } /***************************************************************************\ Transform the given point (from World space to Screen space) Uses tree matrix. Most of this is just duplicatcion of TransformPoint and perhaps should be condensed into 1 function \***************************************************************************/ void Render3D::TransformTreePoint( Tpoint* p, Tpoint *viewOffset, ThreeDVertex* result ) { register float scratch_x; register float scratch_y; register float scratch_z; register DWORD clipFlag; // This part does rotation, translation, and scaling // Note, we're swapping the x and z axes here to get from z up/down to z far/near // then we're swapping the x and y axes to get into conventional screen pixel coordinates scratch_z = Tt.M11 * p->x + Tt.M12 * p->y + Tt.M13 * p->z + viewOffset->x; scratch_x = Tt.M21 * p->x + Tt.M22 * p->y + Tt.M23 * p->z + viewOffset->y; scratch_y = Tt.M31 * p->x + Tt.M32 * p->y + Tt.M33 * p->z + viewOffset->z; // Now determine if the point is out behind us or to the sides clipFlag = GetRangeClipFlags( scratch_z, far_clip ); clipFlag |= GetHorizontalClipFlags( scratch_x, scratch_z ); clipFlag |= GetVerticalClipFlags( scratch_y, scratch_z ); // Finally, do the perspective divide and scale and shift into screen space register float OneOverZ = 1.0f/scratch_z; result->csX = scratch_x; result->csY = scratch_y; result->csZ = scratch_z; result->x = viewportXtoPixel( scratch_x * OneOverZ ); result->y = viewportYtoPixel( scratch_y * OneOverZ ); result->clipFlag = clipFlag; } /***************************************************************************\ Reverse transform the given point (from screen space to world space vector) \***************************************************************************/ void Render3D::UnTransformPoint( Tpoint* p, Tpoint* result ) { float scratch_x, scratch_y, scratch_z; float x, y, z; float mag; // Undo the viewport computations to get normalized screen coordinates scratch_x = (p->x - shiftX) / scaleX; scratch_y = (p->y - shiftY) / scaleY; scratch_z = 1.0f; // Assume the distance from the viewer is 1.0 -- we'll normalize later // This means we don't have to undo the perspective divide // Now undo the field of view scale applied in the transformation scratch_x /= oneOVERtanHFOV; scratch_y /= oneOVERtanVFOV; // Undo the camera rotation (apply the inverse rotation) x = cameraRot.M11*scratch_z + cameraRot.M21*scratch_x + cameraRot.M31*scratch_y; y = cameraRot.M12*scratch_z + cameraRot.M22*scratch_x + cameraRot.M32*scratch_y; z = cameraRot.M13*scratch_z + cameraRot.M23*scratch_x + cameraRot.M33*scratch_y; // Don't need to undo the camera translation, because we want a vector // Lets normalize just to be kind mag = x*x + y*y + z*z; mag = 1.0f / (float)sqrt( mag ); result->x = x * mag; result->y = y * mag; result->z = z * mag; } /***************************************************************************\ Return the distance of the world space point from the camera plane. A negative result indicates the point is behind the camera. \***************************************************************************/ float Render3D::ZDistanceFromCamera( Tpoint* p ) { // This part does rotation, translation, and scaling // Note, we're swapping the x and z axes here to get from z up/down to z far/near // then we're swapping the x and y axes to get into conventional screen pixel coordinates. // Here we only care about the Z axis since that is the distance from the viewer. return ((T.M11 * p->x) + (T.M12 * p->y) + (T.M13 * p->z) + move.x); } /*******************************************************************************************\ Immediatly draw the specified object. Warning: Going this route causes the specfied object to be loaded/unloaded each time it is drawn. Besides being wasteful, this may result in too simple an LOD, no textures, or nothing being drawn because the data will not have arrived from disk by the time the Draw call happens. A prior LockAndLoad() call could avoid these problems. \*******************************************************************************************/ void Render3D::Render3DObject( int id, Tpoint* pos, const Trotation* orientation ) { ShiAssert( IsReady() ); ObjectInstance instance( id ); TheStateStack.DrawObject( &instance, orientation, pos ); } /***************************************************************************\ Draw a colored pixel in worldspace using the current camera. For now, we don't try to draw primitives with any verticies off screen. \***************************************************************************/ void Render3D::Render3DPoint( Tpoint* p1 ) { ThreeDVertex ps1; // Transform the point from world space to window space TransformPoint( p1, &ps1 ); if ( ps1.clipFlag != ON_SCREEN ) return; // Draw the point Render2DPoint( (UInt16)ps1.x, (UInt16)ps1.y ); } /***************************************************************************\ Draw a colored one pixel line in worldspace using the current camera. \***************************************************************************/ void Render3D::Render3DLine( Tpoint* p1, Tpoint* p2 ) { ThreeDVertex ps1, ps2; // Transform the points from world space to window space TransformPoint( p1, &ps1 ); TransformPoint( p2, &ps2 ); // Quit now if both ends are clipped by the same edge if (ps1.clipFlag & ps2.clipFlag) return; // Clip the line as necessary if (ps1.clipFlag & CLIP_NEAR) { IntersectNear( &ps1, &ps2, &ps1 ); } else if (ps2.clipFlag & CLIP_NEAR) { IntersectNear( &ps1, &ps2, &ps2 ); } if (ps1.clipFlag & ps2.clipFlag) return; if (ps1.clipFlag & CLIP_BOTTOM) { IntersectBottom( &ps1, &ps2, &ps1 ); } else if (ps2.clipFlag & CLIP_BOTTOM) { IntersectBottom( &ps1, &ps2, &ps2 ); } if (ps1.clipFlag & CLIP_TOP) { IntersectTop( &ps1, &ps2, &ps1 ); } else if (ps2.clipFlag & CLIP_TOP) { IntersectTop( &ps1, &ps2, &ps2 ); } if (ps1.clipFlag & ps2.clipFlag) return; if (ps1.clipFlag & CLIP_RIGHT) { IntersectRight( &ps1, &ps2, &ps1 ); } else if (ps2.clipFlag & CLIP_RIGHT) { IntersectRight( &ps1, &ps2, &ps2 ); } if (ps1.clipFlag & CLIP_LEFT) { IntersectLeft( &ps1, &ps2, &ps1 ); } else if (ps2.clipFlag & CLIP_LEFT) { IntersectLeft( &ps1, &ps2, &ps2 ); } // Draw the line Render2DLine( (UInt16)ps1.x, (UInt16)ps1.y, (UInt16)ps2.x, (UInt16)ps2.y ); } /***************************************************************************\ Draw a flat shaded triangle in worldspace using the current camera. For now, we don't try to draw primitives with any verticies inside the near plane. \***************************************************************************/ void Render3D::Render3DFlatTri( Tpoint* p1, Tpoint* p2, Tpoint* p3 ) { ThreeDVertex ps1, ps2, ps3; // Transform the points from world space to window space TransformPoint( p1, &ps1 ); TransformPoint( p2, &ps2 ); TransformPoint( p3, &ps3 ); // Skip the tri if clipped anywhere // I'm not sure this function is called anywhere anyway. With the current // state of things, just checking near clip could cause bad problems since // MPR no longer does other edge clipping. We'd have to do that here. if (ps1.clipFlag || ps2.clipFlag || ps3.clipFlag) return; // Don't draw the triangle if it is backfacing (counter-clockwise in screen space) // edg: always draw irregardless of backfacing /* if ( (ps2.y - ps1.y)*(ps3.x - ps1.x) > (ps2.x - ps1.x)*(ps3.y - ps1.y) ) { return; } */ // Draw the triangle Render2DTri( (UInt16)ps1.x, (UInt16)ps1.y, (UInt16)ps2.x, (UInt16)ps2.y, (UInt16)ps3.x, (UInt16)ps3.y ); } /***************************************************************************\ Draw a quad as a fan. Uses current state. Not required to be planar. \***************************************************************************/ void Render3D::DrawSquare(ThreeDVertex* v0, ThreeDVertex* v1, ThreeDVertex* v2, ThreeDVertex* v3, int CullFlag, bool gifPicture, bool terrain) //JAM 14Sep03 { unsigned short count; BOOL useFirst = TRUE; BOOL useLast = TRUE; // Check the clipping flags on the verteces which bound this region if(v0->clipFlag | v1->clipFlag | v2->clipFlag | v3->clipFlag) { // If all verticies are clipped by the same edge, skip this square if(v0->clipFlag & v1->clipFlag & v2->clipFlag & v3->clipFlag) return; ThreeDVertex *vertPointers[4]; vertPointers[2] = v2; // If any verteces are clipped, do separate triangles since the quad isn't necessarily planar if(v0->clipFlag | v1->clipFlag | v2->clipFlag) { vertPointers[0] = v0; vertPointers[1] = v1; ClipAndDraw3DFan(&vertPointers[0],3,CullFlag,gifPicture,terrain); //JAM 14Sep03 useFirst = FALSE; } if(v0->clipFlag | v2->clipFlag | v3->clipFlag) { vertPointers[1] = v0; vertPointers[3] = v3; ClipAndDraw3DFan(&vertPointers[1],3,CullFlag,gifPicture,terrain); //JAM 14Sep03 if(useFirst) useLast = FALSE; else return; } } if(CullFlag) { if(CullFlag == CULL_ALLOW_CW) { // Decide if either of the two triangles are back facing if (useFirst) { if(((v2->y - v1->y))*((v0->x - v1->x)) > ((v2->x - v1->x)) * ((v0->y - v1->y))) useFirst = FALSE; } if(useLast) { if(((v0->y - v3->y))*((v2->x - v3->x)) > ((v0->x - v3->x)) * ((v2->y - v3->y))) useLast = FALSE; } } else { // Decide if either of the two triangles are back facing if(useFirst) { if(((v2->y - v1->y)) * ((v0->x - v1->x)) < ((v2->x - v1->x)) * ((v0->y - v1->y))) useFirst = FALSE; } if(useLast) { if(((v0->y - v3->y)) * ((v2->x - v3->x)) < ((v0->x - v3->x)) * ((v2->y - v3->y))) useLast = FALSE; } } } // If culling or clipping took care of both triangles, quit now if(useFirst && useLast) count = 4; else { if(useFirst || useLast) count = 3; else return; } if(useFirst) { MPRVtxTexClr_t *arr[] = { v0, v1, v2, v3 }; context.DrawPrimitive(MPR_PRM_TRIFAN,MPR_VI_COLOR|MPR_VI_TEXTURE,count,arr,terrain); //JAM 14Sep03 } else { MPRVtxTexClr_t *arr[] = { v0, v2, v3 }; context.DrawPrimitive(MPR_PRM_TRIFAN,MPR_VI_COLOR|MPR_VI_TEXTURE,count,arr,terrain); //JAM 14Sep03 } } /***************************************************************************\ Draw a triangle using current state \***************************************************************************/ void Render3D::DrawTriangle(ThreeDVertex* v0, ThreeDVertex* v1, ThreeDVertex* v2, int CullFlag, bool gifPicture, bool terrain ) //JAM 14Sep03 { // Check the clipping flags on the verteces which bound this region if(v0->clipFlag | v1->clipFlag | v2->clipFlag) { // If all verticies are clipped by the same edge, skip this triangle if(v0->clipFlag & v1->clipFlag & v2->clipFlag) return; // If any verteces are clipped, do them as a special case ThreeDVertex *vertPointers[3]; vertPointers[0] = v0; vertPointers[1] = v1; vertPointers[2] = v2; ClipAndDraw3DFan(vertPointers,3,CullFlag,gifPicture,terrain); //JAM 14Sep03 return; } if(CullFlag) { if(CullFlag == CULL_ALLOW_CW) { // Decide if back facing CW if(((v2->y - v1->y)) * ((v0->x - v1->x)) > ((v2->x - v1->x)) * ((v0->y - v1->y))) return; } else { // Decide if back facing CCW if(((v2->y - v1->y)) * ((v0->x - v1->x)) < ((v2->x - v1->x)) * ((v0->y - v1->y))) return; } } // Draw the tri MPRVtxTexClr_t *arr[] = { v0, v1, v2 }; context.DrawPrimitive(MPR_PRM_TRIFAN,MPR_VI_COLOR|MPR_VI_TEXTURE,3,arr,terrain); //JAM 14Sep03 }
34.756587
156
0.599798
IsraelyFlightSimulator
ee565e6c7a32c2569ed862d38e6d729e39a3317d
1,343
cpp
C++
test/test2.cpp
rpoisel/c-template
42960a5a72d7ee89aee34601950b7639e8f58055
[ "BSD-2-Clause" ]
1
2021-03-16T09:28:06.000Z
2021-03-16T09:28:06.000Z
test/test2.cpp
rpoisel/c-template
42960a5a72d7ee89aee34601950b7639e8f58055
[ "BSD-2-Clause" ]
null
null
null
test/test2.cpp
rpoisel/c-template
42960a5a72d7ee89aee34601950b7639e8f58055
[ "BSD-2-Clause" ]
1
2021-03-16T09:28:09.000Z
2021-03-16T09:28:09.000Z
#include <arithpp.h> #include <catch2/catch.hpp> #include <cmath> #include <limits> TEST_CASE("Assert empty calculator", "[require]") { Arith::Calculator calculator; REQUIRE(calculator.add() == 0); REQUIRE(std::isnan(calculator.divide()) == true); } TEST_CASE("Assert one element in calculator", "[require]") { Arith::Calculator calculator; calculator.push(5); REQUIRE(calculator.add() == 5); REQUIRE(calculator.divide() == 5); } TEST_CASE("Assert one element with value 0 in calculator", "[require]") { Arith::Calculator calculator; calculator.push(0); REQUIRE(calculator.add() == 0); REQUIRE(calculator.divide() == 0); } TEST_CASE("Assert two elements in calculator", "[require]") { Arith::Calculator calculator; calculator.push(5); calculator.push(2); REQUIRE(calculator.add() == 7); REQUIRE(calculator.divide() == 2.5); } TEST_CASE("Assert two elements with first of them 0 in calculator", "[require]") { Arith::Calculator calculator; calculator.push(0); calculator.push(5); REQUIRE(calculator.add() == 5); REQUIRE(calculator.divide() == 0); } TEST_CASE("Assert two elements with second of them 0 in calculator", "[require]") { Arith::Calculator calculator; calculator.push(5); calculator.push(0); REQUIRE(calculator.add() == 5); REQUIRE(std::isinf(calculator.divide())); }
21.66129
81
0.687267
rpoisel
ee56cafe19841d2937a8e7b75f728764ab3cd4ba
1,551
cpp
C++
testy/udpbroadcaster/udpbroadcaster.cpp
Wiladams/netops
80020d08b4fc1929ec51c5c8d3c138134dc97c04
[ "MIT" ]
null
null
null
testy/udpbroadcaster/udpbroadcaster.cpp
Wiladams/netops
80020d08b4fc1929ec51c5c8d3c138134dc97c04
[ "MIT" ]
null
null
null
testy/udpbroadcaster/udpbroadcaster.cpp
Wiladams/netops
80020d08b4fc1929ec51c5c8d3c138134dc97c04
[ "MIT" ]
null
null
null
/* Minimalist example of what's required to broadcast UDP packets on a network. You must minimally specify a port number You must also specify an address. By default, we're using the INADDR_BROADCAST address, so this will hit every machine on the local area network. It will probably be safer to use a local subnet mask so as to limit the potential spread of these broadcast packets. In reality, there's not much concern because most routers and firewalls will not forward such broadcast packets. */ #include "netapp.h" #include <cstdio> constexpr uint16_t MYPORT = 9991; void onRun() { // Setup a UDP Sender socket ASocket sender(SOCK_DGRAM, AF_INET, IPPROTO_UDP, false); // set socket to allow broadcast // if you don't do this, when you go to send // you'll get an error saying the socket doesn't // have permissions. auto res = sender.setBroadcast(); // Construct address we're going to be broadcasting to IPAddress bcastAddr = IPV4Address(INADDR_BROADCAST, MYPORT, AF_INET); // This is the buffer we're using to stuff our // broadcast command into int commandCount = 0; constexpr int bigbuffLen = 1400; char bigbuff[bigbuffLen]; // Just constantly blast stuff out into // the multi-cast channel while (true) { commandCount++; sprintf_s(bigbuff, "Command: %d", commandCount); int packetLen = strlen(bigbuff); int res = sender.sendTo(bcastAddr, bigbuff, packetLen); //printf("sender.sendTo: %d\n", res); // If there's any kind of error, just stop if (SOCKET_ERROR == res) break; } }
26.288136
71
0.728562
Wiladams
ee5905e963004179aac2b291e0f9385e244f0109
199
cpp
C++
Source/manipulator/manipulator.cpp
cypypccpy/UnrealRL
b0e7c8ea734ea17b38d18b9e5ea891b271ab03a7
[ "Apache-2.0" ]
2
2021-11-15T14:45:54.000Z
2021-12-06T10:39:42.000Z
Source/manipulator/manipulator.cpp
cypypccpy/UnrealRL
b0e7c8ea734ea17b38d18b9e5ea891b271ab03a7
[ "Apache-2.0" ]
null
null
null
Source/manipulator/manipulator.cpp
cypypccpy/UnrealRL
b0e7c8ea734ea17b38d18b9e5ea891b271ab03a7
[ "Apache-2.0" ]
1
2022-03-25T01:26:10.000Z
2022-03-25T01:26:10.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "manipulator.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, manipulator, "manipulator" );
28.428571
84
0.79397
cypypccpy
ee5a6300152593ba0fe16dc3d624875d5114a1c7
676
cpp
C++
test/src/Core/MouseCodes.cpp
meintte/MyGui
eabda6a8bb19886214db0ca04162f97c594d75a2
[ "Unlicense" ]
null
null
null
test/src/Core/MouseCodes.cpp
meintte/MyGui
eabda6a8bb19886214db0ca04162f97c594d75a2
[ "Unlicense" ]
null
null
null
test/src/Core/MouseCodes.cpp
meintte/MyGui
eabda6a8bb19886214db0ca04162f97c594d75a2
[ "Unlicense" ]
null
null
null
#include <doctest/doctest.h> #include <mygui/Core/MouseCodes.hpp> #include <string> TEST_CASE("MouseCodes") { CHECK(mygui::Mouse::Button0 == 0); CHECK(mygui::Mouse::Button1 == 1); CHECK(mygui::Mouse::Button2 == 2); CHECK(mygui::Mouse::Button3 == 3); CHECK(mygui::Mouse::Button4 == 4); CHECK(mygui::Mouse::Button5 == 5); CHECK(mygui::Mouse::Button6 == 6); CHECK(mygui::Mouse::Button7 == 7); CHECK(mygui::Mouse::ButtonLast == mygui::Mouse::Button7); CHECK(mygui::Mouse::ButtonLeft == mygui::Mouse::Button0); CHECK(mygui::Mouse::ButtonRight == mygui::Mouse::Button1); CHECK(mygui::Mouse::ButtonMiddle == mygui::Mouse::Button2); }
35.578947
63
0.647929
meintte
ee5b933b80fa068deedfbf41a02a35173f5656e4
94
cpp
C++
source/Foo.cpp
davidgtl/GraphKat
ef711f3b510cb25ed59e3363f010e89948975806
[ "MIT" ]
null
null
null
source/Foo.cpp
davidgtl/GraphKat
ef711f3b510cb25ed59e3363f010e89948975806
[ "MIT" ]
null
null
null
source/Foo.cpp
davidgtl/GraphKat
ef711f3b510cb25ed59e3363f010e89948975806
[ "MIT" ]
null
null
null
// // Created by david on 10/02/2020. // #include "Foo.h" Foo::Foo(Bar &bar) : bar(bar) { }
10.444444
34
0.56383
davidgtl
ee5cc67843146500c633dc4746eb4a513675b191
4,859
cc
C++
myping/ping/tcp.cc
svcx8/myping
8ae1c13a549865fa308c2f7ad7b2883344b5f41e
[ "MIT" ]
null
null
null
myping/ping/tcp.cc
svcx8/myping
8ae1c13a549865fa308c2f7ad7b2883344b5f41e
[ "MIT" ]
null
null
null
myping/ping/tcp.cc
svcx8/myping
8ae1c13a549865fa308c2f7ad7b2883344b5f41e
[ "MIT" ]
null
null
null
#include "tcp.hh" #include "misc/net.hh" using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::system_clock; void SetNonBlocking(int socket) { #ifdef _WIN32 u_long mode = 1; ioctlsocket(socket, FIONBIO, &mode); #else int old_opt = fcntl(socket, F_GETFL); int new_opt = old_opt | O_NONBLOCK; fcntl(socket, F_SETFL, new_opt); #endif } constexpr int timeout_sec = 3; constexpr int interval = 1; void PingConn::Start(const char* ip, int port, int count) { #ifdef _WIN32 WSADATA wsa_data; WSAStartup(0x0201, &wsa_data); #endif logger("[myping] %s:%d, count: %d", ip, port, count); struct timeval timeout { timeout_sec, 0 }; int recv = 0; int fastest = INT_MAX; int slowest = 0; int multiple_of_ten = count / 10; char count_prefix[6] = "%d"; if (multiple_of_ten) { int count_of_zero = 1; while (multiple_of_ten) { count_of_zero++; multiple_of_ten /= 10; } count_prefix[1] = 0x30; if (count_of_zero == 10) { count_prefix[2] = 0x31; count_prefix[3] = 0x30; count_prefix[4] = 0x64; } else { count_prefix[2] = 0x30 + count_of_zero; count_prefix[3] = 0x64; } } char full_prefix[15] = "\t["; int strlen_of_count_prefix = strlen(count_prefix); memcpy(&full_prefix[2], count_prefix, strlen_of_count_prefix); memcpy(&full_prefix[strlen_of_count_prefix + 2], "/", 1); memcpy(&full_prefix[strlen_of_count_prefix + 3], count_prefix, strlen_of_count_prefix); memcpy(&full_prefix[strlen_of_count_prefix + strlen_of_count_prefix + 3], "]", 1); char normal_log_format[32 + 15]{}; int strlen_of_full_prefix = strlen(full_prefix); memcpy(normal_log_format, full_prefix, strlen_of_full_prefix); memcpy(&normal_log_format[strlen_of_full_prefix], "\tFrom %s%s\e[0m\ttime=%s%d ms\e[0m\n", strlen("\tFrom %s%s\e[0m\ttime=%s%d ms\e[0m\n")); char timeout_log_format[45 + 15]{}; memcpy(timeout_log_format, full_prefix, strlen_of_full_prefix); memcpy(&timeout_log_format[strlen_of_full_prefix], "\tFrom \e[1;41m%s\e[0m\ttime=\e[47;30mtimeout\e[0m\n", strlen("\tFrom \e[1;41m%s\e[0m\ttime=\e[47;30mtimeout\e[0m\n")); for (int i = 0; i < count; ++i) { SleepSec(interval); try { int ping_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ping_socket == SOCKET_ERROR) { throw NetEx(); } SetNonBlocking(ping_socket); struct sockaddr_in cmd; cmd.sin_family = AF_INET; cmd.sin_addr.s_addr = inet_addr(ip); cmd.sin_port = htons(port); auto start = system_clock::now(); int result = connect(ping_socket, (sockaddr*)&cmd, sizeof(cmd)) != SOCKET_ERROR; if (result == SOCKET_ERROR) { throw NetEx(); } { fd_set set; FD_ZERO(&set); FD_SET(ping_socket, &set); result = select(ping_socket + 1, nullptr, &set, nullptr, &timeout); if (result > 0) { if (FD_ISSET(ping_socket, &set)) { auto end = system_clock::now(); auto duration = duration_cast<milliseconds>(end - start); int time = duration.count(); fastest = fastest > time ? time : fastest; slowest = slowest < time ? time : slowest; const char* color = " \e[0m"; if (time < 50) { color = "\e[1;30;42m"; } else if (time < 100) { color = "\e[1;30;43m"; } else { color = "\e[1;41m"; } std::printf(normal_log_format, i + 1, count, color, ip, color, time); CloseSocket(ping_socket); recv++; } } else if (result == 0) { std::printf(timeout_log_format, i + 1, count, ip); CloseSocket(ping_socket); } else { throw NetEx(); } } } catch (BaseException& ex) { logger("Exception: %s\n[%s] [%s] Line: #%d", ex.result_, ex.file_, ex.function_, ex.line_); } } logger("\n\tSent: %d\tReceived: %d\tLost: %d\t(%d%% loss)", count, recv, count - recv, (count - recv) * 100 / count); if (recv) logger("\tFastest: %dms\tSlowest: %dms\tAverage: %dms", fastest, slowest, (fastest + slowest) / 2); }
33.510345
175
0.526446
svcx8
ee5dfe031950bddbd59a07bf68e99b479465f67a
54,936
cc
C++
src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
src/connectivity/bluetooth/core/bt-host/l2cap/enhanced_retransmission_mode_tx_engine_unittest.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "enhanced_retransmission_mode_tx_engine.h" #include "gtest/gtest.h" #include "lib/gtest/test_loop_fixture.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/test_helpers.h" #include "src/connectivity/bluetooth/core/bt-host/l2cap/frame_headers.h" namespace bt { namespace l2cap { namespace internal { namespace { constexpr ChannelId kTestChannelId = 0x0001; using TxEngine = EnhancedRetransmissionModeTxEngine; class L2CAP_EnhancedRetransmissionModeTxEngineTest : public ::gtest::TestLoopFixture { public: L2CAP_EnhancedRetransmissionModeTxEngineTest() : kDefaultPayload('h', 'e', 'l', 'l', 'o') {} protected: // The default values are provided for use by tests which don't depend on the // specific value a given parameter. This should make the tests easier to // read, because the reader can focus on only the non-defaulted parameter // values. static constexpr auto kDefaultMTU = bt::l2cap::kDefaultMTU; static constexpr size_t kDefaultMaxTransmissions = 1; static constexpr size_t kDefaultTxWindow = 63; const StaticByteBuffer<5> kDefaultPayload; void VerifyIsReceiverReadyPollFrame(ByteBuffer* buf) { ASSERT_TRUE(buf); ASSERT_EQ(sizeof(SimpleSupervisoryFrame), buf->size()); const auto sframe = buf->As<SimpleSupervisoryFrame>(); EXPECT_EQ(SupervisoryFunction::ReceiverReady, sframe.function()); EXPECT_TRUE(sframe.is_poll_request()); } }; void NoOpTxCallback(ByteBufferPtr){}; void NoOpFailureCallback(){}; TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduTransmitsMinimalSizedSdu) { ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; constexpr size_t kMtu = 10; const auto payload = CreateStaticByteBuffer(1); TxEngine(kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback) .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduTransmitsMaximalSizedSdu) { ByteBufferPtr last_pdu; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; constexpr size_t kMtu = 1; const auto payload = CreateStaticByteBuffer(1); TxEngine(kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback) .QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); EXPECT_EQ(1u, n_pdus); ASSERT_TRUE(last_pdu); // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduSurvivesOversizedSdu) { // TODO(BT-440): Update this test when we add support for segmentation. constexpr size_t kMtu = 1; TxEngine(kTestChannelId, kMtu, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback) .QueueSdu(std::make_unique<DynamicByteBuffer>(CreateStaticByteBuffer(1, 2))); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduSurvivesZeroByteSdu) { TxEngine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback) .QueueSdu(std::make_unique<DynamicByteBuffer>()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduAdvancesSequenceNumber) { const auto payload = CreateStaticByteBuffer(1); ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(0, // Final Bit, TxSeq, MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(1 << 1, // Final Bit, TxSeq=1, MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } { // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(2 << 1, // Final Bit, TxSeq=2, MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduRollsOverSequenceNumber) { constexpr size_t kTxWindow = 63; // Max possible value const auto payload = CreateStaticByteBuffer(1); ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); constexpr size_t kMaxSeq = 64; for (size_t i = 0; i < kMaxSeq; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); tx_engine.UpdateAckSeq((i + 1) % kMaxSeq, false); } // See Core Spec v5.0, Volume 3, Part A, Table 3.2. const auto expected_pdu = CreateStaticByteBuffer(0, // Final Bit, TxSeq (rolls over from 63 to 0), MustBeZeroBit 0, // SAR bits, ReqSeq 1); // Payload last_pdu = nullptr; // Free up space for more transmissions. We need room for the 64th frame from // above (since the TxWindow is 63), and the new 0th frame. Hence we // acknowledge original frames 0 and 1. tx_engine.UpdateAckSeq(2, false); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(payload)); ASSERT_TRUE(last_pdu); EXPECT_TRUE(ContainersEqual(expected_pdu, *last_pdu)); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduDoesNotTransmitBeyondTxWindow) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); EXPECT_EQ(0u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduDoesNotTransmitBeyondTxWindowEvenIfQueueWrapsSequenceNumbers) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); ASSERT_EQ(1u, n_pdus); constexpr size_t kMaxSeq = 64; n_pdus = 0; for (size_t i = 0; i < kMaxSeq; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); ASSERT_EQ(0u, n_pdus); } } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineTransmitsReceiverReadyPollAfterTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; ASSERT_TRUE(RunLoopFor(zx::sec(2))); SCOPED_TRACE(""); VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineTransmitsReceiverReadyPollOnlyOnceAfterTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; ASSERT_TRUE(RunLoopFor(zx::sec(2))); SCOPED_TRACE(""); RETURN_IF_FATAL(VerifyIsReceiverReadyPollFrame(last_pdu.get())); last_pdu = nullptr; // Note: This value is chosen to be at least as long as // kReceiverReadyPollTimerDuration, but shorter than kMonitorTimerDuration. EXPECT_FALSE(RunLoopFor(zx::sec(2))); // No tasks were run. EXPECT_FALSE(last_pdu); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineAdvancesReceiverReadyPollTimeoutOnNewTransmission) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; ASSERT_FALSE(RunLoopFor(zx::sec(1))); // No events should fire. tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); last_pdu = nullptr; ASSERT_FALSE(RunLoopFor(zx::sec(1))); // Original timeout should not fire. ASSERT_TRUE(RunLoopFor(zx::sec(1))); // New timeout should fire. SCOPED_TRACE(""); VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, ReceiverReadyPollIncludesRequestSequenceNumber) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateReqSeq(1); RunLoopUntilIdle(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); last_pdu = nullptr; SCOPED_TRACE(""); EXPECT_TRUE(RunLoopFor(zx::sec(2))); ASSERT_NO_FATAL_FAILURE(VerifyIsReceiverReadyPollFrame(last_pdu.get())); EXPECT_EQ(1u, last_pdu->As<SimpleSupervisoryFrame>().request_seq_num()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, AckOfOnlyOutstandingFrameCancelsReceiverReadyPollTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); EXPECT_FALSE(RunLoopFor(zx::sec(2))); // No tasks were run. EXPECT_FALSE(last_pdu); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, AckOfAllOutstandingFramesCancelsReceiverReadyPollTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; tx_engine.UpdateAckSeq(3, false); RunLoopUntilIdle(); EXPECT_FALSE(RunLoopFor(zx::sec(2))); // No tasks were run. EXPECT_FALSE(last_pdu); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, PartialAckDoesNotCancelReceiverReadyPollTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(last_pdu); last_pdu = nullptr; tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.5.6, under heading // Process-ReqSeq. We should only Stop-RetransTimer if UnackedFrames is 0. SCOPED_TRACE(""); EXPECT_TRUE(RunLoopFor(zx::sec(2))); VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, NewTransmissionAfterAckedFrameReArmsReceiverReadyPollTimeout) { ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); // Send a frame, and get the ACK. tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); // Send a new frame. tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); last_pdu = nullptr; // Having earlier received an ACK for the previous frame should not have left // around any state that would prevent us from sending a receiver-ready poll // for the second frame. SCOPED_TRACE(""); EXPECT_TRUE(RunLoopFor(zx::sec(2))); VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollAfterMonitorTimeout) { constexpr size_t kMaxTransmissions = 2; // Allow retransmission ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. ASSERT_TRUE(RunLoopFor(zx::sec(2))); ASSERT_TRUE(last_pdu); last_pdu = nullptr; // Then the monitor_task_ fires. EXPECT_TRUE(RunLoopFor(zx::sec(12))); VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotRetransmitReceiverReadyPollAfterMonitorTimeoutWhenRetransmissionsAreDisabled) { constexpr size_t kMaxTransmissions = 1; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. ASSERT_TRUE(RunLoopFor(zx::sec(2))); ASSERT_TRUE(last_pdu); last_pdu = nullptr; // Run the event loop long enough for the monitor task to fire again. Because // kMaxTransmissions == 1, the ReceiverReadyPoll should not be retransmitted. RunLoopFor(zx::sec(13)); EXPECT_FALSE(last_pdu); } // See Core Spec v5.0, Volume 3, Part A, Sec 5.4, Table 8.6.5.8, for the row // with "Recv ReqSeqAndFbit" and "F = 1". TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineStopsPollingReceiverReadyFromMonitorTaskAfterReceivingFinalUpdateForAckSeq) { constexpr size_t kMaxTransmissions = 3; // Allow multiple retransmissions ByteBufferPtr last_pdu; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ tx_engine.UpdateAckSeq(1, true); EXPECT_FALSE(RunLoopFor(zx::sec(13))); // No other tasks. } // See Core Spec v5.0, Volume 3, Part A, Sec 5.4, Table 8.6.5.8, for the row // with "Recv ReqSeqAndFbit" and "F = 0". TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineContinuesPollingReceiverReadyFromMonitorTaskAfterReceivingNonFinalUpdateForAckSeq) { constexpr size_t kMaxTransmissions = 2; // Allow retransmissions ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ tx_engine.UpdateAckSeq(1, false); EXPECT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollAfterMultipleMonitorTimeouts) { constexpr size_t kMaxTransmissions = 3; // Allow multiple retransmissions ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ ASSERT_FALSE(RunLoopFor(zx::sec(2))); // RR-poll task does _not_ fire last_pdu = nullptr; EXPECT_TRUE(RunLoopFor(zx::sec(10))); // monitor_task_ again VerifyIsReceiverReadyPollFrame(last_pdu.get()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsReceiverReadyPollIndefinitelyAfterMonitorTimeoutWhenMaxTransmitsIsZero) { constexpr size_t kMaxTransmissions = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // First the receiver_ready_poll_task_ fires. ASSERT_TRUE(RunLoopFor(zx::sec(2))); EXPECT_TRUE(last_pdu); last_pdu = nullptr; // Then the monitor_task_ fires. EXPECT_TRUE(RunLoopFor(zx::sec(12))); EXPECT_TRUE(last_pdu); last_pdu = nullptr; // And the monitor_task_ fires again. EXPECT_TRUE(RunLoopFor(zx::sec(12))); EXPECT_TRUE(last_pdu); last_pdu = nullptr; // And the monitor_task_ fires yet again. EXPECT_TRUE(RunLoopFor(zx::sec(12))); EXPECT_TRUE(last_pdu); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineStopsTransmittingReceiverReadyPollAfterMaxTransmits) { constexpr size_t kMaxTransmissions = 2; ByteBufferPtr last_pdu; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](auto pdu) { last_pdu = std::move(pdu); }, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ last_pdu = nullptr; EXPECT_FALSE(RunLoopFor(zx::sec(13))); EXPECT_FALSE(last_pdu); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineClosesChannelAfterMaxTransmitsOfReceiverReadyPoll) { constexpr size_t kMaxTransmissions = 2; bool connection_failed = false; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, [&] { connection_failed = true; }); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineClosesChannelAfterMaxTransmitsOfReceiverReadyPollEvenIfRetransmissionsAreDisabled) { constexpr size_t kMaxTransmissions = 1; bool connection_failed = false; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, [&] { connection_failed = true; }); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ ASSERT_TRUE(RunLoopFor(zx::sec(12))); // monitor_task_ EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineClosesChannelAfterMaxTransmitsOfIFrame) { constexpr size_t kMaxTransmissions = 2; size_t num_info_frames_sent = 0; bool connection_failed = false; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](ByteBufferPtr pdu) { if (pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame()) { ++num_info_frames_sent; } }, [&] { connection_failed = true; }); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(1u, num_info_frames_sent); // Not having received an acknowledgement after 2 seconds, // receiver_ready_poll_task_ will fire, and cause us to send a // ReceiverReadyPoll. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // The peer indicates that it has not received any frames. This causes us to // retransmit the frame. tx_engine.UpdateAckSeq(0, true); EXPECT_EQ(2u, num_info_frames_sent); // Not having received an acknowledgement after 2 seconds, // receiver_ready_poll_task_ will fire, and cause us to send another // ReceiverReadyPoll. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // The connection should remain open, to allow the peer time to respond to our // poll, and acknowledge the outstanding frame. EXPECT_FALSE(connection_failed); // The peer again indicates that it has not received any frames. tx_engine.UpdateAckSeq(0, true); // Because we've exhausted kMaxTransmissions, the connection will be closed. EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineExhaustsAllRetransmissionsOfIFrameBeforeClosingChannel) { constexpr size_t kMaxTransmissions = 255; size_t num_info_frames_sent = 0; bool connection_failed = false; TxEngine tx_engine( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, [&](ByteBufferPtr pdu) { if (pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame()) { ++num_info_frames_sent; } }, [&] { connection_failed = true; }); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); for (size_t i = 0; i < kMaxTransmissions; ++i) { // Not having received an acknowledgement after 2 seconds, // receiver_ready_poll_task_ will fire, and cause us to send a // ReceiverReadyPoll. ASSERT_TRUE(RunLoopFor(zx::sec(2))) << "(i=" << i << ")"; // The connection should remain open, to allow the peer time to respond to // our poll, and acknowledge the outstanding frame. EXPECT_FALSE(connection_failed); // The peer indicates that it has not received any frames. tx_engine.UpdateAckSeq(0, true); } // The connection is closed, and we've exhausted kMaxTransmissions. EXPECT_TRUE(connection_failed); EXPECT_EQ(255u, num_info_frames_sent); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineClosesChannelAfterMaxTransmitsOfIFrameEvenIfRetransmissionsAreDisabled) { constexpr size_t kMaxTransmissions = 1; bool connection_failed = false; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, [&] { connection_failed = true; }); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Not having received an acknowledgement after 2 seconds, // receiver_ready_poll_task_ will fire, and cause us to send a // ReceiverReadyPoll. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // The connection should remain open, to allow the peer time to respond to our // poll, and acknowledge the outstanding frame. EXPECT_FALSE(connection_failed); // The peer indicates that it has not received any frames. tx_engine.UpdateAckSeq(0, true); EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsMissingFrameOnPollResponse) { constexpr size_t kMaxTransmissions = 2; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); last_pdu = nullptr; ASSERT_TRUE(RunLoopFor(zx::sec(2))); // receiver_ready_poll_task_ last_pdu = nullptr; tx_engine.UpdateAckSeq(0, true); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(0u, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsAllMissingFramesOnPollResponse) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 63; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Send a TxWindow's worth of frames. for (size_t i = 0; i < kTxWindow; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; tx_engine.UpdateAckSeq(0, true); EXPECT_EQ(kTxWindow, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(kTxWindow - 1, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineRetransmitsAllMissingFramesOnPollResponseWithWrappedSequenceNumber) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 63; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Send a TxWindow's worth of frames. for (size_t i = 0; i < kTxWindow; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } // Acknowledge the first 32 of these frames (with sequence numbers 0...31). tx_engine.UpdateAckSeq(32, false); // Queue 32 new frames (with sequence numbers 63, 0 ... 30). for (size_t i = 0; i < 32; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and then clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; // Repeat the earlier acknowledgement. This indicates that the peer has // not received frame 32. tx_engine.UpdateAckSeq(32, true); // We expect to retransmit frames 32...63, and then 0...30. That's 63 frames // in total. EXPECT_EQ(63u, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(30u, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineProperlyHandlesPartialAckWithWrappedSequenceNumber) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 63; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Send a TxWindow's worth of frames. for (size_t i = 0; i < kTxWindow; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } // Acknowledge the first 62 of these frames (with sequence numbers 0...61). tx_engine.UpdateAckSeq(62, false); // Queue 62 new frames. These frames have sequence numebrs 63, 0...60. // (Sequence number 62 was used when we queued the first batch of frames // above.) for (size_t i = 0; i < 62; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and then clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; // Acknowledge an additional 5 frames (with sequence numbers 62, 63, 0, 1, 2). tx_engine.UpdateAckSeq(3, true); // Verify that all unacknowledged frames are retransmitted. EXPECT_EQ(58u, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(60u, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotRetransmitFramesBeyondTxWindow) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 32; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Queue two TxWindow's worth of frames. These have sequence numbers 0...63. for (size_t i = 0; i < 2 * kTxWindow; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; tx_engine.UpdateAckSeq(0, true); EXPECT_EQ(kTxWindow, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); EXPECT_EQ(kTxWindow - 1, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotRetransmitFramesBeyondTxWindowWhenWindowWraps) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 48; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Queue one TxWindow's worth of frames. This advances the sequence numbers, // so that further transmissions can wrap. for (size_t i = 0; i < 48; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } tx_engine.UpdateAckSeq(48, false); RunLoopUntilIdle(); // Queue another TxWindow's worth of frames. These have sequence // numbers 48..63, and 0..31. These _should_ be retransmitted at the next // UpdateAckSeq() call. for (size_t i = 0; i < 48; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Queue a few more frames, with sequence numbers 32..39. These should _not_ // be retransmitted at the next UpdateAckSeq() call. for (size_t i = 0; i < 8; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; // Report that the peer has not received frame 48. This should trigger // retranmissions of unacknowledged frames within the TxWindow. tx_engine.UpdateAckSeq(48, true); // We expect to retransmit frames 48..63 and 0..31. The other frames are // beyond the transmit window. EXPECT_EQ(48u, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(31u, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotRetransmitPreviouslyAckedFramesOnPollResponse) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 2; size_t n_pdus = 0; ByteBufferPtr last_pdu; auto tx_callback = [&](auto pdu) { ++n_pdus; last_pdu = std::move(pdu); }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, and clear out accumulated callback // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); n_pdus = 0; last_pdu = nullptr; constexpr size_t kPollResponseReqSeq = 1; tx_engine.UpdateAckSeq(kPollResponseReqSeq, true); EXPECT_EQ(kTxWindow - kPollResponseReqSeq, n_pdus); ASSERT_TRUE(last_pdu); ASSERT_GE(last_pdu->size(), sizeof(SimpleInformationFrameHeader)); ASSERT_TRUE(last_pdu->As<EnhancedControlField>().designates_information_frame()); EXPECT_EQ(1, last_pdu->As<SimpleInformationFrameHeader>().tx_seq()); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotCrashOnAckOfMoreFramesThanAreOutstanding) { TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateAckSeq(2, true); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotCrashOnSpuriousAckAfterValidAck) { TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateAckSeq(1, true); tx_engine.UpdateAckSeq(2, true); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotCrashOnSpuriousAckBeforeAnyDataHasBeenSent) { TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback); for (size_t i = 0; i <= EnhancedControlField::kMaxSeqNum; ++i) { tx_engine.UpdateAckSeq(i, true); } } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduDoesNotTransmitFramesWhenRemoteIsBusy) { size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); EXPECT_EQ(0u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, UpdateAckSeqTransmitsQueuedDataWhenPossible) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); EXPECT_EQ(1u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, UpdateAckSeqTransmissionOfQueuedDataRespectsTxWindow) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); EXPECT_EQ(1u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, NonFinalUpdateAckSeqDoesNotTransmitQueuedFramesWhenRemoteIsBusy) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.SetRemoteBusy(); tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); EXPECT_EQ(0u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, FinalUpdateAckSeqDoesNotTransmitQueudFramesWhenRemoteIsBusy) { constexpr size_t kTxWindow = 1; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.SetRemoteBusy(); tx_engine.UpdateAckSeq(1, true); RunLoopUntilIdle(); EXPECT_EQ(0u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, MaybeSendQueuedDataTransmitsAllQueuedFramesWithinTxWindow) { constexpr size_t kTxWindow = 63; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); for (size_t i = 0; i < kTxWindow; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); ASSERT_EQ(0u, n_pdus); tx_engine.ClearRemoteBusy(); tx_engine.MaybeSendQueuedData(); RunLoopUntilIdle(); EXPECT_EQ(kTxWindow, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, MaybeSendQueuedDataDoesNotTransmitBeyondTxWindow) { constexpr size_t kTxWindow = 32; size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); for (size_t i = 0; i < kTxWindow + 1; ++i) { tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); } RunLoopUntilIdle(); ASSERT_EQ(0u, n_pdus); tx_engine.ClearRemoteBusy(); tx_engine.MaybeSendQueuedData(); RunLoopUntilIdle(); EXPECT_EQ(kTxWindow, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, MaybeSendQueuedDataRespectsRemoteBusy) { size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(0u, n_pdus); tx_engine.MaybeSendQueuedData(); RunLoopUntilIdle(); EXPECT_EQ(0u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, MaybeSendQueuedDataDoesNotCrashWhenCalledWithoutPendingPdus) { TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, NoOpFailureCallback); tx_engine.MaybeSendQueuedData(); RunLoopUntilIdle(); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduCanSendMoreFramesAfterClearingRemoteBusy) { size_t n_pdus = 0; auto tx_callback = [&](auto pdu) { ++n_pdus; }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(0u, n_pdus); tx_engine.ClearRemoteBusy(); tx_engine.MaybeSendQueuedData(); RunLoopUntilIdle(); ASSERT_EQ(1u, n_pdus); n_pdus = 0; tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); EXPECT_EQ(1u, n_pdus); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduMaintainsSduOrderingAfterClearRemoteBusy) { std::vector<uint8_t> pdu_seq_numbers; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { pdu_seq_numbers.push_back(pdu->As<SimpleInformationFrameHeader>().tx_seq()); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.SetRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); // seq=0 RunLoopUntilIdle(); ASSERT_TRUE(pdu_seq_numbers.empty()); tx_engine.ClearRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); // seq=1 RunLoopUntilIdle(); // This requirement isn't in the specification directly. But it seems // necessary given that we can sometimes exit the remote-busy condition // without transmitting the queued data. See Core Spec v5.0, Volume 3, Part A, // Table 8.7, row for "Recv RR (P=1)" for an example of such an operation. EXPECT_EQ((std::vector<uint8_t>{0, 1}), pdu_seq_numbers); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, UpdateAckSeqRetransmitsUnackedFramesBeforeTransmittingQueuedFrames) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 63; std::vector<uint8_t> pdu_seq_numbers; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { pdu_seq_numbers.push_back(pdu->As<SimpleInformationFrameHeader>().tx_seq()); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); // Send out two frames. tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_EQ(2u, pdu_seq_numbers.size()); pdu_seq_numbers.clear(); // Indicate the remote is busy, and queue a third frame. tx_engine.SetRemoteBusy(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); ASSERT_TRUE(pdu_seq_numbers.empty()); // Clear the busy condition, and then report the new ack sequence number. // Because the ack only acknowledges the first frame, the second frame should // be retransmitted. And that retransmission should come before the (initial) // transmission of the third frame. tx_engine.ClearRemoteBusy(); tx_engine.UpdateAckSeq(1, true); RunLoopUntilIdle(); EXPECT_EQ((std::vector{uint8_t(1), uint8_t(2)}), pdu_seq_numbers); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, QueueSduDoesNotTransmitNewFrameWhenEngineIsAwaitingPollResponse) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 3; std::vector<uint8_t> pdu_seq_numbers; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { pdu_seq_numbers.push_back(pdu->As<SimpleInformationFrameHeader>().tx_seq()); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire. This moves the engine into the 'WAIT_F' // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // Queue a new frame. pdu_seq_numbers.clear(); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); EXPECT_EQ(std::vector<uint8_t>(), pdu_seq_numbers); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, NonFinalUpdateAckSeqDoesNotTransmitNewFrameWhenEngineIsAwaitingPollResponse) { constexpr size_t kMaxTransmissions = 2; constexpr size_t kTxWindow = 1; std::vector<uint8_t> pdu_seq_numbers; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { pdu_seq_numbers.push_back(pdu->As<SimpleInformationFrameHeader>().tx_seq()); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire. This moves the engine into the 'WAIT_F' // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // Acknowledge the first frame, making room for the transmission of the second // frame. pdu_seq_numbers.clear(); tx_engine.UpdateAckSeq(1, false); RunLoopUntilIdle(); // Because we're still in the WAIT_F state, the second frame should _not_ be // transmitted. EXPECT_EQ(pdu_seq_numbers.end(), std::find(pdu_seq_numbers.begin(), pdu_seq_numbers.end(), 1)); } // Note: to make the most of this test, the unit tests should be built with // ASAN. TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotCrashIfExhaustionOfMaxTransmitForIFrameCausesEngineDestruction) { constexpr size_t kMaxTransmissions = 1; constexpr size_t kTxWindow = 2; bool connection_failed = false; std::unique_ptr<TxEngine> tx_engine = std::make_unique<TxEngine>( kTestChannelId, kDefaultMTU, kMaxTransmissions, kTxWindow, NoOpTxCallback, [&] { connection_failed = true; tx_engine.reset(); }); // Queue three SDUs, of which two should be transmitted immediately. tx_engine->QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine->QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine->QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire. This moves the engine into the 'WAIT_F' // state. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // Acknowledge the first frame, making room for the transmission of the third // frame. If the code is buggy, we may encounter use-after-free errors here. tx_engine->UpdateAckSeq(1, true); RunLoopUntilIdle(); // Because we only allow one transmission, the connection should have failed. EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, EngineDoesNotCrashIfExhaustionOfMaxTransmitForReceiverReadyPollCausesEngineDestruction) { constexpr size_t kMaxTransmissions = 1; bool connection_failed = false; std::unique_ptr<TxEngine> tx_engine = std::make_unique<TxEngine>( kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, NoOpTxCallback, [&] { connection_failed = true; tx_engine.reset(); }); tx_engine->QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); // Let receiver_ready_poll_task_ fire, to transmit the poll. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // Let monitor_task_ fire, to attempt retransmission of the poll. The // retransmission should fail, because we have exhausted kMaxTransmissions. If // the code is buggy, we may encounter use-after-free errors here. ASSERT_TRUE(RunLoopFor(zx::sec(12))); EXPECT_TRUE(connection_failed); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, TransmissionOfPduIncludesRequestSeqNum) { uint8_t outbound_req_seq = 0; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { outbound_req_seq = pdu->As<SimpleInformationFrameHeader>().request_seq_num(); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.UpdateReqSeq(5); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); EXPECT_EQ(5u, outbound_req_seq); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, DeferredTransmissionOfPduIncludesCurrentRequestSeqNum) { constexpr size_t kTxWindow = 1; uint8_t outbound_req_seq = 0; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { outbound_req_seq = pdu->As<SimpleInformationFrameHeader>().request_seq_num(); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kDefaultMaxTransmissions, kTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); tx_engine.UpdateReqSeq(5); tx_engine.UpdateAckSeq(1, true); // Peer acks first PDU. RunLoopUntilIdle(); // The second PDU should have been transmitted with ReqSeq = 5. EXPECT_EQ(5u, outbound_req_seq); } TEST_F(L2CAP_EnhancedRetransmissionModeTxEngineTest, RetransmissionOfPduIncludesCurrentSeqNum) { constexpr size_t kMaxTransmissions = 2; uint8_t outbound_req_seq = 0; size_t n_info_frames = 0; auto tx_callback = [&](ByteBufferPtr pdu) { if (pdu && pdu->size() >= sizeof(EnhancedControlField) && pdu->As<EnhancedControlField>().designates_information_frame() && pdu->size() >= sizeof(SimpleInformationFrameHeader)) { ++n_info_frames; outbound_req_seq = pdu->As<SimpleInformationFrameHeader>().request_seq_num(); } }; TxEngine tx_engine(kTestChannelId, kDefaultMTU, kMaxTransmissions, kDefaultTxWindow, tx_callback, NoOpFailureCallback); tx_engine.QueueSdu(std::make_unique<DynamicByteBuffer>(kDefaultPayload)); RunLoopUntilIdle(); EXPECT_EQ(0u, outbound_req_seq); // The receive engine reports that it has received new data from our peer. tx_engine.UpdateReqSeq(10); // Let receiver_ready_poll_task_ fire. This triggers us to query if our peer // has received our data. ASSERT_TRUE(RunLoopFor(zx::sec(2))); // Our peer indicates that it has not received our data. tx_engine.UpdateAckSeq(0, true); RunLoopUntilIdle(); // Our retransmission should include our current request sequence number. EXPECT_EQ(2u, n_info_frames); EXPECT_EQ(10u, outbound_req_seq); } } // namespace } // namespace internal } // namespace l2cap } // namespace bt
38.906516
100
0.73784
opensource-assist
ee5f55acd457d1553648e9afeb42e153e03e0d36
1,944
hpp
C++
interface/omni/ui/entity_widget_provider.hpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
33
2015-03-21T04:12:45.000Z
2021-04-18T21:44:33.000Z
interface/omni/ui/entity_widget_provider.hpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
null
null
null
interface/omni/ui/entity_widget_provider.hpp
daniel-kun/omni
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
[ "MIT" ]
2
2016-03-05T12:57:05.000Z
2017-09-12T10:11:52.000Z
#ifndef OMNI_UI_ENTITY_WIDGET_PROVIDER_HPP #define OMNI_UI_ENTITY_WIDGET_PROVIDER_HPP #include <omni/ui/ui.hpp> #include <omni/ui/entity_widget_provider_base.hpp> #include <QWidget> #include <QKeyEvent> #include <functional> #include <string> #include <memory> namespace omni { namespace core { class context; } } namespace omni { namespace ui { class entity_base_widget; /** @brief Creates edit- and view-widgets for a specific type of entity. **/ class OMNI_UI_API entity_widget_provider : public entity_widget_provider_base { public: static entity_widget_provider & getProvider (std::string entityType); entity_widget_provider ( std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget * editWidget)> viewCreator, std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget)> editCreator, std::function <bool (QKeyEvent * event)> keyHandler); std::unique_ptr <omni::ui::entity_base_widget> createViewWidget (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget * editWidget) override; std::unique_ptr <omni::ui::entity_base_widget> createEditWidget (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget) override; bool keyPressEvent (QKeyEvent * event) override; private: std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget * editWidget)> _viewCreator; std::function <std::unique_ptr <omni::ui::entity_base_widget> (QWidget * parent, omni::core::context & context, omni::ui::entity_base_widget & viewWidget)> _editCreator; std::function <bool (QKeyEvent * event)> _keyHandler; }; } // namespace ui } // namespace omni #endif // include guard
37.384615
176
0.745885
daniel-kun
ee613b51eab92b7025d94887bd9b5ee5c5ded2de
394
cpp
C++
Engine/src/Assets/AssetManager.cpp
Vyraax/VulkanLab
45aeaf576979684bc2a384a50aade276e64c601e
[ "MIT" ]
1
2021-08-06T11:28:18.000Z
2021-08-06T11:28:18.000Z
Engine/src/Assets/AssetManager.cpp
Vyraax/VulkanLab
45aeaf576979684bc2a384a50aade276e64c601e
[ "MIT" ]
null
null
null
Engine/src/Assets/AssetManager.cpp
Vyraax/VulkanLab
45aeaf576979684bc2a384a50aade276e64c601e
[ "MIT" ]
null
null
null
#include <iostream> #include <filesystem> #include "AssetManager.h" #include "../Shaders/Shader.h" namespace fs = std::filesystem; AssetManager::AssetManager(const char* bin_path) { this->root_dir = fs::canonical(fs::path(fs::current_path() / fs::path("../shaders/"))).string(); std::cout << "Shaders directory: " << this->root_dir << std::endl; } AssetManager::~AssetManager() { }
24.625
100
0.675127
Vyraax
ee61a7fc6e312c8eb8c5dd3ed622b01ac5796678
1,474
cpp
C++
PhysicsMaybe/Sphere.cpp
ElectroBean/IntroToPhysics
0609174025cda25fa78d86e6eb4650ff130b59ef
[ "MIT" ]
null
null
null
PhysicsMaybe/Sphere.cpp
ElectroBean/IntroToPhysics
0609174025cda25fa78d86e6eb4650ff130b59ef
[ "MIT" ]
null
null
null
PhysicsMaybe/Sphere.cpp
ElectroBean/IntroToPhysics
0609174025cda25fa78d86e6eb4650ff130b59ef
[ "MIT" ]
null
null
null
#include "Sphere.h" #include "RigidBody.h" #include <Renderer2D.h> #include <Gizmos.h> Sphere::Sphere(glm::vec2 position, glm::vec2 velocity, float mass, bool kinematic, float radius, float linearDrag, float angularDrag, float elasticity, glm::vec4 colour) : RigidBody(SPHERE, position, velocity, 0, mass, kinematic, 0, 0, 0) { m_radius = radius; m_colour = colour; this->m_linearDrag = linearDrag; this->m_angularDrag = angularDrag; this->m_elasticity = elasticity; this->m_moment = 0.5f * m_mass * m_radius * m_radius; m_angularVelocity = 0.0f; } Sphere::~Sphere() { } void Sphere::makeGizmo() { glm::vec2 end = glm::vec2(std::cos(m_rotation), std::sin(m_rotation)) * m_radius; aie::Gizmos::add2DCircle(m_position, m_radius, 16, m_colour); aie::Gizmos::add2DLine(m_position, m_position + end, glm::vec4(1, 1, 1, 1)); } bool Sphere::checkCollision(PhysicsObject * pOther) { //dynamic cast Sphere* other = dynamic_cast<Sphere*>(pOther); if (other) { if ((other->m_radius + this->m_radius) > glm::distance(other->m_position, this->m_position)) { return true; } else return false; } return false; } Sphere::Sphere(glm::vec2 position, float inclination, float speed, float mass, bool kinematic, float radius, float linearDrag, float angularDrag, float elasticity, glm::vec4 colour) : Sphere(position, glm::vec2(sin(inclination), cos(inclination)) * speed, mass, kinematic, radius, linearDrag, angularDrag, elasticity, colour) { }
26.8
169
0.713704
ElectroBean
ee6228c502b7222a8c230dc3c2c8546e66c39690
54,350
cc
C++
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/main/source/jitter_buffer.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
1
2020-02-19T09:55:55.000Z
2020-02-19T09:55:55.000Z
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/main/source/jitter_buffer.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/main/source/jitter_buffer.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
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. */ #include "modules/video_coding/main/source/jitter_buffer.h" #include <algorithm> #include <cassert> #include "modules/video_coding/main/source/event.h" #include "modules/video_coding/main/source/frame_buffer.h" #include "modules/video_coding/main/source/inter_frame_delay.h" #include "modules/video_coding/main/source/internal_defines.h" #include "modules/video_coding/main/source/jitter_buffer_common.h" #include "modules/video_coding/main/source/jitter_estimator.h" #include "modules/video_coding/main/source/packet.h" #include "modules/video_coding/main/source/tick_time_base.h" #include "system_wrappers/interface/critical_section_wrapper.h" #include "system_wrappers/interface/trace.h" #if defined(_WIN32) // VS 2005: Don't warn for default initialized arrays. See help for more info. #pragma warning(disable:4351) #endif namespace webrtc { // Predicates used when searching for frames in the frame buffer list class FrameSmallerTimestamp { public: FrameSmallerTimestamp(uint32_t timestamp) : timestamp_(timestamp) {} bool operator()(VCMFrameBuffer* frame) { return (LatestTimestamp(timestamp_, frame->TimeStamp(), NULL) == timestamp_); } private: uint32_t timestamp_; }; class FrameEqualTimestamp { public: FrameEqualTimestamp(uint32_t timestamp) : timestamp_(timestamp) {} bool operator()(VCMFrameBuffer* frame) { return (timestamp_ == frame->TimeStamp()); } private: uint32_t timestamp_; }; class CompleteDecodableKeyFrameCriteria { public: bool operator()(VCMFrameBuffer* frame) { return (frame->FrameType() == kVideoFrameKey) && (frame->GetState() == kStateComplete || frame->GetState() == kStateDecodable); } }; // Constructor VCMJitterBuffer::VCMJitterBuffer(TickTimeBase* clock, WebRtc_Word32 vcmId, WebRtc_Word32 receiverId, bool master) : _vcmId(vcmId), _receiverId(receiverId), _clock(clock), _running(false), _critSect(CriticalSectionWrapper::CreateCriticalSection()), _master(master), _frameEvent(), _packetEvent(), _maxNumberOfFrames(kStartNumberOfFrames), _frameBuffers(), _frameList(), _lastDecodedState(), _packetsNotDecodable(0), _receiveStatistics(), _incomingFrameRate(0), _incomingFrameCount(0), _timeLastIncomingFrameCount(0), _incomingBitCount(0), _incomingBitRate(0), _dropCount(0), _numConsecutiveOldFrames(0), _numConsecutiveOldPackets(0), _discardedPackets(0), _jitterEstimate(vcmId, receiverId), _delayEstimate(_clock->MillisecondTimestamp()), _rttMs(0), _nackMode(kNoNack), _lowRttNackThresholdMs(-1), _highRttNackThresholdMs(-1), _NACKSeqNum(), _NACKSeqNumLength(0), _waitingForKeyFrame(false), _firstPacket(true) { memset(_frameBuffers, 0, sizeof(_frameBuffers)); memset(_receiveStatistics, 0, sizeof(_receiveStatistics)); memset(_NACKSeqNumInternal, -1, sizeof(_NACKSeqNumInternal)); for (int i = 0; i< kStartNumberOfFrames; i++) { _frameBuffers[i] = new VCMFrameBuffer(); } } // Destructor VCMJitterBuffer::~VCMJitterBuffer() { Stop(); for (int i = 0; i< kMaxNumberOfFrames; i++) { if (_frameBuffers[i]) { delete _frameBuffers[i]; } } delete _critSect; } void VCMJitterBuffer::CopyFrom(const VCMJitterBuffer& rhs) { if (this != &rhs) { _critSect->Enter(); rhs._critSect->Enter(); _vcmId = rhs._vcmId; _receiverId = rhs._receiverId; _running = rhs._running; _master = !rhs._master; _maxNumberOfFrames = rhs._maxNumberOfFrames; _incomingFrameRate = rhs._incomingFrameRate; _incomingFrameCount = rhs._incomingFrameCount; _timeLastIncomingFrameCount = rhs._timeLastIncomingFrameCount; _incomingBitCount = rhs._incomingBitCount; _incomingBitRate = rhs._incomingBitRate; _dropCount = rhs._dropCount; _numConsecutiveOldFrames = rhs._numConsecutiveOldFrames; _numConsecutiveOldPackets = rhs._numConsecutiveOldPackets; _discardedPackets = rhs._discardedPackets; _jitterEstimate = rhs._jitterEstimate; _delayEstimate = rhs._delayEstimate; _waitingForCompletion = rhs._waitingForCompletion; _rttMs = rhs._rttMs; _NACKSeqNumLength = rhs._NACKSeqNumLength; _waitingForKeyFrame = rhs._waitingForKeyFrame; _firstPacket = rhs._firstPacket; _lastDecodedState = rhs._lastDecodedState; _packetsNotDecodable = rhs._packetsNotDecodable; memcpy(_receiveStatistics, rhs._receiveStatistics, sizeof(_receiveStatistics)); memcpy(_NACKSeqNumInternal, rhs._NACKSeqNumInternal, sizeof(_NACKSeqNumInternal)); memcpy(_NACKSeqNum, rhs._NACKSeqNum, sizeof(_NACKSeqNum)); for (int i = 0; i < kMaxNumberOfFrames; i++) { if (_frameBuffers[i] != NULL) { delete _frameBuffers[i]; _frameBuffers[i] = NULL; } } _frameList.clear(); for (int i = 0; i < _maxNumberOfFrames; i++) { _frameBuffers[i] = new VCMFrameBuffer(*(rhs._frameBuffers[i])); if (_frameBuffers[i]->Length() > 0) { FrameList::reverse_iterator rit = std::find_if( _frameList.rbegin(), _frameList.rend(), FrameSmallerTimestamp(_frameBuffers[i]->TimeStamp())); _frameList.insert(rit.base(), _frameBuffers[i]); } } rhs._critSect->Leave(); _critSect->Leave(); } } // Start jitter buffer void VCMJitterBuffer::Start() { CriticalSectionScoped cs(_critSect); _running = true; _incomingFrameCount = 0; _incomingFrameRate = 0; _incomingBitCount = 0; _incomingBitRate = 0; _timeLastIncomingFrameCount = _clock->MillisecondTimestamp(); memset(_receiveStatistics, 0, sizeof(_receiveStatistics)); _numConsecutiveOldFrames = 0; _numConsecutiveOldPackets = 0; _discardedPackets = 0; _frameEvent.Reset(); // start in a non-signaled state _packetEvent.Reset(); // start in a non-signaled state _waitingForCompletion.frameSize = 0; _waitingForCompletion.timestamp = 0; _waitingForCompletion.latestPacketTime = -1; _firstPacket = true; _NACKSeqNumLength = 0; _waitingForKeyFrame = false; _rttMs = 0; _packetsNotDecodable = 0; WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x): Jitter buffer: start", this); } // Stop jitter buffer void VCMJitterBuffer::Stop() { _critSect->Enter(); _running = false; _lastDecodedState.Reset(); _frameList.clear(); for (int i = 0; i < kMaxNumberOfFrames; i++) { if (_frameBuffers[i] != NULL) { static_cast<VCMFrameBuffer*>(_frameBuffers[i])->SetState(kStateFree); } } _critSect->Leave(); _frameEvent.Set(); // Make sure we exit from trying to get a frame to decoder _packetEvent.Set(); // Make sure we exit from trying to get a sequence number WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x): Jitter buffer: stop", this); } bool VCMJitterBuffer::Running() const { CriticalSectionScoped cs(_critSect); return _running; } // Flush jitter buffer void VCMJitterBuffer::Flush() { CriticalSectionScoped cs(_critSect); FlushInternal(); } // Must be called under the critical section _critSect void VCMJitterBuffer::FlushInternal() { // Erase all frames from the sorted list and set their state to free. _frameList.clear(); for (WebRtc_Word32 i = 0; i < _maxNumberOfFrames; i++) { ReleaseFrameInternal(_frameBuffers[i]); } _lastDecodedState.Reset(); // TODO (mikhal): sync reset _packetsNotDecodable = 0; _frameEvent.Reset(); _packetEvent.Reset(); _numConsecutiveOldFrames = 0; _numConsecutiveOldPackets = 0; // Also reset the jitter and delay estimates _jitterEstimate.Reset(); _delayEstimate.Reset(_clock->MillisecondTimestamp()); _waitingForCompletion.frameSize = 0; _waitingForCompletion.timestamp = 0; _waitingForCompletion.latestPacketTime = -1; _firstPacket = true; _NACKSeqNumLength = 0; WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x): Jitter buffer: flush", this); } // Set the frame state to free and remove it from the sorted // frame list. Must be called from inside the critical section _critSect. void VCMJitterBuffer::ReleaseFrameInternal(VCMFrameBuffer* frame) { if (frame != NULL && frame->GetState() != kStateDecoding) { frame->SetState(kStateFree); } } // Update frame state (set as complete if conditions are met) // Doing it here increases the degree of freedom for e.g. future // reconstructability of separate layers. Must be called under the // critical section _critSect. VCMFrameBufferEnum VCMJitterBuffer::UpdateFrameState(VCMFrameBuffer* frame) { if (frame == NULL) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x) FB(0x%x): " "UpdateFrameState NULL frame pointer", this, frame); return kNoError; } int length = frame->Length(); if (_master) { // Only trace the primary jitter buffer to make it possible to parse // and plot the trace file. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x) FB(0x%x): Complete frame added to jitter buffer," " size:%d type %d", this, frame,length,frame->FrameType()); } if (length != 0 && !frame->GetCountedFrame()) { // ignore Ack frames _incomingFrameCount++; frame->SetCountedFrame(true); } // Check if we should drop frame // an old complete frame can arrive too late if (_lastDecodedState.IsOldFrame(frame)) { // Frame is older than the latest decoded frame, drop it. Will be // released by CleanUpOldFrames later. frame->Reset(); frame->SetState(kStateEmpty); WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x) FB(0x%x): Dropping old frame in Jitter buffer", this, frame); _dropCount++; WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Jitter buffer drop count: %d, consecutive drops: %u", _dropCount, _numConsecutiveOldFrames); // Flush() if this happens consistently. _numConsecutiveOldFrames++; if (_numConsecutiveOldFrames > kMaxConsecutiveOldFrames) { FlushInternal(); return kFlushIndicator; } return kNoError; } _numConsecutiveOldFrames = 0; frame->SetState(kStateComplete); // Update receive statistics. We count all layers, thus when you use layers // adding all key and delta frames might differ from frame count if (frame->IsSessionComplete()) { switch (frame->FrameType()) { case kVideoFrameKey: { _receiveStatistics[0]++; break; } case kVideoFrameDelta: { _receiveStatistics[1]++; break; } case kVideoFrameGolden: { _receiveStatistics[2]++; break; } case kVideoFrameAltRef: { _receiveStatistics[3]++; break; } default: assert(false); } } const FrameList::iterator it = FindOldestCompleteContinuousFrame(false); VCMFrameBuffer* oldFrame = NULL; if (it != _frameList.end()) { oldFrame = *it; } // Only signal if this is the oldest frame. // Not necessary the case due to packet reordering or NACK. if (!WaitForNack() || (oldFrame != NULL && oldFrame == frame)) { _frameEvent.Set(); } return kNoError; } // Get received key and delta frames WebRtc_Word32 VCMJitterBuffer::GetFrameStatistics(WebRtc_UWord32& receivedDeltaFrames, WebRtc_UWord32& receivedKeyFrames) const { { CriticalSectionScoped cs(_critSect); receivedDeltaFrames = _receiveStatistics[1] + _receiveStatistics[3]; receivedKeyFrames = _receiveStatistics[0] + _receiveStatistics[2]; } return 0; } WebRtc_UWord32 VCMJitterBuffer::NumNotDecodablePackets() const { CriticalSectionScoped cs(_critSect); return _packetsNotDecodable; } WebRtc_UWord32 VCMJitterBuffer::DiscardedPackets() const { CriticalSectionScoped cs(_critSect); return _discardedPackets; } // Gets frame to use for this timestamp. If no match, get empty frame. WebRtc_Word32 VCMJitterBuffer::GetFrame(const VCMPacket& packet, VCMEncodedFrame*& frame) { if (!_running) // don't accept incoming packets until we are started { return VCM_UNINITIALIZED; } _critSect->Enter(); // Does this packet belong to an old frame? if (_lastDecodedState.IsOldPacket(&packet)) { // Account only for media packets if (packet.sizeBytes > 0) { _discardedPackets++; _numConsecutiveOldPackets++; } // Update last decoded sequence number if the packet arrived late and // belongs to a frame with a timestamp equal to the last decoded // timestamp. _lastDecodedState.UpdateOldPacket(&packet); if (_numConsecutiveOldPackets > kMaxConsecutiveOldPackets) { FlushInternal(); _critSect->Leave(); return VCM_FLUSH_INDICATOR; } _critSect->Leave(); return VCM_OLD_PACKET_ERROR; } _numConsecutiveOldPackets = 0; FrameList::iterator it = std::find_if( _frameList.begin(), _frameList.end(), FrameEqualTimestamp(packet.timestamp)); if (it != _frameList.end()) { frame = *it; _critSect->Leave(); return VCM_OK; } _critSect->Leave(); // No match, return empty frame frame = GetEmptyFrame(); if (frame != NULL) { return VCM_OK; } // No free frame! Try to reclaim some... _critSect->Enter(); RecycleFramesUntilKeyFrame(); _critSect->Leave(); frame = GetEmptyFrame(); if (frame != NULL) { return VCM_OK; } return VCM_JITTER_BUFFER_ERROR; } // Deprecated! Kept for testing purposes. VCMEncodedFrame* VCMJitterBuffer::GetFrame(const VCMPacket& packet) { VCMEncodedFrame* frame = NULL; if (GetFrame(packet, frame) < 0) { return NULL; } return frame; } // Get empty frame, creates new (i.e. increases JB size) if necessary VCMFrameBuffer* VCMJitterBuffer::GetEmptyFrame() { if (!_running) // don't accept incoming packets until we are started { return NULL; } _critSect->Enter(); for (int i = 0; i <_maxNumberOfFrames; ++i) { if (kStateFree == _frameBuffers[i]->GetState()) { // found a free buffer _frameBuffers[i]->SetState(kStateEmpty); _critSect->Leave(); return _frameBuffers[i]; } } // Check if we can increase JB size if (_maxNumberOfFrames < kMaxNumberOfFrames) { VCMFrameBuffer* ptrNewBuffer = new VCMFrameBuffer(); ptrNewBuffer->SetState(kStateEmpty); _frameBuffers[_maxNumberOfFrames] = ptrNewBuffer; _maxNumberOfFrames++; _critSect->Leave(); WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x) FB(0x%x): Jitter buffer " "increased to:%d frames", this, ptrNewBuffer, _maxNumberOfFrames); return ptrNewBuffer; } _critSect->Leave(); // We have reached max size, cannot increase JB size return NULL; } // Find oldest complete frame used for getting next frame to decode // Must be called under critical section FrameList::iterator VCMJitterBuffer::FindOldestCompleteContinuousFrame(bool enable_decodable) { // If we have more than one frame done since last time, pick oldest. VCMFrameBuffer* oldest_frame = NULL; FrameList::iterator it = _frameList.begin(); // When temporal layers are available, we search for a complete or decodable // frame until we hit one of the following: // 1. Continuous base or sync layer. // 2. The end of the list was reached. for (; it != _frameList.end(); ++it) { oldest_frame = *it; VCMFrameBufferStateEnum state = oldest_frame->GetState(); // Is this frame complete or decodable and continuous? if ((state == kStateComplete || (enable_decodable && state == kStateDecodable)) && _lastDecodedState.ContinuousFrame(oldest_frame)) { break; } else { int temporal_id = oldest_frame->TemporalId(); oldest_frame = NULL; if (temporal_id <= 0) { // When temporal layers are disabled or we have hit a base layer // we break (regardless of continuity and completeness). break; } } } if (oldest_frame == NULL) { // No complete frame no point to continue. return _frameList.end(); } else if (_waitingForKeyFrame && oldest_frame->FrameType() != kVideoFrameKey) { // We are waiting for a key frame. return _frameList.end(); } // We have a complete continuous frame. return it; } // Call from inside the critical section _critSect void VCMJitterBuffer::RecycleFrame(VCMFrameBuffer* frame) { if (frame == NULL) { return; } WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "JB(0x%x) FB(0x%x): RecycleFrame, size:%d", this, frame, frame->Length()); ReleaseFrameInternal(frame); } // Calculate frame and bit rates WebRtc_Word32 VCMJitterBuffer::GetUpdate(WebRtc_UWord32& frameRate, WebRtc_UWord32& bitRate) { CriticalSectionScoped cs(_critSect); const WebRtc_Word64 now = _clock->MillisecondTimestamp(); WebRtc_Word64 diff = now - _timeLastIncomingFrameCount; if (diff < 1000 && _incomingFrameRate > 0 && _incomingBitRate > 0) { // Make sure we report something even though less than // 1 second has passed since last update. frameRate = _incomingFrameRate; bitRate = _incomingBitRate; } else if (_incomingFrameCount != 0) { // We have received frame(s) since last call to this function // Prepare calculations if (diff <= 0) { diff = 1; } // we add 0.5f for rounding float rate = 0.5f + ((_incomingFrameCount * 1000.0f) / diff); if (rate < 1.0f) // don't go below 1, can crash { rate = 1.0f; } // Calculate frame rate // Let r be rate. // r(0) = 1000*framecount/delta_time. // (I.e. frames per second since last calculation.) // frameRate = r(0)/2 + r(-1)/2 // (I.e. fr/s average this and the previous calculation.) frameRate = (_incomingFrameRate + (WebRtc_Word32)rate) >> 1; _incomingFrameRate = (WebRtc_UWord8)rate; // Calculate bit rate if (_incomingBitCount == 0) { bitRate = 0; } else { bitRate = 10 * ((100 * _incomingBitCount) / static_cast<WebRtc_UWord32>(diff)); } _incomingBitRate = bitRate; // Reset count _incomingFrameCount = 0; _incomingBitCount = 0; _timeLastIncomingFrameCount = now; } else { // No frames since last call _timeLastIncomingFrameCount = _clock->MillisecondTimestamp(); frameRate = 0; bitRate = 0; _incomingBitRate = 0; } return 0; } // Returns immediately or a X ms event hang waiting for a complete frame, // X decided by caller VCMEncodedFrame* VCMJitterBuffer::GetCompleteFrameForDecoding(WebRtc_UWord32 maxWaitTimeMS) { if (!_running) { return NULL; } _critSect->Enter(); CleanUpOldFrames(); if (_lastDecodedState.init() && WaitForNack()) { _waitingForKeyFrame = true; } FrameList::iterator it = FindOldestCompleteContinuousFrame(false); if (it == _frameList.end()) { if (maxWaitTimeMS == 0) { _critSect->Leave(); return NULL; } const WebRtc_Word64 endWaitTimeMs = _clock->MillisecondTimestamp() + maxWaitTimeMS; WebRtc_Word64 waitTimeMs = maxWaitTimeMS; while (waitTimeMs > 0) { _critSect->Leave(); const EventTypeWrapper ret = _frameEvent.Wait(static_cast<WebRtc_UWord32>(waitTimeMs)); _critSect->Enter(); if (ret == kEventSignaled) { // are we closing down the Jitter buffer if (!_running) { _critSect->Leave(); return NULL; } // Finding oldest frame ready for decoder, but check // sequence number and size CleanUpOldFrames(); it = FindOldestCompleteContinuousFrame(false); if (it == _frameList.end()) { waitTimeMs = endWaitTimeMs - _clock->MillisecondTimestamp(); } else { break; } } else { _critSect->Leave(); return NULL; } } // Inside critSect } else { // we already have a frame reset the event _frameEvent.Reset(); } if (it == _frameList.end()) { // Even after signaling we're still missing a complete continuous frame _critSect->Leave(); return NULL; } VCMFrameBuffer* oldestFrame = *it; it = _frameList.erase(it); // Update jitter estimate const bool retransmitted = (oldestFrame->GetNackCount() > 0); if (retransmitted) { _jitterEstimate.FrameNacked(); } else if (oldestFrame->Length() > 0) { // Ignore retransmitted and empty frames. UpdateJitterAndDelayEstimates(*oldestFrame, false); } oldestFrame->SetState(kStateDecoding); CleanUpOldFrames(); if (oldestFrame->FrameType() == kVideoFrameKey) { _waitingForKeyFrame = false; } _critSect->Leave(); // We have a frame - update decoded state with frame info. _lastDecodedState.SetState(oldestFrame); return oldestFrame; } WebRtc_UWord32 VCMJitterBuffer::GetEstimatedJitterMS() { CriticalSectionScoped cs(_critSect); return GetEstimatedJitterMsInternal(); } WebRtc_UWord32 VCMJitterBuffer::GetEstimatedJitterMsInternal() { WebRtc_UWord32 estimate = VCMJitterEstimator::OPERATING_SYSTEM_JITTER; // Compute RTT multiplier for estimation // _lowRttNackThresholdMs == -1 means no FEC. double rttMult = 1.0f; if (_nackMode == kNackHybrid && (_lowRttNackThresholdMs >= 0 && static_cast<int>(_rttMs) > _lowRttNackThresholdMs)) { // from here we count on FEC rttMult = 0.0f; } estimate += static_cast<WebRtc_UWord32> (_jitterEstimate.GetJitterEstimate(rttMult) + 0.5); return estimate; } void VCMJitterBuffer::UpdateRtt(WebRtc_UWord32 rttMs) { CriticalSectionScoped cs(_critSect); _rttMs = rttMs; _jitterEstimate.UpdateRtt(rttMs); } // wait for the first packet in the next frame to arrive WebRtc_Word64 VCMJitterBuffer::GetNextTimeStamp(WebRtc_UWord32 maxWaitTimeMS, FrameType& incomingFrameType, WebRtc_Word64& renderTimeMs) { if (!_running) { return -1; } _critSect->Enter(); // Finding oldest frame ready for decoder, check sequence number and size CleanUpOldFrames(); FrameList::iterator it = _frameList.begin(); if (it == _frameList.end()) { _packetEvent.Reset(); _critSect->Leave(); if (_packetEvent.Wait(maxWaitTimeMS) == kEventSignaled) { // are we closing down the Jitter buffer if (!_running) { return -1; } _critSect->Enter(); CleanUpOldFrames(); it = _frameList.begin(); } else { _critSect->Enter(); } } if (it == _frameList.end()) { _critSect->Leave(); return -1; } // we have a frame // return frame type // All layers are assumed to have the same type incomingFrameType = (*it)->FrameType(); renderTimeMs = (*it)->RenderTimeMs(); const WebRtc_UWord32 timestamp = (*it)->TimeStamp(); _critSect->Leave(); // return current time return timestamp; } // Answers the question: // Will the packet sequence be complete if the next frame is grabbed for // decoding right now? That is, have we lost a frame between the last decoded // frame and the next, or is the next // frame missing one or more packets? bool VCMJitterBuffer::CompleteSequenceWithNextFrame() { CriticalSectionScoped cs(_critSect); // Finding oldest frame ready for decoder, check sequence number and size CleanUpOldFrames(); if (_frameList.empty()) return true; VCMFrameBuffer* oldestFrame = _frameList.front(); if (_frameList.size() <= 1 && oldestFrame->GetState() != kStateComplete) { // Frame not ready to be decoded. return true; } if (!oldestFrame->Complete()) { return false; } // See if we have lost a frame before this one. if (_lastDecodedState.init()) { // Following start, reset or flush -> check for key frame. if (oldestFrame->FrameType() != kVideoFrameKey) { return false; } } else if (oldestFrame->GetLowSeqNum() == -1) { return false; } else if (!_lastDecodedState.ContinuousFrame(oldestFrame)) { return false; } return true; } // Returns immediately VCMEncodedFrame* VCMJitterBuffer::GetFrameForDecoding() { CriticalSectionScoped cs(_critSect); if (!_running) { return NULL; } if (WaitForNack()) { return GetFrameForDecodingNACK(); } CleanUpOldFrames(); if (_frameList.empty()) { return NULL; } VCMFrameBuffer* oldestFrame = _frameList.front(); if (_frameList.size() <= 1 && oldestFrame->GetState() != kStateComplete) { return NULL; } // Incomplete frame pulled out from jitter buffer, // update the jitter estimate with what we currently know. // This frame shouldn't have been retransmitted, but if we recently // turned off NACK this might still happen. const bool retransmitted = (oldestFrame->GetNackCount() > 0); if (retransmitted) { _jitterEstimate.FrameNacked(); } else if (oldestFrame->Length() > 0) { // Ignore retransmitted and empty frames. // Update with the previous incomplete frame first if (_waitingForCompletion.latestPacketTime >= 0) { UpdateJitterAndDelayEstimates(_waitingForCompletion, true); } // Then wait for this one to get complete _waitingForCompletion.frameSize = oldestFrame->Length(); _waitingForCompletion.latestPacketTime = oldestFrame->LatestPacketTimeMs(); _waitingForCompletion.timestamp = oldestFrame->TimeStamp(); } _frameList.erase(_frameList.begin()); // Look for previous frame loss VerifyAndSetPreviousFrameLost(*oldestFrame); // The state must be changed to decoding before cleaning up zero sized // frames to avoid empty frames being cleaned up and then given to the // decoder. // Set as decoding. Propagates the missingFrame bit. oldestFrame->SetState(kStateDecoding); CleanUpOldFrames(); if (oldestFrame->FrameType() == kVideoFrameKey) { _waitingForKeyFrame = false; } _packetsNotDecodable += oldestFrame->NotDecodablePackets(); // We have a frame - update decoded state with frame info. _lastDecodedState.SetState(oldestFrame); return oldestFrame; } VCMEncodedFrame* VCMJitterBuffer::GetFrameForDecodingNACK() { // when we use NACK we don't release non complete frames // unless we have a complete key frame. // In hybrid mode, we may release decodable frames (non-complete) // Clean up old frames and empty frames CleanUpOldFrames(); // First look for a complete _continuous_ frame. // When waiting for nack, wait for a key frame, if a continuous frame cannot // be determined (i.e. initial decoding state). if (_lastDecodedState.init()) { _waitingForKeyFrame = true; } // Allow for a decodable frame when in Hybrid mode. bool enableDecodable = _nackMode == kNackHybrid ? true : false; FrameList::iterator it = FindOldestCompleteContinuousFrame(enableDecodable); if (it == _frameList.end()) { // If we didn't find one we're good with a complete key/decodable frame. it = find_if(_frameList.begin(), _frameList.end(), CompleteDecodableKeyFrameCriteria()); if (it == _frameList.end()) { return NULL; } } VCMFrameBuffer* oldestFrame = *it; // Update jitter estimate const bool retransmitted = (oldestFrame->GetNackCount() > 0); if (retransmitted) { _jitterEstimate.FrameNacked(); } else if (oldestFrame->Length() > 0) { // Ignore retransmitted and empty frames. UpdateJitterAndDelayEstimates(*oldestFrame, false); } it = _frameList.erase(it); // Look for previous frame loss VerifyAndSetPreviousFrameLost(*oldestFrame); // The state must be changed to decoding before cleaning up zero sized // frames to avoid empty frames being cleaned up and then given to the // decoder. oldestFrame->SetState(kStateDecoding); // Clean up old frames and empty frames CleanUpOldFrames(); if (oldestFrame->FrameType() == kVideoFrameKey) { _waitingForKeyFrame = false; } // We have a frame - update decoded state with frame info. _lastDecodedState.SetState(oldestFrame); return oldestFrame; } // Must be called under the critical section _critSect. Should never be called // with retransmitted frames, they must be filtered out before this function is // called. void VCMJitterBuffer::UpdateJitterAndDelayEstimates(VCMJitterSample& sample, bool incompleteFrame) { if (sample.latestPacketTime == -1) { return; } if (incompleteFrame) { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Received incomplete frame " "timestamp %u frame size %u at time %u", sample.timestamp, sample.frameSize, MaskWord64ToUWord32(sample.latestPacketTime)); } else { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Received complete frame " "timestamp %u frame size %u at time %u", sample.timestamp, sample.frameSize, MaskWord64ToUWord32(sample.latestPacketTime)); } UpdateJitterAndDelayEstimates(sample.latestPacketTime, sample.timestamp, sample.frameSize, incompleteFrame); } // Must be called under the critical section _critSect. Should never be // called with retransmitted frames, they must be filtered out before this // function is called. void VCMJitterBuffer::UpdateJitterAndDelayEstimates(VCMFrameBuffer& frame, bool incompleteFrame) { if (frame.LatestPacketTimeMs() == -1) { return; } // No retransmitted frames should be a part of the jitter // estimate. if (incompleteFrame) { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Received incomplete frame timestamp %u frame type %d " "frame size %u at time %u, jitter estimate was %u", frame.TimeStamp(), frame.FrameType(), frame.Length(), MaskWord64ToUWord32(frame.LatestPacketTimeMs()), GetEstimatedJitterMsInternal()); } else { WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId),"Received complete frame " "timestamp %u frame type %d frame size %u at time %u, " "jitter estimate was %u", frame.TimeStamp(), frame.FrameType(), frame.Length(), MaskWord64ToUWord32(frame.LatestPacketTimeMs()), GetEstimatedJitterMsInternal()); } UpdateJitterAndDelayEstimates(frame.LatestPacketTimeMs(), frame.TimeStamp(), frame.Length(), incompleteFrame); } // Must be called under the critical section _critSect. Should never be called // with retransmitted frames, they must be filtered out before this function // is called. void VCMJitterBuffer::UpdateJitterAndDelayEstimates(WebRtc_Word64 latestPacketTimeMs, WebRtc_UWord32 timestamp, WebRtc_UWord32 frameSize, bool incompleteFrame) { if (latestPacketTimeMs == -1) { return; } WebRtc_Word64 frameDelay; // Calculate the delay estimate WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Packet received and sent to jitter estimate with: " "timestamp=%u wallClock=%u", timestamp, MaskWord64ToUWord32(latestPacketTimeMs)); bool notReordered = _delayEstimate.CalculateDelay(timestamp, &frameDelay, latestPacketTimeMs); // Filter out frames which have been reordered in time by the network if (notReordered) { // Update the jitter estimate with the new samples _jitterEstimate.UpdateEstimate(frameDelay, frameSize, incompleteFrame); } } WebRtc_UWord16* VCMJitterBuffer::GetNackList(WebRtc_UWord16& nackSize,bool& listExtended) { return CreateNackList(nackSize,listExtended); } // Assume called internally with critsect WebRtc_Word32 VCMJitterBuffer::GetLowHighSequenceNumbers(WebRtc_Word32& lowSeqNum, WebRtc_Word32& highSeqNum) const { // TODO (mikhal/stefan): refactor to use lastDecodedState WebRtc_Word32 i = 0; WebRtc_Word32 seqNum = -1; highSeqNum = -1; lowSeqNum = -1; if (!_lastDecodedState.init()) lowSeqNum = _lastDecodedState.sequence_num(); // find highest seq numbers for (i = 0; i < _maxNumberOfFrames; ++i) { seqNum = _frameBuffers[i]->GetHighSeqNum(); // Ignore free / empty frames VCMFrameBufferStateEnum state = _frameBuffers[i]->GetState(); if ((kStateFree != state) && (kStateEmpty != state) && (kStateDecoding != state) && seqNum != -1) { bool wrap; highSeqNum = LatestSequenceNumber(seqNum, highSeqNum, &wrap); } } // for return 0; } WebRtc_UWord16* VCMJitterBuffer::CreateNackList(WebRtc_UWord16& nackSize, bool& listExtended) { // TODO (mikhal/stefan): Refactor to use lastDecodedState. CriticalSectionScoped cs(_critSect); int i = 0; WebRtc_Word32 lowSeqNum = -1; WebRtc_Word32 highSeqNum = -1; listExtended = false; // Don't create list, if we won't wait for it if (!WaitForNack()) { nackSize = 0; return NULL; } // Find the lowest (last decoded) sequence number and // the highest (highest sequence number of the newest frame) // sequence number. The nack list is a subset of the range // between those two numbers. GetLowHighSequenceNumbers(lowSeqNum, highSeqNum); // write a list of all seq num we have if (lowSeqNum == -1 || highSeqNum == -1) { // This happens if we lose the first packet, nothing is popped if (highSeqNum == -1) { // we have not received any packets yet nackSize = 0; } else { // signal that we want a key frame request to be sent nackSize = 0xffff; } return NULL; } int numberOfSeqNum = 0; if (lowSeqNum > highSeqNum) { if (lowSeqNum - highSeqNum > 0x00ff) { // wrap numberOfSeqNum = (0xffff-lowSeqNum) + highSeqNum + 1; } } else { numberOfSeqNum = highSeqNum - lowSeqNum; } if (numberOfSeqNum > kNackHistoryLength) { // Nack list is too big, flush and try to restart. WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Nack list too large, try to find a key frame and restart " "from seq: %d. Lowest seq in jb %d", highSeqNum,lowSeqNum); // This nack size will trigger a key request... bool foundKeyFrame = false; while (numberOfSeqNum > kNackHistoryLength) { foundKeyFrame = RecycleFramesUntilKeyFrame(); if (!foundKeyFrame) { break; } // Check if we still have too many packets in JB lowSeqNum = -1; highSeqNum = -1; GetLowHighSequenceNumbers(lowSeqNum, highSeqNum); if (highSeqNum == -1) { assert(lowSeqNum != -1); // This should never happen // We can't calculate the nack list length... return NULL; } numberOfSeqNum = 0; if (lowSeqNum > highSeqNum) { if (lowSeqNum - highSeqNum > 0x00ff) { // wrap numberOfSeqNum = (0xffff-lowSeqNum) + highSeqNum + 1; highSeqNum=lowSeqNum; } } else { numberOfSeqNum = highSeqNum - lowSeqNum; } } // end while if (!foundKeyFrame) { // No key frame in JB. // Set the last decoded sequence number to current high. // This is to not get a large nack list again right away _lastDecodedState.SetSeqNum(static_cast<uint16_t>(highSeqNum)); // Set to trigger key frame signal nackSize = 0xffff; listExtended = true; WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, -1, "\tNo key frame found, request one. _lastDecodedSeqNum[0] " "%d", _lastDecodedState.sequence_num()); } else { // We have cleaned up the jb and found a key frame // The function itself has set last decoded seq. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, -1, "\tKey frame found. _lastDecodedSeqNum[0] %d", _lastDecodedState.sequence_num()); nackSize = 0; } return NULL; } WebRtc_UWord16 seqNumberIterator = (WebRtc_UWord16)(lowSeqNum + 1); for (i = 0; i < numberOfSeqNum; i++) { _NACKSeqNumInternal[i] = seqNumberIterator; seqNumberIterator++; } // now we have a list of all sequence numbers that could have been sent // zero out the ones we have received for (i = 0; i < _maxNumberOfFrames; i++) { // loop all created frames // We don't need to check if frame is decoding since lowSeqNum is based // on _lastDecodedSeqNum // Ignore free frames VCMFrameBufferStateEnum state = _frameBuffers[i]->GetState(); if ((kStateFree != state) && (kStateEmpty != state) && (kStateDecoding != state)) { // Reaching thus far means we are going to update the nack list // When in hybrid mode, we use the soft NACKing feature. if (_nackMode == kNackHybrid) { _frameBuffers[i]->BuildSoftNackList(_NACKSeqNumInternal, numberOfSeqNum, _rttMs); } else { // Used when the frame is being processed by the decoding thread // don't need to use that info in this loop. _frameBuffers[i]->BuildHardNackList(_NACKSeqNumInternal, numberOfSeqNum); } } } // compress list int emptyIndex = -1; for (i = 0; i < numberOfSeqNum; i++) { if (_NACKSeqNumInternal[i] == -1 || _NACKSeqNumInternal[i] == -2 ) { // this is empty if (emptyIndex == -1) { // no empty index before, remember this position emptyIndex = i; } } else { // this is not empty if (emptyIndex == -1) { // no empty index, continue } else { _NACKSeqNumInternal[emptyIndex] = _NACKSeqNumInternal[i]; _NACKSeqNumInternal[i] = -1; emptyIndex++; } } } // for if (emptyIndex == -1) { // no empty nackSize = numberOfSeqNum; } else { nackSize = emptyIndex; } if (nackSize > _NACKSeqNumLength) { // Larger list: nack list was extended since the last call. listExtended = true; } for (WebRtc_UWord32 j = 0; j < nackSize; j++) { // Check if the list has been extended since it was last created. I.e, // new items have been added if (_NACKSeqNumLength > j && !listExtended) { WebRtc_UWord32 k = 0; for (k = j; k < _NACKSeqNumLength; k++) { // Found the item in the last list, i.e, no new items found yet. if (_NACKSeqNum[k] == (WebRtc_UWord16)_NACKSeqNumInternal[j]) { break; } } if (k == _NACKSeqNumLength) // New item not found in last list. { listExtended = true; } } else { listExtended = true; } _NACKSeqNum[j] = (WebRtc_UWord16)_NACKSeqNumInternal[j]; } _NACKSeqNumLength = nackSize; return _NACKSeqNum; } // Release frame when done with decoding. Should never be used to release // frames from within the jitter buffer. void VCMJitterBuffer::ReleaseFrame(VCMEncodedFrame* frame) { CriticalSectionScoped cs(_critSect); VCMFrameBuffer* frameBuffer = static_cast<VCMFrameBuffer*>(frame); if (frameBuffer != NULL) frameBuffer->SetState(kStateFree); } WebRtc_Word64 VCMJitterBuffer::LastPacketTime(VCMEncodedFrame* frame, bool& retransmitted) const { CriticalSectionScoped cs(_critSect); retransmitted = (static_cast<VCMFrameBuffer*>(frame)->GetNackCount() > 0); return static_cast<VCMFrameBuffer*>(frame)->LatestPacketTimeMs(); } WebRtc_Word64 VCMJitterBuffer::LastDecodedTimestamp() const { CriticalSectionScoped cs(_critSect); return _lastDecodedState.time_stamp(); } // Insert packet // Takes crit sect, and inserts packet in frame buffer, possibly does logging VCMFrameBufferEnum VCMJitterBuffer::InsertPacket(VCMEncodedFrame* buffer, const VCMPacket& packet) { CriticalSectionScoped cs(_critSect); WebRtc_Word64 nowMs = _clock->MillisecondTimestamp(); VCMFrameBufferEnum bufferReturn = kSizeError; VCMFrameBufferEnum ret = kSizeError; VCMFrameBuffer* frame = static_cast<VCMFrameBuffer*>(buffer); // We are keeping track of the first seq num, the latest seq num and // the number of wraps to be able to calculate how many packets we expect. if (_firstPacket) { // Now it's time to start estimating jitter // reset the delay estimate. _delayEstimate.Reset(_clock->MillisecondTimestamp()); _firstPacket = false; } // Empty packets may bias the jitter estimate (lacking size component), // therefore don't let empty packet trigger the following updates: if (packet.frameType != kFrameEmpty) { if (_waitingForCompletion.timestamp == packet.timestamp) { // This can get bad if we have a lot of duplicate packets, // we will then count some packet multiple times. _waitingForCompletion.frameSize += packet.sizeBytes; _waitingForCompletion.latestPacketTime = nowMs; } else if (_waitingForCompletion.latestPacketTime >= 0 && _waitingForCompletion.latestPacketTime + 2000 <= nowMs) { // A packet should never be more than two seconds late UpdateJitterAndDelayEstimates(_waitingForCompletion, true); _waitingForCompletion.latestPacketTime = -1; _waitingForCompletion.frameSize = 0; _waitingForCompletion.timestamp = 0; } } if (frame != NULL) { VCMFrameBufferStateEnum state = frame->GetState(); _lastDecodedState.UpdateOldPacket(&packet); // Insert packet // Check for first packet // High sequence number will be -1 if neither an empty packet nor // a media packet has been inserted. bool first = (frame->GetHighSeqNum() == -1); // When in Hybrid mode, we allow for a decodable state // Note: Under current version, a decodable frame will never be // triggered, as the body of the function is empty. // TODO (mikhal): Update when decodable is enabled. bufferReturn = frame->InsertPacket(packet, nowMs, _nackMode == kNackHybrid, _rttMs); ret = bufferReturn; if (bufferReturn > 0) { _incomingBitCount += packet.sizeBytes << 3; // Has this packet been nacked or is it about to be nacked? if (IsPacketRetransmitted(packet)) { frame->IncrementNackCount(); } // Insert each frame once on the arrival of the first packet // belonging to that frame (media or empty) if (state == kStateEmpty && first) { ret = kFirstPacket; FrameList::reverse_iterator rit = std::find_if( _frameList.rbegin(), _frameList.rend(), FrameSmallerTimestamp(frame->TimeStamp())); _frameList.insert(rit.base(), frame); } } } switch(bufferReturn) { case kStateError: case kTimeStampError: case kSizeError: { if (frame != NULL) { // Will be released when it gets old. frame->Reset(); frame->SetState(kStateEmpty); } break; } case kCompleteSession: { // Only update return value for a JB flush indicator. if (UpdateFrameState(frame) == kFlushIndicator) ret = kFlushIndicator; // Signal that we have a received packet _packetEvent.Set(); break; } case kDecodableSession: case kIncomplete: { // Signal that we have a received packet _packetEvent.Set(); break; } case kNoError: case kDuplicatePacket: { break; } default: { assert(false && "JitterBuffer::InsertPacket: Undefined value"); } } return ret; } // Must be called from within _critSect void VCMJitterBuffer::UpdateOldJitterSample(const VCMPacket& packet) { if (_waitingForCompletion.timestamp != packet.timestamp && LatestTimestamp(_waitingForCompletion.timestamp, packet.timestamp, NULL) == packet.timestamp) { // This is a newer frame than the one waiting for completion. _waitingForCompletion.frameSize = packet.sizeBytes; _waitingForCompletion.timestamp = packet.timestamp; } else { // This can get bad if we have a lot of duplicate packets, // we will then count some packet multiple times. _waitingForCompletion.frameSize += packet.sizeBytes; _jitterEstimate.UpdateMaxFrameSize(_waitingForCompletion.frameSize); } } // Must be called from within _critSect bool VCMJitterBuffer::IsPacketRetransmitted(const VCMPacket& packet) const { if (_NACKSeqNumLength > 0) { for (WebRtc_UWord16 i = 0; i < _NACKSeqNumLength; i++) { if (packet.seqNum == _NACKSeqNum[i]) { return true; } } } return false; } // Get nack status (enabled/disabled) VCMNackMode VCMJitterBuffer::GetNackMode() const { CriticalSectionScoped cs(_critSect); return _nackMode; } // Set NACK mode void VCMJitterBuffer::SetNackMode(VCMNackMode mode, int lowRttNackThresholdMs, int highRttNackThresholdMs) { CriticalSectionScoped cs(_critSect); _nackMode = mode; assert(lowRttNackThresholdMs >= -1 && highRttNackThresholdMs >= -1); assert(highRttNackThresholdMs == -1 || lowRttNackThresholdMs <= highRttNackThresholdMs); assert(lowRttNackThresholdMs > -1 || highRttNackThresholdMs == -1); _lowRttNackThresholdMs = lowRttNackThresholdMs; _highRttNackThresholdMs = highRttNackThresholdMs; if (_nackMode == kNoNack) { _jitterEstimate.ResetNackCount(); } } // Recycle oldest frames up to a key frame, used if JB is completely full bool VCMJitterBuffer::RecycleFramesUntilKeyFrame() { // Remove up to oldest key frame while (_frameList.size() > 0) { // Throw at least one frame. _dropCount++; FrameList::iterator it = _frameList.begin(); WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(_vcmId, _receiverId), "Jitter buffer drop count:%d, lowSeq %d", _dropCount, (*it)->GetLowSeqNum()); RecycleFrame(*it); it = _frameList.erase(it); if (it != _frameList.end() && (*it)->FrameType() == kVideoFrameKey) { // Fake the lastDecodedState to match this key frame. _lastDecodedState.SetStateOneBack(*it); return true; } } _waitingForKeyFrame = true; _lastDecodedState.Reset(); // TODO (mikhal): no sync return false; } // Must be called under the critical section _critSect. void VCMJitterBuffer::CleanUpOldFrames() { while (_frameList.size() > 0) { VCMFrameBuffer* oldestFrame = _frameList.front(); bool nextFrameEmpty = (_lastDecodedState.ContinuousFrame(oldestFrame) && oldestFrame->GetState() == kStateEmpty); if (_lastDecodedState.IsOldFrame(oldestFrame) || (nextFrameEmpty && _frameList.size() > 1)) { ReleaseFrameInternal(_frameList.front()); _frameList.erase(_frameList.begin()); } else { break; } } } // Used in GetFrameForDecoding void VCMJitterBuffer::VerifyAndSetPreviousFrameLost(VCMFrameBuffer& frame) { frame.MakeSessionDecodable(); // Make sure the session can be decoded. if (frame.FrameType() == kVideoFrameKey) return; if (!_lastDecodedState.ContinuousFrame(&frame)) frame.SetPreviousFrameLoss(); } bool VCMJitterBuffer::WaitForNack() { // NACK disabled -> can't wait if (_nackMode == kNoNack) { return false; } // NACK only -> always wait else if (_nackMode == kNackInfinite) { return true; } // else: hybrid mode, evaluate // RTT high, don't wait if (_highRttNackThresholdMs >= 0 && _rttMs >= static_cast<unsigned int>(_highRttNackThresholdMs)) { return false; } // Either NACK only or hybrid return true; } } // namespace webrtc
30.602477
82
0.606293
ilin-in
ee64c8ab261a9460de3a9153b9d166822cea5f97
975
cpp
C++
Graphs/no_of_connected_comp.cpp
git-elliot/competitive_programming_codes
b8b5646ae5074b453e7f1af982af174b9c4138e1
[ "MIT" ]
1
2021-06-20T17:28:54.000Z
2021-06-20T17:28:54.000Z
Graphs/no_of_connected_comp.cpp
git-elliot/competitive_programming_codes
b8b5646ae5074b453e7f1af982af174b9c4138e1
[ "MIT" ]
null
null
null
Graphs/no_of_connected_comp.cpp
git-elliot/competitive_programming_codes
b8b5646ae5074b453e7f1af982af174b9c4138e1
[ "MIT" ]
null
null
null
// Find number of connected components in an undirected graph #include <iostream> #include <vector> using namespace std; vector<int> parent; int find(int w){ if(w == parent[w]){ return w; } return find(parent[w]); } void doUnion(int u, int v){ int uP = find(u); int vP = find(v); parent[uP] = vP; } int numberOfConnectedComponents(vector<pair<int,int> > edges){ for(int i=0; i<edges.size(); i++){ pair<int,int> p = edges[i]; doUnion(p.first, p.second); } int count = 0; for(int i=0; i<parent.size(); i++){ if(parent[i] == i){ count++; } } return count; } int main(){ int i,v,e; cin>>v>>e; vector<pair<int,int> > edges; int e1,e2; for(i=0; i < e; i++){ cin>>e1>>e2; edges.push_back(make_pair(e1,e2)); } parent.resize(v); for(i=0; i<v; i++){ parent[i] = i; } cout<<numberOfConnectedComponents(edges); }
17.727273
62
0.532308
git-elliot
ee661d5d99664556748e1f3d3c9946146b7ba652
14,177
cpp
C++
src/html.cpp
calsev/ork
0247981395e28d68b3a446f62b2e426ea752a322
[ "MIT" ]
null
null
null
src/html.cpp
calsev/ork
0247981395e28d68b3a446f62b2e426ea752a322
[ "MIT" ]
4
2018-01-19T01:24:28.000Z
2018-01-19T01:27:07.000Z
src/html.cpp
calsev/ork
0247981395e28d68b3a446f62b2e426ea752a322
[ "MIT" ]
null
null
null
/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #include "ork/ork.hpp" #define ORK_STL_INC_FILE <string> #include "ork/core/stl_include.inl" #define ORK_STL_INC_FILE <sstream> #include "ork/core/stl_include.inl" #include "ork/html.hpp" namespace ork { namespace html { std::ostream& pair::export_html(std::ostream& out) const { out << export_html(key, value); return out; } bstring pair::export_html(const bstring& key, const bstring& val) { return key + BORK(" = \"") + val + BORK("\""); } std::ostream& string::export_html(std::ostream& out) const { out << text; return out; } std::ostream& heading::export_html(std::ostream& out) const { out << BORK("<h") << level << BORK(" ") << pair::export_html(BORK("class"), style) << BORK(">") << text << BORK("</h") << level << BORK(">\n"); return out; } std::ostream& page_break::export_html(std::ostream& out) const { out << BORK( "<p style=\"page-break-after: always;\"><!--pagebreak--></p>\n\n"); return out; } std::ostream& image::export_html(std::ostream& out) const { out << BORK("<img class=\"") << style << BORK("\" src=\"") << source << BORK("\" "); if(!alt_text.empty()) out << pair::export_html(BORK("alt"), alt_text) << BORK(" "); if(width > 0) out << BORK("width=\"") << width << BORK("px\" "); if(height > 0) out << BORK("height=\"") << height << BORK("px\" "); // TODO: Handle border // TODO: Handle float /* style="float:left;width:42px;height:42px; */ out << pair::export_html(BORK("style"), BORK("border-style:none")); out << BORK(">\n"); return out; } /* <img src = "FADAL%20-%204%20-%20AXIS%20VMC%20MM1.jpg" width = "340px" height = "54px" style = "border-style:none;" / > */ bstring padding::export_html() const { b_string_stream out; out << BORK("padding: ") << top << BORK("px ") << right << BORK("px ") << bottom << BORK("px ") << left << BORK("px;"); return out.str(); } style::style(const bstring& name_, const int size_pct_, const int width_, const unsigned flags_) : name(name_) , size_pct(size_pct_) , width(width_) , flags(flags_) {} style::style( const bstring& name_, const int size_pct_, const int width_, const unsigned flags_, const bstring& color_, const bstring& background_, const padding& pad_) : name(name_) , size_pct(size_pct_) , width(width_) , flags(flags_) , color(color_) , background(background_) , pad(pad_) {} bool style::decorated() const { return (flags & (overline | thruline | underline)) != 0; } std::ostream& style::export_html(std::ostream& out) const { out << name << BORK(" { "); out << BORK("font: "); out << size_pct << BORK("% "); out << (flags & serif ? BORK("serif") : BORK("sans-serif")) << BORK("; "); out << BORK("margin: 0; "); if(flags & bold) out << BORK("font-weight: bold; "); if(width > 0) out << BORK("width: ") << width << BORK("px; "); if(flags & italic) out << BORK("font-style: italic; "); if(decorated()) { out << BORK("text-decoration:"); bool comma = false; if(flags & overline) { out << BORK(" overline"); comma = true; } if(flags & thruline) { out << (comma ? BORK(", ") : BORK("")) << BORK(" thruline"); comma = true; } if(flags & underline) { out << (comma ? BORK(", ") : BORK("")) << BORK(" underline"); comma = true; } out << BORK("; "); } out << BORK("color: #") << color << BORK("; "); if(!background.empty()) { out << BORK("background: #") + background + BORK(" !important; "); } out << pad.export_html(); out << BORK(" }\n"); return out; } std::ostream& image_style::export_html(std::ostream& out) const { out << BORK("img.") << name << BORK(" { margin: 0 auto; "); if(alignment == align::left) { out << BORK("float: left; "); } else if(alignment == align::right) { out << BORK("float: right; "); } else { out << BORK("clear: both; "); } out << pad.export_html(); out << BORK(" }\n"); return out; } div_style::div_style(const bstring& name_, const unsigned width_px_, const align a, const bstring& color) : name(name_) , width_px(width_px_) , alignment(a) , back_color(color) {} std::ostream& div_style::export_html(std::ostream& out) const { out << BORK("div.") << name << BORK(" { margin: 0 auto; "); if(width_px > 0) { out << BORK("width: ") << width_px << BORK("px; "); } if(alignment == align::left) { out << BORK("float: left; "); } else if(alignment == align::right) { out << BORK("float: right; "); } else { out << BORK("clear: both; "); } if(!back_color.empty()) { out << BORK("background-color: #") << back_color << BORK("; "); } out << BORK("}\n"); return out; } table_style::table_style( const bstring& name_, const unsigned border_width_, const border bord, const bstring& color_, const unsigned width_pct_, const unsigned height_px_, const unsigned padding_px_) : name(name_) , border_width(border_width_) , borders(bord) , color(color_) , width_pct(width_pct_) , height_px(height_px_) , padding_px(padding_px_) {} std::ostream& table_style::export_html(std::ostream& out) const { out << BORK("table.") << name << BORK(" { "); if(border_width > 0 && borders != border::none) { if(borders == border::both || borders == border::outside) { out << BORK("border: ") << border_width << BORK("px solid #") << color << BORK("; "); } else { // borders == border::inside; // We must mask the outside borders out << BORK("border: ") << border_width << BORK("px solid border-style: hidden; "); } } out << BORK("border-collapse: collapse; "); // We have not been able to come up with a scenario where we want '90s-style tables if(width_pct > 0) { out << BORK("width: ") << width_pct << BORK("%; "); } if(height_px > 0) { out << BORK("height: ") << height_px << BORK("px; "); } if(padding_px > 0) { out << BORK("padding: ") << padding_px << BORK("px; "); } out << BORK("}\n"); /* Done with the table proper, now for headers, rows, elements */ if(border_width > 0 && borders != border::none && borders != border::outside) { #if 0 #elif 0 out << BORK("\ttable.") << name << BORK(" th, td { "); out << BORK("border: ") << border_width << BORK("px solid #") << color << BORK("; "); out << BORK("}\n"); #else out << BORK("\ttable.") << name << BORK(" tr+tr { "); out << BORK("border-top: ") << border_width << BORK("px solid #") << color << BORK("; "); out << BORK("}\n"); out << BORK("\ttable.") << name << BORK(" th+th, td+td { "); out << BORK("border-left: ") << border_width << BORK("px solid #") << color << BORK("; "); out << BORK("}\n"); #endif } return out; } line_style::line_style( const bstring& name_, const unsigned width, const align a, const bstring& color_, const unsigned top_px, const unsigned bottom_px, const unsigned height_px_) : name(name_) , width_pct(width) , alignment(a) , color(color_) , top_pad(top_px) , bottom_pad(bottom_px) , height_px(height_px_) {} std::ostream& line_style::export_html(std::ostream& out) const { out << BORK("hr.") << name << BORK(" { display: block; clear: both; border: 0 none; margin: 0; "); if(width_pct > 0) { out << BORK("width: ") << width_pct << BORK("%; "); } if(top_pad > 0) { out << BORK("pad-top: ") << top_pad << BORK("px; "); out << BORK("margin-top: ") << top_pad << BORK("px; "); } if(bottom_pad > 0) { out << BORK("pad-bottom: ") << bottom_pad << BORK("px; "); out << BORK("margin-bottom: ") << bottom_pad << BORK("px; "); } out << BORK("height: 0px; "); if(height_px > 0) { // out << BORK("height: ") << height_px << BORK("px; ");//The hr itself will not print out << BORK("border-bottom: solid ") << height_px << BORK("px; "); } if(alignment == align::left) { out << BORK("margin-left: 0; "); out << BORK("margin-right: auto; "); } else if(alignment == align::right) { out << BORK("margin-left: auto; "); out << BORK("margin-right: 0; "); } else { out << BORK("margin-left: auto; "); out << BORK("margin-right: auto; "); } out << BORK("color: #") << color << BORK("; "); out << BORK("border-color: #") << color << BORK("; "); out << BORK("background-color: #") << color << BORK("; "); out << BORK("noshade: noshade; "); out << BORK("}\n"); return out; } /* hr { border-width: 1px; border-top: 1px solid; padding: 0; margin: 1em 0; margin-top: 0.5em; margin-bottom: 0.5em; margin-left: auto; margin-right: auto; border-style: inset; } */ std::ostream& style_set::export_html(std::ostream& out) const { out << BORK("<style>\n"); LOOPVI(styles) { out << BORK("\t"); styles[i].export_html(out); } LOOPVI(image_styles) { out << BORK("\t"); image_styles[i].export_html(out); } LOOPVI(div_styles) { out << BORK("\t"); div_styles[i].export_html(out); } LOOPVI(table_styles) { out << BORK("\t"); table_styles[i].export_html(out); } LOOPVI(line_styles) { out << BORK("\t"); line_styles[i].export_html(out); } out << BORK("\t@media print{\n"); LOOPVI(styles) { if(!styles[i].background.empty()) { out << BORK("\t\t") << styles[i].name << BORK(" { background: #") << styles[i].color << BORK(" !important; "); // out << BORK("-webkit-print-color-adjust: exact; ");//Hack for Chrome/Firefox that makes the color black out << BORK("}\n"); } } LOOPVI(line_styles) { out << BORK("\t\thr.") << line_styles[i].name << BORK(" { display: block; }\n"); } out << BORK("\t}\n"); out << BORK("</style>\n"); return out; } void meta(const bstring& key, const bstring& val, std::ostream& out) { out << BORK("<meta ") << pair::export_html(key, val) << BORK(">\n"); } std::ostream& header::export_html(std::ostream& out) const { out << BORK("<head>\n"); meta(BORK("charset"), encoding, out); if(!author.empty()) meta(BORK("author"), author, out); if(!description.empty()) meta(BORK("description"), description, out); styles.export_html(out); if(!title.empty()) out << BORK("<title>") << title << BORK("</title>\n"); out << BORK("</head>\n"); return out; } std::ostream& line::export_html(std::ostream& out) const { out << BORK("<hr class=\"") << style << BORK("\">\n"); return out; } std::ostream& label::export_html(std::ostream& out) const { #if 0 out << BORK("<pre>") << text << BORK("</pre>"); #else out << text; #endif return out; } void table_element::export_html(const exportable* element, const size_t remain_col, std::ostream& out) { if(element != nullptr) { out << BORK("<td"); if(element->col_span) out << pair::export_html(BORK(" colspan"), std::to_string(remain_col)); if(!element->style.empty()) out << pair::export_html(BORK(" class"), element->style); out << BORK(">"); element->export_html(out); } else { out << BORK("<td>"); } out << BORK("</td>"); } void table::insert_row() { _rows.push_back(row_type()); _rows.back().resize(_num_column); } void table::insert_label(const bstring& style_, const bstring& text) { insert_row(); _rows.back()[0].reset(new label(style_, text)); } table::row_type& table::at(const size_t index) { return _rows.at(index); } const table::row_type& table::at(const size_t index) const { return _rows.at(index); } table::row_type& table::back() { return _rows.back(); } const table::row_type& table::back() const { return _rows.back(); } std::ostream& table::export_html(std::ostream& out) const { out << BORK("<table"); if(!_table_style.empty()) { out << BORK(" class=\"") << _table_style << BORK("\""); } else { if(padding > 0) out << BORK(" cellpadding=\"") << padding << BORK("\""); if(spacing > 0) out << BORK(" cellspacing=\"") << spacing << BORK("\""); } out << BORK(">\n"); for(const table::row_type& row : _rows) { out << BORK("<tr>"); LOOPVI(row) { const ptr_type& element = row[i]; table_element::export_html(element.get(), _num_column - i, out); if(element && element->col_span) break; } out << BORK("</tr>\n"); } out << BORK("</table>\n"); return out; } std::ostream& div::export_html(std::ostream& out) const { out << BORK("<div class=\"") << style << BORK("\">\n"); for(const ptr_type& element : elements) { if(element) element->export_html(out); } out << BORK("</div>\n"); return out; } std::ostream& body::export_html(std::ostream& out) const { out << BORK("<body>\n"); for(const div& d : divs) { d.export_html(out); } out << BORK("</body>\n"); return out; } std::ostream& document::export_html(std::ostream& out) const { out << BORK("<!DOCTYPE html>\n"); // Support HTML 5 out << BORK("<html>\n"); head.export_html(out); body.export_html(out); out << BORK("</html>\n"); return out; } } // namespace html } // namespace ork
26.648496
131
0.533822
calsev
ee67959d94149b0b90f698e30424b7ac81b1807b
1,214
cpp
C++
Submissions/Codeforces/186A.cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
null
null
null
Submissions/Codeforces/186A.cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
null
null
null
Submissions/Codeforces/186A.cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define fo(int, i, a, b) for (int i=a; i<(b); i++) #define forev(int, i, b, a) for (int i = (b)-1; i >= a; i--) #define uns unsigned #define lli long long int #define ld long double #define all(x) x.begin(), x.end() #define sortall(x) sort(all(x)) #define enl "\n" // #define PI 3.1415926535897932384626 // const int MOD = 1000000007; const lli INF = 1e18; const int MX = 100001; void solve() { string s1, s2; getline(cin, s1); getline(cin, s2); int cnt = 0; if (s1.length() != s2.length()) { cout << "NO"; return; } int a = -1, b; for (int i = 0; i < (int)s1.length(); ++i) { if (s1[i] != s2[i]) { cnt++; if (a == -1) a = i; b = i; } } if (cnt != 2) { cout << "NO"; return; } swap(s1[a], s1[b]); cout << ((s1 == s2) ? "YES" : "NO") << enl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); // int testcase; cin >> testcase; for (int i = 1; i <= testcase; ++i) solve(); return 0; }
25.291667
75
0.442339
purhan
ee691a9a0f0436a7916f89d82b7b286d86a6b921
643
cpp
C++
Leetcode/minimum-subsequence-in-non-increasing-order.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
Leetcode/minimum-subsequence-in-non-increasing-order.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
Leetcode/minimum-subsequence-in-non-increasing-order.cpp
gnomegeek/cp-submissions
c046be42876794d7cc6216db4e44a23c1174742d
[ "MIT" ]
null
null
null
class Solution { public: vector<int> minSubsequence(vector<int>& nums) { sort(nums.begin(), nums.end()); int sum = 0; for (int i = 0; i < nums.size(); i++) sum += nums[i]; int start = -1; int curSum = 0; for (int i = 0; i < nums.size(); i++) { curSum += nums[i]; if (curSum >= sum - curSum) { start = i; break; } } cout << start << " "; vector<int> res; for (int i = nums.size() - 1; i >= max(start, 0); i--) { res.push_back(nums[i]); } return res; } };
24.730769
64
0.401244
gnomegeek
ee6cd880c16b6a3701d3fbcfc2bf8fe711c55e38
3,587
hpp
C++
data-struct/cht/ConvexHullTrickAddMonotone.hpp
shiomusubi496/library
907f72eb6ee4ac6ef617bb359693588167f779e7
[ "MIT" ]
3
2021-11-04T08:45:12.000Z
2021-11-29T08:44:26.000Z
data-struct/cht/ConvexHullTrickAddMonotone.hpp
shiomusubi496/library
907f72eb6ee4ac6ef617bb359693588167f779e7
[ "MIT" ]
null
null
null
data-struct/cht/ConvexHullTrickAddMonotone.hpp
shiomusubi496/library
907f72eb6ee4ac6ef617bb359693588167f779e7
[ "MIT" ]
null
null
null
#pragma once #include "../../other/template.hpp" template<class T = ll, bool is_max = false, class LargeT = __int128_t> class ConvexHullTrickAddMonotone { protected: struct Line { T a, b; bool is_query; mutable ll nxt_a, nxt_b; mutable bool has_nxt; T get(T x) const { return a * x + b; } T get_nxt(T x) const { return nxt_a * x + nxt_b; } Line() = default; Line(T a, T b, bool i = false) : a(a), b(b), is_query(i), has_nxt(false) {} friend bool operator<(const Line& lhs, const Line& rhs) { assert(!lhs.is_query || !rhs.is_query); if (lhs.is_query) { if (!rhs.has_nxt) return true; return rhs.get(lhs.a) < rhs.get_nxt(lhs.a); } if (rhs.is_query) { if (!lhs.has_nxt) return false; return lhs.get(rhs.a) > lhs.get_nxt(rhs.a); } return lhs.a == rhs.a ? lhs.b < rhs.b : lhs.a < rhs.a; } }; std::deque<Line> que; bool is_necessary(const typename std::deque<Line>::iterator& itr) { if (itr != que.begin() && itr->a == prev(itr)->a) return itr->b < prev(itr)->b; if (itr != prev(que.end()) && itr->a == next(itr)->a) return itr->b < next(itr)->b; if (itr == que.begin() || itr == prev(que.end())) return true; return (LargeT)(itr->b - prev(itr)->b) * (next(itr)->a - itr->a) < (LargeT)(itr->b - next(itr)->b) * (prev(itr)->a - itr->a); } public: ConvexHullTrickAddMonotone() = default; void add_line(T a, T b) { if IF_CONSTEXPR (is_max) a = - a, b = - b; typename std::deque<Line>::iterator itr; if (que.empty() || que.back().a <= a) { que.emplace_back(a, b); itr = prev(que.end()); } else { assert(a <= que.front().a); que.emplace_front(a, b); itr = que.begin(); } if (!is_necessary(itr)) { que.erase(itr); return; } while (itr != que.begin() && !is_necessary(prev(itr))) { que.pop_back(); que.pop_back(); que.emplace_back(a, b); itr = prev(que.end()); } while (itr != prev(que.end()) && !is_necessary(next(itr))) { que.pop_front(); que.pop_front(); que.emplace_front(a, b); itr = que.begin(); } if (itr != que.begin()) { prev(itr)->nxt_a = itr->a; prev(itr)->nxt_b = itr->b; prev(itr)->has_nxt = true; } if (itr != prev(que.end())) { itr->nxt_a = next(itr)->a; itr->nxt_b = next(itr)->b; itr->has_nxt = true; } else itr->has_nxt = false; } T get_min(T x) const { auto itr = lower_bound(all(que), Line{x, 0, true}); if IF_CONSTEXPR (is_max) return - itr->get(x); return itr->get(x); } T inc_get_min(T x) { while (que.size() > 1 && que.begin()->get(x) > next(que.begin())->get(x)) que.pop_front(); if IF_CONSTEXPR (is_max) return - que.front().get(x); return que.front().get(x); } T dec_get_min(T x) { while (que.size() > 1 && prev(que.end())->get(x) > prev(que.end(), 2)->get(x)) que.pop_back(); if IF_CONSTEXPR (is_max) return - que.back().get(x); return que.back().get(x); } bool empty() const { return que.empty(); } }; /** * @brief ConvexHullTrickAddMonotone * @docs docs/ConvexHullTrickAddMonotone.md */
35.514851
105
0.4954
shiomusubi496
ee6f4dabcb2d3e0542f95058ed5d15eb2c10cf35
615
cpp
C++
unittest/ctable_test.cpp
Jamaika1/charls
2abc1561925031b10f68666421315b2f3c63bbab
[ "BSD-3-Clause" ]
null
null
null
unittest/ctable_test.cpp
Jamaika1/charls
2abc1561925031b10f68666421315b2f3c63bbab
[ "BSD-3-Clause" ]
null
null
null
unittest/ctable_test.cpp
Jamaika1/charls
2abc1561925031b10f68666421315b2f3c63bbab
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) Team CharLS. // SPDX-License-Identifier: BSD-3-Clause #include "pch.h" #include "util.h" #include "../src/lookup_table.h" using Microsoft::VisualStudio::CppUnitTestFramework::Assert; using namespace charls; // clang-format off namespace CharLSUnitTest { TEST_CLASS(ctable_test) { public: TEST_METHOD(CTable_create) { const CTable golomb_table; for (int i = 0; i < 256; i++) { Assert::AreEqual(0, golomb_table.Get(i).GetLength()); Assert::AreEqual(0, golomb_table.Get(i).GetValue()); } } }; } // namespace CharLSUnitTest
18.088235
65
0.642276
Jamaika1
ee7020995470805c1885b07289c220a2404a81f6
8,650
cc
C++
errno.cc
rescrv/po6
7bd35b7cd9f6e49799852892c73d24d336de2275
[ "BSD-3-Clause" ]
16
2015-06-19T02:53:00.000Z
2022-01-20T03:21:22.000Z
errno.cc
rescrv/po6
7bd35b7cd9f6e49799852892c73d24d336de2275
[ "BSD-3-Clause" ]
4
2015-02-18T15:28:36.000Z
2017-09-03T20:07:16.000Z
errno.cc
rescrv/po6
7bd35b7cd9f6e49799852892c73d24d336de2275
[ "BSD-3-Clause" ]
12
2015-01-05T08:46:45.000Z
2019-09-15T01:48:07.000Z
// Copyright (c) 2015, Robert Escriva // 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 po6 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. // C #include <string.h> // POSIX #include <errno.h> // po6 #include <po6/errno.h> std::string po6 :: strerror(int err) { int saved = errno; char buf[1024]; memset(buf, 0, sizeof(buf)); errno = 0; #if _GNU_SOURCE // GNU char* ret = strerror_r(err, buf, sizeof(buf)); if (ret != buf) { strncpy(buf, ret, sizeof(buf)); } #else // XSI-compliant errno = strerror_r(err, buf, sizeof(buf)); #endif int obs = errno; errno = saved; if (obs != 0) { return "unknown error"; } buf[sizeof(buf) - 1] = '\0'; return std::string(buf); } #define CSTRINGIFY(x) if ((x) == err) { return #x; } const char* po6 :: strerrno(int err) { if (err == 0) { return ""; } #ifdef E2BIG CSTRINGIFY(E2BIG) #endif #ifdef EACCES CSTRINGIFY(EACCES) #endif #ifdef EADDRINUSE CSTRINGIFY(EADDRINUSE) #endif #ifdef EADDRNOTAVAIL CSTRINGIFY(EADDRNOTAVAIL) #endif #ifdef EAFNOSUPPORT CSTRINGIFY(EAFNOSUPPORT) #endif #ifdef EAGAIN CSTRINGIFY(EAGAIN) #endif #ifdef EALREADY CSTRINGIFY(EALREADY) #endif #ifdef EAUTH CSTRINGIFY(EAUTH) #endif #ifdef EBADE CSTRINGIFY(EBADE) #endif #ifdef EBADF CSTRINGIFY(EBADF) #endif #ifdef EBADFD CSTRINGIFY(EBADFD) #endif #ifdef EBADMSG CSTRINGIFY(EBADMSG) #endif #ifdef EBADR CSTRINGIFY(EBADR) #endif #ifdef EBADRPC CSTRINGIFY(EBADRPC) #endif #ifdef EBADRQC CSTRINGIFY(EBADRQC) #endif #ifdef EBADSLT CSTRINGIFY(EBADSLT) #endif #ifdef EBUSY CSTRINGIFY(EBUSY) #endif #ifdef ECANCELED CSTRINGIFY(ECANCELED) #endif #ifdef ECAPMODE CSTRINGIFY(ECAPMODE) #endif #ifdef ECHILD CSTRINGIFY(ECHILD) #endif #ifdef ECHRNG CSTRINGIFY(ECHRNG) #endif #ifdef ECOMM CSTRINGIFY(ECOMM) #endif #ifdef ECONNABORTED CSTRINGIFY(ECONNABORTED) #endif #ifdef ECONNREFUSED CSTRINGIFY(ECONNREFUSED) #endif #ifdef ECONNRESET CSTRINGIFY(ECONNRESET) #endif #ifdef EDEADLK CSTRINGIFY(EDEADLK) #endif #ifdef EDEADLOCK CSTRINGIFY(EDEADLOCK) #endif #ifdef EDESTADDRREQ CSTRINGIFY(EDESTADDRREQ) #endif #ifdef EDOM CSTRINGIFY(EDOM) #endif #ifdef EDOOFUS CSTRINGIFY(EDOOFUS) #endif #ifdef EDQUOT CSTRINGIFY(EDQUOT) #endif #ifdef EEXIST CSTRINGIFY(EEXIST) #endif #ifdef EFAULT CSTRINGIFY(EFAULT) #endif #ifdef EFBIG CSTRINGIFY(EFBIG) #endif #ifdef EFTYPE CSTRINGIFY(EFTYPE) #endif #ifdef EHOSTDOWN CSTRINGIFY(EHOSTDOWN) #endif #ifdef EHOSTUNREACH CSTRINGIFY(EHOSTUNREACH) #endif #ifdef EIDRM CSTRINGIFY(EIDRM) #endif #ifdef EILSEQ CSTRINGIFY(EILSEQ) #endif #ifdef EINPROGRESS CSTRINGIFY(EINPROGRESS) #endif #ifdef EINTR CSTRINGIFY(EINTR) #endif #ifdef EINVAL CSTRINGIFY(EINVAL) #endif #ifdef EIO CSTRINGIFY(EIO) #endif #ifdef EISCONN CSTRINGIFY(EISCONN) #endif #ifdef EISDIR CSTRINGIFY(EISDIR) #endif #ifdef EISNAM CSTRINGIFY(EISNAM) #endif #ifdef EKEYEXPIRED CSTRINGIFY(EKEYEXPIRED) #endif #ifdef EKEYREJECTED CSTRINGIFY(EKEYREJECTED) #endif #ifdef EKEYREVOKED CSTRINGIFY(EKEYREVOKED) #endif #ifdef EL2HLT CSTRINGIFY(EL2HLT) #endif #ifdef EL2NSYNC CSTRINGIFY(EL2NSYNC) #endif #ifdef EL3HLT CSTRINGIFY(EL3HLT) #endif #ifdef EL3RST CSTRINGIFY(EL3RST) #endif #ifdef ELIBACC CSTRINGIFY(ELIBACC) #endif #ifdef ELIBBAD CSTRINGIFY(ELIBBAD) #endif #ifdef ELIBEXEC CSTRINGIFY(ELIBEXEC) #endif #ifdef ELIBMAX CSTRINGIFY(ELIBMAX) #endif #ifdef ELIBSCN CSTRINGIFY(ELIBSCN) #endif #ifdef ELOOP CSTRINGIFY(ELOOP) #endif #ifdef EMEDIUMTYPE CSTRINGIFY(EMEDIUMTYPE) #endif #ifdef EMFILE CSTRINGIFY(EMFILE) #endif #ifdef EMLINK CSTRINGIFY(EMLINK) #endif #ifdef EMSGSIZE CSTRINGIFY(EMSGSIZE) #endif #ifdef EMULTIHOP CSTRINGIFY(EMULTIHOP) #endif #ifdef ENAMETOOLONG CSTRINGIFY(ENAMETOOLONG) #endif #ifdef ENEEDAUTH CSTRINGIFY(ENEEDAUTH) #endif #ifdef ENETDOWN CSTRINGIFY(ENETDOWN) #endif #ifdef ENETRESET CSTRINGIFY(ENETRESET) #endif #ifdef ENETUNREACH CSTRINGIFY(ENETUNREACH) #endif #ifdef ENFILE CSTRINGIFY(ENFILE) #endif #ifdef ENOATTR CSTRINGIFY(ENOATTR) #endif #ifdef ENOBUFS CSTRINGIFY(ENOBUFS) #endif #ifdef ENODATA CSTRINGIFY(ENODATA) #endif #ifdef ENODEV CSTRINGIFY(ENODEV) #endif #ifdef ENOENT CSTRINGIFY(ENOENT) #endif #ifdef ENOEXEC CSTRINGIFY(ENOEXEC) #endif #ifdef ENOKEY CSTRINGIFY(ENOKEY) #endif #ifdef ENOLCK CSTRINGIFY(ENOLCK) #endif #ifdef ENOLINK CSTRINGIFY(ENOLINK) #endif #ifdef ENOMEDIUM CSTRINGIFY(ENOMEDIUM) #endif #ifdef ENOMEM CSTRINGIFY(ENOMEM) #endif #ifdef ENOMSG CSTRINGIFY(ENOMSG) #endif #ifdef ENONET CSTRINGIFY(ENONET) #endif #ifdef ENOPKG CSTRINGIFY(ENOPKG) #endif #ifdef ENOPROTOOPT CSTRINGIFY(ENOPROTOOPT) #endif #ifdef ENOSPC CSTRINGIFY(ENOSPC) #endif #ifdef ENOSR CSTRINGIFY(ENOSR) #endif #ifdef ENOSTR CSTRINGIFY(ENOSTR) #endif #ifdef ENOSYS CSTRINGIFY(ENOSYS) #endif #ifdef ENOTBLK CSTRINGIFY(ENOTBLK) #endif #ifdef ENOTCAPABLE CSTRINGIFY(ENOTCAPABLE) #endif #ifdef ENOTCONN CSTRINGIFY(ENOTCONN) #endif #ifdef ENOTDIR CSTRINGIFY(ENOTDIR) #endif #ifdef ENOTEMPTY CSTRINGIFY(ENOTEMPTY) #endif #ifdef ENOTSOCK CSTRINGIFY(ENOTSOCK) #endif #ifdef ENOTSUP CSTRINGIFY(ENOTSUP) #endif #ifdef ENOTTY CSTRINGIFY(ENOTTY) #endif #ifdef ENOTUNIQ CSTRINGIFY(ENOTUNIQ) #endif #ifdef ENXIO CSTRINGIFY(ENXIO) #endif #ifdef EOPNOTSUPP CSTRINGIFY(EOPNOTSUPP) #endif #ifdef EOVERFLOW CSTRINGIFY(EOVERFLOW) #endif #ifdef EPERM CSTRINGIFY(EPERM) #endif #ifdef EPFNOSUPPORT CSTRINGIFY(EPFNOSUPPORT) #endif #ifdef EPIPE CSTRINGIFY(EPIPE) #endif #ifdef EPROCLIM CSTRINGIFY(EPROCLIM) #endif #ifdef EPROCUNAVAIL CSTRINGIFY(EPROCUNAVAIL) #endif #ifdef EPROGMISMATCH CSTRINGIFY(EPROGMISMATCH) #endif #ifdef EPROGUNAVAIL CSTRINGIFY(EPROGUNAVAIL) #endif #ifdef EPROTO CSTRINGIFY(EPROTO) #endif #ifdef EPROTONOSUPPORT CSTRINGIFY(EPROTONOSUPPORT) #endif #ifdef EPROTOTYPE CSTRINGIFY(EPROTOTYPE) #endif #ifdef ERANGE CSTRINGIFY(ERANGE) #endif #ifdef EREMCHG CSTRINGIFY(EREMCHG) #endif #ifdef EREMOTE CSTRINGIFY(EREMOTE) #endif #ifdef EREMOTEIO CSTRINGIFY(EREMOTEIO) #endif #ifdef ERESTART CSTRINGIFY(ERESTART) #endif #ifdef EROFS CSTRINGIFY(EROFS) #endif #ifdef ERPCMISMATCH CSTRINGIFY(ERPCMISMATCH) #endif #ifdef ESHUTDOWN CSTRINGIFY(ESHUTDOWN) #endif #ifdef ESOCKTNOSUPPORT CSTRINGIFY(ESOCKTNOSUPPORT) #endif #ifdef ESPIPE CSTRINGIFY(ESPIPE) #endif #ifdef ESRCH CSTRINGIFY(ESRCH) #endif #ifdef ESTALE CSTRINGIFY(ESTALE) #endif #ifdef ESTRPIPE CSTRINGIFY(ESTRPIPE) #endif #ifdef ETIME CSTRINGIFY(ETIME) #endif #ifdef ETIMEDOUT CSTRINGIFY(ETIMEDOUT) #endif #ifdef ETXTBSY CSTRINGIFY(ETXTBSY) #endif #ifdef EUCLEAN CSTRINGIFY(EUCLEAN) #endif #ifdef EUNATCH CSTRINGIFY(EUNATCH) #endif #ifdef EUSERS CSTRINGIFY(EUSERS) #endif #ifdef EWOULDBLOCK CSTRINGIFY(EWOULDBLOCK) #endif #ifdef EXDEV CSTRINGIFY(EXDEV) #endif #ifdef EXFULL CSTRINGIFY(EXFULL) #endif return "unknown error"; }
18.058455
79
0.728092
rescrv
ee70a56817215e31cfc441758b28dd7b5c6fdd6b
30,012
cpp
C++
multimedia/directx/dplay/dvoice/dxvutils/sndutils.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dplay/dvoice/dxvutils/sndutils.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dplay/dvoice/dxvutils/sndutils.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*========================================================================== * * Copyright (C) 1999-2002 Microsoft Corporation. All Rights Reserved. * * File: sndutils.cpp * Content: * This module contains the implementation of sound related utility * functions. Functions in this module manipulate WAVEFORMATEX * structures and provide full duplex initialization / testing * facilities. * * This module also contains the routines used to measure peak * of an audio buffer and for voice activation. * * History: * Date By Reason * ==== == ====== * 07/16/99 rodtoll Created * 07/30/99 rodtoll Updated util functions to take GUIDs and allow for * users to pre-create capture/playback devices and * pass them into InitXXXXDuplex * 08/25/99 rodtoll General Cleanup/Modifications to support new * compression sub-system. * 08/30/99 rodtoll Added new playback format param to sound init * 09/03/99 rodtoll Fixed return codes on InitFullDuplex * 09/20/99 rodtoll Now checks for invalid GUIDs for playback/record * 10/05/99 rodtoll Added DPF_MODNAMEs * 10/29/99 rodtoll Bug #113726 - Fixed memory leak when full duplex * fails caused by architecture update. * 11/12/99 rodtoll Updated full duplex test to use new abstracted recording * and playback systems. * rodtoll Updated to allow passing of sounddeviceconfig flags in dwflags * parameter to init is effected by the flags specified by user * rodtoll Sound buffers (rec and playback) are now set to silence before * recording/playback is started. * 11/22/99 rodtoll Removed unnessessary set of recording buffer to silence. * 12/01/99 rodtoll Bug #115783 - Will always adjust volume of default device * Updated for new parameters added by above bug. * 12/08/99 rodtoll Bug #121054 - Support for capture focus and removed flags * from buffer, allow dsound to manage buffer location. * 01/21/2000 pnewson Fixed error cleanup code in InitHalfDuplex * 01/27/2000 rodtoll Updated tests to accept buffer descriptions and play flags/priority * 02/10/2000 rodtoll Removed more capture focus * 02/23/2000 rodtoll Fix to allow to run on dsound7. * 05/19/2000 rodtoll Bug #35395 - Unable to run two copies of DPVHELP on same system without * DirectX 8 installed. * 06/21/2000 rodtoll Bug #35767 - Must implement ability to use effects processing on voice buffers * Updated sound initialization routines to handle buffers being passed in. * 07/12/2000 rodtoll Bug #31468 - Add diagnostic spew to logfile to show what is failing the HW Wizard * 10/04/2000 rodtoll Bug #43510 - DPVOICE: Apps receive a DVMSGID_SESSIONLOST w/DVERR_LOCKEDBUFFER * 01/04/2001 rodtoll WinBug #94200 - Remove stray comments * 01/26/2001 rodtoll WINBUG #293197 - DPVOICE: [STRESS} Stress applications cannot tell difference between out of memory and internal errors. * Remap DSERR_OUTOFMEMORY to DVERR_OUTOFMEMORY instead of DVERR_SOUNDINITFAILURE. * Remap DSERR_ALLOCATED to DVERR_PLAYBACKSYSTEMERROR instead of DVERR_SOUNDINITFAILURE. * 04/12/2001 kareemc WINBUG #360971 - Wizard Memory Leaks * ***************************************************************************/ #include "dxvutilspch.h" #undef DPF_SUBCOMP #define DPF_SUBCOMP DN_SUBCOMP_VOICE #define DSERRBREAK_NAME "DSASSERT" DNCRITICAL_SECTION g_csDSDebug; CHAR g_szLastDirectSoundAPI[100] = ""; HRESULT g_hrLastDirectSoundResult = DS_OK; BOOL g_fDSErrorBreak = FALSE; void DSERTRACK_Update( const char *szAPICall, HRESULT hrResult ) { DNEnterCriticalSection( &g_csDSDebug ); if( SUCCEEDED( g_hrLastDirectSoundResult ) ) { g_hrLastDirectSoundResult = hrResult; strcpy( g_szLastDirectSoundAPI , szAPICall ); } DNLeaveCriticalSection( &g_csDSDebug ); } void DSERRTRACK_Reset() { DNEnterCriticalSection( &g_csDSDebug ); g_hrLastDirectSoundResult = DS_OK; g_szLastDirectSoundAPI[0] = 0; DNLeaveCriticalSection( &g_csDSDebug ); } BOOL DSERRTRACK_Init() { if (!DNInitializeCriticalSection( &g_csDSDebug )) { return FALSE; } // Load the setting for the directsound assert g_fDSErrorBreak = GetProfileIntA( "DirectPlay8", DSERRBREAK_NAME, FALSE ); return TRUE; } void DSERRTRACK_UnInit() { DNDeleteCriticalSection( &g_csDSDebug ); } #undef DPF_MODNAME #define DPF_MODNAME "DV_SetupBufferDesc" void DV_SetupBufferDesc( LPDSBUFFERDESC lpdsBufferDesc, LPDSBUFFERDESC lpdsBufferSource, LPWAVEFORMATEX lpwfxFormat, DWORD dwBufferSize ) { // Confirm specified buffer description is valid if( lpdsBufferSource != NULL ) { if( lpdsBufferSource->dwSize == sizeof( DSBUFFERDESC1 ) ) { memcpy( lpdsBufferDesc, lpdsBufferSource, sizeof( DSBUFFERDESC1 ) ); } else { memcpy( lpdsBufferDesc, lpdsBufferSource, sizeof( DSBUFFERDESC ) ); } // We require the following flags, at a minimum so they should always be set lpdsBufferDesc->dwFlags |= DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2; } // User did not specify a buffer description, let's use our own! else { lpdsBufferDesc->dwSize = sizeof( DSBUFFERDESC ); lpdsBufferDesc->dwFlags = DSBCAPS_CTRL3D | DSBCAPS_CTRLVOLUME | DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2; lpdsBufferDesc->dwBufferBytes = 0; lpdsBufferDesc->dwReserved = 0; lpdsBufferDesc->lpwfxFormat = NULL; lpdsBufferDesc->guid3DAlgorithm = DS3DALG_DEFAULT; } lpdsBufferDesc->lpwfxFormat = lpwfxFormat; lpdsBufferDesc->dwBufferBytes = dwBufferSize; } #undef DPF_MODNAME #define DPF_MODNAME "SetRecordBufferToSilence" HRESULT SetPlaybackBufferToSilence( CAudioPlaybackBuffer *pRecBuffer, const WAVEFORMATEX* lpwfxFormat ) { HRESULT hr; LPVOID pBufferPtr1, pBufferPtr2; DWORD dwBufferSize1, dwBufferSize2; hr = pRecBuffer->Lock( 0, 0, &pBufferPtr1, &dwBufferSize1, &pBufferPtr2, &dwBufferSize2, DSBLOCK_ENTIREBUFFER ); DSERTRACK_Update( "Lock", hr ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Lock() failed during silence write hr=0x%x", hr ); return hr; } memset( pBufferPtr1, (lpwfxFormat->wBitsPerSample==8) ? 0x80 : 0x00, dwBufferSize1 ); hr = pRecBuffer->UnLock( pBufferPtr1, dwBufferSize1, pBufferPtr2, dwBufferSize2 ); DSERTRACK_Update( "UnLock", hr ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unlock() failed uffer unlock failed hr=0x%x", hr ); return hr; } return DV_OK; } #undef DPF_MODNAME #define DPF_MODNAME "InitHalfDuplex" // InitHalfDuplex // // This function initializes the playback system for the // specified compression type and the specified playback // format. This function is used to initialize // the AudioPlaybackDevice and AudioPlaybackBuffer. // // It also starts the audio buffer which is used for voice // output playing. (In looping mode). // // Parameters: // HWND hwnd - // Window handle for the window where the output will // be associated // ARDID playbackDeviceID - // The deviceID for the device which will be used for // playback // CAudioPlaybackDevice ** - // A pointer to a pointer which will contain a pointer // to a newly created CAudioPlaybackDevice which will // represent the playback device on success. // CAudioPlaybackBuffer ** - // A pointer to a pointer which will contain a pointer // to a newly created CAudioPlaybacKbuffer which will // be used for voice audio output on success. // CompressionType ct - // The type of compression which will be in use. Used // to determine buffer sizes etc. // WAVEFORMATEX *primaryFormat - // Pointer to a WAVEFORMATEX structure describing the // format of the voice output. (This will also be used // to set the primary format of the output device if // normal is set to false). // bool normal - // Specifies if normal mode should be used or not. // (Only used when using the DirectSound playback // system. Set to true for normal cooperative mode, // false for priority mode). // // Returns: // bool - // Returns true if playback was initializes succesfully, // false if initialization fails. // HRESULT InitHalfDuplex( HWND hwnd, const GUID &guidPlayback, CAudioPlaybackDevice **audioPlaybackDevice, LPDSBUFFERDESC lpdsBufferDesc, CAudioPlaybackBuffer **audioPlaybackBuffer, const GUID &guidCT, WAVEFORMATEX *primaryFormat, WAVEFORMATEX *lpwfxPlayFormat, DWORD dwPlayPriority, DWORD dwPlayFlags, DWORD dwFlags ) { DWORD frameSize; HRESULT hr; DWORD dwBufferSize; BOOL fPriorityMode; DSBUFFERDESC dsBufferDesc; BOOL fPlaybackDeviceAllocated = FALSE; BOOL fPlaybackBufferAllocated = FALSE; fPriorityMode = !( dwFlags & DVSOUNDCONFIG_NORMALMODE ); // *audioPlaybackBuffer = NULL; DPFX(DPFPREP, DVF_INFOLEVEL, "HALFDUPLEX INIT: Begin ==========" ); LPDVFULLCOMPRESSIONINFO lpdvfInfo; hr = DVCDB_GetCompressionInfo( guidCT, &lpdvfInfo ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Error loading compression type: hr = 0x%x", hr ); goto INIT_EXIT_ERROR2; } if( (*audioPlaybackDevice) == NULL ) { #ifdef __WAVESUBSYSTEM if( !(dwFlags & DVSOUNDCONFIG_FORCEWAVEOUT) ) { #endif // Create the object to represent the device using the playback subsystem's // CreateDevice function (*audioPlaybackDevice) = new CDirectSoundPlaybackDevice(); fPlaybackDeviceAllocated = TRUE; if( *audioPlaybackDevice == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR2; } hr = (*audioPlaybackDevice)->Initialize( guidPlayback, hwnd, primaryFormat, fPriorityMode ); #ifndef __WAVESUBSYSTEM if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize playback. hr=0x%x", hr ); goto INIT_EXIT_ERROR2; } #endif #ifdef __WAVESUBSYSTEM } if( dwFlags & DVSOUNDCONFIG_FORCEWAVEOUT || ((dwFlags & DVSOUNDCONFIG_ALLOWWAVEOUT) && FAILED( hr )) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initialize directsound, defaulting to waveout hr=0x%x", hr ); delete (*audioPlaybackDevice); (*audioPlaybackDevice) = new CWaveOutPlaybackDevice( ); fPlaybackDeviceAllocated = TRUE; if( (*audioPlaybackDevice) == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR2; } hr = (*audioPlaybackDevice)->Initialize( guidPlayback, hwnd, primaryFormat, fPriorityMode ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initalize waveOut. Init failed hr=0x%x", hr ); goto INIT_EXIT_ERROR2; } } else if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize playback. hr=0x%x", hr ); goto INIT_EXIT_ERROR2; } #endif // At this point we should have a valid device, waveOut or DirectSound } DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init" ); // Create a buffer if the user didn't specify one if( !(*audioPlaybackBuffer) ) { frameSize = DVCDB_CalcUnCompressedFrameSize( lpdvfInfo, lpwfxPlayFormat ); dwBufferSize = lpdvfInfo->dwFramesPerBuffer * frameSize; DV_SetupBufferDesc( &dsBufferDesc, lpdsBufferDesc, lpwfxPlayFormat, dwBufferSize ); // Create the audio buffer which will be used for output hr = (*audioPlaybackDevice)->CreateBuffer( &dsBufferDesc, frameSize, audioPlaybackBuffer); fPlaybackBufferAllocated = TRUE; if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to create sound buffer. hr=0x%x", hr ); goto INIT_EXIT_ERROR2; } } DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init 2" ); hr = SetPlaybackBufferToSilence( *audioPlaybackBuffer, lpwfxPlayFormat ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Unable to set playback to silence" ); goto INIT_EXIT_ERROR2; } DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init 3" ); // Start the audio playback buffer playing hr = (*audioPlaybackBuffer)->Play( dwPlayPriority, dwPlayFlags ); if( FAILED( hr ) ) { DPFX(DPFPREP, DVF_ERRORLEVEL, "> Can't play" ); goto INIT_EXIT_ERROR2; } Diagnostics_Write( DVF_INFOLEVEL, "Half Duplex Init Result = DV_OK " ); return DV_OK; // Handle errors INIT_EXIT_ERROR2: if( fPlaybackBufferAllocated && *audioPlaybackBuffer != NULL ) { delete *audioPlaybackBuffer; *audioPlaybackBuffer = NULL; } if( fPlaybackDeviceAllocated && *audioPlaybackDevice != NULL ) { delete *audioPlaybackDevice; *audioPlaybackDevice = NULL; } Diagnostics_Write( DVF_ERRORLEVEL, "Half Duplex Init Result = 0x%x", hr ); return hr; } #undef DPF_MODNAME #define DPF_MODNAME "InitializeRecordBuffer" HRESULT InitializeRecordBuffer( HWND hwnd, const DVFULLCOMPRESSIONINFO* lpdvfInfo, CAudioRecordDevice *parecDevice, CAudioRecordBuffer **pparecBuffer, DWORD dwFlags ) { WAVEFORMATEX *lpwfxRecordFormat; DSCBUFFERDESC1 dscdesc; DWORD dwFrameSize; HRESULT hr; for( DWORD dwIndex = 0; dwIndex < GetNumRecordFormats(); dwIndex++ ) { lpwfxRecordFormat = GetRecordFormat( dwIndex ); dwFrameSize = DVCDB_CalcUnCompressedFrameSize( lpdvfInfo, lpwfxRecordFormat ); memset( &dscdesc, 0x00, sizeof( DSCBUFFERDESC1 ) ); dscdesc.dwSize = sizeof( DSCBUFFERDESC1 ); dscdesc.dwFlags = 0; dscdesc.lpwfxFormat = lpwfxRecordFormat; dscdesc.dwBufferBytes = dwFrameSize*lpdvfInfo->dwFramesPerBuffer; if( !(dwFlags & DVSOUNDCONFIG_NOFOCUS) ) { dscdesc.dwFlags |= DSCBCAPS_FOCUSAWARE; if( dwFlags & DVSOUNDCONFIG_STRICTFOCUS ) { dscdesc.dwFlags |= DSCBCAPS_STRICTFOCUS; } } hr = parecDevice->CreateBuffer( (DSCBUFFERDESC *) &dscdesc, hwnd, dwFrameSize, pparecBuffer ); if( FAILED( hr ) ) { DPFX(DPFPREP, DVF_WARNINGLEVEL, "Could not initialize %d hz, %d bits, %s (hr=0x%x)", lpwfxRecordFormat->nSamplesPerSec, lpwfxRecordFormat->wBitsPerSample, (lpwfxRecordFormat->nChannels==1) ? _T("Mono") : _T("Stereo"), hr ); continue; } else { Diagnostics_Write( DVF_INFOLEVEL, "Recording Initialized. Format=" ); Diagnositcs_WriteWAVEFORMATEX( DVF_INFOLEVEL, lpwfxRecordFormat ); } hr = (*pparecBuffer)->Record(TRUE); if( FAILED( hr ) ) { DPFX(DPFPREP, DVF_WARNINGLEVEL, "Could not start rec at %d hz, %d bits, %s (hr=0x%x)", lpwfxRecordFormat->nSamplesPerSec, lpwfxRecordFormat->wBitsPerSample, (lpwfxRecordFormat->nChannels==1) ? _T("Mono") : _T("Stereo"), hr ); delete (*pparecBuffer); (*pparecBuffer) = NULL; continue; } else { Diagnostics_Write( DVF_INFOLEVEL, "Recording Started. Format=" ); Diagnositcs_WriteWAVEFORMATEX( DVF_INFOLEVEL, lpwfxRecordFormat ); // Reset the directsound erros as we expect errors in this part and if we suceed we handled // them. return DV_OK; } } return DVERR_RECORDSYSTEMERROR; } #undef DPF_MODNAME #define DPF_MODNAME "InitFullDuplex" // InitFullDuplex // // The tricky part. // // This function is responsible for initializing the system into full duplex // mode using the specified parameters. This function will create and // initialize the playback and record devices as well as start the // playback device playing and the recording device recording. (On success). // This is neccessary because the order of Play and Record and device // creation is important. // // Parameters: // HWND hwnd - // Window handle for the window where the output will // be associated // ARDID playbackDeviceID - // The deviceID for the device which will be used for // playback // CAudioPlaybackDevice ** - // A pointer to a pointer which will contain a pointer // to a newly created CAudioPlaybackDevice which will // represent the playback device on success. // CAudioPlaybackBuffer ** - // A pointer to a pointer which will contain a pointer // to a newly created CAudioPlaybacKbuffer which will // be used for voice audio output on success. // ARDID recordDeviceID - // The ARDID for the device which will be used for recording. // CAudioRecordSubSystem *recordSubSystem - // This parameter is a pointer to the object representing // the subsystem which will be used for recording. // CAudioRecordDevice ** - // A pointer to a pointer which will contain a newly // create CAudioRecordDevice for voice recording on // success. // CompressionType ct - // The type of compression which will be in use. Used // to determine buffer sizes etc. // WAVEFORMATEX *primaryFormat - // Pointer to a WAVEFORMATEX structure describing the // format of the voice output. (This will also be used // to set the primary format of the output device if // normal is set to false). // bool aso - // This parameter controls the ASO option. The ASO // option controls the "Startup Order". Enabling // this option allows full duplex to be initialized // on some troublesome cards. // bool normal - // Specifies if normal mode should be used or not. // (Only used when using the DirectSound playback // system. Set to true for normal cooperative mode, // false for priority mode). // // Returns: // bool - true on successful full duplex initialization, // false on failure. // HRESULT InitFullDuplex( HWND hwnd, const GUID &guidPlayback, CAudioPlaybackDevice **audioPlaybackDevice, LPDSBUFFERDESC lpdsBufferDesc, CAudioPlaybackBuffer **audioPlaybackBuffer, const GUID &guidRecord, CAudioRecordDevice **audioRecordDevice, CAudioRecordBuffer **audioRecordBuffer, const GUID &guidCT, WAVEFORMATEX *primaryFormat, WAVEFORMATEX *lpwfxPlayFormat, BOOL aso, DWORD dwPlayPriority, DWORD dwPlayFlags, DWORD dwFlags ) { DWORD frameSize; DWORD dwBufferSize; HRESULT hr; DSBUFFERDESC dsbdesc; BOOL fPriorityMode; BOOL fPlaybackDeviceAllocated = FALSE; BOOL fPlaybackBufferAllocated = FALSE; BOOL fRecordDeviceAllocated = FALSE; fPriorityMode = !(dwFlags & DVSOUNDCONFIG_NORMALMODE); // *audioPlaybackBuffer = NULL; *audioRecordBuffer = NULL; DPFX(DPFPREP, DVF_INFOLEVEL, "FULLDUPLEX INIT: Begin ==========" ); LPDVFULLCOMPRESSIONINFO lpdvfInfo; hr = DVCDB_GetCompressionInfo( guidCT, &lpdvfInfo ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Error loading compression type: hr = 0x%x", hr ); goto INIT_EXIT_ERROR; } if( (*audioPlaybackDevice) == NULL ) { #ifdef __WAVESUBSYSTEM if( !(dwFlags & DVSOUNDCONFIG_FORCEWAVEOUT) ) { #endif // Create the object to represent the device using the playback subsystem's // CreateDevice function (*audioPlaybackDevice) = new CDirectSoundPlaybackDevice(); fPlaybackDeviceAllocated = TRUE; if( *audioPlaybackDevice == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR; } hr = (*audioPlaybackDevice)->Initialize( guidPlayback, hwnd, primaryFormat, fPriorityMode ); #ifndef __WAVESUBSYSTEM if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize playback. hr=0x%x", hr ); goto INIT_EXIT_ERROR; } #endif #ifdef __WAVESUBSYSTEM } if( dwFlags & DVSOUNDCONFIG_FORCEWAVEOUT || ((dwFlags & DVSOUNDCONFIG_ALLOWWAVEOUT) && FAILED( hr )) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initialize directsound, defaulting to waveout hr=0x%x", hr ); delete (*audioPlaybackDevice); (*audioPlaybackDevice) = new CWaveOutPlaybackDevice(); fPlaybackDeviceAllocated = TRUE; if( (*audioPlaybackDevice) == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR; } hr = (*audioPlaybackDevice)->Initialize( guidPlayback, hwnd, primaryFormat, fPriorityMode ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initalize waveOut. Init failed hr=0x%x", hr ); goto INIT_EXIT_ERROR; } } else if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize playback. hr=0x%x", hr ); goto INIT_EXIT_ERROR; } #endif } DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init" ); frameSize = DVCDB_CalcUnCompressedFrameSize( lpdvfInfo, lpwfxPlayFormat ); DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init" ); dwBufferSize = lpdvfInfo->dwFramesPerBuffer * frameSize; if( !(*audioPlaybackBuffer) ) { DV_SetupBufferDesc( &dsbdesc, lpdsBufferDesc, lpwfxPlayFormat, dwBufferSize ); // Create the audio buffer which will be used for output hr = (*audioPlaybackDevice)->CreateBuffer( &dsbdesc, frameSize, audioPlaybackBuffer); fPlaybackBufferAllocated = TRUE; if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to create sound buffer. hr=0x%x", hr ); goto INIT_EXIT_ERROR; } } DPFX(DPFPREP, DVF_INFOLEVEL, "> Play init 2" ); DPFX(DPFPREP, DVF_INFOLEVEL, "> Initing Recording" ); // We're creating the device.. if( (*audioRecordDevice) == NULL ) { #ifdef __WAVESUBSYSTEM if( !(dwFlags & DVSOUNDCONFIG_FORCEWAVEIN) ) { #endif (*audioRecordDevice) = new CDirectSoundCaptureRecordDevice(); fRecordDeviceAllocated = TRUE; if( *audioRecordDevice == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR; } hr = (*audioRecordDevice)->Initialize( guidRecord ); // DSC Init passed, try getting a buffer if( SUCCEEDED( hr ) ) { hr = InitializeRecordBuffer( hwnd, lpdvfInfo, *audioRecordDevice, audioRecordBuffer, dwFlags ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize dsc buffer hr=0x%x", hr ); #ifndef __WAVESUBSYSTEM Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize record. hr=0x%x", hr ); goto INIT_EXIT_ERROR; #endif } else { // Need to reset because we expect errors during initialization. DSERRTRACK_Reset(); } } #ifndef __WAVESUBSYSTEM else { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize record. hr=0x%x", hr ); goto INIT_EXIT_ERROR; } #endif #ifdef __WAVESUBSYSTEM } // DSC Init failed, try and get a waveIn device if( dwFlags & DVSOUNDCONFIG_FORCEWAVEIN || ((dwFlags & DVSOUNDCONFIG_ALLOWWAVEIN) && FAILED( hr ))) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initialize directsoundcapture, defaulting to wavein hr=0x%x", hr ); delete (*audioRecordDevice); (*audioRecordDevice) = new CWaveInRecordDevice(); fRecordDeviceAllocated = TRUE; if( (*audioRecordDevice) == NULL ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Out of memory" ); hr = DVERR_OUTOFMEMORY; goto INIT_EXIT_ERROR; } hr = (*audioRecordDevice)->Initialize( guidPlayback ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Could not initalize waveIn. Init failed hr=0x%x", hr ); goto INIT_EXIT_ERROR; } hr = InitializeRecordBuffer( hwnd, lpdvfInfo, *audioRecordDevice, audioRecordBuffer, dwFlags ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize waveIn buffer hr=0x%x", hr ); goto INIT_EXIT_ERROR; } } else if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize record. hr=0x%x", hr ); goto INIT_EXIT_ERROR; } #endif } // Use specified device, just try and create the buffer else { hr = InitializeRecordBuffer( hwnd, lpdvfInfo, *audioRecordDevice, audioRecordBuffer, dwFlags ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "Unable to initialize dsc buffer hr=0x%x", hr ); goto INIT_EXIT_ERROR; } } DPFX(DPFPREP, DVF_INFOLEVEL, "> Rec Init 2" ); hr = SetPlaybackBufferToSilence( *audioPlaybackBuffer, lpwfxPlayFormat ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Unable to set playback to silence" ); goto INIT_EXIT_ERROR; } DPFX(DPFPREP, DVF_INFOLEVEL, "> Rec Init 3" ); // Depending on the ASO parameter start the playback buffer // playing and the recording buffer recording. if( aso ) { DPFX(DPFPREP, DVF_INFOLEVEL, "> ASO " ); hr = (*audioPlaybackBuffer)->Play( dwPlayPriority, dwPlayFlags ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Can't play" ); goto INIT_EXIT_ERROR; } hr = (*audioRecordBuffer)->Record(TRUE); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Can't start recording" ); goto INIT_EXIT_ERROR; } } else { DPFX(DPFPREP, DVF_INFOLEVEL, "> !ASO " ); /* hr = (*audioRecordBuffer)->Record(TRUE); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Can't start recording" ); goto INIT_EXIT_ERROR; } */ hr = (*audioPlaybackBuffer)->Play( dwPlayPriority, dwPlayFlags ); if( FAILED( hr ) ) { Diagnostics_Write( DVF_ERRORLEVEL, "> Can't play" ); goto INIT_EXIT_ERROR; } } DPFX(DPFPREP, DVF_INFOLEVEL, "FULL DUPLEX INIT: End ==========" ); Diagnostics_Write( DVF_INFOLEVEL, "Full Duplex Init Result = DV_OK" ); return DV_OK; INIT_EXIT_ERROR: if( *audioRecordBuffer != NULL ) { delete *audioRecordBuffer; *audioRecordBuffer = NULL; } // Only delete on error if we allocated if( fRecordDeviceAllocated && *audioRecordDevice != NULL ) { delete *audioRecordDevice; *audioRecordDevice = NULL; } // Only delete on error if we allocated if( fPlaybackBufferAllocated && *audioPlaybackBuffer != NULL ) { delete *audioPlaybackBuffer; *audioPlaybackBuffer = NULL; } // Only delete on error if we allocated if( fPlaybackDeviceAllocated && *audioPlaybackDevice != NULL ) { delete *audioPlaybackDevice; *audioPlaybackDevice = NULL; } Diagnostics_Write( DVF_ERRORLEVEL, "Full Duplex Init Result = 0x%x", hr ); return hr; } #undef DPF_MODNAME #define DPF_MODNAME "FindPeak8Bit" // FindPeak8Bit // // This function determines what the peak for a buffer // of 8 bit audio is. Peak is defined as the loudest // sample in a set of audio data rated on a scale of // between 0 and 100. // // Parameters: // BYTE *data - // Pointer to the buffer containing the audio data // to find the peak of. // DWORD frameSize - // The size in bytes of the audio data we are // checking. // // Returns: // BYTE - // The peak of the audio buffer, a value between 0 and 100. // BYTE FindPeak8Bit( const BYTE *data, DWORD frameSize ) { BYTE peak = 0; int tmpData; for( int index = 0; index < frameSize; index++ ) { tmpData = data[index]; tmpData -= 0x80; if( tmpData < 0 ) tmpData *= -1; if( tmpData > peak ) { peak = (unsigned char) tmpData; } } tmpData = peak * 100 / 0x7F; return (BYTE) tmpData; } #undef DPF_MODNAME #define DPF_MODNAME "FindPeak16Bit" // FindPeak16Bit // // This function determines what the peak for a buffer // of 16 bit audio is. Peak is defined as the loudest // sample in a set of audio data rated on a scale of // between 0 and 100. // // Parameters: // BYTE *data - // Pointer to the buffer containing the audio data // to find the peak of. // DWORD frameSize - // The size in bytes of the audio data we are // checking. // // Returns: // BYTE - // The peak of the audio buffer, a value between 0 and 100. // BYTE FindPeak16Bit( const short *data, DWORD frameSize ) { int peak, tmpData; frameSize /= 2; peak = 0; for( int index = 0; index < frameSize; index++ ) { tmpData = data[index]; if( tmpData < 0 ) { tmpData *= -1; } if( tmpData > peak ) { peak = tmpData; } } tmpData = (peak * 100) / 0x7FFF; return (BYTE) tmpData; } #undef DPF_MODNAME #define DPF_MODNAME "FindPeak" // FindPeak // // This function determines what the peak for a buffer // of 8 or 16 bit audio is. Peak is defined as the loudest // sample in a set of audio data rated on a scale of // between 0 and 100. // // Parameters: // BYTE *data - // Pointer to the buffer containing the audio data // to find the peak of. // DWORD frameSize - // The size in bytes of the audio data we are // checking. // BOOL eightBit - // Determins if the buffer is 8 bit or not. Set to // TRUE for 8 bit data, FALSE for 16 bit data. // // Returns: // BYTE - // The peak of the audio buffer, a value between 0 and 100. // BYTE FindPeak( BYTE *data, DWORD frameSize, BOOL eightBit ) { if( eightBit ) { return FindPeak8Bit( data, frameSize ); } else { return FindPeak16Bit( (signed short *) data, frameSize ); } }
30.376518
167
0.666333
npocmaka
ee71cb77bdd00b1aca9632efe4b2f8605c379b3e
688
cpp
C++
dynamic-prog/FARIDA.cpp
stepan-krivanek/spoj
3a91d7e666fd6af5cb2a7978dc20318077e62850
[ "MIT" ]
null
null
null
dynamic-prog/FARIDA.cpp
stepan-krivanek/spoj
3a91d7e666fd6af5cb2a7978dc20318077e62850
[ "MIT" ]
null
null
null
dynamic-prog/FARIDA.cpp
stepan-krivanek/spoj
3a91d7e666fd6af5cb2a7978dc20318077e62850
[ "MIT" ]
null
null
null
#include <iostream> #define ll long long using namespace std; int main(){ int num_of_subjects; cin >> num_of_subjects; int num_of_monsters; for (int subject = 1; subject <= num_of_subjects; subject++){ cin >> num_of_monsters; ll int monster; ll int take = 0; ll int tmp; ll int not_take = 0; for (int i = 0; i < num_of_monsters; i++){ cin >> monster; tmp = not_take; not_take = take > not_take ? take : not_take; take = tmp + monster; } cout << "Case " << subject << ": " << (take > not_take ? take : not_take) << endl; } return 0; }
23.724138
90
0.517442
stepan-krivanek
ee722ddf5b56d5772f624b45b67cadad3afb8208
11,200
cpp
C++
engine/src/ph/renderer/ImGuiRenderer.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/src/ph/renderer/ImGuiRenderer.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/src/ph/renderer/ImGuiRenderer.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #include "ph/renderer/ImGuiRenderer.hpp" #include <utility> // std::swap() #include <sfz/math/Matrix.hpp> #include "ph/Context.hpp" #include "ph/renderer/ZeroGUtils.hpp" namespace ph { using sfz::mat44; // Constants // ------------------------------------------------------------------------------------------------ constexpr uint32_t IMGUI_MAX_NUM_VERTICES = 32768; constexpr uint32_t IMGUI_MAX_NUM_INDICES = 32768; constexpr uint64_t IMGUI_VERTEX_BUFFER_SIZE = IMGUI_MAX_NUM_VERTICES * sizeof(ImGuiVertex); constexpr uint64_t IMGUI_INDEX_BUFFER_SIZE = IMGUI_MAX_NUM_INDICES * sizeof(uint32_t); // ImGuiRenderer: State methods // ------------------------------------------------------------------------------------------------ bool ImGuiRenderer::init( sfz::Allocator* allocator, zg::CommandQueue& copyQueue, const phConstImageView& fontTextureView) noexcept { // Init some general stuff mAllocator = allocator; // Init imgui settings GlobalConfig& cfg = getGlobalConfig(); mScaleSetting = cfg.sanitizeFloat("Imgui", "scale", true, FloatBounds(2.0f, 1.0f, 3.0f)); // Build ImGui pipeline bool pipelineSuccess = CHECK_ZG zg::PipelineRenderBuilder() .addVertexAttribute(0, 0, ZG_VERTEX_ATTRIBUTE_F32_2, offsetof(ImGuiVertex, pos)) .addVertexAttribute(1, 0, ZG_VERTEX_ATTRIBUTE_F32_2, offsetof(ImGuiVertex, texcoord)) .addVertexAttribute(2, 0, ZG_VERTEX_ATTRIBUTE_F32_4, offsetof(ImGuiVertex, color)) .addVertexBufferInfo(0, sizeof(ImGuiVertex)) .addPushConstant(0) .addSampler(0, ZG_SAMPLING_MODE_TRILINEAR) .addRenderTarget(ZG_TEXTURE_FORMAT_RGBA_U8_UNORM) .setCullingEnabled(false) .setBlendingEnabled(true) .setBlendFuncColor(ZG_BLEND_FUNC_ADD, ZG_BLEND_FACTOR_SRC_ALPHA, ZG_BLEND_FACTOR_SRC_INV_ALPHA) .setDepthTestEnabled(false) //.addVertexShaderPath("VSMain", "res_ph/shaders/imgui.hlsl") //.addPixelShaderPath("PSMain", "res_ph/shaders/imgui.hlsl") //.buildFromFileHLSL(mPipeline, ZG_SHADER_MODEL_6_0); .addVertexShaderPath("VSMain", "res_ph/shaders/imgui_vs.spv") .addPixelShaderPath("PSMain", "res_ph/shaders/imgui_ps.spv") .buildFromFileSPIRV(mPipeline); if (!pipelineSuccess) return false; // Allocate memory for font texture sfz_assert_hard(fontTextureView.type == ImageType::R_U8); ZgTexture2DCreateInfo texCreateInfo = {}; texCreateInfo.format = ZG_TEXTURE_FORMAT_R_U8_UNORM; texCreateInfo.width = fontTextureView.width; texCreateInfo.height = fontTextureView.height; texCreateInfo.numMipmaps = 1; // TODO: Mipmaps ZgTexture2DAllocationInfo texAllocInfo = {}; CHECK_ZG zg::Texture2D::getAllocationInfo(texAllocInfo, texCreateInfo); texCreateInfo.offsetInBytes = 0; texCreateInfo.sizeInBytes = texAllocInfo.sizeInBytes; bool texMemSuccess = CHECK_ZG mFontTextureHeap.create(texAllocInfo.sizeInBytes, ZG_MEMORY_TYPE_TEXTURE); texMemSuccess &= CHECK_ZG mFontTextureHeap.texture2DCreate( mFontTexture, texCreateInfo); CHECK_ZG mFontTexture.setDebugName("ImGui_FontTexture"); if (!texMemSuccess) return false; // Allocate memory for vertex and index buffer const uint64_t uploadHeapNumBytes = (IMGUI_VERTEX_BUFFER_SIZE + IMGUI_INDEX_BUFFER_SIZE) * MAX_NUM_FRAMES; bool memSuccess = CHECK_ZG mUploadHeap.create(uploadHeapNumBytes, ZG_MEMORY_TYPE_UPLOAD); // Upload font texture to GPU { // Utilize vertex and index buffer upload heap to upload font texture // Create temporary upload buffer zg::Buffer tmpUploadBuffer; CHECK_ZG mUploadHeap.bufferCreate(tmpUploadBuffer, 0, texAllocInfo.sizeInBytes); // Convert to ZgImageViewConstCpu ZgImageViewConstCpu imageView = {}; imageView.format = ZG_TEXTURE_FORMAT_R_U8_UNORM; imageView.data = fontTextureView.rawData; imageView.width = fontTextureView.width; imageView.height = fontTextureView.height; imageView.pitchInBytes = fontTextureView.width * sizeof(uint8_t); // Copy to the texture zg::CommandList commandList; CHECK_ZG copyQueue.beginCommandListRecording(commandList); CHECK_ZG commandList.memcpyToTexture(mFontTexture, 0, imageView, tmpUploadBuffer); CHECK_ZG commandList.enableQueueTransition(mFontTexture); CHECK_ZG copyQueue.executeCommandList(commandList); CHECK_ZG copyQueue.flush(); } // Actually create the vertex and index buffers uint64_t uploadHeapOffset = 0; uint32_t frameStateIdx = 0; mFrameStates.initAllStates([&](ImGuiFrameState& frame) { memSuccess &= CHECK_ZG mUploadHeap.bufferCreate( frame.uploadVertexBuffer, uploadHeapOffset, IMGUI_VERTEX_BUFFER_SIZE); uploadHeapOffset += IMGUI_VERTEX_BUFFER_SIZE; CHECK_ZG frame.uploadVertexBuffer.setDebugName(str32("ImGui_VertexBuffer_%u", frameStateIdx)); memSuccess &= CHECK_ZG mUploadHeap.bufferCreate( frame.uploadIndexBuffer, uploadHeapOffset, IMGUI_INDEX_BUFFER_SIZE); uploadHeapOffset += IMGUI_INDEX_BUFFER_SIZE; CHECK_ZG frame.uploadIndexBuffer.setDebugName(str32("ImGui_IndexBuffer_%u", frameStateIdx)); frameStateIdx += 1; }); sfz_assert(uploadHeapOffset == uploadHeapNumBytes); if (!memSuccess) return false; // Initialize fences for per frame state CHECK_ZG mFrameStates.initAllFences(); return true; } void ImGuiRenderer::swap(ImGuiRenderer& other) noexcept { std::swap(this->mAllocator, other.mAllocator); this->mPipeline.swap(other.mPipeline); this->mFontTextureHeap.swap(other.mFontTextureHeap); this->mFontTexture.swap(other.mFontTexture); this->mUploadHeap.swap(other.mUploadHeap); std::swap(this->mFrameStates, other.mFrameStates); std::swap(this->mScaleSetting, other.mScaleSetting); } void ImGuiRenderer::destroy() noexcept { mAllocator = nullptr; mPipeline.release(); mFontTextureHeap.release(); mFontTexture.release(); mUploadHeap.release(); mFrameStates.deinitAllStates([](ImGuiFrameState& state) { state = ImGuiFrameState(); }); mFrameStates.releaseAllFences(); mScaleSetting = nullptr; } // ImGuiRenderer: Methods // ------------------------------------------------------------------------------------------------ void ImGuiRenderer::render( uint64_t frameIdx, zg::CommandQueue& presentQueue, zg::Framebuffer& framebuffer, vec2_i32 framebufferRes, const phImguiVertex* vertices, uint32_t numVertices, const uint32_t* indices, uint32_t numIndices, const phImguiCommand* commands, uint32_t numCommands) noexcept { sfz_assert_hard(numVertices < IMGUI_MAX_NUM_VERTICES); sfz_assert_hard(numIndices < IMGUI_MAX_NUM_INDICES); // Get current frame's resources and then wait until they are available (i.e. the frame they // are part of has finished rendering). PerFrame<ImGuiFrameState>& imguiFrame = mFrameStates.getState(frameIdx); CHECK_ZG imguiFrame.renderingFinished.waitOnCpuBlocking(); // Convert ImGui vertices because slightly different representation if (imguiFrame.state.convertedVertices.data() == nullptr) { imguiFrame.state.convertedVertices.init(IMGUI_MAX_NUM_VERTICES, mAllocator, sfz_dbg("")); } imguiFrame.state.convertedVertices.hackSetSize(numVertices); for (uint32_t i = 0; i < numVertices; i++) { imguiFrame.state.convertedVertices[i].pos = vertices[i].pos; imguiFrame.state.convertedVertices[i].texcoord = vertices[i].texcoord; imguiFrame.state.convertedVertices[i].color = [&]() { vec4 color; color.x = float(vertices[i].color & 0xFFu) * (1.0f / 255.0f); color.y = float((vertices[i].color >> 8u) & 0xFFu) * (1.0f / 255.0f); color.z = float((vertices[i].color >> 16u) & 0xFFu) * (1.0f / 255.0f); color.w = float((vertices[i].color >> 24u) & 0xFFu) * (1.0f / 255.0f); return color; }(); } // Memcpy vertices and indices to imgui upload buffers CHECK_ZG imguiFrame.state.uploadVertexBuffer.memcpyTo( 0, imguiFrame.state.convertedVertices.data(), numVertices * sizeof(ImGuiVertex)); CHECK_ZG imguiFrame.state.uploadIndexBuffer.memcpyTo( 0, indices, numIndices * sizeof(uint32_t)); // Here we should normally signal that imguiFrame.uploadFinished() and then wait on it before // executing the imgui rendering commands. But because we only upload data to the UPLOAD heap // (which is synchronous) we don't actually need to do this. Therefore we skip it in this case. zg::CommandList commandList; CHECK_ZG presentQueue.beginCommandListRecording(commandList); // Set framebuffer CHECK_ZG commandList.setFramebuffer(framebuffer); // Set ImGui pipeline CHECK_ZG commandList.setPipeline(mPipeline); CHECK_ZG commandList.setIndexBuffer(imguiFrame.state.uploadIndexBuffer, ZG_INDEX_BUFFER_TYPE_UINT32); CHECK_ZG commandList.setVertexBuffer(0, imguiFrame.state.uploadVertexBuffer); // Bind pipeline parameters CHECK_ZG commandList.setPipelineBindings(zg::PipelineBindings() .addTexture(0, mFontTexture)); // Retrieve imgui scale factor float imguiScaleFactor = 1.0f; if (mScaleSetting != nullptr) imguiScaleFactor /= mScaleSetting->floatValue(); float imguiInvScaleFactor = 1.0f / imguiScaleFactor; float imguiWidth = framebufferRes.x * imguiScaleFactor; float imguiHeight = framebufferRes.y * imguiScaleFactor; // Calculate and set ImGui projection matrix mat44 projMatrix; projMatrix.row0 = vec4(2.0f / imguiWidth, 0.0f, 0.0f, -1.0f); projMatrix.row1 = vec4(0.0f, 2.0f / -imguiHeight, 0.0f, 1.0f); projMatrix.row2 = vec4(0.0f, 0.0f, 0.5f, 0.5f); projMatrix.row3 = vec4(0.0f, 0.0f, 0.0f, 1.0f); CHECK_ZG commandList.setPushConstant(0, &projMatrix, sizeof(mat44)); // Render ImGui commands for (uint32_t i = 0; i < numCommands; i++) { const phImguiCommand& cmd = commands[i]; sfz_assert((cmd.numIndices % 3) == 0); ZgFramebufferRect scissorRect = {}; scissorRect.topLeftX = uint32_t(cmd.clipRect.x * imguiInvScaleFactor); scissorRect.topLeftY = uint32_t(cmd.clipRect.y * imguiInvScaleFactor); scissorRect.width = uint32_t((cmd.clipRect.z - cmd.clipRect.x) * imguiInvScaleFactor); scissorRect.height = uint32_t((cmd.clipRect.w - cmd.clipRect.y) * imguiInvScaleFactor); CHECK_ZG commandList.setFramebufferScissor(scissorRect); CHECK_ZG commandList.drawTrianglesIndexed(cmd.idxBufferOffset, cmd.numIndices / 3); } // Execute command list CHECK_ZG presentQueue.executeCommandList(commandList); // Signal that we have finished rendering this ImGui frame CHECK_ZG presentQueue.signalOnGpu(imguiFrame.renderingFinished); } } // namespace ph
38.356164
107
0.754375
PetorSFZ
ee7579543308d2ff64eda343664c8333de5189a8
546
cpp
C++
src/core/Hit.cpp
nagato0614/pathtracing
1295b6fb38a89ca15e4da240208b612a22cb45d2
[ "MIT" ]
null
null
null
src/core/Hit.cpp
nagato0614/pathtracing
1295b6fb38a89ca15e4da240208b612a22cb45d2
[ "MIT" ]
6
2018-09-16T14:16:51.000Z
2018-09-16T14:33:22.000Z
src/core/Hit.cpp
nagato0614/Pathtracing
1295b6fb38a89ca15e4da240208b612a22cb45d2
[ "MIT" ]
null
null
null
// // Created by 長井亨 on 2018/07/18. // #include "Hit.hpp" namespace nagato { Hit::Hit(float d, Vector3 p, Vector3 n, Object *sphere) : distance(d), point(p), normal(n), object(sphere) { } Hit::Hit() { } const float Hit::getDistance() const { return distance; } const Vector3 &Hit::getPoint() const { return point; } const Vector3 &Hit::getNormal() const { return normal; } const Object & Hit::getObject() const { return *object; } }
16.058824
62
0.53663
nagato0614
ee7aae91ee59244d1f52cb2159e640d5b664f7bc
9,667
cpp
C++
src/CommandLine.cpp
kernsuite-debian/amber
5eaa39330968b5bad24b080f23691d5d8d358756
[ "Apache-2.0" ]
null
null
null
src/CommandLine.cpp
kernsuite-debian/amber
5eaa39330968b5bad24b080f23691d5d8d358756
[ "Apache-2.0" ]
null
null
null
src/CommandLine.cpp
kernsuite-debian/amber
5eaa39330968b5bad24b080f23691d5d8d358756
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <CommandLine.hpp> void processCommandLineOptions(isa::utils::ArgumentList & argumentList, Options & options, DeviceOptions & deviceOptions, DataOptions & dataOptions, Configurations & configurations, GeneratorOptions & generatorOptions, AstroData::Observation & observation) { try { options.print = argumentList.getSwitch("-print"); options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion"); options.compactResults = argumentList.getSwitch("-compact_results"); options.threshold = argumentList.getSwitchArgument<float>("-threshold"); deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform"); deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device"); deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name"); AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file")); dataOptions.dataLOFAR = argumentList.getSwitch("-lofar"); #ifndef HAVE_HDF5 if (dataOptions.dataLOFAR) { std::cerr << "Not compiled with HDF5 support." << std::endl; throw std::exception(); }; #endif // HAVE_HDF5 dataOptions.dataPSRDADA = argumentList.getSwitch("-dada"); #ifndef HAVE_PSRDADA if (dataOptions.dataPSRDADA) { std::cerr << "Not compiled with PSRDADA support." << std::endl; throw std::exception(); }; #endif // HAVE_PSRDADA dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc"); if ( !((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)) ) { std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl; throw std::exception(); } dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels"); dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps"); if ( !options.subbandDedispersion ) { Dedispersion::readTunedDedispersionConf(configurations.dedispersionParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file")); } else { Dedispersion::readTunedDedispersionConf(configurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_step_one_file")); Dedispersion::readTunedDedispersionConf(configurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_step_two_file")); } Integration::readTunedIntegrationConf(configurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file")); SNR::readTunedSNRConf(configurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file")); if ( dataOptions.dataLOFAR ) { observation.setNrBeams(1); observation.setNrSynthesizedBeams(1); dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header"); dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data"); dataOptions.limit = argumentList.getSwitch("-limit"); if ( dataOptions.limit ) { observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches")); } } else if ( dataOptions.dataSIGPROC ) { observation.setNrBeams(1); observation.setNrSynthesizedBeams(1); dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header"); dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data"); observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches")); if ( options.subbandDedispersion ) { observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), argumentList.getSwitchArgument<unsigned int>("-channels"), argumentList.getSwitchArgument<float>("-min_freq"), argumentList.getSwitchArgument<float>("-channel_bandwidth")); } else { observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"), argumentList.getSwitchArgument<float>("-min_freq"), argumentList.getSwitchArgument<float>("-channel_bandwidth")); } observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples")); observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time")); } else if ( dataOptions.dataPSRDADA ) { #ifdef HAVE_PSRDADA dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16); if ( options.subbandDedispersion ) { observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f); } else { observation.setFrequencyRange(1, 1, 1.0f, 1.0f); } observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams")); observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams")); observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches")); #endif // HAVE_PSRDADA } else { observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams")); observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams")); observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches")); if ( options.subbandDedispersion ) { observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), argumentList.getSwitchArgument<unsigned int>("-channels"), argumentList.getSwitchArgument<float>("-min_freq"), argumentList.getSwitchArgument<float>("-channel_bandwidth")); } else { observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"), argumentList.getSwitchArgument<float>("-min_freq"), argumentList.getSwitchArgument<float>("-channel_bandwidth")); } observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples")); observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time")); generatorOptions.random = argumentList.getSwitch("-random"); generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width"); generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm"); } dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output"); if ( options.subbandDedispersion ) { observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"), argumentList.getSwitchArgument<float>("-subbanding_dm_first"), argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true); } observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"), argumentList.getSwitchArgument<float>("-dm_first"), argumentList.getSwitchArgument<float>("-dm_step")); } catch ( isa::utils::EmptyCommandLine & err ) { usage(argumentList.getName()); throw; } catch ( isa::utils::SwitchNotFound & err ) { std::cerr << err.what() << std::endl; throw; } catch ( std::exception & err ) { std::cerr << "Unknown error: " << err.what() << std::endl; throw; } } void usage(const std::string & program) { std::cerr << program << " -opencl_platform ... -opencl_device ... -device_name ... -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ... -snr_file ... [-subband_dedispersion] [-print] [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]"; #ifdef HAVE_HDF5 std::cerr << " [-lofar]"; #endif // HAVE_HDF5 #ifdef HAVE_PSRDADA std::cerr << " [-dada]"; #endif // HAVE_PSRDADA std::cerr << std::endl; std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl; std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_step_one_file ... -dedispersion_step_two_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ... -subbanding_dm_step ..." << std::endl; #ifdef HAVE_HDF5 std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl; std::cerr << "\t\t -limit -batches ..." << std::endl; #endif // HAVE_HDF5 std::cerr << "\tSIGPROC: -sigproc -header ... -data ... -batches ... -channels ... -min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl; #ifdef HAVE_PSRDADA std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl; #endif // HAVE_PSRDADA std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ... -min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl; }
66.668966
354
0.726078
kernsuite-debian
ee7b90a444f24ed7dd35c3dd7d04460c185f6279
22,485
cpp
C++
OpenRobertaParent/RobotArdu/resources/hardware/additional/arduino/hardware/samd/1.6.20/cores/arduino/USB/USBCore.cpp
WGraterol64/robertalab
368c970c06008c6b56e59e3df19daf6e00022ad9
[ "Apache-2.0" ]
null
null
null
OpenRobertaParent/RobotArdu/resources/hardware/additional/arduino/hardware/samd/1.6.20/cores/arduino/USB/USBCore.cpp
WGraterol64/robertalab
368c970c06008c6b56e59e3df19daf6e00022ad9
[ "Apache-2.0" ]
null
null
null
OpenRobertaParent/RobotArdu/resources/hardware/additional/arduino/hardware/samd/1.6.20/cores/arduino/USB/USBCore.cpp
WGraterol64/robertalab
368c970c06008c6b56e59e3df19daf6e00022ad9
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2016 Arduino LLC. All right reserved. 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. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #if defined(USBCON) #include <Arduino.h> #include "SAMD21_USBDevice.h" #include "PluggableUSB.h" #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <limits.h> USBDevice_SAMD21G18x usbd; /** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */ #define TX_RX_LED_PULSE_MS 100 #ifdef PIN_LED_TXL static volatile uint8_t txLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */ #endif #ifdef PIN_LED_RXL static volatile uint8_t rxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */ #endif static char isRemoteWakeUpEnabled = 0; static char isEndpointHalt = 0; extern void (*gpf_isr)(void); // USB_Handler ISR extern "C" void UDD_Handler(void) { USBDevice.ISRHandler(); } const uint16_t STRING_LANGUAGE[2] = { (3<<8) | (2+2), 0x0409 // English }; #ifndef USB_PRODUCT // If no product is provided, use USB IO Board #define USB_PRODUCT "USB IO Board" #endif const uint8_t STRING_PRODUCT[] = USB_PRODUCT; #if USB_VID == 0x2341 # if defined(USB_MANUFACTURER) # undef USB_MANUFACTURER # endif # define USB_MANUFACTURER "Arduino LLC" #elif !defined(USB_MANUFACTURER) // Fall through to unknown if no manufacturer name was provided in a macro # define USB_MANUFACTURER "Unknown" #endif const uint8_t STRING_MANUFACTURER[] = USB_MANUFACTURER; // DEVICE DESCRIPTOR const DeviceDescriptor USB_DeviceDescriptorB = D_DEVICE(0xEF, 0x02, 0x01, 64, USB_VID, USB_PID, 0x100, IMANUFACTURER, IPRODUCT, ISERIAL, 1); const DeviceDescriptor USB_DeviceDescriptor = D_DEVICE(0x00, 0x00, 0x00, 64, USB_VID, USB_PID, 0x100, IMANUFACTURER, IPRODUCT, ISERIAL, 1); //================================================================== volatile uint32_t _usbConfiguration = 0; volatile uint32_t _usbSetInterface = 0; static __attribute__((__aligned__(4))) //__attribute__((__section__(".bss_hram0"))) uint8_t udd_ep_out_cache_buffer[7][64]; static __attribute__((__aligned__(4))) //__attribute__((__section__(".bss_hram0"))) uint8_t udd_ep_in_cache_buffer[7][64]; // Some EP are handled using EPHanlders. // Possibly all the sparse EP handling subroutines will be // converted into reusable EPHandlers in the future. static EPHandler *epHandlers[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; //================================================================== // Send a USB descriptor string. The string is stored as a // plain ASCII string but is sent out as UTF-16 with the // correct 2-byte prefix bool USBDeviceClass::sendStringDescriptor(const uint8_t *string, uint8_t maxlen) { if (maxlen < 2) return false; uint8_t buffer[maxlen]; buffer[0] = strlen((const char*)string) * 2 + 2; buffer[1] = 0x03; uint8_t i; for (i = 2; i < maxlen && *string; i++) { buffer[i++] = *string++; if (i == maxlen) break; buffer[i] = 0; } return USBDevice.sendControl(buffer, i); } bool _dry_run = false; bool _pack_message = false; uint16_t _pack_size = 0; uint8_t _pack_buffer[256]; void USBDeviceClass::packMessages(bool val) { if (val) { _pack_message = true; _pack_size = 0; } else { _pack_message = false; sendControl(_pack_buffer, _pack_size); } } uint8_t USBDeviceClass::SendInterfaces(uint32_t* total) { uint8_t interfaces = 0; #if defined(CDC_ENABLED) total[0] += CDC_GetInterface(&interfaces); #endif #ifdef PLUGGABLE_USB_ENABLED total[0] += PluggableUSB().getInterface(&interfaces); #endif return interfaces; } // Construct a dynamic configuration descriptor // This really needs dynamic endpoint allocation etc uint32_t USBDeviceClass::sendConfiguration(uint32_t maxlen) { uint32_t total = 0; // Count and measure interfaces _dry_run = true; uint8_t interfaces = SendInterfaces(&total); _Pragma("pack(1)") ConfigDescriptor config = D_CONFIG((uint16_t)(total + sizeof(ConfigDescriptor)), interfaces); _Pragma("pack()") // Now send them _dry_run = false; if (maxlen == sizeof(ConfigDescriptor)) { sendControl(&config, sizeof(ConfigDescriptor)); return true; } total = 0; packMessages(true); sendControl(&config, sizeof(ConfigDescriptor)); SendInterfaces(&total); packMessages(false); return true; } static void utox8(uint32_t val, char* s) { for (int i = 0; i < 8; i++) { int d = val & 0XF; val = (val >> 4); s[7 - i] = d > 9 ? 'A' + d - 10 : '0' + d; } } bool USBDeviceClass::sendDescriptor(USBSetup &setup) { uint8_t t = setup.wValueH; uint8_t desc_length = 0; bool _cdcComposite; int ret; const uint8_t *desc_addr = 0; if (t == USB_CONFIGURATION_DESCRIPTOR_TYPE) { return USBDevice.sendConfiguration(setup.wLength); } #ifdef PLUGGABLE_USB_ENABLED ret = PluggableUSB().getDescriptor(setup); if (ret != 0) { return (ret > 0 ? true : false); } #endif if (t == USB_DEVICE_DESCRIPTOR_TYPE) { if (setup.wLength == 8) _cdcComposite = 1; desc_addr = _cdcComposite ? (const uint8_t*)&USB_DeviceDescriptorB : (const uint8_t*)&USB_DeviceDescriptor; if (*desc_addr > setup.wLength) { desc_length = setup.wLength; } } else if (USB_STRING_DESCRIPTOR_TYPE == t) { if (setup.wValueL == 0) { desc_addr = (const uint8_t*)&STRING_LANGUAGE; } else if (setup.wValueL == IPRODUCT) { return sendStringDescriptor(STRING_PRODUCT, setup.wLength); } else if (setup.wValueL == IMANUFACTURER) { return sendStringDescriptor(STRING_MANUFACTURER, setup.wLength); } else if (setup.wValueL == ISERIAL) { #ifdef PLUGGABLE_USB_ENABLED // from section 9.3.3 of the datasheet #define SERIAL_NUMBER_WORD_0 *(volatile uint32_t*)(0x0080A00C) #define SERIAL_NUMBER_WORD_1 *(volatile uint32_t*)(0x0080A040) #define SERIAL_NUMBER_WORD_2 *(volatile uint32_t*)(0x0080A044) #define SERIAL_NUMBER_WORD_3 *(volatile uint32_t*)(0x0080A048) char name[ISERIAL_MAX_LEN]; utox8(SERIAL_NUMBER_WORD_0, &name[0]); utox8(SERIAL_NUMBER_WORD_1, &name[8]); utox8(SERIAL_NUMBER_WORD_2, &name[16]); utox8(SERIAL_NUMBER_WORD_3, &name[24]); PluggableUSB().getShortName(&name[32]); return sendStringDescriptor((uint8_t*)name, setup.wLength); #endif } else { return false; } if (*desc_addr > setup.wLength) { desc_length = setup.wLength; } } else { } if (desc_addr == 0) { return false; } if (desc_length == 0) { desc_length = *desc_addr; } sendControl(desc_addr, desc_length); return true; } void USBDeviceClass::standby() { usbd.noRunInStandby(); } void USBDeviceClass::handleEndpoint(uint8_t ep) { #if defined(CDC_ENABLED) if (ep == CDC_ENDPOINT_IN) { // NAK on endpoint IN, the bank is not yet filled in. usbd.epBank1ResetReady(CDC_ENDPOINT_IN); usbd.epBank1AckTransferComplete(CDC_ENDPOINT_IN); } if (ep == CDC_ENDPOINT_ACM) { // NAK on endpoint IN, the bank is not yet filled in. usbd.epBank1ResetReady(CDC_ENDPOINT_ACM); usbd.epBank1AckTransferComplete(CDC_ENDPOINT_ACM); } #endif #if defined(PLUGGABLE_USB_ENABLED) // Empty #endif } void USBDeviceClass::init() { #ifdef PIN_LED_TXL txLEDPulse = 0; pinMode(PIN_LED_TXL, OUTPUT); digitalWrite(PIN_LED_TXL, HIGH); #endif #ifdef PIN_LED_RXL rxLEDPulse = 0; pinMode(PIN_LED_RXL, OUTPUT); digitalWrite(PIN_LED_RXL, HIGH); #endif // Enable USB clock PM->APBBMASK.reg |= PM_APBBMASK_USB; // Set up the USB DP/DN pins PORT->Group[0].PINCFG[PIN_PA24G_USB_DM].bit.PMUXEN = 1; PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg &= ~(0xF << (4 * (PIN_PA24G_USB_DM & 0x01u))); PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg |= MUX_PA24G_USB_DM << (4 * (PIN_PA24G_USB_DM & 0x01u)); PORT->Group[0].PINCFG[PIN_PA25G_USB_DP].bit.PMUXEN = 1; PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg &= ~(0xF << (4 * (PIN_PA25G_USB_DP & 0x01u))); PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg |= MUX_PA25G_USB_DP << (4 * (PIN_PA25G_USB_DP & 0x01u)); // Put Generic Clock Generator 0 as source for Generic Clock Multiplexer 6 (USB reference) GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(6) | // Generic Clock Multiplexer 6 GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source GCLK_CLKCTRL_CLKEN; while (GCLK->STATUS.bit.SYNCBUSY) ; USB_SetHandler(&UDD_Handler); // Reset USB Device usbd.reset(); usbd.calibrate(); usbd.setUSBDeviceMode(); usbd.runInStandby(); usbd.setFullSpeed(); // Configure interrupts NVIC_SetPriority((IRQn_Type) USB_IRQn, 0UL); NVIC_EnableIRQ((IRQn_Type) USB_IRQn); usbd.enable(); initialized = true; } bool USBDeviceClass::attach() { if (!initialized) return false; usbd.attach(); usbd.enableEndOfResetInterrupt(); usbd.enableStartOfFrameInterrupt(); _usbConfiguration = 0; return true; } void USBDeviceClass::setAddress(uint32_t addr) { usbd.epBank1SetByteCount(0, 0); usbd.epBank1AckTransferComplete(0); // RAM buffer is full, we can send data (IN) usbd.epBank1SetReady(0); // Wait for transfer to complete while (!usbd.epBank1IsTransferComplete(0)) {} // Set USB address to addr USB->DEVICE.DADD.bit.DADD = addr; // Address USB->DEVICE.DADD.bit.ADDEN = 1; // Enable } bool USBDeviceClass::detach() { if (!initialized) return false; usbd.detach(); return true; } bool USBDeviceClass::end() { if (!initialized) return false; usbd.disable(); return true; } bool USBDeviceClass::configured() { return _usbConfiguration != 0; } bool USBDeviceClass::handleClassInterfaceSetup(USBSetup& setup) { uint8_t i = setup.wIndex; #if defined(CDC_ENABLED) if (CDC_ACM_INTERFACE == i) { if (CDC_Setup(setup) == false) { sendZlp(0); } return true; } #endif #if defined(PLUGGABLE_USB_ENABLED) bool ret = PluggableUSB().setup(setup); if ( ret == false) { sendZlp(0); } return ret; #endif return false; } uint32_t EndPoints[] = { USB_ENDPOINT_TYPE_CONTROL, #ifdef CDC_ENABLED USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0), // CDC_ENDPOINT_ACM USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_OUT(0), // CDC_ENDPOINT_OUT USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_IN(0), // CDC_ENDPOINT_IN #endif #ifdef PLUGGABLE_USB_ENABLED //allocate 6 endpoints and remove const so they can be changed by the user 0, 0, 0, 0, 0, 0, #endif }; void USBDeviceClass::initEndpoints() { for (uint8_t i = 1; i < sizeof(EndPoints) && EndPoints[i] != 0; i++) { initEP(i, EndPoints[i]); } } void USBDeviceClass::initEP(uint32_t ep, uint32_t config) { if (config == (USB_ENDPOINT_TYPE_INTERRUPT | USB_ENDPOINT_IN(0))) { usbd.epBank1SetSize(ep, 64); usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]); usbd.epBank1SetType(ep, 4); // INTERRUPT IN } else if (config == (USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_OUT(0))) { if (epHandlers[ep] != NULL) { delete (DoubleBufferedEPOutHandler*)epHandlers[ep]; } epHandlers[ep] = new DoubleBufferedEPOutHandler(usbd, ep, 256); } else if (config == (USB_ENDPOINT_TYPE_BULK | USB_ENDPOINT_IN(0))) { usbd.epBank1SetSize(ep, 64); usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]); // NAK on endpoint IN, the bank is not yet filled in. usbd.epBank1ResetReady(ep); usbd.epBank1SetType(ep, 3); // BULK IN } else if (config == USB_ENDPOINT_TYPE_CONTROL) { // Setup Control OUT usbd.epBank0SetSize(ep, 64); usbd.epBank0SetAddress(ep, &udd_ep_out_cache_buffer[ep]); usbd.epBank0SetType(ep, 1); // CONTROL OUT / SETUP // Setup Control IN usbd.epBank1SetSize(ep, 64); usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[0]); usbd.epBank1SetType(ep, 1); // CONTROL IN // Release OUT EP usbd.epBank0SetMultiPacketSize(ep, 64); usbd.epBank0SetByteCount(ep, 0); // NAK on endpoint OUT, the bank is full. usbd.epBank0SetReady(ep); } } void USBDeviceClass::flush(uint32_t ep) { if (available(ep)) { // RAM buffer is full, we can send data (IN) usbd.epBank1SetReady(ep); // Clear the transfer complete flag usbd.epBank1AckTransferComplete(ep); } } void USBDeviceClass::stall(uint32_t ep) { // TODO: test // TODO: use .bit. notation // Stall endpoint USB->DEVICE.DeviceEndpoint[ep].EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ(2); } bool USBDeviceClass::connected() { // Count frame numbers uint8_t f = USB->DEVICE.FNUM.bit.FNUM; //delay(3); return f != USB->DEVICE.FNUM.bit.FNUM; } uint32_t USBDeviceClass::recvControl(void *_data, uint32_t len) { uint8_t *data = reinterpret_cast<uint8_t *>(_data); // The RAM Buffer is empty: we can receive data usbd.epBank0ResetReady(0); //usbd.epBank0AckSetupReceived(0); uint32_t read = armRecvCtrlOUT(0); if (read > len) read = len; //while (!usbd.epBank0AckTransferComplete(0)) {} uint8_t *buffer = udd_ep_out_cache_buffer[0]; for (uint32_t i=0; i<len; i++) { data[i] = buffer[i]; } return read; } // Number of bytes, assumes a rx endpoint uint32_t USBDeviceClass::available(uint32_t ep) { if (epHandlers[ep]) { return epHandlers[ep]->available(); } else { return usbd.epBank0ByteCount(ep); } } // Non Blocking receive // Return number of bytes read uint32_t USBDeviceClass::recv(uint32_t ep, void *_data, uint32_t len) { if (!_usbConfiguration) return -1; #ifdef PIN_LED_RXL if (rxLEDPulse == 0) digitalWrite(PIN_LED_RXL, LOW); rxLEDPulse = TX_RX_LED_PULSE_MS; #endif if (epHandlers[ep]) { return epHandlers[ep]->recv(_data, len); } if (available(ep) < len) len = available(ep); armRecv(ep); usbd.epBank0DisableTransferComplete(ep); memcpy(_data, udd_ep_out_cache_buffer[ep], len); // release empty buffer if (len && !available(ep)) { // The RAM Buffer is empty: we can receive data usbd.epBank0ResetReady(ep); // Clear Transfer complete 0 flag usbd.epBank0AckTransferComplete(ep); // Enable Transfer complete 0 interrupt usbd.epBank0EnableTransferComplete(ep); } return len; } // Recv 1 byte if ready int USBDeviceClass::recv(uint32_t ep) { uint8_t c; if (recv(ep, &c, 1) != 1) { return -1; } else { return c; } } uint8_t USBDeviceClass::armRecvCtrlOUT(uint32_t ep) { // Get endpoint configuration from setting register usbd.epBank0SetAddress(ep, &udd_ep_out_cache_buffer[ep]); usbd.epBank0SetMultiPacketSize(ep, 8); usbd.epBank0SetByteCount(ep, 0); usbd.epBank0ResetReady(ep); // Wait OUT while (!usbd.epBank0IsReady(ep)) {} while (!usbd.epBank0IsTransferComplete(ep)) {} return usbd.epBank0ByteCount(ep); } uint8_t USBDeviceClass::armRecv(uint32_t ep) { uint16_t count = usbd.epBank0ByteCount(ep); if (count >= 64) { usbd.epBank0SetByteCount(ep, count - 64); } else { usbd.epBank0SetByteCount(ep, 0); } return usbd.epBank0ByteCount(ep); } // Timeout for sends #define TX_TIMEOUT_MS 70 static char LastTransmitTimedOut[7] = { 0, 0, 0, 0, 0, 0, 0 }; // Blocking Send of data to an endpoint uint32_t USBDeviceClass::send(uint32_t ep, const void *data, uint32_t len) { uint32_t written = 0; uint32_t length = 0; if (!_usbConfiguration) return -1; if (len > 16384) return -1; #ifdef PIN_LED_TXL if (txLEDPulse == 0) digitalWrite(PIN_LED_TXL, LOW); txLEDPulse = TX_RX_LED_PULSE_MS; #endif // Flash area while (len != 0) { if (usbd.epBank1IsReady(ep)) { // previous transfer is still not complete // convert the timeout from microseconds to a number of times through // the wait loop; it takes (roughly) 23 clock cycles per iteration. uint32_t timeout = microsecondsToClockCycles(TX_TIMEOUT_MS * 1000) / 23; // Wait for (previous) transfer to complete // inspired by Paul Stoffregen's work on Teensy while (!usbd.epBank1IsTransferComplete(ep)) { if (LastTransmitTimedOut[ep] || timeout-- == 0) { LastTransmitTimedOut[ep] = 1; // set byte count to zero, so that ZLP is sent // instead of stale data usbd.epBank1SetByteCount(ep, 0); return -1; } } } LastTransmitTimedOut[ep] = 0; if (len >= EPX_SIZE) { length = EPX_SIZE - 1; } else { length = len; } /* memcopy could be safer in multi threaded environment */ memcpy(&udd_ep_in_cache_buffer[ep], data, length); usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]); usbd.epBank1SetByteCount(ep, length); // Clear the transfer complete flag usbd.epBank1AckTransferComplete(ep); // RAM buffer is full, we can send data (IN) usbd.epBank1SetReady(ep); written += length; len -= length; data = (char *)data + length; } return written; } uint32_t USBDeviceClass::armSend(uint32_t ep, const void* data, uint32_t len) { memcpy(&udd_ep_in_cache_buffer[ep], data, len); // Get endpoint configuration from setting register usbd.epBank1SetAddress(ep, &udd_ep_in_cache_buffer[ep]); usbd.epBank1SetMultiPacketSize(ep, 0); usbd.epBank1SetByteCount(ep, len); return len; } uint32_t USBDeviceClass::sendControl(const void* _data, uint32_t len) { const uint8_t *data = reinterpret_cast<const uint8_t *>(_data); uint32_t length = len; uint32_t sent = 0; uint32_t pos = 0; if (_dry_run == true) return length; if (_pack_message == true) { memcpy(&_pack_buffer[_pack_size], data, len); _pack_size += len; return length; } while (len > 0) { sent = armSend(EP0, data + pos, len); pos += sent; len -= sent; } return length; } void USBDeviceClass::sendZlp(uint32_t ep) { // Set the byte count as zero usbd.epBank1SetByteCount(ep, 0); } bool USBDeviceClass::handleStandardSetup(USBSetup &setup) { switch (setup.bRequest) { case GET_STATUS: if (setup.bmRequestType == 0) // device { // Send the device status // TODO: Check current configuration for power mode (if device is configured) // TODO: Check if remote wake-up is enabled uint8_t buff[] = { 0, 0 }; armSend(0, buff, 2); return true; } // if( setup.bmRequestType == 2 ) // Endpoint: else { // Send the endpoint status // Check if the endpoint if currently halted uint8_t buff[] = { 0, 0 }; if (isEndpointHalt == 1) buff[0] = 1; armSend(0, buff, 2); return true; } case CLEAR_FEATURE: // Check which is the selected feature if (setup.wValueL == 1) // DEVICEREMOTEWAKEUP { // Enable remote wake-up and send a ZLP uint8_t buff[] = { 0, 0 }; if (isRemoteWakeUpEnabled == 1) buff[0] = 1; armSend(0, buff, 2); return true; } else // if( setup.wValueL == 0) // ENDPOINTHALT { isEndpointHalt = 0; sendZlp(0); return true; } case SET_FEATURE: // Check which is the selected feature if (setup.wValueL == 1) // DEVICEREMOTEWAKEUP { // Enable remote wake-up and send a ZLP isRemoteWakeUpEnabled = 1; uint8_t buff[] = { 0 }; armSend(0, buff, 1); return true; } if (setup.wValueL == 0) // ENDPOINTHALT { // Halt endpoint isEndpointHalt = 1; sendZlp(0); return true; } case SET_ADDRESS: setAddress(setup.wValueL); return true; case GET_DESCRIPTOR: return sendDescriptor(setup); case SET_DESCRIPTOR: return false; case GET_CONFIGURATION: armSend(0, (void*)&_usbConfiguration, 1); return true; case SET_CONFIGURATION: if (REQUEST_DEVICE == (setup.bmRequestType & REQUEST_RECIPIENT)) { initEndpoints(); _usbConfiguration = setup.wValueL; #if defined(CDC_ENABLED) // Enable interrupt for CDC reception from host (OUT packet) usbd.epBank1EnableTransferComplete(CDC_ENDPOINT_ACM); usbd.epBank0EnableTransferComplete(CDC_ENDPOINT_OUT); #endif sendZlp(0); return true; } else { return false; } case GET_INTERFACE: armSend(0, (void*)&_usbSetInterface, 1); return true; case SET_INTERFACE: _usbSetInterface = setup.wValueL; sendZlp(0); return true; default: return true; } } void USBDeviceClass::ISRHandler() { if (_pack_message == true) { return; } // End-Of-Reset if (usbd.isEndOfResetInterrupt()) { // Configure EP 0 initEP(0, USB_ENDPOINT_TYPE_CONTROL); // Enable Setup-Received interrupt usbd.epBank0EnableSetupReceived(0); _usbConfiguration = 0; usbd.ackEndOfResetInterrupt(); } // Start-Of-Frame if (usbd.isStartOfFrameInterrupt()) { usbd.ackStartOfFrameInterrupt(); // check whether the one-shot period has elapsed. if so, turn off the LED #ifdef PIN_LED_TXL if (txLEDPulse > 0) { txLEDPulse--; if (txLEDPulse == 0) digitalWrite(PIN_LED_TXL, HIGH); } #endif #ifdef PIN_LED_RXL if (rxLEDPulse > 0) { rxLEDPulse--; if (rxLEDPulse == 0) digitalWrite(PIN_LED_RXL, HIGH); } #endif } // Endpoint 0 Received Setup interrupt if (usbd.epBank0IsSetupReceived(0)) { usbd.epBank0AckSetupReceived(0); USBSetup *setup = reinterpret_cast<USBSetup *>(udd_ep_out_cache_buffer[0]); /* Clear the Bank 0 ready flag on Control OUT */ // The RAM Buffer is empty: we can receive data usbd.epBank0ResetReady(0); bool ok; if (REQUEST_STANDARD == (setup->bmRequestType & REQUEST_TYPE)) { // Standard Requests ok = handleStandardSetup(*setup); } else { // Class Interface Requests ok = handleClassInterfaceSetup(*setup); } if (ok) { usbd.epBank1SetReady(0); } else { stall(0); } if (usbd.epBank1IsStalled(0)) { usbd.epBank1AckStalled(0); // Remove stall request usbd.epBank1DisableStalled(0); } } // end Received Setup handler uint8_t i=0; uint8_t ept_int = usbd.epInterruptSummary() & 0xFE; // Remove endpoint number 0 (setup) while (ept_int != 0) { // Check if endpoint has a pending interrupt if ((ept_int & (1 << i)) != 0) { // Endpoint Transfer Complete (0/1) Interrupt if (usbd.epBank0IsTransferComplete(i) || usbd.epBank1IsTransferComplete(i)) { if (epHandlers[i]) { epHandlers[i]->handleEndpoint(); } else { handleEndpoint(i); } } ept_int &= ~(1 << i); } i++; if (i > USB_EPT_NUM) break; // fire exit } } /* * USB Device instance * ------------------- */ // USBDevice class instance USBDeviceClass USBDevice; #endif
22.85061
140
0.696598
WGraterol64
ee82252e4f79331e3af18e529f28cf25a25f0ed0
2,203
cpp
C++
ThunkLibs/libSDL2/libSDL2_Guest.cpp
duck-37/FEX
fbda0e7ba521d151d3448f5d664da6879686cff8
[ "MIT" ]
null
null
null
ThunkLibs/libSDL2/libSDL2_Guest.cpp
duck-37/FEX
fbda0e7ba521d151d3448f5d664da6879686cff8
[ "MIT" ]
null
null
null
ThunkLibs/libSDL2/libSDL2_Guest.cpp
duck-37/FEX
fbda0e7ba521d151d3448f5d664da6879686cff8
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include <GL/glx.h> #include <dlfcn.h> #include <stdio.h> #include <cstring> #include <map> #include <string> #include <stdarg.h> #include "common/Guest.h" #include "thunks.inl" #include "function_packs.inl" #include "function_packs_public.inl" LOAD_LIB(libSDL2) #include <vector> struct __va_list_tag; int SDL_snprintf(char*, size_t, const char*, ...) { return printf("SDL2: SDL_snprintf\n"); } int SDL_sscanf(const char*, const char*, ...) { return printf("SDL2: SDL_sscanf\n"); } void SDL_Log(const char*, ...) { printf("SDL2: SDL_Log\n"); } void SDL_LogCritical(int, const char*, ...) { printf("SDL2: SDL_LogCritical\n"); } void SDL_LogDebug(int, const char*, ...) { printf("SDL2: SDL_LogDebug\n"); } void SDL_LogError(int, const char*, ...) { printf("SDL2: SDL_LogError\n"); } void SDL_LogInfo(int, const char*, ...) { printf("SDL2: SDL_LogInfo\n"); } void SDL_LogMessage(int, SDL_LogPriority, const char*, ...) { printf("SDL2: SDL_LogMessage\n"); } void SDL_LogVerbose(int, const char*, ...) { printf("SDL2: SDL_LogVerbose\n"); } void SDL_LogWarn(int, const char*, ...) { printf("SDL2: SDL_LogWarn\n"); } int SDL_SetError(const char*, ...) { return printf("SDL2: SDL_SetError\n"); } void SDL_LogMessageV(int, SDL_LogPriority, const char*, __va_list_tag*) { printf("SDL2: SDL_LogMessageV\n");} int SDL_vsnprintf(char*, size_t, const char*, __va_list_tag*) { return printf("SDL2: SDL_vsnprintf\n");} int SDL_vsscanf(const char*, const char*, __va_list_tag*) { return printf("SDL2: SDL_vsscanf\n");} extern "C" { void* SDL_GL_GetProcAddress(const char* name) { // TODO: Fix this HACK return (void*)glXGetProcAddress((const GLubyte*)name); } // TODO: These are not 100% conforming to SDL either void *SDL_LoadObject(const char *sofile) { auto lib = dlopen(sofile, RTLD_NOW | RTLD_LOCAL); if (!lib) { printf("SDL_LoadObject: Failed to load %s\n", sofile); } return lib; } void *SDL_LoadFunction(void *lib, const char *name) { return dlsym(lib, name); } void SDL_UnloadObject(void *lib) { if (lib) { dlclose(lib); } } }
33.378788
109
0.662279
duck-37
ee825be7ed59f4d159cab9152ee4e6c01e053b1c
1,899
cpp
C++
simulatorCore/src/glBlock.cpp
claytronics/visiblesim
2762a88a23e50516d0f166dd9629f1ac7290fded
[ "Apache-2.0" ]
4
2016-08-18T03:19:49.000Z
2020-09-20T03:29:26.000Z
simulatorCore/src/glBlock.cpp
claytronics/visiblesim
2762a88a23e50516d0f166dd9629f1ac7290fded
[ "Apache-2.0" ]
2
2016-08-18T03:25:07.000Z
2016-08-29T17:51:50.000Z
simulatorCore/src/glBlock.cpp
claytronics/visiblesim
2762a88a23e50516d0f166dd9629f1ac7290fded
[ "Apache-2.0" ]
3
2015-05-14T07:29:55.000Z
2021-07-18T23:45:36.000Z
#include "glBlock.h" #include <sstream> #include "objLoader.h" GlBlock::GlBlock(bID id):blockId(id) { position[0] = 0.0; position[1] = 0.0; position[2] = 0.0; color[0] = 0.5; color[1] = 0.5; color[2] = 0.5; color[3] = 1.0; isHighlighted = false; } GlBlock::GlBlock(bID id,const Vector3D &pos, const Vector3D &col) : blockId(id) { position[0] = pos[0]; position[1] = pos[1]; position[2] = pos[2]; color[0] = col[0]; color[1] = col[1]; color[2] = col[2]; color[3] = 1.0; isHighlighted = false; } GlBlock::~GlBlock() { } void GlBlock::setPosition(const Vector3D &pos) { position[0] = GLfloat(pos[0]); position[1] = GLfloat(pos[1]); position[2] = GLfloat(pos[2]); } void GlBlock::setColor(const Vector3D &col) { color[0] = GLfloat(col[0]); color[1] = GLfloat(col[1]); color[2] = GLfloat(col[2]); color[3] = 1.0; } void GlBlock::setColor(const Color &col) { color[0] = col[0]; color[1] = col[1]; color[2] = col[2]; color[3] = 1.0; } void GlBlock::setVisible(bool visible) { color[3] = visible; } void GlBlock::toggleHighlight() { isHighlighted=!isHighlighted; } string GlBlock::getInfo() { ostringstream out; out << blockId << "\n"; out << fixed; out.precision(1); out << "Pos=(" << position[0] << "," << position[1] << "," << position[2] << ") "; out << "Col=(" << (int)(color[0] * 255) << "," << (int)(color[1] * 255) << "," << (int)(color[2] * 255) << ")"; return out.str(); } string GlBlock::getPopupInfo() { ostringstream out; out << blockId << "\n"; return out.str(); } void GlBlock::glDrawId(ObjLoader::ObjLoader *ptrObj,int &n) { glPushMatrix(); glTranslatef(position[0],position[1],position[2]); ptrObj->glDrawId(n); glPopMatrix(); } void GlBlock::glDrawIdByMaterial(ObjLoader::ObjLoader *ptrObj,int &n) { glPushMatrix(); glTranslatef(position[0],position[1],position[2]); ptrObj->glDrawIdByMaterial(n); glPopMatrix(); }
20.419355
112
0.617167
claytronics
ee88d8839f6bf5d8ce143fdc88e75a258efb6a74
2,648
cpp
C++
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
tangziwen/Cube-Engine
c79b878dcc7e2e382f4463ca63519627d6220afd
[ "MIT" ]
360
2015-01-26T08:15:01.000Z
2021-07-11T16:30:58.000Z
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
multithread3/Cube-Engine
aa76db88fdace41b09cbfc51e5959a9686cca3f3
[ "MIT" ]
6
2015-03-09T09:15:07.000Z
2020-07-06T01:34:00.000Z
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
multithread3/Cube-Engine
aa76db88fdace41b09cbfc51e5959a9686cca3f3
[ "MIT" ]
41
2015-03-10T03:17:46.000Z
2021-07-13T06:26:26.000Z
#include "TextureMgr.h" #include <utility> #include "Utility/log/Log.h" namespace tzw { Texture *TextureMgr::getByPath(std::string filePath, bool isNeedMipMap) { if (filePath.empty()) return nullptr; auto result = m_texturePool.find(filePath); if(result!=m_texturePool.end()) { return result->second; }else { Texture * tex = new Texture(filePath); if(isNeedMipMap) { tex->genMipMap(); } m_texturePool.insert(std::make_pair(filePath,tex)); return tex; } } Texture* TextureMgr::getByPathSimple(std::string filePath) { return getByPath(filePath, false); } Texture* TextureMgr::getByPathAsync(std::string filePath, std::function<void (Texture *)> finishedCallBack, bool isNeedMiMap) { if (filePath.empty()) { if(finishedCallBack) { finishedCallBack(nullptr); } return nullptr; } auto result = m_texturePool.find(filePath); if(result!=m_texturePool.end()) { if(finishedCallBack) { finishedCallBack(result->second); } return result->second; }else { return loadAsync(filePath, finishedCallBack, isNeedMiMap); } } Texture* TextureMgr::loadAsync(std::string filePath, std::function<void(Texture*)> finishedCallBack, bool isNeedMiMap) { Texture * tex = new Texture(); auto onFinished = [this, tex, isNeedMiMap, filePath, finishedCallBack](Texture *) { if(isNeedMiMap) { tex->genMipMap(); } if(finishedCallBack) { finishedCallBack(tex); } }; m_texturePool.insert(std::make_pair(filePath,tex)); tex->loadAsync(filePath, onFinished); return tex; } Texture *TextureMgr::getByPath(std::string PosX, std::string NegX, std::string PosY, std::string NegY, std::string PosZ, std::string NegZ) { auto result = m_texturePool.find(PosX); if(result!=m_texturePool.end()) { return result->second; }else { Texture * tex = new Texture(PosX,NegX,PosY,NegY,PosZ,NegZ); m_texturePool.insert(std::make_pair(PosX,tex)); return tex; } } Texture* TextureMgr::loadSingleCubeMap(std::string filePath) { auto result = m_texturePool.find(filePath); if(result!=m_texturePool.end()) { return result->second; }else { //there is a bug, should be EWUDNS Texture * tex = new Texture(filePath, "EWDUNS"); m_texturePool.insert(std::make_pair(filePath,tex)); return tex; } } TextureMgr::TextureMgr() { } TextureMgr::~TextureMgr() { tlog("somebody kill me"); } } // namespace tzw
22.632479
125
0.629909
tangziwen
ee8bdbd14703200c0abba03f35df7f3c29f0c2b1
5,980
cc
C++
get-energy.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
8
2019-01-17T12:48:34.000Z
2022-02-04T11:40:58.000Z
get-energy.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
null
null
null
get-energy.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
[ "MIT" ]
2
2019-12-01T02:23:07.000Z
2019-12-09T02:56:44.000Z
/* * Measure the energy of executing another program. * Code based on IgProf energy profiling module by Filip Nybäck. * * TODO: * Use waitpid() instead of wait(). * Account for RAPL overflows. * * Author: Mikael Hirki <mikael.hirki@aalto.fi> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <math.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <signal.h> #include <vector> #include <papi.h> #define READ_ENERGY(a) PAPI_read(s_event_set, a) static int s_event_set = 0; static int s_num_events = 0; static long long *s_begin_values = NULL; static long long *s_end_values = NULL; static int idx_pkg_energy = -1; static int idx_pp0_energy = -1; static int idx_pp1_energy = -1; static int idx_dram_energy = -1; // Set the scale factor for the RAPL energy readings: // one integer step is 15.3 microjoules, scale everything to joules. static const double scaleFactor = 1e-9; static pid_t child_pid = -1; static double gettimeofday_double() { struct timeval now; gettimeofday(&now, NULL); return now.tv_sec + now.tv_usec * 1e-6; } static void sighandler(int signum) { printf("Received signal %d\n", signum); if (child_pid > 0) { kill(child_pid, signum); } else { exit(-1); } } static void do_signals() { signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); signal(SIGINT, sighandler); } static bool init_rapl() { if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT) { fprintf(stderr, "PAPI library initialisation failed.\n"); return false; } // Find the RAPL component of PAPI. int num_components = PAPI_num_components(); int component_id; const PAPI_component_info_t *component_info = 0; for (component_id = 0; component_id < num_components; ++component_id) { component_info = PAPI_get_component_info(component_id); if (component_info && strstr(component_info->name, "rapl")) { break; } } if (component_id == num_components) { fprintf(stderr, "No RAPL component found in PAPI library.\n"); return false; } if (component_info->disabled) { fprintf(stderr, "RAPL component of PAPI disabled: %s.\n", component_info->disabled_reason); return false; } // Create an event set. s_event_set = PAPI_NULL; if (PAPI_create_eventset(&s_event_set) != PAPI_OK) { fprintf(stderr, "Could not create PAPI event set.\n"); return false; } int code = PAPI_NATIVE_MASK; for (int retval = PAPI_enum_cmp_event(&code, PAPI_ENUM_FIRST, component_id); retval == PAPI_OK; retval = PAPI_enum_cmp_event(&code, PAPI_ENUM_EVENTS, component_id)) { char event_name[PAPI_MAX_STR_LEN]; if (PAPI_event_code_to_name(code, event_name) != PAPI_OK) { fprintf(stderr, "Could not get PAPI event name.\n"); return false; } PAPI_event_info_t event_info; if (PAPI_get_event_info(code, &event_info) != PAPI_OK) { fprintf(stderr, "Could not get PAPI event info.\n"); return false; } if (event_info.data_type != PAPI_DATATYPE_UINT64) { continue; } if (strstr(event_name, "PACKAGE_ENERGY:")) { idx_pkg_energy = s_num_events; } else if (strstr(event_name, "PP0_ENERGY:")) { idx_pp0_energy = s_num_events; } else if (strstr(event_name, "PP1_ENERGY:")) { idx_pp1_energy = s_num_events; } else if (strstr(event_name, "DRAM_ENERGY:")) { idx_dram_energy = s_num_events; } else { continue; // Skip other counters } //printf("Adding %s to event set.\n", event_name); if (PAPI_add_event(s_event_set, code) != PAPI_OK) break; ++s_num_events; } if (s_num_events == 0) { fprintf(stderr, "Could not find any RAPL events.\n"); return false; } // Allocate memory for reading the counters s_begin_values = (long long *)calloc(s_num_events, sizeof(long long)); s_end_values = (long long *)calloc(s_num_events, sizeof(long long)); // Activate the event set. if (PAPI_start(s_event_set) != PAPI_OK) { fprintf(stderr, "Could not activate the event set.\n"); return false; } return true; } static void do_fork_and_exec(int argc, char **argv) { if (argc > 1) { child_pid = fork(); if (child_pid == 0) { execvp(argv[1], &argv[1]); perror("execlp"); exit(-1); } else if (child_pid < 0) { perror("fork"); } else { int status; while (true) { int rval = wait(&status); if (rval < 0) { if (errno == EINTR) continue; else break; } if (WIFEXITED(status) || WIFSIGNALED(status)) { child_pid = -1; break; } } } } else { printf("Usage: %s <program> [parameters]\n", argv[0]); } } int main(int argc, char **argv) { do_signals(); if (init_rapl()) { double begin_time = gettimeofday_double(); READ_ENERGY(s_begin_values); do_fork_and_exec(argc, argv); READ_ENERGY(s_end_values); double end_time = gettimeofday_double(); double time_elapsed = end_time - begin_time; printf("Real time elapsed: %f seconds\n", time_elapsed); if (idx_pkg_energy != -1) { double pkg_energy = scaleFactor * (s_end_values[idx_pkg_energy] - s_begin_values[idx_pkg_energy]); printf("Package energy consumed: %f J\n", pkg_energy); printf("Package average power: %f W\n", pkg_energy / time_elapsed); } if (idx_pp0_energy != -1) { double pp0_energy = scaleFactor * (s_end_values[idx_pp0_energy] - s_begin_values[idx_pp0_energy]); printf("PP0 energy consumed: %f J\n", pp0_energy); printf("PP0 average power: %f W\n", pp0_energy / time_elapsed); } if (idx_pp1_energy != -1) { double pp1_energy = scaleFactor * (s_end_values[idx_pp1_energy] - s_begin_values[idx_pp1_energy]); printf("PP1 energy consumed: %f J\n", pp1_energy); printf("PP1 average power: %f W\n", pp1_energy / time_elapsed); } if (idx_dram_energy != -1) { double dram_energy = scaleFactor * (s_end_values[idx_dram_energy] - s_begin_values[idx_dram_energy]); printf("DRAM energy consumed: %f J\n", dram_energy); printf("DRAM average power: %f W\n", dram_energy / time_elapsed); } } return 0; }
27.813953
167
0.691304
mhirki
ee8d2481fa3ec70137fdeb4b8fcc3b83a23d4188
2,624
cpp
C++
src/main.cpp
IllidanS4/samp-compat
91a7762f32d89fa3cab0d174546a6529e46dff27
[ "MIT" ]
null
null
null
src/main.cpp
IllidanS4/samp-compat
91a7762f32d89fa3cab0d174546a6529e46dff27
[ "MIT" ]
null
null
null
src/main.cpp
IllidanS4/samp-compat
91a7762f32d89fa3cab0d174546a6529e46dff27
[ "MIT" ]
null
null
null
/* # main.cpp The "main" source file with most of the boilerplate code. Includes the `NativesMain` header for initialising plugin-natives. - `Supports` declares to the SA:MP server which features this plugin uses. - `Load` is called when the plugin loads and sets up the `logprintf` function. */ #include <amx/amx.h> #include <plugincommon.h> #include <string.h> #include "common.hpp" #include "natives.hpp" #include "addresses.hpp" #include "impl.hpp" logprintf_t logprintf; void** ppPluginData = NULL; void* pRakServer = NULL; bool Initialized = false; bool PostInitialized = false; int iNetVersion; int iCompatVersion; int iCompatVersion2; char szVersion[64] = "Unknown"; unsigned char PlayerCompat[MAX_PLAYERS] = { 0 }; int currentVersion = SAMPVersion::VERSION_UNKNOWN; extern "C" { AMX_NATIVE_INFO nativeList[] = { { "IsPlayerCompat", Natives::IsPlayerCompat}, { 0, 0 } }; } void Initialize() { switch (currentVersion) { case SAMPVersion::VERSION_037_R2: { iNetVersion = 4057; iCompatVersion = 4062; iCompatVersion2 = 32769; strcpy(szVersion, "0.3.7-R2"); break; } case SAMPVersion::VERSION_03DL_R1: { iNetVersion = 4062; iCompatVersion = 4057; iCompatVersion2 = 4057; strcpy(szVersion, "0.3.DL-R1"); break; } } Addresses::Initialize(); Impl::InstallPreHooks(); logprintf(" -- samp-compat for %s initialized", szVersion); Initialized = true; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void** ppData) { ppPluginData = ppData; pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; DWORD addr = reinterpret_cast<DWORD>(logprintf); if (addr == Addresses::FUNC_Logprintf_037_R2) { currentVersion = SAMPVersion::VERSION_037_R2; Initialize(); } else if (addr == Addresses::FUNC_Logprintf_03DL_R1) { currentVersion = SAMPVersion::VERSION_03DL_R1; Initialize(); } else { logprintf(" -- samp-compat: Unsupported version", szVersion); return false; } return true; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX* amx) { if (!PostInitialized) { // Get pRakServer int(*pfn_GetRakServer)(void) = (int(*)(void))ppPluginData[PLUGIN_DATA_RAKSERVER]; pRakServer = (void*)pfn_GetRakServer(); Impl::InstallPostHooks(); PostInitialized = true; } return amx_Register(amx, nativeList, -1); } PLUGIN_EXPORT int PLUGIN_CALL Unload() { if (Initialized) { Impl::UninstallHooks(); } return 1; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX* amx) { return 1; }
19.58209
83
0.716082
IllidanS4
ee8e079de7f4afbd0ca4779cb9be34e2761d2f32
137
cpp
C++
docs/assets/playground/char_class_union.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
docs/assets/playground/char_class_union.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
docs/assets/playground/char_class_union.cpp
gkgoat1/lexy
9c600fa906e81efbb3e34b8951ebc56809f2a0df
[ "BSL-1.0" ]
null
null
null
// INPUT:H123 struct production { static constexpr auto rule // = dsl::identifier(dsl::ascii::upper / dsl::ascii::digit); };
19.571429
65
0.635036
gkgoat1
ee8f18afcecb0020ca5d313cabee7ebee4cb4e85
1,056
cpp
C++
ECE551-cpp/042_bits_arr/numToBits.cpp
yo1995/cht_Duke_courses
d889e85e677f419c67c12e78143f3e8143457944
[ "MIT" ]
8
2019-03-28T18:37:32.000Z
2022-03-29T22:15:05.000Z
ECE551-cpp/042_bits_arr/numToBits.cpp
yo1995/cht_Duke_courses
d889e85e677f419c67c12e78143f3e8143457944
[ "MIT" ]
null
null
null
ECE551-cpp/042_bits_arr/numToBits.cpp
yo1995/cht_Duke_courses
d889e85e677f419c67c12e78143f3e8143457944
[ "MIT" ]
13
2018-09-12T19:56:46.000Z
2020-11-24T22:48:46.000Z
#include <stdio.h> #include <stdlib.h> #include <stdint.h> int getNthBit(uint32_t number, int bit) { if (bit <0 || bit >= 32) { printf("Bit %d is invalid\n", bit); exit (EXIT_FAILURE); } return (number & (1<<bit)) != 0; } void numToBits(uint32_t * nums, int nNums, int * bits, int nBits) { int i,j; if(nBits<nNums*32) { printf("Invalid call to numToBits! nBits is %d, nNums is %d\n",nBits,nNums); } else { for(i=0;i<nNums;i++) { for(j=0;j<32;j++) { bits[i*32+j]=getNthBit(nums[i],(31-j)); } } } } void doTest(uint32_t * nums, int n) { int bits[n *32]; numToBits(nums, n, bits, n*32); for (int i =0; i < n; i++) { printf(" %9d (%8X) => ", nums[i], nums[i]); for (int j = 0; j < 32; j++) { printf("%d", bits[i*32 + j]); } printf("\n"); } } int main(void) { uint32_t array1[] = { 1, 2, 3, 4, 5, 15, 109}; uint32_t array2[] = { 123456789, 987654321 }; int bits[7*32-1]; doTest (array1, 7); doTest (array2, 2); numToBits(array1,7, bits , 7*32-1); return EXIT_SUCCESS; }
19.924528
78
0.549242
yo1995
ee91090d1aa9d27dc9332b8de85cb316ab57e015
8,277
cpp
C++
helperfunctions/filterHelpers/gpumle/GPUgenerateBlobs VS2013/GPUgenerateBlobs/mexFunction.cpp
qnano/smfish
6f82c2a571d47336b4f5216e8a79395caec190af
[ "MIT" ]
null
null
null
helperfunctions/filterHelpers/gpumle/GPUgenerateBlobs VS2013/GPUgenerateBlobs/mexFunction.cpp
qnano/smfish
6f82c2a571d47336b4f5216e8a79395caec190af
[ "MIT" ]
null
null
null
helperfunctions/filterHelpers/gpumle/GPUgenerateBlobs VS2013/GPUgenerateBlobs/mexFunction.cpp
qnano/smfish
6f82c2a571d47336b4f5216e8a79395caec190af
[ "MIT" ]
1
2021-01-18T11:17:25.000Z
2021-01-18T11:17:25.000Z
#include <stdio.h> /* for stderr */ #include <stdlib.h> #include <iostream> #include <string.h> #include "mex.h" #include "math.h" #include "cuda_runtime.h" #include "matrix.h" #include "definitions.h" #include "kernel.h" extern void kernel_guassiansampleblobs_wrapper(dim3 dimGrid, dim3 dimBlock, int,int,int, float*,float*,float*, float*,float*,float*,float*,float*,float*); extern void kernel_guassianintegrateblobs_wrapper(dim3 dimGrid, dim3 dimBlock,int,int,int, float*,float*,float*, float*,float*,float*,float*,float*,float*); void CUDAERROR(const char *instr); void cudasafe( cudaError_t err, char* str, int lineNumber); #define min(a,b) (((a) < (b)) ? (a) : (b)) #define max(a,b) (((a) > (b)) ? (a) : (b)) #define roundf(x) x >= 0.0f ? floorf(x + 0.5f) : ceilf(x - 0.5f); //******************************************************************************************* void CUDAERROR(const char *instr) { cudaError_t errornum; const char *str; if (errornum=cudaGetLastError()) { str=cudaGetErrorString(errornum); mexPrintf("%s\n", str); mexPrintf("You should clear this function in MATLAB for proper operation.\n", str); } } //******************************************************************************************* void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /*! * \brief Entry point in the code for Matlab. Equivalent to main(). * \param nlhs number of left hand mxArrays to return * \param plhs array of pointers to the output mxArrays * \param nrhs number of input mxArrays * \param prhs array of pointers to the input mxArrays. */ int blockx; int threadx; int ii,iii,jj,kk,flag; int memblobsnum,ysz,xsz; float * xarray, * yarray, * Narray,*yt,*xl,*xsigma,*ysigma,*covariance,*im; float *d_xarray, *d_yarray, *d_Narray, *d_xsigma, *d_ysigma,*d_covariance,*d_im,*d_xl,*d_yt,*subim; const mwSize *datasize; int locr; mwSize imdim[2]; if (nrhs<9) mexErrMsgTxt("xsize,ysize,x_array, y_array, N_array, sigmaX, sigmaY, covariance, UseIntegrated_FLAG\n"); if (mxGetClassID(prhs[0])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); if (mxGetClassID(prhs[1])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); if (mxGetClassID(prhs[2])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); if (mxGetClassID(prhs[3])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); if (mxGetClassID(prhs[4])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); if (mxGetClassID(prhs[5])!=mxSINGLE_CLASS) mexErrMsgTxt("Data must be comprised of single floats!\n"); datasize=mxGetDimensions(prhs[2]); if (datasize[1]!=1) mexErrMsgTxt("xarray should be n X 1 array\n"); datasize=mxGetDimensions(prhs[3]); if (datasize[1]!=1) mexErrMsgTxt("xarray should be n X 1 array\n"); datasize=mxGetDimensions(prhs[4]); if (datasize[1]!=1) mexErrMsgTxt("xarray should be n X 1 array\n"); datasize=mxGetDimensions(prhs[5]); if (datasize[1]!=1) mexErrMsgTxt("xarray should be n X 1 array\n"); xsz =(int) mxGetScalar(prhs[0]); ysz =(int) mxGetScalar(prhs[1]); imdim[0]=xsz; imdim[1]=ysz; //PSFSigma=(float)mxGetScalar(prhs[1]); //matlab-dip_image convention xarray =(float *) mxGetData(prhs[2]); yarray =(float *) mxGetData(prhs[3]); Narray =(float *) mxGetData(prhs[4]); xsigma =(float *)mxGetData(prhs[5]); ysigma =(float *)mxGetData(prhs[6]); covariance =(float *)mxGetData(prhs[7]); flag =(int) mxGetScalar(prhs[8]); int blobn = (int)datasize[0]; //check to see whether it exceeds 400MB=20*20*250000*4, if it reaches, it probably could crush. The image reconstruction should be implemented on reconstruct on GPU device memory instead of host memory on PC. if (blobn>250000) mexErrMsgTxt("Size of total blobs to be generated exceeded capacity of GPU global memory (blobn>250,000). Consider partitioning them using 'for' loops \n"); float maxsigma=-1; float sigma; for(ii=0;ii<blobn;ii++){ sigma=sqrt(pow(xsigma[ii],2)+pow(ysigma[ii],2)); maxsigma=max(maxsigma,sigma); } int sz= (int) roundf(8.0*maxsigma); sz=min(sz,20); if ((flag!=1)&&(flag!=0)) mexErrMsgTxt("flag can only be 0 or 1\n"); // over allocate for additional thread reading error int BlockSize=(int) min(ceil((float) 15000/4/sz/sz),64); memblobsnum=(int)ceil((float)datasize[0]/BlockSize)+128; cudaMalloc((void**)&d_xarray, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_xarray, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_xarray, xarray, datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_yarray, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_yarray, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_yarray, yarray,datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_Narray, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_Narray, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_Narray, Narray,datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_xsigma, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_xsigma, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_xsigma, xsigma,datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_ysigma, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_ysigma, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_ysigma, ysigma,datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_covariance, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_covariance, 0, memblobsnum*BlockSize*sizeof(float)); cudaMemcpy(d_covariance, covariance,datasize[0]*sizeof(float), cudaMemcpyHostToDevice); cudaMalloc((void**)&d_im, sz*sz*memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_im, 0, sz*sz*memblobsnum*BlockSize*sizeof(float)); cudaMalloc((void**)&d_xl, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_xl, 0, memblobsnum*BlockSize*sizeof(float)); cudaMalloc((void**)&d_yt, memblobsnum*BlockSize*sizeof(float)); cudaMemset(d_yt, 0, memblobsnum*BlockSize*sizeof(float)); //only run NK blocks in each kernel int numK=(int)ceil((float)datasize[0]/BlockSize/NK); for (int ii=0;ii<numK;ii++) { blockx = (int) min(ceil(((float)(((float)datasize[0])/BlockSize)-ii*NK)), NK); blockx = (int) max(blockx,1); threadx= BlockSize; dim3 dimBlock(threadx); dim3 dimGrid(blockx); //printf("threadx: %d,blockx: %d\n", threadx, blockx); switch (flag) { case 0: kernel_guassiansampleblobs_wrapper(dimGrid, dimBlock,ii,BlockSize,sz, d_xarray,d_yarray,d_Narray, d_xsigma,d_ysigma,d_covariance,d_im,d_xl,d_yt); break;//15x15 images, 64 per block case 1: kernel_guassianintegrateblobs_wrapper(dimGrid, dimBlock,ii,BlockSize,sz, d_xarray,d_yarray,d_Narray, d_xsigma,d_ysigma,d_covariance,d_im,d_xl,d_yt); break;//15x15 images, 64 per block } // too make the loop work, we have to operate on d_data // this trick works to over smart compiler! //cudaMemcpy(d_xarray, xarray, 1*sizeof(float), cudaMemcpyHostToDevice); CUDAERROR("kernel"); //mexEvalString("pause(0.001)"); } subim= (float * )malloc(datasize[0]*sz*sz*sizeof(float)); xl=(float * )malloc(datasize[0]*sizeof(float)); yt=(float * )malloc(datasize[0]*sizeof(float)); //reconstruct images plhs[0]=mxCreateNumericArray(2, imdim, mxSINGLE_CLASS, mxREAL); im=(float *)mxGetData(plhs[0]); cudaMemcpy(subim, d_im, datasize[0]*sz*sz*sizeof(float), cudaMemcpyDeviceToHost); cudaMemcpy(xl, d_xl, datasize[0]*sizeof(float), cudaMemcpyDeviceToHost); cudaMemcpy(yt, d_yt, datasize[0]*sizeof(float), cudaMemcpyDeviceToHost); for(kk=0;kk<blobn;kk++){ for(jj=0;jj<sz;jj++){ for(iii=0;iii<sz;iii++){ if ((((int)xl[kk]+iii)<(xsz))&&(((int)yt[kk]+jj)<(ysz))){ locr=((int)yt[kk]+jj)*xsz+(int)xl[kk]+iii; if((subim[kk*sz*sz+jj*sz+iii]>0)&&(subim[kk*sz*sz+jj*sz+iii]<100000)&&(locr>=0)&&(locr<((xsz)*(ysz)))) im[locr]+=subim[kk*sz*sz+jj*sz+iii]; } } } } free(subim); free(xl); free(yt); cudaFree(d_xarray); cudaFree(d_yarray); cudaFree(d_Narray); cudaFree(d_xsigma); cudaFree(d_ysigma); cudaFree(d_covariance); cudaFree(d_im); cudaFree(d_xl); cudaFree(d_yt); }
33.922131
209
0.695663
qnano
ee9425fc42b56f5644c040b5b052deb2d31bc2ad
1,096
hpp
C++
include/GlobalNamespace/SR.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/SR.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/SR.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: SR class SR : public ::Il2CppObject { public: // Creating value type constructor for type: SR SR() noexcept {} // static System.String Format(System.String resourceFormat, System.Object p1) // Offset: 0x1A648DC static ::Il2CppString* Format(::Il2CppString* resourceFormat, ::Il2CppObject* p1); // static System.String Format(System.String resourceFormat, System.Object p1, System.Object p2) // Offset: 0x1A6495C static ::Il2CppString* Format(::Il2CppString* resourceFormat, ::Il2CppObject* p1, ::Il2CppObject* p2); }; // SR #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::SR*, "", "SR");
39.142857
107
0.652372
darknight1050
ee956cf1556c07a179152771e0103e119e283038
14,786
cpp
C++
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * 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 * */ #include "DocumentPropertyEditor.h" #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> #include <AzCore/DOM/DomUtils.h> #include <AzFramework/DocumentPropertyEditor/PropertyEditorNodes.h> #include <AzToolsFramework/UI/DocumentPropertyEditor/PropertyEditorToolsSystemInterface.h> namespace AzToolsFramework { // helper method used by both the view and row widgets to empty layouts static void DestroyLayoutContents(QLayout* layout) { while (auto layoutItem = layout->takeAt(0)) { auto subWidget = layoutItem->widget(); if (subWidget) { delete subWidget; } delete layoutItem; } } DPERowWidget::DPERowWidget(QWidget* parentWidget) : QWidget(parentWidget) { m_mainLayout = new QVBoxLayout(this); setLayout(m_mainLayout); m_columnLayout = new QHBoxLayout(); m_mainLayout->addLayout(m_columnLayout); m_childRowLayout = new QVBoxLayout(); m_mainLayout->addLayout(m_childRowLayout); } DPERowWidget::~DPERowWidget() { Clear(); } void DPERowWidget::Clear() { // propertyHandlers own their widgets, so don't destroy them here. Set them free! for (auto propertyWidgetIter = m_widgetToPropertyHandler.begin(), endIter = m_widgetToPropertyHandler.end(); propertyWidgetIter != endIter; ++propertyWidgetIter) { m_columnLayout->removeWidget(propertyWidgetIter->first); } m_widgetToPropertyHandler.clear(); DestroyLayoutContents(m_columnLayout); DestroyLayoutContents(m_childRowLayout); m_domOrderedChildren.clear(); } void DPERowWidget::AddChildFromDomValue(const AZ::Dom::Value& childValue, int domIndex) { auto childType = childValue.GetNodeName(); // create a child widget from the given DOM value and add it to the correct layout QBoxLayout* layoutForWidget = nullptr; QWidget* addedWidget = nullptr; if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::Row>()) { // if it's a row, recursively populate the children from the DOM array in the passed value auto newRow = new DPERowWidget(this); newRow->SetValueFromDom(childValue); addedWidget = newRow; layoutForWidget = m_childRowLayout; } else if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::Label>()) { auto labelString = childValue[AZ::DocumentPropertyEditor::Nodes::Label::Value.GetName()].GetString(); addedWidget = new QLabel(QString::fromUtf8(labelString.data(), static_cast<int>(labelString.size())), this); layoutForWidget = m_columnLayout; } else if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::PropertyEditor>()) { auto dpeSystem = AZ::Interface<AzToolsFramework::PropertyEditorToolsSystemInterface>::Get(); auto handlerId = dpeSystem->GetPropertyHandlerForNode(childValue); // if we found a valid handler, grab its widget and add it to our column layout if (handlerId) { // store, then reference the unique_ptr that will manage the handler's lifetime auto handler = dpeSystem->CreateHandlerInstance(handlerId); handler->SetValueFromDom(childValue); addedWidget = handler->GetWidget(); m_widgetToPropertyHandler[addedWidget] = AZStd::move(handler); layoutForWidget = m_columnLayout; } } else { AZ_Assert(0, "unknown node type for DPE"); } // insert this new widget into the dom order, even if it's an empty widget to ensure the order is correct auto insertIterator = m_domOrderedChildren.begin() + domIndex; insertIterator = m_domOrderedChildren.insert(insertIterator, addedWidget); // properly place the new widget in its given layout, correctly ordered by DOM index if (addedWidget && layoutForWidget) { // search subsequent dom entries for the first occurrence of a widget in the same layout, // then insert this new widget right before it. If there aren't any, then append this to the layout ++insertIterator; bool inserted = false; while (!inserted && insertIterator != m_domOrderedChildren.end()) { const int insertIndex = layoutForWidget->indexOf(*insertIterator); if (insertIndex != -1) { layoutForWidget->insertWidget(insertIndex, addedWidget); inserted = true; } } if (!inserted) { layoutForWidget->addWidget(addedWidget); } } } void DPERowWidget::SetValueFromDom(const AZ::Dom::Value& domArray) { Clear(); // populate all direct children of this row for (size_t arrayIndex = 0, numIndices = domArray.ArraySize(); arrayIndex < numIndices; ++arrayIndex) { auto& childValue = domArray[arrayIndex]; AddChildFromDomValue(childValue, static_cast<int>(arrayIndex)); } } void DPERowWidget::HandleOperationAtPath(const AZ::Dom::PatchOperation& domOperation, size_t pathIndex) { const auto& fullPath = domOperation.GetDestinationPath(); auto pathEntry = fullPath[pathIndex]; AZ_Assert(pathEntry.IsIndex() || pathEntry.IsEndOfArray(), "the direct children of a row must be referenced by index"); // if we're on the last entry in the path, this row widget is the direct owner if (pathIndex == fullPath.Size() - 1) { int childIndex = 0; if (pathEntry.IsIndex()) { // remove and replace operations must match an existing index. Add operations can be one past the current end. AZ_Assert( (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add ? childIndex <= m_domOrderedChildren.size() : childIndex < m_domOrderedChildren.size()), "patch index is beyond the array bounds!"); childIndex = static_cast<int>(pathEntry.GetIndex()); } else if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add) { childIndex = static_cast<int>(m_domOrderedChildren.size()); } else // must be IsEndOfArray and a replace or remove, use the last existing index { childIndex = static_cast<int>(m_domOrderedChildren.size() - 1); } // if this is a remove or replace, remove the existing entry first, // then, if this is a replace or add, add the new entry if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Remove || domOperation.GetType() == AZ::Dom::PatchOperation::Type::Replace) { const auto childIterator = m_domOrderedChildren.begin() + childIndex; delete *childIterator; // deleting the widget also automatically removes it from the layout m_domOrderedChildren.erase(childIterator); } if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Replace || domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add) { AddChildFromDomValue(domOperation.GetValue(), static_cast<int>(childIndex)); } } else // not the direct owner of the entry to patch { // find the next widget in the path and delegate the operation to them const size_t childIndex = (pathEntry.IsIndex() ? pathEntry.GetIndex() : m_domOrderedChildren.size() - 1); AZ_Assert(childIndex <= m_domOrderedChildren.size(), "DPE: Patch failed to apply, invalid child index specified"); if (childIndex > m_domOrderedChildren.size()) { return; } QWidget* childWidget = m_domOrderedChildren[childIndex]; if (m_childRowLayout->indexOf(childWidget) != -1) { // child is a DPERowWidget if it's in this layout, pass patch processing to it static_cast<DPERowWidget*>(childWidget)->HandleOperationAtPath(domOperation, pathIndex + 1); } else // child must be a label or a PropertyEditor { // pare down the path to this node, then look up and set the value from the DOM auto subPath = fullPath; for (size_t pathEntryIndex = fullPath.size() - 1; pathEntryIndex > pathIndex; --pathEntryIndex) { subPath.Pop(); } const auto valueAtSubPath = GetDPE()->GetAdapter()->GetContents()[subPath]; m_widgetToPropertyHandler[childWidget]->SetValueFromDom(valueAtSubPath); } } } DocumentPropertyEditor* DPERowWidget::GetDPE() { DocumentPropertyEditor* theDPE = nullptr; QWidget* ancestorWidget = parentWidget(); while (ancestorWidget && !theDPE) { theDPE = qobject_cast<DocumentPropertyEditor*>(ancestorWidget); ancestorWidget = ancestorWidget->parentWidget(); } AZ_Assert(theDPE, "the top level widget in any DPE hierarchy must be the DocumentPropertyEditor itself!"); return theDPE; } DocumentPropertyEditor::DocumentPropertyEditor(QWidget* parentWidget) : QFrame(parentWidget) { new QVBoxLayout(this); } DocumentPropertyEditor::~DocumentPropertyEditor() { DestroyLayoutContents(GetVerticalLayout()); } void DocumentPropertyEditor::SetAdapter(AZ::DocumentPropertyEditor::DocumentAdapter* theAdapter) { m_adapter = theAdapter; m_resetHandler = AZ::DocumentPropertyEditor::DocumentAdapter::ResetEvent::Handler( [this]() { this->HandleReset(); }); m_adapter->ConnectResetHandler(m_resetHandler); m_changedHandler = AZ::DocumentPropertyEditor::DocumentAdapter::ChangedEvent::Handler( [this](const AZ::Dom::Patch& patch) { this->HandleDomChange(patch); }); m_adapter->ConnectChangedHandler(m_changedHandler); // populate the view from the full adapter contents, just like a reset HandleReset(); } QVBoxLayout* DocumentPropertyEditor::GetVerticalLayout() { return static_cast<QVBoxLayout*>(layout()); } void DocumentPropertyEditor::AddRowFromValue(const AZ::Dom::Value& domValue, int rowIndex) { auto newRow = new DPERowWidget(this); newRow->SetValueFromDom(domValue); GetVerticalLayout()->insertWidget(rowIndex, newRow); } void DocumentPropertyEditor::HandleReset() { // clear any pre-existing DPERowWidgets DestroyLayoutContents(GetVerticalLayout()); auto topContents = m_adapter->GetContents(); for (size_t arrayIndex = 0, numIndices = topContents.ArraySize(); arrayIndex < numIndices; ++arrayIndex) { auto& rowValue = topContents[arrayIndex]; auto domName = rowValue.GetNodeName().GetStringView(); const bool isRow = (domName == AZ::DocumentPropertyEditor::Nodes::Row::Name); AZ_Assert(isRow, "adapters must only have rows as direct children!"); if (isRow) { AddRowFromValue(rowValue, static_cast<int>(arrayIndex)); } } } void DocumentPropertyEditor::HandleDomChange(const AZ::Dom::Patch& patch) { auto* rowLayout = GetVerticalLayout(); for (auto operationIterator = patch.begin(), endIterator = patch.end(); operationIterator != endIterator; ++operationIterator) { const auto& patchPath = operationIterator->GetDestinationPath(); auto firstAddressEntry = patchPath[0]; AZ_Assert( firstAddressEntry.IsIndex() || firstAddressEntry.IsEndOfArray(), "first entry in a DPE patch must be the index of the first row"); auto rowIndex = (firstAddressEntry.IsIndex() ? firstAddressEntry.GetIndex() : rowLayout->count()); AZ_Assert( rowIndex < rowLayout->count() || (rowIndex <= rowLayout->count() && operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Add), "received a patch for a row that doesn't exist"); // if the patch points at our root, this operation is for the top level layout if (patchPath.IsEmpty()) { if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Add) { AddRowFromValue(operationIterator->GetValue(), static_cast<int>(rowIndex)); } else { auto rowWidget = static_cast<DPERowWidget*>(GetVerticalLayout()->itemAt(static_cast<int>(firstAddressEntry.GetIndex()))->widget()); if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Replace) { rowWidget->SetValueFromDom(operationIterator->GetValue()); } else if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Remove) { rowLayout->removeWidget(rowWidget); delete rowWidget; } } } else { // delegate the action th the rowWidget, which will, in turn, delegate to the next row in the path, if available auto rowWidget = static_cast<DPERowWidget*>(GetVerticalLayout()->itemAt(static_cast<int>(firstAddressEntry.GetIndex()))->widget()); constexpr size_t pathDepth = 1; // top level has been handled, start the next operation at path depth 1 rowWidget->HandleOperationAtPath(*operationIterator, pathDepth); } } } } // namespace AzToolsFramework
42.245714
138
0.600027
BreakerOfThings
ee96685d4b1d0cea12e5ed0ad31f5b2b98dd200c
4,718
cpp
C++
vm/drivers/cli.cpp
samleb/rubinius
38eec1983b9b6739d7a552081e208aa433b99483
[ "BSD-3-Clause" ]
1
2016-05-09T10:45:38.000Z
2016-05-09T10:45:38.000Z
vm/drivers/cli.cpp
samleb/rubinius
38eec1983b9b6739d7a552081e208aa433b99483
[ "BSD-3-Clause" ]
null
null
null
vm/drivers/cli.cpp
samleb/rubinius
38eec1983b9b6739d7a552081e208aa433b99483
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include <sys/stat.h> #include "vm/environment.hpp" #include "vm/oop.hpp" #include "vm/type_info.hpp" #include "vm/exception.hpp" using namespace std; using namespace rubinius; /* Loads the runtime kernel files. They're stored in /kernel. * These files consist of classes needed to bootstrap the kernel * and just get things started in general. * * @param root [String] The file root for /kernel. This expects to find * alpha.rbc (will compile if not there). * @param env [Environment&] The environment for Rubinius. It is the uber * manager for multiple VMs and process-Ruby interaction. */ static void load_runtime_kernel(Environment& env, std::string root) { std::string dirs = root + "/index"; std::ifstream stream(dirs.c_str()); if(!stream) { std::cout << "It appears that " << root << "/index is missing.\n"; exit(1); } // Load the ruby file to prepare for bootstrapping Ruby! // The bootstrapping for the VM is already done by the time we're here. env.run_file(root + "/alpha.rbc"); while(!stream.eof()) { std::string line; stream >> line; stream.get(); // eat newline // skip empty lines if(line.size() == 0) continue; env.load_directory(root + "/" + line); } } /* The main function here handles the CL arguments passed to it. * It then boots the VM, runs the appropriate file (`loader`), * and returns 0. If there is an Assertion raised or an Exception, * it prints the backtrace supplied. This function is the wrapper for * the entire VM, as it deals with anything that could possibly happen * to the VM. It's like the person playing whack-a-mole, in that if * something tries to come out of the VM that's evil (such as a failed * assertion or exception), it catches it and skins it and shows it to * the user. * * Note: Although Rubinius is gathering support for multiple VMs, this * function does not deal with that subject. */ int main(int argc, char** argv) { Environment env(argc, argv); env.state->init_stack_size(); env.state->set_stack_start(&env); try { const char* runtime = getenv("RBX_RUNTIME"); if(!runtime) { struct stat st; runtime = RBA_PATH; if(stat(runtime, &st) == -1 || !S_ISDIR(st.st_mode)) { // Use throw rather than ::raise here because we're outside // the VM really. throw new Assertion("set RBX_RUNTIME to runtime (or equiv)"); } } std::string root = std::string(runtime); env.load_platform_conf(root); env.boot_vm(); env.load_argv(argc, argv); load_runtime_kernel(env, std::string(root)); std::string loader = root + "/loader.rbc"; env.enable_preemption(); env.start_signal_thread(); env.run_file(loader); return env.exit_code(); } catch(Assertion *e) { std::cout << "VM Assertion:" << std::endl; std::cout << " " << e->reason << std::endl << std::endl; e->print_backtrace(); std::cout << std::endl << "Ruby backtrace:" << std::endl; env.state->print_backtrace(); delete e; } catch(RubyException &e) { std::cout << "Ruby Exception hit toplevel:\n"; // Prints Ruby backtrace, and VM backtrace if captured e.show(env.state); } catch(TypeError &e) { /* TypeError's here are dealt with specially so that they can deliver * more information, such as _why_ there was a type error issue. * * This has the same name as the RubyException TypeError (run `5 + "string"` * as an example), but these are NOT the same - this exception is raised * internally when Qnil gets passed to an array method, for instance, when * an array was expected. */ std::cout << "Type Error detected:" << std::endl; TypeInfo* wanted = env.state->find_type(e.type); if(!e.object->reference_p()) { std::cout << " Tried to use non-reference value " << e.object; } else { TypeInfo* was = env.state->find_type(e.object->type_id()); std::cout << " Tried to use object of type " << was->type_name << " (" << was->type << ")"; } std::cout << " as type " << wanted->type_name << " (" << wanted->type << ")" << std::endl; e.print_backtrace(); std::cout << "Ruby backtrace:" << std::endl; env.state->print_backtrace(); } catch(std::runtime_error& e) { std::cout << "Runtime exception: " << e.what() << std::endl; } catch(VMException &e) { std::cout << "Unknown VM exception detected." << std::endl; e.print_backtrace(); } catch(std::string e) { std::cout << e << std::endl; } catch(...) { std::cout << "Unknown exception detected." << std::endl; } }
32.095238
80
0.633319
samleb
ee97070dd1aa511ba5b3855ccb16fd8b5e3351d6
3,336
hpp
C++
bmc_state_manager.hpp
msbarth/ibm-phosphor-state-manager
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
[ "Apache-2.0" ]
null
null
null
bmc_state_manager.hpp
msbarth/ibm-phosphor-state-manager
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
[ "Apache-2.0" ]
null
null
null
bmc_state_manager.hpp
msbarth/ibm-phosphor-state-manager
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
[ "Apache-2.0" ]
null
null
null
#pragma once #include "xyz/openbmc_project/State/BMC/server.hpp" #include <linux/watchdog.h> #include <sdbusplus/bus.hpp> #include <functional> namespace phosphor { namespace state { namespace manager { using BMCInherit = sdbusplus::server::object::object< sdbusplus::xyz::openbmc_project::State::server::BMC>; namespace sdbusRule = sdbusplus::bus::match::rules; /** @class BMC * @brief OpenBMC BMC state management implementation. * @details A concrete implementation for xyz.openbmc_project.State.BMC * DBus API. */ class BMC : public BMCInherit { public: /** @brief Constructs BMC State Manager * * @param[in] bus - The Dbus bus object * @param[in] busName - The Dbus name to own * @param[in] objPath - The Dbus object path */ BMC(sdbusplus::bus::bus& bus, const char* objPath) : BMCInherit(bus, objPath, true), bus(bus), stateSignal(std::make_unique<decltype(stateSignal)::element_type>( bus, sdbusRule::type::signal() + sdbusRule::member("JobRemoved") + sdbusRule::path("/org/freedesktop/systemd1") + sdbusRule::interface("org.freedesktop.systemd1.Manager"), std::bind(std::mem_fn(&BMC::bmcStateChange), this, std::placeholders::_1))) { subscribeToSystemdSignals(); discoverInitialState(); discoverLastRebootCause(); this->emit_object_added(); }; /** @brief Set value of BMCTransition **/ Transition requestedBMCTransition(Transition value) override; /** @brief Set value of CurrentBMCState **/ BMCState currentBMCState(BMCState value) override; /** @brief Returns the last time the BMC was rebooted * * @details Uses uptime information to determine when * the BMC was last rebooted. * * @return uint64_t - Epoch time, in milliseconds, of the * last reboot. */ uint64_t lastRebootTime() const override; /** @brief Set value of LastRebootCause **/ RebootCause lastRebootCause(RebootCause value) override; private: /** * @brief Retrieve input systemd unit state **/ std::string getUnitState(const std::string& unitToCheck); /** * @brief discover the state of the bmc **/ void discoverInitialState(); /** * @brief subscribe to the systemd signals **/ void subscribeToSystemdSignals(); /** @brief Execute the transition request * * @param[in] tranReq - Transition requested */ void executeTransition(Transition tranReq); /** @brief Callback function on bmc state change * * Check if the state is relevant to the BMC and if so, update * corresponding BMC object's state * * @param[in] msg - Data associated with subscribed signal * */ int bmcStateChange(sdbusplus::message::message& msg); /** @brief Persistent sdbusplus DBus bus connection. **/ sdbusplus::bus::bus& bus; /** @brief Used to subscribe to dbus system state changes **/ std::unique_ptr<sdbusplus::bus::match_t> stateSignal; /** * @brief discover the last reboot cause of the bmc **/ void discoverLastRebootCause(); }; } // namespace manager } // namespace state } // namespace phosphor
28.512821
74
0.639089
msbarth
ee9883d50c029ffa8aec2c438de71d0e1409e4ec
130
hxx
C++
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_QUERYCAPABILITIES_PRIVATE_H #define __UNIX_QUERYCAPABILITIES_PRIVATE_H #endif #endif
10.833333
42
0.853846
brunolauze
ee9ad06223a193620c30a7c0344ac7a114660687
1,120
cpp
C++
dataset/test/1624B/8.cpp
Karina5005/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
3
2022-02-15T00:29:39.000Z
2022-03-15T08:36:44.000Z
dataset/test/1624B/8.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
dataset/test/1624B/8.cpp
Kira5005-code/Plagiarism
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
[ "MIT" ]
null
null
null
#include <complex> #include <queue> #include <set> #include <unordered_set> #include <list> #include <chrono> #include <random> #include <iostream> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <map> #include <unordered_map> #include <stack> #include <array> #include <iomanip> using namespace std; typedef long long int ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<ll> vl; typedef vector<int> vi; #define fo(i, a, n) for(int i = a; i < n; i++) #define fi(i, n, a) for(int i = n; i >= a; i--) #define mp make_pair #define pb push_back #define INF 2e18 #define all(x) (x).begin(), (x).end() #define sz(x) ((ll)(x).size()) void solve() { ll A, B, C; cin >> A >> B >> C; ll G1 = 2*B-C; ll G2 = 2*B-A; ll G3 = A+C; cout << ((G1%A==0&&G1>0)||(G2%C==0&&G2>0)||(G3%2==0&&(G3/2)%B==0&&G3>0)?"YES":"NO") << "\n"; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); int T = 1; cin >> T; while(T--) { solve(); } return 0; }
20.740741
97
0.55625
Karina5005
ee9ba9e52a3ff2f6095f356e87910124a4ba2d1c
5,272
cpp
C++
AI/ObstacleAvoidance.cpp
tstaples/AI-VGP332
b4df47e64b3a25060d5300bb6c3171947f4c509c
[ "MIT" ]
null
null
null
AI/ObstacleAvoidance.cpp
tstaples/AI-VGP332
b4df47e64b3a25060d5300bb6c3171947f4c509c
[ "MIT" ]
null
null
null
AI/ObstacleAvoidance.cpp
tstaples/AI-VGP332
b4df47e64b3a25060d5300bb6c3171947f4c509c
[ "MIT" ]
null
null
null
#include "ObstacleAvoidance.h" #include "Agent.h" #include "AIWorld.h" namespace AI { ObstacleAvoidance::ObstacleAvoidance(Agent* pAgent, float weight) : SteeringBehavior(pAgent, weight) { } SVector2 ObstacleAvoidance::Update(float deltatime) { // todo: set bounding volume in character load. // Get the transformation matrices SMatrix33 agentToWorld = mpAgent->GetTransform(); SMatrix33 worldToAgent(agentToWorld); worldToAgent.Inverse(); SVector2 vel(mpAgent->GetVelocity()); float maxSpeed(mpAgent->GetMaxSpeed()); SVector2 pos(mpAgent->GetPosition()); SVector2 head(mpAgent->GetHeading()); // Calculate the length of the bounding volume const float minBoxLength = mBoundingVolume.max.x * 3.0f; // temp float range = minBoxLength + (vel.Length() / maxSpeed) * minBoxLength; // Debug draw DrawBoundingVolume(range, agentToWorld); const float height = mBoundingVolume.GetHeight() * 0.5f; SLineSegment xAxis(0.0f, 0.0f, range, 0.0f); SVector2 minIntersect(FLT_MAX, FLT_MAX); SCircle closestObstacle; bool hasObstacles = false; // If we actually intersect with any of the obstacles AIWorld::ObstacleList obstacles = mpAgent->GetAIWorld().GetObstacles(); ObstacleList::iterator it = obstacles.begin(); for (it; it != obstacles.end(); ++it) { SCircle& circle = *it; // Check that the obstacle is within range if (Intersect(circle, SCircle(pos, range))) { // Transform the obstacle into the agent's space circle.center = worldToAgent.TransformCoord(circle.center); // Ignore obstacles behind the agent. // Since we're in the agent's local space, anything with a negative x is behind. if (circle.center.x > 0.0f) { // Expand the radius of the obstacle by the height of the bounding volume circle.radius += height; // If distance from x axis to obstacle's position is less than its radius + half the width of the volumebox // then there is a potential intersection. if (fabs(circle.center.y) < circle.radius) { // Get the intersection point, but only if it's positive since a negative point means we're // already inside the ostacle. SVector2 intersect(GetXIntersect(circle, xAxis), 0.0f); if (intersect.x < minIntersect.x) { // This is the closest intersect so far minIntersect = intersect; closestObstacle = circle; hasObstacles = true; } } } } } SVector2 force(0.0f, 0.0f); if (hasObstacles) { // Debug drawing SVector2 worldIntersect = agentToWorld.TransformCoord(minIntersect); Graphics_DebugCircle(worldIntersect, 10.0f, 0xffff00); // closest intersect SVector2 closestObsWorld = agentToWorld.TransformCoord(closestObstacle.center); Graphics_DebugCircle(closestObsWorld, closestObstacle.radius, 0xf0f000); // expanded radius // Multiplier increases the closer the obstacle is to the agent float multiplier = 1.0f + (range - minIntersect.x) / range; //float lateralForce = (fabs(closestObstacle.center.y) - closestObstacle.radius) + multiplier; float lateralForce = (closestObstacle.radius - closestObstacle.center.y) * multiplier; //if (closestObstacle.center.y < 0.0f) //{ // // Below the x axis y is positive (DX), so we need to invert the force // lateralForce *= -1.0f; //} //float brakeForce = (minIntersect.x - range) * multiplier; const float brakeWeight = 0.2f; float brakeForce = (closestObstacle.radius - closestObstacle.center.y) * brakeWeight; // Bring the force back into world space force = agentToWorld.TransformNormal(SVector2(brakeForce, lateralForce)); } return force; } void ObstacleAvoidance::DrawBoundingVolume(const float range, SMatrix33& agentToWorld) { SVector2 pos(mpAgent->GetPosition()); SVector2 head(mpAgent->GetHeading()); SVector2 min = agentToWorld.TransformCoord(SVector2(mBoundingVolume.max.x, mBoundingVolume.min.y)); SVector2 max = agentToWorld.TransformCoord(mBoundingVolume.max); SVector2 minline = agentToWorld.TransformCoord(SVector2(range, mBoundingVolume.min.y)); SVector2 maxline = agentToWorld.TransformCoord(SVector2(range, mBoundingVolume.max.y)); SLineSegment rangeLine(pos, pos + (head * range)); Graphics_DebugLine(rangeLine, 0xff0000); Graphics_DebugLine(min, minline); Graphics_DebugLine(max, maxline); // Draw bounding box SVector2 tl = agentToWorld.TransformCoord(mBoundingVolume.min); SVector2 br = agentToWorld.TransformCoord(mBoundingVolume.max); SVector2 tr = agentToWorld.TransformCoord(SVector2(mBoundingVolume.max.x, mBoundingVolume.min.y)); SVector2 bl = agentToWorld.TransformCoord(SVector2(mBoundingVolume.min.x, mBoundingVolume.max.y)); Graphics_DebugLine(tl, tr, 0xff00ff); // Top line Graphics_DebugLine(tl, bl, 0xff00ff); // Left Graphics_DebugLine(bl, br, 0xff00ff); // Bottom Graphics_DebugLine(br, tr, 0xff00ff); // Right } float ObstacleAvoidance::GetXIntersect(const SCircle& c, const SLineSegment& l) { // x = Cx +/- sqrt(r^2 - Cy^2) float sqrtPart = sqrt(c.radius * c.radius - c.center.y * c.center.y); float rootX1 = c.center.x + sqrtPart; float rootX2 = c.center.x - sqrtPart; // Start with the negative root since it will be closer float x = rootX2; if (x <= 0.0f) { // Root2 is behind us, so we have to use the second root x = rootX1; } return x; } }
34.913907
111
0.731032
tstaples
eea25dcdca81b713365256e88123e13734c81441
399
cpp
C++
Nebula-Storm/src/App.cpp
GalacticKittenSS/Nebula
1620a1dab815d6721b1ae1e3e390ae16313309da
[ "Apache-2.0" ]
3
2021-11-21T21:05:44.000Z
2021-12-27T20:44:08.000Z
Nebula-Storm/src/App.cpp
GalacticKittenSS/Nebula
1620a1dab815d6721b1ae1e3e390ae16313309da
[ "Apache-2.0" ]
null
null
null
Nebula-Storm/src/App.cpp
GalacticKittenSS/Nebula
1620a1dab815d6721b1ae1e3e390ae16313309da
[ "Apache-2.0" ]
null
null
null
#include <Nebula.h> #include <Nebula_EntryPoint.h> #include "EditorLayer.h" namespace Nebula { class NebulaStorm : public Application { public: NebulaStorm(ApplicationCommandLineArgs args): Application("Nebula Storm", args) { PushLayer(new EditorLayer()); } ~NebulaStorm() { } }; Application* CreateApplication(ApplicationCommandLineArgs args) { return new NebulaStorm(args); } }
21
83
0.739348
GalacticKittenSS
eea5d071de1039c97fa41edb0cfaf94d2dc5f739
1,337
cpp
C++
effective-modern-cpp/item39_multi.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
19
2018-07-06T06:53:56.000Z
2022-01-01T16:36:26.000Z
effective-modern-cpp/item39_multi.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
null
null
null
effective-modern-cpp/item39_multi.cpp
miaogen123/daily-coding
5d7f463ad1fee5e512aeb36206526b53b9a781f6
[ "MIT" ]
17
2019-03-27T23:18:43.000Z
2021-01-18T11:17:57.000Z
#include<iostream> #include<vector> #include<windows.h> #include<atomic> #include<thread> #include<chrono> #include<future> using namespace std; using namespace std::literals; // //以及多个线程之间使用shared_future std::promise<void> commu_channel; std::atomic<bool> poll_flag(false); std::condition_variable cv; void f() { std::this_thread::sleep_for(1s); } //FIXME:: 下面的 这个模板 有问题 template <typename T, typename... param> inline std::future<typename std::result_of<T(param...)>::type> ReallyAsync(T&& f, param&&... params){ return async(std::launch::async, std::forward<T>(f), std::forward<param>(params)...); } void react() { std::cout<<"hello i'm in the react"<<endl; } void detect() { cout<<"inside the detect!!!"<<endl; auto sf=commu_channel.get_future().share(); std::vector<std::thread> vt; for(auto i=0;i<5;i++){ vt.emplace_back([sf]{sf.wait();react();}); vt.back().detach(); } //thread to_react([](){commu_channel.get_future().wait();react();}); //to_react.detach(); while(!poll_flag) Sleep(1); commu_channel.set_value(); } int main(void) { cout<<"ready to work!!!"<<endl; //ReallyAsync(detect); auto detect_async=std::async(std::launch::async,detect); cout<<"to work!!!"<<endl; poll_flag=true; auto futu=std::async(f); while(futu.wait_for(100ms)!=std::future_status::ready){} return 0; }
19.1
69
0.673897
miaogen123
eea86c32bd28db9d839add2d0cfb13ef7a607c1b
928
cpp
C++
arduino/hellospiffs/src/main.cpp
ricklon/kombuchamanager
5ab11322637294e49a4f85c8cc65bdd780af806c
[ "Apache-2.0" ]
null
null
null
arduino/hellospiffs/src/main.cpp
ricklon/kombuchamanager
5ab11322637294e49a4f85c8cc65bdd780af806c
[ "Apache-2.0" ]
null
null
null
arduino/hellospiffs/src/main.cpp
ricklon/kombuchamanager
5ab11322637294e49a4f85c8cc65bdd780af806c
[ "Apache-2.0" ]
null
null
null
/* Hello World SPIFFS based of DFRObot Tutorial https://www.dfrobot.com/blog-1111.html */ #include <Arduino.h> #include "SPIFFS.h" void setup() { Serial.begin(115200); if(!SPIFFS.begin(true)){ Serial.println("An Error has occurred while mounting SPIFFS"); return; } File file = SPIFFS.open("/test.txt", FILE_WRITE); if(!file){ Serial.println("There was an error opening the file for writing"); return; } if(file.print("TEST")){ Serial.println("File was written");; } else { Serial.println("File write failed"); } file.close(); File file2 = SPIFFS.open("/test.txt"); if(!file2){ Serial.println("Failed to open file for reading"); return; } Serial.println("File Content:"); while(file2.available()){ Serial.write(file2.read()); } file2.close(); } void loop() {}
17.509434
74
0.578664
ricklon
eeab701031cf569d33514c1ac4220f3a1ac2d52b
3,118
cpp
C++
src/main.cpp
pawREP/Glacier-Prim-IO
5c6a512656e526b5c5d859623c3670eaa802d88f
[ "MIT" ]
12
2020-04-03T00:00:16.000Z
2022-03-09T11:40:48.000Z
src/main.cpp
pawREP/Glacier-Prim-IO
5c6a512656e526b5c5d859623c3670eaa802d88f
[ "MIT" ]
2
2020-04-12T03:10:09.000Z
2020-05-10T22:24:45.000Z
src/main.cpp
pawREP/Glacier-Prim-IO
5c6a512656e526b5c5d859623c3670eaa802d88f
[ "MIT" ]
4
2020-04-10T03:06:05.000Z
2021-09-30T06:03:30.000Z
#include "mainwindow.h" #include "GlacierFormats.h" #include <iostream> #include <QApplication> #include <QtConcurrent/qtconcurrentrun.h> void initAppStyle() { qApp->setStyle(QStyleFactory::create("Fusion")); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(25, 25, 25)); darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); darkPalette.setColor(QPalette::Disabled, QPalette::Window, QColor(53, 53, 53)); darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, Qt::gray); darkPalette.setColor(QPalette::Disabled, QPalette::Base, QColor(25, 25, 25)); darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, QColor(53, 53, 53)); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, Qt::gray); darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, Qt::gray); darkPalette.setColor(QPalette::Disabled, QPalette::Text, Qt::gray); darkPalette.setColor(QPalette::Disabled, QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::gray); darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Disabled, QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, Qt::black); qApp->setPalette(darkPalette); qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); } void initGlacierFormats() { QProgressDialog progressDialog; progressDialog.setWindowTitle("Loading..."); progressDialog.setRange(0, 0); progressDialog.setLabel(new QLabel("Initilizing GlacierFormats, this might take a few seconds...", &progressDialog)); progressDialog.show(); auto future = QtConcurrent::run(&GlacierFormats::GlacierInit); while (!future.isFinished()) { qApp->processEvents(); Sleep(33); } if (progressDialog.wasCanceled()) exit(0); progressDialog.close(); } int main(int argc, char *argv[]) { #ifndef _DEBUG ShowWindow(GetConsoleWindow(), SW_HIDE); #endif QApplication app(argc, argv); initAppStyle(); initGlacierFormats(); MainWindow window; QSize windowSize(1200, 800); window.resize(windowSize); window.show(); return app.exec(); }
39.468354
121
0.716806
pawREP
eead54f4bba87a27acef158e255573de02dfcf37
2,068
cpp
C++
QSettingsDialog/core/qsettingsentry.cpp
cybik/QSettingsDialog
106ab053f042d57a89acec49ddb348aaf2aec14d
[ "BSD-3-Clause" ]
9
2017-04-18T06:10:49.000Z
2022-03-28T14:35:07.000Z
QSettingsDialog/core/qsettingsentry.cpp
cybik/QSettingsDialog
106ab053f042d57a89acec49ddb348aaf2aec14d
[ "BSD-3-Clause" ]
null
null
null
QSettingsDialog/core/qsettingsentry.cpp
cybik/QSettingsDialog
106ab053f042d57a89acec49ddb348aaf2aec14d
[ "BSD-3-Clause" ]
8
2016-12-23T08:24:23.000Z
2022-02-18T01:54:15.000Z
#include "qsettingsentry.h" #include "qsettingsentry_p.h" #include <QThread> #define d this->d_ptr QSettingsEntry::QSettingsEntry(int displaytype, QSettingsLoader *loader) : d_ptr(new QSettingsEntryPrivate(displaytype, loader)) {} QSettingsEntry::QSettingsEntry(int displaytype, QSettingsLoader *loader, const QString &name, bool optional, const QString &tooltip, const UiPropertyMap &properties) : d_ptr(new QSettingsEntryPrivate(displaytype, loader)) { d->name = name; d->optional = optional; d->tooltip = tooltip; d->properties = properties; } QSettingsEntry::~QSettingsEntry() { #ifndef QT_NO_DEBUG Q_ASSERT_X(d->refCounter == 0, Q_FUNC_INFO, "settings entry destroyed with active loaders!"); #endif } QString QSettingsEntry::entryName() const { return d->name; } void QSettingsEntry::setEntryName(const QString &name) { d->name = name; } bool QSettingsEntry::isOptional() const { return d->optional; } void QSettingsEntry::setOptional(bool optional) { d->optional = optional; } QString QSettingsEntry::tooltip() const { return d->tooltip; } void QSettingsEntry::setTooltip(const QString &tooltip) { d->tooltip = tooltip; } UiPropertyMap QSettingsEntry::uiProperties() const { return d->properties; } void QSettingsEntry::setUiProperties(const UiPropertyMap &properties) { d->properties = properties; } void QSettingsEntry::setUiProperty(const QString &name, const QVariant &value) { d->properties.insert(name, value); } int QSettingsEntry::displaytype() { return d->displaytype; } QSettingsLoader *QSettingsEntry::getLoader() { #ifndef QT_NO_DEBUG d->refCounter++; #endif return d->loader.data(); } void QSettingsEntry::freeLoader(QSettingsLoader *) { #ifndef QT_NO_DEBUG d->refCounter--; #endif } void QSettingsEntryPrivate::LoaderDeleter::cleanup(QSettingsLoader *loader) { if(loader && loader->isAsync()) { auto async = loader->async(); if(async->thread() == QThread::currentThread()) async->deleteLater(); else QMetaObject::invokeMethod(async, "deleteLater", Qt::QueuedConnection); } else delete loader; }
20.07767
167
0.747582
cybik
eead7264b40b36f4dc87ea386eedb960a958322b
1,700
cpp
C++
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<cmath> using namespace std; #define ull unsigned long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define RG register #define IL inline const int maxN=101000; const int inf=2147483647; ull n,K,srt; bool notprime[maxN]; int pcnt,P[maxN]; ull num,Num[maxN+maxN],Id[maxN+maxN],G[maxN+maxN],H[maxN+maxN],Sum[maxN+maxN]; IL void Init(); IL int GetId(RG ull x); ull Calc(RG ull m,RG ull k); ull S(RG ull x,RG int p); int main(){ Init();RG int TTT;RG ull nn,k; scanf("%d",&TTT); while (TTT--){ scanf("%llu%llu",&nn,&k); printf("%llu\n",Calc(nn,k)); } return 0; } IL void Init(){ notprime[1]=1; for (RG int i=2;i<maxN;++i){ if (notprime[i]==0) P[++pcnt]=i,Sum[pcnt]=Sum[pcnt-1]+i; for (RG int j=1;(j<=pcnt)&&(1ll*i*P[j]<maxN);++j){ notprime[i*P[j]]=1;if (i%P[j]==0) break; } } return; } IL int GetId(RG ull x){ if (x<=srt) return Id[x]; else return Id[n/x+maxN]; } IL ull Calc(RG ull m,RG ull k){ num=0;n=m;srt=sqrt(m);K=k; for (RG ull i=1,j;i<=n;i=j+1){ j=n/i;Num[++num]=j;//G[num]=j*(j+1)/2-1; H[num]=j-1; if (j<=srt) Id[j]=num; else Id[i+maxN]=num;j=n/j; } //for (int i=1;i<=100;i++) cout<<P[i]<<" ";cout<<endl; for (RG int j=1;j<=pcnt;++j) for (RG int i=1;(i<=num)&&(1ll*P[j]*P[j]<=Num[i]);++i) H[i]=H[i]-H[GetId(Num[i]/P[j])]+j-1; return S(m,1)+1; } ull S(RG ull x,RG int p){ if ((x<=1)||(P[p]>x)) return 0; RG int id=GetId(x);RG ull ret=(H[id]-(p-1))*(K+1); for (RG int i=p;(i<=pcnt)&&(1ll*P[i]*P[i]<=x);++i){ RG ull mul=P[i]; for (RG int j=1;mul*P[i]<=x;j++,mul*=P[i]) ret=ret+S(x/mul,i+1)*(K*j+1)+(ull)K*(j+1)+1; } return ret; }
21.794872
78
0.58
SYCstudio
eeae7fd238aeeb0ea28c1039413c0ecc1f76b3d7
507
hpp
C++
lib/wedges/wedge.hpp
llpm/llpm
47000202b2bb5f09cf739b9094f948744f6d72d2
[ "Apache-2.0" ]
1
2021-11-28T14:56:21.000Z
2021-11-28T14:56:21.000Z
lib/wedges/wedge.hpp
llpm/llpm
47000202b2bb5f09cf739b9094f948744f6d72d2
[ "Apache-2.0" ]
null
null
null
lib/wedges/wedge.hpp
llpm/llpm
47000202b2bb5f09cf739b9094f948744f6d72d2
[ "Apache-2.0" ]
null
null
null
#ifndef __LLPM_WEDGES_WEDGE_HPP__ #define __LLPM_WEDGES_WEDGE_HPP__ #include <util/files.hpp> namespace llpm { // Fwd defs class Module; class Wedge { public: virtual ~Wedge() { } virtual void writeModule(FileSet& fileset, Module* mod) = 0; }; /** * Specifies a class which wraps a module in another, usually to * provide translation. Good accessory for a wedge. */ class Wrapper { public: virtual Module* wrapModule(Module* mod) = 0; }; } // llpm #endif // __LLPM_WEDGES_WEDGE_HPP__
16.9
64
0.712032
llpm
eeb0a2314fe1a6c64d24e5dee64c0a0f92499f25
17,794
cpp
C++
source/Lib/CommonLib/ContextModelling.cpp
theambient/hhi_next_software
a99e39bad84ccde327c81e62dc2aa83fa73a295a
[ "BSD-3-Clause" ]
null
null
null
source/Lib/CommonLib/ContextModelling.cpp
theambient/hhi_next_software
a99e39bad84ccde327c81e62dc2aa83fa73a295a
[ "BSD-3-Clause" ]
null
null
null
source/Lib/CommonLib/ContextModelling.cpp
theambient/hhi_next_software
a99e39bad84ccde327c81e62dc2aa83fa73a295a
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2017, ITU/ISO/IEC * 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 ITU/ISO/IEC 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. */ /** \file ContextModelling.cpp \brief Classes providing probability descriptions and contexts */ #include "ContextModelling.h" #include "UnitTools.h" #include "CodingStructure.h" #include "Picture.h" CoeffCodingContext::CoeffCodingContext(const TransformUnit& tu, ComponentID component, bool signHide) : m_compID (component) , m_chType (toChannelType(m_compID)) , m_width (tu.block(m_compID).width) , m_height (tu.block(m_compID).height) , m_log2CGWidth ((m_width & 3) || (m_height & 3) ? 1 : 2) , m_log2CGHeight ((m_width & 3) || (m_height & 3) ? 1 : 2) , m_log2CGSize (m_log2CGWidth + m_log2CGHeight) , m_widthInGroups (m_width >> m_log2CGWidth) , m_heightInGroups (m_height >> m_log2CGHeight) , m_log2BlockWidth (g_aucLog2[m_width]) , m_log2BlockHeight (g_aucLog2[m_height]) , m_log2WidthInGroups (g_aucLog2[m_widthInGroups]) , m_log2HeightInGroups (g_aucLog2[m_heightInGroups]) , m_log2BlockSize ((m_log2BlockWidth + m_log2BlockHeight)>>1) , m_maxNumCoeff (m_width * m_height) , m_AlignFlag (tu.cs->sps->getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag()) , m_signHiding (signHide) , m_useGoRiceParAdapt (tu.cs->sps->getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag()) , m_extendedPrecision (tu.cs->sps->getSpsRangeExtension().getExtendedPrecisionProcessingFlag()) , m_maxLog2TrDynamicRange (tu.cs->sps->getMaxLog2TrDynamicRange(m_chType)) , m_scanType (CoeffScanType(TU::getCoefScanIdx( tu, m_compID))) , m_scan (g_scanOrder [SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )]) , m_scanPosX (g_scanOrderPosXY[SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )][0]) , m_scanPosY (g_scanOrderPosXY[SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )][1]) , m_scanCG (g_scanOrder[SCAN_UNGROUPED ][m_scanType][gp_sizeIdxInfo->idxFrom(m_widthInGroups)][gp_sizeIdxInfo->idxFrom(m_heightInGroups)]) , m_CtxSetLastX (Ctx::LastX[m_chType]) , m_CtxSetLastY (Ctx::LastY[m_chType]) , m_maxLastPosX (g_uiGroupIdx[m_width - 1]) , m_maxLastPosY (g_uiGroupIdx[m_height - 1]) , m_lastOffsetX (0) , m_lastOffsetY (0) , m_lastShiftX (0) , m_lastShiftY (0) , m_TrafoBypass (tu.cs->sps->getSpsRangeExtension().getTransformSkipContextEnabledFlag() && (tu.cu->transQuantBypass || tu.transformSkip[m_compID])) , m_SigBlockType (m_TrafoBypass ? 0 : m_width == 4 && m_height == 4 ? 1 : m_width == 8 && m_height == 8 ? 2 : m_log2CGSize==2 ? 4 : 3 ) , m_sigCtxSet (Ctx::SigFlag[m_chType]) , m_scanPosLast (-1) , m_subSetId (-1) , m_subSetPos (-1) , m_minSubPos (-1) , m_maxSubPos (-1) , m_sigGroupCtxId (-1) , m_gt1FlagCtxSet (0, 0) , m_gt2FlagCtxId (-1) , m_currentGolombRiceStatistic(-1) , m_prevGt2 (false) , m_sigCoeffGroupFlag () , m_altResiCompId ( tu.cs->sps->getSpsNext().getAltResiCompId() ) , m_emtNumSigCoeff (0) { // LOGTODO unsigned log2sizeX = m_log2BlockWidth; unsigned log2sizeY = m_log2BlockHeight; if (m_scanType == SCAN_VER) { std::swap(log2sizeX, log2sizeY); std::swap(const_cast<unsigned&>(m_maxLastPosX), const_cast<unsigned&>(m_maxLastPosY)); } if (m_chType == CHANNEL_TYPE_CHROMA) { if( tu.cs->pcv->rectCUs ) { const_cast<int&>(m_lastShiftX) = Clip3( 0, 2, int( ( m_scanType == SCAN_VER ? m_height : m_width ) >> 3) ); const_cast<int&>(m_lastShiftY) = Clip3( 0, 2, int( ( m_scanType == SCAN_VER ? m_width : m_height ) >> 3) ); } else { const_cast<int&>(m_lastShiftX) = log2sizeX - 2; const_cast<int&>(m_lastShiftY) = log2sizeY - 2; } } else { if( tu.cs->pcv->rectCUs ) { static const int prefix_ctx[8] = { 0, 0, 0, 3, 6, 10, 15, 21 }; const_cast<int&>(m_lastOffsetX) = prefix_ctx[ log2sizeX ]; const_cast<int&>(m_lastOffsetY) = prefix_ctx[ log2sizeY ];; } else { const_cast<int&>(m_lastOffsetX) = 3 * (log2sizeX - 2) + ((log2sizeX - 1) >> 2); const_cast<int&>(m_lastOffsetY) = 3 * (log2sizeY - 2) + ((log2sizeY - 1) >> 2); } const_cast<int&>(m_lastShiftX) = (log2sizeX + 1) >> 2; const_cast<int&>(m_lastShiftY) = (log2sizeY + 1) >> 2; } if( m_altResiCompId == 1 ) { if( m_scanType && m_log2BlockWidth == 3 && m_log2BlockHeight == 3 ) { m_scan = g_scanOrder [ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ]; m_scanPosX = g_scanOrderPosXY[ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ][0]; m_scanPosY = g_scanOrderPosXY[ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ][1]; } if( m_scanType == SCAN_VER && m_log2WidthInGroups == 1 && m_log2HeightInGroups == 1 ) { m_scanCG = g_scanOrder[ SCAN_UNGROUPED ][ m_scanType - 1 ][ gp_sizeIdxInfo->idxFrom( m_widthInGroups ) ][ gp_sizeIdxInfo->idxFrom( m_heightInGroups ) ]; } } } void CoeffCodingContext::initSubblock( int SubsetId, bool sigGroupFlag ) { m_subSetId = SubsetId; m_subSetPos = m_scanCG[ m_subSetId ]; m_minSubPos = m_subSetId << m_log2CGSize; m_maxSubPos = m_minSubPos + ( 1 << m_log2CGSize ) - 1; if( sigGroupFlag ) { m_sigCoeffGroupFlag.set ( m_subSetPos ); } unsigned CGPosY = 0; unsigned CGPosX = 0; unsigned sigRight = 0; unsigned sigLower = 0; if( m_altResiCompId == 1 ) { unsigned widthInGroups = m_widthInGroups; unsigned heightInGroups = m_heightInGroups; if( m_widthInGroups == 2 && m_heightInGroups ) { if( m_scanType == SCAN_HOR ) { widthInGroups = 1; heightInGroups = 4; } else if( m_scanType == SCAN_VER ) { widthInGroups = 4; heightInGroups = 1; } } CGPosY = m_subSetPos >> m_log2WidthInGroups; CGPosX = m_subSetPos - ( CGPosY << m_log2WidthInGroups ); bool hor8x8 = m_width == 8 && m_height == 8 && m_scanType == SCAN_HOR; bool ver8x8 = m_width == 8 && m_height == 8 && m_scanType == SCAN_VER; bool bonDiag8x8 = hor8x8 || ver8x8; if( bonDiag8x8 ) { CGPosY = ( bonDiag8x8 ? m_subSetPos : 0 ); CGPosX = ( bonDiag8x8 ? m_subSetPos : 0 ); } sigRight = unsigned( ( CGPosX + 1 ) < widthInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + 1 ] : false ); sigLower = unsigned( ( CGPosY + 1 ) < heightInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + widthInGroups ] : false ); } else { CGPosY = m_subSetPos >> m_log2WidthInGroups; CGPosX = m_subSetPos - ( CGPosY << m_log2WidthInGroups ); sigRight = unsigned( ( CGPosX + 1 ) < m_widthInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + 1 ] : false ); sigLower = unsigned( ( CGPosY + 1 ) < m_heightInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + m_widthInGroups ] : false ); } const unsigned ctxSet = m_prevGt2 + ( m_chType == CHANNEL_TYPE_LUMA ? ( m_subSetId > 0 ? 2 : 0 ) : 4 ); m_sigGroupCtxId = Ctx::SigCoeffGroup[m_chType]( sigRight | sigLower ); m_gt1FlagCtxSet = Ctx::GreaterOneFlag[ ctxSet ]; m_gt2FlagCtxId = Ctx::GreaterTwoFlag( ctxSet ); m_sigCGPattern = sigRight + ( sigLower << 1 ); if( m_altResiCompId > 0 ) { m_sigCtxSet = Ctx::SigFlag [ m_chType + 2 ]; m_gt1FlagCtxSet = Ctx::GreaterOneFlag[ m_chType + 6 ]; m_sigGroupCtxId = Ctx::SigCoeffGroup [ m_chType + 2 ]( sigRight | sigLower ); } } unsigned CoeffCodingContext::sigCtxId( int scanPos ) const { int offset = 0; // DC if( m_SigBlockType == 0 ) // bypass { offset = ( m_chType == CHANNEL_TYPE_LUMA ? 27 : 15 ); } else if( scanPos ) { const unsigned posY = m_scanPosY[ scanPos ]; const unsigned posX = m_scanPosX[ scanPos ]; if( m_SigBlockType == 1 ) // 4x4 { // const unsigned ctxIndMap4x4[16] = { 0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8 }; offset = ctxIndMap4x4[ ( posY << 2 ) + posX ]; } else { int cnt = 0; switch( m_sigCGPattern ) { case 0: { unsigned posIS = ( posX & 3 ) + ( posY & 3 ); cnt = ( posIS >= 3 ? 0 : posIS >= 1 ? 1 : 2 ); } break; case 1: { unsigned posIS = ( posY & 3 ); cnt = ( posIS >= 2 ? 0 : posIS >= 1 ? 1 : 2 ); } break; case 2: { unsigned posIS = ( posX & 3 ); cnt = ( posIS >= 2 ? 0 : posIS >= 1 ? 1 : 2 ); } break; case 3: { cnt = 2; } break; default: THROW( "sig pattern must be in range [0;3]" ); } offset = ( m_chType == CHANNEL_TYPE_LUMA && ( posX > 3 || posY > 3 ) ? 3 : 0 ) + cnt; if( m_SigBlockType == 2 ) // 8x8 { offset += ( m_scanType != SCAN_DIAG && m_chType == CHANNEL_TYPE_LUMA ? 15 : 9 ); } else // NxN { offset += ( m_chType == CHANNEL_TYPE_LUMA ? 21 : 12 ); } } } return m_sigCtxSet( offset ); } unsigned DeriveCtx::CtxCUsplit( const CodingStructure& cs, Partitioner& partitioner ) { auto adPartitioner = dynamic_cast<AdaptiveDepthPartitioner*>( &partitioner ); if( !adPartitioner ) { return 0; } const Position pos = partitioner.currArea().blocks[cs.chType]; const unsigned curSliceIdx = cs.slice->getIndependentSliceIdx(); const unsigned curTileIdx = cs.picture->tileMap->getTileIdxMap( partitioner.currArea().lumaPos() ); unsigned ctxId = 0; // get left depth const CodingUnit* cuLeft = cs.getCURestricted( pos.offset( -1, 0 ), curSliceIdx, curTileIdx, cs.chType ); ctxId = ( cuLeft && cuLeft->qtDepth > partitioner.currQtDepth ) ? 1 : 0; // get above depth const CodingUnit* cuAbove = cs.getCURestricted( pos.offset( 0, -1 ), curSliceIdx, curTileIdx, cs.chType ); ctxId += ( cuAbove && cuAbove->qtDepth > partitioner.currQtDepth ) ? 1 : 0; if( cs.sps->getSpsNext().getUseLargeCTU() ) { unsigned minDepth = 0; unsigned maxDepth = 0; adPartitioner->setMaxMinDepth( minDepth, maxDepth, cs ); if( partitioner.currDepth < minDepth ) { ctxId = 3; } else if( partitioner.currDepth >= maxDepth + 1 ) { ctxId = 4; } } return ctxId; } unsigned DeriveCtx::CtxQtCbf( const ComponentID compID, const unsigned trDepth ) { if( isChroma( compID ) ) { return trDepth; } else { return ( trDepth == 0 ? 1 : 0 ); } } unsigned DeriveCtx::CtxInterDir( const PredictionUnit& pu ) { if( pu.cs->sps->getSpsNext().getUseLargeCTU() ) { if( pu.cs->pcv->rectCUs ) { return Clip3( 0, 3, 7 - ( ( g_aucLog2[pu.lumaSize().width] + g_aucLog2[pu.lumaSize().height] + 1 ) >> 1 ) ); // VG-ASYMM DONE } return Clip3( 0, 3, 6 - g_aucLog2[pu.cu->lumaSize().width] ); } return pu.cu->qtDepth; } unsigned DeriveCtx::CtxAffineFlag( const CodingUnit& cu ) { const CodingStructure *cs = cu.cs; unsigned ctxId = 0; const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu); ctxId = (cuLeft && cuLeft->affine) ? 1 : 0; const CodingUnit *cuAbove= cs->getCURestricted(cu.lumaPos().offset(0, -1), cu); ctxId += (cuAbove && cuAbove->affine) ? 1 : 0; return ctxId; } unsigned DeriveCtx::CtxSkipFlag( const CodingUnit& cu ) { const CodingStructure *cs = cu.cs; unsigned ctxId = 0; // Get BCBP of left PU const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu); ctxId = (cuLeft && cuLeft->skip) ? 1 : 0; // Get BCBP of above PU const CodingUnit *cuAbove= cs->getCURestricted(cu.lumaPos().offset(0, -1), cu); ctxId += (cuAbove && cuAbove->skip) ? 1 : 0; return ctxId; } unsigned DeriveCtx::CtxIMVFlag( const CodingUnit& cu ) { const CodingStructure *cs = cu.cs; unsigned ctxId = 0; // Get BCBP of left PU const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu); ctxId = ( cuLeft && cuLeft->imv ) ? 1 : 0; // Get BCBP of above PU const CodingUnit *cuAbove = cs->getCURestricted(cu.lumaPos().offset(0, -1), cu); ctxId += ( cuAbove && cuAbove->imv ) ? 1 : 0; return ctxId; } unsigned DeriveCtx::CtxBTsplit(const CodingStructure& cs, Partitioner& partitioner) { const Position pos = partitioner.currArea().blocks[cs.chType]; const unsigned curSliceIdx = cs.slice->getIndependentSliceIdx(); const unsigned curTileIdx = cs.picture->tileMap->getTileIdxMap( pos ); unsigned ctx = 0; const CodingUnit *cuLeft = cs.getCURestricted( pos.offset( -1, 0 ), curSliceIdx, curTileIdx, cs.chType ); const CodingUnit *cuAbove = cs.getCURestricted( pos.offset( 0, -1 ), curSliceIdx, curTileIdx, cs.chType ); { const unsigned currDepth = partitioner.currQtDepth * 2 + partitioner.currBtDepth; if( cuLeft ) ctx += ( ( 2 * cuLeft->qtDepth + cuLeft->btDepth ) > currDepth ? 1 : 0 ); if( cuAbove ) ctx += ( ( 2 * cuAbove->qtDepth + cuAbove->btDepth ) > currDepth ? 1 : 0 ); } return ctx; } unsigned DeriveCtx::CtxFrucFlag( const PredictionUnit& pu ) { unsigned ctxId = 0; const CodingStructure &cs = *pu.cs; const Position pos = pu.lumaPos(); const PredictionUnit *puLeft = cs.getPURestricted( pos.offset( -1, 0 ), pu ); ctxId = ( puLeft ) ? puLeft->frucMrgMode > 0 : 0; const PredictionUnit *puAbove = cs.getPURestricted( pos.offset( 0, -1 ), pu ); ctxId += ( puAbove ) ? puAbove->frucMrgMode > 0 : 0; return ctxId; } unsigned DeriveCtx::CtxFrucMode( const PredictionUnit& pu ) { unsigned ctxId = 0; const CodingStructure &cs = *pu.cs; const Position pos = pu.lumaPos(); const PredictionUnit *puLeft = cs.getPURestricted( pos.offset( -1, 0 ), pu ); ctxId = ( puLeft ) ? puLeft->frucMrgMode == FRUC_MERGE_BILATERALMV : 0; const PredictionUnit *puAbove = cs.getPURestricted( pos.offset( 0, -1 ), pu ); ctxId += ( puAbove ) ? puAbove->frucMrgMode == FRUC_MERGE_BILATERALMV : 0; return ctxId; } Void MergeCtx::setMergeInfo( PredictionUnit& pu, int candIdx ) { CHECK( candIdx >= numValidMergeCand, "Merge candidate does not exist" ); pu.mergeFlag = true; pu.interDir = interDirNeighbours[candIdx]; pu.mergeIdx = candIdx; pu.mergeType = mrgTypeNeighnours[candIdx]; pu.mv [REF_PIC_LIST_0] = mvFieldNeighbours[(candIdx << 1) + 0].mv; pu.mv [REF_PIC_LIST_1] = mvFieldNeighbours[(candIdx << 1) + 1].mv; pu.mvd [REF_PIC_LIST_0] = Mv(); pu.mvd [REF_PIC_LIST_1] = Mv(); pu.refIdx [REF_PIC_LIST_0] = mvFieldNeighbours[( candIdx << 1 ) + 0].refIdx; pu.refIdx [REF_PIC_LIST_1] = mvFieldNeighbours[( candIdx << 1 ) + 1].refIdx; pu.mvpIdx [REF_PIC_LIST_0] = NOT_VALID; pu.mvpIdx [REF_PIC_LIST_1] = NOT_VALID; pu.mvpNum [REF_PIC_LIST_0] = NOT_VALID; pu.mvpNum [REF_PIC_LIST_1] = NOT_VALID; if( pu.lumaSize() == pu.cu->lumaSize() ) { pu.cu->LICFlag = ( pu.cs->slice->getUseLIC() ? LICFlags[candIdx] : false ); } }
37.940299
168
0.621052
theambient
eeb16b553883c3e711070e8293e2d53f7dae71d6
288
hpp
C++
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once namespace NewtonianEuler { /*! * \ingroup AnalyticSolutionsGroup * \brief Holds classes implementing a solution to the Newtonian Euler system. */ namespace Solutions {} } // namespace NewtonianEuler
22.153846
78
0.756944
macedo22
eeb1c0ae7d7d873e462453b4edc1f0044994411f
643
cpp
C++
euler/euler05.cpp
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
2
2015-11-08T10:01:47.000Z
2020-03-10T00:00:58.000Z
euler/euler05.cpp
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
null
null
null
euler/euler05.cpp
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> /* Ülesanne: leida 10001. algarv alustades 2'st Lahendus: proovime jõumeetodil Raivo Laanemets */ using namespace std; int main(int argc, char *argv[]) { int arv=3, b=3, k=1; bool algarv; do { b=3; algarv=true; while(b<=arv/2) { if(arv%b==0) algarv=false; b=b+2; } if(algarv) { k++; printf("%i\n", arv); } arv+=2; if(k%100==0) printf("%i\n", k/100); } while (k<10001); printf("10001. algarv on %i\n", arv-2); //NB viimase tsükli lõpus suurendati arvu 2 võrra! system("PAUSE"); return 0; }
16.921053
93
0.541213
rla
eeb2595c15e215af9d108f10e63e0a2a7aca8c70
8,829
cpp
C++
jerome/npc/factories/WeightingFactory.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
3
2018-06-11T10:48:54.000Z
2021-05-30T07:10:15.000Z
jerome/npc/factories/WeightingFactory.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
jerome/npc/factories/WeightingFactory.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
// // WeightingFactory.cpp // // Created by Anton Leuski on 9/1/15. // Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved. // // This file is part of Jerome. // // 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 <jerome/type/Record.hpp> #include <jerome/ir/rm/weighting.hpp> #include <jerome/ir/rm/AnyWeighting.hpp> #include <jerome/ir/rm/weighting/query/jelinek_mercer.hpp> #include <jerome/ir/rm/weighting/document/cross_entropy_jelinek_mercer.hpp> #include "WeightingFactory.hpp" namespace jerome { namespace npc { namespace detail { struct SubWeightingParsingVisitor : public Record::Visitor { String weightingName; SubWeightingParsingVisitor(const String& inDefaultWeightingName) : weightingName(inDefaultWeightingName) { } using Record::Visitor::operator (); void operator () (const String& inKey, const String& inValue) { if (inKey == ir::rm::weighting::Weighting::NAME_KEY) { weightingName = inValue; } } }; struct WeightingParsingVisitor : public Record::Visitor { std::vector<String> fieldName; String weightingName; String defaultFieldName; using Record::Visitor::operator (); WeightingParsingVisitor(const String& inDefaultWeightingName, const String& inDefaultFieldName) : weightingName(inDefaultWeightingName) , defaultFieldName(inDefaultFieldName) { } void operator () (const String& inKey, const String& inValue) { if (inKey == ir::rm::weighting::Weighting::NAME_KEY) { weightingName = inValue; } } void operator () (const String& inKey, const Record& inValue) { if (inKey == ir::rm::weighting::Weighting::SUB_WEIGHTING_KEY) { SubWeightingParsingVisitor visitor(defaultFieldName); inValue.visit(visitor); fieldName.push_back(visitor.weightingName); } } template <typename Object, typename DW, template <typename ...> class W> inline Result<Object> makeWeighting(const String& inProviderID) { switch (fieldName.size()) { case 1: return Object::template make<W>(inProviderID, weightingName, DW(fieldName[0])); case 2: return Object::template make<W>(inProviderID, weightingName, DW(fieldName[0]), DW(fieldName[1])); case 3: return Object::template make<W>(inProviderID, weightingName, DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2])); case 4: return Object::template make<W>(inProviderID, weightingName, DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2]), DW(fieldName[3])); case 5: return Object::template make<W>(inProviderID, weightingName, DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2]), DW(fieldName[3]), DW(fieldName[4])); default: return Error("too many fields when creating a weighting: " + std::to_string(fieldName.size())); } } template <typename Object, typename DW, template <typename ...> class W> inline Result<Object> parseRecord(const String& inProviderID) { if (fieldName.size() == 0) { fieldName.push_back("unigram"); } return makeWeighting<Object, DW, W>(inProviderID); } }; struct DefaultDocumentWeightingProvider : public AnswerWeightingFactory::provider_type { static constexpr const char* IDENTIFIER = "jerome.weighting.document.addCrossEntropyJelinekMercer"; Result<AnswerWeightingFactory::object_type> provide( const Record& inRecord) override { WeightingParsingVisitor visitor("answer", "unigram"); inRecord.visit(visitor); return visitor.parseRecord<AnswerWeightingFactory::object_type, ir::rm::weighting::document::CrossEntropyJelinekMercer, ir::rm::weighting::document::AddDocumentProbabilities>(IDENTIFIER); } }; struct DefaultQueryWeightingProvider : public QuestionWeightingFactory::provider_type { static constexpr const char* IDENTIFIER = "jerome.weighting.query.multiplyJelinekMercer"; Result<QuestionWeightingFactory::object_type> provide( const Record& inRecord) override { WeightingParsingVisitor visitor("question", "unigram"); inRecord.visit(visitor); return visitor.parseRecord<QuestionWeightingFactory::object_type, jerome::ir::rm::weighting::query::JelinekMercer, ir::rm::weighting::query::MultiplyQueryProbabilities>(IDENTIFIER); } }; } AnswerWeightingFactory::AnswerWeightingFactory() { registerProviderClass<detail::DefaultDocumentWeightingProvider>(); using namespace jerome::ir::rm::weighting; // text unigram registerModel("unigram", { AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER , Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER , Weighting::NAME_KEY, "answer" , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "unigram" } }); registerModel("bigram", { AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER , Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER , Weighting::NAME_KEY, "answer" , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "unigram" } , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "bigram" } }); registerModel("unigram+id", { AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER , Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER , Weighting::NAME_KEY, "answer" , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "unigram" } , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "id" } }); setDefaultModelKey("unigram"); } QuestionWeightingFactory::QuestionWeightingFactory() { registerProviderClass<detail::DefaultQueryWeightingProvider>(); using namespace jerome::ir::rm::weighting; // text unigram registerModel("unigram", { AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultQueryWeightingProvider::IDENTIFIER , Weighting::IDENTIFIER_KEY, query::MultiplyQueryProbabilitiesConst::IDENTIFIER , Weighting::NAME_KEY, "question" , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "unigram" } }); // text unigram registerModel("bigram", { AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultQueryWeightingProvider::IDENTIFIER , Weighting::IDENTIFIER_KEY, query::MultiplyQueryProbabilitiesConst::IDENTIFIER , Weighting::NAME_KEY, "question" , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "unigram" } , Weighting::SUB_WEIGHTING_KEY, Record { Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER , Weighting::NAME_KEY, "bigram" } }); setDefaultModelKey("unigram"); } } }
35.175299
98
0.643901
leuski-ict
eeb657c35074beacab88d2f7c50b17d4655916c3
179
c++
C++
extra/xftp/xftp-client/supercontrol_exit.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
extra/xftp/xftp-client/supercontrol_exit.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
extra/xftp/xftp-client/supercontrol_exit.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
#include "supercontrol.h++" #include <cstdlib> #include "client.h++" #include "superduperclient.h++" void xftpclient::SuperControl::Exit (Tokenizer & optns) { app.Exit(); }
14.916667
57
0.687151
maciek-27
eeb7d5bb63d4585f6319ba12baf25c3fbaf09b13
1,945
cpp
C++
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-12-06T20:36:35.000Z
2021-12-06T20:36:35.000Z
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
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. */ #include <aws/appflow/model/UpsolverS3OutputFormatConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Appflow { namespace Model { UpsolverS3OutputFormatConfig::UpsolverS3OutputFormatConfig() : m_fileType(FileType::NOT_SET), m_fileTypeHasBeenSet(false), m_prefixConfigHasBeenSet(false), m_aggregationConfigHasBeenSet(false) { } UpsolverS3OutputFormatConfig::UpsolverS3OutputFormatConfig(JsonView jsonValue) : m_fileType(FileType::NOT_SET), m_fileTypeHasBeenSet(false), m_prefixConfigHasBeenSet(false), m_aggregationConfigHasBeenSet(false) { *this = jsonValue; } UpsolverS3OutputFormatConfig& UpsolverS3OutputFormatConfig::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("fileType")) { m_fileType = FileTypeMapper::GetFileTypeForName(jsonValue.GetString("fileType")); m_fileTypeHasBeenSet = true; } if(jsonValue.ValueExists("prefixConfig")) { m_prefixConfig = jsonValue.GetObject("prefixConfig"); m_prefixConfigHasBeenSet = true; } if(jsonValue.ValueExists("aggregationConfig")) { m_aggregationConfig = jsonValue.GetObject("aggregationConfig"); m_aggregationConfigHasBeenSet = true; } return *this; } JsonValue UpsolverS3OutputFormatConfig::Jsonize() const { JsonValue payload; if(m_fileTypeHasBeenSet) { payload.WithString("fileType", FileTypeMapper::GetNameForFileType(m_fileType)); } if(m_prefixConfigHasBeenSet) { payload.WithObject("prefixConfig", m_prefixConfig.Jsonize()); } if(m_aggregationConfigHasBeenSet) { payload.WithObject("aggregationConfig", m_aggregationConfig.Jsonize()); } return payload; } } // namespace Model } // namespace Appflow } // namespace Aws
21.373626
90
0.752699
perfectrecall
eeb8c16b1ee43e8392f2e79fdc2253b928372354
8,661
cc
C++
src/DAF/AE/AESender.cc
Miguel-A/RinaSim
70ff28dc05e8250ca28c438290cf8c08f8a94a23
[ "MIT" ]
1
2016-02-24T19:31:04.000Z
2016-02-24T19:31:04.000Z
src/DAF/AE/AESender.cc
Miguel-A/RinaSim
70ff28dc05e8250ca28c438290cf8c08f8a94a23
[ "MIT" ]
null
null
null
src/DAF/AE/AESender.cc
Miguel-A/RinaSim
70ff28dc05e8250ca28c438290cf8c08f8a94a23
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2014-2016 Brno University of Technology, PRISTINE project // // 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 "AESender.h" Define_Module(AESender); PingMsg::PingMsg(){ pingAt = simTime(); } PongMsg::PongMsg(simtime_t _pingAt){ pingAt = _pingAt; pongAt = simTime(); } AESender::AESender() : AE() { S_TIM_START = "StartCommunication"; S_TIM_COM = "MakeCommunication"; S_TIM_STOP = "StopCommunication"; S_PAR_START = "startAt"; S_PAR_STOP = "stopAt"; S_PAR_SEND = "sendAfter"; S_PAR_DSTAPNAME = "dstApName"; S_PAR_DSTAPINSTANCE = "dstApInstance"; S_PAR_DSTAENAME = "dstAeName"; S_PAR_DSTAEINSTANCE = "dstAeInstance"; S_PAR_RATE = "rate"; S_PAR_RATE_VAR = "ratevar"; S_PAR_SIZE = "size"; S_PAR_SIZE_VAR = "sizevar"; S_MSG_PING = "PING-"; S_PAR_PING = "pingAt"; S_VAL_MODULEPATH = "getFullPath()"; } AESender::~AESender() { connectionState = NIL; FlowObject = NULL; Irm = NULL; Cdap = NULL; } void AESender::prepareAllocateRequest() { //Schedule AllocateRequest cMessage* m1 = new cMessage(S_TIM_START); scheduleAt(startAt, m1); } void AESender::prepareDeallocateRequest() { //Schedule DeallocateRequest cMessage* m3 = new cMessage(S_TIM_STOP); scheduleAt(stopAt, m3); } void AESender::initialize() { //Init pointers initPointers(); //Source info initNamingInfo(); //Setup signals initSignalsAndListeners(); //Init QoSRequirements initQoSRequiremets(); //Timers startAt = simTime() + par(S_PAR_START); stopAt = simTime() + par(S_PAR_STOP); sendAfter = par(S_PAR_SEND); if(sendAfter<1){ sendAfter = 1; } //Time between PDUS (s) rate = par(S_PAR_RATE).doubleValue(); ratevar = par(S_PAR_RATE_VAR).doubleValue(); //SIZE of PDU size = par(S_PAR_SIZE); sizevar = par(S_PAR_SIZE_VAR); //Destination for flow dstApName = this->par(S_PAR_DSTAPNAME).stringValue(); dstApInstance = this->par(S_PAR_DSTAPINSTANCE).stringValue(); dstAeName = this->par(S_PAR_DSTAENAME).stringValue(); dstAeInstance = this->par(S_PAR_DSTAEINSTANCE).stringValue(); //Schedule AllocateRequest if (startAt > 0) prepareAllocateRequest(); //Schedule DeallocateRequest /* if (stopAt > 0) prepareDeallocateRequest(); */ myPath = this->getFullPath(); send = 0; received = 0; pingreceived = 0; sendSize = 0; receivedSize = 0; pingreceivedSize = 0; minDelay = 999; maxDelay = -1; firstR = -1; lastR = 0; recTimes = par("recTimes").boolValue(); pduburst = par("pduburst").longValue(); if(pduburst<1) { pduburst = 1; } //Watchers WATCH(FlowObject); WATCH(send); WATCH(received); WATCH(pingreceived); WATCH(sendSize); WATCH(receivedSize); WATCH(pingreceivedSize); WATCH(minDelay); WATCH(maxDelay); } void AESender::finish() { if(par("printAtEnd").boolValue()){ EV << "At "<<this->getApni()<<endl; if(FlowObject != NULL) { EV << "With QoS " << FlowObject->getConId().getQoSId() <<endl; } EV << "send " << send << " ("<<sendSize << ")"<<endl; // EV << "pingsRcv " << pingreceived << " ("<<pingreceivedSize << ")"<<endl; EV << "pongsRcv " << received << " ("<<receivedSize << ")"<<endl; EV << "delay " << minDelay << " / "<<maxDelay<<endl; EV << "timestamps " << firstR << " -> "<<lastR<<endl; if(recTimes){ EV << "-----------------"<<endl; for(std::map<double, int>::iterator it = times.begin(); it!=times.end(); it++) { EV << " " << it->first << " " << it->second <<endl; } EV << "-----------------"<<endl; } EV << "-----------------"<<endl; } } void AESender::handleSelfMessage(cMessage *msg) { //EV << flows.back().info() << endl; if ( !strcmp(msg->getName(), S_TIM_START) ) { //FIXME: Vesely - last flow in a list?! //Flow APNamingInfo src = this->getApni(); APNamingInfo dst = APNamingInfo( APN(this->dstApName), this->dstApInstance, this->dstAeName, this->dstAeInstance); FlowObject = new Flow(src, dst); FlowObject->setQosRequirements(this->getQoSRequirements()); //Insert it to the Flows ADT insertFlow(); sendAllocationRequest(FlowObject); //Schedule ComRequest cMessage* m = new cMessage(S_TIM_COM); scheduleAt(simTime()+sendAfter+uniform(0,rate), m); } else if ( !strcmp(msg->getName(), S_TIM_STOP) ) { sendDeallocationRequest(FlowObject); } else if ( !strcmp(msg->getName(), S_TIM_COM) ) { if(stopAt > simTime()){ int tburst = intuniform(1,pduburst); double msgWait = tburst*rate; for(int i = 0; i < tburst; i++){ int msgSize = size + intuniform(-sizevar,sizevar); msgWait += uniform(-ratevar,ratevar); //Create PING messsage CDAP_M_Read* ping = new PingMsg(); ping->setByteLength(msgSize); //Send message sendData(FlowObject, ping); send++; sendSize += msgSize; } //Schedule ComRequest cMessage* m = new cMessage(S_TIM_COM); scheduleAt(simTime()+msgWait, m); } } else EV << this->getFullPath() << " received unknown self-message " << msg->getName(); delete(msg); } void AESender::handleMessage(cMessage *msg) { if ( msg->isSelfMessage() ) this->handleSelfMessage(msg); } void AESender::processMRead(CDAPMessage* msg) { PingMsg* ping = check_and_cast<PingMsg*>(msg); if(ping){ PongMsg* pong = new PongMsg(ping->pingAt); pong->setByteLength(msg->getByteLength()); sendData(FlowObject, pong); /* pingreceived++; pingreceivedSize += msg->getByteLength(); simtime_t delay = simTime() - ping->pingAt; if(minDelay>delay){ minDelay = delay; } if(maxDelay<delay){ maxDelay = delay; } if(firstR<0) { firstR = simTime(); } lastR = simTime(); */ } } void AESender::processMReadR(CDAPMessage* msg) { PongMsg* pong = check_and_cast<PongMsg*>(msg); if(pong){ received++; receivedSize += msg->getByteLength(); simtime_t delay = simTime() - pong->pingAt; if(minDelay>delay){ minDelay = delay; } if(maxDelay<delay){ maxDelay = delay; } if(firstR<0) { firstR = simTime(); } lastR = simTime(); if(recTimes){ double dl = dround(delay.dbl(), 3); times[dl]++; } } } double AESender::dround(double a, int ndigits) { int exp_base10 = round(log10(a)); double man_base10 = a*pow(10.0,-exp_base10); double factor = pow(10.0,-ndigits+1); double truncated_man_base10 = man_base10 - fmod(man_base10,factor); double rounded_remainder = fmod(man_base10,factor)/factor; rounded_remainder = rounded_remainder > 0.5 ? 1.0*factor : 0.0; return (truncated_man_base10 + rounded_remainder)*pow(10.0,exp_base10) ; }
29.161616
92
0.583882
Miguel-A
eeb910648792ca5927ca049160a7f2e931de0bfc
3,374
cpp
C++
src/analyze/anaylzeMZ.cpp
Alex4386/pe-parser
45cf63e923adc66e914f913c0094ad3615e126c5
[ "MIT-0" ]
5
2019-08-20T14:04:32.000Z
2020-10-06T10:32:52.000Z
src/analyze/anaylzeMZ.cpp
Alex4386/pe-parser
45cf63e923adc66e914f913c0094ad3615e126c5
[ "MIT-0" ]
1
2019-06-11T03:35:13.000Z
2019-06-11T06:31:13.000Z
src/analyze/anaylzeMZ.cpp
Alex4386/pe-parser
45cf63e923adc66e914f913c0094ad3615e126c5
[ "MIT-0" ]
1
2019-05-27T21:21:32.000Z
2019-05-27T21:21:32.000Z
#include "../common/common.hpp" #include "../parser/parser.hpp" #include "../common/options.hpp" #include "analyze.hpp" int analyzeMZ(MZParser mzParser, CommandLineOptions options) { MZHeader parsedHeader = mzParser.mzHeader; if (!options.outputAsJson) { analyzeMZTerminal(parsedHeader); } else { analyzeMZJson(parsedHeader); } return 0; } int analyzeMZTerminal(MZHeader parsedHeader) { std::cout << "MZ Header:" << std::endl; std::cout << " Page Count: " << parsedHeader.howManyPages << std::endl; std::cout << " Last Page Size: " << decimalWithHex(parsedHeader.lastPageBytes, "bytes") << std::endl; std::cout << " Relocations: " << parsedHeader.relocations << std::endl; std::cout << " Header Size: " << decimalWithHex(parsedHeader.headerSize, "bytes") << std::endl; std::cout << " Minimum Memory: " << decimalWithHex(parsedHeader.minMemory, "bytes") << std::endl; std::cout << " Maximum Memory: " << decimalWithHex(parsedHeader.maxMemory, "bytes") << std::endl; std::cout << " Init StackSegment: " << decimalWithHex(parsedHeader.initStackSegment) << std::endl; std::cout << " Init StackPointer: " << decimalWithHex(parsedHeader.initStackPointer) << std::endl; std::cout << " Checksum: " << decimalWithHex(parsedHeader.checksum) << std::endl; std::cout << " Init IP: " << outputHex(parsedHeader.initInstructionPointer) << std::endl; std::cout << " Init CS: " << outputHex(parsedHeader.initCodeSegment) << std::endl; std::cout << " Reloc. Table Addr: " << outputHex(parsedHeader.relocationTableAddress) << std::endl; std::cout << " Overlay counts: " << outputHex(parsedHeader.howManyOverlays) << std::endl; std::cout << " Oem ID: " << outputHex(parsedHeader.howManyOverlays) << std::endl; std::cout << " Oem Info: " << outputHex(parsedHeader.howManyOverlays) << std::endl; std::cout << " PE Header Address: " << outputHex(parsedHeader.peHeaderPointer) << std::endl; std::cout << "" << std::endl; std::cout << "MZ Header Extra:" << std::endl; std::cout << " Entrypoint: " << outputHex(parsedHeader.headerSize * 0x10) << std::endl; return 0; } int analyzeMZJson(MZHeader parsedHeader) { std::cout << "\"mzHeader\": {"; std::cout << "\"pageCount\": " << parsedHeader.howManyPages << ", "; std::cout << "\"lastPageSize\": " << parsedHeader.lastPageBytes << ", "; std::cout << "\"relocationCount\": " << parsedHeader.relocations << ", "; std::cout << "\"headerSize\": " << parsedHeader.headerSize << ", "; std::cout << "\"minMemory\": " << parsedHeader.minMemory << ", "; std::cout << "\"maxMemory\": " << parsedHeader.maxMemory << ", "; std::cout << "\"initSS\": " << parsedHeader.initStackSegment << ", "; std::cout << "\"initSP\": " << parsedHeader.initStackPointer << ", "; std::cout << "\"checksum\": " << parsedHeader.checksum << ", "; std::cout << "\"initIP\": " << parsedHeader.initInstructionPointer << ", "; std::cout << "\"initCS\": " << parsedHeader.initCodeSegment << ", "; std::cout << "\"relocationTableAddress\": " << parsedHeader.relocationTableAddress << ", "; std::cout << "\"overlayCount\": " << parsedHeader.howManyOverlays << ", "; std::cout << "\"oemId\": " << parsedHeader.oemId << ", "; std::cout << "\"oemInfo\": " << parsedHeader.oemInfo << ", "; std::cout << "\"peHeaderPointer\": " << parsedHeader.oemInfo << "} "; return 0; }
52.71875
104
0.633669
Alex4386
eebd14c6097aa7f5e7970c3f16d4346041f9694d
5,459
cpp
C++
src_lib/csutil.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
src_lib/csutil.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
src_lib/csutil.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
#include <csutil.hpp> double s13::ana::lab2cm_solid_angle_factor(double proton_cm_theta_rad, DatasetType ds_type) { const double p_he4_gamma_cm = 1.12654467394258; const double p_he6_gamma_cm = 1.14966481938141; double gamma = p_he4_gamma_cm; if (ds_type == DatasetType::he6 || ds_type == DatasetType::carbon) { gamma = p_he6_gamma_cm; } else if (ds_type == DatasetType::he4) { gamma = p_he4_gamma_cm; } else { throw std::invalid_argument("Invalid dataset type!"); } double theta = proton_cm_theta_rad; double num = gamma * std::abs(std::cos(theta) - 1); double denom = std::pow(std::sin(theta), 2) + std::pow(gamma, 2) * std::pow(1 - std::cos(theta), 2); denom = std::pow(denom, 3./2); return num / denom; } s13::ana::ScatteringYield s13::ana::lab_yield_to_cm(const s13::ana::ScatteringYield& lab_yield, DatasetType ds_type) { misc::MessageLogger log_("lab_yield_to_cm()"); TInterpPtr angle_interp = make_lab2cm_angle_interp(ds_type); const double lab_theta_min = (lab_yield.GetBinArg(0) - lab_yield.GetBinWidth() / 2); const double lab_theta_max = (lab_yield.GetBinArg(lab_yield.GetBinsNumber() - 1) + lab_yield.GetBinWidth() / 2); // const double cm_theta_max = lab_theta_angle_to_cm(lab_theta_min); // const double cm_theta_min = lab_theta_angle_to_cm(lab_theta_max); const double cm_theta_max = angle_interp->Eval(lab_theta_min); const double cm_theta_min = angle_interp->Eval(lab_theta_max); log_.debug("CM angular range: [%.1f; %.1f]", cm_theta_min, cm_theta_max); ScatteringYield cm_yield(lab_yield.GetBinsNumber(), cm_theta_min, cm_theta_max); log_.debug("Converting yield..."); for (int i = cm_yield.GetBinsNumber() - 1; i >= 0; --i) { // Double_t cm_angle = lab_theta_angle_to_cm(lab_yield.GetBinArg(i)); Double_t cm_angle = angle_interp->Eval(lab_yield.GetBinArg(i)); cm_yield.SetBinValue(cm_angle, lab_yield.GetBinValue(i)); cm_yield.SetBinError(cm_angle, lab_yield.GetBinError(i)); } return cm_yield; } s13::ana::TInterpPtr s13::ana::make_lab2cm_angle_interp(DatasetType ds_type) { std::string fname = ds_type == DatasetType::he4 ? "data/p_he4_recoil_A_lab_A_cm.csv" : "data/p_he6_recoil_A_lab_A_cm.csv"; auto csv_data = io::load_csv(fname, 2, 2); assert (csv_data.size() == 2 && "Invalid number of columns in input file."); std::vector<double> a_cm, a_lab; for (size_t i = 0; i < csv_data[0].size(); i++) { a_lab.push_back(csv_data[0][i]); a_cm.push_back(csv_data[1][i]); } TInterp* interp = new TInterp{static_cast<unsigned int>(a_lab.size()), ROOT::Math::Interpolation::kLINEAR}; interp->SetData(a_lab, a_cm); return TInterpPtr{interp}; } /* Converts CS from lab to center of mass frame. */ s13::ana::ScatteringYield s13::ana::lab_cs_to_cm(const s13::ana::ScatteringYield& lab_cs, DatasetType ds_type) { misc::MessageLogger log_("lab_cs_to_cm()"); TInterpPtr angle_interp = make_lab2cm_angle_interp(ds_type); const double lab_theta_min = (lab_cs.GetBinArg(0) - lab_cs.GetBinWidth() / 2); const double lab_theta_max = (lab_cs.GetBinArg(lab_cs.GetBinsNumber() - 1) + lab_cs.GetBinWidth() / 2); // const double cm_theta_max = lab_theta_angle_to_cm(lab_theta_min); // const double cm_theta_min = lab_theta_angle_to_cm(lab_theta_max); const double cm_theta_max = angle_interp->Eval(lab_theta_min); const double cm_theta_min = angle_interp->Eval(lab_theta_max); log_.debug("CM angular range: [%.1f; %.1f]", cm_theta_min, cm_theta_max); ScatteringYield cm_cs(lab_cs.GetBinsNumber(), cm_theta_min, cm_theta_max); log_.debug("Converting cross-section..."); for (int i = cm_cs.GetBinsNumber() - 1; i >= 0; --i) { int cm_cs_idx = cm_cs.GetBinsNumber() - 1 - i; // Double_t cm_angle = lab_theta_angle_to_cm(lab_cs.GetBinArg(i)); Double_t cm_angle = angle_interp->Eval(lab_cs.GetBinArg(i)); log_.debug("\t Computing CM MS for angle: %.3f; angle in scattering " "yield object: %.3f", cm_angle, cm_cs.GetBinArg(cm_cs_idx)); Double_t solid_angle_factor_nonrel = 1 / (4 * TMath::Sin((cm_angle * gk_d2r) / 2)); Double_t solid_angle_factor = lab2cm_solid_angle_factor(cm_angle * s13::gk_d2r, ds_type); log_.debug("SA factors (rel; non-rel): %.4f, %.4f", solid_angle_factor, solid_angle_factor_nonrel); Double_t cm_cs_value = lab_cs.GetBinValue(i) * solid_angle_factor; log_.debug("\t CS value in lab frame: %.3f; in CM frame: %.3f", lab_cs.GetBinValue(i), cm_cs_value); cm_cs.SetBinValue(cm_angle, cm_cs_value); cm_cs.SetBinError(cm_angle, lab_cs.GetBinError(i) * solid_angle_factor); } return cm_cs; } s13::ana::ScatteringYield s13::ana::cs_from_yields(s13::ana::ScatteringYield& yields, s13::ana::SolidAngle& solid_angle, double num_beam_incident, double tgt_areal_density) { ScatteringYield cs = yields; for (int i = 0; i < yields.GetBinsNumber(); i++) { double theta = yields.GetBinArg(i); double sa = solid_angle.at(theta); Double_t norm_factor = 1 / (num_beam_incident * tgt_areal_density * sa); // from cm2 to barns norm_factor *= 1e24; // now into millibarns norm_factor *= 1e3; cs.ScaleBin(i, norm_factor); } return cs; }
38.174825
82
0.680528
serjinio
eebe79c6c6f524e7f66284e31053c5b8659a7fe1
8,998
cpp
C++
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
jpan127/RJD-MP3
8659a12e46021882cce6202befa59d88afe4d7c2
[ "MIT" ]
null
null
null
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
jpan127/RJD-MP3
8659a12e46021882cce6202befa59d88afe4d7c2
[ "MIT" ]
null
null
null
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
jpan127/RJD-MP3
8659a12e46021882cce6202befa59d88afe4d7c2
[ "MIT" ]
null
null
null
/* * SocialLedge.com - Copyright (C) 2013 * * This file is part of free software framework for embedded processors. * You can use it and/or distribute it as long as this copyright header * remains unmodified. The code is free for personal use and requires * permission to use in a commercial product. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * You can reach the author of this software at : * p r e e t . w i k i @ g m a i l . c o m */ #include <stdio.h> #include "lpc_sys.h" #include "wireless.h" #include "lpc_timers.h" #include "io.hpp" #include "FreeRTOS.h" #include "task.h" /// These bitmasks should match up with the timer MCR register to trigger interrupt upon match enum { mr0_mcr_for_overflow = (UINT32_C(1) << 0), mr1_mcr_for_mesh_bckgnd_task = (UINT32_C(1) << 3), mr2_mcr_for_ir_sensor_timeout = (UINT32_C(1) << 6), mr3_mcr_for_watchdog_reset = (UINT32_C(1) << 9), }; /// Periodic interrupt for mesh networking. This timer match interrupt is disabled if FreeRTOS starts to run. #define LPC_SYS_TIME_FOR_BCKGND_TASK_US (1 * 1000) /// Time in microseconds that will feed the watchdog, which should be roughly half of the actual watchdog reset #define LPC_SYS_WATCHDOG_RESET_TIME_US ((SYS_CFG_WATCHDOG_TIMEOUT_MS / 2) * 1000) /// Timer overflow interrupt will increment this upon the last UINT32 value, 16-bit is enough for many years! static volatile uint16_t g_timer_rollover_count = 0; /// Pointer to the timer struct based on SYS_CFG_SYS_TIMER LPC_TIM_TypeDef *gp_timer_ptr = NULL; extern "C" void lpc_sys_setup_system_timer(void) { // Note: Timer1 is required for IR sensor's decoding logic since its pin is tied to Timer1 Capture Pin const lpc_timer_t sys_timer_source = (lpc_timer_t) SYS_CFG_SYS_TIMER; // Get the IRQ number of the timer to enable the interrupt const IRQn_Type timer_irq = lpc_timer_get_irq_num(sys_timer_source); // Initialize the timer structure pointer gp_timer_ptr = lpc_timer_get_struct(sys_timer_source); // Setup the timer to tick with a fine-grain resolution const uint32_t one_micro_second = 1; lpc_timer_enable(sys_timer_source, one_micro_second); /** * MR0: Setup the match register to take care of the overflow. * Upon the roll-over, we increment the roll-over count and the timer restarts from zero. */ gp_timer_ptr->MR0 = UINT32_MAX; // MR1: Setup the periodic interrupt to do background processing gp_timer_ptr->MR1 = LPC_SYS_TIME_FOR_BCKGND_TASK_US; #if (1 == SYS_CFG_SYS_TIMER) // MR2: IR code timeout when timer1 is used since IR receiver is tied to timer1 capture pin gp_timer_ptr->MR2 = 0; #else #warning "IR receiver will not work unless SYS_CFG_SYS_TIMER uses TIMER1, so set it to 1 if possible" #endif /* Setup the first match interrupt to reset the watchdog */ gp_timer_ptr->MR3 = LPC_SYS_WATCHDOG_RESET_TIME_US; // Enable the timer match interrupts gp_timer_ptr->MCR = (mr0_mcr_for_overflow | mr1_mcr_for_mesh_bckgnd_task | mr3_mcr_for_watchdog_reset); // Only if we have got TIMER1, we can use IR sensor timeout match interrupt #if (1 == SYS_CFG_SYS_TIMER) gp_timer_ptr->MCR |= (mr2_mcr_for_ir_sensor_timeout); #endif /* Enable the interrupt and use higher priority than other peripherals because we want * to drive the periodic ISR above other interrupts since we reset the watchdog timer. */ NVIC_SetPriority(timer_irq, IP_high); vTraceSetISRProperties(timer_irq, "AUX Timer", IP_high); NVIC_EnableIRQ(timer_irq); } extern "C" uint64_t sys_get_uptime_us(void) { uint32_t before = 0; uint32_t after = 0; uint32_t rollovers = 0; /** * Loop until we can safely read both the rollover value and the timer value. * When the timer rolls over, the TC value will start from zero, and the "after" * value will be less than the before value in which case, we will loop again * and pick up the new rollover count. This avoid critical section and simplifies * the logic of reading higher 16-bit (roll-over) and lower 32-bit (timer value). */ do { before = gp_timer_ptr->TC; rollovers = g_timer_rollover_count; after = gp_timer_ptr->TC; } while (after < before); // each rollover is 2^32 or UINT32_MAX return (((uint64_t)rollovers << 32) | after); } /** * Actual ISR function (@see startup.cpp) */ #if (0 == SYS_CFG_SYS_TIMER) extern "C" void TIMER0_IRQHandler() #elif (1 == SYS_CFG_SYS_TIMER) extern "C" void TIMER1_IRQHandler() #elif (2 == SYS_CFG_SYS_TIMER) extern "C" void TIMER2_IRQHandler() #elif (3 == SYS_CFG_SYS_TIMER) extern "C" void TIMER3_IRQHandler() #else #error "SYS_CFG_SYS_TIMER must be between 0-3 inclusively" void TIMERX_BAD_IRQHandler() #endif { enum { timer_mr0_intr_timer_rollover = (1 << 0), timer_mr1_intr_mesh_servicing = (1 << 1), timer_mr2_intr_ir_sensor_timeout = (1 << 2), timer_mr3_intr_for_watchdog_rst = (1 << 3), timer_capt0_intr_ir_sensor_edge_time_captured = (1 << 4), timer_capt1_intr = (1 << 5), }; const uint32_t intr_reason = gp_timer_ptr->IR; #if (1 == SYS_CFG_SYS_TIMER) /* ISR for captured time of the capture input pin */ if (intr_reason & timer_capt0_intr_ir_sensor_edge_time_captured) { gp_timer_ptr->IR = timer_capt0_intr_ir_sensor_edge_time_captured; // Store the IR capture time and setup timeout of the IR signal (unless we reset it again) IS.storeIrCode(gp_timer_ptr->CR0); gp_timer_ptr->MR2 = 10000 + gp_timer_ptr->TC; } /* MR2: End of IR capture (no IR capture after initial IR signal) */ else if (intr_reason & timer_mr2_intr_ir_sensor_timeout) { gp_timer_ptr->IR = timer_mr2_intr_ir_sensor_timeout; IS.decodeIrCode(); } /* MR0 is used for the timer rollover count */ else #endif if(intr_reason & timer_mr0_intr_timer_rollover) { gp_timer_ptr->IR = timer_mr0_intr_timer_rollover; ++g_timer_rollover_count; } else if(intr_reason & timer_mr1_intr_mesh_servicing) { gp_timer_ptr->IR = timer_mr1_intr_mesh_servicing; /* FreeRTOS task is used to service the wireless_service() function, otherwise if FreeRTOS * is not running, timer ISR will call this function to carry out mesh networking logic. */ if (taskSCHEDULER_RUNNING != xTaskGetSchedulerState()) { wireless_service(); } else { /* Disable this timer interrupt if FreeRTOS starts to run */ gp_timer_ptr->MCR &= ~(mr1_mcr_for_mesh_bckgnd_task); } /* Setup the next periodic interrupt */ gp_timer_ptr->MR1 += gp_timer_ptr->TC + LPC_SYS_TIME_FOR_BCKGND_TASK_US; } else if (intr_reason & timer_mr3_intr_for_watchdog_rst) { gp_timer_ptr->IR = timer_mr3_intr_for_watchdog_rst; /* If no one feeds the watchdog, we will watchdog reset. We are using a periodic ISR * to feed watchdog because if a critical exception hits, it will enter while(1) loop inside * the interrupt, and since watchdog won't reset, it will trigger system reset. */ sys_watchdog_feed(); /* Setup the next watchdog reset timer */ gp_timer_ptr->MR3 = gp_timer_ptr->TC + LPC_SYS_WATCHDOG_RESET_TIME_US; } else { // Unexpected interrupt, so stay here to trigger watchdog interrupt puts("Unexpected ISR call at lpc_sys.c"); while (1) { ; } } } extern "C" void sys_get_mem_info_str(char buffer[280]) { sys_mem_t info = sys_get_mem_info(); sprintf(buffer, "Memory Information:\n" "Global Used : %5d\n" "malloc Used : %5d\n" "malloc Avail. : %5d\n" "System Avail. : %5d\n" "Next Heap ptr : 0x%08X\n" "Last sbrk() ptr : 0x%08X\n" "Last sbrk() size : %u\n" "Num sbrk() calls: %u\n", (int)info.used_global, (int)info.used_heap, (int)info.avail_heap, (int)info.avail_sys, (unsigned int)info.next_malloc_ptr, (unsigned int)info.last_sbrk_ptr, (unsigned int)info.last_sbrk_size, (unsigned int)info.num_sbrk_calls); }
37.491667
112
0.660369
jpan127
eec0066e8515af438eb866eed0d8668214158c7c
4,428
cpp
C++
sp/src/game/server/ai_condition.cpp
joshmartel/source-sdk-2013
524e87f708d6c30360613b1f65ee174deafa20f4
[ "Unlicense" ]
2,268
2015-01-01T19:31:56.000Z
2022-03-31T20:15:31.000Z
sp/src/game/server/ai_condition.cpp
joshmartel/source-sdk-2013
524e87f708d6c30360613b1f65ee174deafa20f4
[ "Unlicense" ]
241
2015-01-01T15:26:14.000Z
2022-03-31T22:09:59.000Z
sp/src/game/server/ai_condition.cpp
joshmartel/source-sdk-2013
524e87f708d6c30360613b1f65ee174deafa20f4
[ "Unlicense" ]
2,174
2015-01-01T08:18:05.000Z
2022-03-31T10:43:59.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "stringregistry.h" #include "ai_basenpc.h" #include "ai_condition.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Given and condition name, return the condition ID //----------------------------------------------------------------------------- int CAI_BaseNPC::GetConditionID(const char* condName) { return GetSchedulingSymbols()->ConditionSymbolToId(condName); } //----------------------------------------------------------------------------- // Purpose: Register the default conditions // Input : // Output : //----------------------------------------------------------------------------- #define ADD_CONDITION_TO_SR( _n ) idSpace.AddCondition( #_n, _n, "CAI_BaseNPC" ) void CAI_BaseNPC::InitDefaultConditionSR(void) { CAI_ClassScheduleIdSpace &idSpace = CAI_BaseNPC::AccessClassScheduleIdSpaceDirect(); ADD_CONDITION_TO_SR( COND_NONE ); ADD_CONDITION_TO_SR( COND_IN_PVS ); ADD_CONDITION_TO_SR( COND_IDLE_INTERRUPT ); ADD_CONDITION_TO_SR( COND_LOW_PRIMARY_AMMO ); ADD_CONDITION_TO_SR( COND_NO_PRIMARY_AMMO ); ADD_CONDITION_TO_SR( COND_NO_SECONDARY_AMMO ); ADD_CONDITION_TO_SR( COND_NO_WEAPON ); ADD_CONDITION_TO_SR( COND_SEE_HATE ); ADD_CONDITION_TO_SR( COND_SEE_FEAR ); ADD_CONDITION_TO_SR( COND_SEE_DISLIKE ); ADD_CONDITION_TO_SR( COND_SEE_ENEMY ); ADD_CONDITION_TO_SR( COND_LOST_ENEMY ); ADD_CONDITION_TO_SR( COND_ENEMY_WENT_NULL ); ADD_CONDITION_TO_SR( COND_HAVE_ENEMY_LOS ); ADD_CONDITION_TO_SR( COND_HAVE_TARGET_LOS ); ADD_CONDITION_TO_SR( COND_ENEMY_OCCLUDED ); ADD_CONDITION_TO_SR( COND_TARGET_OCCLUDED ); ADD_CONDITION_TO_SR( COND_ENEMY_TOO_FAR ); ADD_CONDITION_TO_SR( COND_LIGHT_DAMAGE ); ADD_CONDITION_TO_SR( COND_HEAVY_DAMAGE ); ADD_CONDITION_TO_SR( COND_PHYSICS_DAMAGE ); ADD_CONDITION_TO_SR( COND_REPEATED_DAMAGE ); ADD_CONDITION_TO_SR( COND_CAN_RANGE_ATTACK1 ); ADD_CONDITION_TO_SR( COND_CAN_RANGE_ATTACK2 ); ADD_CONDITION_TO_SR( COND_CAN_MELEE_ATTACK1 ); ADD_CONDITION_TO_SR( COND_CAN_MELEE_ATTACK2 ); ADD_CONDITION_TO_SR( COND_PROVOKED ); ADD_CONDITION_TO_SR( COND_NEW_ENEMY ); ADD_CONDITION_TO_SR( COND_ENEMY_FACING_ME ); ADD_CONDITION_TO_SR( COND_BEHIND_ENEMY ); ADD_CONDITION_TO_SR( COND_ENEMY_DEAD ); ADD_CONDITION_TO_SR( COND_ENEMY_UNREACHABLE ); ADD_CONDITION_TO_SR( COND_SEE_PLAYER ); ADD_CONDITION_TO_SR( COND_LOST_PLAYER ); ADD_CONDITION_TO_SR( COND_SEE_NEMESIS ); ADD_CONDITION_TO_SR( COND_TASK_FAILED ); ADD_CONDITION_TO_SR( COND_SCHEDULE_DONE ); ADD_CONDITION_TO_SR( COND_SMELL ); ADD_CONDITION_TO_SR( COND_TOO_CLOSE_TO_ATTACK ); ADD_CONDITION_TO_SR( COND_TOO_FAR_TO_ATTACK ); ADD_CONDITION_TO_SR( COND_NOT_FACING_ATTACK ); ADD_CONDITION_TO_SR( COND_WEAPON_HAS_LOS ); ADD_CONDITION_TO_SR( COND_WEAPON_BLOCKED_BY_FRIEND ); // Friend between gun and target ADD_CONDITION_TO_SR( COND_WEAPON_PLAYER_IN_SPREAD ); // Player in shooting direction ADD_CONDITION_TO_SR( COND_WEAPON_PLAYER_NEAR_TARGET ); // Player near shooting position ADD_CONDITION_TO_SR( COND_WEAPON_SIGHT_OCCLUDED ); ADD_CONDITION_TO_SR( COND_BETTER_WEAPON_AVAILABLE ); ADD_CONDITION_TO_SR( COND_HEALTH_ITEM_AVAILABLE ); ADD_CONDITION_TO_SR( COND_FLOATING_OFF_GROUND ); ADD_CONDITION_TO_SR( COND_MOBBED_BY_ENEMIES ); ADD_CONDITION_TO_SR( COND_GIVE_WAY ); ADD_CONDITION_TO_SR( COND_WAY_CLEAR ); ADD_CONDITION_TO_SR( COND_HEAR_DANGER ); ADD_CONDITION_TO_SR( COND_HEAR_THUMPER ); ADD_CONDITION_TO_SR( COND_HEAR_COMBAT ); ADD_CONDITION_TO_SR( COND_HEAR_WORLD ); ADD_CONDITION_TO_SR( COND_HEAR_PLAYER ); ADD_CONDITION_TO_SR( COND_HEAR_BULLET_IMPACT ); ADD_CONDITION_TO_SR( COND_HEAR_BUGBAIT ); ADD_CONDITION_TO_SR( COND_HEAR_PHYSICS_DANGER ); ADD_CONDITION_TO_SR( COND_HEAR_MOVE_AWAY ); ADD_CONDITION_TO_SR( COND_NO_HEAR_DANGER ); ADD_CONDITION_TO_SR( COND_PLAYER_PUSHING ); ADD_CONDITION_TO_SR( COND_RECEIVED_ORDERS ); ADD_CONDITION_TO_SR( COND_PLAYER_ADDED_TO_SQUAD ); ADD_CONDITION_TO_SR( COND_PLAYER_REMOVED_FROM_SQUAD ); ADD_CONDITION_TO_SR( COND_NPC_FREEZE ); ADD_CONDITION_TO_SR( COND_NPC_UNFREEZE ); ADD_CONDITION_TO_SR( COND_TALKER_RESPOND_TO_QUESTION ); ADD_CONDITION_TO_SR( COND_NO_CUSTOM_INTERRUPTS ); }
41.773585
89
0.746838
joshmartel
eec0dbdd299e7bcb80be5939c1bfe15d0e5b89db
323
cpp
C++
examples/example_bindings.cpp
avilchess/carma
32857b2ab70a0338d15c81fdaf30945ba238a32e
[ "Apache-2.0" ]
null
null
null
examples/example_bindings.cpp
avilchess/carma
32857b2ab70a0338d15c81fdaf30945ba238a32e
[ "Apache-2.0" ]
null
null
null
examples/example_bindings.cpp
avilchess/carma
32857b2ab70a0338d15c81fdaf30945ba238a32e
[ "Apache-2.0" ]
null
null
null
#include <pybind11/pybind11.h> // include numpy header for usage of array_t #include <pybind11/numpy.h> namespace py = pybind11; #include "manual_conversion.h" #include "automatic_conversion.h" PYBIND11_MODULE(carma_examples, m) { bind_manual_example(m); bind_update_example(m); bind_automatic_example(m); }
21.533333
44
0.758514
avilchess
eec2798f36b1875b318b67e27356e2438fc7d94c
2,317
cpp
C++
src/game_components/Input.cpp
sgol13/boulder-dash
140b7eac3c9f820e84abda07164d057c22540db9
[ "MIT" ]
5
2021-11-28T10:13:12.000Z
2021-12-12T14:51:36.000Z
src/game_components/Input.cpp
sgol13/boulder-dash
140b7eac3c9f820e84abda07164d057c22540db9
[ "MIT" ]
null
null
null
src/game_components/Input.cpp
sgol13/boulder-dash
140b7eac3c9f820e84abda07164d057c22540db9
[ "MIT" ]
null
null
null
// Szymon Golebiowski // Boulder Dash #include "boulder-dash/game_components/Input.hpp" bd::Input::Input(sf::RenderWindow &_window) : Engine(_window) {} void bd::Input::processInputOperations() { handleEvents(); if (!pause_game_) { handleControl(); } } void bd::Input::handleEvents() { sf::Event event; while (window_.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: // exit the game end_game_ = true; window_.close(); break; case sf::Event::KeyPressed: if (window_.hasFocus()) { handleKeyPressed(event.key); } break; default: break; } } } void bd::Input::handleKeyPressed(const sf::Event::KeyEvent &key) { switch (key.code) { case sf::Keyboard::C: // exit the game using C exit_game_ = true; window_.close(); break; case sf::Keyboard::Return: // exit the game - enter exit_game_ = true; break; case sf::Keyboard::Space: // pause the game - space if (!end_game_) { pause_game_ = !pause_game_; } break; default: break; } } void bd::Input::handleControl() { MapCoordinates arrow_keys = {0, 0}; // read the current states of the arrow keys if (window_.hasFocus() && !end_game_) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { arrow_keys += DIR_UP; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { arrow_keys += DIR_RIGHT; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { arrow_keys += DIR_DOWN; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { arrow_keys += DIR_LEFT; } } // set the player's planned move on the basis of the arrow keys' states if (abs(arrow_keys.r) + abs(arrow_keys.c) <= 1) { player_->setPlannedMove(arrow_keys); } if (player_->getMovePhase() == Moveable::MovePhase::MOVING) { if ((arrow_keys.r != 0 && player_->getCurrentMove().r == -arrow_keys.r) || (arrow_keys.c != 0 && player_->getCurrentMove().c == -arrow_keys.c)) { player_->reverseMove(); } } }
22.495146
82
0.547259
sgol13
eec54846508065fb7c8e441810362307fc52fdb9
60
hpp
C++
src/boost_geometry_multi_algorithms_intersection.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_multi_algorithms_intersection.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_multi_algorithms_intersection.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/multi/algorithms/intersection.hpp>
30
59
0.833333
miathedev
eec6a147cbfd28457442e9ac797b316555806a55
10,853
cpp
C++
src/lib/pubkey/pk_algs.cpp
clayne/botan
1f16adea08c4c9bf3fb0fbf699d284cb48150898
[ "BSD-2-Clause" ]
2
2021-12-24T03:02:36.000Z
2021-12-24T03:02:59.000Z
src/lib/pubkey/pk_algs.cpp
clayne/botan
1f16adea08c4c9bf3fb0fbf699d284cb48150898
[ "BSD-2-Clause" ]
2
2021-12-22T15:41:22.000Z
2021-12-22T15:42:20.000Z
src/lib/pubkey/pk_algs.cpp
clayne/botan
1f16adea08c4c9bf3fb0fbf699d284cb48150898
[ "BSD-2-Clause" ]
null
null
null
/* * PK Key * (C) 1999-2010,2016 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/pk_algs.h> #include <botan/internal/parsing.h> #if defined(BOTAN_HAS_RSA) #include <botan/rsa.h> #endif #if defined(BOTAN_HAS_DSA) #include <botan/dsa.h> #endif #if defined(BOTAN_HAS_DL_GROUP) #include <botan/dl_group.h> #endif #if defined(BOTAN_HAS_DIFFIE_HELLMAN) #include <botan/dh.h> #endif #if defined(BOTAN_HAS_ECC_PUBLIC_KEY_CRYPTO) #include <botan/ecc_key.h> #endif #if defined(BOTAN_HAS_ECDSA) #include <botan/ecdsa.h> #endif #if defined(BOTAN_HAS_ECGDSA) #include <botan/ecgdsa.h> #endif #if defined(BOTAN_HAS_ECKCDSA) #include <botan/eckcdsa.h> #endif #if defined(BOTAN_HAS_ED25519) #include <botan/ed25519.h> #endif #if defined(BOTAN_HAS_GOST_34_10_2001) #include <botan/gost_3410.h> #endif #if defined(BOTAN_HAS_ELGAMAL) #include <botan/elgamal.h> #endif #if defined(BOTAN_HAS_ECDH) #include <botan/ecdh.h> #endif #if defined(BOTAN_HAS_CURVE_25519) #include <botan/curve25519.h> #endif #if defined(BOTAN_HAS_MCELIECE) #include <botan/mceliece.h> #endif #if defined(BOTAN_HAS_XMSS_RFC8391) #include <botan/xmss.h> #endif #if defined(BOTAN_HAS_SM2) #include <botan/sm2.h> #endif namespace Botan { std::unique_ptr<Public_Key> load_public_key(const AlgorithmIdentifier& alg_id, const std::vector<uint8_t>& key_bits) { const std::string oid_str = alg_id.get_oid().to_formatted_string(); const std::vector<std::string> alg_info = split_on(oid_str, '/'); const std::string alg_name = alg_info[0]; #if defined(BOTAN_HAS_RSA) if(alg_name == "RSA") return std::make_unique<RSA_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_CURVE_25519) if(alg_name == "Curve25519") return std::make_unique<Curve25519_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_MCELIECE) if(alg_name == "McEliece") return std::make_unique<McEliece_PublicKey>(key_bits); #endif #if defined(BOTAN_HAS_ECDSA) if(alg_name == "ECDSA") return std::make_unique<ECDSA_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECDH) if(alg_name == "ECDH") return std::make_unique<ECDH_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_DIFFIE_HELLMAN) if(alg_name == "DH") return std::make_unique<DH_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_DSA) if(alg_name == "DSA") return std::make_unique<DSA_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ELGAMAL) if(alg_name == "ElGamal") return std::make_unique<ElGamal_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECGDSA) if(alg_name == "ECGDSA") return std::make_unique<ECGDSA_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECKCDSA) if(alg_name == "ECKCDSA") return std::make_unique<ECKCDSA_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ED25519) if(alg_name == "Ed25519") return std::make_unique<Ed25519_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_GOST_34_10_2001) if(alg_name == "GOST-34.10" || alg_name == "GOST-34.10-2012-256" || alg_name == "GOST-34.10-2012-512") return std::make_unique<GOST_3410_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_SM2) if(alg_name == "SM2" || alg_name == "SM2_Sig" || alg_name == "SM2_Enc") return std::make_unique<SM2_PublicKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_XMSS_RFC8391) if(alg_name == "XMSS") return std::make_unique<XMSS_PublicKey>(key_bits); #endif throw Decoding_Error("Unknown or unavailable public key algorithm " + alg_name); } std::unique_ptr<Private_Key> load_private_key(const AlgorithmIdentifier& alg_id, const secure_vector<uint8_t>& key_bits) { const std::string alg_name = alg_id.get_oid().to_formatted_string(); #if defined(BOTAN_HAS_RSA) if(alg_name == "RSA") return std::make_unique<RSA_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_CURVE_25519) if(alg_name == "Curve25519") return std::make_unique<Curve25519_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECDSA) if(alg_name == "ECDSA") return std::make_unique<ECDSA_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECDH) if(alg_name == "ECDH") return std::make_unique<ECDH_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_DIFFIE_HELLMAN) if(alg_name == "DH") return std::make_unique<DH_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_DSA) if(alg_name == "DSA") return std::make_unique<DSA_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_MCELIECE) if(alg_name == "McEliece") return std::make_unique<McEliece_PrivateKey>(key_bits); #endif #if defined(BOTAN_HAS_ECGDSA) if(alg_name == "ECGDSA") return std::make_unique<ECGDSA_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ECKCDSA) if(alg_name == "ECKCDSA") return std::make_unique<ECKCDSA_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ED25519) if(alg_name == "Ed25519") return std::make_unique<Ed25519_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_GOST_34_10_2001) if(alg_name == "GOST-34.10" || alg_name == "GOST-34.10-2012-256" || alg_name == "GOST-34.10-2012-512") return std::make_unique<GOST_3410_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_SM2) if(alg_name == "SM2" || alg_name == "SM2_Sig" || alg_name == "SM2_Enc") return std::make_unique<SM2_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_ELGAMAL) if(alg_name == "ElGamal") return std::make_unique<ElGamal_PrivateKey>(alg_id, key_bits); #endif #if defined(BOTAN_HAS_XMSS_RFC8391) if(alg_name == "XMSS") return std::make_unique<XMSS_PrivateKey>(key_bits); #endif throw Decoding_Error("Unknown or unavailable public key algorithm " + alg_name); } #if defined(BOTAN_HAS_ECC_GROUP) namespace { std::string default_ec_group_for(const std::string& alg_name) { if(alg_name == "SM2" || alg_name == "SM2_Enc" || alg_name == "SM2_Sig") return "sm2p256v1"; if(alg_name == "GOST-34.10" || alg_name == "GOST-34.10-2012-256") return "gost_256A"; if(alg_name == "GOST-34.10-2012-512") return "gost_512A"; if(alg_name == "ECGDSA") return "brainpool256r1"; return "secp256r1"; } } #endif BOTAN_PUBLIC_API(3,0) std::unique_ptr<Private_Key> create_ec_private_key(const std::string& alg_name, const EC_Group& ec_group, RandomNumberGenerator& rng) { #if defined(BOTAN_HAS_ECDSA) if(alg_name == "ECDSA") return std::make_unique<ECDSA_PrivateKey>(rng, ec_group); #endif #if defined(BOTAN_HAS_ECDH) if(alg_name == "ECDH") return std::make_unique<ECDH_PrivateKey>(rng, ec_group); #endif #if defined(BOTAN_HAS_ECKCDSA) if(alg_name == "ECKCDSA") return std::make_unique<ECKCDSA_PrivateKey>(rng, ec_group); #endif #if defined(BOTAN_HAS_GOST_34_10_2001) if(alg_name == "GOST-34.10" || alg_name == "GOST-34.10-2012-256" || alg_name == "GOST-34.10-2012-512") return std::make_unique<GOST_3410_PrivateKey>(rng, ec_group); #endif #if defined(BOTAN_HAS_SM2) if(alg_name == "SM2" || alg_name == "SM2_Sig" || alg_name == "SM2_Enc") return std::make_unique<SM2_PrivateKey>(rng, ec_group); #endif #if defined(BOTAN_HAS_ECGDSA) if(alg_name == "ECGDSA") return std::make_unique<ECGDSA_PrivateKey>(rng, ec_group); #endif return nullptr; } std::unique_ptr<Private_Key> create_private_key(const std::string& alg_name, RandomNumberGenerator& rng, const std::string& params, const std::string& provider) { /* * Default paramaters are chosen for work factor > 2**128 where possible */ #if defined(BOTAN_HAS_CURVE_25519) if(alg_name == "Curve25519") return std::make_unique<Curve25519_PrivateKey>(rng); #endif #if defined(BOTAN_HAS_RSA) if(alg_name == "RSA") { const size_t rsa_bits = (params.empty() ? 3072 : to_u32bit(params)); return std::make_unique<RSA_PrivateKey>(rng, rsa_bits); } #endif #if defined(BOTAN_HAS_MCELIECE) if(alg_name == "McEliece") { std::vector<std::string> mce_param = Botan::split_on(params.empty() ? "2960,57" : params, ','); if(mce_param.size() != 2) throw Invalid_Argument("create_private_key bad McEliece parameters " + params); size_t mce_n = Botan::to_u32bit(mce_param[0]); size_t mce_t = Botan::to_u32bit(mce_param[1]); return std::make_unique<Botan::McEliece_PrivateKey>(rng, mce_n, mce_t); } #endif #if defined(BOTAN_HAS_XMSS_RFC8391) if(alg_name == "XMSS") { return std::make_unique<XMSS_PrivateKey>(XMSS_Parameters(params.empty() ? "XMSS-SHA2_10_512" : params).oid(), rng); } #endif #if defined(BOTAN_HAS_ED25519) if(alg_name == "Ed25519") { return std::make_unique<Ed25519_PrivateKey>(rng); } #endif // ECC crypto #if defined(BOTAN_HAS_ECC_PUBLIC_KEY_CRYPTO) if(alg_name == "ECDSA" || alg_name == "ECDH" || alg_name == "ECKCDSA" || alg_name == "ECGDSA" || alg_name == "SM2" || alg_name == "SM2_Sig" || alg_name == "SM2_Enc" || alg_name == "GOST-34.10" || alg_name == "GOST-34.10-2012-256" || alg_name == "GOST-34.10-2012-512") { const EC_Group ec_group(params.empty() ? default_ec_group_for(alg_name) : params); return create_ec_private_key(alg_name, ec_group, rng); } #endif // DL crypto #if defined(BOTAN_HAS_DL_GROUP) if(alg_name == "DH" || alg_name == "DSA" || alg_name == "ElGamal") { std::string default_group = (alg_name == "DSA") ? "dsa/botan/2048" : "modp/ietf/2048"; DL_Group modp_group(params.empty() ? default_group : params); #if defined(BOTAN_HAS_DIFFIE_HELLMAN) if(alg_name == "DH") return std::make_unique<DH_PrivateKey>(rng, modp_group); #endif #if defined(BOTAN_HAS_DSA) if(alg_name == "DSA") return std::make_unique<DSA_PrivateKey>(rng, modp_group); #endif #if defined(BOTAN_HAS_ELGAMAL) if(alg_name == "ElGamal") return std::make_unique<ElGamal_PrivateKey>(rng, modp_group); #endif } #endif BOTAN_UNUSED(alg_name, rng, params, provider); return std::unique_ptr<Private_Key>(); } std::vector<std::string> probe_provider_private_key(const std::string& alg_name, const std::vector<std::string> possible) { std::vector<std::string> providers; for(auto&& prov : possible) { if(prov == "base") providers.push_back(prov); } BOTAN_UNUSED(alg_name); return providers; } }
26.088942
121
0.685433
clayne
eec6a2f21e18b45dcda30a71b4f26f955712f661
2,591
cc
C++
test/core/gprpp/examine_stack_test.cc
thiagoss/grpc
3eb743ba4c9e38941aeac3a54420628b46335d20
[ "Apache-2.0" ]
3
2020-11-30T15:35:37.000Z
2022-01-06T14:17:18.000Z
test/core/gprpp/examine_stack_test.cc
thiagoss/grpc
3eb743ba4c9e38941aeac3a54420628b46335d20
[ "Apache-2.0" ]
54
2020-06-23T17:34:04.000Z
2022-03-31T02:04:06.000Z
test/core/gprpp/examine_stack_test.cc
thiagoss/grpc
3eb743ba4c9e38941aeac3a54420628b46335d20
[ "Apache-2.0" ]
12
2020-07-14T23:59:57.000Z
2022-03-22T09:59:18.000Z
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "src/core/lib/gprpp/examine_stack.h" #include <stdio.h> #include <string.h> #include <gtest/gtest.h> #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include <grpc/support/log.h> namespace { std::string SimpleCurrentStackTraceProvider() { return "stacktrace"; } std::string AbseilCurrentStackTraceProvider() { std::string result = "Stack trace:\n"; constexpr int kNumStackFrames = 10; void* stack[kNumStackFrames]; int frame_sizes[kNumStackFrames]; int depth = absl::GetStackFrames(stack, frame_sizes, kNumStackFrames, 1); for (int i = 0; i < depth; i++) { char tmp[1024]; const char* symbol = "(unknown)"; if (absl::Symbolize(stack[i], tmp, sizeof(tmp))) { symbol = tmp; } result += symbol; result += +"\n"; } return result; } } // namespace TEST(ExamineStackTest, NullStackProvider) { grpc_core::SetCurrentStackTraceProvider(nullptr); EXPECT_EQ(grpc_core::GetCurrentStackTraceProvider(), nullptr); EXPECT_EQ(grpc_core::GetCurrentStackTrace(), absl::nullopt); } TEST(ExamineStackTest, SimpleStackProvider) { grpc_core::SetCurrentStackTraceProvider(&SimpleCurrentStackTraceProvider); EXPECT_NE(grpc_core::GetCurrentStackTraceProvider(), nullptr); EXPECT_EQ(grpc_core::GetCurrentStackTrace(), "stacktrace"); } TEST(ExamineStackTest, AbseilStackProvider) { grpc_core::SetCurrentStackTraceProvider(&AbseilCurrentStackTraceProvider); EXPECT_NE(grpc_core::GetCurrentStackTraceProvider(), nullptr); const absl::optional<std::string> stack_trace = grpc_core::GetCurrentStackTrace(); EXPECT_NE(stack_trace, absl::nullopt); gpr_log(GPR_INFO, "stack_trace=%s", stack_trace->c_str()); #if !defined(NDEBUG) && !defined(GPR_MUSL_LIBC_COMPAT) EXPECT_TRUE(stack_trace->find("GetCurrentStackTrace") != -1); #endif } int main(int argc, char** argv) { absl::InitializeSymbolizer(argv[0]); ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
30.482353
76
0.732536
thiagoss
eec6c98ef1163653d659d69f1693ed732156245e
1,307
cpp
C++
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
22
2019-06-13T01:16:44.000Z
2022-03-29T02:42:39.000Z
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
26
2019-09-20T06:46:05.000Z
2022-03-11T08:07:14.000Z
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
14
2019-07-15T06:42:39.000Z
2022-02-15T10:32:28.000Z
/* * StringQueueAppender.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "PortabilityImpl.hh" #include "log4cpp/StringQueueAppender.hh" namespace log4cpp { StringQueueAppender::StringQueueAppender(const std::string& name) : LayoutAppender(name) { } StringQueueAppender::~StringQueueAppender() { close(); } void StringQueueAppender::close() { // empty } void StringQueueAppender::_append(const LoggingEvent& event) { _queue.push(_getLayout().format(event)); } bool StringQueueAppender::reopen() { return true; } std::queue<std::string>& StringQueueAppender::getQueue() { return _queue; } const std::queue<std::string>& StringQueueAppender::getQueue() const { return _queue; } size_t StringQueueAppender::queueSize() const { return getQueue().size(); } std::string StringQueueAppender::popMessage() { std::string message; if (!_queue.empty()) { message = _queue.front(); _queue.pop(); } return message; } }
22.534483
79
0.61974
chewaiwai
eec7a96a383fe7a664060d714dd948be14295b33
8,033
cpp
C++
src/qt/qtbase/src/corelib/doc/snippets/code/doc_src_qiterator.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-01-21T01:48:04.000Z
2015-01-21T01:48:04.000Z
src/qt/qtbase/src/corelib/doc/snippets/code/doc_src_qiterator.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/corelib/doc/snippets/code/doc_src_qiterator.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] QList<float> list; ... QListIterator<float> i(list); while (i.hasNext()) qDebug() << i.next(); //! [0] //! [1] QListIterator<float> i(list); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [1] //! [2] QLinkedList<float> list; ... QLinkedListIterator<float> i(list); while (i.hasNext()) qDebug() << i.next(); //! [2] //! [3] QLinkedListIterator<float> i(list); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [3] //! [4] QVector<float> vector; ... QVectorIterator<float> i(vector); while (i.hasNext()) qDebug() << i.next(); //! [4] //! [5] QVectorIterator<float> i(vector); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [5] //! [6] QSet<QString> set; ... QSetIterator<QString> i(set); while (i.hasNext()) qDebug() << i.next(); //! [6] //! [7] QSetIterator<QString> i(set); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [7] //! [8] QList<float> list; ... QMutableListIterator<float> i(list); while (i.hasNext()) qDebug() << i.next(); //! [8] //! [9] QMutableListIterator<float> i(list); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [9] //! [10] QMutableListIterator<int> i(list); while (i.hasNext()) { int val = i.next(); if (val < 0) { i.setValue(-val); } else if (val == 0) { i.remove(); } } //! [10] //! [11] QLinkedList<float> list; ... QMutableLinkedListIterator<float> i(list); while (i.hasNext()) qDebug() << i.next(); //! [11] //! [12] QMutableLinkedListIterator<float> i(list); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [12] //! [13] QMutableLinkedListIterator<int> i(list); while (i.hasNext()) { int val = i.next(); if (val < 0) { i.setValue(-val); } else if (val == 0) { i.remove(); } } //! [13] //! [14] QVector<float> vector; ... QMutableVectorIterator<float> i(vector); while (i.hasNext()) qDebug() << i.next(); //! [14] //! [15] QMutableVectorIterator<float> i(vector); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [15] //! [16] QMutableVectorIterator<int> i(vector); while (i.hasNext()) { int val = i.next(); if (val < 0) { i.setValue(-val); } else if (val == 0) { i.remove(); } } //! [16] //! [17] QSet<float> set; ... QMutableSetIterator<float> i(set); while (i.hasNext()) qDebug() << i.next(); //! [17] //! [18] QMutableSetIterator<float> i(set); i.toBack(); while (i.hasPrevious()) qDebug() << i.previous(); //! [18] //! [19] QMutableListIterator<int> i(list); while (i.hasNext()) { int val = i.next(); if (val < -32768 || val > 32767) i.remove(); } //! [19] //! [20] QMutableLinkedListIterator<int> i(list); while (i.hasNext()) { int val = i.next(); if (val < -32768 || val > 32767) i.remove(); } //! [20] //! [21] QMutableVectorIterator<int> i(vector); while (i.hasNext()) { int val = i.next(); if (val < -32768 || val > 32767) i.remove(); } //! [21] //! [22] QMutableSetIterator<int> i(set); while (i.hasNext()) { int val = i.next(); if (val < -32768 || val > 32767) i.remove(); } //! [22] //! [23] QMutableListIterator<double> i(list); while (i.hasNext()) { double val = i.next(); i.setValue(sqrt(val)); } //! [23] //! [24] QMutableLinkedListIterator<double> i(list); while (i.hasNext()) { double val = i.next(); i.setValue(sqrt(val)); } //! [24] //! [25] QMutableVectorIterator<double> i(list); while (i.hasNext()) { double val = i.next(); i.setValue(sqrt(val)); } //! [25] //! [26] QMap<int, QWidget *> map; ... QMapIterator<int, QWidget *> i(map); while (i.hasNext()) { i.next(); qDebug() << i.key() << ": " << i.value(); } //! [26] //! [27] QMapIterator<int, QWidget *> i(map); i.toBack(); while (i.hasPrevious()) { i.previous(); qDebug() << i.key() << ": " << i.value(); } //! [27] //! [28] QMapIterator<int, QWidget *> i(map); while (i.findNext(widget)) { qDebug() << "Found widget " << widget << " under key " << i.key(); } //! [28] //! [29] QHash<int, QWidget *> hash; ... QHashIterator<int, QWidget *> i(hash); while (i.hasNext()) { i.next(); qDebug() << i.key() << ": " << i.value(); } //! [29] //! [30] QHashIterator<int, QWidget *> i(hash); i.toBack(); while (i.hasPrevious()) { i.previous(); qDebug() << i.key() << ": " << i.value(); } //! [30] //! [31] QHashIterator<int, QWidget *> i(hash); while (i.findNext(widget)) { qDebug() << "Found widget " << widget << " under key " << i.key(); } //! [31] //! [32] QMap<int, QWidget *> map; ... QMutableMapIterator<int, QWidget *> i(map); while (i.hasNext()) { i.next(); qDebug() << i.key() << ": " << i.value(); } //! [32] //! [33] QMutableMapIterator<int, QWidget *> i(map); i.toBack(); while (i.hasPrevious()) { i.previous(); qDebug() << i.key() << ": " << i.value(); } //! [33] //! [34] QMutableMapIterator<int, QWidget *> i(map); while (i.findNext(widget)) { qDebug() << "Found widget " << widget << " under key " << i.key(); } //! [34] //! [35] QMutableMapIterator<QString, QString> i(map); while (i.hasNext()) { i.next(); if (i.key() == i.value()) i.remove(); } //! [35] //! [36] QHash<int, QWidget *> hash; ... QMutableHashIterator<QString, QWidget *> i(hash); while (i.hasNext()) { i.next(); qDebug() << i.key() << ": " << i.value(); } //! [36] //! [37] QMutableHashIterator<int, QWidget *> i(hash); i.toBack(); while (i.hasPrevious()) { i.previous(); qDebug() << i.key() << ": " << i.value(); } //! [37] //! [38] QMutableHashIterator<int, QWidget *> i(hash); while (i.findNext(widget)) { qDebug() << "Found widget " << widget << " under key " << i.key(); } //! [38] //! [39] QMutableHashIterator<QString, QString> i(hash); while (i.hasNext()) { i.next(); if (i.key() == i.value()) i.remove(); } //! [39]
19.08076
77
0.569775
viewdy
eecb0ad8d95d2e9dc558a674b6ca49095dba1708
3,522
cpp
C++
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Oct/03/2020 22:17 * solution_verdict: Wrong answer on test 5 language: GNU C++14 * run_time: 30 ms memory_used: 11900 KB * problem: https://codeforces.com/contest/521/problem/B ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; const int N=1e6; int a[N+2],b[N+2]; set<pair<int,int> >st;set<int>fr; map<pair<int,int>,int>mp; int up(int x,int y) { int cnt=0; cnt+=(st.find({x-1,y+1})!=st.end()); cnt+=(st.find({x,y+1})!=st.end()); cnt+=(st.find({x+1,y+1})!=st.end()); return cnt; } int dw(int x,int y) { int cnt=0; cnt+=(st.find({x-1,y-1})!=st.end()); cnt+=(st.find({x,y-1})!=st.end()); cnt+=(st.find({x+1,y-1})!=st.end()); return cnt; } void ck(int x,int y) { if(st.find({x,y})==st.end())return ; int id=mp[{x,y}]; if(up(x,y)==0) { fr.insert(id);//cout<<id<<endl; } } int tk[N+2]; const int mod=1e9+9; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=0;i<n;i++) { int x,y;cin>>x>>y;a[i]=x,b[i]=y; mp[{x,y}]=i;st.insert({x,y}); } for(int i=0;i<n;i++) { if(up(a[i],b[i])==0)fr.insert(i); } int lo=0,hi=n-1,tr=1;vector<int>ans; for(int i=1;i<=n;i++) { if(tr) { int dl=-1; while(true) { if(hi<lo)break; if(tk[hi]){hi--;continue;} if(*fr.rbegin()>=hi){dl=*fr.rbegin();break;} int c1=2,c2=2,c3=2; if(st.find({a[hi]-1,b[hi]+1})!=st.end())c1=dw(a[hi]-1,b[hi]+1); if(st.find({a[hi],b[hi]+1})!=st.end())c2=dw(a[hi],b[hi]+1); if(st.find({a[hi]+1,b[hi]+1})!=st.end())c3=dw(a[hi]+1,b[hi]+1); if(c1>=2&&c2>=2&&c3>=2){dl=hi;break;} else hi--; } //cout<<"*"<<fr.size()<<endl; if(dl==-1)dl=*fr.rbegin(); //cout<<"*"<<dl<<endl; ans.push_back(dl);st.erase({a[dl],b[dl]}); tk[dl]=1;if(fr.find(dl)!=fr.end())fr.erase(dl); ck(a[dl]-1,b[dl]-1);ck(a[dl],b[dl]-1);ck(a[dl]+1,b[dl]-1); } else { int dl=-1; while(true) { if(hi<lo)break; if(tk[lo]){lo++;continue;} if(*fr.begin()<=lo){dl=*fr.begin();break;} int c1=2,c2=2,c3=2; if(st.find({a[lo]-1,b[lo]+1})!=st.end())c1=dw(a[lo]-1,b[lo]+1); if(st.find({a[lo],b[lo]+1})!=st.end())c2=dw(a[lo],b[lo]+1); if(st.find({a[lo]+1,b[lo]+1})!=st.end())c3=dw(a[lo]+1,b[lo]+1); if(c1>=2&&c2>=2&&c3>=2){dl=lo;break;} else lo++; } if(dl==-1)dl=*fr.begin(); //cout<<"*"<<fr.size()<<endl; //cout<<"*"<<dl<<endl; ans.push_back(dl);st.erase({a[dl],b[dl]}); tk[dl]=1;if(fr.find(dl)!=fr.end())fr.erase(dl); ck(a[dl]-1,b[dl]-1);ck(a[dl],b[dl]-1);ck(a[dl]+1,b[dl]-1); } tr^=1; } int ad=0,p=1; for(int i=n-1;i>=0;i--) { ad=(ad+1LL*ans[i]*p)%mod; p=(1LL*p*n)%mod; } cout<<ad<<endl; return 0; }
27.515625
111
0.463941
kzvd4729
eed2e403c7eea1cdb1eb76858afbe48226891011
1,534
cpp
C++
HackerRank Problems/Balanced Brackets/soultion.cpp
Kankona-C/Coding-Questions
6416fb79ba5c499c97581258b287ccfab854af7a
[ "MIT" ]
14
2020-10-06T07:52:25.000Z
2021-01-22T15:01:03.000Z
HackerRank Problems/Balanced Brackets/soultion.cpp
Kankona-C/Coding-Questions
6416fb79ba5c499c97581258b287ccfab854af7a
[ "MIT" ]
18
2020-10-06T10:24:55.000Z
2020-10-30T20:10:58.000Z
HackerRank Problems/Balanced Brackets/soultion.cpp
Kankona-C/Coding-Questions
6416fb79ba5c499c97581258b287ccfab854af7a
[ "MIT" ]
40
2020-10-06T09:54:10.000Z
2021-02-20T19:20:09.000Z
// in this function i am checking if the brackets are balanced or not..if they are opeiing bracket i am pushing them in stack else if they are closing bracket i am poping top most element . at last if stack is empty print yes else no #include <bits/stdc++.h> using namespace std; // isBalaced function to check // Complete the isBalanced function below. string isBalanced(string s) { stack<int>ss; //using stack // iterate over every element for (int i = 0; i < s.length(); i++) { //if it is opening bracket then push if (s[i] == '{' || s[i] == '(' || s[i] == '[' ) { ss.push(s[i]); } else { // if empty print no if (ss.empty()) return ("NO"); else { // if closing bracket pop if (s[i] == ')' && ss.top() == '(') ss.pop(); else if (s[i] == '}' && ss.top() == '{') ss.pop(); else if (s[i] == ']' && ss.top() == '[') ss.pop(); else return ("NO"); } } } // if empty print yes else no if (ss.empty()) return ("YES"); return ("NO"); } // main function to take input and print the output1 int main() { ofstream fout(getenv("OUTPUT_PATH")); int t; cin >> t; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int t_itr = 0; t_itr < t; t_itr++) { string s; getline(cin, s); string result = isBalanced(s); fout << result << "\n"; } fout.close(); return 0; }
25.566667
233
0.508475
Kankona-C
eed3e7a5854fe72b4ef643886a99daa320c2e727
560
cpp
C++
Online Judges/UVA/12650/1833886_AC_12ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Online Judges/UVA/12650/1833886_AC_12ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Online Judges/UVA/12650/1833886_AC_12ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ld double #define ll long long int #define scldd(x,y) scanf("%lf%lf",&x,&y) #define scld(x) scanf("%lf",&x) #define scll(x,y) scanf("%lld%lld",&x,&y) #define scl(x) scanf("%lld",&x) using namespace std; int main() { ll a,b,ar; while(scll(a,b)==2) { map<ll,ll>mk; for(ll i=1;i<=b;i++) { scl(ar); mk[ar]++; } ll flag=0; //sort(mk.begin(),mk.end()); for(ll i=1;i<=a;i++) { if(mk[i]==0) { flag=1; cout<<i<<" "; } } if(flag==0) cout<<"*"; puts(""); } return 0; }
15.135135
41
0.494643
moni-roy
eed5a0939b1523d408d7065ff83dc28ac8038ea4
1,132
hpp
C++
Source/Gui/MainWindow.hpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
4
2018-12-06T01:20:50.000Z
2019-08-04T10:19:23.000Z
Source/Gui/MainWindow.hpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
null
null
null
Source/Gui/MainWindow.hpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
null
null
null
/** * Copyright (C) 2015-2019 * Author Alvin Ahmadov <alvin.dev.ahmadov@gmail.com> * * This file is part of Dixter Project * License-Identifier: MIT License * See README.md for more information. */ #pragma once #include "WindowBase.hpp" namespace Dixter { namespace Gui { class Panel; class TranslatorPanel; class DictionaryPanel; class SettingsDialog; /** * Main window * */ class DixterWindow : public WindowBase { Q_OBJECT public: explicit DixterWindow(const QString& title, int width = -1, int height = -1, bool visible = true); virtual ~DixterWindow() dxDECL_NOEXCEPT dxDECL_OVERRIDE; void showAll(bool visible = true, bool showChildren = true); DictionaryPanel* getDictionary(); TranslatorPanel* getTranslator(); protected: void init() dxDECL_OVERRIDE; void connectEvents() dxDECL_OVERRIDE; void initDictionary(); void initTranslator(); private: Group <QWidget, WidgetID>* m_widgets; DictionaryPanel* m_dictionaryPanel = nullptr; TranslatorPanel* m_translatorPanel = nullptr; }; } }
18.557377
101
0.674028
alvinahmadov
eed6f642bef3262feb6223e8b7a37f06093b6549
6,612
cpp
C++
tests/BufferPipeTest.cpp
Manuvr/ManuvrOS
e3a812c9b609ad69670ff2f8050a07bd423ebc78
[ "Apache-2.0" ]
5
2015-03-26T22:58:58.000Z
2021-06-15T05:36:57.000Z
tests/BufferPipeTest.cpp
Manuvr/ManuvrOS
e3a812c9b609ad69670ff2f8050a07bd423ebc78
[ "Apache-2.0" ]
2
2016-09-26T09:25:58.000Z
2017-08-03T05:27:24.000Z
tests/BufferPipeTest.cpp
Manuvr/ManuvrOS
e3a812c9b609ad69670ff2f8050a07bd423ebc78
[ "Apache-2.0" ]
2
2016-04-29T07:43:32.000Z
2020-02-07T06:43:01.000Z
#include <cstdio> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <fstream> #include <iostream> #include <Platform/Platform.h> #include "DataStructures/BufferPipe.h" #include "Transports/BufferPipes/XportBridge/XportBridge.h" class DummyTransport : public BufferPipe { public: DummyTransport(const char*); DummyTransport(const char*, BufferPipe*); /* Override from BufferPipe. */ virtual int8_t toCounterparty(uint8_t* buf, unsigned int len, int8_t mm); virtual int8_t fromCounterparty(uint8_t* buf, unsigned int len, int8_t mm); void printDebug(StringBuilder*); void runTest(StringBuilder*); private: const char* _name; StringBuilder _accumulator; }; DummyTransport::DummyTransport(const char* nom) : BufferPipe() { _name = nom; } /** * Constructor. We are passed one BufferPipe. Presumably the instance that gave * rise to us. * Without both sides of the bridge, all transfers in either direction will * fail with MEM_MGMT_RESPONSIBLE_CALLER. */ DummyTransport::DummyTransport(const char* nom, BufferPipe* x) : BufferPipe() { _name = nom; setNear(x); } /******************************************************************************* * Functions specific to this class * *******************************************************************************/ /* * This should just accumulate. */ int8_t DummyTransport::toCounterparty(uint8_t* buf, unsigned int len, int8_t mm) { switch (mm) { case MEM_MGMT_RESPONSIBLE_CALLER: // NOTE: No break. This might be construed as a way of saying CREATOR. case MEM_MGMT_RESPONSIBLE_CREATOR: _accumulator.concat(buf, len); return MEM_MGMT_RESPONSIBLE_CREATOR; // Reject the buffer. case MEM_MGMT_RESPONSIBLE_BEARER: _accumulator.concat(buf, len); free(buf); return MEM_MGMT_RESPONSIBLE_BEARER; // Reject the buffer. default: /* This is more ambiguity than we are willing to bear... */ return MEM_MGMT_RESPONSIBLE_ERROR; } } /* * The other side of the bridge. */ int8_t DummyTransport::fromCounterparty(uint8_t* buf, unsigned int len, int8_t mm) { switch (mm) { case MEM_MGMT_RESPONSIBLE_CALLER: // NOTE: No break. This might be construed as a way of saying CREATOR. case MEM_MGMT_RESPONSIBLE_CREATOR: /* The system that allocated this buffer either... a) Did so with the intention that it never be free'd, or... b) Has a means of discovering when it is safe to free. */ if (haveFar()) { /* We are not the transport driver, and we do no transformation. */ return far()->fromCounterparty(buf, len, mm); } return MEM_MGMT_RESPONSIBLE_CALLER; // Reject the buffer. case MEM_MGMT_RESPONSIBLE_BEARER: /* We are now the bearer. That means that by returning non-failure, the caller will expect _us_ to manage this memory. */ if (haveFar()) { /* We are not the transport driver, and we do no transformation. */ return far()->fromCounterparty(buf, len, mm); } return MEM_MGMT_RESPONSIBLE_CALLER; // Reject the buffer. default: /* This is more ambiguity than we are willing to bear... */ return MEM_MGMT_RESPONSIBLE_ERROR; } } void DummyTransport::printDebug(StringBuilder* output) { output->concatf("\t-- %s ----------------------------------\n", _name); if (haveNear()) { output->concatf("\t _near \t[%p]\n", (unsigned long)near()); } if (haveFar()) { output->concatf("\t _far \t[%p]\n", (unsigned long)far()); } if (_accumulator.length() > 0) { output->concatf("\t _accumulator (%d bytes): ", _accumulator.length()); _accumulator.printDebug(output); } } void DummyTransport::runTest(StringBuilder* output) { printf("runTest() ---> fromCounterparty() ---> %s\n", BufferPipe::memMgmtString( this->toCounterparty(output->string(), output->length(), MEM_MGMT_RESPONSIBLE_CREATOR) ) ); } /* * Allocates two dummy objects and tries to move data between them. */ int test_BufferPipe_0(void) { printf("Beginning test_BufferPipe_0()....\n"); StringBuilder log; StringBuilder* tmp_str = new StringBuilder("data to move...\n"); DummyTransport _xport0("Xport0"); DummyTransport _xport1("Xport1", &_xport0); // NOTE: This will make the pair circular, and thus make the test crash from // a stack overflow. //_xport0.setNear(&_xport1); _xport1.runTest(tmp_str); log.concat("\n_xport0\n"); _xport0.printDebug(&log); log.concat("\n_xport1\n"); _xport1.printDebug(&log); log.concat("\n"); _xport0.runTest(tmp_str); log.concat("\n_xport0\n"); _xport0.printDebug(&log); log.concat("\n_xport1\n"); _xport1.printDebug(&log); printf("%s\n", log.string()); return 0; } /* * Allocates two dummy objects and tries to move data between them via an XportBridge. */ int test_BufferPipe_1(void) { printf("Beginning test_BufferPipe_1()....\n"); StringBuilder log; StringBuilder* tmp_str = new StringBuilder("data to move...\n"); DummyTransport _xport2("Xport2"); DummyTransport _xport3("Xport3"); XportBridge _bridge(&_xport2, &_xport3); log.concatf("_xport2->toCounterparty() ---> %s\n", BufferPipe::memMgmtString( _xport2.toCounterparty(tmp_str->string(), tmp_str->length(), MEM_MGMT_RESPONSIBLE_CREATOR) ) ); _xport2.printDebug(&log); _xport3.printDebug(&log); log.concat("\n"); tmp_str->clear(); tmp_str->concat("This is a differnt bits.\n"); log.concatf("_xport3->toCounterparty() ---> %s\n", BufferPipe::memMgmtString( _xport3.toCounterparty(tmp_str->string(), tmp_str->length(), MEM_MGMT_RESPONSIBLE_CREATOR) ) ); _xport2.printDebug(&log); _xport3.printDebug(&log); printf("%s\n", log.string()); return 0; } /**************************************************************************************************** * The main function. * ****************************************************************************************************/ int main(int argc, char *argv[]) { platform.platformPreInit(); // Our test fixture needs random numbers. platform.bootstrap(); // TODO: This is presently needed to prevent the program from hanging. WHY?? StringBuilder out; platform.kernel()->printScheduler(&out); printf("\n"); test_BufferPipe_0(); printf("\n\n"); //test_BufferPipe_1(); printf("\n\n"); exit(0); }
29
101
0.624773
Manuvr
eed94336a762afe8f1e2cf259bceaf86d58c5ecf
4,667
hpp
C++
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file load_dispatch.hpp * * @brief load_dispatch の定義 * * @author myoukaku */ #ifndef BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP #define BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP #include <bksge/fnd/serialization/detail/serialize_dispatch.hpp> #include <bksge/fnd/serialization/version.hpp> #include <bksge/fnd/serialization/nvp.hpp> #include <bksge/fnd/type_traits/bool_constant.hpp> #include <bksge/fnd/type_traits/is_null_pointer.hpp> #include <bksge/fnd/type_traits/is_array.hpp> #include <bksge/fnd/type_traits/is_arithmetic.hpp> #include <bksge/fnd/type_traits/is_enum.hpp> #include <bksge/fnd/type_traits/is_pointer.hpp> #include <bksge/fnd/type_traits/remove_const.hpp> #include <bksge/fnd/type_traits/conditional.hpp> #include <utility> namespace bksge { namespace serialization { namespace detail { class load_dispatch { private: template <typename Archive, typename T> struct is_load_version_free_invocable { private: template <typename A2, typename T2> static auto test(int) -> decltype( load(std::declval<A2&>(), std::declval<T2&>(), std::declval<bksge::serialization::version_t>()), bksge::true_type()); template <typename A2, typename T2> static auto test(...)->bksge::false_type; using type = decltype(test<Archive, T>(0)); public: static const bool value = type::value; }; template <typename Archive, typename T> struct is_load_free_invocable { private: template <typename A2, typename T2> static auto test(int) -> decltype( load(std::declval<A2&>(), std::declval<T2&>()), bksge::true_type()); template <typename A2, typename T2> static auto test(...)->bksge::false_type; using type = decltype(test<Archive, T>(0)); public: static const bool value = type::value; }; struct load_array { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { ar.load_array(t); } }; struct load_arithmetic { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { ar.load_arithmetic(t); } }; struct load_enum { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { ar.load_enum(t); } }; struct load_pointer { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { ar.load_pointer(t); } }; struct load_null_pointer { template <typename Archive, typename T> static void invoke(Archive&, T& t) { t = nullptr; } }; struct load_nvp { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { ar.load_nvp(const_cast<bksge::remove_const_t<T>&>(t)); } }; struct load_version_free { template <typename Archive, typename T> static void invoke(Archive& ar, T& t, bksge::serialization::version_t version) { load(ar, t, version); } }; struct load_free { template <typename Archive, typename T> static void invoke(Archive& ar, T& t, bksge::serialization::version_t) { load(ar, t); } }; struct load_object { template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { using type = bksge::conditional_t< access::is_load_version_memfun_invocable<Archive, T>::value, access::load_version_memfun, bksge::conditional_t< access::is_load_memfun_invocable<Archive, T>::value, access::load_memfun, bksge::conditional_t< is_load_version_free_invocable<Archive, T>::value, load_version_free, bksge::conditional_t< is_load_free_invocable<Archive, T>::value, load_free, serialize_dispatch >>>>; bksge::serialization::version_t version; ar.load(version); type::invoke(ar, t, version); } }; public: template <typename Archive, typename T> static void invoke(Archive& ar, T& t) { using type = bksge::conditional_t< bksge::is_array<T>::value, load_array, bksge::conditional_t< bksge::is_arithmetic<T>::value, load_arithmetic, bksge::conditional_t< bksge::is_enum<T>::value, load_enum, bksge::conditional_t< bksge::is_pointer<T>::value, load_pointer, bksge::conditional_t< bksge::is_null_pointer<T>::value, load_null_pointer, bksge::conditional_t< is_nvp<T>::value, load_nvp, load_object >>>>>>; type::invoke(ar, t); } }; } // namespace detail } // namespace serialization } // namespace bksge #endif // BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP
21.310502
100
0.664453
myoukaku
eed948a7eee4b293e0993f3301ae385fc5b23211
1,637
cc
C++
lib/src/resource.cc
puppetlabs/libral
8f18f1022ef3676a3df6d13d6b483d2100c5bc97
[ "Apache-2.0" ]
68
2017-01-06T18:32:02.000Z
2019-03-16T01:56:41.000Z
lib/src/resource.cc
puppetlabs-toy-chest/libral
8f18f1022ef3676a3df6d13d6b483d2100c5bc97
[ "Apache-2.0" ]
41
2017-01-19T19:42:23.000Z
2017-11-08T21:38:03.000Z
lib/src/resource.cc
puppetlabs-toy-chest/libral
8f18f1022ef3676a3df6d13d6b483d2100c5bc97
[ "Apache-2.0" ]
15
2017-01-08T02:45:56.000Z
2021-03-24T11:18:09.000Z
#include <libral/resource.hpp> namespace libral { bool resource::is_name(const std::string& key) const { // This hardcodes namevar for now return key == "name"; } const value& resource::operator[](const std::string& key) const { if (is_name(key)) { throw std::invalid_argument { "The name can not be accessed with operator[]" }; } auto v = _attrs.find(key); if (v == _attrs.end()) { return value::none; } else { return v->second; } } value& resource::operator[](const std::string& key) { if (is_name(key)) { throw std::invalid_argument { "The name can not be accessed with operator[]" }; } return _attrs[key]; } template<typename T> const T& resource::lookup(const std::string& key, const T& deflt) const { auto it = _attrs.find(key); if (it == _attrs.end()) { return deflt; } else if (auto p = it->second.as<T>()) { return *p; } else { return deflt; } } template<typename T> const T* resource::lookup(const std::string& key) const { auto it = _attrs.find(key); if (it == _attrs.end()) { return nullptr; } else { return it->second.as<T>(); } }; template const bool& resource::lookup(const std::string&, const bool&) const; template const std::string& resource::lookup(const std::string&, const std::string&) const; template const std::string* resource::lookup(const std::string&) const; template const array& resource::lookup(const std::string&, const array&) const; template const array* resource::lookup(const std::string&) const; }
25.184615
75
0.611484
puppetlabs
eed989a805c02eed03d7c14c8306bf81ff2b10c3
9,433
hh
C++
src/USRP.hh
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
8
2020-12-05T20:30:54.000Z
2022-01-22T13:32:14.000Z
src/USRP.hh
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
3
2020-10-28T22:15:27.000Z
2021-01-27T14:43:41.000Z
src/USRP.hh
drexelwireless/dragonradio
885abd68d56af709e7a53737352641908005c45b
[ "MIT" ]
null
null
null
// Copyright 2018-2020 Drexel University // Author: Geoffrey Mainland <mainland@drexel.edu> #ifndef USRP_H_ #define USRP_H_ #include <atomic> #include <deque> #include <string> #include <thread> #include <uhd/usrp/multi_usrp.hpp> #include "logging.hh" #include "Clock.hh" #include "IQBuffer.hh" /** @brief A USRP. */ class USRP { public: enum DeviceType { kUSRPN210, kUSRPX310, kUSRPUnknown }; USRP(const std::string& addr, const std::optional<std::string>& tx_subdev, const std::optional<std::string>& rx_subdev, double freq, const std::string& tx_ant, const std::string& rx_ant, float tx_gain, float rx_gain); ~USRP(); USRP() = delete; USRP(const USRP&) = delete; USRP(USRP&&) = delete; USRP& operator=(const USRP&) = delete; USRP& operator=(USRP&&) = delete; /** @brief Get type of this device. */ DeviceType getDeviceType(void) { return device_type_; } /** @brief Get clock sources. */ std::vector<std::string> getClockSources(const size_t mboard = 0) { return usrp_->get_clock_sources(mboard); } /** @brief Get clock source. */ std::string getClockSource(const size_t mboard = 0) { return usrp_->get_clock_source(mboard); } /** @brief Set clock source. */ void setClockSource(const std::string clock_source, const size_t mboard = uhd::usrp::multi_usrp::ALL_MBOARDS) { return usrp_->set_clock_source(clock_source, mboard); } /** @brief Get time sources. */ std::vector<std::string> getTimeSources(const size_t mboard = 0) { return usrp_->get_time_sources(mboard); } /** @brief Get time source. */ std::string getTimeSource(const size_t mboard = 0) { return usrp_->get_time_source(mboard); } /** @brief Set time source. */ void setTimeSource(const std::string &time_source, const size_t mboard = uhd::usrp::multi_usrp::ALL_MBOARDS) { return usrp_->set_time_source(time_source, mboard); } /** @brief Get master clock rate. */ double getMasterClockRate(void) { return usrp_->get_master_clock_rate(0); } /** @brief Get TX frequency. */ double getTXFrequency(void) { return usrp_->get_tx_freq(); } /** @brief Set TX frequency. * @param freq The center frequency */ void setTXFrequency(double freq); /** @brief Get RX frequency. */ double getRXFrequency(void) { return usrp_->get_rx_freq(); } /** @brief Set RX frequency. * @param freq The center frequency */ void setRXFrequency(double freq); /** @brief Get TX rate. */ double getTXRate(void) { return usrp_->get_tx_rate(); } /** @brief Set TX rate. */ void setTXRate(double rate) { usrp_->set_tx_rate(rate); logUSRP(LOGDEBUG, "TX rate set to %f", rate); tx_rate_ = usrp_->get_tx_rate(); } /** @brief Get RX rate. */ double getRXRate(void) { return usrp_->get_rx_rate(); } /** @brief Set RX rate. */ void setRXRate(double rate) { usrp_->set_rx_rate(rate); logUSRP(LOGDEBUG, "RX rate set to %f", rate); rx_rate_ = usrp_->get_rx_rate(); } /** @brief Get TX gain (dB). */ double getTXGain(void) { return usrp_->get_tx_gain(); } /** @brief Set TX gain (dB). */ void setTXGain(float db) { return usrp_->set_tx_gain(db); } /** @brief Get RX gain (dB). */ double getRXGain(void) { return usrp_->get_rx_gain(); } /** @brief Set RX gain (dB). */ void setRXGain(float db) { return usrp_->set_rx_gain(db); } /** @brief Get automatic DC offset correction. */ bool getAutoDCOffset(bool enable) { return auto_dc_offset_; } /** @brief Get time at which next transmission will occur */ std::optional<MonoClock::time_point> getNextTXTime() { return t_next_tx_; } /** @brief Set automatic DC offset correction. */ void setAutoDCOffset(bool enable) { auto_dc_offset_ = enable; usrp_->set_rx_dc_offset(auto_dc_offset_); usrp_->set_tx_dc_offset(auto_dc_offset_); } /** @brief Transmit a burst of IQ buffers at the given time. * @param when Time at which to start the burst. * @param start_of_burst Is this the start of a burst? * @param end_of_burst Is this the end of a burst? * @param bufs A list of IQBuf%s to transmit. */ void burstTX(std::optional<MonoClock::time_point> when, bool start_of_burst, bool end_of_burst, std::list<std::shared_ptr<IQBuf>>& bufs); /** @brief Stop TX burst */ void stopTXBurst(void); /** @brief Start streaming read */ void startRXStream(MonoClock::time_point when); /** @brief Stop streaming read */ void stopRXStream(void); /** @brief Receive specified number of samples at the given time * @param when The time at which to start receiving. * @param nsamps The number of samples to receive. * @param buf The IQBuf to hold received IQ samples. The buffer should be at * least getRecommendedBurstRXSize(nsamps) bytes. * @returns Returns true if the burst was successfully received, false * otherwise. */ bool burstRX(MonoClock::time_point when, size_t nsamps, IQBuf& buf); /** @brief Return the maximum number of samples we will read at a time * during burstRX. */ size_t getMaxRXSamps(void) { return rx_max_samps_; } /** @brief Set the maximum number of samples we will read at a time * during burstRX. */ void setMaxRXSamps(size_t count) { rx_max_samps_ = count; logUSRP(LOGDEBUG, "rx_max_samps_=%lu", rx_max_samps_); } /** @brief Set the multiplier for the maximum number of samples we will read * at a time during burstRX. */ void setMaxRXSampsFactor(unsigned n) { setMaxRXSamps(n*rx_stream_->get_max_num_samps()); } /** @brief Return the maximum number of samples we will write at a time * during burstTX. */ size_t getMaxTXSamps(void) { return tx_max_samps_; } /** @brief Set the maximum number of samples we will write at a time * during burstTX. */ void setMaxTXSamps(size_t count) { tx_max_samps_ = count; logUSRP(LOGDEBUG, "tx_max_samps_=%lu", tx_max_samps_); } /** @brief Set the multiplier for the maximum number of samples we will read * at a time during burstTX. */ void setMaxTXSampsFactor(unsigned n) { setMaxTXSamps(n*tx_stream_->get_max_num_samps()); } /** @brief Return the recommended buffer size during burstRX. * @param nsamps Number of samples to read during burst * @return Recommended buffer size */ size_t getRecommendedBurstRXSize(size_t nsamps) { return nsamps + 8*rx_max_samps_; } /** @brief Get the TX underflow count. * @return The number of TX underflow errors */ /** Return the number of TX underflow errors and reset the counter */ uint64_t getTXUnderflowCount(void) { return tx_underflow_count_.exchange(0, std::memory_order_relaxed); } /** @brief Get the TX late count. * @return The number of late TX packet errors */ /** Return the number of TX late packet errors and reset the counter */ uint64_t getTXLateCount(void) { return tx_late_count_.exchange(0, std::memory_order_relaxed); } /** @brief Stop processing data. */ void stop(void); private: /** @brief Our associated UHD USRP. */ uhd::usrp::multi_usrp::sptr usrp_; /** @brief The DeviceType of the main device */ DeviceType device_type_; /** @brief Current TX rate */ double tx_rate_; /** @brief Current RX rate */ double rx_rate_; /** @brief Current TX frequency */ double tx_freq_; /** @brief Current RX frequency */ double rx_freq_; /** @brief The UHD TX stream for this USRP. */ uhd::tx_streamer::sptr tx_stream_; /** @brief The UHD RX stream for this USRP. */ uhd::rx_streamer::sptr rx_stream_; /** @brief Maximum number of samples we will send at a time during burstTX. */ size_t tx_max_samps_; /** @brief Maximum number of samples we will read at a time during burstRX. */ size_t rx_max_samps_; /** @brief Time at which next transmission will occur */ std::optional<MonoClock::time_point> t_next_tx_; /** @brief Flag indicating whether or not to enable automatic DC offset * correction. */ bool auto_dc_offset_; /** @brief Flag indicating the we should stop processing data. */ bool done_; /** @brief TX underflow count. */ std::atomic<uint64_t> tx_underflow_count_; /** @brief TX late count. */ std::atomic<uint64_t> tx_late_count_; /** @brief Thread that receives TX errors. */ std::thread tx_error_thread_; /** @brief Determine the type of the main device. */ void determineDeviceType(void); /** @brief Worker that receives TX errors. */ void txErrorWorker(void); }; #endif /* USRP_H_ */
26.202778
81
0.618573
drexelwireless
eedbd43579d0656d45f4c8f578229fc1932df769
8,053
cc
C++
usr_local/src/festival/src/modules/hts_engine/fest2hts_engine.cc
parnurzeal/tts-tutorial
db11aed2adc5101cc6d06d1138f74d5f5afe666f
[ "Apache-2.0" ]
30
2016-09-23T06:38:08.000Z
2022-02-14T02:02:14.000Z
usr_local/src/festival/src/modules/hts_engine/fest2hts_engine.cc
xbsdsongnan/docker-festival
1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6
[ "Apache-2.0" ]
3
2020-06-05T18:09:02.000Z
2021-06-10T20:06:02.000Z
usr_local/src/festival/src/modules/hts_engine/fest2hts_engine.cc
xbsdsongnan/docker-festival
1e1c50c8bbd92d47ecb7edc7a464aadad5b9a0d6
[ "Apache-2.0" ]
13
2016-11-06T05:52:23.000Z
2020-08-26T18:38:00.000Z
/* ----------------------------------------------------------------- */ /* The HMM-Based Speech Synthesis Module for Festival */ /* "festopt_hts_engine" developed by HTS Working Group */ /* http://hts-engine.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2001-2013 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* 2001-2008 Tokyo Institute of Technology */ /* Interdisciplinary Graduate School of */ /* Science and Engineering */ /* */ /* 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 HTS working group 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. */ /* ----------------------------------------------------------------- */ /* standard C libraries */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include "festival.h" /* header of hts_engine API */ #include "HTS_engine.h" #include "HTS_hidden.h" /* Getfp: wrapper for fopen */ static FILE *Getfp(const char *name, const char *opt) { FILE *fp = fopen(name, opt); if (fp == NULL) { cerr << "Getfp: Cannot open " << name << endl; festival_error(); } return (fp); } /* HTS_Synthesize_Utt: generate speech from utt by using hts_engine API */ static LISP HTS_Synthesize_Utt(LISP utt) { EST_Utterance *u = get_c_utt(utt); EST_Item *item = 0; LISP hts_engine_params = NIL; LISP hts_output_params = NIL; char **fn_voices = NULL; char *fn_htsvoice = NULL; HTS_Engine engine; FILE *labfp = NULL; FILE *rawfp = NULL, *durfp = NULL; int sampling_rate; double speech_speed; /* get params */ hts_engine_params = siod_get_lval("hts_engine_params", "festopt_hts_engine: no parameters set for module"); hts_output_params = siod_get_lval("hts_output_params", "festopt_hts_engine: no output parameters set for module"); /* get model file names */ fn_voices = (char **) malloc(sizeof(char *)); fn_htsvoice = (char *) get_param_str("-m", hts_engine_params, "hts/htsvoice"); fn_voices[0] = fn_htsvoice; /* get speech speed */ speech_speed = (double) get_param_float("-r", hts_engine_params, 1.0); /* open input file pointers */ labfp = Getfp(get_param_str("-labelfile", hts_output_params, "utt.feats"), "r"); /* open output file pointers */ rawfp = Getfp(get_param_str("-or", hts_output_params, "tmp.raw"), "wb"); durfp = Getfp(get_param_str("-od", hts_output_params, "tmp.lab"), "wb"); /* initialize */ HTS_Engine_initialize(&engine); /* load models */ HTS_Engine_load(&engine, fn_voices, 1); free(fn_voices); /* turn off audio output */ HTS_Engine_set_audio_buff_size(&engine, 0); /* get sampling frequency */ sampling_rate = HTS_Engine_get_sampling_frequency(&engine); /* set speech speed */ HTS_Engine_set_speed(&engine, speech_speed); /* generate speech */ if (u->relation("Segment")->first()) { /* only if there segments */ HTS_Engine_synthesize_from_fn(&engine, get_param_str("-labelfile", hts_output_params, "utt.feats")); if (rawfp != NULL) HTS_Engine_save_generated_speech(&engine, rawfp); if (durfp != NULL) HTS_Engine_save_label(&engine, durfp); HTS_Engine_refresh(&engine); } /* free */ HTS_Engine_clear(&engine); /* close output file pointers */ if (rawfp != NULL) fclose(rawfp); if (durfp != NULL) fclose(durfp); /* close input file pointers */ if (labfp != NULL) fclose(labfp); /* Load back in the waveform */ EST_Wave *w = new EST_Wave; w->resample(sampling_rate); if (u->relation("Segment")->first()) /* only if there segments */ w->load_file(get_param_str("-or", hts_output_params, "tmp.raw"), "raw", sampling_rate, "short", str_to_bo("native"), 1); item = u->create_relation("Wave")->append(); item->set_val("wave", est_val(w)); /* Load back in the segment times */ EST_Relation *r = new EST_Relation; EST_Item *s, *o; r->load(get_param_str("-od", hts_output_params, "tmp.lab"), "htk"); for (o = r->first(), s = u->relation("Segment")->first(); (o != NULL) && (s != NULL); o = o->next(), s = s->next()) if (o->S("name").before("+").after("-").matches(s->S("name"))) s->set("end", o->F("end")); else cerr << "HTS_Synthesize_Utt: Output segment mismatch"; delete r; return utt; } #define HTS_VERSION "1.07" #define HTS_URL "http://hts-engine.sourceforge.net/" #define HTS_NCOPYRIGHT 1 /* HTS_get_copyright: write copyright to string */ void HTS_get_copyright(char *str) { int i, nCopyright = HTS_NCOPYRIGHT; char url[] = HTS_URL, version[] = HTS_VERSION; char *copyright[] = { HTS_COPYRIGHT }; sprintf(str, "\nThe HMM-Based Speech Synthesis Engine \"hts_engine API\"\n"); sprintf(str, "%shts_engine API version %s (%s)\n", str, version, url); for (i = 0; i < nCopyright; i++) { if (i == 0) sprintf(str, "%sCopyright (C) %s\n", str, copyright[i]); else sprintf(str, "%s %s\n", str, copyright[i]); } sprintf(str, "%sAll rights reserved.\n", str); return; } void festival_hts_engine_init(void) { char buf[4096]; HTS_get_copyright(buf); proclaim_module("hts_engine", buf); festival_def_utt_module("HTS_Synthesize", HTS_Synthesize_Utt, "(HTS_Synthesis UTT)\n Synthesize a waveform using the hts_engine and the current models"); }
36.438914
118
0.556935
parnurzeal
eedc7e0b05041c3e743fb143b219f6aaa77bc50c
9,215
cpp
C++
DLL/RenderingHUD/rendering-hud.cpp
ClementDreptin/ModdingResources
e5e52285493bd138daf5db373753aaffccf1227a
[ "MIT" ]
null
null
null
DLL/RenderingHUD/rendering-hud.cpp
ClementDreptin/ModdingResources
e5e52285493bd138daf5db373753aaffccf1227a
[ "MIT" ]
null
null
null
DLL/RenderingHUD/rendering-hud.cpp
ClementDreptin/ModdingResources
e5e52285493bd138daf5db373753aaffccf1227a
[ "MIT" ]
null
null
null
#include "pch.h" #include "..\Utils\Utils.h" // HUD API structs and enums enum he_type_t : int { HE_TYPE_FREE, HE_TYPE_TEXT, HE_TYPE_VALUE, HE_TYPE_PLAYERNAME, HE_TYPE_MATERIAL, HE_TYPE_MAPNAME, HE_TYPE_GAMETYPE, HE_TYPE_TIMER_DOWN, HE_TYPE_TIMER_UP, HE_TYPE_TIMER_STATIC, HE_TYPE_TENTHS_TIMER_DOWN, HE_TYPE_TENTHS_TIMER_UP, HE_TYPE_CLOCK_DOWN, HE_TYPE_CLOCK_UP, HE_TYPE_WAYPOINT, HE_TYPE_COUNT, }; typedef enum align_t : int { ALIGN_TOP_LEFT = 0, ALIGN_MIDDLE_LEFT = 1, ALIGN_BOTTOM_LEFT = 2, ALIGN_TOP_MIDDLE = 4, ALIGN_MIDDLE_MIDDLE = 5, ALIGN_BOTTOM_MIDDLE = 6, ALIGN_TOP_RIGHT = 8, ALIGN_MIDDLE_RIGHT = 9, ALIGN_BOTTOM_RIGHT = 10 }; struct hudelem_color_t { uint8_t r; uint8_t g; uint8_t b; uint8_t a; }; struct hudelem_s { he_type_t type; float y; float x; float z; int targetEntNum; float fontScale; float fromFontScale; int fontScaleStartTime; int fontScaleTime; int label; int font; align_t alignOrg; align_t alignScreen; hudelem_color_t color; hudelem_color_t fromColor; int fadeStartTime; int fadeTime; int height; int width; int materialIndex; int fromHeight; int fromWidth; int scaleStartTime; int scaleTime; float fromY; float fromX; int fromAlignOrg; int fromAlignScreen; int moveStartTime; int moveTime; float value; int time; int duration; int text; float sort; hudelem_color_t glowColor; int fxBirthTime; int fxLetterTime; int fxDecayStartTime; int fxDecayDuration; int soundID; int flags; }; struct game_hudelem_s { hudelem_s elem; int clientNum; int teamNum; int archived; }; // HUD API functions game_hudelem_s *(*HudElem_Alloc)(int clientNum, int teamNum) = reinterpret_cast<game_hudelem_s *(*)(int, int)>(0x821DF928); int (*G_MaterialIndex)(const char *name) = reinterpret_cast<int(*)(const char *)>(0x8220C960); int (*G_LocalizedStringIndex)(const char *string) = reinterpret_cast<int(*)(const char *)>(0x8220C7A0); // Rendering API structs struct Color { float r; float g; float b; float a; }; struct Font_s { int fontName; int pixelHeight; int glyphCount; int material; int glowMaterial; int glyphs; }; // Rendering API functions void (*R_AddCmdDrawStretchPic)(float x, float y, float w, float h, float s0, float t0, float s1, float t1, const float *color, HANDLE material) = reinterpret_cast<void(*)(float, float, float, float, float, float, float, float, const float *, HANDLE)>(0x8234F9B8); void (*R_AddCmdDrawText)(const char *text, int maxChars, Font_s *font, float x, float y, float xScale, float yScale, float rotation, const float *color, int style) = reinterpret_cast<void(*)(const char *, int, Font_s *, float, float, float, float, float, const float *, int)>(0x82350278); Font_s *(*R_RegisterFont)(const char *font, int imageTrack) = reinterpret_cast<Font_s *(*)(const char *, int)>(0x8234DCB0); HANDLE (*Material_RegisterHandle)(const char *name, int imageTrack) = reinterpret_cast<HANDLE(*)(const char *, int)>(0x8234E510); // Used to change some dvars void (*SV_GameSendServerCommand)(int clientNum, int type, const char *text) = reinterpret_cast<void(*)(int, int, const char *)>(0x822548D8); void __declspec(naked) SCR_DrawScreenFieldStub(const int localClientNum, int refreshedUI) { // The stub needs to, at least, contain 7 instructions __asm { nop nop nop nop nop nop nop } } HANDLE hMaterial = nullptr; Font_s *normalFont = nullptr; Color black = { 0.0f, 0.0f, 0.0f, 0.0f }; Color white = { 1.0f, 1.0f, 1.0f, 0.0f }; void SCR_DrawScreenFieldHook(const int localClientNum, int refreshedUI) { // Calling the original SCR_DrawScreenField function SCR_DrawScreenFieldStub(localClientNum, refreshedUI); // Register the white material the first time we draw if (!hMaterial) hMaterial = Material_RegisterHandle("white", 0); // Register the normal font the first time we draw if (!pFont) pFont = R_RegisterFont("fonts/normalFont", 0); // Rendering the rectangle only if the alpha channel is positive if (black.a > 0.0f) R_AddCmdDrawStretchPic(5.0f, 5.0f, 400.0f, 710.0f, 0.0f, 0.0f, 1.0f, 1.0f, reinterpret_cast<float *>(&black), hMaterial); // Rendering the text only if the alpha channel is positive if (white.a > 0.0f) { const char *text = "Rendering API Text"; R_AddCmdDrawText(text, strlen(text), normalFont, 90.0f, 375.0f, 1.0f, 1.0f, 0.0f, reinterpret_cast<float *>(&white), 0); } } void __declspec(naked) SV_ExecuteClientCommandStub(int client, const char *s, int clientOK, int fromOldServer) { // The stub needs to, at least, contain 7 instructions __asm { nop nop nop nop nop nop li r3, 1 } } game_hudelem_s *rectangleElem = nullptr; game_hudelem_s *textElem = nullptr; void SV_ExecuteClientCommandHook(int client, const char *s, int clientOK, int fromOldServer) { // Calling the original SV_ExecuteClientCommand function SV_ExecuteClientCommandStub(client, s, clientOK, fromOldServer); // Checking if dpad left is pressed if (!strcmp(s, "n 19")) { // Creating the rectangle and removing localization warnings only the first time we press the button if (!pRectangleElem) { // Removing UNLOCALIZED() around texts SV_GameSendServerCommand(0, 0, "s loc_warnings \"0\""); SV_GameSendServerCommand(0, 0, "s loc_warningsUI \"0\""); pRectangleElem = HudElem_Alloc(0, 0); pRectangleElem->elem.x = 441.0f; pRectangleElem->elem.y = 5.0f; pRectangleElem->elem.width = 300; pRectangleElem->elem.height = 470; pRectangleElem->elem.color.r = 0; pRectangleElem->elem.color.g = 0; pRectangleElem->elem.color.b = 0; pRectangleElem->elem.color.a = 0; pRectangleElem->elem.type = HE_TYPE_MATERIAL; pRectangleElem->elem.alignOrg = ALIGN_TOP_LEFT; pRectangleElem->elem.alignScreen = ALIGN_TOP_LEFT; pRectangleElem->elem.sort = 0.0f; pRectangleElem->elem.materialIndex = G_MaterialIndex("white"); } // Creating the text only the first time we press the button if (!pTextElem) { pTextElem = HudElem_Alloc(0, 0); pTextElem->elem.x = 441.0f + (300.0f / 2.0f) + (5.0f / 2.0f); pTextElem->elem.y = 5.0f + (470.0f / 2.0f); pTextElem->elem.color.r = 255; pTextElem->elem.color.g = 255; pTextElem->elem.color.b = 255; pTextElem->elem.color.a = 0; pTextElem->elem.type = HE_TYPE_TEXT; pTextElem->elem.alignOrg = ALIGN_MIDDLE_MIDDLE; pTextElem->elem.alignScreen = ALIGN_TOP_LEFT; pTextElem->elem.font = 4; pTextElem->elem.sort = 1.0f; pTextElem->elem.fontScale = 2.0f; pTextElem->elem.text = G_LocalizedStringIndex("HUD API Text"); } // Toggle the visibility of the rectangle and the text from the HUD API if (!pRectangleElem->elem.color.a) { pRectangleElem->elem.color.a = 255; pTextElem->elem.color.a = 255; } else { pRectangleElem->elem.color.a = 0; pTextElem->elem.color.a = 0; } // Toggle the visibility of the rectangle and the text from the rendering API if (!black.a) { black.a = 1.0f; white.a = 1.0f; } else { black.a = 0.0f; white.a = 0.0f; } } } // Sets up the hook void InitMW2() { XNotifyQueueUI(0, 0, XNOTIFY_SYSTEM, L"MW2", nullptr); // Waiting a little bit for the game to be fully loaded in memory Sleep(200); const DWORD SV_ExecuteClientCommandAddr = 0x82253140; const DWORD SCR_DrawScreenFieldAddr = 0x8214BEB8; // Hooking SV_ExecuteClientCommand HookFunctionStart(reinterpret_cast<DWORD *>(SV_ExecuteClientCommandAddr), reinterpret_cast<DWORD *>(SV_ExecuteClientCommandStub), reinterpret_cast<DWORD>(SV_ExecuteClientCommandHook)); HookFunctionStart(reinterpret_cast<DWORD *>(SCR_DrawScreenFieldAddr), reinterpret_cast<DWORD *>(SCR_DrawScreenFieldStub), reinterpret_cast<DWORD>(SCR_DrawScreenFieldHook)); } BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, void *pReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // Runs MonitorTitleId in separate thread ExCreateThread(nullptr, 0, nullptr, nullptr, reinterpret_cast<PTHREAD_START_ROUTINE>(MonitorTitleId), nullptr, 2); break; case DLL_PROCESS_DETACH: g_bRunning = FALSE; // We give the system some time to clean up the thread before exiting Sleep(250); break; } return TRUE; }
29.347134
188
0.644276
ClementDreptin
4abe4ae483c2e1c7511f98865a754505aa151c7c
5,956
cpp
C++
tracker_tests/src/epnp_test.cpp
clickcao/fato
d2de665e83f82ea1094f488102aba37a8cdd53bb
[ "BSD-3-Clause" ]
1
2018-07-31T04:11:32.000Z
2018-07-31T04:11:32.000Z
tracker_tests/src/epnp_test.cpp
clickcao/fato
d2de665e83f82ea1094f488102aba37a8cdd53bb
[ "BSD-3-Clause" ]
null
null
null
tracker_tests/src/epnp_test.cpp
clickcao/fato
d2de665e83f82ea1094f488102aba37a8cdd53bb
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009, V. Lepetit, EPFL // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <vector> using namespace std; #include "epnp.h" const double uc = 320; const double vc = 240; const double fu = 800; const double fv = 800; // MtM takes more time than 12x12 opencv SVD with about 180 points and more: const int n = 100; const double noise = 10; double rand(double min, double max) { return min + (max - min) * double(rand()) / RAND_MAX; } void random_pose(double R[3][3], double t[3]) { const double range = 1; double phi = rand(0, range * 3.14159 * 2); double theta = rand(0, range * 3.14159); double psi = rand(0, range * 3.14159 * 2); R[0][0] = cos(psi) * cos(phi) - cos(theta) * sin(phi) * sin(psi); R[0][1] = cos(psi) * sin(phi) + cos(theta) * cos(phi) * sin(psi); R[0][2] = sin(psi) * sin(theta); R[1][0] = -sin(psi) * cos(phi) - cos(theta) * sin(phi) * cos(psi); R[1][1] = -sin(psi) * sin(phi) + cos(theta) * cos(phi) * cos(psi); R[1][2] = cos(psi) * sin(theta); R[2][0] = sin(theta) * sin(phi); R[2][1] = -sin(theta) * cos(phi); R[2][2] = cos(theta); t[0] = 0.0f; t[1] = 0.0f; t[2] = 6.0f; } void random_point(double & Xw, double & Yw, double & Zw) { double theta = rand(0, 3.14159), phi = rand(0, 2 * 3.14159), R = rand(0, +2); Xw = sin(theta) * sin(phi) * R; Yw = -sin(theta) * cos(phi) * R; Zw = cos(theta) * R; } void project_with_noise(double R[3][3], double t[3], double Xw, double Yw, double Zw, double & u, double & v) { double Xc = R[0][0] * Xw + R[0][1] * Yw + R[0][2] * Zw + t[0]; double Yc = R[1][0] * Xw + R[1][1] * Yw + R[1][2] * Zw + t[1]; double Zc = R[2][0] * Xw + R[2][1] * Yw + R[2][2] * Zw + t[2]; double nu = rand(-noise, +noise); double nv = rand(-noise, +noise); u = uc + fu * Xc / Zc + nu; v = vc + fv * Yc / Zc + nv; } int main(int /*argc*/, char ** /*argv*/) { fato::PNPSolver PnP; srand(time(0)); PnP.set_internal_parameters(uc, vc, fu, fv); PnP.set_maximum_number_of_correspondences(n); double R_true[3][3], t_true[3]; random_pose(R_true, t_true); vector<cv::Point3f> model_pts; vector<cv::Point2f> proj_pts; PnP.reset_correspondences(); for(int i = 0; i < n; i++) { double Xw, Yw, Zw, u, v; random_point(Xw, Yw, Zw); project_with_noise(R_true, t_true, Xw, Yw, Zw, u, v); PnP.add_correspondence(Xw, Yw, Zw, u, v); model_pts.push_back(cv::Point3d(Xw, Yw, Zw)); proj_pts.push_back(cv::Point2d(u, v)); } cv::Mat camera_matrix(3, 3, CV_64FC1, 0.0f); //var intrinsic = new Mat(3, 3, MatType.CV_64F, new double[] { d1, d2, d3, d4, d5, d6, d7, d8, d9 }) camera_matrix.at<double>(0,0) = fu; camera_matrix.at<double>(1,1) = fv; camera_matrix.at<double>(0,2) = uc; camera_matrix.at<double>(1,2) = vc; cv::Mat rotation(3, 3, CV_64FC1, 0.0f); cv::Mat translation(1, 3, CV_64FC1, 0.0f); cv::Mat rotation_vec(1, 3, CV_64FC1, 0.0f); vector<int> inliers; cv::solvePnPRansac(model_pts, proj_pts, camera_matrix, cv::Mat::zeros(1, 8, CV_64F), rotation_vec, translation, false, 30, 5.0, 50, inliers, CV_EPNP); cv::Rodrigues(rotation_vec, rotation); double R_est[3][3], t_est[3]; double err2 = PnP.compute_pose(R_est, t_est); double rot_err, transl_err; std::vector<int> custom_inliers; fato::PNPSolver pnp_ransac; pnp_ransac.set_internal_parameters(uc, vc, fu, fv); pnp_ransac.set_maximum_number_of_correspondences(n); pnp_ransac.setCorrespondences(model_pts, proj_pts); pnp_ransac.solvePnP(30, 50, 5.0, custom_inliers); PnP.relative_error(rot_err, transl_err, R_true, t_true, R_est, t_est); cout << ">>> Reprojection error: " << err2 << endl; cout << ">>> rot_err: " << rot_err << ", transl_err: " << transl_err << endl; cout << endl; cout << "'True reprojection error':" << PnP.reprojection_error(R_true, t_true) << endl; cout << endl; cout << "True pose:" << endl; PnP.print_pose(R_true, t_true); cout << endl; cout << "Found pose:" << endl; PnP.print_pose(R_est, t_est); cout << "Opnecv pose:" << endl; for(auto i = 0; i < 3; ++i) { for(auto j = 0; j < 3; ++j) { cout << rotation.at<double>(i,j) << " "; } cout << "\n"; } cout << "Opencv inliers " << inliers.size() << endl; return 0; }
31.347368
102
0.642377
clickcao
4ac02aae273428114c62b071a2417e29c378c34b
991
hpp
C++
src/mlpack/core/math/log_add.hpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-07T14:34:37.000Z
2019-11-07T14:34:37.000Z
src/mlpack/core/math/log_add.hpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-10T17:39:50.000Z
2020-04-11T14:56:25.000Z
src/mlpack/core/math/log_add.hpp
tomjpsun/mlpack
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file log_add.hpp * @author Arash Abghari * * Functions for logarithmic addition. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_MATH_LOG_ADD_HPP #define MLPACK_CORE_MATH_LOG_ADD_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace math { /** * Internal log-addition. * * @param x log value * @param y log value * @return log(e^x + e^y) */ template<typename T> T LogAdd(T x, T y); /** * Sum a vector of log values. (T should be an Armadillo type.) * * @param x vector of log values * @return log(e^x0 + e^x1 + ...) */ template<typename T> typename T::elem_type AccuLog(const T& x); } // namespace math } // namespace mlpack // Include implementation. #include "log_add_impl.hpp" #endif
21.543478
78
0.699294
tomjpsun
4ac3d42e885530bf12f77447317774694bda50ef
3,855
cpp
C++
android/android/opengl/appkit/GLTextureStreamHost.cpp
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
5
2016-12-07T10:51:48.000Z
2018-11-26T07:21:10.000Z
android/android/opengl/appkit/GLTextureStreamHost.cpp
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
null
null
null
android/android/opengl/appkit/GLTextureStreamHost.cpp
naver/androidpp
d87b9c7e356872514a92bacd63ce18133fba5a18
[ "BSD-3-Clause" ]
5
2016-12-06T13:06:20.000Z
2021-07-24T03:33:35.000Z
/* * Copyright (C) 2016 Naver Corp. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GLTextureStreamHost.h" #include "EGLPbufferSurface.h" #include "GLTextureStreamChannelMessages.h" #include "GLTextureStreamHostMessages.h" #include <android/os/appkit/Process.h> #include <android/os/appkit/Thread.h> #include <assert> namespace android { namespace opengl { namespace appkit { GLTextureStreamHost::GLTextureStreamHost(std::shared_ptr<Messenger>&& messageSender) : MessageHost(std::move(messageSender)) , m_width(0) , m_height(0) , m_surfaceType(GLTransportSurface::Unknown) , m_shareHandle(0) { } GLTextureStreamHost::~GLTextureStreamHost() { } void GLTextureStreamHost::initializeOnce() { static bool onceFlag = false; setReceiveMessages(onceFlag, GLTextureStreamHostMessages::get()); } std::shared_ptr<GLTransportSurface> GLTextureStreamHost::import(EGLConfig config) { std::shared_ptr<GLTransportSurface> surface; switch (m_surfaceType) { case GLTransportSurface::EGLPbuffer: surface = EGLPbufferSurface::import(config, m_shareHandle, m_width, m_height); break; default: assert(false); return nullptr; } m_surface = surface; return std::move(surface); } void GLTextureStreamHost::receive(Message& message) { if (message.what == GLTextureStreamHostMessages::get().RESHAPE) { m_width = message.arg1; m_height = message.arg2; send(GLTextureStreamChannelMessages::get().Reshaped()); } else if (message.what == GLTextureStreamHostMessages::get().PUBLISH) { m_surfaceType = static_cast<GLTransportSurface::Type>(message.arg1); m_shareHandle = message.obj; protect(); if (!m_surface.expired()) m_surface.lock()->reset(m_shareHandle, m_width, m_height); send(GLTextureStreamChannelMessages::get().Published()); } else { MessageHost::receive(message); } } void GLTextureStreamHost::setReceiveMessages(bool& onceFlag, Messages& messages) { if (onceFlag) return; onceFlag = true; Thread::runOnMainThread([&] { Process::current().setMessageReceiver(GLTextureStreamHost::receiveMessage, messages); }); } bool GLTextureStreamHost::receiveMessage(Messenger& replySender, Message& message) { if (message.what == GLTextureStreamHostMessages::get().CONNECT) { new GLTextureStreamHost(std::shared_ptr<Messenger>(message.replyTo)); return true; } return false; } } // namespace appkit } // namespace opengl } // namespace android
32.394958
93
0.724514
naver
4ac445f3891caf4866ab3d9f4575bd66e461d1c1
17,738
cpp
C++
sample/src/VK/Sources/SssrSample.cpp
TheozZhh79/FidelityFX-SSSR
d9bfe98d43782c758e3c28b90754be209471dd96
[ "MIT" ]
126
2020-05-11T16:57:41.000Z
2022-03-29T11:43:53.000Z
sample/src/VK/Sources/SssrSample.cpp
TheozZhh79/FidelityFX-SSSR
d9bfe98d43782c758e3c28b90754be209471dd96
[ "MIT" ]
1
2022-01-28T09:38:08.000Z
2022-01-29T02:27:58.000Z
sample/src/VK/Sources/SssrSample.cpp
TheozZhh79/FidelityFX-SSSR
d9bfe98d43782c758e3c28b90754be209471dd96
[ "MIT" ]
14
2020-05-20T06:15:12.000Z
2022-02-25T21:17:49.000Z
/********************************************************************** Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved. 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 "stdafx.h" #include "SssrSample.h" #include "base/ShaderCompilerCache.h" #include "base/Instance.h" namespace SSSR_SAMPLE_VK { SssrSample::SssrSample(LPCSTR name) : FrameworkWindows(name) { m_DeltaTime = 0; m_Distance = 0; m_Pitch = 0; m_Yaw = 0; m_selectedScene = 0; m_LastFrameTime = MillisecondsNow(); m_Time = 0; m_bPlay = true; m_bShowUI = true; m_CameraControlSelected = 0; // select WASD on start up m_pGltfLoader = NULL; } //-------------------------------------------------------------------------------------- // // OnCreate // //-------------------------------------------------------------------------------------- void SssrSample::OnCreate(HWND hWnd) { // get the list of scenes for (const auto& scene : m_JsonConfigFile["scenes"]) m_SceneNames.push_back(scene["name"]); DWORD dwAttrib = GetFileAttributes("..\\media\\"); if ((dwAttrib == INVALID_FILE_ATTRIBUTES) || ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) == 0) { MessageBox(NULL, "Media files not found!\n\nPlease check the readme on how to get the media files.", "Cauldron Panic!", MB_ICONERROR); exit(0); } // Create Device // #ifdef _DEBUG bool cpuValidationLayerEnabled = true; bool gpuValidationLayerEnabled = false; #else bool cpuValidationLayerEnabled = false; bool gpuValidationLayerEnabled = false; #endif // Create the device InstanceProperties ip; ip.Init(); m_Device.SetEssentialInstanceExtensions(cpuValidationLayerEnabled, gpuValidationLayerEnabled, &ip); // Create instance VkInstance vulkanInstance; VkPhysicalDevice physicalDevice; CreateInstance("SssrSample", "Cauldron", &vulkanInstance, &physicalDevice, &ip); DeviceProperties dp; dp.Init(physicalDevice); m_Device.SetEssentialDeviceExtensions(&dp); dp.AddDeviceExtensionName(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME); bool addedSubgroupSizeControl = dp.AddDeviceExtensionName(VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME); VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroupSizeControlFeatures = {}; subgroupSizeControlFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT; subgroupSizeControlFeatures.pNext = nullptr; subgroupSizeControlFeatures.subgroupSizeControl = true; subgroupSizeControlFeatures.computeFullSubgroups = false; if (addedSubgroupSizeControl) { dp.SetNewNext(&subgroupSizeControlFeatures); } // Create device m_Device.OnCreateEx(vulkanInstance, physicalDevice, hWnd, &dp); m_Device.CreatePipelineCache(); // Init the shader compiler InitDirectXCompiler(); CreateShaderCache(); // Create Swapchain // uint32_t dwNumberOfBackBuffers = 2; m_SwapChain.OnCreate(&m_Device, dwNumberOfBackBuffers, hWnd); // Create a instance of the renderer and initialize it, we need to do that for each GPU // m_Node = new SampleRenderer(); m_Node->OnCreate(&m_Device, &m_SwapChain); // init GUI (non gfx stuff) // ImGUI_Init((void*)hWnd); // Init Camera, looking at the origin // m_Yaw = 0.0f; m_Pitch = 0.0f; m_Distance = 3.5f; // init GUI state m_State.toneMapper = 2; m_State.skyDomeType = 1; m_State.exposure = 1.0f; m_State.emmisiveFactor = 1.0f; m_State.iblFactor = 1.0f; m_State.bDrawBoundingBoxes = false; m_State.bDrawLightFrustum = false; m_State.bDrawBloom = false; m_State.camera.LookAt(m_Yaw, m_Pitch, m_Distance, XMVectorSet(0, 0, 0, 0)); m_State.lightIntensity = 10.f; m_State.lightCamera.SetFov(XM_PI / 6.0f, 1024, 1024, 0.1f, 20.0f); m_State.lightCamera.LookAt(XM_PI / 2.0f, 0.58f, 3.5f, XMVectorSet(0, 0, 0, 0)); m_State.lightColor = XMFLOAT3(1, 1, 1); m_State.targetFrametime = 0; m_State.temporalStability = 0.99f; m_State.temporalVarianceThreshold = 0.002f; m_State.maxTraversalIterations = 128; m_State.mostDetailedDepthHierarchyMipLevel = 1; m_State.depthBufferThickness = 0.015f; m_State.minTraversalOccupancy = 4; m_State.samplesPerQuad = 1; m_State.bEnableVarianceGuidedTracing = true; m_State.bShowIntersectionResults = false; m_State.roughnessThreshold = 0.2f; m_State.showReflectionTarget = false; m_State.bDrawScreenSpaceReflections = true; LoadScene(m_selectedScene); } //-------------------------------------------------------------------------------------- // // OnDestroy // //-------------------------------------------------------------------------------------- void SssrSample::OnDestroy() { ImGUI_Shutdown(); m_Device.GPUFlush(); // Fullscreen state should always be false before exiting the app. m_SwapChain.SetFullScreen(false); m_Node->UnloadScene(); m_Node->OnDestroyWindowSizeDependentResources(); m_Node->OnDestroy(); delete m_Node; m_SwapChain.OnDestroyWindowSizeDependentResources(); m_SwapChain.OnDestroy(); //shut down the shader compiler DestroyShaderCache(&m_Device); m_Device.DestroyPipelineCache(); if (m_pGltfLoader) { delete m_pGltfLoader; m_pGltfLoader = NULL; } m_Device.OnDestroy(); } //-------------------------------------------------------------------------------------- // // OnEvent, forward Win32 events to ImGUI // //-------------------------------------------------------------------------------------- bool SssrSample::OnEvent(MSG msg) { if (ImGUI_WndProcHandler(msg.hwnd, msg.message, msg.wParam, msg.lParam)) return true; return true; } //-------------------------------------------------------------------------------------- // // SetFullScreen // //-------------------------------------------------------------------------------------- void SssrSample::SetFullScreen(bool fullscreen) { m_Device.GPUFlush(); m_SwapChain.SetFullScreen(fullscreen); } void SssrSample::OnParseCommandLine(LPSTR lpCmdLine, uint32_t* pWidth, uint32_t* pHeight, bool* pbFullScreen) { // First load configuration std::ifstream f("config.json"); if (!f) { MessageBox(NULL, "Config file not found!\n", "Cauldron Panic!", MB_ICONERROR); exit(-1); } f >> m_JsonConfigFile; // Parse command line and override the config file try { if (strlen(lpCmdLine) > 0) { auto j3 = json::parse(lpCmdLine); m_JsonConfigFile.merge_patch(j3); } } catch (json::parse_error) { Trace("Error parsing commandline\n"); exit(0); } // Set values *pWidth = m_JsonConfigFile.value("width", 1920); *pHeight = m_JsonConfigFile.value("height", 1080); *pbFullScreen = m_JsonConfigFile.value("fullScreen", false); m_State.isBenchmarking = m_JsonConfigFile.value("benchmark", false); } void SssrSample::BuildUI() { ImGuiStyle& style = ImGui::GetStyle(); style.FrameBorderSize = 1.0f; bool opened = true; ImGui::Begin("FidelityFX SSSR", &opened); if (ImGui::CollapsingHeader("Info", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Resolution : %ix%i", m_Width, m_Height); } if (ImGui::CollapsingHeader("Controls", ImGuiTreeNodeFlags_DefaultOpen)) { char* cameraControl[] = { "WASD", "Orbit", "cam #0", "cam #1", "cam #2", "cam #3" , "cam #4", "cam #5" }; if (m_CameraControlSelected >= m_pGltfLoader->m_cameras.size() + 2) m_CameraControlSelected = 0; ImGui::Combo("Camera", &m_CameraControlSelected, cameraControl, (int)(m_pGltfLoader->m_cameras.size() + 2)); } if (ImGui::CollapsingHeader("Reflections", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Checkbox("Draw Screen Space Reflections", &m_State.bDrawScreenSpaceReflections); ImGui::Checkbox("Show Reflection Target", &m_State.showReflectionTarget); ImGui::Checkbox("Show Intersection Results", &m_State.bShowIntersectionResults); ImGui::SliderFloat("Target Frametime in ms", &m_State.targetFrametime, 0.0f, 50.0f); ImGui::SliderInt("Max Traversal Iterations", &m_State.maxTraversalIterations, 0, 256); ImGui::SliderInt("Min Traversal Occupancy", &m_State.minTraversalOccupancy, 0, 32); ImGui::SliderInt("Most Detailed Level", &m_State.mostDetailedDepthHierarchyMipLevel, 0, 5); ImGui::SliderFloat("Depth Buffer Thickness", &m_State.depthBufferThickness, 0.0f, 0.03f); ImGui::SliderFloat("Roughness Threshold", &m_State.roughnessThreshold, 0.0f, 1.f); ImGui::SliderFloat("Temporal Stability", &m_State.temporalStability, 0.0f, 1.0f); ImGui::SliderFloat("Temporal Variance Threshold", &m_State.temporalVarianceThreshold, 0.0f, 0.01f); ImGui::Checkbox("Enable Variance Guided Tracing", &m_State.bEnableVarianceGuidedTracing); ImGui::Text("Samples Per Quad"); ImGui::SameLine(); ImGui::RadioButton("1", &m_State.samplesPerQuad, 1); ImGui::SameLine(); ImGui::RadioButton("2", &m_State.samplesPerQuad, 2); ImGui::SameLine(); ImGui::RadioButton("4", &m_State.samplesPerQuad, 4); ImGui::Value("Tile Classification Elapsed Time", 1000 * m_State.tileClassificationTime, "%.1f us"); ImGui::Value("Intersection Elapsed Time", 1000 * m_State.intersectionTime, "%.1f us"); ImGui::Value("Denoising Elapsed Time", 1000 * m_State.denoisingTime, "%.1f us"); } if (ImGui::CollapsingHeader("Profiler")) { const std::vector<TimeStamp>& timeStamps = m_Node->GetTimingValues(); if (timeStamps.size() > 0) { for (uint32_t i = 0; i < timeStamps.size(); i++) { ImGui::Text("%-22s: %7.1f", timeStamps[i].m_label.c_str(), timeStamps[i].m_microseconds); } //scrolling data and average computing static float values[128]; values[127] = timeStamps.back().m_microseconds; for (uint32_t i = 0; i < 128 - 1; i++) { values[i] = values[i + 1]; } ImGui::PlotLines("", values, 128, 0, "GPU frame time (us)", 0.0f, 30000.0f, ImVec2(0, 80)); } } ImGui::Text("'X' to show/hide GUI"); ImGui::End(); } void SssrSample::HandleInput() { // If the mouse was not used by the GUI then it's for the camera // ImGuiIO& io = ImGui::GetIO(); static std::chrono::system_clock::time_point last = std::chrono::system_clock::now(); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::duration<double> diff = now - last; last = now; io.DeltaTime = static_cast<float>(diff.count()); if (ImGui::IsKeyPressed('X')) { m_bShowUI = !m_bShowUI; ShowCursor(m_bShowUI); } if (io.WantCaptureMouse == false || !m_bShowUI) { if ((io.KeyCtrl == false) && (io.MouseDown[0] == true)) { m_Yaw -= io.MouseDelta.x / 100.f; m_Pitch += io.MouseDelta.y / 100.f; } // Choose camera movement depending on setting // if (m_CameraControlSelected == 0) { // WASD // m_State.camera.UpdateCameraWASD(m_Yaw, m_Pitch, io.KeysDown, io.DeltaTime); } else if (m_CameraControlSelected == 1) { // Orbiting // m_Distance -= (float)io.MouseWheel / 3.0f; m_Distance = std::max<float>(m_Distance, 0.1f); bool panning = (io.KeyCtrl == true) && (io.MouseDown[0] == true); m_State.camera.UpdateCameraPolar(m_Yaw, m_Pitch, panning ? -io.MouseDelta.x / 100.0f : 0.0f, panning ? io.MouseDelta.y / 100.0f : 0.0f, m_Distance); } else { // Use a camera from the GLTF // m_pGltfLoader->GetCamera(m_CameraControlSelected - 2, &m_State.camera); m_Yaw = m_State.camera.GetYaw(); m_Pitch = m_State.camera.GetPitch(); } } } void SssrSample::LoadScene(int sceneIndex) { json scene = m_JsonConfigFile["scenes"][sceneIndex]; if (m_pGltfLoader != NULL) { //free resources, unload the current scene, and load new scene... m_Device.GPUFlush(); m_Node->UnloadScene(); m_Node->OnDestroyWindowSizeDependentResources(); m_Node->OnDestroy(); m_pGltfLoader->Unload(); m_Node->OnCreate(&m_Device, &m_SwapChain); m_Node->OnCreateWindowSizeDependentResources(&m_SwapChain, m_Width, m_Height); } delete(m_pGltfLoader); m_pGltfLoader = new GLTFCommon(); if (m_pGltfLoader->Load(scene["directory"], scene["filename"]) == false) { MessageBox(NULL, "The selected model couldn't be found, please check the documentation", "Cauldron Panic!", MB_ICONERROR); exit(0); } // Load the UI settings, and also some defaults cameras and lights, in case the GLTF has none { #define LOAD(j, key, val) val = j.value(key, val) // global settings LOAD(scene, "toneMapper", m_State.toneMapper); LOAD(scene, "skyDomeType", m_State.skyDomeType); LOAD(scene, "exposure", m_State.exposure); LOAD(scene, "iblFactor", m_State.iblFactor); LOAD(scene, "emmisiveFactor", m_State.emmisiveFactor); LOAD(scene, "skyDomeType", m_State.skyDomeType); // default light m_State.lightIntensity = scene.value("intensity", 1.0f); // default camera (in case the gltf has none) json camera = scene["camera"]; LOAD(camera, "yaw", m_Yaw); LOAD(camera, "pitch", m_Pitch); LOAD(camera, "distance", m_Distance); XMVECTOR lookAt = GetVector(GetElementJsonArray(camera, "lookAt", { 0.0, 0.0, 0.0 })); m_State.camera.LookAt(m_Yaw, m_Pitch, m_Distance, lookAt); // set benchmarking state if enabled if (m_State.isBenchmarking) { BenchmarkConfig(scene["BenchmarkSettings"], -1, m_pGltfLoader); } // indicate the mainloop we started loading a GLTF and it needs to load the rest (textures and geometry) m_bLoadingScene = true; } } //-------------------------------------------------------------------------------------- // // OnResize // //-------------------------------------------------------------------------------------- void SssrSample::OnResize(uint32_t width, uint32_t height) { if (m_Width != width || m_Height != height) { // Flush GPU // m_Device.GPUFlush(); // If resizing but no minimizing // if (m_Width > 0 && m_Height > 0) { if (m_Node != NULL) { m_Node->OnDestroyWindowSizeDependentResources(); } m_SwapChain.OnDestroyWindowSizeDependentResources(); } m_Width = width; m_Height = height; // if resizing but not minimizing the recreate it with the new size // if (m_Width > 0 && m_Height > 0) { m_SwapChain.OnCreateWindowSizeDependentResources(m_Width, m_Height, false, DISPLAYMODE_SDR); if (m_Node != NULL) { m_Node->OnCreateWindowSizeDependentResources(&m_SwapChain, m_Width, m_Height); } } } m_State.camera.SetFov(XM_PI / 4, m_Width, m_Height, 0.1f, 1000.0f); } //-------------------------------------------------------------------------------------- // // OnRender, updates the state from the UI, animates, transforms and renders the scene // //-------------------------------------------------------------------------------------- void SssrSample::OnRender() { // Get timings // double timeNow = MillisecondsNow(); m_DeltaTime = timeNow - m_LastFrameTime; m_LastFrameTime = timeNow; // Build UI and set the scene state. Note that the rendering of the UI happens later. // ImGUI_UpdateIO(); ImGui::NewFrame(); if (m_bLoadingScene) { static int loadingStage = 0; // LoadScene needs to be called a number of times, the scene is not fully loaded until it returns 0 // This is done so we can display a progress bar when the scene is loading loadingStage = m_Node->LoadScene(m_pGltfLoader, loadingStage); if (loadingStage == 0) { m_Time = 0; m_bLoadingScene = false; } } else if (m_pGltfLoader && m_State.isBenchmarking) { const std::vector<TimeStamp>& timeStamps = m_Node->GetTimingValues(); const std::string* screenshotName; m_Time = BenchmarkLoop(timeStamps, &m_State.camera, &screenshotName); } else { if (m_bShowUI) { BuildUI(); } if (!m_bLoadingScene) { HandleInput(); } } // Set animation time // if (m_bPlay) { m_Time += (float)m_DeltaTime / 1000.0f; } // Animate and transform the scene // if (m_pGltfLoader) { m_pGltfLoader->SetAnimationTime(0, m_Time); m_pGltfLoader->TransformScene(0, XMMatrixIdentity()); } m_State.time = m_Time; // Do Render frame using AFR // m_Node->OnRender(&m_State, &m_SwapChain); m_SwapChain.Present(); } } //-------------------------------------------------------------------------------------- // // WinMain // //-------------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { LPCSTR Name = "FidelityFX Stochastic Screen Space Reflection Sample VK v1.2"; // create new sample return RunFramework(hInstance, lpCmdLine, nCmdShow, new SSSR_SAMPLE_VK::SssrSample(Name)); }
31.064799
152
0.648664
TheozZhh79
4ac53eaffb31abb49c585970a59e160b847f94d3
10,051
cpp
C++
logdevice/common/test/benchmarks/SequencerBatchingBenchmark.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
1
2019-12-18T09:07:45.000Z
2019-12-18T09:07:45.000Z
logdevice/common/test/benchmarks/SequencerBatchingBenchmark.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
null
null
null
logdevice/common/test/benchmarks/SequencerBatchingBenchmark.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <atomic> #include <chrono> #include <thread> #include <vector> #include <folly/Benchmark.h> #include <folly/ScopeGuard.h> #include <folly/Singleton.h> #include <folly/container/F14Map.h> #include "logdevice/common/Appender.h" #include "logdevice/common/Processor.h" #include "logdevice/common/Semaphore.h" #include "logdevice/common/Sender.h" #include "logdevice/common/Sequencer.h" #include "logdevice/common/SequencerBatching.h" #include "logdevice/common/Timer.h" #include "logdevice/common/Worker.h" #include "logdevice/common/configuration/UpdateableConfig.h" #include "logdevice/common/debug.h" #include "logdevice/common/test/TestUtil.h" using namespace facebook::logdevice; using namespace std::chrono_literals; using namespace std::chrono; namespace { class SequencerBatchingBenchmark { public: struct Params { size_t num_appends; size_t nworkers{64}; size_t nwriters{32}; size_t append_size{140}; // by defautl time trigger is not used std::chrono::milliseconds time_trigger{10000}; // by default batch 50 records ssize_t size_trigger{7000}; Compression compression{Compression::NONE}; // how many appends can be in-flight for each writer size_t writer_max_in_flight{1000}; }; struct TestStats { std::atomic<size_t> append_started{0}; std::atomic<size_t> append_received{0}; std::atomic<size_t> append_success{0}; std::atomic<size_t> append_failed{0}; }; explicit SequencerBatchingBenchmark(Params params); ~SequencerBatchingBenchmark(); // block until the num_appends finished appending void run(); bool shouldStop() const { const size_t num_success = test_stats_.append_success.load(); return num_success > 0 && num_success >= params_.num_appends; } void shutdown(); std::unique_ptr<Appender> createAppender(size_t writer_id, logid_t logid); TestStats test_stats_; const Params params_; struct WriterState { explicit WriterState(size_t writer_max_in_flight) : tickets(writer_max_in_flight) {} std::atomic<size_t> appends_finished{0}; Semaphore tickets; }; const std::string payload_; // settings used to create the processor and sequencer batching Settings settings_; std::shared_ptr<UpdateableConfig> updateable_config_; std::vector<std::thread> writer_threads_; std::unordered_map<size_t, WriterState> writer_states_; // StatsHolder stats_; std::shared_ptr<Processor> processor_; void writerThread(size_t writer_id); PayloadHolder genPayload(); }; class MockSequencerBatching : public SequencerBatching { public: using MockSender = SenderTestProxy<MockSequencerBatching>; MockSequencerBatching(SequencerBatchingBenchmark* test, Processor* processor) : SequencerBatching(processor), test_(test) { sender_ = std::make_unique<MockSender>(this); ld_check(test != nullptr); } folly::Optional<APPENDED_Header> runBufferedAppend(logid_t, AppendAttributes, const Payload&, InternalAppendRequest::Callback callback, APPEND_flags_t, int, uint32_t, uint32_t) override { Worker::onThisThread()->addWithPriority( [callback]() { callback(Status::OK, lsn_t(1), NodeID(), RecordTimestamp::zero()); }, folly::Executor::HI_PRI); // append is accepted; return folly::none; } int sendMessageImpl(std::unique_ptr<Message>&& msg, const Address&, BWAvailableCallback*, SocketCallback*) { ld_check(msg->type_ == MessageType::APPENDED); APPENDED_Message* reply = dynamic_cast<APPENDED_Message*>(msg.get()); ld_check(reply != nullptr); const auto writer_id = reply->header_.rqid.val(); ld_check(writer_id < test_->params_.nwriters); auto& w_st = test_->writer_states_.at(writer_id); if (reply->header_.status == Status::OK) { ++test_->test_stats_.append_success; ++w_st.appends_finished; } else { ++test_->test_stats_.append_failed; } w_st.tickets.post(); return 0; } bool canSendToImpl(const Address&, TrafficClass, BWAvailableCallback&) { return true; } private: SequencerBatchingBenchmark* const test_; }; class TestAppenderRequest : public Request { public: explicit TestAppenderRequest(SequencerBatchingBenchmark* test, size_t writer_id, logid_t log_id) : Request(RequestType::TEST_APPENDER_REQUEST), test_(test), writer_id_(writer_id), log_id_(log_id) {} Request::Execution execute() override { auto& w_st = test_->writer_states_.at(writer_id_); if (test_->shouldStop()) { ++test_->test_stats_.append_failed; w_st.tickets.post(); return Execution::COMPLETE; } auto appender = test_->createAppender(writer_id_, log_id_); auto res = test_->processor_->sequencerBatching().buffer(log_id_, appender); if (res) { ++test_->test_stats_.append_received; } else { RATELIMIT_INFO(std::chrono::seconds(2), 2, "Appender for log %lu from writer %lu is not bufferd.", log_id_.val(), writer_id_); ++test_->test_stats_.append_failed; w_st.tickets.post(); } return Execution::COMPLETE; } private: SequencerBatchingBenchmark* const test_; const size_t writer_id_; const logid_t log_id_; }; SequencerBatchingBenchmark::SequencerBatchingBenchmark(Params params) : params_(std::move(params)), payload_('c', params_.append_size), settings_(create_default_settings<Settings>()) { ld_check(params_.num_appends > 0); ld_check(params_.nwriters > 0); // change settings to reflect the benchmark params settings_.server = true; settings_.num_workers = params_.nworkers; settings_.sequencer_batching = true; settings_.sequencer_batching_time_trigger = params_.time_trigger; settings_.sequencer_batching_size_trigger = params_.size_trigger; updateable_config_ = std::make_shared<UpdateableConfig>( Configuration::fromJsonFile(TEST_CONFIG_FILE("sequencer_test.conf"))); processor_ = make_test_processor( settings_, updateable_config_, /*stats=*/nullptr, NodeID(1, 1)); ld_check(processor_ != nullptr); processor_->setSequencerBatching( std::make_unique<MockSequencerBatching>(this, processor_.get())); // pre-allocate writer states for (size_t i = 0; i < params_.nwriters; ++i) { auto res = writer_states_.emplace( std::piecewise_construct, std::forward_as_tuple(i), std::forward_as_tuple(params_.writer_max_in_flight)); ld_check(res.second); } } PayloadHolder SequencerBatchingBenchmark::genPayload() { return PayloadHolder( Payload(payload_.data(), payload_.size()), PayloadHolder::UNOWNED); } std::unique_ptr<Appender> SequencerBatchingBenchmark::createAppender(size_t writer_id, logid_t log_id) { return std::make_unique<Appender>(nullptr, nullptr, std::chrono::milliseconds(1000), request_id_t(writer_id), STORE_flags_t(0), log_id, AppendAttributes(), genPayload(), ClientID(), EPOCH_MIN, params_.append_size, LSN_INVALID); } void SequencerBatchingBenchmark::writerThread(size_t writer_id) { auto& w_st = writer_states_.at(writer_id); while (!shouldStop()) { // get an inflight ticket w_st.tickets.wait(); ++test_stats_.append_started; // pick a logid from [1, 100] logid_t log_id = logid_t(folly::Random::rand32() % 100 + 1); std::unique_ptr<Request> rq = std::make_unique<TestAppenderRequest>(this, writer_id, log_id); int rv = processor_->postRequest(rq); if (rv != 0) { ++test_stats_.append_failed; w_st.tickets.post(); } } ld_info("Writer %lu finished processing of %lu appends successfuly.", writer_id, w_st.appends_finished.load()); } SequencerBatchingBenchmark::~SequencerBatchingBenchmark() {} void SequencerBatchingBenchmark::run() { for (size_t i = 0; i < params_.nwriters; i++) { writer_threads_.emplace_back(std::thread([i, this]() { writerThread(i); })); } for (std::thread& t : writer_threads_) { t.join(); } } void SequencerBatchingBenchmark::shutdown() { gracefully_shutdown_processor(processor_.get()); processor_.reset(); // print benchmark run stats ld_info("\nAppend started: %lu, append received: %lu.\n" "Append success: %lu, append failed: %lu.\n", test_stats_.append_started.load(), test_stats_.append_received.load(), test_stats_.append_success.load(), test_stats_.append_failed.load()); } BENCHMARK_MULTI(LDSequencerBatchingBenchmark, n) { SequencerBatchingBenchmark::Params params{n}; std::unique_ptr<SequencerBatchingBenchmark> b; BENCHMARK_SUSPEND { b = std::make_unique<SequencerBatchingBenchmark>(params); ld_info("n appends = %u", n); } b->run(); BENCHMARK_SUSPEND { b->shutdown(); } return b->test_stats_.append_success.load(); } } // namespace #ifndef BENCHMARK_BUNDLE int main(int argc, char** argv) { dbg::currentLevel = dbg::Level::ERROR; folly::SingletonVault::singleton()->registrationComplete(); gflags::ParseCommandLineFlags(&argc, &argv, true); folly::runBenchmarks(); return 0; } #endif
31.117647
80
0.662521
majra20
4ac771e3679ec0f59d3c254c288ae677afb0ab4b
1,345
hpp
C++
routing/checkpoints.hpp
Barysman/omim
469632c879027ec38278ebda699415c28dbd79e0
[ "Apache-2.0" ]
1
2021-07-02T08:45:02.000Z
2021-07-02T08:45:02.000Z
routing/checkpoints.hpp
Barysman/omim
469632c879027ec38278ebda699415c28dbd79e0
[ "Apache-2.0" ]
1
2020-06-15T15:16:23.000Z
2020-06-15T15:59:19.000Z
routing/checkpoints.hpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
1
2018-10-01T10:27:21.000Z
2018-10-01T10:27:21.000Z
#pragma once #include "geometry/point2d.hpp" #include <string> #include <utility> #include <vector> namespace routing { class Checkpoints final { public: Checkpoints() = default; Checkpoints(m2::PointD const & start, m2::PointD const & finish) : m_points({start, finish}) {} explicit Checkpoints(std::vector<m2::PointD> && points); m2::PointD const & GetStart() const { return m_points.front(); } m2::PointD const & GetFinish() const { return m_points.back(); } std::vector<m2::PointD> const & GetPoints() const { return m_points; } size_t GetPassedIdx() const { return m_passedIdx; } void SetPointFrom(m2::PointD const & point); m2::PointD const & GetPoint(size_t pointIdx) const; m2::PointD const & GetPointFrom() const; m2::PointD const & GetPointTo() const; size_t GetNumSubroutes() const { return m_points.size() - 1; } bool IsFinished() const { return m_passedIdx >= GetNumSubroutes(); } void PassNextPoint(); private: // m_points contains start, finish and intermediate points. std::vector<m2::PointD> m_points = {m2::PointD::Zero(), m2::PointD::Zero()}; // m_passedIdx is the index of the checkpoint by which the user passed by. // By default, user has passed 0, it is start point. size_t m_passedIdx = 0; }; std::string DebugPrint(Checkpoints const & checkpoints); } // namespace routing
31.27907
97
0.705576
Barysman
4ac7c3c55c26329ff2bdc88a48551c5760a2c3c6
54
cpp
C++
templates/src/bar.cpp
mcqueen256/mql4dllft
2b918da25efa8056eca967e4d40d07487f030ee8
[ "MIT" ]
null
null
null
templates/src/bar.cpp
mcqueen256/mql4dllft
2b918da25efa8056eca967e4d40d07487f030ee8
[ "MIT" ]
11
2017-07-11T22:26:44.000Z
2017-07-20T04:14:54.000Z
templates/src/bar.cpp
mcqueen256/mql4dllft
2b918da25efa8056eca967e4d40d07487f030ee8
[ "MIT" ]
null
null
null
#include "Bar.hpp" Bar::Bar() { } Bar::~Bar() { }
6
18
0.462963
mcqueen256
4acab282d778b0dc51a38c4f29fc67826ab297e7
739
cpp
C++
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
AKC23/AUST
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
[ "MIT" ]
null
null
null
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
AKC23/AUST
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
[ "MIT" ]
null
null
null
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
AKC23/AUST
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
[ "MIT" ]
null
null
null
#include <stdio.h> #include <bits/stdc++.h> #include <math.h> using namespace std; double f(float x) { // return (x*x*x - x -1); return (tan(x)+x); } int main() { float a = 2, b = 2.1; float root; float f0, f1, f2; if (f(a) * f(b) > 0) { printf("wrong guess"); } do { f1 = f(a); f2 = f(b); root = (a + b) / 2; f0 = f(root); if (f1 * f0 < 0) { b = root; // f2 = f0; } else { a = root; // f1 = f0; } printf("\nRoot = %f", root); } while (fabs(f(root)) >= 0.01); printf("\nRoot = %f", root); }
16.065217
37
0.345061
AKC23
4acae05e90a409aabe41ac3c578007667de6f69d
1,030
cc
C++
labs/evthrift/thrift_server.cc
sandeepsgangwar/evpp
38f0e3e775072a268060a36b6c871a8475ed90bc
[ "BSD-3-Clause" ]
null
null
null
labs/evthrift/thrift_server.cc
sandeepsgangwar/evpp
38f0e3e775072a268060a36b6c871a8475ed90bc
[ "BSD-3-Clause" ]
null
null
null
labs/evthrift/thrift_server.cc
sandeepsgangwar/evpp
38f0e3e775072a268060a36b6c871a8475ed90bc
[ "BSD-3-Clause" ]
3
2019-04-24T08:51:27.000Z
2019-09-04T06:40:00.000Z
#include "thrift_server.h" namespace evthrift { ThriftServer::~ThriftServer() {} void ThriftServer::serve() { server_.SetMessageCallback(std::bind(&ThriftServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2)); server_.Init(); server_.Start(); } void ThriftServer::stop() { server_.Stop(); } void ThriftServer::OnConnection(const evpp::TCPConnPtr& conn) { if (conn->IsConnected()) { ThriftConnectionPtr ptr(new ThriftConn(this, conn)); conn->set_context(evpp::Any(ptr)); } else { conn->set_context(evpp::Any()); } } void ThriftServer::OnMessage(const evpp::TCPConnPtr& conn, evpp::Buffer* buffer) { const evpp::Any& a = conn->context(); if (a.IsEmpty()) { EVPP_LOG_ERROR << "The evpp::TCPConn is not assoiated with a Thrift Connection"; return; } ThriftConnectionPtr ptr = a.Get<ThriftConnectionPtr>(); ptr->OnMessage(conn, buffer); } }
26.410256
88
0.605825
sandeepsgangwar
4acb11d69ee5e8f334f47fafde82ab5c91ede3e0
7,835
cc
C++
packager/media/base/http_key_fetcher.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-13T17:47:27.000Z
2021-06-17T15:00:16.000Z
packager/media/base/http_key_fetcher.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2022-02-10T12:40:20.000Z
2022-02-10T12:40:20.000Z
packager/media/base/http_key_fetcher.cc
koln67/shaka-packager
5b9fd409a5de502e8af2e46ee12840bd2226874d
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2022-01-29T15:55:14.000Z
2022-01-29T15:55:14.000Z
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/base/http_key_fetcher.h" #include <curl/curl.h> #include <gflags/gflags.h> #include "packager/base/logging.h" #include "packager/base/strings/string_number_conversions.h" #include "packager/base/strings/stringprintf.h" #include "packager/base/synchronization/lock.h" DEFINE_bool(disable_peer_verification, false, "Disable peer verification. This is needed to talk to servers " "without valid certificates."); namespace shaka { namespace { const char kUserAgentString[] = "shaka-packager-http_fetcher/1.0"; const char kSoapActionHeader[] = "SOAPAction: \"http://schemas.microsoft.com/DRM/2007/03/protocols/" "AcquirePackagingData\""; const char kXmlContentTypeHeader[] = "Content-Type: text/xml; charset=UTF-8"; const char kJsonContentTypeHeader[] = "Content-Type: application/json"; const int kMinLogLevelForCurlDebugFunction = 2; int CurlDebugFunction(CURL* /* handle */, curl_infotype type, const char* data, size_t size, void* /* userptr */) { const char* type_text; int log_level = kMinLogLevelForCurlDebugFunction; switch (type) { case CURLINFO_TEXT: type_text = "== Info"; log_level = kMinLogLevelForCurlDebugFunction + 1; break; case CURLINFO_HEADER_IN: type_text = "<= Recv header"; log_level = kMinLogLevelForCurlDebugFunction; break; case CURLINFO_HEADER_OUT: type_text = "=> Send header"; log_level = kMinLogLevelForCurlDebugFunction; break; case CURLINFO_DATA_IN: type_text = "<= Recv data"; log_level = kMinLogLevelForCurlDebugFunction + 1; break; case CURLINFO_DATA_OUT: type_text = "=> Send data"; log_level = kMinLogLevelForCurlDebugFunction + 1; break; case CURLINFO_SSL_DATA_IN: type_text = "<= Recv SSL data"; log_level = kMinLogLevelForCurlDebugFunction + 2; break; case CURLINFO_SSL_DATA_OUT: type_text = "=> Send SSL data"; log_level = kMinLogLevelForCurlDebugFunction + 2; break; default: // Ignore other debug data. return 0; } VLOG(log_level) << "\n\n" << type_text << " (0x" << std::hex << size << std::dec << " bytes)" << "\n" << std::string(data, size) << "\nHex Format: \n" << base::HexEncode(data, size); return 0; } // Scoped CURL implementation which cleans up itself when goes out of scope. class ScopedCurl { public: ScopedCurl() { ptr_ = curl_easy_init(); } ~ScopedCurl() { if (ptr_) curl_easy_cleanup(ptr_); } CURL* get() { return ptr_; } private: CURL* ptr_; DISALLOW_COPY_AND_ASSIGN(ScopedCurl); }; size_t AppendToString(char* ptr, size_t size, size_t nmemb, std::string* response) { DCHECK(ptr); DCHECK(response); const size_t total_size = size * nmemb; response->append(ptr, total_size); return total_size; } class LibCurlInitializer { public: LibCurlInitializer() : initialized_(false) { base::AutoLock lock(lock_); if (!initialized_) { curl_global_init(CURL_GLOBAL_DEFAULT); initialized_ = true; } } ~LibCurlInitializer() { base::AutoLock lock(lock_); if (initialized_) { curl_global_cleanup(); initialized_ = false; } } private: base::Lock lock_; bool initialized_; DISALLOW_COPY_AND_ASSIGN(LibCurlInitializer); }; } // namespace namespace media { HttpKeyFetcher::HttpKeyFetcher() : timeout_in_seconds_(0) {} HttpKeyFetcher::HttpKeyFetcher(uint32_t timeout_in_seconds) : timeout_in_seconds_(timeout_in_seconds) {} HttpKeyFetcher::~HttpKeyFetcher() {} Status HttpKeyFetcher::FetchKeys(const std::string& url, const std::string& request, std::string* response) { return Post(url, request, response); } Status HttpKeyFetcher::Get(const std::string& path, std::string* response) { return FetchInternal(GET, path, "", response); } Status HttpKeyFetcher::Post(const std::string& path, const std::string& data, std::string* response) { return FetchInternal(POST, path, data, response); } Status HttpKeyFetcher::FetchInternal(HttpMethod method, const std::string& path, const std::string& data, std::string* response) { DCHECK(method == GET || method == POST); static LibCurlInitializer lib_curl_initializer; ScopedCurl scoped_curl; CURL* curl = scoped_curl.get(); if (!curl) { LOG(ERROR) << "curl_easy_init() failed."; return Status(error::HTTP_FAILURE, "curl_easy_init() failed."); } response->clear(); curl_easy_setopt(curl, CURLOPT_URL, path.c_str()); curl_easy_setopt(curl, CURLOPT_USERAGENT, kUserAgentString); curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout_in_seconds_); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, AppendToString); curl_easy_setopt(curl, CURLOPT_WRITEDATA, response); if (FLAGS_disable_peer_verification) curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); if (!client_cert_private_key_file_.empty() && !client_cert_file_.empty()) { // Some PlayReady packaging servers only allow connects via HTTPS with // client certificates. curl_easy_setopt(curl, CURLOPT_SSLKEY, client_cert_private_key_file_.data()); if (!client_cert_private_key_password_.empty()) { curl_easy_setopt(curl, CURLOPT_KEYPASSWD, client_cert_private_key_password_.data()); } curl_easy_setopt(curl, CURLOPT_SSLKEYTYPE, "PEM"); curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM"); curl_easy_setopt(curl, CURLOPT_SSLCERT, client_cert_file_.data()); } if (!ca_file_.empty()) { // Host validation needs to be off when using self-signed certificates. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(curl, CURLOPT_CAINFO, ca_file_.data()); } if (method == POST) { curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size()); curl_slist* chunk = nullptr; if (data.find("soap:Envelope") != std::string::npos) { // Adds Http headers for SOAP requests. chunk = curl_slist_append(chunk, kXmlContentTypeHeader); chunk = curl_slist_append(chunk, kSoapActionHeader); } else { chunk = curl_slist_append(chunk, kJsonContentTypeHeader); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); } if (VLOG_IS_ON(kMinLogLevelForCurlDebugFunction)) { curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, CurlDebugFunction); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); } CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { std::string error_message = base::StringPrintf( "curl_easy_perform() failed: %s.", curl_easy_strerror(res)); if (res == CURLE_HTTP_RETURNED_ERROR) { long response_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); error_message += base::StringPrintf(" Response code: %ld.", response_code); } LOG(ERROR) << error_message; return Status( res == CURLE_OPERATION_TIMEDOUT ? error::TIME_OUT : error::HTTP_FAILURE, error_message); } return Status::OK; } } // namespace media } // namespace shaka
32.110656
84
0.66739
koln67
4acb9e0c0b5a1b2e0b18274d5acb0f2cc60c828e
24,090
cpp
C++
Products/DiffWorks/diffworks.cpp
TrevorDArcyEvans/DivingMagpieSoftware
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
1
2021-05-27T10:27:25.000Z
2021-05-27T10:27:25.000Z
Products/DiffWorks/diffworks.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
Products/DiffWorks/diffworks.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------- // // Filename: DiffWorks.cpp // Description: This defines the interface to SolidWorks and the // initialization routines for the DLL. // // ------------------------------------------------------------------- // pre-compiled headers #include "stdafx.h" // MFC includes #include <afxdllx.h> #include "DiffWorks.h" #include "resource.h" #include "SldWorks.h" #include "ExampleApp.h" #include <tchar.h> #include <shlwapi.h> #include "SLogError.h" #include "DMS_Comm.h" #include "DMS_Comm_i.c" #include "DMS_DiffWks.h" #include "DMS_DiffWks_i.c" #include "DMS_ProgPipe.h" #include "DMS_ProgPipe_i.c" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //------------------------------------------------------------------------ // the application object CDiffWorksApp* TheApplication = NULL; static AFX_EXTENSION_MODULE DiffWorksDLL = { NULL, NULL }; //------------------------------------------------------------------------ HRESULT DW_GetMass ( CString Part, double* Mass, double* Volume, double* Area ); HRESULT DW_Compare ( CString OriginalPart, CString ChangedPart , CString DisplayPart , double Transparency, long Colour ); void DllExport DW_CompareFiles(void); void DllExport DW_ShowLast(void); void DllExport DW_Help(void); void DW_CheckRegistered(bool bShowDialog); int DllExport DW_RegisterUpdate(void); void DllExport DW_Register(void); void DllExport DW_About(void); //------------------------------------------------------------------------ int g_bRegistered = false; long g_NumMaxSections = 5; long g_NumBodiesRetrieved = -1; LPBODY* g_pBodyList = NULL; CComBSTR g_OriginalName; CComBSTR g_ChangedName; CComBSTR g_DisplayName; double g_MassOriginal = 0.0; double g_VolumeOriginal = 0.0; double g_MassChanged = 0.0; double g_VolumeChanged = 0.0; double g_AreaOriginal = 0.0; double g_AreaChanged = 0.0; double g_Transparency = 0.7; long g_Colour = RGB(255, 0 , 0); //------------------------------------------------------------------------ extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("DiffWorks.DLL Initializing!\n"); // Extension DLL one-time initialization AfxInitExtensionModule(DiffWorksDLL, hInstance); CoInitialize(NULL); // check registered status via DMS_Comm DW_CheckRegistered(false); if (true == g_bRegistered) { // registered program has practically unlimited differences! g_NumMaxSections = 2000000; } g_pBodyList = new LPBODY [g_NumMaxSections]; for (long i = 0; i < g_NumMaxSections; i++) { g_pBodyList[i] = NULL; } // Insert this DLL into the resource chain new CDynLinkLibrary(DiffWorksDLL); } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0("DiffWorks.DLL Terminating!\n"); // shut down the sample application TheApplication->TerminateApplication(); delete TheApplication; // Terminate the library before destructors are called AfxTermExtensionModule(DiffWorksDLL); try { // clean up each object in the list for (long i = 0; i < g_NumMaxSections; i++) { if (NULL != g_pBodyList[i]) { g_pBodyList[i]->Release(); g_pBodyList[i] = NULL; } } } catch (...) { } delete [] g_pBodyList; } return 1; // ok } // -------------------------------- // connections to SolidWorks // -------------------------------- #define DllExport __declspec( dllexport ) //------------------------------------------------------------------------ // this is the function SolidWorks calls to connect // to the add-in application long DllExport InitUserDLL3(LPSLDWORKS pSldWorks) { // this function should be called once per session if ( TheApplication != NULL ) { ASSERT ( FALSE ); return 0; } // start the application TheApplication = new CDiffWorksApp(pSldWorks); if (!TheApplication->StartApplication()) return 0; // connected successfully return 1; } //------------------------------------------------------------------------ // DW_GetMass // // returns // S_OK // if successful // // S_FALSE // probably if there was a problem loading one of the files, or // // notes // not a COM method, only used internally HRESULT DW_GetMass ( CString Part, double* Mass, double* Volume, double* Area ) { try { CComPtr <ISldWorks> pSldWorks; CComPtr <IModelDoc> pModelDoc; double MassPropertyValues[12]; long Errors = 0; VARIANT_BOOL bRetVal = FALSE; VARIANT_BOOL bSaveFlag = TRUE ; pSldWorks = TheApplication->GetSWApp(); SASSERT(pSldWorks != NULL); STEST_HR(pSldWorks->IOpenDoc2(CComBSTR(Part), swDocPART, FALSE, FALSE, TRUE, &Errors, &pModelDoc)); // note that we will probably get a swFileAlreadyOpenWarn // for some of these. This is expected behaviour. if (swFileNotFoundError == Errors || swGenericError == Errors ) { // error loading one of the files return S_FALSE; } // calculate density to be used for the differences // density is based on where we will be displaying the diffs STEST_HR(pModelDoc->IGetMassProperties(MassPropertyValues, &bRetVal)); SASSERT(MassPropertyValues[3] > 0.0); *Mass = MassPropertyValues[5]; *Volume = MassPropertyValues[3]; *Area = MassPropertyValues[4]; return S_OK; } catch (_com_error& e) { return e.Error(); } catch (...) { return E_UNEXPECTED; } } //------------------------------------------------------------------------ // DW_Compare // compares two parts and highlights the differences between them. Will // also calculate the difference in mass between the two parts // // parameters // OriginalPart // fully qualified name to SW part file containing the original part // // ChangedPart // fully qualified name to SW part file containing the changed part // // DisplayPart // fully qualified name to SW part file in which to display the // differences. This will generally be the same as the original // part. // // Transparency // transparency setting for the display part // 0.0 is solid // 1.0 is totally transparent ie invisible // // Colour // RGB colour in which to display the differences, as returned // from the RGB() macro // // returns // S_OK // if successful // // S_FALSE // probably if there was a problem loading one of the files, or // // not enough space for all the differences but highly unlikely... // // notes // not a COM method, only used internally HRESULT DW_Compare ( CString OriginalPart, CString ChangedPart , CString DisplayPart , double Transparency, long Colour ) { try { CComPtr <ISldWorks> pSldWorks; CComPtr <IModelDoc> pModelDocOriginal; CComPtr <IModelDoc> pModelDocChanged; CComPtr <IModelDoc> pModelDocDisplay; CComPtr <IModelDoc> pDummy; CComQIPtr <IPartDoc> pPartDocOriginal; CComQIPtr <IPartDoc> pPartDocChanged; CComQIPtr <IPartDoc> pPartDocDisplay; CComPtr <IBody> pBodyOriginal; CComPtr <IBody> pBodyChanged; CComPtr <IBody> pCopyBodyOriginal; CComPtr <IBody> pCopyBodyChanged; double MaterialPropertyValues[9]; long errors = 0; long ErrorsOriginal = 0; long ErrorsChanged = 0; long ErrorsDisplay = 0; long i = 0; VARIANT_BOOL bRetVal = FALSE; VARIANT_BOOL bSaveFlag = TRUE ; pSldWorks = TheApplication->GetSWApp(); SASSERT(pSldWorks != NULL); STEST_HR(pSldWorks->IOpenDoc2(CComBSTR(OriginalPart), swDocPART, FALSE, FALSE, FALSE, &ErrorsOriginal, &pModelDocOriginal)); STEST_HR(pSldWorks->IOpenDoc2(CComBSTR(ChangedPart ), swDocPART, FALSE, FALSE, FALSE, &ErrorsChanged , &pModelDocChanged )); STEST_HR(pSldWorks->IOpenDoc2(CComBSTR(DisplayPart ), swDocPART, FALSE, FALSE, FALSE, &ErrorsDisplay , &pModelDocDisplay )); // note that we will probably get a swFileAlreadyOpenWarn // for some of these. This is expected behaviour. if (swFileNotFoundError == ErrorsOriginal || swGenericError == ErrorsOriginal || swInvalidFileTypeError == ErrorsOriginal || swFileNotFoundError == ErrorsChanged || swGenericError == ErrorsChanged || swInvalidFileTypeError == ErrorsChanged || swFileNotFoundError == ErrorsDisplay || swGenericError == ErrorsDisplay || swInvalidFileTypeError == ErrorsDisplay ) { // error loading one of the files return S_FALSE; } pPartDocOriginal = pModelDocOriginal; pPartDocChanged = pModelDocChanged ; pPartDocDisplay = pModelDocDisplay ; SASSERT(pPartDocOriginal != NULL); SASSERT(pPartDocChanged != NULL); SASSERT(pPartDocDisplay != NULL); STEST_HR(pPartDocOriginal->IBodyObject(&pBodyOriginal)); STEST_HR(pPartDocChanged ->IBodyObject(&pBodyChanged )); STEST_HR(pBodyOriginal->ICopy(&pCopyBodyOriginal)); STEST_HR(pBodyChanged ->ICopy(&pCopyBodyChanged )); STEST_HR(pCopyBodyOriginal->IOperations(SWBODYCUT, pCopyBodyChanged, g_NumMaxSections, g_pBodyList, &g_NumBodiesRetrieved)); if (g_NumBodiesRetrieved == g_NumMaxSections) { // oops! not enough bodies allocated in our global list // should never get this error... if (TRUE == g_bRegistered) { // FIX ME! should really release all pointers, delete g_pBodyList, increase g_NumBodiesRetrieved, reallocate g_pBodyList and call ourselves recursviely } return S_FALSE; } for (i = 0; i < g_NumBodiesRetrieved; i++) { STEST_HR(g_pBodyList[i]->IDisplay(pPartDocDisplay, Colour)); } // check whether there are any unsaved changes before we make // our change to the transparency STEST_HR(pModelDocDisplay->GetSaveFlag(&bSaveFlag)); STEST_HR(pModelDocDisplay->get_IMaterialPropertyValues(MaterialPropertyValues)); // reduce transparency MaterialPropertyValues[7] = Transparency; STEST_HR(pModelDocDisplay->put_IMaterialPropertyValues(MaterialPropertyValues)); if (FALSE == bSaveFlag) { // changing transparency sets the save flag, so we should // clear the save flag if this is the only change which has // been made // FIX ME! awaiting API from SW //STEST_HR(pModelDocDisplay->ClearSaveFlag()); } // show the diffs to the user pSldWorks->IActivateDoc2(CComBSTR(DisplayPart), TRUE, &errors, &pDummy); return S_OK; } catch (_com_error& e) { return e.Error(); } catch (...) { return E_UNEXPECTED; } } //------------------------------------------------------------------------ class AutoResource { private: HINSTANCE m_SaveResource; HINSTANCE m_NewResourceHandle; public: AutoResource(CString ModuleName) { m_SaveResource = AfxGetResourceHandle(); m_NewResourceHandle = LoadLibrary(ModuleName); // Switch to the Application resources AfxSetResourceHandle(m_NewResourceHandle); } ~AutoResource() { // Reset to previous resource handle AfxSetResourceHandle(m_SaveResource); } HINSTANCE GetSavedResource() { return m_SaveResource; } HINSTANCE GetResource() { return m_NewResourceHandle; } }; //------------------------------------------------------------------------ void DllExport DW_CompareFiles(void) { // Save the current resource handle HINSTANCE SaveResource = AfxGetResourceHandle(); HINSTANCE DW_ResourceHandle = GetModuleHandle(DIFF_DLL_NAME); // Switch to the Application resources AfxSetResourceHandle(DW_ResourceHandle); try { USES_CONVERSION; HRESULT hres = S_OK; HRESULT hresOriginal = S_OK; HRESULT hresChanged = S_OK; CComBSTR sMassOriginal = _T("Loading "); CComBSTR sMassChanged = _T("Loading "); CComBSTR sCompareOriginal= _T("Comparing "); CComBSTR sCompareChanged = _T("Comparing "); CComBSTR sCalculating = _T("Calculating results..."); CComBSTR sDisplaying = _T("Displaying differences..."); TCHAR sOriginalName[MAX_PATH]; TCHAR sChangedName [MAX_PATH]; // run dialog to get 3 filenames, transparency & colour hres = TheApplication->m_DMS_DiffWks->GetCompareInfo ( &g_OriginalName, &g_ChangedName , &g_DisplayName , &g_Transparency, &g_Colour ); if (hres != S_OK) { // user cancelled selection of files goto CLEAN_UP; } // remove all the path details from the file names _tcscpy(sOriginalName, OLE2T(g_OriginalName)); _tcscpy(sChangedName , OLE2T(g_ChangedName )); PathStripPath(sOriginalName); PathStripPath(sChangedName ); // so they display fully in the progress pipe dialog sMassOriginal .Append(sOriginalName); sMassChanged .Append(sChangedName ); sCompareOriginal.Append(sOriginalName); sCompareChanged .Append(sChangedName ); TheApplication->m_DMS_ProgPipe->Reset(); TheApplication->m_DMS_ProgPipe->put_TotalSteps(8); TheApplication->m_DMS_ProgPipe->Show(); Sleep(500); TheApplication->m_DMS_ProgPipe->Step(); // get mass info before we start diff'ing TheApplication->m_DMS_ProgPipe->put_Text(sMassOriginal); TheApplication->m_DMS_ProgPipe->Step(); // info for original part AfxSetResourceHandle(SaveResource); hresOriginal = DW_GetMass(g_OriginalName.m_str, &g_MassOriginal, &g_VolumeOriginal, &g_AreaOriginal); AfxSetResourceHandle(DW_ResourceHandle); TheApplication->m_DMS_ProgPipe->put_Text(sMassChanged); TheApplication->m_DMS_ProgPipe->Step(); // info for changed part AfxSetResourceHandle(SaveResource); hresChanged = DW_GetMass(g_ChangedName .m_str, &g_MassChanged , &g_VolumeChanged, &g_AreaChanged); AfxSetResourceHandle(DW_ResourceHandle); // make sure there were no errors loading the two files if (S_OK != hresOriginal || S_OK != hresChanged ) { goto CLEAN_UP; } TheApplication->m_DMS_ProgPipe->put_Text(sCompareOriginal); TheApplication->m_DMS_ProgPipe->Step(); // compare original -> changed AfxSetResourceHandle(SaveResource); hresOriginal = DW_Compare(g_OriginalName.m_str, g_ChangedName .m_str, g_OriginalName.m_str, g_Transparency, g_Colour); AfxSetResourceHandle(DW_ResourceHandle); TheApplication->m_DMS_ProgPipe->put_Text(sCompareChanged); TheApplication->m_DMS_ProgPipe->Step(); // compare changed -> original AfxSetResourceHandle(SaveResource); hresChanged = DW_Compare(g_ChangedName .m_str, g_OriginalName.m_str, g_OriginalName.m_str, g_Transparency, g_Colour); AfxSetResourceHandle(DW_ResourceHandle); // make sure there were no errors diff'ing the two files if (S_OK != hresOriginal || S_OK != hresChanged ) { goto CLEAN_UP; } TheApplication->m_DMS_ProgPipe->put_Text(sCalculating); TheApplication->m_DMS_ProgPipe->Step(); true == g_bRegistered ? Sleep(500) : Sleep(5000); TheApplication->m_DMS_ProgPipe->put_Text(sDisplaying); TheApplication->m_DMS_ProgPipe->Step(); true == g_bRegistered ? Sleep(500) : Sleep(5000); TheApplication->m_DMS_ProgPipe->Step(); true == g_bRegistered ? Sleep(500) : Sleep(5000); TheApplication->m_DMS_ProgPipe->Hide(); hres = TheApplication->m_DMS_DiffWks->ShowCompareResults ( g_OriginalName, g_ChangedName, g_MassOriginal, g_MassChanged, g_VolumeOriginal, g_VolumeChanged, g_AreaOriginal, g_AreaChanged ); } catch (_com_error& e) { (void ) e; } catch (...) { } CLEAN_UP : ; // always hide the progress bar TheApplication->m_DMS_ProgPipe->Hide(); // Reset to previous resource handle AfxSetResourceHandle(SaveResource); } //------------------------------------------------------------------------ void DllExport DW_ShowLast(void) { try { HRESULT hres = S_OK; hres = TheApplication->m_DMS_DiffWks->ShowCompareResults ( g_OriginalName, g_ChangedName, g_MassOriginal, g_MassChanged, g_VolumeOriginal, g_VolumeChanged, g_AreaOriginal, g_AreaChanged ); } catch (_com_error& e) { (void ) e; } catch (...) { } } //------------------------------------------------------------------------ void DllExport DW_Help(void) { WinExec("winhlp32 C:\\Program Files\\SolidPartners\\DiffWorks\\DiffWks.hlp" , SW_NORMAL); } //------------------------------------------------------------------------ // // parameters // bShowDialog // true if dialog is to be shown // false if just want to check .ini file // notes // updates g_bRegistered void DW_CheckRegistered ( bool bShowDialog ) { // Save the current resource handle HINSTANCE SaveResource = AfxGetResourceHandle(); HINSTANCE DW_ResourceHandle = GetModuleHandle(DIFF_DLL_NAME); // Switch to the Application resources AfxSetResourceHandle(DW_ResourceHandle); try { HRESULT hres; CComPtr<IDMS_Common> DMS_Comm; hres = DMS_Comm.CoCreateInstance(__uuidof(DMS_Common), NULL, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER); ASSERT(SUCCEEDED(hres)); DMS_Comm->put_Commercial(true); DMS_Comm->put_ProductCode(CComBSTR(DIFF_WORKS_TITLE_CODE)); DMS_Comm->put_ProductName(CComBSTR(DIFF_WORKS_TITLE)); DMS_Comm->put_IniFileName(CComBSTR(DIFF_WORKS_INI_FILE_NAME)); if (true == bShowDialog) { DMS_Comm->put_Icon((long ) LoadIcon(DW_ResourceHandle, MAKEINTRESOURCE(IDI_ICON_DIFF_WKS))); // only run dialog if asked // will store result to .ini file if successfully registered DMS_Comm->Register(); } DMS_Comm->get_IsRegistered(&g_bRegistered); DMS_Comm = NULL; } catch (_com_error& e) { (void ) e; } catch (...) { } // Reset to previous resource handle AfxSetResourceHandle(SaveResource); } //------------------------------------------------------------------------ int DllExport DW_RegisterUpdate(void) { #if 0 return 0; // If you want the menu item to be unchecked and disabled (grayed out) return 1; // If you want the menu item to be unchecked and enabled return 2; // If you want the menu item to be checked and disabled (grayed out) return 3; // If you want the menu item to be checked and enabled #endif return g_bRegistered == true ? 0 : 1; } //------------------------------------------------------------------------ void DllExport DW_Register(void) { DW_CheckRegistered(true); } //------------------------------------------------------------------------ void DllExport DW_About(void) { // Save the current resource handle HINSTANCE SaveResource = AfxGetResourceHandle(); HINSTANCE DW_ResourceHandle = GetModuleHandle(DIFF_DLL_NAME); try { HRESULT hres; CComPtr<IDMS_Common> DMS_Comm; hres = DMS_Comm.CoCreateInstance(__uuidof(DMS_Common), NULL, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER); ASSERT(SUCCEEDED(hres)); DMS_Comm->put_Commercial(true); DMS_Comm->put_ProductName(CComBSTR(DIFF_WORKS_TITLE)); DMS_Comm->put_Icon((long ) LoadIcon(DW_ResourceHandle, MAKEINTRESOURCE(IDI_ICON_DIFF_WKS))); DMS_Comm->About(); DMS_Comm = NULL; } catch (_com_error& e) { (void ) e; } catch (...) { } // Reset to previous resource handle AfxSetResourceHandle(SaveResource); } //------------------------------------------------------------------------ // -------------------------------- // End of DiffWorks.cpp // --------------------------------
32.379032
172
0.52611
TrevorDArcyEvans
4acde5994af6af142394ab93acf9d67b6c2e8c3f
1,986
cc
C++
cartographer/common/rate_timer_test.cc
linghusmile/Cartographer_-
28be85c1af353efae802cebb299b8d2486fbd800
[ "Apache-2.0" ]
36
2017-01-17T10:19:30.000Z
2022-02-13T09:11:51.000Z
cartographer/common/rate_timer_test.cc
linghusmile/Cartographer_-
28be85c1af353efae802cebb299b8d2486fbd800
[ "Apache-2.0" ]
2
2019-06-26T06:01:49.000Z
2019-08-02T04:27:27.000Z
cartographer/common/rate_timer_test.cc
linghusmile/Cartographer_-
28be85c1af353efae802cebb299b8d2486fbd800
[ "Apache-2.0" ]
37
2016-10-09T01:52:45.000Z
2022-01-22T10:51:54.000Z
/* * Copyright 2016 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "cartographer/common/rate_timer.h" #include "gtest/gtest.h" namespace cartographer { namespace common { namespace { TEST(RateTimerTest, ComputeRate) { RateTimer<> rate_timer(common::FromSeconds(1.)); common::Time time = common::FromUniversal(42); for (int i = 0; i < 100; ++i) { rate_timer.Pulse(time); time += common::FromSeconds(0.1); } EXPECT_NEAR(10., rate_timer.ComputeRate(), 1e-3); } struct SimulatedClock { using rep = std::chrono::steady_clock::rep; using period = std::chrono::steady_clock::period; using duration = std::chrono::steady_clock::duration; using time_point = std::chrono::steady_clock::time_point; static constexpr bool is_steady = true; static time_point time; static time_point now() noexcept { return time; } }; SimulatedClock::time_point SimulatedClock::time; TEST(RateTimerTest, ComputeWallTimeRateRatio) { common::Time time = common::FromUniversal(42); RateTimer<SimulatedClock> rate_timer(common::FromSeconds(1.)); for (int i = 0; i < 100; ++i) { rate_timer.Pulse(time); time += common::FromSeconds(0.1); SimulatedClock::time += std::chrono::duration_cast<SimulatedClock::duration>( std::chrono::duration<double>(0.05)); } EXPECT_NEAR(2., rate_timer.ComputeWallTimeRateRatio(), 1e-3); } } // namespace } // namespace common } // namespace cartographer
31.03125
75
0.712487
linghusmile
4acde62f9f0434f5e9bc4a846c5e84444d5e3efb
1,210
cpp
C++
Difficulty 900/Mocha_and_Red_and_Blue.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
Difficulty 900/Mocha_and_Red_and_Blue.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
Difficulty 900/Mocha_and_Red_and_Blue.cpp
desmondweh29/A-Problem-A-Day
135b21d21d74e6c716c9f7e36e8fa3a216f02727
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Question: https://codeforces.com/problemset/problem/1559/B void solve() { int n; cin >> n; string a; cin >> a; string s1 = a; string s2 = a; if (a[0] == '?') { s1[0] = 'B'; s2[0] = 'R'; } for (int i = 1; i < n; i++) { if (a[i] == '?') { if (s1[i-1] == 'R') { s1[i] = 'B'; } else { s1[i] = 'R'; } } if (a[i] == '?') { if (s2[i-1] == 'R') { s2[i] = 'B'; } else { s2[i] = 'R'; } } } int c1 = 0; int c2 = 0; for (int i = 1; i < n; i++) { if (s1[i-1] == s1[i]) { c1++; } if (s2[i-1] == s2[i]) { c2++; } } if (c1 < c2) { cout << s1 << "\n"; } else { cout << s2 << "\n"; } } int main() { ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--) { solve(); } }
14.069767
61
0.261983
desmondweh29
4acf2dee5ce71889a7f1345de64a210ff5321e3c
1,129
hpp
C++
src/core/tests/util/float_util.hpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
ngraph/test/util/float_util.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
ngraph/test/util/float_util.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <algorithm> #include <bitset> #include <cmath> #include <limits> #include <sstream> #include "ngraph/ngraph.hpp" namespace ngraph { namespace test { union FloatUnion { FloatUnion() { i = 0; } FloatUnion(float val) { f = val; } FloatUnion(uint32_t val) { i = val; } FloatUnion(uint32_t s, uint32_t e, uint32_t f) : FloatUnion(s << 31 | e << 23 | f) {} float f; uint32_t i; }; union DoubleUnion { DoubleUnion() { i = 0; } DoubleUnion(double val) { d = val; } DoubleUnion(uint64_t val) { i = val; } double d; uint64_t i; }; std::string bfloat16_to_bits(bfloat16 f); std::string float16_to_bits(float16 f); std::string float_to_bits(float f); std::string double_to_bits(double d); bfloat16 bits_to_bfloat16(const std::string& s); float bits_to_float(const std::string& s); double bits_to_double(const std::string& s); float16 bits_to_float16(const std::string& s); } // namespace test } // namespace ngraph
18.508197
89
0.633304
pazamelin
4ad042b3c25eed4bf4366b794766f3757459652d
23,384
hpp
C++
include/GlobalNamespace/MainSettingsModelSO.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MainSettingsModelSO.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MainSettingsModelSO.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: PersistentScriptableObject #include "GlobalNamespace/PersistentScriptableObject.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: FloatSO class FloatSO; // Forward declaring type: BoolSO class BoolSO; // Forward declaring type: Vector2IntSO class Vector2IntSO; // Forward declaring type: IntSO class IntSO; // Forward declaring type: Vector3SO class Vector3SO; // Forward declaring type: LanguageSO class LanguageSO; // Forward declaring type: StringSO class StringSO; } // Forward declaring namespace: System namespace System { // Forward declaring type: String class String; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x154 #pragma pack(push, 1) // Autogenerated type: MainSettingsModelSO class MainSettingsModelSO : public GlobalNamespace::PersistentScriptableObject { public: // Nested type: GlobalNamespace::MainSettingsModelSO::WindowMode struct WindowMode; // Nested type: GlobalNamespace::MainSettingsModelSO::Config class Config; // [SOVariableAttribute] Offset: 0xE172D4 // public FloatSO vrResolutionScale // Size: 0x8 // Offset: 0x18 GlobalNamespace::FloatSO* vrResolutionScale; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE172E4 // public FloatSO menuVRResolutionScaleMultiplier // Size: 0x8 // Offset: 0x20 GlobalNamespace::FloatSO* menuVRResolutionScaleMultiplier; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE172F4 // public BoolSO useFixedFoveatedRenderingDuringGameplay // Size: 0x8 // Offset: 0x28 GlobalNamespace::BoolSO* useFixedFoveatedRenderingDuringGameplay; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17304 // public Vector2IntSO windowResolution // Size: 0x8 // Offset: 0x30 GlobalNamespace::Vector2IntSO* windowResolution; // Field size check static_assert(sizeof(GlobalNamespace::Vector2IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17314 // public BoolSO fullscreen // Size: 0x8 // Offset: 0x38 GlobalNamespace::BoolSO* fullscreen; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17324 // public IntSO antiAliasingLevel // Size: 0x8 // Offset: 0x40 GlobalNamespace::IntSO* antiAliasingLevel; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17334 // public FloatSO volume // Size: 0x8 // Offset: 0x48 GlobalNamespace::FloatSO* volume; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17344 // public FloatSO ambientVolumeScale // Size: 0x8 // Offset: 0x50 GlobalNamespace::FloatSO* ambientVolumeScale; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17354 // public BoolSO controllersRumbleEnabled // Size: 0x8 // Offset: 0x58 GlobalNamespace::BoolSO* controllersRumbleEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17364 // public Vector3SO roomCenter // Size: 0x8 // Offset: 0x60 GlobalNamespace::Vector3SO* roomCenter; // Field size check static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17374 // public FloatSO roomRotation // Size: 0x8 // Offset: 0x68 GlobalNamespace::FloatSO* roomRotation; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17384 // public Vector3SO controllerPosition // Size: 0x8 // Offset: 0x70 GlobalNamespace::Vector3SO* controllerPosition; // Field size check static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17394 // public Vector3SO controllerRotation // Size: 0x8 // Offset: 0x78 GlobalNamespace::Vector3SO* controllerRotation; // Field size check static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173A4 // public IntSO mirrorGraphicsSettings // Size: 0x8 // Offset: 0x80 GlobalNamespace::IntSO* mirrorGraphicsSettings; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173B4 // public IntSO mainEffectGraphicsSettings // Size: 0x8 // Offset: 0x88 GlobalNamespace::IntSO* mainEffectGraphicsSettings; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173C4 // public IntSO bloomPrePassGraphicsSettings // Size: 0x8 // Offset: 0x90 GlobalNamespace::IntSO* bloomPrePassGraphicsSettings; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173D4 // public BoolSO smokeGraphicsSettings // Size: 0x8 // Offset: 0x98 GlobalNamespace::BoolSO* smokeGraphicsSettings; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173E4 // public BoolSO enableAlphaFeatures // Size: 0x8 // Offset: 0xA0 GlobalNamespace::BoolSO* enableAlphaFeatures; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE173F4 // public IntSO pauseButtonPressDurationLevel // Size: 0x8 // Offset: 0xA8 GlobalNamespace::IntSO* pauseButtonPressDurationLevel; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17404 // public BoolSO burnMarkTrailsEnabled // Size: 0x8 // Offset: 0xB0 GlobalNamespace::BoolSO* burnMarkTrailsEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17414 // public BoolSO screenDisplacementEffectsEnabled // Size: 0x8 // Offset: 0xB8 GlobalNamespace::BoolSO* screenDisplacementEffectsEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17424 // public BoolSO smoothCameraEnabled // Size: 0x8 // Offset: 0xC0 GlobalNamespace::BoolSO* smoothCameraEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17434 // public FloatSO smoothCameraFieldOfView // Size: 0x8 // Offset: 0xC8 GlobalNamespace::FloatSO* smoothCameraFieldOfView; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17444 // public Vector3SO smoothCameraThirdPersonPosition // Size: 0x8 // Offset: 0xD0 GlobalNamespace::Vector3SO* smoothCameraThirdPersonPosition; // Field size check static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17454 // public Vector3SO smoothCameraThirdPersonEulerAngles // Size: 0x8 // Offset: 0xD8 GlobalNamespace::Vector3SO* smoothCameraThirdPersonEulerAngles; // Field size check static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17464 // public BoolSO smoothCameraThirdPersonEnabled // Size: 0x8 // Offset: 0xE0 GlobalNamespace::BoolSO* smoothCameraThirdPersonEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17474 // public FloatSO smoothCameraRotationSmooth // Size: 0x8 // Offset: 0xE8 GlobalNamespace::FloatSO* smoothCameraRotationSmooth; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17484 // public FloatSO smoothCameraPositionSmooth // Size: 0x8 // Offset: 0xF0 GlobalNamespace::FloatSO* smoothCameraPositionSmooth; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17494 // public BoolSO overrideAudioLatency // Size: 0x8 // Offset: 0xF8 GlobalNamespace::BoolSO* overrideAudioLatency; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174A4 // public FloatSO audioLatency // Size: 0x8 // Offset: 0x100 GlobalNamespace::FloatSO* audioLatency; // Field size check static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174B4 // public IntSO maxShockwaveParticles // Size: 0x8 // Offset: 0x108 GlobalNamespace::IntSO* maxShockwaveParticles; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174C4 // public IntSO maxNumberOfCutSoundEffects // Size: 0x8 // Offset: 0x110 GlobalNamespace::IntSO* maxNumberOfCutSoundEffects; // Field size check static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174D4 // public BoolSO onlineServicesEnabled // Size: 0x8 // Offset: 0x118 GlobalNamespace::BoolSO* onlineServicesEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174E4 // public BoolSO oculusMRCEnabled // Size: 0x8 // Offset: 0x120 GlobalNamespace::BoolSO* oculusMRCEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE174F4 // public BoolSO openVrThreadedHaptics // Size: 0x8 // Offset: 0x128 GlobalNamespace::BoolSO* openVrThreadedHaptics; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17504 // public LanguageSO language // Size: 0x8 // Offset: 0x130 GlobalNamespace::LanguageSO* language; // Field size check static_assert(sizeof(GlobalNamespace::LanguageSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17514 // public BoolSO useCustomServerEnvironment // Size: 0x8 // Offset: 0x138 GlobalNamespace::BoolSO* useCustomServerEnvironment; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17524 // public StringSO customServerHostName // Size: 0x8 // Offset: 0x140 GlobalNamespace::StringSO* customServerHostName; // Field size check static_assert(sizeof(GlobalNamespace::StringSO*) == 0x8); // [SOVariableAttribute] Offset: 0xE17534 // public BoolSO depthTextureEnabled // Size: 0x8 // Offset: 0x148 GlobalNamespace::BoolSO* depthTextureEnabled; // Field size check static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE17544 // private System.Boolean <createScreenshotDuringTheGame>k__BackingField // Size: 0x1 // Offset: 0x150 bool createScreenshotDuringTheGame; // Field size check static_assert(sizeof(bool) == 0x1); // [CompilerGeneratedAttribute] Offset: 0xE17554 // private System.Boolean <playingForTheFirstTime>k__BackingField // Size: 0x1 // Offset: 0x151 bool playingForTheFirstTime; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _playingForTheFirstTimeChecked // Size: 0x1 // Offset: 0x152 bool playingForTheFirstTimeChecked; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _isLoaded // Size: 0x1 // Offset: 0x153 bool isLoaded; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: MainSettingsModelSO MainSettingsModelSO(GlobalNamespace::FloatSO* vrResolutionScale_ = {}, GlobalNamespace::FloatSO* menuVRResolutionScaleMultiplier_ = {}, GlobalNamespace::BoolSO* useFixedFoveatedRenderingDuringGameplay_ = {}, GlobalNamespace::Vector2IntSO* windowResolution_ = {}, GlobalNamespace::BoolSO* fullscreen_ = {}, GlobalNamespace::IntSO* antiAliasingLevel_ = {}, GlobalNamespace::FloatSO* volume_ = {}, GlobalNamespace::FloatSO* ambientVolumeScale_ = {}, GlobalNamespace::BoolSO* controllersRumbleEnabled_ = {}, GlobalNamespace::Vector3SO* roomCenter_ = {}, GlobalNamespace::FloatSO* roomRotation_ = {}, GlobalNamespace::Vector3SO* controllerPosition_ = {}, GlobalNamespace::Vector3SO* controllerRotation_ = {}, GlobalNamespace::IntSO* mirrorGraphicsSettings_ = {}, GlobalNamespace::IntSO* mainEffectGraphicsSettings_ = {}, GlobalNamespace::IntSO* bloomPrePassGraphicsSettings_ = {}, GlobalNamespace::BoolSO* smokeGraphicsSettings_ = {}, GlobalNamespace::BoolSO* enableAlphaFeatures_ = {}, GlobalNamespace::IntSO* pauseButtonPressDurationLevel_ = {}, GlobalNamespace::BoolSO* burnMarkTrailsEnabled_ = {}, GlobalNamespace::BoolSO* screenDisplacementEffectsEnabled_ = {}, GlobalNamespace::BoolSO* smoothCameraEnabled_ = {}, GlobalNamespace::FloatSO* smoothCameraFieldOfView_ = {}, GlobalNamespace::Vector3SO* smoothCameraThirdPersonPosition_ = {}, GlobalNamespace::Vector3SO* smoothCameraThirdPersonEulerAngles_ = {}, GlobalNamespace::BoolSO* smoothCameraThirdPersonEnabled_ = {}, GlobalNamespace::FloatSO* smoothCameraRotationSmooth_ = {}, GlobalNamespace::FloatSO* smoothCameraPositionSmooth_ = {}, GlobalNamespace::BoolSO* overrideAudioLatency_ = {}, GlobalNamespace::FloatSO* audioLatency_ = {}, GlobalNamespace::IntSO* maxShockwaveParticles_ = {}, GlobalNamespace::IntSO* maxNumberOfCutSoundEffects_ = {}, GlobalNamespace::BoolSO* onlineServicesEnabled_ = {}, GlobalNamespace::BoolSO* oculusMRCEnabled_ = {}, GlobalNamespace::BoolSO* openVrThreadedHaptics_ = {}, GlobalNamespace::LanguageSO* language_ = {}, GlobalNamespace::BoolSO* useCustomServerEnvironment_ = {}, GlobalNamespace::StringSO* customServerHostName_ = {}, GlobalNamespace::BoolSO* depthTextureEnabled_ = {}, bool createScreenshotDuringTheGame_ = {}, bool playingForTheFirstTime_ = {}, bool playingForTheFirstTimeChecked_ = {}, bool isLoaded_ = {}) noexcept : vrResolutionScale{vrResolutionScale_}, menuVRResolutionScaleMultiplier{menuVRResolutionScaleMultiplier_}, useFixedFoveatedRenderingDuringGameplay{useFixedFoveatedRenderingDuringGameplay_}, windowResolution{windowResolution_}, fullscreen{fullscreen_}, antiAliasingLevel{antiAliasingLevel_}, volume{volume_}, ambientVolumeScale{ambientVolumeScale_}, controllersRumbleEnabled{controllersRumbleEnabled_}, roomCenter{roomCenter_}, roomRotation{roomRotation_}, controllerPosition{controllerPosition_}, controllerRotation{controllerRotation_}, mirrorGraphicsSettings{mirrorGraphicsSettings_}, mainEffectGraphicsSettings{mainEffectGraphicsSettings_}, bloomPrePassGraphicsSettings{bloomPrePassGraphicsSettings_}, smokeGraphicsSettings{smokeGraphicsSettings_}, enableAlphaFeatures{enableAlphaFeatures_}, pauseButtonPressDurationLevel{pauseButtonPressDurationLevel_}, burnMarkTrailsEnabled{burnMarkTrailsEnabled_}, screenDisplacementEffectsEnabled{screenDisplacementEffectsEnabled_}, smoothCameraEnabled{smoothCameraEnabled_}, smoothCameraFieldOfView{smoothCameraFieldOfView_}, smoothCameraThirdPersonPosition{smoothCameraThirdPersonPosition_}, smoothCameraThirdPersonEulerAngles{smoothCameraThirdPersonEulerAngles_}, smoothCameraThirdPersonEnabled{smoothCameraThirdPersonEnabled_}, smoothCameraRotationSmooth{smoothCameraRotationSmooth_}, smoothCameraPositionSmooth{smoothCameraPositionSmooth_}, overrideAudioLatency{overrideAudioLatency_}, audioLatency{audioLatency_}, maxShockwaveParticles{maxShockwaveParticles_}, maxNumberOfCutSoundEffects{maxNumberOfCutSoundEffects_}, onlineServicesEnabled{onlineServicesEnabled_}, oculusMRCEnabled{oculusMRCEnabled_}, openVrThreadedHaptics{openVrThreadedHaptics_}, language{language_}, useCustomServerEnvironment{useCustomServerEnvironment_}, customServerHostName{customServerHostName_}, depthTextureEnabled{depthTextureEnabled_}, createScreenshotDuringTheGame{createScreenshotDuringTheGame_}, playingForTheFirstTime{playingForTheFirstTime_}, playingForTheFirstTimeChecked{playingForTheFirstTimeChecked_}, isLoaded{isLoaded_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // static field const value: static public System.Single kDefaultPlayerHeight static constexpr const float kDefaultPlayerHeight = 1.8; // Get static field: static public System.Single kDefaultPlayerHeight static float _get_kDefaultPlayerHeight(); // Set static field: static public System.Single kDefaultPlayerHeight static void _set_kDefaultPlayerHeight(float value); // static field const value: static public System.Single kHeadPosToPlayerHeightOffset static constexpr const float kHeadPosToPlayerHeightOffset = 0.1; // Get static field: static public System.Single kHeadPosToPlayerHeightOffset static float _get_kHeadPosToPlayerHeightOffset(); // Set static field: static public System.Single kHeadPosToPlayerHeightOffset static void _set_kHeadPosToPlayerHeightOffset(float value); // static field const value: static private System.String kFileName static constexpr const char* kFileName = "settings.cfg"; // Get static field: static private System.String kFileName static ::Il2CppString* _get_kFileName(); // Set static field: static private System.String kFileName static void _set_kFileName(::Il2CppString* value); // static field const value: static private System.String kTempFileName static constexpr const char* kTempFileName = "settings.cfg.tmp"; // Get static field: static private System.String kTempFileName static ::Il2CppString* _get_kTempFileName(); // Set static field: static private System.String kTempFileName static void _set_kTempFileName(::Il2CppString* value); // static field const value: static private System.String kBackupFileName static constexpr const char* kBackupFileName = "settings.cfg.bak"; // Get static field: static private System.String kBackupFileName static ::Il2CppString* _get_kBackupFileName(); // Set static field: static private System.String kBackupFileName static void _set_kBackupFileName(::Il2CppString* value); // static field const value: static private System.String kCurrentVersion static constexpr const char* kCurrentVersion = "1.7.0"; // Get static field: static private System.String kCurrentVersion static ::Il2CppString* _get_kCurrentVersion(); // Set static field: static private System.String kCurrentVersion static void _set_kCurrentVersion(::Il2CppString* value); // static field const value: static public System.Single kControllersPositionOffsetLimit static constexpr const float kControllersPositionOffsetLimit = 0.1; // Get static field: static public System.Single kControllersPositionOffsetLimit static float _get_kControllersPositionOffsetLimit(); // Set static field: static public System.Single kControllersPositionOffsetLimit static void _set_kControllersPositionOffsetLimit(float value); // static field const value: static public System.Single kControllersRotationOffsetLimit static constexpr const float kControllersRotationOffsetLimit = 180; // Get static field: static public System.Single kControllersRotationOffsetLimit static float _get_kControllersRotationOffsetLimit(); // Set static field: static public System.Single kControllersRotationOffsetLimit static void _set_kControllersRotationOffsetLimit(float value); // public System.Boolean get_createScreenshotDuringTheGame() // Offset: 0x10D8D80 bool get_createScreenshotDuringTheGame(); // private System.Void set_createScreenshotDuringTheGame(System.Boolean value) // Offset: 0x10D8D88 void set_createScreenshotDuringTheGame(bool value); // public System.Boolean get_playingForTheFirstTime() // Offset: 0x10D8D94 bool get_playingForTheFirstTime(); // private System.Void set_playingForTheFirstTime(System.Boolean value) // Offset: 0x10D8D9C void set_playingForTheFirstTime(bool value); // public System.Void Save() // Offset: 0x10D8DA8 void Save(); // public System.Void Load(System.Boolean forced) // Offset: 0x10D92F0 void Load(bool forced); // public System.Void __DeleteSettingsFiles() // Offset: 0x10D99AC void __DeleteSettingsFiles(); // protected System.Void OnDisable() // Offset: 0x10D9B78 void OnDisable(); // protected override System.Void OnEnable() // Offset: 0x10D9AE4 // Implemented from: PersistentScriptableObject // Base method: System.Void PersistentScriptableObject::OnEnable() void OnEnable(); // public System.Void .ctor() // Offset: 0x10D9B88 // Implemented from: PersistentScriptableObject // Base method: System.Void PersistentScriptableObject::.ctor() // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MainSettingsModelSO* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MainSettingsModelSO::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MainSettingsModelSO*, creationType>())); } }; // MainSettingsModelSO #pragma pack(pop) static check_size<sizeof(MainSettingsModelSO), 339 + sizeof(bool)> __GlobalNamespace_MainSettingsModelSOSizeCheck; static_assert(sizeof(MainSettingsModelSO) == 0x154); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MainSettingsModelSO*, "", "MainSettingsModelSO");
52.313199
4,383
0.731996
darknight1050
4ad308989037d81fec68b1f177b02b8c699e7396
2,907
cpp
C++
Source/AstralShipwright/Nova.cpp
arbonagw/AstralShipwright
8a41015f23fa810ab79d72460f9ada2dd7e37852
[ "BSD-3-Clause" ]
59
2021-11-29T22:20:03.000Z
2022-03-17T00:07:48.000Z
Source/AstralShipwright/Nova.cpp
arbonagw/AstralShipwright
8a41015f23fa810ab79d72460f9ada2dd7e37852
[ "BSD-3-Clause" ]
null
null
null
Source/AstralShipwright/Nova.cpp
arbonagw/AstralShipwright
8a41015f23fa810ab79d72460f9ada2dd7e37852
[ "BSD-3-Clause" ]
4
2022-01-05T09:44:12.000Z
2022-02-21T02:02:32.000Z
// Astral Shipwright - Gwennaël Arbona #include "Nova.h" #include "Game/NovaGameTypes.h" #include "Engine.h" IMPLEMENT_PRIMARY_GAME_MODULE(FNovaModule, AstralShipwright, "AstralShipwright"); #define LOCTEXT_NAMESPACE "AstralShipwright" /*---------------------------------------------------- Debugging tools ----------------------------------------------------*/ FText GetDateText(struct FNovaTime Time) { FDateTime DateTime = FDateTime(ENovaConstants::ZeroTime) + FDateTime(Time.AsMinutes() * ETimespan::TicksPerMinute); return FText::AsDateTime(DateTime); } FText GetDurationText(FNovaTime Time, int32 MaxComponents) { FString Result; double SourceMinutes = Time.AsMinutes(); if (SourceMinutes > 365 * 24 * 60) { return LOCTEXT("VeryLongTime", "A very long time"); } // Break up the time int32 Days = FMath::Floor(SourceMinutes / (24 * 60)); SourceMinutes -= Days * 24 * 60; int32 Hours = FMath::Floor(SourceMinutes / 60); SourceMinutes -= Hours * 60; int32 Minutes = FMath::Floor(SourceMinutes); SourceMinutes -= Minutes; int32 Seconds = FMath::Floor(SourceMinutes * 60.0f); // Format the time int32 ComponentCount = 0; if (Days) { if (ComponentCount == MaxComponents - 1) { Days++; } Result += FText::FormatNamed(LOCTEXT("DaysFormat", "{days} {days}|plural(one=day,other=days)"), TEXT("days"), FText::AsNumber(Days)) .ToString(); ComponentCount++; } if (Hours && ComponentCount < MaxComponents) { if (ComponentCount > 0) { Result += TEXT(", "); } if (ComponentCount == MaxComponents - 1) { Hours++; } Result += FText::FormatNamed( LOCTEXT("HoursFormat", "{hours} {hours}|plural(one=hour,other=hours)"), TEXT("hours"), FText::AsNumber(Hours)) .ToString(); ComponentCount++; } if (Minutes && ComponentCount < MaxComponents) { if (ComponentCount > 0) { Result += TEXT(", "); } if (ComponentCount == MaxComponents - 1) { Minutes++; } Result += FText::FormatNamed( LOCTEXT("MinutesFormat", "{minutes} {minutes}|plural(one=minute,other=minutes)"), TEXT("minutes"), FText::AsNumber(Minutes)) .ToString(); ComponentCount++; } if ((Seconds && ComponentCount < MaxComponents) || ComponentCount == 0) { if (ComponentCount > 0) { Result += TEXT(", "); } if (ComponentCount == MaxComponents - 1) { Seconds++; } Result += FText::FormatNamed( LOCTEXT("SecondsFormat", "{seconds} {seconds}|plural(one=second,other=seconds)"), TEXT("seconds"), FText::AsNumber(Seconds)) .ToString(); ComponentCount++; } return FText::FromString(Result); } FText GetPriceText(FNovaCredits Credits) { FNumberFormattingOptions Options; Options.MaximumFractionalDigits = 0; return FText::FromString(FText::AsCurrency(Credits.GetValue(), TEXT("CUR"), &Options).ToString().Replace(TEXT("CUR"), TEXT("Ѥ"))); } #undef LOCTEXT_NAMESPACE
25.060345
134
0.643619
arbonagw
4ad45c165ab0fc546ac9441a52969a47dfc6a5ba
1,292
cpp
C++
aws-cpp-sdk-kinesis/source/model/ListTagsForStreamResult.cpp
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-kinesis/source/model/ListTagsForStreamResult.cpp
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-kinesis/source/model/ListTagsForStreamResult.cpp
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. */ #include <aws/kinesis/model/ListTagsForStreamResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Kinesis::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListTagsForStreamResult::ListTagsForStreamResult() : m_hasMoreTags(false) { } ListTagsForStreamResult::ListTagsForStreamResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_hasMoreTags(false) { *this = result; } ListTagsForStreamResult& ListTagsForStreamResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("Tags")) { Array<JsonView> tagsJsonList = jsonValue.GetArray("Tags"); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { m_tags.push_back(tagsJsonList[tagsIndex].AsObject()); } } if(jsonValue.ValueExists("HasMoreTags")) { m_hasMoreTags = jsonValue.GetBool("HasMoreTags"); } return *this; }
24.846154
114
0.740712
Neusoft-Technology-Solutions
4ad9625feae2e3e5c1786b78ceefe6760fb080a7
7,248
cc
C++
service/zookeeper_configuration_service.cc
sharpyfox/soa
193cdae4e1412f09d655d8135c41f82225907099
[ "Apache-2.0" ]
1
2018-12-14T17:47:20.000Z
2018-12-14T17:47:20.000Z
service/zookeeper_configuration_service.cc
sharpyfox/soa
193cdae4e1412f09d655d8135c41f82225907099
[ "Apache-2.0" ]
null
null
null
service/zookeeper_configuration_service.cc
sharpyfox/soa
193cdae4e1412f09d655d8135c41f82225907099
[ "Apache-2.0" ]
null
null
null
/** zookeeper_configuration_service.cc Jeremy Barnes, 26 September 2012 Copyright (c) 2012 Datacratic Inc. All rights reserved. Configuration service using Zookeeper. */ #include "zookeeper_configuration_service.h" #include "soa/service/zookeeper.h" #include "jml/utils/exc_assert.h" #include <boost/algorithm/string.hpp> using namespace std; using namespace ML; namespace Datacratic { std::string printZookeeperEventType(int type) { if (type == ZOO_CREATED_EVENT) return "CREATED"; if (type == ZOO_DELETED_EVENT) return "DELETED"; if (type == ZOO_CHANGED_EVENT) return "CHANGED"; if (type == ZOO_CHILD_EVENT) return "CHILD"; if (type == ZOO_SESSION_EVENT) return "SESSION"; if (type == ZOO_NOTWATCHING_EVENT) return "NOTWATCHING"; return ML::format("UNKNOWN(%d)", type); } std::string printZookeeperState(int state) { if (state == ZOO_EXPIRED_SESSION_STATE) return "ZOO_EXPIRED_SESSION_STATE"; if (state == ZOO_AUTH_FAILED_STATE) return "ZOO_AUTH_FAILED_STATE"; if (state == ZOO_CONNECTING_STATE) return "ZOO_CONNECTING_STATE"; if (state == ZOO_ASSOCIATING_STATE) return "ZOO_ASSOCIATING_STATE"; if (state == ZOO_CONNECTED_STATE) return "ZOO_CONNECTED_STATE"; return ML::format("ZOO_UNKNOWN_STATE(%d)", state); } void watcherFn(int type, std::string const & path, void * watcherCtx) { typedef std::shared_ptr<ConfigurationService::Watch::Data> SharedPtr; std::unique_ptr<SharedPtr> data(reinterpret_cast<SharedPtr *>(watcherCtx)); #if 0 cerr << "type = " << printZookeeperEventType(type) << " state = " << printZookeeperState(state) << " path = " << path << " context " << watcherCtx << " data " << data->get() << endl; #endif ConfigurationService::ChangeType change; if (type == ZOO_CREATED_EVENT) change = ConfigurationService::CREATED; if (type == ZOO_DELETED_EVENT) change = ConfigurationService::DELETED; if (type == ZOO_CHANGED_EVENT) change = ConfigurationService::VALUE_CHANGED; if (type == ZOO_CHILD_EVENT) change = ConfigurationService::NEW_CHILD; auto & item = *data; if (item->watchReferences > 0) { item->onChange(path, change); } } ZookeeperConnection::Callback::Type getWatcherFn(const ConfigurationService::Watch & watch) { if (!watch) return nullptr; return watcherFn; } /*****************************************************************************/ /* ZOOKEEPER CONFIGURATION SERVICE */ /*****************************************************************************/ ZookeeperConfigurationService:: ZookeeperConfigurationService() { } ZookeeperConfigurationService:: ZookeeperConfigurationService(const std::string & host, const std::string & prefix, int timeout) { init(host, prefix, timeout); } ZookeeperConfigurationService:: ~ZookeeperConfigurationService() { } void ZookeeperConfigurationService:: init(const std::string & host, const std::string & prefix, int timeout) { zoo.reset(new ZookeeperConnection()); zoo->connect(host, timeout); this->prefix = prefix; if (!this->prefix.empty() && this->prefix[this->prefix.size() - 1] != '/') this->prefix = this->prefix + "/"; if (!this->prefix.empty() && this->prefix[0] != '/') this->prefix = "/" + this->prefix; zoo->createPath(this->prefix); #if 0 for (unsigned i = 1; i < prefix.size(); ++i) { if (prefix[i] == '/') { zoo->createNode(string(prefix, 0, i), "", false, false, false /* must succeed */); } } #endif } Json::Value ZookeeperConfigurationService:: getJson(const std::string & key, Watch watch) { ExcAssert(zoo); auto val = zoo->readNode(prefix + key, getWatcherFn(watch), watch.get()); try { if (val == "") return Json::Value(); return Json::parse(val); } catch (...) { cerr << "error parsing JSON entry '" << val << "'" << endl; throw; } } void ZookeeperConfigurationService:: set(const std::string & key, const Json::Value & value) { //cerr << "setting " << key << " to " << value << endl; // TODO: race condition if (!zoo->createNode(prefix + key, boost::trim_copy(value.toString()), false, false, false /* must succeed */, true /* create path */).second) zoo->writeNode(prefix + key, boost::trim_copy(value.toString())); ExcAssert(zoo); } std::string ZookeeperConfigurationService:: setUnique(const std::string & key, const Json::Value & value) { //cerr << "setting unique " << key << " to " << value << endl; ExcAssert(zoo); return zoo->createNode(prefix + key, boost::trim_copy(value.toString()), true /* ephemeral */, false /* sequential */, true /* mustSucceed */, true /* create path */) .first; } std::vector<std::string> ZookeeperConfigurationService:: getChildren(const std::string & key, Watch watch) { //cerr << "getChildren " << key << " watch " << watch << endl; return zoo->getChildren(prefix + key, false /* fail if not there */, getWatcherFn(watch), watch.get()); } bool ZookeeperConfigurationService:: forEachEntry(const OnEntry & onEntry, const std::string & startPrefix) const { //cerr << "forEachEntry: startPrefix = " << startPrefix << endl; ExcAssert(zoo); std::function<bool (const std::string &)> doNode = [&] (const std::string & currentPrefix) { //cerr << "doNode " << currentPrefix << endl; string r = zoo->readNode(prefix + currentPrefix); //cerr << "r = " << r << endl; if (r != "") { if (!onEntry(currentPrefix, Json::parse(r))) return false; } vector<string> children = zoo->getChildren(prefix + currentPrefix, false); for (auto child: children) { //cerr << "child = " << child << endl; string newPrefix = currentPrefix + "/" + child; if (currentPrefix.empty()) newPrefix = child; if (!doNode(newPrefix)) return false; } return true; }; if (!zoo->nodeExists(prefix + startPrefix)) { return true; } return doNode(startPrefix); } void ZookeeperConfigurationService:: removePath(const std::string & path) { ExcAssert(zoo); zoo->removePath(prefix + path); } } // namespace Datacratic
27.664122
79
0.545116
sharpyfox
4ada621e9b0d35e0fc2dc045239521f1cd592c27
13,933
cc
C++
src/fluid/fluidmsg/fluid/ofcommon/common.cc
lionelgo/openair-mme
75bc0993613f61072342f5ae13dca28574253671
[ "BSD-3-Clause" ]
19
2020-04-25T15:51:52.000Z
2021-11-24T04:51:02.000Z
src/fluid/fluidmsg/fluid/ofcommon/common.cc
lionelgo/openair-mme
75bc0993613f61072342f5ae13dca28574253671
[ "BSD-3-Clause" ]
10
2020-09-09T09:54:20.000Z
2021-04-27T20:47:52.000Z
src/fluid/fluidmsg/fluid/ofcommon/common.cc
lionelgo/openair-mme
75bc0993613f61072342f5ae13dca28574253671
[ "BSD-3-Clause" ]
24
2020-05-31T01:41:12.000Z
2022-01-16T17:06:35.000Z
#include "common.hh" namespace fluid_msg { PortCommon::PortCommon() : hw_addr_(), name_(), config_(0), state_(0), curr_(0), advertised_(0), supported_(0), peer_(0) {} PortCommon::PortCommon(EthAddress hw_addr, std::string name, uint32_t config, uint32_t state, uint32_t curr, uint32_t advertised, uint32_t supported, uint32_t peer) : hw_addr_(hw_addr), name_(name), config_(config), state_(state), curr_(curr), advertised_(advertised), supported_(supported), peer_(peer) {} bool PortCommon::operator==(const PortCommon &other) const { return ((this->hw_addr_ == other.hw_addr_) && (this->name_ == other.name_) && (this->config_ == other.config_) && (this->state_ == other.state_) && (this->curr_ == other.curr_) && (this->advertised_ == other.advertised_) && (this->supported_ == other.supported_) && (this->peer_ == other.peer_)); } bool PortCommon::operator!=(const PortCommon &other) const { return !(*this == other); } QueueProperty::QueueProperty() : property_(0), len_(0) {} QueueProperty::QueueProperty(uint16_t property) : property_(property), len_(sizeof(struct ofp_queue_prop_header)) {} bool QueueProperty::equals(const QueueProperty &other) { return ((*this == other)); } bool QueueProperty::operator==(const QueueProperty &other) const { return ((this->property_ == other.property_) && (this->len_ == other.len_)); } bool QueueProperty::operator!=(const QueueProperty &other) const { return !(*this == other); } size_t QueueProperty::pack(uint8_t *buffer) { struct ofp_queue_prop_header *qp = (struct ofp_queue_prop_header *)buffer; qp->property = hton16(this->property_); qp->len = hton16(this->len_); return this->len_; } of_error QueueProperty::unpack(uint8_t *buffer) { struct ofp_queue_prop_header *qp = (struct ofp_queue_prop_header *)buffer; this->property_ = ntoh16(qp->property); this->len_ = ntoh16(qp->len); return 0; } QueuePropertyList::QueuePropertyList(std::list<QueueProperty *> property_list) { this->property_list_ = property_list_; for (std::list<QueueProperty *>::const_iterator it = property_list.begin(); it != property_list.end(); ++it) { this->length_ += (*it)->len(); } } QueuePropertyList::QueuePropertyList(const QueuePropertyList &other) { this->length_ = other.length_; for (std::list<QueueProperty *>::const_iterator it = other.property_list_.begin(); it != other.property_list_.end(); ++it) { this->property_list_.push_back((*it)->clone()); } } QueuePropertyList::~QueuePropertyList() { this->property_list_.remove_if(QueueProperty::delete_all); } bool QueuePropertyList::operator==(const QueuePropertyList &other) const { std::list<QueueProperty *>::const_iterator ot = other.property_list_.begin(); for (std::list<QueueProperty *>::const_iterator it = this->property_list_.begin(); it != this->property_list_.end(); ++it, ++ot) { if (!((*it)->equals(**ot))) { return false; } } return true; } bool QueuePropertyList::operator!=(const QueuePropertyList &other) const { return !(*this == other); } size_t QueuePropertyList::pack(uint8_t *buffer) { uint8_t *p = buffer; for (std::list<QueueProperty *>::iterator it = this->property_list_.begin(), end = this->property_list_.end(); it != end; it++) { (*it)->pack(p); p += (*it)->len(); } return 0; } of_error QueuePropertyList::unpack10(uint8_t *buffer) { uint8_t *p = buffer; size_t len = this->length_; QueueProperty *prop; while (len) { uint16_t type = ntoh16(*((uint16_t *)p)); prop = QueueProperty::make_queue_of10_property(type); prop->unpack(p); this->property_list_.push_back(prop); len -= prop->len(); p += prop->len(); } return 0; } of_error QueuePropertyList::unpack13(uint8_t *buffer) { uint8_t *p = buffer; size_t len = this->length_; QueueProperty *prop; while (len) { uint16_t type = ntoh16(*((uint16_t *)p)); prop = QueueProperty::make_queue_of13_property(type); prop->unpack(p); this->property_list_.push_back(prop); len -= prop->len(); p += prop->len(); } return 0; } QueuePropertyList &QueuePropertyList::operator=(QueuePropertyList other) { swap(*this, other); return *this; } void swap(QueuePropertyList &first, QueuePropertyList &second) { std::swap(first.length_, second.length_); std::swap(first.property_list_, second.property_list_); } void QueuePropertyList::add_property(QueueProperty *prop) { this->property_list_.push_back(prop); this->length_ += prop->len(); } QueuePropRate::QueuePropRate() : QueueProperty(), rate_(0) {} QueuePropRate::QueuePropRate(uint16_t property) : QueueProperty(property), rate_(0){}; QueuePropRate::QueuePropRate(uint16_t property, uint16_t rate) : QueueProperty(property), rate_(rate) {} bool QueuePropRate::equals(const QueueProperty &other) { if (const QueuePropRate *prop = dynamic_cast<const QueuePropRate *>(&other)) { return ((QueueProperty::equals(other)) && (this->rate_ == prop->rate_)); } else { return false; } } PacketQueueCommon::PacketQueueCommon() : len_(0), queue_id_(0), properties_() {} PacketQueueCommon::PacketQueueCommon(uint32_t queue_id) : len_(0), queue_id_(queue_id) {} void PacketQueueCommon::property(QueuePropertyList properties) { this->properties_ = properties; this->len_ += properties.length(); } bool PacketQueueCommon::operator==(const PacketQueueCommon &other) const { return ((this->properties_ == other.properties_) && (this->len_ == other.len_)); } bool PacketQueueCommon::operator!=(const PacketQueueCommon &other) const { return !(*this == other); } void PacketQueueCommon::add_property(QueueProperty *qp) { this->properties_.add_property(qp); this->len_ += qp->len(); } SwitchDesc::SwitchDesc(std::string mfr_desc, std::string hw_desc, std::string sw_desc, std::string serial_num, std::string dp_desc) { this->mfr_desc_ = mfr_desc; this->hw_desc_ = hw_desc; this->sw_desc_ = sw_desc; this->serial_num_ = serial_num; this->dp_desc_ = dp_desc; } bool SwitchDesc::operator==(const SwitchDesc &other) const { return ((this->mfr_desc_ == other.mfr_desc_) && (this->hw_desc_ == other.hw_desc_) && (this->sw_desc_ == other.sw_desc_) && (this->serial_num_ == other.serial_num_) && (this->dp_desc_ == other.dp_desc_)); } bool SwitchDesc::operator!=(const SwitchDesc &other) const { return !(*this == other); } size_t SwitchDesc::pack(uint8_t *buffer) { struct ofp_desc *ds = (struct ofp_desc *)buffer; memset(ds->mfr_desc, 0x0, DESC_STR_LEN); memset(ds->hw_desc, 0x0, DESC_STR_LEN); memset(ds->sw_desc, 0x0, DESC_STR_LEN); memset(ds->serial_num, 0x0, SERIAL_NUM_LEN); memset(ds->dp_desc, 0x0, DESC_STR_LEN); memcpy(ds->mfr_desc, this->mfr_desc_.c_str(), this->mfr_desc_.size() < DESC_STR_LEN ? this->mfr_desc_.size() : DESC_STR_LEN); memcpy(ds->hw_desc, this->hw_desc_.c_str(), this->hw_desc_.size() < DESC_STR_LEN ? this->hw_desc_.size() : DESC_STR_LEN); memcpy(ds->sw_desc, this->sw_desc_.c_str(), this->sw_desc_.size() < DESC_STR_LEN ? this->sw_desc_.size() : DESC_STR_LEN); memcpy(ds->serial_num, this->serial_num_.c_str(), this->serial_num_.size() < SERIAL_NUM_LEN ? this->serial_num_.size() : SERIAL_NUM_LEN); memcpy(ds->dp_desc, this->dp_desc_.c_str(), this->dp_desc_.size() < DESC_STR_LEN ? this->dp_desc_.size() : DESC_STR_LEN); return 0; } of_error SwitchDesc::unpack(uint8_t *buffer) { struct ofp_desc *ds = (struct ofp_desc *)buffer; this->mfr_desc_ = std::string(ds->mfr_desc); this->hw_desc_ = std::string(ds->hw_desc); this->sw_desc_ = std::string(ds->sw_desc); this->serial_num_ = std::string(ds->serial_num); this->dp_desc_ = std::string(ds->dp_desc); return 0; } FlowStatsCommon::FlowStatsCommon() : length_(0), table_id_(0), duration_sec_(0), duration_nsec_(0), priority_(0), idle_timeout_(0), hard_timeout_(0), cookie_(0), packet_count_(0), byte_count_(0) {} FlowStatsCommon::FlowStatsCommon(uint8_t table_id, uint32_t duration_sec, uint32_t duration_nsec, uint16_t priority, uint16_t idle_timeout, uint16_t hard_timeout, uint64_t cookie, uint64_t packet_count, uint64_t byte_count) : length_(0), table_id_(table_id), duration_sec_(duration_sec), duration_nsec_(duration_nsec), priority_(priority), idle_timeout_(idle_timeout), hard_timeout_(hard_timeout), cookie_(cookie), packet_count_(packet_count), byte_count_(byte_count) {} bool FlowStatsCommon::operator==(const FlowStatsCommon &other) const { return ((this->table_id_ == other.table_id_) && (this->duration_sec_ == other.duration_sec_) && (this->duration_nsec_ == other.duration_nsec_) && (this->priority_ == other.priority_) && (this->idle_timeout_ == other.idle_timeout_) && (this->hard_timeout_ == other.hard_timeout_) && (this->cookie_ == other.cookie_) && (this->packet_count_ == other.packet_count_) && (this->byte_count_ == other.byte_count_)); } bool FlowStatsCommon::operator!=(const FlowStatsCommon &other) const { return !(*this == other); } TableStatsCommon::TableStatsCommon() : table_id_(0), active_count_(0), lookup_count_(0), matched_count_(0) {} TableStatsCommon::TableStatsCommon(uint8_t table_id, uint32_t active_count, uint64_t lookup_count, uint64_t matched_count) : table_id_(table_id), active_count_(active_count), lookup_count_(lookup_count), matched_count_(matched_count) {} bool TableStatsCommon::operator==(const TableStatsCommon &other) const { return ((this->table_id_ == other.table_id_) && (this->active_count_ == other.active_count_) && (this->lookup_count_ == other.lookup_count_) && (this->matched_count_ == other.matched_count_)); } bool TableStatsCommon::operator!=(const TableStatsCommon &other) const { return !(*this == other); } PortStatsCommon::PortStatsCommon() : collisions_(0) {} PortStatsCommon::PortStatsCommon(struct port_rx_tx_stats rx_tx_stats, struct port_err_stats err_stats, uint64_t collisions) { this->rx_tx_stats = rx_tx_stats; this->err_stats = err_stats; this->collisions_ = collisions; } bool PortStatsCommon::operator==(const PortStatsCommon &other) const { return ((this->rx_tx_stats == other.rx_tx_stats) && (this->err_stats == other.err_stats) && (this->collisions_ == other.collisions_)); } bool PortStatsCommon::operator!=(const PortStatsCommon &other) const { return !(*this == other); } size_t PortStatsCommon::pack(uint8_t *buffer) { struct port_rx_tx_stats *rt = (struct port_rx_tx_stats *)buffer; struct port_err_stats *es = (struct port_err_stats *)(buffer + sizeof(struct port_rx_tx_stats)); rt->rx_packets = hton64(this->rx_tx_stats.rx_packets); rt->tx_packets = hton64(this->rx_tx_stats.tx_packets); rt->rx_bytes = hton64(this->rx_tx_stats.rx_bytes); rt->tx_bytes = hton64(this->rx_tx_stats.tx_bytes); rt->rx_dropped = hton64(this->rx_tx_stats.rx_dropped); rt->tx_dropped = hton64(this->rx_tx_stats.tx_dropped); es->rx_errors = hton64(this->err_stats.rx_errors); es->tx_errors = hton64(this->err_stats.tx_errors); es->rx_frame_err = hton64(this->err_stats.rx_frame_err); es->rx_over_err = hton64(this->err_stats.rx_over_err); es->rx_crc_err = hton64(this->err_stats.rx_crc_err); return 0; } of_error PortStatsCommon::unpack(uint8_t *buffer) { struct port_rx_tx_stats *rt = (struct port_rx_tx_stats *)buffer; struct port_err_stats *es = (struct port_err_stats *)(buffer + sizeof(struct port_rx_tx_stats)); this->rx_tx_stats.rx_packets = hton64(rt->rx_packets); this->rx_tx_stats.tx_packets = hton64(rt->tx_packets); this->rx_tx_stats.rx_bytes = hton64(rt->rx_bytes); this->rx_tx_stats.tx_bytes = hton64(rt->tx_bytes); this->rx_tx_stats.rx_dropped = hton64(rt->rx_dropped); this->rx_tx_stats.tx_dropped = hton64(rt->tx_dropped); this->err_stats.rx_errors = hton64(es->rx_errors); this->err_stats.tx_errors = hton64(es->tx_errors); this->err_stats.rx_frame_err = hton64(es->rx_frame_err); this->err_stats.rx_over_err = hton64(es->rx_over_err); this->err_stats.rx_crc_err = hton64(es->rx_crc_err); return 0; } QueueStatsCommon::QueueStatsCommon() : queue_id_(0), tx_bytes_(0), tx_packets_(0), tx_errors_(0) {} QueueStatsCommon::QueueStatsCommon(uint32_t queue_id, uint64_t tx_bytes, uint64_t tx_packets, uint64_t tx_errors) : queue_id_(queue_id), tx_bytes_(tx_bytes), tx_packets_(tx_packets), tx_errors_(tx_errors) {} bool QueueStatsCommon::operator==(const QueueStatsCommon &other) const { return ((this->queue_id_ == other.queue_id_) && (this->tx_bytes_ == other.tx_bytes_) && (this->tx_packets_ == other.tx_packets_) && (this->tx_errors_ == other.tx_errors_)); } bool QueueStatsCommon::operator!=(const QueueStatsCommon &other) const { return !(*this == other); } } // End of namespace fluid_msg
34.317734
80
0.656355
lionelgo
4adaa86670c59bc14a5dbe6187bcbcbf5edb4862
19,835
cpp
C++
WindowsDesktop/Test/TestBoolArray.cpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
7
2020-04-26T11:06:02.000Z
2021-09-05T16:42:31.000Z
WindowsDesktop/Test/TestBoolArray.cpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
10
2020-04-26T13:25:36.000Z
2022-03-01T12:34:44.000Z
WindowsDesktop/Test/TestBoolArray.cpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
2
2020-05-11T08:23:23.000Z
2020-08-08T12:33:30.000Z
 # include "Test.hpp" # if defined(SIV3D_DO_TEST) # include <Siv3D.hpp> # include <ThirdParty/Catch2/catch.hpp> TEST_CASE("BoolArray") { { Array<bool> v; REQUIRE(v.size() == 0); } { Array<bool> v{}; REQUIRE(v.size() == 0); } { Array<bool> v{ true }; REQUIRE(v.size() == 1); } { Array<bool> v = { true }; REQUIRE(v.size() == 1); } { Array<bool> v = { true, false }; REQUIRE(v.size() == 2); } { Array<bool> v{ true, false }; REQUIRE(v.size() == 2); } { Array<bool> v = { true, false, true, true, false }; REQUIRE(v.size() == 5); } { Array<bool> v{ true, false, true, true, false }; REQUIRE(v.size() == 5); } { Array<bool> v(10); REQUIRE(v.size() == 10); } { Array<bool> v(10, true); REQUIRE(v.size() == 10); } { struct Gen { bool operator()() { return true; } }; Array<bool> v(10, Arg::generator = Gen()); REQUIRE(v.size() == 10); REQUIRE(v.front() == true); REQUIRE(v.back() == true); } { Array<bool> v(10, Arg::generator = []() { return true; }); REQUIRE(v.size() == 10); REQUIRE(v.front() == true); REQUIRE(v.back() == true); } { struct Gen { bool operator()(size_t i) { return IsEven(i); } }; Array<bool> v(10, Arg::indexedGenerator = Gen()); REQUIRE(v.size() == 10); REQUIRE(v.front() == true); REQUIRE(v.back() == false); } { Array<bool> v(10, Arg::indexedGenerator = IsEven); REQUIRE(v.size() == 10); REQUIRE(v.front() == true); REQUIRE(v.back() == false); } { Array<bool> v; REQUIRE(v.size() == 0); REQUIRE(v.isEmpty() == true); REQUIRE(static_cast<bool>(v) == false); REQUIRE(v.size_bytes() == 0); REQUIRE_THROWS_AS(v.at(0), std::out_of_range); } { const Array<bool> v0 = { true, false, true, true }, v1 = { true, false, true, true, false }; REQUIRE(v0 == v0); REQUIRE(v0 != v1); REQUIRE(v1 != v0); REQUIRE(v1 == v1); REQUIRE(v0 == MakeArray(true, false, true, true)); REQUIRE(Array<bool>() == Array<bool>()); REQUIRE(Array<bool>() != v0); REQUIRE(v0 != Array<bool>()); } /* { Array<bool> v = { 10, 20, 30, 40, 50 }; REQUIRE(v.size() == 5); REQUIRE(v.isEmpty() == false); REQUIRE(static_cast<bool>(v) == true); REQUIRE(v.size_bytes() == (5 * sizeof(bool))); REQUIRE(v[0] == 10); REQUIRE(v[4] == 50); REQUIRE(v[0] == 10); REQUIRE(v[4] == 50); REQUIRE_NOTHROW(v.at(4)); REQUIRE_THROWS_AS(v.at(5), std::out_of_range); } { Array<bool> v(1000); v.release(); REQUIRE(v.size() == 0); REQUIRE(v.capacity() < 1000); } { Array<bool> v; v.push_front(20); REQUIRE(v == Array<bool>{20}); v.push_front(10); REQUIRE(v == Array<bool>{10, 20}); v.pop_front(); REQUIRE(v == Array<bool>{20}); v.pop_front(); REQUIRE(v == Array<bool>{}); v << 10 << 20; REQUIRE(v == MakeArray(10, 20)); v.append(MakeArray(30, 40)); REQUIRE(v == MakeArray(10, 20, 30, 40)); } { REQUIRE(Array<bool>{10, 20, 30, 40, 50}[4] == 50); REQUIRE(Array<bool>{10, 20, 30, 40, 50}.at(4) == 50); } { const Array<bool> v; REQUIRE(v.all(IsEven) == true); REQUIRE(v.all(IsOdd) == true); REQUIRE(v.any(IsEven) == false); REQUIRE(v.any(IsOdd) == false); REQUIRE(v.none(IsEven) == true); REQUIRE(v.none(IsOdd) == true); } { const Array<bool> v = { 12, 34, 56, 78, 90 }; REQUIRE(v.all(IsEven) == true); REQUIRE(v.all(IsOdd) == false); REQUIRE(v.any(IsEven) == true); REQUIRE(v.any(IsOdd) == false); REQUIRE(v.none(IsEven) == false); REQUIRE(v.none(IsOdd) == true); } { const Array<bool> v = { 12, 34, 56, 78, 90 }; REQUIRE(v.includes(v.choice())); REQUIRE(v.choice(5) == v); REQUIRE(v.includes(v.choice(GetDefaultRNG()))); REQUIRE(v.choice(5, GetDefaultRNG()) == v); } { const Array<bool> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; REQUIRE(v.chunk(0) == Array<Array<bool>>{}); REQUIRE(v.chunk(4) == Array<Array<bool>>{ { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }}); REQUIRE(v.chunk(5) == Array<Array<bool>>{ { 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 10, 11 }}); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.count(10) == 2); REQUIRE(v.count(40) == 0); REQUIRE(v.count_if(Equal(10)) == 2); REQUIRE(v.count_if(LessThan(30)) == 4); REQUIRE(v.count_if([](bool n) { return n != 10 && n != 50; }) == 4); } { const Array<bool> v = { 12, 34, 56, 78, 90 }; REQUIRE(v.dropped(0) == MakeArray(12, 34, 56, 78, 90)); REQUIRE(v.dropped(2) == MakeArray(56, 78, 90)); REQUIRE(v.dropped(100) == MakeArray<bool>()); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.dropped_while(LessThan(30)) == MakeArray(30, 20, 50, 30, 20, 10)); REQUIRE(v.dropped_while(LessThan(0)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(v.dropped_while(LessThan(100)) == MakeArray<bool>()); } { bool count = 0; const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; v.each([&](bool) { ++count; }); v.each([&](const bool&) { ++count; }); REQUIRE(count == 14); } { bool count = 0; Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; v.each([&](bool& n) { ++count; n *= 2; }); v.each([&](bool) { ++count; }); REQUIRE(count == 14); REQUIRE(v == MakeArray(20, 60, 40, 100, 60, 40, 20)); } { size_t count = 0; const Array<bool> v = { 10, 30, 20 }; v.each_index([&](size_t i, bool) { count += i; }); v.each_index([&](size_t, const bool& n) { count += n; }); REQUIRE(count == 63); } { size_t count = 0; Array<bool> v = { 10, 30, 20 }; v.each_index([&](size_t i, bool& n) { count += i; n *= 2; }); v.each_index([&](size_t, const bool& n) { count += n; }); REQUIRE(count == 123); } { const Array<bool> v = { 10, 30, 20 }; REQUIRE(v.fetch(1, -1) == 30); REQUIRE(v.fetch(5, -1) == -1); const Array<bool> v2; REQUIRE(v2.fetch(0, -1) == -1); } { Array<bool> v(10); v.fill(123); REQUIRE(v.size() == 10); REQUIRE(v.all(Equal(123))); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.filter(LessThan(25)) == MakeArray(10, 20, 20, 10)); } { const Array<bool> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; REQUIRE(v.in_groups(0) == Array<Array<bool>>{}); REQUIRE(v.in_groups(2) == Array<Array<bool>>{ { 0, 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10, 11 }}); REQUIRE(v.in_groups(5) == Array<Array<bool>>{ { 0, 1, 2}, { 3, 4, 5 }, { 6, 7 }, { 8, 9 }, { 10, 11 }}); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.includes(50)); REQUIRE(v.includes(40) == false); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.includes_if(IsEven) == true); REQUIRE(v.includes_if(GreaterThan(100)) == false); } { const Array<bool> v0 = { 10, 30, 20, 50, 30, 20, 10 }; const Array<bool> v1 = { 10, 10, 20, 20, 30, 50 }; REQUIRE(v0.isSorted() == false); REQUIRE(v1.isSorted() == true); } { const Array<bool> v0 = {}; const Array<bool> v1 = { 12, 34, 56 }; REQUIRE(v0.join() == U"{}"); REQUIRE(v0.join(U"\t", U"[", U"]") == U"[]"); REQUIRE(v1.join() == U"{12, 34, 56}"); REQUIRE(v1.join(U"\t", U"[", U"]") == U"[12\t34\t56]"); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.keep_if(LessThan(100)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.keep_if(LessThan(25)) == MakeArray(10, 20, 20, 10)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.keep_if(LessThan(0)) == MakeArray<bool>()); } } { const Array<bool> v = { 10, 20, 30 }; REQUIRE(v.map(Plus(1)) == MakeArray(11, 21, 31)); } { using Arg::_; const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.reduce(_ + _, 0) == 15); REQUIRE(v.reduce(_ * _, 1) == 120); } { using Arg::_; const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.reduce(_ + _, 0) == 15); REQUIRE(v.reduce(_ * _, 1) == 120); } { using Arg::_; const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.reduce1(_ + _) == 15); REQUIRE(v.reduce1(_ * _) == 120); const Array<bool> v1 = {}; REQUIRE_THROWS_AS(v1.reduce1(_ + _), std::out_of_range); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove(10) == MakeArray(30, 20, 50, 30, 20)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove(100) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.removed(10) == MakeArray(30, 20, 50, 30, 20)); REQUIRE(v.removed(100) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).removed(10) == MakeArray(30, 20, 50, 30, 20)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).removed(100) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove_at(1).remove_at(2) == MakeArray(10, 20, 30, 20, 10)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE_THROWS_AS(v.remove_at(7), std::out_of_range); } } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.removed_at(1) == MakeArray(10, 20, 50, 30, 20, 10)); REQUIRE(v.removed_at(3) == MakeArray(10, 30, 20, 30, 20, 10)); REQUIRE_THROWS_AS(v.removed_at(7), std::out_of_range); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove_if(LessThan(25)) == MakeArray(30, 50, 30)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove_if(LessThan(100)) == MakeArray<bool>()); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.remove_if(LessThan(0)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.removed_if(LessThan(25)) == MakeArray(30, 50, 30)); REQUIRE(v.removed_if(LessThan(100)) == MakeArray<bool>()); REQUIRE(v.removed_if(LessThan(0)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).removed_if(LessThan(25)) == MakeArray(30, 50, 30)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).removed_if(LessThan(100)) == MakeArray<bool>()); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).removed_if(LessThan(0)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replace(10, 40) == MakeArray(40, 30, 20, 50, 30, 20, 40)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replace(0, 40) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replaced(10, 40) == MakeArray(40, 30, 20, 50, 30, 20, 40)); REQUIRE(v.replaced(0, 40) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).replaced(10, 40) == MakeArray(40, 30, 20, 50, 30, 20, 40)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).replaced(0, 40) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replace_if(LessThan(25), -1) == MakeArray(-1, 30, -1, 50, 30, -1, -1)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replace_if(LessThan(100), -1) == MakeArray(-1, -1, -1, -1, -1, -1, -1)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replace_if(LessThan(0), -1) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.replaced_if(LessThan(25), -1) == MakeArray(-1, 30, -1, 50, 30, -1, -1)); REQUIRE(v.replaced_if(LessThan(100), -1) == MakeArray(-1, -1, -1, -1, -1, -1, -1)); REQUIRE(v.replaced_if(LessThan(0), -1) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).replaced_if(LessThan(25), -1) == MakeArray(-1, 30, -1, 50, 30, -1, -1)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).replaced_if(LessThan(100), -1) == MakeArray(-1, -1, -1, -1, -1, -1, -1)); REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).replaced_if(LessThan(0), -1) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.reverse() == MakeArray(5, 4, 3, 2, 1)); } { const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.reversed() == MakeArray(5, 4, 3, 2, 1)); } { const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(MakeArray(1, 2, 3, 4, 5).reversed() == MakeArray(5, 4, 3, 2, 1)); } { bool i = 0; Array<bool> v = { 1, 2, 3, 4, 5 }; v.reverse_each([&](bool& n) { n += i; ++i; }); REQUIRE(v.all(Equal(5))); } { bool i = 0; const Array<bool> v = { 1, 2, 3, 4, 5 }; v.reverse_each([&](bool n) { i = i * 10 + n; }); REQUIRE(i == 54321); } { Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.rotate(0) == MakeArray(1, 2, 3, 4, 5)); REQUIRE(v.rotate(1) == MakeArray(2, 3, 4, 5, 1)); REQUIRE(v.rotate(-1) == MakeArray(1, 2, 3, 4, 5)); REQUIRE(v.rotate(54) == MakeArray(5, 1, 2, 3, 4)); REQUIRE(v.rotate(-54) == MakeArray(1, 2, 3, 4, 5)); } { const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.rotated(0) == MakeArray(1, 2, 3, 4, 5)); REQUIRE(v.rotated(1) == MakeArray(2, 3, 4, 5, 1)); REQUIRE(v.rotated(-1) == MakeArray(5, 1, 2, 3, 4)); REQUIRE(v.rotated(54) == MakeArray(5, 1, 2, 3, 4)); REQUIRE(v.rotated(-54) == MakeArray(2, 3, 4, 5, 1)); } { REQUIRE(MakeArray(1, 2, 3, 4, 5).rotated(0) == MakeArray(1, 2, 3, 4, 5)); REQUIRE(MakeArray(1, 2, 3, 4, 5).rotated(1) == MakeArray(2, 3, 4, 5, 1)); REQUIRE(MakeArray(1, 2, 3, 4, 5).rotated(-1) == MakeArray(5, 1, 2, 3, 4)); REQUIRE(MakeArray(1, 2, 3, 4, 5).rotated(54) == MakeArray(5, 1, 2, 3, 4)); REQUIRE(MakeArray(1, 2, 3, 4, 5).rotated(-54) == MakeArray(2, 3, 4, 5, 1)); } { { Array<bool> v = Range(0, 100); v.shuffle(); REQUIRE(v != Range(0, 100).asArray()); } { Array<bool> v = Range(0, 100); v.shuffle(GetDefaultRNG()); REQUIRE(v != Range(0, 100).asArray()); } } { const Array<bool> v = Range(0, 100); REQUIRE(v.shuffled() != Range(0, 100).asArray()); REQUIRE(v.shuffled(GetDefaultRNG()) != Range(0, 100).asArray()); REQUIRE(Range(0, 100).asArray().shuffled() != Range(0, 100).asArray()); REQUIRE(Range(0, 100).asArray().shuffled(GetDefaultRNG()) != Range(0, 100).asArray()); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.slice(0) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(v.slice(1) == MakeArray(30, 20, 50, 30, 20, 10)); REQUIRE(v.slice(3) == MakeArray(50, 30, 20, 10)); REQUIRE(v.slice(7) == MakeArray<bool>()); REQUIRE(v.slice(0, 0) == MakeArray<bool>()); REQUIRE(v.slice(0, 1) == MakeArray(10)); REQUIRE(v.slice(0, 3) == MakeArray(10, 30, 20)); REQUIRE(v.slice(0, 7) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(v.slice(0, 10) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(v.slice(2, 0) == MakeArray<bool>()); REQUIRE(v.slice(2, 1) == MakeArray(20)); REQUIRE(v.slice(2, 3) == MakeArray(20, 50, 30)); REQUIRE(v.slice(2, 7) == MakeArray(20, 50, 30, 20, 10)); REQUIRE(v.slice(2, 10) == MakeArray(20, 50, 30, 20, 10)); REQUIRE(v.slice(7, 0) == MakeArray<bool>()); REQUIRE(v.slice(7, 1) == MakeArray<bool>()); REQUIRE(v.slice(7, 10) == MakeArray<bool>()); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.sort() == MakeArray(10, 10, 20, 20, 30, 30, 50)); } { Array<Obj> v = { { 50, 0 }, { 10, 0 }, { 30, 0 }, { 20, 0 }, { 20, 1 }, { 50, 1 }, { 20, 2 }, { 20, 3 }, { 10, 1 }}; REQUIRE(v.stable_sort() == MakeArray( Obj{ 10, 0 }, Obj{ 10, 1 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 }, Obj{ 30, 0 }, Obj{ 50, 0 }, Obj{ 50, 1 })); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.sort_by(std::greater<>()) == MakeArray(50, 30, 30, 20, 20, 10, 10)); } { Array<Obj> v = { { 50, 0 }, { 10, 0 }, { 30, 0 }, { 20, 0 }, { 20, 1 }, { 50, 1 }, { 20, 2 }, { 20, 3 }, { 10, 1 } }; REQUIRE(v.stable_sort_by([](const Obj& a, const Obj& b) { return a.id < b.id; }) == MakeArray( Obj{ 50, 0 }, Obj{ 10, 0 }, Obj{ 30, 0 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 50, 1 }, Obj{ 10, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 })); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.sorted() == MakeArray(10, 10, 20, 20, 30, 30, 50)); } { const Array<Obj> v = { { 50, 0 }, { 10, 0 }, { 30, 0 }, { 20, 0 }, { 20, 1 }, { 50, 1 }, { 20, 2 }, { 20, 3 }, { 10, 1 } }; REQUIRE(v.stable_sorted() == MakeArray( Obj{ 10, 0 }, Obj{ 10, 1 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 }, Obj{ 30, 0 }, Obj{ 50, 0 }, Obj{ 50, 1 })); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).sorted() == MakeArray(10, 10, 20, 20, 30, 30, 50)); } { REQUIRE(MakeArray( Obj{ 50, 0 }, Obj{ 10, 0 }, Obj{ 30, 0 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 50, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 }, Obj{ 10, 1 }) .stable_sorted() == MakeArray( Obj{ 10, 0 }, Obj{ 10, 1 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 }, Obj{ 30, 0 }, Obj{ 50, 0 }, Obj{ 50, 1 })); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.sorted_by(std::greater<>()) == MakeArray(50, 30, 30, 20, 20, 10, 10)); } { const Array<Obj> v = { { 50, 0 }, { 10, 0 }, { 30, 0 }, { 20, 0 }, { 20, 1 }, { 50, 1 }, { 20, 2 }, { 20, 3 }, { 10, 1 } }; REQUIRE(v.stable_sorted_by([](const Obj& a, const Obj& b) { return a.id < b.id; }) == MakeArray( Obj{ 50, 0 }, Obj{ 10, 0 }, Obj{ 30, 0 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 50, 1 }, Obj{ 10, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 })); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).sorted_by(std::greater<>()) == MakeArray(50, 30, 30, 20, 20, 10, 10)); } { REQUIRE(MakeArray( Obj{ 50, 0 }, Obj{ 10, 0 }, Obj{ 30, 0 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 50, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 }, Obj{ 10, 1 }) .stable_sorted_by([](const Obj& a, const Obj& b) { return a.id < b.id; }) == MakeArray( Obj{ 50, 0 }, Obj{ 10, 0 }, Obj{ 30, 0 }, Obj{ 20, 0 }, Obj{ 20, 1 }, Obj{ 50, 1 }, Obj{ 10, 1 }, Obj{ 20, 2 }, Obj{ 20, 3 })); } { const Array<bool> v = { 1, 2, 3, 4, 5 }; REQUIRE(v.sum() == 15); const Array<String> vs = { U"AA", U"BB", U"CC" }; REQUIRE(vs.sum() == U"AABBCC"); } { const Array<float> v = { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f }; REQUIRE(v.sumF() == 1.5f); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.take(0) == MakeArray<bool>()); REQUIRE(v.take(1) == MakeArray(10)); REQUIRE(v.take(3) == MakeArray(10, 30, 20)); REQUIRE(v.take(7) == MakeArray(10, 30, 20, 50, 30, 20, 10)); REQUIRE(v.take(100) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.take_while(LessThan(0)) == MakeArray<bool>()); REQUIRE(v.take_while(LessThan(25)) == MakeArray(10)); REQUIRE(v.take_while(LessThan(100)) == MakeArray(10, 30, 20, 50, 30, 20, 10)); } { Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.unique() == MakeArray(10, 20, 30, 50)); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.uniqued() == MakeArray(10, 20, 30, 50)); } { REQUIRE(MakeArray(10, 30, 20, 50, 30, 20, 10).uniqued() == MakeArray(10, 20, 30, 50)); } { const Array<bool> v = { 10, 30, 20, 50, 30, 20, 10 }; REQUIRE(v.values_at({}) == MakeArray<bool>()); REQUIRE(v.values_at({ 0, 1, 2 }) == MakeArray(10, 30, 20)); REQUIRE(v.values_at({ 6, 0 }) == MakeArray(10, 10)); REQUIRE_THROWS_AS(v.values_at({ 6, 7 }), std::out_of_range); } { const Array<bool> v = Range(0, 100'000); REQUIRE(v.parallel_count_if(IsPrime) == 9592); } { std::atomic_int64_t sum = 0; Array<bool> v = Range(0, 100'000); v.parallel_each([](bool& n) { n *= 2; }); v.parallel_each([&](bool n) { sum += n; }); REQUIRE(sum == 10000100000LL); } { const Array<bool> v = Range(0, 100'000); REQUIRE(v.map(Plus(1)) == Range(1, 100'001).asArray()); } */ } # endif
27.096995
130
0.532846
yumetodo
4adc33604e648353d6d2e5170a482ca0824e84ed
8,353
cpp
C++
XMath/XErrHand/NT4ProcessInfo.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
8
2021-07-08T18:06:33.000Z
2022-01-17T18:29:57.000Z
XMath/XErrHand/NT4ProcessInfo.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
null
null
null
XMath/XErrHand/NT4ProcessInfo.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
1
2021-12-31T15:52:56.000Z
2021-12-31T15:52:56.000Z
/*---------------------------------------------------------------------- John Robbins - Microsoft Systems Journal Bugslayer Column Windows NT 4.0 access functions for getting to process information. Windows95 and NT5 can use TOOLHELP32.DLL. ----------------------------------------------------------------------*/ #include "stdafx.h" #include "PCH.h" #include "BugslayerUtil.h" /*////////////////////////////////////////////////////////////////////// Typedefs //////////////////////////////////////////////////////////////////////*/ // The typedefs for the PSAPI.DLL functions used by this module. typedef BOOL (WINAPI *ENUMPROCESSMODULES) ( HANDLE hProcess , HMODULE * lphModule , DWORD cb , LPDWORD lpcbNeeded ) ; typedef DWORD (WINAPI *GETMODULEBASENAME) ( HANDLE hProcess , HMODULE hModule , LPTSTR lpBaseName , DWORD nSize ) ; /*////////////////////////////////////////////////////////////////////// File Static Data //////////////////////////////////////////////////////////////////////*/ // Has the function stuff here been initialized? This is only to be // used by the InitPSAPI function and nothing else. static BOOL g_bInitialized = FALSE ; // The pointer to EnumProcessModules. static ENUMPROCESSMODULES g_pEnumProcessModules = NULL ; // The pointer to GetModuleBaseName. static GETMODULEBASENAME g_pGetModuleBaseName = NULL ; /*---------------------------------------------------------------------- FUNCTION : InitPSAPI DISCUSSION : Loads PSAPI.DLL and initializes all the pointers needed by this file. If BugslayerUtil.DLL statically linked to PSAPI.DLL, it would not work on Windows95. Note that I conciously chose to allow the resource leak on loading PSAPI.DLL. PARAMETERS : None. RETURNS : TRUE - Everything initialized properly. FALSE - There was a problem. ----------------------------------------------------------------------*/ static BOOL InitPSAPI ( void ) { if ( TRUE == g_bInitialized ) { return ( TRUE ) ; } // Load up PSAPI.DLL. HINSTANCE hInst = LoadLibraryA ( "PSAPI.DLL" ) ; ASSERT ( NULL != hInst ) ; if ( NULL == hInst ) { TRACE0 ( "Unable to load PSAPI.DLL!\n" ) ; return ( FALSE ) ; } // Now do the GetProcAddress stuff. g_pEnumProcessModules = (ENUMPROCESSMODULES)GetProcAddress ( hInst , "EnumProcessModules" ) ; ASSERT ( NULL != g_pEnumProcessModules ) ; if ( NULL == g_pEnumProcessModules ) { TRACE0 ( "GetProcAddress failed on EnumProcessModules!\n" ) ; return ( FALSE ) ; } g_pGetModuleBaseName = (GETMODULEBASENAME)GetProcAddress ( hInst , "GetModuleBaseNameA" ) ; ASSERT ( NULL != g_pGetModuleBaseName ) ; if ( NULL == g_pGetModuleBaseName ) { TRACE0 ( "GetProcAddress failed on GetModuleBaseNameA!\n" ) ; return ( FALSE ) ; } // All OK, Jumpmaster! g_bInitialized = TRUE ; return ( TRUE ) ; } /*---------------------------------------------------------------------- FUNCTION : NT4GetLoadedModules DISCUSSION : The NT4 specific version of GetLoadedModules. This function assumes that GetLoadedModules does the work to validate the parameters. PARAMETERS : dwPID - The process ID to look into. uiCount - The number of slots in the paModArray buffer. If this value is 0, then the return value will be TRUE and puiRealCount will hold the number of items needed. paModArray - The array to place the HMODULES into. If this buffer is too small to hold the result and uiCount is not zero, then FALSE is returned, but puiRealCount will be the real number of items needed. puiRealCount - The count of items needed in paModArray, if uiCount is zero, or the real number of items in paModArray. RETURNS : FALSE - There was a problem, check GetLastError. TRUE - The function succeeded. See the parameter discussion for the output parameters. ----------------------------------------------------------------------*/ BOOL NT4GetLoadedModules ( DWORD dwPID , UINT uiCount , HMODULE * paModArray , LPUINT puiRealCount ) { // Initialize PSAPI.DLL, if needed. if ( FALSE == InitPSAPI ( ) ) { ASSERT ( FALSE ) ; SetLastErrorEx ( ERROR_DLL_INIT_FAILED , SLE_ERROR ) ; return ( FALSE ) ; } // Convert the process ID into a process handle. HANDLE hProc = OpenProcess ( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE , dwPID ) ; ASSERT ( NULL != hProc ) ; if ( NULL == hProc ) { TRACE1 ( "Unable to OpenProcess on %08X\n" , dwPID ) ; return ( FALSE ) ; } // Now get the modules for the specified process. ASSERT ( NULL != g_pEnumProcessModules ) ; // Because of possible DLL unload order differences, make sure that // PSAPI.DLL is still loaded in case this function is called during // shutdown. ASSERT ( FALSE == IsBadCodePtr ( (FARPROC)g_pEnumProcessModules ) ); if ( TRUE == IsBadCodePtr ( (FARPROC)g_pEnumProcessModules ) ) { TRACE0 ( "PSAPI.DLL has been unloaded on us!\n" ) ; // Close the process handle used. VERIFY ( CloseHandle ( hProc ) ) ; SetLastErrorEx ( ERROR_INVALID_DLL , SLE_ERROR ) ; return ( FALSE ) ; } DWORD dwTotal = 0 ; BOOL bRet = g_pEnumProcessModules ( hProc , paModArray , uiCount * sizeof ( HMODULE ) , &dwTotal ); // Close the process handle used. VERIFY ( CloseHandle ( hProc ) ) ; // Convert the count from bytes to HMODULE values. *puiRealCount = dwTotal / sizeof ( HMODULE ) ; // If bRet was FALSE, and the user was not just asking for the // total, there was a problem. if ( ( ( FALSE == bRet ) && ( uiCount > 0 ) ) || ( 0 == dwTotal ) ) { ASSERT ( FALSE ) ; TRACE0 ( "EnumProcessModules failed!\n" ) ; return ( FALSE ) ; } // If the total returned in puiRealCount is larger than the value in // uiCount, then return an error. If uiCount is zero, then it is // not an error. if ( ( *puiRealCount > uiCount ) && ( uiCount > 0 ) ) { ASSERT ( FALSE ) ; TRACE0 ( "Buffer is too small in NT4GetLoadedModules!\n" ) ; SetLastErrorEx ( ERROR_INSUFFICIENT_BUFFER , SLE_ERROR ) ; return ( FALSE ) ; } // All OK, Jumpmaster! SetLastError ( ERROR_SUCCESS ) ; return ( TRUE ) ; } DWORD __stdcall NTGetModuleBaseName ( HANDLE hProcess , HMODULE hModule , LPTSTR lpBaseName , DWORD nSize ) { // Initialize PSAPI.DLL, if needed. if ( FALSE == InitPSAPI ( ) ) { ASSERT ( FALSE ) ; SetLastErrorEx ( ERROR_DLL_INIT_FAILED , SLE_ERROR ) ; return ( FALSE ) ; } return ( g_pGetModuleBaseName ( hProcess , hModule , lpBaseName , nSize ) ) ; }
38.851163
73
0.477912
koalefant